﻿/* ################################## SETTINGS ################################## */

var protocol = "http";
var hostdomain = "www.odyssey.co.uk"; // e.g. www.mysite.com
var testdomain = "www.odyssey.co.uk"; // e.g. develop.mysite.com
var directory = "engage"; // e.g. engage
var language = "php"; // Currently only php available
var chatclosemessage = "Are you sure you want to end the chat session?"; // Confirm message displayed when closing the sesion
var chatrestartmessage = "Restart Chat" // Text (or image) to enable the visitor to restart chat
var template = "default"; // template folder used for images
var usingjquery = true; // Is the rest of the site is using jQuery? true | false

/* #################### DO NOT EDIT ANYTHING BELOW THIS LINE #################### */

var ENGChatDiv;
var ENGTextBox;
var ENGButton;
var ENGChatUID;
var ENGSessionID;
var ENGServerURL;
var ENGDomain;
var ENGChatDisplay;
var ENGCloseSession;
var ENGTimeoutHandle;
var ENGKeepAliveHandle;
var ENGReStartingChat;
var ENGStartNewChat;
var ENGTrackTimeout;
var doKeepAlive;
doKeepAlive = false;
ENGStartNewChat = false;
ENGCloseSession = false;
ENGReStartingChat = false;

var jeng = (usingjquery == true ? $: jQuery.noConflict());

function silentErrorHandler() {return true;}
window.onerror=silentErrorHandler;


// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}


function startChatWindow2() {
	setupChatWindow();
	
	var engageuserid = ''; 
	jeng.post(protocol+"://"+(testdomain ? testdomain : hostdomain)+"/"+directory+"/"+language+'/sessions.'+language, { func: "recalluserid" }, function(data) {
		if (data != null && data != ""){
			if (ENGStartNewChat)
			{
			ENGStartSession();
			} else {
			ENGContinueSession(data); // continue with the same id
			scrollDiv(data); // open chat window : will need refining			
			}
		}
		else{
			//CallSingle();
			ENGStartSession();
		}
	});
	
}

function pause(milliseconds) {
	var dt = new Date();
	while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

function trackPolling()
{
		jeng.getJSON("/engage/php/spoll.php?" + "u="+escape(window.location)+"&r="+escape(document.referrer)+"", function(){});
		ENGTrackTimeout = setTimeout(trackPolling, 7000);
}

function CloseChatSession() {
   var answer = confirm(chatclosemessage)
	if (answer){
		ENGCloseSession = true;
		doKeepAlive = false;
		clearTimeout(ENGTimeoutHandle);
		clearTimeout(ENGKeepAliveHandle);
		jeng.getJSON(ENGServerURL + "CloseChatSession&SessionID=" + ENGSessionID + "&Domain="+ENGDomain+"&method=?", CallBackChatClose);
		jeng.post(protocol+"://"+(testdomain ? testdomain : hostdomain)+"/"+directory+"/"+language+'/sessions.'+language, { func: "sessionstatus","sessionstatus" : "closed"});
		
		jeng("#chatbox").slideUp(function(){
			jeng("#sideform").slideDown();
			jeng("#outerchat").append('<a href="javascript:void(\'\')" id="restartchat">'+chatrestartmessage+'</a>');
		});
	}
}

function CloseChatSession2() {
		ENGCloseSession = true;
		clearTimeout(ENGTimeoutHandle);
		clearTimeout(ENGKeepAliveHandle);
		jeng.getJSON(ENGServerURL + "CloseChatSession&SessionID=" + ENGSessionID + "&Domain="+ENGDomain+"&method=?", CallBackChatClose);
		jeng.post(protocol+"://"+(testdomain ? testdomain : hostdomain)+"/"+directory+"/"+language+'/sessions.'+language, { func: "sessionstatus","sessionstatus" : "closed"});
		
		jeng("#chatbox").slideUp(function(){
			jeng("#sideform").slideDown();
			jeng("#outerchat").append('<a href="javascript:void(\'\')" id="restartchat">'+chatrestartmessage+'</a>');
		});
}


function CallBackChatClose() {
           resultDiv = document.getElementById("ENGChatDisplay");
           resultDiv.innerHTML = "Chat Session Closed";
       }

function CallSingle() {
	jeng.getJSON("/engage/php/sinfo.php?" + "u="+escape(window.location)+"&r="+escape(document.referrer)+"", function(){});
	pause(50);
	jeng.getJSON(ENGServerURL + "GetStatus&Department=&Domain="+ENGDomain+"&Language=en&UserAgent=" + navigator.userAgent + "&method=?", CallBackSingle);
}

function CallBackSingle(WebServiceResult) {
	if (WebServiceResult.Operators.length > 0) {
		//ENGChatDisplay.innerHTML = "Hi there - how can I help?";
		ENGStartSession();
	} else {
		ENGChatDisplay.innerHTML = "Sorry no Operators are online!";
	}
}

function ENGStartSession() {
    ENGSessionID = createUUID();
	ENGCloseSession = false;
	ENGChatDisplay.innerHTML="";
//	jeng.getJSON("/engage/php/sinfo.php?" + "u="+escape(window.location)+"&r="+escape(document.referrer)+"", function(){});
    jeng.getJSON(ENGServerURL + "StartChat&Domain=" + ENGDomain + "&SelectedOperator=&SelectedDepartment=&SessionID=" + ENGSessionID + "&Language=en&VisitorName=Auto&method=?", ENGCallBackChatStart);
	
}

function ENGContinueSession(engageuserid) {
    ENGSessionID = engageuserid;
    recallMessages();
}

function ENGCheckForMessage() {
//	$.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8"});
	//jeng.getJSON("/engage/php/spoll.php?" + "u="+escape(window.location)+"&r="+escape(document.referrer)+"", function(){});
    clearTimeout(ENGTimeoutHandle);
	if (!ENGCloseSession)
	{
	jeng.getJSON(ENGServerURL + "CheckForMessage&SessionID=" + ENGSessionID + "&Domain=" + ENGDomain + "&method=?", ENGCallBackMessageCheck);
	ENGTimeoutHandle = setTimeout(ENGCheckForMessage, 1000);
	}
}

function ENGKeepAlive() {
	if (!ENGCloseSession)
	{
	if (doKeepAlive)
	{
	jeng.getJSON(ENGServerURL + "KeepAlive&SessionID=" + ENGSessionID + "&Domain=" + ENGDomain + "&method=?", ENGKeepAliveResponse);
    ENGKeepAliveHandle = setTimeout(ENGKeepAlive, 1000);
	}
	}
}


function recallMessages() {
	var engageconversation = '';
	jeng.post(protocol+"://"+(testdomain ? testdomain : hostdomain)+"/"+directory+"/"+language+'/sessions.'+language, { func: "recallconversation" }, function(data) {
		var sp = document.createElement("div");
		sp.innerHTML = '<span class="cap"></span>'+data;
		ENGChatDisplay.innerHTML = "";
		ENGChatDisplay.appendChild(sp);
		clearTimeout(ENGTimeoutHandle);
		ENGTimeoutHandle = setTimeout(ENGCheckForMessage, 1000);
		scrollDiv(data);
	});
	 
}

// Event Handlers
function ENGSendMessage(e) {
    jeng.getJSON(ENGServerURL + "SendMessage&SessionID=" + ENGSessionID + "&Domain=" + ENGDomain + "&Message=" + escape(jeng.trim(ENGTextBox.value)) + "&method=?", ENGMessageSent);
    ENGTextBox.value = "";
}

function ENGTextBoxKeyPress(e) {
    var characterCode;
    if (e && e.which) {           // NN4 specific code
        e = e;
        characterCode = e.which;
    } else {
        e = event;
        characterCode = e.keyCode;  // IE specific code
    }
    if (characterCode == 13) {
		ENGSendMessage(e);
		}    // Enter key is 13
}


// Callback Functions

function ENGMessageSent() { }

function ENGCallBackChatStart(ChatStartResult) { // Keiron Firebug: {"Busy":false,"ChatUID":"36FBB64827","IsError":false,"Message":null} );
    ENGChatUID = ChatStartResult.ChatUID;
	ENGChatBusy = ChatStartResult.Busy;
	//alert('Busy: '+ENGChatBusy);
	//alert('UID: '+ENGChatUID);
    ENGCheckForMessage();
}

function ENGCallBackMessageCheck(MessageResult) {

	var cmd = MessageResult.substring(0, 2);
    var dat = MessageResult.substring(2);
	if (cmd=="X:")
	{
	if (ENGCloseSession==false)
	{
			//ENGStartSession();
			if (ENGReStartingChat)
			{
				ENGReStartingChat = false;
				ENGStartSession();
				
			} 
			else 
			{
				CloseChatSession2();
			}
			
	}
	}
	/*
	jeng.post('sessions.php', { func: "recalllastmessage" }, function(savedmessage) {
		if (savedmessage != null && savedmessage != "" && savedmessage != dat && dat != null && dat != ""){
			document.title = savedmessage+" is different to "+dat;
			
		}
		else{
			document.title = "match";
		}
		
		});
	
	*/
	
    if (MessageResult != "" && MessageResult != "0:") {
    
		var sp = document.createElement("div");
		
		if(dat.indexOf('linesays') > 0 && dat.indexOf('lineo') > 0){ 					// Keiron added this
			sp.className = "operatorbubble"; 											// Keiron added this
		}																				// Keiron added this
		else if(dat.indexOf('linesays') > 0 && dat.indexOf('linev') > 0){ 				// Keiron added this
			sp.className = "visitorbubble"; 											// Keiron added this
		}																				// Keiron added this
		else {																			// Keiron added this
			sp.className = "serverbubble";												// Keiron added this
		}																				// Keiron added this
        if(dat){  																		// Keiron added this to stop empty messages poping up
			scrollDiv(dat); 															// Keiron added this
			dat = dat.replace(' says:', ':');
			dat = dat.replace('Guest:', 'You:');										// Keiron added this | <img src="'+window.visitorimage+'" />
			dat = dat.replace('<br>&nbsp;', '');										// Keiron added this
			dat = dat.replace('<br>', '');												// Keiron added this
			sp.innerHTML = '<span class="cap"></span>'+dat; 							// keiron removed  + "<br />"
			ENGChatDisplay.appendChild(sp);
						
			jeng.post(protocol+"://"+(testdomain ? testdomain : hostdomain)+"/"+directory+"/"+language+'/sessions.'+language, { func: "saveconversation","engageconversation": ENGChatDisplay.innerHTML});
		}
    }
}

function ENGKeepAliveResponse(MessageResult) {	

}


function createUUID() {
    // http://www.ietf.org/rfc/rfc4122.txt
    var s = [];
    var hexDigits = "0123456789ABCDEF";
    for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[12] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01

    var uuid = s.join("");
	
	jeng.post(protocol+"://"+(testdomain ? testdomain : hostdomain)+"/"+directory+"/"+language+'/sessions.'+language, { func: "saveuserid","engageuserid": uuid});
	jeng.post(protocol+"://"+(testdomain ? testdomain : hostdomain)+"/"+directory+"/"+language+'/sessions.'+language, { func: "savechatstatus","chatstatus": "open"});
	jeng.post(protocol+"://"+(testdomain ? testdomain : hostdomain)+"/"+directory+"/"+language+'/sessions.'+language, { func: "saveconversation","engageconversation": ""});

    return uuid;
}


// Set up variables
	var startstate = 'hidden'; // hidden or....
	var startimage = protocol+'://'+(testdomain ? testdomain : hostdomain)+'/'+directory+'/templates/'+template+'/images/chatHeader.gif'; // If hidden,the start image to show
	var visitorimage = protocol+'://'+(testdomain ? testdomain : hostdomain)+'/'+directory+'/templates/'+template+'/images/vis.gif'; // If hidden,the start image to show
	var operatorimage = protocol+'://'+(testdomain ? testdomain : hostdomain)+'/'+directory+'/templates/'+template+'/images/opp.gif'; // If hidden,the start image to show
	var sessionstatus = "";


if (/*@cc_on!@*/false) { // check for Internet Explorer
	document.onfocusin = chatresume;
	document.onfocusout = keepAlive;
} else {
	window.onfocus = chatresume;
	window.onblur = keepAlive;
}

function chatsuspend(){
	clearTimeout(ENGTimeoutHandle);
}

function keepAlive(){
	clearTimeout(ENGTimeoutHandle);
	if (!ENGCloseSession)
	{	
		ENGKeepAlive();
	}
}

function chatresume(){
	clearTimeout(ENGKeepAliveHandle);
	if(ENGChatDisplay){
		recallMessages();
	  if (!ENGCloseSession)
	  {
		ENGCheckForMessage();
	  }

	}

}

function setupChatWindow(){
	jeng("#outerchat").append('<div id="chatbox"><a href="javascript:CloseChatSession();" title="End Chat" id="closechat"><img src="'+protocol+'://'+(testdomain ? testdomain : hostdomain)+'/'+directory+'/templates/'+template+'/images/trans.gif" width="10" height="10" alt="End Chat" /></a><div id="chatheader"><img src="'+startimage+'" id="triggerchat" /></div><div id="ENGChatDiv"><div id="ENGChatDisplay"></div><div id="chatinputs"><textarea id="ENGTextBox" onKeyPress="ENGTextBoxKeyPress(); return true"></textarea><input type="button" id="ENGButton" onclick="ENGSendMessage(); return true" value="Send" class=""></div></div></div>');
	jeng('#chatbox').show();
	ENGChatDiv = document.getElementById('ENGChatDiv');
	ENGTextBox = document.getElementById('ENGTextBox');
	ENGButton  = document.getElementById('ENGButton');
	ENGChatDisplay = document.getElementById('ENGChatDisplay');
	ENGTextBox.onkeypress = ENGTextBoxKeyPress; // Keiron put this back in
//	ENGServerURL = url + "/";
	ENGServerURL = protocol + "://" + (testdomain ? testdomain : hostdomain) + "/" + directory + "/" + language + "/p." + language + "?act=";
	ENGDomain = hostdomain;
}


function intializeifready(){
	trackPolling();
	// Check operators are online before doing anuthing else
	jeng.getJSON(protocol+"://"+(testdomain ? testdomain : hostdomain)+"/"+directory+"/"+language+"/p."+language+"?act=GetStatus&Department=&Domain="+hostdomain+"&Language=en&UserAgent=" + navigator.userAgent + "&method=?", isAlive);
}


jeng(document).ready(function() {
	//jeng.getJSON("/engage/php/sinfo.php?" + "u="+escape(window.location)+"&r="+escape(document.referrer)+"&randon="+rand, intializeifready); //sinfo call
	var EngageDisable= Get_Cookie("EngageDisable");
	if (EngageDisable=='true')
	{
		return false;
	} else {

	rand = Math.floor(Math.random()*199999);
	jeng.ajax({
	  url: "/engage/php/sinfo.php?" + "u="+escape(window.location)+"&r="+escape(document.referrer)+"&randon="+rand,
	  context: document.body,
	  success: intializeifready
	  });	
	
	jeng("#ENGChatDisplay a").live('click', function(){
		jeng(this).removeAttr("target")
	});

	jeng("#restartchat").live('click', function(){
		
		jeng("#restartchat").remove();
		jeng(".ajaxSubmit").fadeOut(100, function(){
			jeng(".ajaxSubmit").remove();
		});
		
		jeng.post(protocol+"://"+(testdomain ? testdomain : hostdomain)+"/"+directory+"/"+language+'/sessions.'+language, { func: "killsession","killsession" : ""});
			jeng("#sideform").slideUp(function(){
			
				//if(jeng('#chatbox').length == 0){
				//	jeng("#outerchat").append('<div id="chatbox"><a href="javascript:CloseChatSession();" title="End Chat" id="closechat"><img src="'+protocol+'://'+(testdomain ? testdomain : hostdomain)+'/'+directory+'/templates/'+template+'/images/trans.gif" width="10" height="10" alt="End Chat" /></a><div id="chatheader"><img src="'+startimage+'" id="triggerchat" /></div><div id="ENGChatDiv"><div id="ENGChatDisplay"></div><div id="chatinputs"><textarea id="ENGTextBox" onKeyPress="ENGTextBoxKeyPress(); return true"></textarea><input type="button" id="ENGButton" onclick="ENGSendMessage(); return true" value="Send" class=""></div></div></div>');			
				//}
				
					jeng("#chatbox").slideDown();
					//ENGReStartingChat = true;
					startChatWindow2();
				
	
			});
	});	
	jeng('#switchchat').live('click',function(){
		if (jeng('#ENGChatDiv').closest('div').is(':visible') ) {
			jeng('#ENGChatDiv').closest('div').slideUp();
			jeng('#nochat').slideDown();
			jeng.post(protocol+"://"+(testdomain ? testdomain : hostdomain)+"/"+directory+"/"+language+'/sessions.'+language, { func: "savechatstatus","chatstatus": "closed"});
		}
		else{
			jeng('#ENGChatDiv').closest('div').slideDown();
			jeng('#nochat').slideUp();
			jeng.post(protocol+"://"+(testdomain ? testdomain : hostdomain)+"/"+directory+"/"+language+'/sessions.'+language, { func: "savechatstatus","chatstatus": "open"});
		}
	});	
	}// ifelse engagedisable
});


function isAlive(WebServiceResult) {
	available = false; // check if operators are available
	for (var ops in  WebServiceResult.Operators)
	{
	if (WebServiceResult.Operators[ops].Status==0)
	{
		available = true;
	}
	}

	if (available)
	{
		jeng.post(protocol+"://"+(testdomain ? testdomain : hostdomain)+"/"+directory+"/"+language+'/sessions.'+language, { func: "ischatclosed" }, function(data) {
			if (data == "open"){
			setupChatWindow();
			doKeepAlive = true;
			jeng.post(protocol+"://"+(testdomain ? testdomain : hostdomain)+"/"+directory+"/"+language+'/sessions.'+language, { func: "recalluserid" }, function(data) {
			ENGContinueSession(data);
			});
			} else {
			jeng.post(protocol+"://"+(testdomain ? testdomain : hostdomain)+"/"+directory+"/"+language+'/sessions.'+language, { func:"issessionclosed" }, function(data) {
			if (data){
				jeng("#sideform").show();
				jeng("#outerchat").append('<a href="javascript:void(\'\')" id="restartchat">'+chatrestartmessage+'</a>');
			} else {
			ENGStartNewChat = true;
			doKeepAlive = true;
			startChatWindow2();
			}				
			});
			}
		});
	} else {
		jeng("#sideform").show();
		jeng("#outerchat").append('<a href="javascript:void(\'\')" id="restartchat">'+chatrestartmessage+'</a>');
	}


}

function scrollDiv(message){
			
		if(message.indexOf('linesays') > 0 && message.indexOf('lineo') > 0){
			if(jeng("#ENGChatDiv").is(":hidden")){ // Before sliding down we want to hide previous server messages (and we only want to do this once)
				jeng('.serverbubble').remove();
				//jeng('#switchchat').html('Minimise chat').removeClass('closed');
			}
						
			jeng('#ENGChatDiv').closest('div').slideDown();
			jeng('#nochat').slideUp();
			
			//jeng('#triggerchat').closest('div').slideUp(400, function(){
			//jeng('#triggerchat').closest('div').attr('id','switchchat').html('Minimise chat').slideDown();
		//});
		}
		


		jeng("#ENGChatDisplay").animate({ scrollTop: jeng("#ENGChatDisplay").attr("scrollHeight") }, 300);
				
	}

