/**
 * EXTEXTAREA
 * Copyright (c) ChrisBuchholz <http://www.chrisbuchholz.name>
 * Licensed under the MIT license <http://www.chrisbuchholz.name/mit-license>
 *
 * requires mootools 1.2.4 or later <http://mootools.net>
 **/

var exTextarea = new Class({
	Implements: [Options],

	options: {
		padding_bottom: 20,
	},
    
    initialize: function (textarea_selector, options) {
		this.setOptions(options);
		
		var opt = this.options;
		if(textarea_selector && textarea_selector.constructor == Array)
			var textareas = textarea_selector;
		else
			var textareas = textarea_selector != null && textarea_selector.constructor.toString().match(/textarea/i) ? [textarea_selector] : $(document.body).getElements('textarea');

		if(!textareas || textareas.length === 0) {
			return false;
		}
		
		var fitTextarea = function (textarea, hdiv) {
			hdiv.set('html', textarea.get('value'));
			var hdiv_y = hdiv.getSize().y;
			if(hdiv_y + opt.padding_bottom > textarea.getSize().y) {
				textarea.setStyle('height', hdiv_y + (opt.padding_bottom * 6));
			}
		};

		textareas.each(function(textarea) {
			textarea.setStyles('overflow', 'hidden');
			var styles = textarea.getStyles('padding-top', 'padding-bottom', 'padding-left', 'padding-right', 'line-height', 'font-size', 'font-family', 'font-weight', 'font-style');
			var hdiv = new Element('div', {
				'styles': {
					'width': textarea.getSize().x,
					'padding-top': styles['padding-top'],
					'padding-bottom': styles['padding-bottom'],
					'padding-left': styles['padding-left'],
					'padding-right': styles['padding-right'],
					'line-height': styles['line-height'],
					'font-size': styles['font-size'],
					'font-family': styles['font-family'],
					'font-weight': styles['font-weight'],
					'font-style': styles['font-style'],
					'position': 'absolute',
					'top': '-9999px',
					'left': '-9999px',
					'white-space': 'pre-wrap'
				}
			});  
			$(document.body).grab(hdiv);    
			fitTextarea(textarea, hdiv);
			textarea.addEvent('keyup', function() {
				fitTextarea(this, hdiv);
			});
		});

		return textareas;
	}
});