//-----------------------------------------------------------LIVE---------------------------------------------
/*
Name: Window ChatScript     
Ver. No.: 0.1.17
Developed By: Umer Jafer

Future Updates: 
1) Make changes accordingly when the asp.net chat window starts working. The major change would be that the js window
should not pop up if the asp.net window is open. A solution could be to make a totally separate script for asp.net window.

//The Previous updates:
1) The Location of the Close button has been updated in the window and a minimize window and 
a maximize window button has been added.
2) All the images have been moved to wg_chatwindow folder so that it is a standard folder for webgreeter.
	
//Current Updates:
1) The path for the Images Online and offline status has been updated to exact URL i.e. http://www.webgreeter.com/wg_chatwindow/online.gif.
2) Variables for all the cookies, images and the services URLs have been added so that the code is easily manageable. 
   Variables will be placed in a separate file and not in newRef.js.
    
*/
//---------------------------------
//NOTE: Message Repition is a major issue due to which Page Refresh process and page switching process is defined.
//For that The ChatId needs to be stored in a cookie right after chat starts.
//Also logic check needs to be implemented to stop this chat from being inserted as a new chat.
//Visitor Name Service is required to get a visitor name for the visitor Id.
//This name needs to be set by the operator panel

//--------------------------------
makeFrame();
// List of Global Variables required for the Chat
var autoGreetMessage = null;
var autoGreetTime = null;
var lc_message = null;
var visitorId = null;
var visitorName = null;
var isGetVisitorName = false;
var isPageSwitching = false;
var username = null;
var senderId = null;            
var actualUserId = null;      //NOTE: The name of the variable user id is not being changed as it is already being at numerous places.
var chatId = null;
var messageId = null;
var messagesFromServer = new Array();
var firstMessage = true;
var unblock = true;
var completeChatText = "";
var chatCloseMessageTimer = null;
var isCautioned = false;
var isWindowClosing = false;
var pageToPush = "";
var greetId = null;
var isOnlyGreeted=false;

var lastUserMessageId = 0;
var WithoutGreet = false;
var GreetingTimer = null;
var isAlreadyInChat = false;
var CloseGreet=null;

var intervalsForGettingMessages = new Array();
var timersForCloseMessage = new Array();
var timerForUserMessage = new Array();

var MsgWin = document.getElementById("txtMessageWin");
var ChatWin = document.getElementById("txtChatWin");
var statusDIV = document.getElementById("statusImage");

var lc_servicestatus = "";
//var btnVisit = document.getElementById("btnURL");

//The Method can be used to disable the Anchor Tag in both IE and FireFox
//the Disable attribute for Anchor does not work in Firefox.

function StartChatProcess() {
      if (!isAlreadyInChat) {
        if (GUID != null) {
            //btnVisit.setAttribute("onclick", "");
            //alert(host);
            //Get Visitor Id
            var visitorIdURL = _chatURL+"GetChatPrerequisiteByLanguage?parSession=";
            visitorIdURL += escape(GUID);
            visitorIdURL += "&parDomain=";
            visitorIdURL += host;
            var dt = new Date();
            visitorIdURL += "&strRandom=";
            visitorIdURL += dt.getTime().toString();
            visitorIdURL += "&method=onGetChatPrerequisiteResponse";
            jsonpCreator(visitorIdURL);
        }
    }
}

function StarChatOnClick() {
    WithoutGreet = true;
    clearTimeout(GreetingTimer);
    StartChatProcess();
}

//The Complete Chat Logic    

//If Get VisitorId for SessionId Service is successful
function onGetChatPrerequisiteResponse(result) {
	 var aLink = document.getElementById("conversationDIV");
    if (result != null) {
		var lc_anchorTag=null;
		var anchorTag=null;
        visitorId = result[0];
        visitorName = result[1];
        //variables @ 2 and 3 are not required currently.
        //Start a New Chat
        if (result[4] == "-1") {
            username = result[5];
			if(typeof(lc_userName)!="undefined") //NOTE: This condition checks the whether there is a span for displaying username in the html or not. 
				{lc_userName.innerHTML=username;}//This feature is only available to Old DEP Clients, currently.
            if (username != "" && username != null) {
                if (!WithoutGreet) {
                     if (document.getElementById("live_chat_img") == null) {
                        if(typeof(lc_img_anchor)=="undefined"){
							anchorTag = document.createElement("a");
							anchorTag.setAttribute("href", "#");
							anchorTag.style.border="none";
						}
						else{
							lc_anchorTag=document.getElementById("live_chat_anchor");
						}
                    var footDiv = document.getElementById(liveChatStatus);
                    var imgTag = document.createElement("img");
					imgTag.style.border="none";
                    imgTag.setAttribute("id", "live_chat_img");
                    imgTag.setAttribute("src", _imageURL + LC_onlineImg);
                    if(typeof(lc_img_anchor)=="undefined"){
						anchorTag.appendChild(imgTag);
						footDiv.appendChild(anchorTag);
						}
					else{
						lc_anchorTag.appendChild(imgTag);
						//footDiv.appendChild(lc_anchor);
						}
						jQuery("#live_chat_img").bind("click",function () {
						WithoutGreet = true;
						clearTimeout(GreetingTimer);
						StartChatProcess();
						});
                 }
                }
                senderId = result[6];
                actualUserId = result[6];
                autoGreetTime = result[7];
                autoGreetMessage = result[8];
                lc_message = result[8];
				lc_servicestatus = result[9];
				if (!WithoutGreet) {
				if(lc_servicestatus=="1"){
				GreetingTimer = setTimeout("showWindow()", autoGreetTime * 1000);}
                }
                else {
                    setTimeout("showWindow()", 1000);
                }
            }
            else {
               if (document.getElementById("live_chat_img") == null) {
                   if(typeof(lc_img_anchor)=="undefined"){
					var anchorTag = document.createElement("a");
                    anchorTag.setAttribute("href", "#");
					anchorTag.style.border="none";
				}
				else{
					lc_anchorTag=document.getElementById("live_chat_anchor");
				}
                    var footDiv = document.getElementById(liveChatStatus);
                    var imgTag = document.createElement("img");
					imgTag.style.border="none";
                    imgTag.setAttribute("id", "live_chat_img");
                    imgTag.setAttribute("src", _imageURL + LC_offlineImg);
                    if(typeof(lc_img_anchor)=="undefined"){
					anchorTag.appendChild(imgTag);
                    footDiv.appendChild(anchorTag);
					}
					else{
						lc_anchorTag.appendChild(imgTag);
						//footDiv.appendChild(lc_anchorTag);
					}
					jQuery("#live_chat_img").bind("click",function(){
				window.open(_offlineURL+"?websiteId="+websiteId+"&MySession="+"Session=" + GUID,"_blank", "menubar=0,resizable=0,width=630,height=450,scrollbars=0");
				});
                }
                else {
                    var imgTag = document.getElementById("live_chat_img");
					imgTag.style.border="none";
                    jQuery("#live_chat_img").bind("click",function(){
				window.open(_offlineURL+"?websiteId="+websiteId+"&MySession="+"Session=" + GUID,"_blank", "menubar=0,resizable=0,width=630,height=450,scrollbars=0");
				});
                    imgTag.setAttribute("src", _imageURL + LC_offlineImg);
                }
            }
        }
        /*Continue Chat
		//NOTE: One more Prerequisite can be added i.e. the message sender.
		//0 visitorId
		//1 visitorname
		//2 is live status 
		//3 website Id
		//4 is continued
		//5 chatID
		//6 userID
		//7 username
		//8 messageId
		//9 messageText
		//10 service status*/
        else if (result[4] == "1") {
            isAlreadyInChat = true;
            chatId = result[5];
            actualUserId = result[6];
            username = result[7];
            if (username != "") {
				if(typeof(lc_userName)!="undefined") //NOTE: This condition checks the whether there is a span for displaying username in the html or not. 
				{lc_userName.innerHTML=username;}//This feature is only available to Old DEP Clients, currently.
               if (document.getElementById("live_chat_img") == null) {
                    var anchorTag = document.createElement("a");
                    anchorTag.setAttribute("href", "#");
					anchorTag.style.border="none";
                    var footDiv = document.getElementById(liveChatStatus);
                    var imgTag = document.createElement("img");
					imgTag.style.border="none";
                    imgTag.setAttribute("id", "live_chat_img");
                    imgTag.setAttribute("src", _imageURL + LC_onlineImg);
                    anchorTag.appendChild(imgTag);
                    footDiv.appendChild(anchorTag);
					jQuery("#live_chat_img").bind("click",function () {
					WithoutGreet = true;
					clearTimeout(GreetingTimer);
					StartChatProcess();
				});
                }
                else {
                    var imgTag = document.getElementById("live_chat_img");
					imgTag.style.border="none";
					jQuery("#live_chat_img").bind("click",function () {
					WithoutGreet = true;
					clearTimeout(GreetingTimer);
					StartChatProcess();
				});
                    imgTag.setAttribute("src", _imageURL + LC_onlineImg);
                }

                messageId = result[8];
                lc_message = result[9];
				senderId = result[10];
				lc_servicestatus = result[11];
                firstMessage = false; //If chat is continued then first message is false.
                jQuery("#ChatDiv").fadeIn("3000");
				if (senderId == 0) {
					ChatWin.value += visitorName + ": " + lc_message + "\n";
					ChatWin.scrollTop = ChatWin.scrollHeight;
				}
				else{
					ChatWin.value += username + ": " + lc_message + "\n";
					ChatWin.scrollTop = ChatWin.scrollHeight;
				}
                chatMessageAltURL = _chatURL+"GetChatMessagesAlt?parChatId=";
                chatMessageAltURL += chatId;
                chatMessageAltURL += "&parMessageId=";
                chatMessageAltURL += messageId;
                var dt = new Date();
                chatMessageAltURL += "&strRandom=";
                chatMessageAltURL += dt.getTime().toString();
                chatMessageAltURL += "&method=onGetChatMessagesAltResponse";
                jsonpCreator(chatMessageAltURL);
				aLink.setAttribute("href", "javascript:onConversationClick()");
            }
        }
        //URL For Complete Conversation
		aLink.style.display = 'block';
    }
}

function onConversationClick() {
    window.open(_convURL+"?chatId=" + chatId, "_blank", "menubar=0,resizable=1,width=400,height=500,scrollbars=1");
}

//To Display Chat Window
function showWindow() {
	if(readCookie(LC_CEC)!=null){
		createCookie(LC_CEC,null,-24);
		//alert(readCookie(LC_CEC));
}
		jQuery("#ChatDiv").fadeIn("3000");
		ChatWin.value = username + ": " + lc_message + "\n";
		dt = new Date();
		var greetInfoInsertURL = _chatURL+"InsertGreetInfo?parUserId=";
		greetInfoInsertURL += senderId;
		greetInfoInsertURL += "&parVisitorId=";
		greetInfoInsertURL += visitorId;
		greetInfoInsertURL += "&parWebsiteId=";
		greetInfoInsertURL += websiteId;
		greetInfoInsertURL += "&parRandom=";
		greetInfoInsertURL += dt.getTime().toString();
		greetInfoInsertURL += "&method=onInsertGreetInfoResponse";
		jsonpCreator(greetInfoInsertURL);
}

function onInsertGreetInfoResponse(result)
	{
		if (result != null) 
		{
			greetId=result;
			isOnlyGreeted=true;
			CloseGreet=setTimeout("CloseChatWindow()",1000*60*5); //Close Chat window after 5 minutes if visitor does not repond.
		}
	}
//If Insert Chat Info Service is successful
function onInsertChatInfoResponse(result) {
    if (result != null) {
        chatId = result[0];
		messageId=result[1];
        isAlreadyInChat = true;
        //URL For Complete Conversation
        var aLink = document.getElementById("conversationDIV");
        aLink.setAttribute("href", "javascript:onConversationClick()");
        aLink.style.display = 'block';        
		SetIntervalForMessages();
    }
}

//To Insert a Chat Message into the Database
function insertChatMessages() {
    //Call chat Message Insertion Service
	var chatMessageInsertURL = _chatURL+"InsertChatMessage?parMessage=";
    var strChatMessageTmp = lc_message.toString();
	var updatedChatMessage = ReplaceSpecialCharacters(escape(strChatMessageTmp));
    chatMessageInsertURL += updatedChatMessage;
    chatMessageInsertURL += "&parChatId=";
    chatMessageInsertURL += chatId;
    chatMessageInsertURL += "&parUserId=";
    chatMessageInsertURL += senderId;
	chatMessageInsertURL += "&parAssignedUserId=";
    chatMessageInsertURL += actualUserId;
    chatMessageInsertURL += "&parTimestamp=";
    var messageTimeStamp = new Date();
    chatMessageInsertURL += messageTimeStamp.getFullYear().toString() + "_" + messageTimeStamp.getMonth().toString() + "_" + messageTimeStamp.getDate().toString() + "_" + messageTimeStamp.getHours().toString() + "_" + messageTimeStamp.getMinutes().toString() + "_" + messageTimeStamp.getSeconds().toString();
    chatMessageInsertURL += "&method=onInsertChatMessageResponse";
    jsonpCreator(chatMessageInsertURL);
}

function onInsertChatMessageResponse(result) {
    if (result != null){
        if (messageId < result){
            messageId = result;
        }
        if (!firstMessage) {
            SetIntervalForMessages();
        }
    }
}

function GetNextMessage() {
    var dt = new Date();
    chatMessageAltURL = _chatURL+"GetChatMessagesAlt?parChatId=";
    chatMessageAltURL += chatId;
    chatMessageAltURL += "&parMessageId=";
    chatMessageAltURL += messageId;
    chatMessageAltURL += "&strRandom=";
    chatMessageAltURL += dt.getTime().toString();
    chatMessageAltURL += "&method=onGetChatMessagesAltResponse";
    jsonpCreator(chatMessageAltURL);
}

function onUpdateTypingStatusURLResponse(result){
    if (result != null) {
        if (result) {
            //do some task here
            return;
        }
        else
        { return; }
    }
}

function onUserTypingStatusResponse(result){
    if (result != null) {
        if (result) {
            statusDIV.style.display = "block";
        }

        else {
            statusDIV.style.display = "none";
        }
    }
}

function GetUserTypingStatusMethod() {
    var getOperatorTypingStatusURL = _chatURL+"GetUserTypingStatus?parUserId=";
    getOperatorTypingStatusURL += chatId;
    var dt = new Date();
    getOperatorTypingStatusURL += "&strRandom=";
    getOperatorTypingStatusURL += dt.getTime().toString();
    getOperatorTypingStatusURL += "&method=onUserTypingStatusResponse";
    jsonpCreator(getOperatorTypingStatusURL);
    return;
}

/*function UpdateTypingStatusMethod() {
    var updateTypingStatusURL = _chatURL+"UpdateVisitorTypingStatus?parVisitorId=";
    updateTypingStatusURL += visitorId;

    updateTypingStatusURL += "&parIsTyping=";
    if (MsgWin.value == "") {
        updateTypingStatusURL += false;
    }
    else {
        updateTypingStatusURL += true;
    }
    var dt = new Date();
    updateTypingStatusURL += "&strRandom=";
    updateTypingStatusURL += dt.getTime().toString();
    updateTypingStatusURL += "&method=onUpdateTypingStatusURLResponse";
    jsonpCreator(updateTypingStatusURL);
}
*/
//To see which operator has sent the message. If zero is returned then it is from the visitor.
function onGetStatusOfMessageResponse(result) {
    if (result != null) {
        jQuery("#ChatDiv").fadeIn("3000");
        senderId = result;

        if (result == 0) {
            ChatWin.value += visitorName + ": " + lc_message + "\n";
            ChatWin.scrollTop = ChatWin.scrollHeight;
        }

        else if (result == senderId) {
            ChatWin.value += username + ": " + lc_message + "\n";
            ChatWin.scrollTop = ChatWin.scrollHeight;
        }

        else {
            actualUserId = result;
            var getUserNameURL = _chatURL+"GetUsername?parUserId=";
            getUserNameURL += senderId;
            var dt = new Date();
            getUserNameURL += "&strRandom=";
            getUserNameURL += dt.getTime().toString();
            getUserNameURL += "&method=onGetUsernameOnlyResponse";
            jsonpCreator(getUserNameURL);
        }
    }
}

function onGetUsernameOnlyResponse(result) {
    if (result != null) {
        username = result;

        ChatWin.value += username + ": " + lc_message + "\n";
        ChatWin.scrollTop = ChatWin.scrollHeight;
        actualUserId = senderId;
    }
}
//Get Visitor Name
function onGetVisitorNameOnlyResponse(result) {
    if (result != null) {
        visitorName = result.toString();
    }
}

function GetVisitorNameMethod() {
    var visitorNameURL = _chatURL+"GetVisitorName?parVisitorId=";
    visitorNameURL += visitorId;
    var dt = new Date();
    visitorNameURL += "&strRandom=";
    visitorNameURL += dt.getTime().toString();
    visitorNameURL += "&method=onGetVisitorNameOnlyResponse";
    jsonpCreator(visitorNameURL);
}

//If Get Chats Messages Service is successful
function onGetChatMessagesAltResponse(result) {
    if (result != null) {
        //The Array Consists of a Pair of Values the Message Text and the SenderId
        messagesFromServer = result;
        RetreiveAllMessages();
    }
}

jQuery("#btnURL").bind("click",function() {
	if(pageToPush!="" && pageToPush!=null){
	window.open(pageToPush, "_blank", "menubar=1,resizable=1,width=800,height=600,scrollbars=1");
	}
});

function ExtractURL() {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    //alert(regexp.test(lc_message));
    if (regexp.test(messagesFromServer[count].toString())) {
        var urlArr = messagesFromServer[count].toString().match(regexp);
        pageToPush = urlArr[0].toString();
        //btnVisit.setAttribute("onclick", "PopPushPage()");
        //PopPushPage();
		jQuery("#btnURL").click();
    }
}

function RetreiveAllMessages() {
    ClearIntervalForMessages();

   // var callGetVisitorName = GetVisitorNameMethod();
		if(messagesFromServer.length>1)
		{
		 visitorName= messagesFromServer[messagesFromServer.length-3]; //Setting visitor name
		
    if (messagesFromServer[0] != "") {

			for (count = 0; count < messagesFromServer.length - 7; count += 3) {
				//THIS NEEDS TO BE CHECKED AGAIN.
				if (messagesFromServer[count + 1] == 0 && messageId != messagesFromServer[count + 2]) {
					lc_message = messagesFromServer[count].toString();
					messageId = messagesFromServer[count + 2].toString();

					ChatWin.value += visitorName + ": " + messagesFromServer[count].toString() + "\n";
					ChatWin.scrollTop = ChatWin.scrollHeight;

				} //End of If
				else if (messageId != messagesFromServer[count + 2]) //If message received is a user message
				{
					if (messagesFromServer[count + 1] == actualUserId) { //If User is same
						lc_message = messagesFromServer[count].toString();
						messageId = messagesFromServer[count + 2].toString();
						username = messagesFromServer[messagesFromServer.length-2]; //Setting new username
						actualUserId = messagesFromServer[count + 1];
						if(typeof(lc_userName)!="undefined") //NOTE: This condition checks the whether there is a span for displaying username in the html or not. 
							{lc_userName.innerHTML=username;}//This feature is only available to Old DEP Clients, currently.
						ChatWin.value += username + ": " + messagesFromServer[count].toString() + "\n";

						ChatWin.scrollTop = ChatWin.scrollHeight;

						ExtractURL();
					}
					else { //If chat is transferred and user is updated
						lc_message = messagesFromServer[count];
						senderId = messagesFromServer[count + 1];
						messageId = messagesFromServer[count + 2];
						username = messagesFromServer[messagesFromServer.length-2]; //Setting new username
						actualUserId = messagesFromServer[count + 1];
						if(typeof(lc_userName)!="undefined") //NOTE: This condition checks the whether there is a span for displaying username in the html or not. 
							{lc_userName.innerHTML=username;}//This feature is only available to Old DEP Clients, currently.
						ChatWin.value += username + ": " + lc_message + "\n";
						ChatWin.scrollTop = ChatWin.scrollHeight;
						/*var getUserNameURL = _chatURL+"GetUsername?parUserId=";
						getUserNameURL += senderId;
						var dt = new Date();
						getUserNameURL += "&strRandom=";
						getUserNameURL += dt.getTime().toString();
						getUserNameURL += "&method=onGetUsernameOnlyResponse";
						jsonpCreator(getUserNameURL);*/
						//Expression to extract URL from message
						ExtractURL();
					}
				} //End of Else

				//Used to check the time duration before the chat is automatically transferred to another operator.
				// Call Auto Transfer Chat Method here
				//SetTimerForAutoTransfer();
			} //End of For Loop

			//Updating Visitor Typing Status and Fetching User Typing Status.
			// NOTE: THIS IS CURRENTLY DISABLED AND CAN BE ACTIVATED AT ANY TIME.    
			//  var updateTyping =  UpdateTypingStatusMethod();
			//   var getTyping = GetUserTypingStatusMethod();
		} //End of If (messagesFromServer[0] != "")
		else if (messagesFromServer[messagesFromServer.length - 6] == "True") {
			ClearIntervalForMessages();
			ChatWin.value = username + ": This Chat has been closed due to inactivity and the window will close now in 10 seconds. To chat again kindly refresh your page." + "\n";
			setTimeout("document.getElementById('ChatDiv').style.display = 'none'", 10 * 1000);
			return;
		}
		if (messagesFromServer[messagesFromServer.length - 5] == "1" && messagesFromServer[messagesFromServer.length - 3] != "1") {
			//alert("DND"+messagesFromServer[messagesFromServer.length - 2]);
			createCookie(LC_DND, LC_DND+"=1", 8064);
		}
		else if (messagesFromServer[messagesFromServer.length - 4] == "1") {
			//alert("Ignore"+messagesFromServer[messagesFromServer.length - 1]);
			createCookie(LC_IGN, LC_IGN+"=1", 16128);
		}
		if(statusDIV!=null)	{
			 if (messagesFromServer[messagesFromServer.length - 1]=="True"){
				statusDIV.style.display = "block";
			}
			else{
				statusDIV.style.display = "none";
			}
		 }
	}
    SetIntervalForMessages();
}

//To transfer chat to another available operator.
function TransferChat() {
    //Call Get User on Minimum Chats Service
    //This method will return a userId of the new user.
    //The current Domain and the userId are passed as parameters to this service.
    getMinimumChatUserURL = _chatURL+"GetAutoTransferUser?parDomain=";
    getMinimumChatUserURL += host;
    getMinimumChatUserURL += "&parUserId=";
    getMinimumChatUserURL += senderId;
    var dt = new Date();
    getUsernameServiceURL += "&strRandom=";
    getUsernameServiceURL += dt.getTime().toString();
    getUsernameServiceURL += "&method=onGetNewUserIdOnly";
    jsonpCreator(getUsernameServiceURL);
}

//To fetch the username of the new assigned operator
function onGetNewUserIdOnly(result) {
    if (result != null) {
        senderId = result;
        //Call Get User Id Service
        var getUserURL = _chatURL+"TransferTempChatMessages?parChatId=";
        getUserURL += chatId;
        getUserURL += "&parUserId=";
        getUserURL += result;
        var dt = new Date();
        getUserURL += "&strRandom=";
        getUserURL += dt.getTime().toString();
        getUserURL += "&method=onTransferTempChatMessagesResponse";
        jsonpCreator(getUserURL);
    }
}

//To fetch the userId of the new assigned operator.
function onTransferTempChatMessagesResponse(result){
    if (result != null) {
        if (result == "") {
            var getUserNameURL = _chatURL+"GetUsername?parUserId=";
            getUserNameURL += senderId;
            var dt = new Date();
            getUserNameURL += "&strRandom=";
            getUserNameURL += dt.getTime().toString();
            getUserNameURL += "&method=onGetUsernameOnly";
            jsonpCreator(getUserNameURL);
        }
        //If Chat is not transferred
        else {
            //Code for chat not transferred.
        }
    }
}

//Update to the new username returned on chat transfer.
function onGetUsernameOnly(result) {
    if (result != null) {
        username = result;
    }
}

//Set Timer for Auto Transfer of Chat
// to set timer for close message
function SetTimerForAutoTransfer() {
    for (var i = 0; i < timerForUserMessage.length; i++) {
        if (timerForUserMessage[i] == null) {
            timerForUserMessage = setTimeout("TransferChat()", 3 * 60 * 1000);
            return;
        }
    }
    timerForUserMessage[timerForUserMessage.length] = setTimeout("TransferChat()", 3 * 60 * 1000);
}

//to reset timers for close message
function ClearTimerForUserMessage() {
    for (var i = 0; i < timerForUserMessage.length; i++) {
        clearTimeout(timerForUserMessage[i]);
    }
}

//On Clicking Send Chat Message Button
jQuery("#btnSend").bind("click",function() {
    //Reset Timer which displays message to close chat
    if (MsgWin.value.toString().length >= 300) {
        MsgWin.value.toString().substr(0, 300);
    }
	
    clearTimeout(chatCloseMessageTimer);
    if (isCautioned) {
        ChatWin.value = "";
        ChatWin.value = completeChatText;
        isCautioned = false;
    }
    var str = MsgWin.value;
    var trimmed = str.replace(/^\s+|\s+$/g, '');
    //If there is no text in the text Message Window
    if (trimmed != ""){
        lc_message = MsgWin.value;
        ChatWin.value += visitorName.toString() + ": " + lc_message + "\n";
        MsgWin.scrollTop = MsgWin.scrollHeight;
        ChatWin.scrollTop = ChatWin.scrollHeight;
        MsgWin.value = "";
        senderId = 0;
        //This will run only once
        if (firstMessage){
            //countOfMessages++;
			clearTimeout(CloseGreet);
            firstMessage = false;
			isOnlyGreeted = false;
			var aLink = document.getElementById("conversationDIV");
			aLink.setAttribute("href", "javascript:onConversationClick()");
			aLink.style.display = 'block';
			InsertChat();
            //Update Chat End Time to null as it may be set by the server.
            ResetChatEndTime();
        }
        else{
            ClearIntervalForMessages();
            insertChatMessages();
            SetTimerVar = false; //Not used
            // Start Timer for 3 minutes if time completes Display Message that chat is going
            // to closed. This feature is not being used.
            // SetTimerForCloseMessage();
        }
    }
});

function onUpdateUserChatResponse(result)
		{
			if(result!=null)
			{
				//Do Nothing
			}
		}

//to set interval for getting messages
function SetIntervalForMessages() {
    for (var i = 0; i < intervalsForGettingMessages.length; i++) {
        if (intervalsForGettingMessages[i] == null) {
            intervalsForGettingMessages[i] = setTimeout("GetNextMessage()", 1800);
            return;
        }
    }
    intervalsForGettingMessages[intervalsForGettingMessages.length] = setTimeout("GetNextMessage()", 1800);
}

// to reset interval for getting messages
function ClearIntervalForMessages() {
    for (var i = 0; i < intervalsForGettingMessages.length; i++) {
        clearTimeout(intervalsForGettingMessages[i]);
    }
}

//On Pressing Close Chat Window button.
function CloseChatWindow() {
    jQuery("#ChatDiv").fadeOut("2000");
    //reset timer and set cookie expiries of sessionId and chatId and update end time of database
    if(!isOnlyGreeted){
	var EndChatURL = _chatURL+"UpdateChatEndTime?parChatId=";
    EndChatURL += chatId;
    EndChatURL += "&parChatEndTime=";
    var chatEndTimeDate = new Date();
    EndChatURL += chatEndTimeDate.getDate().toString() + "_" + chatEndTimeDate.getMonth().toString() + "_" + chatEndTimeDate.getFullYear().toString() + "_" + chatEndTimeDate.getHours().toString() + "_" + chatEndTimeDate.getMinutes().toString() + "_" + chatEndTimeDate.getSeconds().toString();
    EndChatURL += "&method=onEndChatResponse";
    jsonpCreator(EndChatURL);
	}
	else
	{
	createCookie(LC_CEC, "EndStatus=1", 1);
            isAlreadyInChat = false;
	}
	ChatWin.value = "";
    MsgWin.value = "";
    //UpdateTypingStatusMethod();
    ClearTimerForCloseMessage();
    ClearIntervalForMessages();
    //to stop polling for new messages.
    //Set Expiry of ChatId and SessionId cookies here
}

function onEndChatResponse(result) {
    if (result != null) {
        if (result || result == "") {
			firstMessage = true;
            //Do some task here
            createCookie(LC_CEC, "EndStatus=1", 1);
            isAlreadyInChat = false;
            //     
            ChatWin.value = "";
            MsgWin.value = "";

            //UpdateTypingStatusMethod();
            ClearTimerForCloseMessage();
            ClearIntervalForMessages();
            //to stop polling for new messages.
            //Set Expiry of ChatId and SessionId cookies here
            //return;
        }
        //    else
        //      return;
    }
}

function ResetChatEndTime() {
    var EndChatURL = _chatURL+"UpdateChatEndTime?parChatId=";
    EndChatURL += chatId;
    EndChatURL += "&parChatEndTime=";
    EndChatURL += "";
    EndChatURL += "&method=onUpdateChatEndTimeResponse";
    jsonpCreator(EndChatURL);
	//Update Chat Count of a User by One
	//UpdateUserChatCount();
}

/* This Feature is implemented on ther server end
function UpdateUserChatCount()
{
	var UpdateUserChat = _chatURL+"UpdateUserChats?parUserId=";
			UpdateUserChat += actualUserId;
			UpdateUserChat += "&strRandom=";
			var dt = new Date();
			UpdateUserChat += dt.getTime().toString();
			UpdateUserChat += "&method=onUpdateUserChatResponse";
			jsonpCreator(UpdateUserChat);
            SetIntervalForMessages();
}
*/

function onUpdateChatEndTimeResponse(result) {
    if (result != null) {
        if (result != "") {
            //Do Some Task here
			//firstMessage = true;
			//isOnlyGreeted=true;
        }
    }
}

//Block Enter Key
function BlockKey() {
    MsgWin.value = "";
    setTimeout("unblock=true", 1000);
}

//On Pressing Enter Key
jQuery("#txtMessageWin").bind("keypress",function(event) {
    var keynum;
    //On Key Press Check Character Count and trim message
    if (MsgWin.value.toString().length >= 300) {
        var tmpMessage = MsgWin.value.toString();
        MsgWin.value = tmpMessage.substr(0, 300);
    }
    if (window.event) // IE
    {
        keynum = event.keyCode;
    }
    else if (event.which) // Netscape/Firefox/Opera
    {
        keynum = event.which;
    }
    if (keynum == 13) {
        if (unblock) {
            var messageSender = jQuery("#btnSend").click();//SendChatMessage();
            unblock = false;
        }
        BlockKey();
    }
});

//To Remove all the text in the chat window
jQuery("#txtMessageWin").bind("keyup",function(event) {
    var keynum;
    if (window.event) // IE
    {
        keynum = event.keyCode;
    }
    else if (event.which) // Netscape/Firefox/Opera
    {
        keynum = event.which;
    }
    if (keynum == 13) {
        MsgWin.value = "";
    }
});

//
function ClearMsgWin() {
    MsgWin.value = "";
}

//
function onPageLeavingUpdateVisitorReponse(result) {
    if (result != null) {
        if (result) {
            //Do some task here
            return;
        }
        else
        { return; }
        if (isWindowClosing) {
            CloseChatWindow();
        }
    }
}

//NOTE: This method needs to be checked as it is not working properly in a few browsers.
function ResetChatTimer() {
    if (visitorId != 0) {
        var liveVisitorResetURL = _chatURL+"UpdateVisitorStatus?parVisitorId=";
        liveVisitorResetURL += visitorId + "&parIsLiveVisitor=";
        liveVisitorResetURL += false;
        var dt = new Date();
        liveVisitorResetURL += "&strRandom=";
        liveVisitorResetURL += dt.getTime().toString();
        liveVisitorResetURL += "&method=onPageLeavingUpdateVisitorReponse";
        jsonpCreator(liveVisitorResetURL);
        //var liveVisitorReset = ChatServiceLocal.UpdateVisitorStatus(visitorId, false);
        for (i = 0; i < 30; )
        { i++; }
    }
    //alert("Leaving the browser UNLOAD!");
    // clearTimeout(timerForGettingMessages);
    ClearIntervalForMessages();
}

//NOTE: This method needs to be fixed as it has a few bugs in it.
function CheckWindowClosing() {
    //in case of a close action with the white cross in the red square in the title bar
    if (window.event.clientY < 0 && (window.event.clientX > (document.documentElement.clientWidth - 5) || window.event.clientX < 15)) {
        isWindowClosing = true;
        //action to fire when leaving...
        var liveVisitorClosingURL = _chatURL+"UpdateVisitorStatus?parVisitorId=";
        liveVisitorClosingURL += visitorId + "&parIsLiveVisitor=";
        liveVisitorClosingURL += false;
        var dt = new Date();
        liveVisitorClosingURL += "&strRandom=";
        liveVisitorClosingURL += dt.getTime().toString();
        liveVisitorClosingURL += "&method=onPageLeavingUpdateVisitorReponse";
        jsonpCreator(liveVisitorClosingURL);
        CloseChatWindow();
        for (i = 0; i < 30; )
        { i++; }
    }
}

//Feature to minimize and maximize chat window
function minimizeWindow(){
    jQuery("#ChatDiv").fadeOut("1000");
	 document.getElementById("minDiv").style.top = document.getElementById("ChatDiv").style.top;
	 document.getElementById("minDiv").style.left = document.getElementById("ChatDiv").style.left;
    jQuery("#minDiv").fadeIn("1000");
}

function maximizeWindow(){
    jQuery("#minDiv").fadeOut("1000");
	document.getElementById("ChatDiv").style.top = document.getElementById("minDiv").style.top;
	 document.getElementById("ChatDiv").style.left = document.getElementById("minDiv").style.left;
    jQuery("#ChatDiv").fadeIn("1000");
}

//NOTE: THE CLOSE CHAT MESSAGE AND IT'S RELATED METHODS ARE NOT BEING USED BECAUSE THIS FEATURE WILL BE IMPLEMENTED
// FROM THE OPERATOR END.
//Display Message that window will close in 2 mintues
function CloseChatMessage() {
    completeChatText = ChatWin.value;
    ChatWin.value += "\n" + "Due to Inactivity this chat window will close in 2 minutes!" + "\n";
    chatCloseMessageTimer = setTimeout("CloseChatWindow()", 2 * 60 * 1000);
    isCautioned = true;
}

// to set timer for close message
function SetTimerForCloseMessage() {
    for (var i = 0; i < timersForCloseMessage.length; i++) {
        if (timersForCloseMessage[i] == null) {
            timersForCloseMessage[i] = setTimeout("CloseChatMessage()", 3 * 60 * 1000);
            return;
        }
    }
    timersForCloseMessage[timersForCloseMessage.length] = setTimeout("CloseChatMessage()", 3 * 60 * 1000);
}

//to reset timers for close message
function ClearTimerForCloseMessage() {
    for (var i = 0; i < timersForCloseMessage.length; i++) {
        clearTimeout(timersForCloseMessage[i]);
    }
}

//New Method Added on 19/01/10 to improve application performance.
function InsertChat(){
	var chatInfoInsertURL = _chatURL+"InsertChatInfoAndMessage?parUserId=";
		chatInfoInsertURL += actualUserId;
		chatInfoInsertURL += "&parAssignedUserId=";
		chatInfoInsertURL += actualUserId;		
		chatInfoInsertURL += "&parWebsiteId=";
		chatInfoInsertURL += websiteId;		
		chatInfoInsertURL += "&parVisitorId=";
		chatInfoInsertURL += visitorId;
		chatInfoInsertURL += "&parRunningStatus=";
		chatInfoInsertURL += false;
		chatInfoInsertURL += "&parVisitorName=";
		chatInfoInsertURL += visitorName;
		chatInfoInsertURL += "&parGreetId=";
		chatInfoInsertURL += greetId;
		chatInfoInsertURL += "&parGreetMessage=";
		var newGreetMessage = ReplaceSpecialCharacters(autoGreetMessage);
		chatInfoInsertURL += newGreetMessage;
		chatInfoInsertURL += "&parChatMessage=";
		chatInfoInsertURL += ReplaceSpecialCharacters(lc_message);
		chatInfoInsertURL += "&parRandom=";
		var dt = new Date();
		chatInfoInsertURL += dt.getTime().toString();
		chatInfoInsertURL += "&method=onInsertChatInfoResponse";
		jsonpCreator(chatInfoInsertURL);
}

function ReplaceSpecialCharacters(stringValue)
{
	var updatedString="";
	updatedString = stringValue.replace("#","%23");
	updatedString = updatedString.replace("$","%24");
	updatedString = updatedString.replace("&","%26");
	updatedString = updatedString.replace("+","%2B");
	updatedString = updatedString.replace(",","%2C");
	updatedString = updatedString.replace("/","%2F");
	updatedString = updatedString.replace(":","%3A");
	updatedString = updatedString.replace(";","%3B");
	updatedString = updatedString.replace("=","%3D");
	updatedString = updatedString.replace("?","%3F");
	updatedString = updatedString.replace("@","%40");
	return updatedString;
}