﻿if (!window.MS) { window.MS = {}; }
if (!MS.Support) { MS.Support = {}; }
if (!MS.Support.MSS) { MS.Support.MSS = {}; }

MS.Support.MSS.Utils =
{
    AddEvent: function(el, strEvent, funcPtr) {
        if (window.addEventListener) {
            el.addEventListener(strEvent, funcPtr, false);
        }
        else if (window.attachEvent) {
            el.attachEvent('on' + strEvent, funcPtr);
        }
    },

    RemoveEvent: function(el, strEvent, funcPtr) {
        if (window.removeEventListener) {
            el.removeEventListener(strEvent, funcPtr, false);
        }
        else if (window.detachEvent) {
            el.detachEvent('on' + strEvent, funcPtr);
        }
    },

    SrcEl: function(e) {
        if (e.srcElement) {
            return e.srcElement;
        }

        if (e.target) {
            return e.target;
        }

        return e;
    },

    setCookie: function(key, val, subkey, persist) {
        if (!key) return;

        var cv, cs = '';

        if (persist) {
            var d = new Date();
            cs += '; expires=' + d.toGMTString(d.setFullYear(d.getFullYear() + 1));
        }

        var ld = document.domain;
        if ((typeof (gCookieDomain) != 'undefined') && (gCookieDomain != null) && (gCookieDomain != '')) { ld = gCookieDomain; }
        if (ld.indexOf(".com") > -1) cs += '; Domain=' + ld;

        cv = this.getCookie(key);

        if (cv && subkey) {
            var cn, subkeyfound = false;
            if (cv.indexOf('=') > -1) {
                var ca = cv.split('&');
                for (var i = 0; i < ca.length; i++) {
                    cn = ca[i].substring(0, ca[i].indexOf('='));
                    if (cn.charAt(0) == ' ') cn = cn.substring(1, cn.length);
                    if (subkey === cn) {
                        ca[i] = subkey + '=' + val;
                        cv = ca.join('&');
                        subkeyfound = true;
                        break;
                    }
                }

                if (!subkeyfound) {
                    if (ca.length > 0) cv += '&';
                    cv += subkey + '=' + val;
                }
            } else cv = subkey + '=' + val;
        }
        else if (!cv && subkey) cv = subkey + '=' + val;
        else if (!subkey) cv = val;
        else return;

        document.cookie = key + '=' + cv + cs + '; path=/';
    },

    getCookie: function(key, subkey) {
        if (!key) return;

        var cn, cv, ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            cn = ca[i].substring(0, ca[i].indexOf('='));
            if (cn.charAt(0) == ' ') cn = cn.substring(1, cn.length);
            if (key === cn) {
                cv = ca[i].substring(ca[i].indexOf('=') + 1, ca[i].length);
                break;
            }
        }

        if (!cv) return '';
        if (!subkey) return cv;

        ca = cv.split('&');
        for (var i = 0; i < ca.length; i++) {
            cn = ca[i].substring(0, ca[i].indexOf('='));
            if (cn.charAt(0) == ' ') cn = cn.substring(1, cn.length);
            if (subkey === cn) return ca[i].substring(ca[i].indexOf('=') + 1, ca[i].length);
        }
    }
};
var initialized = initialized ? initialized : false;
/***************************************************
Content Logging
Datacollection Object
***************************************************/
MS.Support.MSS.Logging = function() {
    var mssUtils = MS.Support.MSS.Utils;
    var imgLoaded = false;

    encodeURL = function(strInput) {
        if (typeof (strInput) == 'undefined') { return ""; }
        strInput = strInput.toString();
        var c;
        var EncodeUrl = '';
        for (var cnt = 0; cnt < strInput.length; cnt++) {
            c = strInput.charCodeAt(cnt);
            if (((c > 96) && (c < 123)) || ((c > 64) && (c < 91)) || ((c > 47) && (c < 58)) || (c == 46) || (c == 45) || (c == 95)) { EncodeUrl = EncodeUrl + String.fromCharCode(c); }
            else if (c > 127) { EncodeUrl = EncodeUrl + '%u' + encodeTwoByteHex(c); }
            else { EncodeUrl = EncodeUrl + '%' + encodeSingleByteHex(c); }
        }
        return EncodeUrl;
    };

    encodeSingleByteHex = function(charC) {
        var SingleByteHex = charC.toString(16);
        for (var cnt = SingleByteHex.length; cnt < 2; cnt++) { SingleByteHex = "0" + SingleByteHex; }
        return SingleByteHex;
    };
    encodeTwoByteHex = function(charC) {
        var TwoByteHex = charC.toString(16);
        for (var cnt = TwoByteHex.length; cnt < 4; cnt++) { TwoByteHex = "0" + TwoByteHex; }
        return TwoByteHex;
    };

    getCookieIncrement = function() {
        var cookieKey = 'sdninc';
        var inc = mssUtils.getCookie(cookieKey);
        if (inc == '') { inc = '0'; }
        inc = parseInt(inc);
        inc += 1;
        document.cookie = cookieKey + '=' + inc + '; path=/;';
        return inc;
    };
    //Check if the n'th bit is set in the binary equivalent of the number
    isLogBitSet = function(number, flagbit) {

        if (number == 0 || flagbit == 0) return false;

        var binary = number.toString(2);

        if (binary.length > flagbit) {
            if (binary.charAt(binary.length - flagbit - 1) == "1") return true;
        }
        return false;
    };

    setLogCollectionBit = function(collection, bit) {
        if (!isLogBitSet(collection, bit)) {
            collection += Math.pow(2, bit);
        }
        return collection;
    };
    logPageOnLoad = function() {
        var elem = document.createElement("img");
        elem.id = 'dataCollectionImg';
        elem.name = 'dataCollectionImg';

        document.body.insertBefore(elem);

        var dataCollImg = document.getElementById(DataCollectionObj.options.dataCollectionImg);
        if (!dataCollImg) {
            return;
        }
        DataCollectionObj.options.eventSeqNo = getCookieIncrement();
        var currentOpts = DataCollectionObj.options;
         var ltsUrl = window.location.protocol + '//' + currentOpts.host + '?';
        ltsUrl += 'SSID=29' + '&' +
				'EventCollectionID=' + currentOpts.eventCollectionId + '&' +
				'URL=' + encodeURL(currentOpts.url) + '&' +
				'SiteCulture=' + encodeURL(currentOpts.siteLn) + '&' +
				'RefURL=' + encodeURL(currentOpts.refUrl) + '&' +
				'EventSeqNo=' + encodeURL(currentOpts.eventSeqNo) + '&' +
				'SSversion=' + encodeURL(currentOpts.SsVersion)

        mssUtils.AddEvent(dataCollImg, "load", function() { imgLoaded = true; });
        dataCollImg.src = ltsUrl;

    };

    logPageOnUnLoad = function() {

        var dataCollImg = document.getElementById(DataCollectionObj.options.dataCollectionImg);

        if (!dataCollImg) return;

        if (!imgLoaded)
            return;

        DataCollectionObj.options.dwellTime = new Date().getTime() - DataCollectionObj.options.startDate.getTime();

        if (DataCollectionObj.options.scrollUsed) { DataCollectionObj.options.eventCollectionId = setLogCollectionBit(DataCollectionObj.options.eventCollectionId, 27); }

        if (DataCollectionObj.options.eventSeqNo == '0') options.eventSeqNo = getCookieIncrement();

        var currentOpts = DataCollectionObj.options;

        var ltsUrl = window.location.protocol + '//' + currentOpts.host + '?';
         ltsUrl +=
	    'SSID=29' + '&' +
	    'EventCollectionID=' + currentOpts.eventCollectionId + '&' +
	    'SiteCulture=' + encodeURL(currentOpts.siteLn) + '&' +
	    'SSversion=' + encodeURL(currentOpts.SsVersion) + '&' +
	    'DwellTime=' + encodeURL(currentOpts.dwellTime) + '&' +
	    'TargetURL=' + encodeURL(currentOpts.targetUrl) + '&' +
        'EventSeqNo=' + encodeURL(currentOpts.eventSeqNo) + '&' +
	    'unload=true';

        dataCollImg.src = ltsUrl;

        var today = new Date();
        var now = today.getTime();
        while (1) {
            var today2 = new Date();
            var now2 = today2.getTime();
            if ((now2 - now) > currentOpts.onUnloadTimeout)
                return;
        }
    };

    setExitLinks = function(e) {
        var El = mssUtils.SrcEl(e);
        var elId = null;
        var parentId = null;
        if (!El) { return; }
        if (!El.tagName) { return; }
        if (El.tagName.toUpperCase() != 'A') {
            if (El.parentNode && El.parentNode.tagName && El.parentNode.tagName.toUpperCase() == 'A') {
                El = El.parentNode;
            }
            else {
                return;
            }
        }
        if (!El.href) { return; }
        if (El.href.indexOf('javascript:') > -1) { return; }
        if (El.href.indexOf('mailto:') > -1) { return; }
        if (El.id) {
            this.exitLinkId = El.id;
        }
        else {
            this.exitLinkId = '';
            this.exitContainerId = '';
        }
        DataCollectionObj.options.targetUrl = El.href;
    };

    scrollHandler = function() {
        DataCollectionObj.options.scrollUsed = true;
        mssUtils.RemoveEvent(window, "scroll", scrollHandler);
    };

    loggingOptions = function(logObject) {
        this.startDate = new Date();
        this.dataCollectionImg = 'dataCollectionImg';
        this.host = '/LTS/';
        this.scrollUsed = false;
        this.eventCollectionId = 1;
        this.url = document.location && document.location != '' ? document.location.toString() : '';
        this.refUrl = document.referrer && document.referrer != '' ? document.referrer.toString() : '';
        this.eventSeqNo = 0;
        this.targetUrl = '';
        this.SsVersion = '';
        this.siteLn = '';
        this.onUnloadTimeout = 150
    };

    this.options = null;
    this.Initialize = function() {

        if (initialized == true) {
            return;
        }
        initialized = true;
        this.options = new loggingOptions();

        //if (!options.dataCollectionImg) return;

        mssUtils.AddEvent(document, "click", function(e) { try { setExitLinks(e); } catch (err) { } });
        mssUtils.AddEvent(window, "load", function() { try { logPageOnLoad(); } catch (err) { } });
        mssUtils.AddEvent(window, "unload", function() { try { logPageOnUnLoad(); } catch (err) { } });
        mssUtils.AddEvent(window, "scroll", scrollHandler);

    };

};
var DataCollectionObj = DataCollectionObj ? DataCollectionObj : new MS.Support.MSS.Logging();
