﻿/*
 /*
* Simple Auto Expanding Text Area (0.1.2-dev)
* by Antti Kaihola (antti.kaihola.fi)
* akaihol+jquery@ambitone.com
*
* Copyright (c) 2009 Antti Kaihola (antti.kaihola.fi)
* Licensed under the MIT and BSD licenses.
*
* NOTE: This script requires jQuery to work. Download jQuery at
* http://www.jquery.com
*
* Improvements :
* arnaud-k http://blog.Arnaud-k.fr . Takes care of the textarea’s vertical paddings
* zero-zombie http://www.zzzombie.com. Takes the textarea’s initial height as a minimum + minor optimizations
*/
 
(function(jQuery) {
 
	jQuery.fn.simpleautogrow = function() {
		return this.each(function() { new jQuery.simpleautogrow(this); }); 
	};
 
	jQuery.simpleautogrow = function (e) {
	    var self = this;
	    var $e = this.textarea = jQuery(e)
		    .css({overflow: 'hidden', display: 'block'})
		    .bind('focus', function() {
			    this.timer = window.setInterval(function() {self.checkExpand(); }, 200); 
		    })
		    .bind('blur', function() { clearInterval(this.timer); });
 
		    var reg=new RegExp('(px)','g');
		    this.paddingSum = parseInt(this.textarea.css('padding-top').replace(reg,'')) + parseInt(this.textarea.css('padding-bottom').replace(reg,''));
		    this.minHeight = 40;
 
		    this.border = $e.outerHeight() - $e.innerHeight();
		    this.clone = $e.clone().css({position: 'absolute', visibility: 'hidden'}).attr('name', '')
		    $e.height( Math.max(e.scrollHeight + this.border + this.paddingSum, this.minHeight)).after(this.clone);
			
		    this.checkExpand();
	};
 
	jQuery.simpleautogrow.prototype.checkExpand = function() {
		var target_height = this.clone[0].scrollHeight + this.border + this.paddingSum;
		if (this.minHeight == 0) this.minHeight = target_height; // first call : target_height eq current height
		var target_height = Math.max(target_height, this.minHeight);
		if (this.textarea.height() != target_height)
		this.textarea.height(target_height + 'px');
		this.clone.attr('value', this.textarea.attr('value')).height(0); 
	};
 
})(jQuery);
