/* MGD
based on code from http://stackoverflow.com/questions/931207/is-there-a-jquery-autogrow-plugin-for-text-fields
modified to allow specifying minwidth and maxwidth as attributes, calc padding automatically, 
and to autosize to content at startup
*/

(function($){
	$.fn.autoGrowInput = function(o) {
		o = $.extend({minWidth:30}, o);
		this.filter('input:text').each(function() {
			var	input = $(this),
			minWidth = input.attr('minwidth') || o.minWidth || input.width(),
			maxWidth = input.attr('maxwidth') || o.maxWidth,
			padding = o.padding || input.outerWidth()-input.width();
			val = '',
			testSubject = $('<div/>').css({
				position: 'absolute',
				top: -9999,
				left: -9999,
				width: 'auto',
				fontSize: input.css('fontSize'),
				fontFamily: input.css('fontFamily'),
				fontWeight: input.css('fontWeight'),
				letterSpacing: input.css('letterSpacing'),
				whiteSpace: 'nowrap',
				textIndent: 0
				}),
			check = function(event) {
				if( val === (val = input.val()) )
					return true;
				// enter new content into testSubject
				var escaped = val.replace(/&/g, '&amp;').replace(/\s/g,'&nbsp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
				testSubject.html(escaped);
				// calculate new width + whether to change
				/*
				var testerWidth = testSubject.width(),
					newWidth = (testerWidth + o.padding) >= minWidth ? testerWidth + o.padding : minWidth,
					currentWidth = input.width(),
					isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth) || (newWidth > minWidth && newWidth < maxWidth);
				$('#v').text("tw="+testerWidth+" nw="+newWidth+" cw="+currentWidth+" iv="+isValidWidthChange);
				// animate width
				if( isValidWidthChange )
					input.width(newWidth);
				*/
				var newWidth = testSubject.width()+padding;
				if( newWidth < minWidth ) newWidth = minWidth; else if( newWidth > maxWidth ) newWidth = maxWidth;
				/*
				if( event )
					$('#v').text("nw="+newWidth+" cw="+input.width()+" et="+event.type+" ew="+event.which);
				else
					$('#v').text("nw="+newWidth+" cw="+input.width());
				*/
				/*
				if( event )
					if( event.type == 'keyup' )
						event.preventDefault();
				*/
				if( newWidth != input.width() )
					input.width(newWidth);
				/*
				if( event )
					if( event.type == 'keyup' )
						input.trigger('keyup',event.which);
				*/
				return true;
				};
		//$("<div id=v></div>").insertBefore(input);
		testSubject.insertAfter(input);
		check();
		input.bind('keyup keydown blur update', check);
		//$(this).bind('keyup blur update', check).bind('keydown', function() { setTimeout(check); });
		});
	return this;
	};
})(jQuery);


