var AutoGrow = Class.create();
AutoGrow.prototype = {
	dummy : null,

	textarea : null,

	executer : null,

	options : {
		minHeight : 60,
		maxHeight : 350,
		interval : 0.3,
		margin : 55
	},

	initialize : function(textarea, options)
	{
		var style;
		var styles = ['font-family', 'width', 'border-left', 'border-right', 'border-top', 'border-bottom'];
		var newStyle = {
			'overflow-x' :	'hidden',
			'position' :	'absolute',
			'top' :			'0px',
			'left' :		'-9999px',
			'font-size':	'12px',
			'padding':		'2px',
			'line-height':	'14px'
		};
		var x;
		var l;

		this.textarea = $(textarea);
		Object.extend(this.options, options || {});

		this.textarea.setStyle({'overflow': 'hidden'});

		this.dummy = new Element('div');
		for (x = 0, l = styles.length; x < l; ++x)
		{
			style = styles[x];
			newStyle[style] = this.textarea.getStyle(style);
		}
		this.dummy.setStyle(newStyle);

		document.body.insert(this.dummy);
		this.executer = new PeriodicalExecuter(this.resize.bind(this), this.options.interval);
	},

	resize : function(force)
	{
		var newHeight;
		var triggerHeight;
		var text = ''+this.textarea.value+'';
			text = text.replace(/\n|\r\n/g, '<br>X');

		if(force || this.dummy.innerHTML.toLowerCase() != text.toLowerCase())
		{
			this.dummy.update(text);
			triggerHeight = (this.dummy.getHeight() + this.options.margin);
			if(this.textarea.clientHeight != triggerHeight)
			{
				newHeight = Math.max(this.options.minHeight, triggerHeight);
				if(newHeight <= this.options.maxHeight)
				{
					this.textarea.setStyle({'height': newHeight+'px'});
					this.textarea.setStyle({'overflow': 'hidden'});
				}
				else
				{
					this.textarea.setStyle({'height': this.options.maxHeight+'px'});
					this.textarea.setStyle({'overflow': 'auto'});
				}
			}
		}
	},

	setMinHight : function()
	{
		this.textarea.setStyle({'height': this.options.minHeight+'px'});
		this.textarea.setStyle({'overflow': 'hidden'});
	}
};
