/*
*   Tracking functions
*/

//The main method called on load

var trackerLoc = '/';


var http = null;
var id;

var variation;

var phone = '1.800.292.4439';

var cookieID = 'IBeeSessionTracker';

/*
*
*   This is the  first tracker method called by all pages within the site.
*   Its main purpose is to obtain the visit id (either retreiving it from a cookie or by fetching a new one) and store it in the id variable.
*   It is also responsible for setting up the http variable that is used in our AJAX calls
*/

function loadTracker(affiliate, pagename, pageVersion, site) {
    try {
        //create variable to facilitate AJAX calls
        http = getHTTPObject();

        //attempt to fetch the visit id from the cookie
        id = readCookie(cookieID);

        //if no cookie, get new visit id and store in cookie
        if (id == null) {
            id = recordVisitor(affiliate);

            createCookie(cookieID, id);
            checkID = readCookie(cookieID);
            if (id != checkID) {
                createCookie(cookieID, id); // read it back and check it matches
            }
            createCookie('IBeeAffiliate', affiliate);

            var overridev = queryString('var');
            if (overridev != null) {
                variation = overridev;
            }
            else {
                if (id % 10 == 0) {
                    variation = 'A';
                }
                else {
                    variation = 'B';
                }
            }

            //recordVariation(id, variation);
        }
        else {
            var overridev = queryString('var');
            if (overridev != null) {
                variation = overridev;
                //recordVariation(id, variation);
            }
            else {
                variation = 'A';
                //variation = getVariation(id);
            }
        }

        permId = readCookie(cookieID + 'Perm');
        if (permId == null) {
            createPermCookie(cookieID + 'Perm', id, 30);    // save in a permanent cookie as well
        }

        if (isNaN(parseInt(id))) {
            deleteCookie(cookieID);
            return;
        }

        //records this page hit
        recordPageVisit(id, pagename, pageVersion, site);
        // if we landed on not found, then save the referrer
        if ((pagename == 'Not Found' || pagename == 'notFound') && document.referrer) {
            fileForm('referrer', document.referrer);
        }

        var campaignId = queryString('cam');
        var groupId = queryString('adg');
        var sourceId = queryString('Source');
        if (sourceId == null)
            sourceId = '';

        // Determine the phone number based on the url parameters        
        if (groupId != null && campaignId != null) {
            phone = getNo(campaignId, groupId, sourceId);
        }
        else if (groupId != null) {
            phone = getNo(0, groupId, sourceId);
        }
        else if (campaignId != null) {
            phone = getNo(campaignId, '', sourceId);
        }
        else {
            phone = getNo('', '', sourceId);
        }


        var phoneArray = $('[span|div].ecommsphone');
        phoneArray.each(function (el) {
            el.set('html', phone);
        }
        );


        var phoneOccurences = document.getElementById('phoneOccurences');
        if (phoneOccurences != null) {
            phoneOccurences = phoneOccurences.value;

            for (i = 1; i <= phoneOccurences; i++) {
                var phoneOccId = 'phoneHolder' + i;
                var phoneLocation = document.getElementById(phoneOccId);
                phoneLocation.innerHTML = phone;
            }
        }
        else {
            var phoneLocations = document.getElementsByName('phoneHolder');
            for (i = 0; i < phoneLocations.length; i++) {
                phoneLocations[i].innerHTML = phone;
            }
        }

    } catch (err) {
        variation = 'B';
        alert(err);
    }

}

/*
*   This method is called from within onLoad.
*   Its purpose is to attach the formSub method to the onSubmit of the form (if there is one)
*
*/
function attachSubmission() {
    //attach the formSub method to the onSubmit of the form (if there is one)
    if (document.forms[0]) {
        document.forms[0].onsubmit = function () { formSub(); }
    }

    //check whether the the quote process has assigned this visitor its own visitorId. (this is to link visitors to another system)

    var visitorId = 0;
    var quoteId = 0;
    if (document.getElementById('pms_visitorid') != null) {
        visitorId = document.getElementById('pms_visitorid').value;
    }
    if (document.getElementById('quoteid') != null) {
        quoteId = document.getElementById('quoteid').value;
    }
    if (visitorId > 0) {
        recordVisitorId(id, visitorId, quoteId);
    }
}



/*
*   This method is called when any html form on the site is submitted.
*   All data from text and hidden input fields are extracted and filed
*/
function formSub() {

    //for each element on the submitted form
    for (var i = 0; i < document.forms[0].elements.length; i++) {
        var element = document.forms[0].elements[i];

        var key = element.id;
        var value = element.value;

        //check field type       
        switch (element.type) {
            case 'text':
            case 'hidden':
                //if text or hidden field, file it
                fileForm(key, value);
                break;
            case 'button':
                break;
        }

    }

    //check for matches to previous visitors
    //matchMaker();
}


/*
*   This method kicks off a server side function that compares answers submitted by the current visitor id to those of previous visitors
*   in attempt to link them to a previous visit
*/
function matchMaker() {
    http.open("GET", trackerLoc + "Tracking.aspx?method=matchMaker&param1=" + id, false);

    http.send(null);


}

/*
*   This method is called by formSub to facilitate the saving of form values to the database
*/
function fileForm(key, value) {

    if (http != null) {
        http.open("GET", trackerLoc + "Tracking.aspx?method=recordFormEntry&param1=" + id + "&param2=" + key + "&param3=" + value, false);
        http.send(null);
    }
}




function createCookie(name, value) {

    document.cookie = name + "=" + value + "; path=/";
}

function createPermCookie(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=/";
}

function deleteCookie(name) {

    var d = new Date();
    document.cookie = name + "='';expires=" + d.toGMTString();
}


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);
    }
    return null;
}

//this method creates the http variable differently depending on the browser
function getHTTPObject() {

    var xhr = false; //set to false, so if it fails, do nothing	

    if (window.XMLHttpRequest) {//detect to see if browser allows this method		
        var xhr = new XMLHttpRequest(); //set var the new request	
    } else if (window.ActiveXObject) {//detect to see if browser allows this method		
        try {
            var xhr = new ActiveXObject("Msxml2.XMLHTTP"); //try this method first		
        } catch (e) {//if it fails move onto the next			
            try {
                var xhr = new ActiveXObject("Microsoft.XMLHTTP"); //try this method next			
            } catch (e) {//if that also fails return false.				
                xhr = false;
            }
        }
    }
    return xhr; //return the value of xhr
}



/*
*   Records a visitor in the database and returns a new visit id
*/
function recordVisitor(affiliate) {
    var res = 'unknown';
    var visitor;

    if (screen) {
        res = screen.width + 'x' + screen.height;
    }

    try {
        var url = trackerLoc + "Tracking.aspx?method=recordVisitor&param1=" + affiliate + "&param2=" + res + "&param3=" + document.referrer;
        http.open("GET", trackerLoc + "Tracking.aspx?method=recordVisitor&param1=" + affiliate + "&param2=" + res + "&param3=" + document.referrer, false);
        http.send(null);

        var results = http.responseText;
        visitor = results;
    }
    catch (e) { console.log(e.toString()); }

    return visitor;
}

/*
*   This method records a page visit in the databse  
*/
function recordPageVisit(visit, page, pageVersion, site) {
    //alert('recordPageVisit');

    try {
        var d = new Date();
        http.open("GET", trackerLoc + "Tracking.aspx?method=recordPageVisit&param1=" + visit + "&param2=" + page + "&param3=" + site + "&param4=" + pageVersion + "&param5=" + variation + "&ms=" + d.getMilliseconds(), false);
        http.send(null);
    }
    catch (e) { console.log(e.toString()); }
}


/*
*   This method can be confusing. The site is linked with our quote engine which generates visitorIds of its own.
*   This method links quote visitorIds with a tracking visitId.
*/
function recordVisitorId(visitId, visitorId, quoteId) {
    //alert('recordVisitorId');

    try {
        var d = new Date();
        http.open("GET", trackerLoc + "Tracking.aspx?method=recordVisitorId&param1=" + visitId + "&param4=" + visitorId + "&param6=" + quoteId + "&ms=" + d.getMilliseconds(), false);
        http.send(null);
    }
    catch (e) { console.log(e.toString()); }
}


function recordVariation(visitId, variation) {
    //alert('recordVisitorId');
    try {
        var d = new Date();
        http.open("GET", trackerLoc + "Tracking.aspx?method=recordVariation&param1=" + visitId + "&param2=" + variation + "&ms=" + d.getMilliseconds(), false);
        http.send(null);
    }
    catch (e) { console.log(e.toString()); }
}

function getVariation(visitId) {
    var v;

    var d = new Date();
    try {
        http.open("GET", trackerLoc + "Tracking.aspx?method=getVariation&param1=" + id + "&ms=" + d.getMilliseconds(), false);
        http.send(null);
        v = http.responseText;
    }
    catch (e) { console.log(e.toString()); }

    return v;
}

function getNo(campaign, group, source) {
    var v;
    var d = new Date();

    try {
        http.open("GET", trackerLoc + "Tracking.aspx?method=getPhoneNoExt&param2=" + campaign + "&param3=" + group + "&param5=" + source + "&param6=" + id + "&ms=" + d.getMilliseconds(), false);
        //http.open("GET", trackerLoc+"Tracking.aspx?method=getPhoneNo&param1="+campaign+"&param4="+group+"&param6="+id+"&ms="+d.getMilliseconds(), false);
        http.send(null);
        v = http.responseText;
    } catch (e) { console.log(e.toString()); }

    return v;
}


function queryString(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i = 0; i < gy.length; i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
}

function getVisitId() {
    return id;
}

function getPhoneNo() {

    return phone;
}


