// JavaScript Document
var LastMessageId = 0;
var req= null;

function trim(val)
{
   var temp = val;
   var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
   if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
   var obj = /  /g;
   while (temp.match(obj)) { temp = temp.replace(obj, " "); }
   return temp;
}

function UpdateBoxContent( data )
{
	var shoutbox_table = document.getElementById("shoutbox_table");
	
	var temp = data.split(">");
	var name = temp[0];
	var message = temp[1];
	var date = temp[2];
	
	//var tblBody = document.getElementById(tblId).tBodies[0];
	var newRow = shoutbox_table.insertRow(-1);
  	var newCell = newRow.insertCell(0);
	newCell.style.backgroundColor = "#efefef";
	newCell.style.borderBottom = "solid #ffffff 1px";
  	newCell.innerHTML = '<span class="f12"><strong>' + name + ': </strong> ' + message.replace("'","`") + '</span><br><span class="f4">' + date + '</span><br>';
	
	var shoutbox_div = document.getElementById("shoutbox_div");
	shoutbox_div.scrollTop = shoutbox_div.scrollHeight;
}

function ProcessRetValue( data )
{
	var splitdata = data.split("~");
	LastMessageId = splitdata[0];
	for( var x=1; x <= ( splitdata.length - 1 ); x++ )
	{
		UpdateBoxContent( splitdata[x] );
	}
	
	req = null;
}

function CallAPI( IsSave )
{
	var butShout = document.getElementById("butShout");
	
	if( req != null )
		req.abort();
		
	var url = "api/shoutbox_api.aspx";
	var dataToSend = "msgId=" + LastMessageId;
	
	if( IsSave )
	{
		var nameObj = document.getElementById("shoutname");
		var msgObj = document.getElementById("shoutmsg");
		
		var name = trim( nameObj.value );
		var msg = trim( msgObj.value );
		
		msgObj.value = "";
	
  		dataToSend += "&name=" + escape( name ) + "&msg=" + escape( msg );
		
		butShout.disabled = true;
	}
	
	if ( window.XMLHttpRequest )
		req = new XMLHttpRequest();
	else if (window.ActiveXObject) 
		req = new ActiveXObject("Microsoft.XMLHTTP");
	if (req != undefined) 
	{		
		req.onreadystatechange = function() {APIReturn();};
    	req.open("POST", url, true);
		req.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    	req.send( dataToSend );
  	}	
}

function APIReturn() {            
if (req.readyState == 4) { // only if req is "loaded"
	var butShout = document.getElementById("butShout");
    if (req.status == 200) { // only if "OK"
      ProcessRetValue( req.responseText );
    } else {
      req = null;
    }
	butShout.disabled = false;
  }
}

function Shout()
{
	var name = trim( document.getElementById("shoutname").value );
	var msg = trim( document.getElementById("shoutmsg").value );
		
	if((name != "" ) && (msg != "" ))
		CallAPI( true );
	else
		alert('Name and Message fields needs to have a value.');
}