//Main js for Chat application. -JustinNguyen
var hasText=0;var idleminutes=60;var chatTimeOut=null;var alertTimeOut=null;var lastSent=new Date();var sendReq = getXmlHttpRequestObject();var receiveReq = getXmlHttpRequestObject();var genReq = getXmlHttpRequestObject();var lastMessage = 0;var mTimer;var currentPage=document.location;var chatHolder=null;var agentID=null;var agentName=null;var chatHolder=null;var chatWindow=null;var chatTimer=null;var chatname=null;var chatemail=null;var chatphone=null;var chatid=0;var lastchatid=0;var chatstat=0;var bPlaySound=true;var agentInfo="";var lastChatNumber=0;
window.onbeforeunload = function() {if(chatstat==1){var url="api.cfm?action=logoff&chatid="+chatid+"&nc="+Math.random();genReq.open("GET", url, false);genReq.send(null);endSession();}}
function initChat(pagentID,pagentName,byPass,myurl){
	chatHolder=document.getElementById("chatWindow");
	chatWindow=document.getElementById("TextContainer");
	if(myurl!=undefined){currentPage=myurl;}
	agentID=pagentID;
	agentName=pagentName;
	if(isUserOnline(agentID)){startChat();var myScode='<iframe src="sounds/logon.cfm" id="soundholder" width=30 height=30 frameborder=0 scrolling="no" style="display:none;"></iframe>';document.writeln(myScode);}else{startContact();}
}
function playSound(srcName){if(bPlaySound){document.getElementById("soundholder").src=srcName+"?nc="+Math.random();}}
function turnSound(chkObj){if(chkObj.checked){bPlaySound=true;	}else{bPlaySound=false;}}
function runTimer(){getMessage();}
function closeChat(){if(confirm("Are you sure you want to close the chat session?")){clearInterval(chatTimer);chatstat=0;endSession();window.close();}}
function getChat(){receiveReq.open("GET", 'api.cfm?action=getChat&uid=' + uid+'&nc='+Math.random(), false);receiveReq.send(null);if(receiveReq.responseText.indexOf("online")>-1){return true;}else{return false;}}
function processMessage(jsObj,sCount){
	var chatMessage="";
	for(var i=0;i<sCount;i++){
		chatMessage+=jsObj.message[i].text;
		}
		updateChatText(chatMessage);
		if(lastChatNumber<sCount){playSound('sounds/newmessage.cfm');lastChatNumber=sCount;self.focus();}
}

function getMessage(){
	if(isUserOnline(agentID)){
		var url="api.cfm?action=getmessage&chatid="+chatid+"&you="+chatname+"&typed="+hasText+"&nc="+Math.random();
		receiveReq.open("GET", url, true);
		receiveReq.send(null);
		receiveReq.onreadystatechange=function(){
			if(receiveReq.readyState==4){
				var myChat=eval(trim(receiveReq.responseText));
				processMessage(chatJSON,chatJSON.message.length);
				}	
			};
			return;
		}
		endSession();
		updateChatText(getChatText()+"<div class='warning'>****The Agent has logged off. Chat Session closed****</div>");
		clearInterval(chatTimer);
		chatstat=0;	
		agentOff();
	}
function endSession(){receiveReq.open("GET", 'api.cfm?action=endsession&uid=' + chatid+'&nc='+Math.random(), false);receiveReq.send(null);document.getElementById("typestatus").style.display='none';}
function getAgentInfo(){var url="api.cfm?action=agentinfo&agentid="+agentID+"&nc="+Math.random();genReq.open("GET", url, true);genReq.send(null);genReq.onreadystatechange=function(){if(genReq.readyState==4){document.getElementById("agentInfoMidd").innerHTML=genReq.responseText;}}}
function showAgentInfo(){document.getElementById("middLeft2Agent").style.display='block';document.getElementById("MiddChatBlock").style.display='none';getAgentInfo();}
function sendMessage(){var xtext=escape(document.getElementById("chattextbox").value);if(xtext==""){ return;}var url="api.cfm?action=sendmessage&you="+chatname+"&agentid="+agentID+"&them="+agentName+"&chatid="+chatid+"&chattext="+xtext+"&nc="+Math.random();sendReq.open("GET", url, true);sendReq.send(null);sendReq.onreadystatechange=function(){if(sendReq.readyState==4){playSound('sounds/sendmessage.cfm');lastChatNumber++;getMessage();hasText=0;document.getElementById("chattextbox").value="";hideAgentInfo();}};}
function startChat(){var html='<div id="canvas"><div id="header"><div id="logo"><img src="images/liveChatLogoUser.jpg" /></div></div><div id="blocksTop"><div id="MiddChatBlock" class="middLeftLogin"><div id="titleBlockContainer"><div id="titleBar">Enter information to start chat</div></div><div id="middBlockContainer"><div id="Top"></div><div id="Midd"><b>Welcome to HAR\'s Online Agent chatting platform!</b><br>If you are a first-time user, please take a minute to read through this brief overview.<br>In order to begin chatting with an agent, you will need to enter your name. If you\'d like, you can enter your e-mail address as well. Once you\'ve signed on to chat, the agent will automatically be alerted that you are online and you can begin chatting. To learn more about this program, please click here.<br><br><div id="inputFormContainer"><div class="labelLoginForm">Name</div><div class="inputTextLoginForm"><input name="" type="text" class="input" name="chattername"  id="chattername" /></div><div class="labelLoginForm">Email</div><div class="inputTextLoginForm"><input name="" type="text" class="input" name="chatteremail"  id="chatteremail" /></div><div class="labelLoginForm">Interested in</div><div class="inputTextLoginForm"><input type=radio value="Buying" name="chatsubject" id="chatsubjecttxt" >Buying&nbsp;&nbsp;<input type=radio value="Selling" name="chatsubject" id="chatsubjecttxt" >Selling&nbsp;&nbsp;<input type=radio value="Buying and Selling" name="chatsubject" id="chatsubjecttxt" >Buying & Selling&nbsp;&nbsp;<input type=radio value="Leasing" name="chatsubject" id="chatsubjecttxt" >Leasing<br></div><div class="labelLoginForm">&nbsp;</div><div class="inputTextLoginForm"> <br /><img src="images/btnStart.jpg" border="0" style="cursor:pointer;" onclick="startChatSession();" alt="Start Chat" />&nbsp;<img src="images/btnCancel.jpg" border="0"  onclick="window.close();" style="cursor:pointer;" alt="Cancel" title="Cancel" />&nbsp; </div></div><div style="font-weight:bold;padding-left:140px;padding-top:10px;">By clicking \'Submit\', you agree to the Terms of Use.</div></div><div id="Footer"></div></div></div></div></div></div>';updateChatBox(html);return;}
function startContact(){var html='<div id="canvas"><div id="header"><div id="logo"><img src="images/liveChatLogoUser.jpg" /></div></div><div id="blocksTop"><div id="MiddChatBlock" class="middLeftLogin"><div id="titleBlockContainer"><div id="titleBar">'+agentName+' is offline. Send '+agentName+' a message</div></div><div id="middBlockContainer"><div id="Top"></div><div id="Midd"><div style="float:left;width:120px;font-weight:bold;font-size:1em;"><img src="http://pictures.har.com/agent/'+agentID+'.jpg" onerror="this.src=\'images/nophoto.gif\';"><br>'+agentName+'</div><div style="float:left;width:440px;"><div>I am currently offline. Please send me a message regarding your real estate needs, and I will get back to you as soon as I can.</div><br /><div id="inputFormContainer" style="width:550px;"><div class="labelLoginForm" style="width:65px;">Name</div><div class="inputTextLoginForm" style="width:310px;"><input name="" type="text" class="input" name="chattername"  id="chattername" /></div><div class="labelLoginForm" style="width:65px;">Email</div><div class="inputTextLoginForm" style="width:310px;"><input name="" type="text" class="input" name="chatteremail"  id="chatteremail" /></div><div class="labelLoginForm" style="width:65px;">Message</div><div class="inputTextLoginForm" style="width:310px;"><textarea name=""  rows="4" class="inputBig" name="chatsubject" id="chatsubjecttxt" ></textarea></div><div class="labelLoginForm">&nbsp;</div><div class="inputTextLoginForm" style="width:310px;"> <br /><img src="images/btnSubmit.jpg" border="0"  onclick="sendEmail();" style="cursor:pointer;" alt="Send Message" title="Send Message"/>&nbsp;<img src="images/btnCancel.jpg" border="0"  onclick="window.close();" style="cursor:pointer;" alt="Cancel" title="Cancel" />&nbsp; </div></div></div><div style="clear:both;"></div></div><div id="Footer"></div></div></div></div></div></div>';updateChatBox(html);return;}
function logoff(){var url="api.cfm?action=logoff&chatname="+chatname+"&chatemail="+chatemail+"&chatphone="+chatphone+"&agentid="+agentID+"&agentname="+agentName+"&nc="+Math.random();genReq.open("GET", url, false);genReq.send(null);}
function sendEmail(){chatname=document.getElementById("chattername").value;chatemail=document.getElementById("chatteremail").value;chatsubjectc=document.getElementById("chatsubjecttxt").value;if(chatname =="" || chatemail == "" || chatsubjectc==""){alert("Please fill out all the required fields");	return;	}var url="api.cfm?action=sendemail&chatname="+chatname+"&chatemail="+chatemail+"&chatsubject="+chatsubjectc+"&agentid="+agentID+"&agentname="+agentName+"&myurl="+escape(currentPage)+"&nc="+Math.random();genReq.open("GET", url, false);genReq.send(null);if(genReq.responseText.indexOf("error")>-1){alert("There was an error sending the message. Please make sure you fill out all the required fields.");return;}else{alert("Thank you. Your message was sent. Click OK to close this window.");window.close();}}
function startChatSession(){
chatstat=1;chatname=document.getElementById("chattername").value.replace(/[^a-zA-Z 0-9]+/g,'');chatemail=document.getElementById("chatteremail").value.replace(/[^a-zA-Z 0-9 @ .]+/g,'');chatsubjectc=getRadio("chatsubject");
		if(chatname==""){alert("Please fill out your name.");return;}
		document.getElementById("soundholder").style.display="block";

			var url="api.cfm?action=startsession&chatname="+chatname.replace(/[^a-zA-Z 0-9]+/g,'')+"&chatemail="+chatemail+"&chatsubject="+chatsubjectc+"&agentid="+agentID+"&agentname="+agentName+"&myurl="+escape(currentPage)+"&nc="+Math.random();
			genReq.open("GET", url, false);
			genReq.send(null);
			if(genReq.responseText.indexOf("error")>-1){alert("There was an error trying to start the chat. Please make sure your name is filled out.");return;}else{chatid=parseInt(genReq.responseText);}
			var myBox=constructChatBox();
			myBox=(myBox.replace("[CHATCAPTION]","Chatting with "+agentName)).replace("[CHATTEXT]",'<div><i>you are now chatting with '+agentName+'.</i></div>').replace("[CHATCAPTION]","Chatting with "+agentName);
			updateChatBox(myBox);chatTimer= setInterval(runTimer,3800);chatTimeOut=setInterval(checkIdle,61000);showAgentInfo();
	
}
function showAgentTyping(bFlag){
	var typeStatusobj=document.getElementById("typestatus");
	if(bFlag==1 && chatstat==1){
		
		typeStatusobj.style.display="block";
		typeStatusobj.innerHTML="Agent is typing ...";	
	}else{
		typeStatusobj.innerHTML="";	
		typeStatusobj.style.display="block";
	}
	
}
function hideAgentInfo(){if(document.getElementById('MiddChatBlock').style.display!="block"){showDiv('MiddChatBlock','middLeft2Agent');}}
function getRadio(id){var rObj=document.getElementsByName(id);for(i=0;i<rObj.length;i++){if(rObj[i].checked){return rObj[i].value;}}return "";}
function stayConnect(){lastSent=new Date();clearInterval(alertTimeOut);alertTimeOut=null;clearInterval(chatTimeOut);chatTimeOut=setInterval(checkIdle,61000);hideAlert();}
function agentOff(){clearInterval(chatTimer);clearInterval(chatTimeOut);clearInterval(alertTimeOut);document.getElementById("blocksTop").innerHTML="<div style='padding-top:150px;height:400px;text-align:center;color:red;font-size:2em;'>Chat Session Ended. Agent Logged Off.<br><br><img src='images/btnCloseWindow.png' style='cursor:pointer;' onclick='window.close();'></div>";document.getElementById("typeContainer").style.display='none';document.getElementById("rightBtns").style.display='none';endSession();hideAlert();}
function logMeOff(){clearInterval(chatTimer);clearInterval(chatTimeOut);chatTimeOut=null;clearInterval(alertTimeOut);alertTimeOut=null;document.getElementById("blocksTop").innerHTML="<div style='padding-top:150px;height:400px;text-align:center;color:red;font-size:2em;'>Your chat session was expired<br><br><img src='images/btnCloseWindow.png' style='cursor:pointer;' onclick='window.close();'></div>";document.getElementById("typeContainer").style.display='none';document.getElementById("rightBtns").style.display='none';endSession();hideAlert();}
function checkIdle(){var myNewTime=new Date();var lminutes=idleminutes*60000;if(myNewTime-lastSent>lminutes){var msg="<div style='float:left;'><img src='images/warning.png'></div><div style='float:left;width:200px;'> You've been idle. Please click on 'Stay Connected' to stay logged in.</div><div style='clear:both;'></div><div style='padding-top:10px;text-align:center;width:220px;'><img src='images/btnStayConnected.png'  onclick='stayConnect();' style='cursor:pointer;'>&nbsp;<img src='images/btnLogOff.png'  onclick='logMeOff();' style='cursor:pointer;'></div>";alertIt(msg);alertTimeOut=setInterval(logMeOff,60000);clearInterval(chatTimeOut);}}
function alertIt(msgtext){document.getElementById("myalertbox").innerHTML=msgtext;document.getElementById("myalertbox").style.display='block'; self.focus();}
function hideAlert(){document.getElementById("myalertbox").style.display='none';}
function constructChatBox(){
	var htmText='<div id="canvas"><div id="header"><div id="logo"><img src="images/liveChatLogoUser.jpg" /></div><div id="rightBtns"><div id="logOutBtn"><img src="images/btn_EndChat.jpg" border="0" onclick="closeChat();" style="cursor:pointer;"/></div>';
	htmText+='<div id="soundBtn"><label><input name="" type="checkbox" value="" checked  onclick="turnSound(this);"/>Play Sound</label></div>';
    htmText+='</div></div><div id="blocksTop"><div id="MiddChatBlock" class="middLeftAgent"><div id="titleBlockContainer"><div id="titleBar">[CHATCAPTION]</div>';
    htmText+='<div id="leftBtn"><img src="images/btnAgentInfo.jpg" border="0" onclick="showAgentInfo();" style="cursor:pointer;"/></div></div>';
    htmText+='<div id="middBlockContainer"><div id="Top"></div><div id="Midd"><div id="TextContainer">[CHATTEXT]</div></div><div id="Footer"></div></div></div>';
    htmText+='<div id="middLeft2Agent" style="display:none;"><div id="titleBlockContainer"><div id="titleBar">[CHATCAPTION]</div>';
    htmText+='<div id="leftBtn"><img src="images/btnAgentInfo2.jpg" border="0" /></div></div><div id="middBlockContainerAgent"><div id="Top"></div><div id="Midd">';
    htmText+='<div id="agentInfoContainer"><div id="agentInfoTop"><img src="images/userInfoHeaderWide.jpg" /></div><div id="agentInfoMidd">';
    htmText+='</div><div id="agentInfoFooter"><img src="images/userInfoFooterWide.jpg" /></div></div></div><div id="Footer"></div></div></div>';
 	htmText+='</div><div id="typeContainer"><div id="blocksLinker"></div><div id="typeleft"><img src="images/typeBlockLeft.jpg" /></div><div id="typeMidd"><div id="inputContainer">';
    htmText+='<div id="inputLeft"><img src="images/typeInputBgLeft.jpg" /></div><div id="inputContent"><form style="marign:0px;padding:0px" onsubmit="sendMessage();return false;";><input type="text" class="inputText" id="chattextbox" onkeypress="stayConnect();enteredText(this);"></form>';
    htmText+='</div><div id="inputRight"><img src="images/btnSend.jpg" border="0" style="cursor:pointer;" onclick="sendMessage();"/></div></div></div><div id="typeRight"><img src="images/typeBlockright.jpg" /></div></div></div>';
	return htmText;
}
function isUserOnline(uid){
	genReq.open("GET", 'api.cfm?action=checkonline&chatid='+chatid+'&uid=' + uid+'&nc='+Math.random(), false);
	genReq.send(null);
	if(genReq.responseText.indexOf("istyping")>-1){
			showAgentTyping(1);
	}
if(genReq.responseText.indexOf("nottyping")>-1){
			showAgentTyping(0);
	}
	
	if(genReq.responseText.indexOf("online")>-1){return true;}else{return false;}
}
function enteredText(inObj){
	if(inObj.value.length>0){
		hasText=1;	
	}else{
		hasText=0;	
	}
}
function updateChatBox(sText){document.getElementById("chatWindow").innerHTML=sText;}
function updateChatText(sText){document.getElementById("TextContainer").innerHTML=sText;document.getElementById("TextContainer").scrollTop = document.getElementById("TextContainer").scrollHeight;}
function getChatText(){return document.getElementById("TextContainer").innerHTML;}
function generateChatText(sfrom,stext){var tHTML="<div class='chatGuast'><b>"+sfrom+"</b>: "+stext+"</div>";return tHTML;}
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.');}}
function trim(str, chars) {return ltrim(rtrim(str, chars), chars);}
function ltrim(str, chars) {chars = chars || "\\s"; return str.replace(new RegExp("^[" + chars + "]+", "g"), "");}
function rtrim(str, chars) {chars = chars || "\\s";return str.replace(new RegExp("[" + chars + "]+$", "g"), "");}	

