/*
 * jQuery Auto Resize (Auto resize textarea)
 * @copyright Can Erdošan http://blog.canerdogan.me/
 * @version 1.00
 */

(function($){
    
    $.fn.autoResize = function(options) {
        
        // Just some abstracted details,
        // to make plugin users happy:
        var settings = $.extend({
			minHeight: 75,
			maxHeight: 500,
            extraSpace : 10
        }, options);
		
		var hCheck = !($.browser.msie || $.browser.opera); 
		var textarea = $(this);
		var orjHeight = textarea.height();
		var lastHeight = orjHeight;
		
		function onchenc(e){
		
			e = e.target || e;

			// find content length and box width
			var vlen = e.value.length, ewidth = e.offsetWidth;
			if (vlen != e.valLength || ewidth != e.boxWidth) {

				if (hCheck && (vlen < e.valLength || ewidth != e.boxWidth)) e.style.height = "0px";
				var h = Math.max(e.expandMin, Math.min(e.scrollHeight, e.expandMax));

				e.style.overflow = (e.scrollHeight > h ? "auto" : "hidden");
				e.style.height = h + "px";

				e.valLength = vlen;
				e.boxWidth = ewidth;
			}

			return true;
		}
		
		this.each(function() {
			// is a textarea?
			if (this.nodeName.toLowerCase() != "textarea") return;
			
			this.expandMin = settings.minHeight;
			this.expandMax = settings.maxHeight;
			
			// initial resize
			onchenc(this);

			// zero vertical padding and add events
			if (!this.Initialized) {
				this.Initialized = true;
				$(this).css("padding-top", 0).css("padding-bottom", 0);
				$(this).bind("keydown", onchenc).bind("keyup", onchenc).bind("focus", onchenc);
			}
		});
		
        return this;
    };

})(jQuery);