﻿//newRef Ver.No.: 0.1.7 ----------------------------------------LIVE----------------------------------------
/*----------------------------- Important Note--------------
This script consists of the jquery min libarary as well as custom javascript. The custom javascript currently
consists of visitor tracking information and chat process initialization
----------------------------------------------------------*/
/*  
File Name: newRef.js 
Ver.No.: 0.1.8
NOTE: Service Schedule is now live. Offline Service Page is also implemented.

Bugs Removed:
1) If a visitor who has already chatted once starts a chat and then switches the page, was unable to view his/her chat after page switching.
   This issue is now resolved.
Features Added:
none
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 ChatScript.js currently they are placed in this file.
*/

//Variables used
var GUID = null;
var referrer = null;
var source = "";
var endStatus = "0";
var websiteId = null;
var host = new String();
var SessionCookie = null;
var ChatStatusCookie = null;
host = location.hostname.toString();

//Variables for cookies and urls
var WG_CEC = "DEP_CEC";
var WG_VIC = "DEP_VIC";
var WG_DND = "DEP_DND";
var WG_IGN = "DEP_IGN";
var WG_onlineImg = "op_online.gif";
var WG_offlineImg = "op_offline.gif";
var _trackURL = "http://www.dealereprocesschat.com:8089/Default.aspx";
var _offlineURL = "http://www.dealereprocesschat.com:8089/OfflineMessage.aspx";
var _chatURL = "http://www.dealereprocesschat.com:8085/VisitorService/ChatService.svc/";
var _imageURL = "http://www.dealereprocesschat.com/dealereprocess/";
var _convURL = "http://www.dealereprocesschat.com:8088/Conversation.aspx";
var live_chat_status = "footerDIV";
var lc_typing_status=false; /**/

//To remove
//alert(host.substring(0, 4));
if (host.substring(0, 4) == "www.") {
    host = host.substring(4, host.length);
    //alert(host);
}
var statusErased = false;

//Manage Methods on page load event
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

//addLoadEvent(makeFrame);

// to Extract the domain out of a URL
function GetDomainName(url) {
    return url.split(/\/+/g)[1]; //url.match(/:\/\/(.[^/]+)/)[1];
}

//To Get Data from the cookie
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ')
        { c = c.substring(1, c.length); }

        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
}

//To Create A Cookie with expiry in hours
function createCookie(name, value, hours) {
    if (hours) {
        var date = new Date();
        date.setTime(date.getTime() + (hours * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/; domain=" + host + ";";
}

//To Create a cookie with Expiry in Days
function createCookieWithDayExpiry(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

//TO set values/value of the cookie
function setCookie(name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
    document.cookie = curCookie;
}

//To Erase a Cookie
/*function eraseCookie(name) {
jQuery.cookie(name,null);
   // document.cookie = name + "=" + ";" + "expires=Thu, 01-Jan-70 00:00:01 GMT" + "; path=/";
}*/

//To create a dynamic script tag with the source as specified in the url and append at the end of the body of the page.
function jsonpCreator(url) {
    var script = document.createElement("script");
    script.setAttribute("src", url);
    script.setAttribute("type", "text/javascript");
    document.body.appendChild(script);
}

function onGetGUIDResponse(result) {
    GUID = result.toString();
    //Create a Session Cookie with Session equal to GUID and its lifetime set to one hour
    createCookie(WG_VIC, "Session=" + result.toString(), 2160);
    if (readCookie(WG_VIC) != null) {
        SetSource();
    }
}


//Set GUID in Cookie
function SetGUID() {
    jsonpCreator(_chatURL+"GetGUID?method=onGetGUIDResponse");
}

//Set Tracking Server Source for the Iframe.
function SetSource() {
    source = _trackURL+"?MySession=" + "Session=" + GUID + "&websiteId=" + websiteId + "&ref=";
    if (!referrer) {
        referrer = "None";
    }
    CreateIframe(referrer, source);
    var DNDCookie = readCookie(WG_DND);
    var IgnCook = readCookie(WG_IGN);
    if (statusErased && DNDCookie==null) {
        setTimeout("StartChatProcess()", 1000);
    }
    else if (IgnCook == null) {
      
	  //Call Get User on Minimum Chats Service
        getUsernameServiceURL = _chatURL+"GetUserOnMinimumChatsByLanguage?parDomain=";
        getUsernameServiceURL += host;
        var dt = new Date();
        getUsernameServiceURL += "&strRandom=";
        getUsernameServiceURL += dt.getTime().toString();
        getUsernameServiceURL += "&method=onGetUserOnMinimumChatsResponse";
        jsonpCreator(getUsernameServiceURL);
    }
}

//Create Iframe to load dynamic page
function CreateIframe(ref, src) {
    src += escape(ref);
    src += "&url=" + escape(document.URL.toString());
    ifrm = document.createElement("IFRAME");
    ifrm.setAttribute("src", src);
    ifrm.style.border = "none";
    ifrm.style.width = 0 + "px";
    ifrm.style.height = 0 + "px";
    document.body.appendChild(ifrm);
}

//To return the website Id against the domain name provided. If zero then it means that the domain is not registered.
function onGetWebsiteIDResponse(result) {
    if (result != null) {
        websiteId = result;
        if (result != 0) {
            var setId = SetGUID();
        }
    }
}

function onGetWebsiteIDResponseOnly(result) {
    if (result != null) {
        websiteId = result;
        source = _trackURL+"?MySession=" + SessionCookie + "&websiteId=" + websiteId + "&ref=";
        CreateIframe(referrer, source);

        var index = SessionCookie.search("Session=") + 8;

        GUID = SessionCookie.substring(index, index + 32);
        var DNDCookie = readCookie(WG_DND);
        var IgnCook = readCookie(WG_IGN);
        
        if (statusErased && DNDCookie==null) {
            setTimeout("StartChatProcess()", 1000);
        }
        else if (IgnCook == null) {
            //Call Get User on Minimum Chats Service
            getUsernameServiceURL = _chatURL+"GetUserOnMinimumChatsByLanguage?parDomain=";
            getUsernameServiceURL += host;
            var dt = new Date();
            getUsernameServiceURL += "&strRandom=";
            getUsernameServiceURL += dt.getTime().toString();
            getUsernameServiceURL += "&method=onGetUserOnMinimumChatsResponse";
            jsonpCreator(getUsernameServiceURL);
        }
    }
}

//The Method Called on Page Load
function makeFrame() {
    var refDomain = "";
    SessionCookie = readCookie(WG_VIC);
    //To check whether the referrer exists or not.
    if (document.referrer && document.referrer != "") {
        referrer = document.referrer.toString();
    }
    if (referrer) {
        refDomain = GetDomainName(referrer);
		//alert(refDomain);
		//alert(referrer);
    }
    //to see if the referred age and the current page have the same domain. If same then it means
    //that the visitor is a current visitor if different then it means that the visitor has visited
    //from another website.
	//alert(readCookie(WG_CEC));
    if (refDomain != location.hostname || refDomain == "" || readCookie(WG_CEC)==null) {
        //alert("location.hostname");
		//eraseCookie(WG_CEC);
		createCookie(WG_CEC,null,-24);
        statusErased = true;
    }

    ChatStatusCookie = readCookie(WG_CEC);

    if (ChatStatusCookie!=null) {
        var index2 = ChatStatusCookie.search("EndStatus=") + 10;
        endStatus = ChatStatusCookie.substring(index2, index2 + 1);
    }
    
    if (SessionCookie != null) {
        //alert("is not new visitor");
        var websiteIdURL = _chatURL+"GetWebsiteID?parDomain=";
        websiteIdURL += escape(host);
        var dt = new Date();
        websiteIdURL += "&strRandom=";
        websiteIdURL += dt.getTime().toString();
        websiteIdURL += "&method=onGetWebsiteIDResponseOnly";
        jsonpCreator(websiteIdURL);
    }
    else {
        //If the visitor has just arrived on the website.
        //Check whether domain of the visitor is registered in the database or not.
        //alert("is new visitor");
        var websiteIdURL = _chatURL+"GetWebsiteID?parDomain=";
        websiteIdURL += escape(host);
        var dt = new Date();
        websiteIdURL += "&strRandom=";
        websiteIdURL += dt.getTime().toString();
        websiteIdURL += "&method=onGetWebsiteIDResponse";
        jsonpCreator(websiteIdURL);
    }
}

function WG_OnOfflineClick(){
	window.open(_offlineURL+"?websiteId="+websiteId+"&MySession="+"Session=" + GUID,"_blank", "menubar=0,resizable=0,width=630,height=450,scrollbars=0");
}

function onGetUserOnMinimumChatsResponse(result) {
    if (result != null) {
        if (result != "") {
            if (document.getElementById("live_chat_img") == null) {
                    var anchorTag = document.createElement("a");
                    anchorTag.setAttribute("href", "#");
					anchorTag.style.border="none";
                    var footDiv = document.getElementById(live_chat_status);
                    var imgTag = document.createElement("img");
					imgTag.style.border="none";
                    imgTag.setAttribute("id", "live_chat_img");
                    imgTag.setAttribute("onClick", "StarChatOnClick()");
                    imgTag.setAttribute("src", _imageURL + WG_onlineImg);
                    anchorTag.appendChild(imgTag);
                    footDiv.appendChild(anchorTag);
                }
                else {
                    var imgTag = document.getElementById("live_chat_img");
					imgTag.style.border="none";
                    imgTag.setAttribute("onClick", "StarChatOnClick()");
                    imgTag.setAttribute("src", _imageURL + WG_onlineImg);
                }
        }
        else {
             if (document.getElementById("live_chat_img") == null) {
                    var anchorTag = document.createElement("a");
                    anchorTag.setAttribute("href", "#");
					anchorTag.style.border="none";
                    var footDiv = document.getElementById(live_chat_status);
                    var imgTag = document.createElement("img");
					imgTag.style.border="none";
                    imgTag.setAttribute("id", "live_chat_img");
                    imgTag.setAttribute("onClick", "WG_OnOfflineClick()");
                    imgTag.setAttribute("src", _imageURL + WG_offlineImg);
                    anchorTag.appendChild(imgTag);
                    footDiv.appendChild(anchorTag);
                }
                else {
                    var imgTag = document.getElementById("live_chat_img");
					imgTag.style.border="none";
                    imgTag.setAttribute("onClick", "WG_OnOfflineClick()");
                    imgTag.setAttribute("src", _imageURL + WG_offlineImg);
                }
        }
        }
    }
