/** 
 *  Another TextArea Autogrow plugin (0.2) alpha's alpha
 *  by Nikolay Borisov aka KOSIASIK
 *  mne@figovo.com
 *
 *  http://figovo.com/
 *
 *  Example: 
 *  $('textarea').ata();
 *
 *  jQuery required. Download it at http://jquery.com/
 *
 * Version -f3 by cf
 * added options-param "idsuffix"
 * 
 * 20090825 - added minHeight
 */


(function(jQuery){

	jQuery.fn.ata = function(options){

		options = jQuery.extend({
			timer:100,
			idsuffix:"",
			minHeight:26
		}, options);
	
		return this.each(function(i){
	
			var $t = jQuery(this),
				t = this;

			t.style.resize = 'none';
			t.style.overflow = 'hidden';

			var tVal = t.value;			
			t.style.height = '0px';
			t.value = "W\nW\nW";
			var H3 = t.scrollHeight;
			t.value = "W\nW\nW\nW";
			var H4 = t.scrollHeight;
			var H = H4 - H3;
			t.value = tVal;
			tVal = null;
			
			var id="ataa_"+options.idsuffix+i;
			
			$t.before("<div id=\""+id+"\"></div>");

			var $c = jQuery('#'+id),
				c = $c.get(0);

			c.style.padding = '0px';
			c.style.margin = '0px';

			$t.appendTo($c);

			$t.bind('focus', function(){
				t.startUpdating()
			}).bind('blur', function(){
				t.stopUpdating()
			});

			this.heightUpdate = function(){
			
				if (tVal != t.value){
					//alert ("height update");
					t.doHeightUpdate();
//					tVal = t.value;
//					t.style.height = '0px';
//					var tH = t.scrollHeight;
//					t.style.height = tH + 'px';
//					c.style.height = 'auto';
					// c.style.height = c.offsetHeight + 'px';
					
				}
	
			}
			
			this.doHeightUpdate = function(){
				tVal = t.value;
				t.style.height = '0px';
				var tH = t.scrollHeight;
				if(tH < options.minHeight) tH = options.minHeight;
				t.style.height = tH + 'px';
				c.style.height = 'auto';
			}
			
			this.startUpdating = function(){
				t.interval = window.setInterval(function(){
					t.heightUpdate()
				}, options.timer);
			}

			this.stopUpdating = function(){
				clearInterval(t.interval);	
			}

			jQuery(function(){
				t.heightUpdate();
			});

			// der IE 7 h?tte gern ein zweites Update
			setTimeout(function(){t.doHeightUpdate()}, 20);

		});

	};

})(jQuery);
