function User(name, nickname)
{
	this.name 		= name;
	this.nickname 	= nickname;
}

function Message(owner, content, timestamp)
{
	this.sender 	= owner;
	this.content 	= content;
	this.timestamp	= timestamp
}

var timerRunning = false;
var timer;
var INTERVAL = 3000;
var debugOutput = false;

var xmlhttp;

var logInResponse = new Array();
var loggedInUsers = new Array();	
var rcvdMessages  = new Array();	
  
var whoAmI;
var userNickName;
var userName;

var clicked = false;


function loginResult(param)
{
	var success = parseInt(logInResponse[0].value);
	var message = logInResponse[0].loginmessage;
		
	if (success == 1)
	{
		lblLoginMessage.setText(message);
		loginSuccessful();
	}
	else if (success == 0)
	{
		lblLoginMessage.setText(message);
	}
}


function clearLogin()
{
	txtUserName.setValue("");
	txtNickName.setValue("");
}

function loggedOut(param)
{
	whoAmI 		 = null;
	userName	 = null;
	userNickName = null;
	
	maskat.hideLayout("ChatRoomLayout");
	maskat.showLayout("ChatLoginLayout");

	lblLoginMessage.setText("Please type in Name and Nickname to log in...");
	
	window.clearInterval(timer);
	timerRunning = false;
}

function loginSuccessful()
{
	whoAmI 		 = new User(txtUserName.getValue(), txtNickName.getValue());
	userName	 = txtUserName.getValue();
	userNickName = txtNickName.getValue();
	
	maskat.hideLayout("ChatLoginLayout");
	maskat.loadLayoutFile("chatRoomLayout.xml", 'document.getElementById("divConteiner")');
	maskat.loadEventFile("chatRoomLayout_e.xml");
	
	updateLoggedInUsersGrid();

	timer = window.setInterval("createXMLHTTPObj()", INTERVAL);
	timerRunning = true;
	txtInterval.setValue(INTERVAL);
}


function createXMLHTTPObj()
{
	  	try 
	  	{
	    	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	  	} 
	  	catch (e) 
	  	{
	    	try 
	    	{
	      		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	    	} 
	    	catch (e) 
	    	{
				xmlhttp = false;
	    	}
	  	}
	  	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') 
	  	{
	    	xmlhttp = new XMLHttpRequest();
	  	}
 	
 	
	  	xmlhttp.onreadystatechange = function()
	    {
	      	if( xmlhttp.readyState == 4 )
			{
		       	if (window.ActiveXObject)
		       	{
		        	var doc = new ActiveXObject("Microsoft.XMLDOM");
		        	
		        	doc.async = false;
		        	
		        	doc.loadXML(xmlhttp.responseText);
		        }
		        else
		        {
		        	var parser = new DOMParser();
		        	var doc = xmlhttp.responseXML;
		        }
		        
		        
		        
		        var root = doc.documentElement;
		        	
				try
				{
					var messageNodes = maskat.xpath(root, "result/message");
					var messageArray = new Array(messageNodes.length);
		
					for (var i = 0; i < messageNodes.length; i++)
					{
						var msgNode		 			= messageNodes[i]
						
						messageArray[i]				 = new Message(); 
						messageArray[i]["owner"] 	 = maskat.xpath(msgNode, "owner/text()");
						messageArray[i]["content"] 	 = maskat.xpath(msgNode, "content/text()");
						messageArray[i]["timestamp"] = maskat.xpath(msgNode, "timestamp/text()");
					}        	
					
					
					
					var userNodes 		= maskat.xpath(root, "result/user");
					var userNicknames 	= new Array(userNodes.length);
					
					for (var j = 0; j < userNodes.length; j++)
					{
						var userNode	= userNodes[j];
						userNicknames[j] = new User();
						userNicknames[j]["nickname"]	= maskat.xpath(userNode, "nickname/text()");
					}
					
					
					if(messageArray.length > 0)
					{
						displayMessages(messageArray);
					}
					
					updateLoggedInUsersGrid(userNicknames);
					
					if (debugOutput)
					{
		       			updateDebug(xmlhttp.responseText);
		       		}
		      	}
		       	catch(e)
		       	{
		       		updateDebug(e);
				}
			}
		}

	  	xmlhttp.open("POST", "../../chatClient/Login", true);
	  	xmlhttp.setRequestHeader("maskat_requesttype", "sendMessages");
	  	xmlhttp.setRequestHeader("maskat_user", userNickName);
 	
  	xmlhttp.send(null);
  	delete xmlhttp;
}


function updateLoggedInUsersGrid(userArray)
{
	
	if (!userArray)
	{
		var loggedInUsersLenght = loggedInUsers.length;
		var usersNickNames 		= new Array(loggedInUsersLenght);
		
		var tmpGridData = grdUsers.tabData;
		
		if (tmpGridData.length >= 1)
		{
			grdUsers.deleteLines();
		}
			
		for (var i = 0; i < loggedInUsersLenght; i++)
		{
			grdUsers.addOneLine([loggedInUsers[i].nickname]);
		}
	}	
	else
	{
		var userArrayLength = userArray.length;
		
		var tmpGridData = grdUsers.tabData;
		
		if (tmpGridData.length >= 1)
		{
			grdUsers.deleteLines();
		}
		
		for (var i = 0; i < userArrayLength; i++)
		{
			grdUsers.addOneLine([userArray[i]["nickname"]]);
		}
	}
}

function displayMessages(newMessagesArray)
{
	if (!newMessagesArray && rcvdMessages != null)
	{
		txtMsgToSend.setValue("");
				
		var rcvdMsgsLength	= rcvdMessages.length;
		var oldText 		= txtChatMsgs.getValue();
		var newLine;
		
		var i = 0;
		
		if (rcvdMessages.length > 0)
		{
			if (oldText == "")
			{
				txtChatMsgs.setValue(rcvdMessages[0].owner + "> " + rcvdMessages[0].content);
				i = 1
			}
			
			
			for (; i < rcvdMsgsLength; i++)
			{
				newLine = rcvdMessages[i].owner + "> " + rcvdMessages[i].content;
				
				oldText = txtChatMsgs.getValue();		
				
				txtChatMsgs.setValue(oldText + "\n" + newLine);
			}
		}
		
		rcvdMessages = null;
		
		updateLoggedInUsersGrid();
	}
	else if (newMessagesArray)
	{
		var oldText 	= txtChatMsgs.getValue();
		var newLine;
		
		var i = 0;
		
		if (newMessagesArray.length > 0)
		{
			if (oldText == "")
			{
				txtChatMsgs.setValue(newMessagesArray[i]["owner"] + "> " + newMessagesArray[i]["content"]);
				i = 1
			}
			
			for (; i < newMessagesArray.length; i++)
			{
				newLine = newMessagesArray[i]["owner"] + "> " + newMessagesArray[i]["content"];
				oldText = txtChatMsgs.getValue();
				txtChatMsgs.setValue(oldText + "\n" + newLine);
			}
		}
	}
}

function updateDebug(str)
{
	txtDebug.setValue(txtDebug.getValue() + "\n" + str);
}



function startStopTimer()
{
	if (timerRunning == true)
	{
		clearInterval(timer);
		timerRunning = false;
		
		btnDebug.setTitle("start timer");
	}
	else if (timerRunning == false)
	{
		timer = window.setInterval("createXMLHTTPObj()", INTERVAL);
		timerRunning = true;
		
		btnDebug.setTitle("stop timer");
	}
}

function setTimerInterval()
{
	INTERVAL 	= txtInterval.getValue();
	
	clearInterval(timer);
	timer 		= window.setInterval("createXMLHTTPObj()", INTERVAL);
}

function setDebugOutput()
{
	if (debugOutput == true)
	{
		debugOutput = false;
	}
	else 
	{
		debugOutput = true;
	}
}
