/*
* Flext - A Mootools Based Flexible TextArea Class
* version 1.1 - for mootools 1.2
* by Graham McNicoll
* Copyright 2008-2009 - Education.com
* License: MIT-style license.
*
*/

var Flext = new Class({
Implements: Options,
options: { aniTime: 100, maxHeight: 0, defaultMaxHeight: 1000, parentDepth: 6,	growClass: 'growme' },
initialize: function(el, options) {
	this.setOptions(options);
	this.el = $(el);
	this.autoGrow = el.hasClass(this.options.growClass);
	if(this.autoGrow) {
		this.resizer = new Fx.Tween(this.el, {duration: this.options.aniTime});
		this.getMaxSize();
		this.reachedMax = false;
		var y = this.el.getSize().y;
		this.startSize = this.origSize = y > 0 ? y : parseInt(this.el.getStyle('height').replace(/px/,''));
		this.vertPadding = this.el.getStyle('padding-top').toInt()+this.el.getStyle('padding-bottom').toInt()+this.el.getStyle('border-top').toInt()+this.el.getStyle('border-bottom').toInt();

		this.el.addEvents({
		'keyup': function(e) {
			this.checkSize(e);
		}.bind(this),
		'change': function(e) {
			this.checkSize(e);
		}.bind(this),
		'click': function(e) {
			this.checkSize(e);
		}.bind(this)
		});
		this.checkSize();
	}
},
getMaxSize: function() {
	this.maxSize = this.options.maxHeight;
	if(this.maxSize == 0) {
		var testmax = this.el.className.match(/maxheight-(\d*)/);
		if(testmax) {
			this.maxSize = testmax[1];
		} else {
			this.maxSize = this.options.defaultMaxHeight;
		}
	}
},
checkSize: function(e) {
	var theSize = this.el.getSize();
	var theScrollSize = this.el.getScrollSize();
	theScrollSize.y = theScrollSize.y > 0 ? theScrollSize.y : parseInt(this.el.getStyle('height').replace(/px/,''));
	if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
		var checksize = theScrollSize.y;
	} else {
		var checksize = theScrollSize.y + this.vertPadding;
	}

	if(checksize > theSize.y) {
		this.resizeIt(theSize, theScrollSize);
	}
},
resizeIt: function(theSize, scrollSize) {
	var newSize = scrollSize.y;
	if((scrollSize.y+this.vertPadding) > this.maxSize && !this.reachedMax) {
		newSize = this.maxSize;
		this.el.setStyle('overflow', '');
		this.resizer.start('height', newSize);
		this.reachedMax = true;
	}
	if(!this.reachedMax) {
		var increasedSize = newSize - this.startSize;
		if(increasedSize < 0) increasedSize = 0;
		this.startSize = newSize;
		this.resizer.start('height', newSize);
	}
}
});

if (typeof(__flext_no_autostart)=='undefined') {
	window.addEvent('domready', function() {
		$$('textarea.flext').each(function(el) { new Flext(el);	});
	});
}
