
// SmartTextarea constructor
function SmartTextarea(oTextarea) {
	this.textarea = oTextarea;
	this.textarea.style.height = "auto";
	this.textarea.setAttribute("wrap", "soft");
	this.startRowsCount = this.textarea.getAttribute("rows");
	this.cols = this.textarea.getAttribute("cols");
	this.init();
}

// Creates callback functions for SmartTextarea events
SmartTextarea.prototype.init = function () {
	var oThis = this;
	this.textarea.onkeyup =
	function (oEvent) {
		if (!oEvent) oEvent = window.event;
		oThis.handleKeyUp(oEvent);
	};
	/*this.textarea.onpaste =
	function () {
		window.setTimeout(this.resize(), 1000);
		return true;
	}*/
};

SmartTextarea.prototype.handleKeyUp = function (oEvent) {

    var iKeyCode = oEvent.keyCode;
    if (13 == iKeyCode || 32 == iKeyCode || 8 == iKeyCode || 46 == iKeyCode)
    	this.resize();
};

SmartTextarea.prototype.resize = function () {
	var newRows = this.textarea.value.split("\n");
	var newRowsCount = newRows.length;
	for (var i=0; i < newRows.length; i++)
    	newRowsCount += Math.floor(newRows[i].length/this.cols); // for each row divide by cols
    if (newRowsCount > newRows.length) newRowsCount++;
    if (navigator.userAgent.indexOf('IE') > -1) newRowsCount++;
    if (newRowsCount != this.textarea.getAttribute("rows"))
    	if (newRowsCount >= this.startRowsCount)
    		this.textarea.setAttribute("rows", newRowsCount);
    	else
    		this.textarea.setAttribute("rows", this.startRowsCount);
};