
function getXmlHttpRequestObject() 
	{
		if (window.XMLHttpRequest) 
		{
			return new XMLHttpRequest();
		} else if(window.ActiveXObject) 
			{
				return new ActiveXObject("Microsoft.XMLHTTP");
			}
		 else {
			alert("Status: Cound not create XmlHttpRequest Object.' + 'Consider upgrading your browser.");
		}
	}
	
	//Request Chat and get chat ID to start chat  :client
	function requestChat()
	{
		sendReq = getXmlHttpRequestObject();
		receiveReq = getXmlHttpRequestObject();
		reqChat = getXmlHttpRequestObject();
		if (reqChat.readyState == 4 || reqChat.readyState == 0) 
		{
			reqChat.open("GET", "getChat.asp?action=requestChat", true);
			reqChat.onreadystatechange = handlerequestChat;
			reqChat.send(null);
		}
	}
	
	//Function for handling the return of chat text
	function handleReceiveChat() 
	{
		if (receiveReq.readyState == 4) 
		{
			var chat_div = document.getElementById("div_chat");
			var xmldoc = receiveReq.responseXML;
			if (!xmldoc.getElementsByTagName("ERRORMESSAGE")[0]) // Show message that user sign out
			{
				var message_nodes = xmldoc.getElementsByTagName("MESSAGE");
				var n_messages = message_nodes.length;
				for (i = 0; i < n_messages; i++) 
				{
					var user_node = message_nodes[i].getElementsByTagName("USER");
					var text_node = message_nodes[i].getElementsByTagName("TEXT");
					var page_node = message_nodes[i].getElementsByTagName("PAGE");
					if (user_node[0].firstChild.nodeValue == "customer")
					{
						/// write chat message.
						chat_div.innerHTML += "<div class='user message'>&nbsp;&nbsp;&nbsp;&nbsp;" + text_node[0].firstChild.nodeValue + '';
						/// write customer's current page under chat screen.
						if(userName != "customer")
							document.getElementById("start_page").innerHTML ="Customer page: <div class='bold'>" + xmldoc.getElementsByTagName("PAGE")[0].firstChild.nodeValue + "</div>";
					}
					else
						chat_div.innerHTML += "<div class='message'>" +text_node[0].firstChild.nodeValue + '';
					lastMessage = (message_nodes[i].getAttribute('id')); 
					EvalSound("newMessage");
					ScrollDown();
					window.focus();
					document.getElementById('txt_message').focus();
				}
				mTimer = setTimeout('getChatText();',5000);
			}
			else
			{
				EvalSound("newMessage");
				window.focus();
				clearInterval(mTimer);
				chat_div.innerHTML += "<div class='message red'>" + xmldoc.getElementsByTagName("ERRORMESSAGE")[0].firstChild.nodeValue;
				ScrollDown();
				document.getElementById("txt_message").style.display = "none";
				document.getElementById("btn_send_chat").style.display = "none";
			}
		}
	}
	
	//Gets the current messages from the server
	function getChatText() 
	{
		if (receiveReq.readyState == 4 || receiveReq.readyState == 0) 
		{
			receiveReq.open("GET", 'getChat.asp?user='+userName+'&chatid=' + chatid +'&last=' + lastMessage, true);
			receiveReq.onreadystatechange = handleReceiveChat;
			receiveReq.send(null);
		}
	}
	
	//Function for initializating client's the page.
	function startChat()
	{
		sendReq = getXmlHttpRequestObject();
		receiveReq = getXmlHttpRequestObject();
		//Set the focus to the Message Box.
		document.getElementById('txt_message').focus();
		//Start Recieving Messages.
		getChatText();
	}
	
	function closeChat(d) 
	{
		clearInterval(mTimer);
		if ((sendReq.readyState == 4 || sendReq.readyState == 0) && typeof(chatid) != "undefined") 
		{
			sendReq.open("GET", 'getChat.asp?action=close&chatid=' + chatid, false);
			sendReq.send(null);
		}
		
		if (d == "close") window.opener.login(d);
		window.close();
	}
	
	//When our message has been sent, update our page.
	function handleSendChat() 
	{
		//Clear out the existing timer so we don't have
		//multiple timer instances running.
		clearInterval(mTimer);
		getChatText();
	}
	
	//Add a message to the chat server.
	function sendChatText() 
	{
		if (sendReq.readyState == 4 || sendReq.readyState == 0) 
		{
		
			var _page;
			try{_page = window.opener.document.title;}catch(err){_page = "undefined";} 
			
			sendReq.open("GET", "getChat.asp?user=" + userName  +"&action=add&chatid=" + chatid + "&message=" + document.getElementById('txt_message').value + "&page=" + _page + "&last=" + lastMessage, true);
			sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			sendReq.onreadystatechange = handleSendChat;
			sendReq.send(null);
			document.getElementById('txt_message').value = '';
		}
	}
	
	function handlerequestChat()
	{
		if (reqChat.readyState == 4) 
		{
			var xmldoc = reqChat.responseXML;
			
			var message_nodes = xmldoc.getElementsByTagName("CHAT")[0];
			if(message_nodes)
			{
				var user_node = message_nodes.getElementsByTagName("USER");
				var message_node = message_nodes.getElementsByTagName("MESSAGE");
				chatid = xmldoc.getElementsByTagName("CHAT")[0].attributes[0].nodeValue;
				document.getElementById("div_chat").innerHTML += "<div class='message'>" + message_node[0].firstChild.nodeValue + '';
				getChatText();
			}
			else
			{
				document.getElementById("div_chat").style.display = "none";
				document.getElementById("start_page").innerHTML = "Chat is not available now. Please try later.";
				document.getElementById("txt_message").style.display = "none";
				document.getElementById("btn_send_chat").style.display = "none";
			}
		}
	}
	function login(d)
	{
			if(d == "true") 
			{
				document.getElementById("txt_name").disabled = true;
				document.getElementById("btn_start_chat").value = "End Chat";
			}
			
			if(d == "close") 
			{
				if(typeof(mTimer1) != "undefined") 	clearInterval(mTimer1);
				chatid = "";
				sendReqToStart = null;
				sendReq = null;
				receiveReq = null;
				waitingForChat("start");
			}
			
			if(d == "false") 
			{
				document.getElementById("btn_start_chat").value = "Start Chat";
				document.getElementById("txt_name").disabled = false;
				if(typeof(mTimer1) != "undefined") 	clearInterval(mTimer1);
			}
	}
		function startWaitingForChatButPressed()
		{
			if(document.getElementById("btn_start_chat").value == "Start Chat" && document.getElementById("txt_name").value != "")
				waitingForChat("start");
			else
				waitingForChat("stop");
		}
		
		function waitingForChat(val)
		{
			if(typeof(mTimer1) != "undefined") 	clearInterval(mTimer1);
			if(val == "start")
			{
				sendReqToStart = getXmlHttpRequestObject();
				sendReq = getXmlHttpRequestObject();
				sendReq.open("GET", "getChat.asp?user="+document.getElementById("txt_name").value+"&action=start", true);
				sendReq.onreadystatechange = handleStartChat;
				sendReq.send(null);
				login('true');
				return;
			}
			if(val == "stop")
			{
				adminSignOut();
				login('false');
			}
		}
		
		function adminSignOut()
		{
			if(typeof(chatid) != 'undefined')
			{
				try
				{
					var sendReqStop = getXmlHttpRequestObject();
					sendReqStop.open("GET", "getChat.asp?chatid=" +chatid + "&user="+document.getElementById("txt_name").value+"&action=stopChat", false);
					sendReqStop.send(null);
				}
				catch(err){}
			}
		}
		
		function handleStartChat() 
		{
			if (sendReq.readyState == 4 ) 
			{
				var xmldoc = sendReq.responseXML;
				chatid = xmldoc.getElementsByTagName("CHAT_ID")[0].firstChild.nodeValue;
				mTimer1 = setTimeout('sendRequestToOpenChat();', 3000);
			}
		}
		
		function sendRequestToOpenChat()
		{
			if (sendReqToStart.readyState == 4 || sendReqToStart.readyState == 0) 
			{
				sendReqToStart.open("GET", "getChat.asp?chatid=" +chatid + "&action=requestChatAdmin", true);
				sendReqToStart.onreadystatechange = handleRequestToOpenChat;
				sendReqToStart.send(null);
			}
		}
		
		function handleRequestToOpenChat()
		{
			if (sendReqToStart.readyState == 4) 
			{
				var xmldoc = sendReqToStart.responseXML;
				if(xmldoc.getElementsByTagName("CHAT")[0].firstChild.nodeValue == "True")
				{
					var b = window.open("chat.asp?chatid=" + chatid +"&user=admin&userName="+document.getElementById("txt_name").value+"",'adminchat' + chatid + '','location=no,status=no,width=405,height=335');
					clearInterval(mTimer1);
				}
				else
					mTimer1 = setTimeout('sendRequestToOpenChat();',3000);
			}
		}
		
function EvalSound(soundobj) 
{
	try
	{
  		var thissound = document.getElementById(soundobj);
  		thissound.Play();
	}
	catch(err){}
}

function ScrollDown()
{
	try{ //code for IE
		document.getElementById("div_chat").doScroll("pageDown");
	}
	catch(err){}
}

/// These functions are called from pblic pages
function chat()
{
	if(typeof(chatTimer) != "undefined") clearInterval(chatTimer);
	sChat = getXmlHttpRequestObject();
	if(sChat.readyState == 4 || sChat.readyState == 0) 
	{
		sChat.open("GET", "/chat/getChat.asp?action=requestToShowChatIcon", true);
		sChat.onreadystatechange = handleChat;
		sChat.send(null);
	}
}

function handleChat()
{
 	if (sChat.readyState == 4)
 	{
 		var xmldoc = sChat.responseXML;
		var message_nodes = xmldoc.getElementsByTagName("CHAT")[0];
		if(message_nodes)
			document.getElementById("chat").style.display = "inline";
		else
			document.getElementById("chat").style.display = "none";
		chatTimer = setTimeout('chat();',8000);
 	}
}

