/*!
 * Autogrow Textarea Plugin Version v2.0
 * http://www.technoreply.com/autogrow-textarea-plugin-version-2-0
 *
 * Copyright 2011, Jevin O. Sewaruth
 *
 * Date: March 13, 2011
 */
jQuery.fn.autoGrow = function(){
	return this.each(function(){
		// Variables
		var colsDefault = this.cols;
		var rowsDefault = this.rows;
		
		//Functions
		var grow = function() {
			growByRef(this);
		}
		
		var growByRef = function(obj) {
			var linesCount = -1;
			var lines = obj.value.split('\n');
			
			for (var i=lines.length-1; i>=0; --i)
			{
			
				var extra =  (Math.ceil(lines[i].length / 29) * 4) - 4;
				linesCount += Math.floor(((lines[i].length-extra) / (colsDefault)) + 1);
			}
			
			if(linesCount > 4)
			{
				obj.rows = 6;
			}
			else if (linesCount >= rowsDefault)
			{
				obj.rows = linesCount + 1;
				$("#live_assist_messages").animate({scrollTop: $("#live_assist_messages").prop("scrollHeight") - $('#live_assist_messages').height() }, 100);
			}
			else
			{
				obj.rows = rowsDefault;
			}
				
			//live_assist_messages
			//live_assist_txt	
			
			var height = (obj.rows * 15) + 17;
			
			var messageHeight = 235 - (height - 32);

			jQuery("#live_assist_txt").css("height", height + "px");
			jQuery("#live_assist_messages").css("height", messageHeight + "px");
			
			var message = $(obj).val();
			
			$.post("/jquery/chat.php?action=setTypingCust",
			{
				message: message
			});
		}
		
		var characterWidth = function (obj){
			var characterWidth = 0;
			var temp1 = 0;
			var temp2 = 0;
			var tempCols = obj.cols;
			
			obj.cols = 1;
			temp1 = obj.offsetWidth;
			obj.cols = 2;
			temp2 = obj.offsetWidth;
			characterWidth = temp2 - temp1;
			obj.cols = tempCols;
			
			return characterWidth;
		}
		
		
		// Manipulations
		
		this.style.height = "auto";
		
		this.onkeyup = grow;
		this.onfocus = grow;
		this.onblur = grow;
		growByRef(this);
	});
};
