/*
 * jQuery TextArea - AutoGrow
 * Made for: http://www.avondjevansinterklaas.nl/
 *
 * Copyright (c) 2011, Stephen Kil
 * http://www.skylinestudios.nl/autogrow/
 *
 * Date: Thu Aug 25 11:19:48 2011 +0200 
 */
(function($) {
	$.fn.autogrow = function() {	
		var grow = function(element) {
			var count = 0;
			var lines = $(element).attr('value').split('\n');
			
			for (var i = lines.length - 1; i >= 0; --i) 
				count += Math.floor((lines[i].length / $(element).attr('cols')) + 1);
			$(element).attr('rows', Math.max(count + 1, 8));
		}
		
		return this.each(function(){
			// Store current width for later use;
			var width = $(this).width();
			
			$(this).css({
				height: 'auto',
				overflow: 'hidden',
				width: 'auto',
			})
			
			// Use 'cols' instead of width, as this is controlable;
			.attr('cols', Math.floor(width / ($(this).attr('cols', 2).width() - $(this).attr('cols', 1).width())))
			.css('width', '100%')
			.bind('keyup focus blur', function() { grow($(this)); })
			.trigger('blur');
		});
	};
})(jQuery);

