/***

Makes textareas grow to fit the text in them.

Apply the class 'expand' to textareas to implement.

Written by Matt Dolan 11/01/10

REQUIRES Prototype

***/

/*** Auto growing textareas ***/

var ExpandingTextArea = Class.create({
	autoExpand: function () {
		this.dummyEl.setValue(this.el.value);
		this.dummyEl.style.display = 'block';
		this.dummyEl.style.height = 0; // this is necessary to make it shrink when deleting
		this.dummyEl.style.height = this.dummyEl.scrollHeight + 'px';
		this.dummyEl.style.height = (parseInt(this.dummyEl.style.height) + 10) + 'px';
		if (parseInt(this.dummyEl.style.height)<this.initialHeight)
			this.dummyEl.style.height = this.initialHeight + 'px';
		this.el.style.height = this.dummyEl.style.height;
	},
	keyUp: function (ev) {
		this.autoExpand();
	},

	initialize: function (el) {
		this.el = $(el);
		if (!this.el) return false;
		
		this.el.style.overflow = 'hidden';
		this.initialHeight = this.el.getHeight();
		
		// if the height is zero, it's possible that the CSS isn't loaded yet
		if (this.initialHeight == 0) {
			this.initialize.bind(this,el).delay(0.5);
			return;
		}
		
		this.dummyEl = new Element('textarea',{
									style: "position:absolute; left:-9999em; top:-9999em; display:none",
									'class': this.el.readAttribute('class'),
									tabindex: '-1'
								});
		this.el.insert({after: this.dummyEl});
		this.el.observe('keyup',this.keyUp.bind(this));
		this.autoExpand();
	}
});

// initialize expanding on any textareas with the class 'expand'
document.observe('dom:loaded',function() {
	$$('textarea.expand').each(function(el){ new ExpandingTextArea(el); });
});

