/* 
* Automatic Expanding Text Area (v0.2)
* by Jonathan Chao
* June 18, 2009
* 
* Inspiration comes from Jason Frame's implementation located at 
*   http://github.com/jaz303/jquery-grab-bag/blob/master/javascripts/jquery.autogrow-textarea.js
*
* NOTE: This script requires jQuery to work. Developed with jQuery v1.3.2
* 
* Licensed under the Attribution-Noncommercial 3.0 Creative Commons License
* http://creativecommons.org/licenses/by-nc/3.0/
* 
* v0.2 Changes
* - Fixed bug if the textarea already contains a value
* - Changed verbose setting of div css to looping through an array of attributes
* 
*/

(function($) {
    $.fn.autoExpand = function(o) {
        var defaults = {
            maxHeight: 200,
            lineHeight: 14
        };
        var options = $.extend(defaults, o);
        
        return this.each(function() {
            var $textarea   = $(this),
                interval    = null,
                minHeight   = $textarea.height(),
                lineHeight  = ($.browser.msie) ? options.lineHeight : parseInt($textarea.css("line-height"));

            var div = $('<div></div>').css({
                display:    "none",
                minHeight:  $textarea.height() - lineHeight,
                width:      $textarea.width() - parseInt($textarea.css("padding-left")) - parseInt($textarea.css("padding-right"))
            }).appendTo(document.body);

			var cssToCopy = [ 'fontSize', 'fontFamily', 'paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop', 'lineHeight'];
			var i = cssToCopy.length;
			while (i--) { div.css(cssToCopy[i].toString(), $textarea.css(cssToCopy[i].toString())); }
			
            if ($.browser.msie) { div.css({ wordWrap: "break-word" }); }
            else { div.css({ whiteSpace: "-moz-pre-wrap", whiteSpace: "pre-wrap" }); }

            $textarea.css({ overflow: "hidden" });
            $textarea.bind("focus", function() { interval = window.setInterval(checkSize, 200); });
            $textarea.bind("blur", function() { window.clearInterval(interval); });

            var checkSize = function() {
                var repeat = function (str, num) { return new Array(num + 1).join(str); }
                div.html($textarea.val().replace(/\n/g, "<br />").replace(/ {2,}/g, function(n) { return repeat("&nbsp;", n.length); }));
				if (div.height() < options.maxHeight) {
	                var newHeight = Math.min(Math.max(div.height() + lineHeight, minHeight), options.maxHeight);
	                $textarea.css({ overflow: (newHeight == options.maxHeight) ? "auto" : "hidden" });
	                $textarea.animate({ height: newHeight + "px" }, 100);
				}
            };
			
			$textarea.height(div.height() + lineHeight);
			div.text($textarea.val());
        });
    };
})(jQuery);