/*
 * jQuery plugin:	cursorPosition - v0.1.0 - last change: 2008-08-28
 * Author	Annan Yearian
 * Licence	Creative Commons ( http://creativecommons.org/licenses/by-sa/2.5/scotland )
 */

(function(Q){
	jQuery.fn.getCursorPosition = function(font)
	{
		/* textarea css default
		 * change these or pass an object to getCursorPosition 
		 * if you apply your own fonts to textareas
		 */
		font = {
			family: 'monospace',
			size: 'medium',
			style: 'normal',
			variant: 'normal',
			weight: 'normal'
		}
	
		var e = this.jquery ? this[0] : this;
		/*
		 * get the text that is before the cursur
		 */
		var text = e.value.substr(
			0,
			(
				(
					'selectionStart' in e /*DOM 3*/
					&& function()
					{
						return e.selectionEnd;
					}
				)
				||
				/* exploder */
				(
					document.selection
					&& function()
					{
						e.focus();
						var range = document.selection.createRange();
						if (range == null)
							return '';
						var re = e.createTextRange();
						var rc = re.duplicate();
						re.moveToBookmark(range.getBookmark());
						rc.setEndPoint('EndToStart', re);
						
						return rc.text.length;
					}
				) ||
				/* browser not supported */
				function()
				{
					return 0;
				}
			)()
		);
		
		/* 
		 * render the text so we can measure it
		 */
		var span = document.createElement('span');
		Q(span).css({
			border: "0",
			margin: "0",
			padding: "0",
			height: "1em",
			width: "auto",
			whiteSpace: 'pre',
			fontFamily: font.family,
			fontSize: font.size,
			fontStyle: font.style,
			fontVariant: font.variant,
			fontWeight: font.weight
		});
		span.innerHTML = text;
		span = document.body.appendChild(span); /* we need to render it to get the text width*/
		
		/* 
		 * calculate values
		 */
		
		var wraps = text.split('\n');
		
		span.innerHTML = wraps[wraps.length - 1];
		
		var textWidth = span.offsetWidth;
		var textHeight = span.offsetHeight * ( wraps.length );
		
		var top = Q(e).offset().top /* get the distance from the top of the textarea*/
			 + (parseInt(e.style.borderTopWidth) || 2) /* add the border width */
			 + (parseInt(e.style.paddingTopWidth) || 0) /* and padding*/
			 + textHeight
			 - span.offsetHeight; 
		var left = Q(e).offset().left /* as above for the height */
			 + (parseInt(e.style.borderLeftWidth) || 2)
			 + (parseInt(e.style.paddingLeftWidth) || 0)
			 + textWidth;
			 
		document.body.removeChild(span);
		
		return {
			'rows': wraps, 
			'text': text, 
			'textWidth': textWidth, 
			'textHeight': textHeight, 
			'top': top, 
			'left':left
		};
	};
})(jQuery);
