﻿// Based on querystring.js by Adam Vandenberg http://adamv.com/dev/javascript/qslicense.txt

// optionally pass a this.cookiesString to parse
// adapted specifically for GA cookies to extract specific values from them
function gaVKIcookies(intGoogDomainHash, strCookies) {
    this.params = {};
    this.cookiesString = strCookies;

    if (this.cookiesString == null) this.cookiesString = document.cookie;
    if (this.cookiesString.length == 0) return;

    // extract only those cookies for this domain
    // pattern to find only the __utm cookies with the appropriate domain hash
    var rePattern = new RegExp('(__utm[a-z]{1,2}=' + intGoogDomainHash + '[^;]*)', "g");
    // recreate cookiestring by creating an array of selected cookies and joining with ; delimiter
    var aryMatches = this.cookiesString.match(rePattern, "$1");
    if (aryMatches)
        this.cookiesString = aryMatches.join(';');
    else {
        this.cookiesString = '';
        return;
    }

    // change components of  __utmz to independant name=value pairs
    this.cookiesString = this.cookiesString.replace(/(\.|\|)utm/g, ';utm');

    // parse out name/value pairs separated via ;
    var args = this.cookiesString.split(';');

    // split out each name=value pair
    for (var i = 0; i < args.length; i++) {

        var pair = args[i].match(/([^=]*)=(.*)/);  // Don't use: pair = args[i].split('=') since value could contain a 2nd =
        // Thanks Danny Ng of www.firstrate.com.au
        var name = decodeURIComponent(pair[1]);
        name = name.replace(/^\s+|\s+$/g, '')
        var value = (pair.length >= 2)
			? decodeURIComponent(pair[2])
			: '';

        // in case page has access to > 1 domain that has __utm* cookies, we need to ensure we look only at the
        // cookies for the tracked (sub-)domain. 
        // Since JS has no access to read a cookie's domain, we need to matching on the required Google Domain Hash.  
        // All __utm* cookies begin with the domain hash = position 0
        this.params[name] = value;
        var subValues = value.split('.');

        switch (name) {
            case '__utma': //domainhash.anonymizedVisitorID.ftime.ltime.stime.sessioncount
                this.params['domainhash'] = subValues[0];
                this.params['visitorId'] = subValues[1];
                this.params['ftime'] = subValues[2];
                this.params['ltime'] = subValues[3];
                this.params['stime'] = subValues[4];
                this.params['sessioncount'] = subValues[5];
                break;
            case '__utmb': // eg .45.10.1218592192
                this.params['gif_hits'] = subValues[1];
                break;
            case '__utmv':
                this.params['custom'] = subValues[1];
                break;
            case '__utmz': //nsession.nresponses
                this.params['nsession'] = subValues[2];
                this.params['nresponses'] = subValues[3];
                break;
            case 'utmcsr':
                this.params['trafficsource'] = subValues[0];
                break;
            case 'utmccn':
                this.params['campaignname'] = subValues[0];
                break;
            case 'utmcmd':
                this.params['campaignmedium'] = subValues[0];
                break;
            case 'utmctr':
                this.params['campaignterm'] = subValues[0];
                break;
            case 'utmcct':
                this.params['campaigncontent'] = subValues[0];
                break;
            case 'utmcid':
                this.params['campaignid'] = subValues[0];
        }
    }
}

gaVKIcookies.prototype.get = function(key, default_) {
    var value = this.params[key];
    return (value != null) ? value : default_;
}


gaVKIcookies.prototype.contains = function(key) {
    var value = this.params[key];
    return (value != null);
}

gaVKIcookies.prototype.formatDateTime = function(strSession) {
    var value = this.params[strSession]
    var d = new Date(value * 1000);

    strDate = d.toLocaleDateString();
    strDate = strDate.replace(/[a-z]{3}.*[, ]+([a-z]{3})[^, ]*/i, '$1');
    strDate += ' ' + d.toLocaleTimeString();

    return strDate;
}

gaVKIcookies.prototype.dumpDebug = function() {

    var strDump = '';

    if (document.location.search.indexOf('debug=y') !== -1 && document.cookie) {
        var aryCookies = document.cookie.split(';');
        aryCookies.sort();
        strDump = ('<br /><hr /><b>document.cookie:</b><br />' + unescape(aryCookies.join('<br />')));
        strDump += ('<br /><br /><b>gaVKIcookies string. Relevant Domain Hash only:</b><br />' + unescape(this.cookiesString.replace(/;/g, ';<br />')) + '<hr />');
    }
    return strDump;
}

//-----------------------------------
deleteCookie = function(strCookieName, strDomainName, strPath) {
    var strCookie = strCookieName + '=' +
		  ';expires=1;path=' + strPath +
		  ';domain=' + strDomainName;
    document.cookie = strCookie;
}


function gaTracker(domainCode, clientIp) {

    this.__GetXML = function() {

        var Result = "<VisitorClientSession>";
        Result += "<domainName>" + this.domainName + "</domainName>";
        Result += "<visitorId>" + this.visitorId + "</visitorId>";
        Result += "<visitId>" + this.visitId + "</visitId>";
        Result += "<pageUrl>" + this.pageUrl + "</pageUrl>";
        Result += "<referrer>" + this.referrer + "</referrer>";
        Result += "<Campaign>" + this.campaignname + "</Campaign>";
        Result += "<Medium>" + this.campaignmedium + "</Medium>";
        Result += "<Source>" + this.trafficsource + "</Source>";
        Result += "<Content>" + this.campaigncontent + "</Content>";
        Result += "<Term>" + this.campaignterm + "</Term>";
        Result += "<appliedSource>" + this.appliedSourceCode + "</appliedSource>";
        Result += "<clientIpAddress>" + this.clientIp + "</clientIpAddress>";
        Result += "</VisitorClientSession>";
        return Result;
    }

    this.__GetURL = function() {

    var Result = new String("/?d={domainName}&v={visitorId}&vs={visitId}&p={pageUrl}&r={referrer}&c={campaign}&m={medium}&s={source}&cn={content}&t={term}&as={appliedSource}&ip={clientIp}&cpid={campaignId}&tc={timeStamp}");
        Result = Result.replace("\{domainName\}", escape(this.domainName));
        Result = Result.replace("\{visitorId\}", escape(this.visitorId));
        Result = Result.replace("\{visitId\}", escape(this.visitId));
        Result = Result.replace("\{pageUrl\}", escape(this.pageUrl));
        Result = Result.replace("\{referrer\}", escape(this.referrer));
        Result = Result.replace("\{campaign\}", escape(this.campaignname));
        Result = Result.replace("\{medium\}", escape(this.campaignmedium));
        Result = Result.replace("\{source\}", escape(this.trafficsource));
        Result = Result.replace("\{content\}", escape(this.campaigncontent));
        Result = Result.replace("\{term\}", escape(this.campaignterm));
        Result = Result.replace("\{appliedSource\}", escape(this.appliedSourceCode));
        Result = Result.replace("\{clientIp\}", escape(this.clientIp));
        Result = Result.replace("\{campaignId\}", escape(this.campaignid));
        Result = Result.replace("\{timeStamp\}", escape(new Date().getTime()));

        //        Result = Result.replace("\{domainName\}", escape(this.domainName));
        //        Result = Result.replace("\{domainName\}", escape(this.domainName));
        //        //Result += "<domainName>" + +"</domainName>";
        //        Result += "<visitorId>" + escape(this.visitorId) + "</visitorId>";
        //        Result += "<visitId>" + escape(this.visitId) + "</visitId>";
        //        Result += "<pageUrl>" + escape(this.pageUrl) + "</pageUrl>";
        //        Result += "<referrer>" + escape(this.referrer) + "</referrer>";
        //        Result += "<Campaign>" + escape(this.campaignname) + "</Campaign>";
        //        Result += "<Medium>" + escape(this.campaignmedium) + "</Medium>";
        //        Result += "<Source>" + escape(this.trafficsource) + "</Source>";
        //        Result += "<Content>" + escape(this.campaigncontent) + "</Content>";
        //        Result += "<Term>" + escape(this.campaignterm) + "</Term>";
        //        Result += "<appliedSource>" + escape(this.appliedSourceCode) + "</appliedSource>";
        //        Result += "<clientIpAddress>" + escape(this.clientIp) + "</clientIpAddress>";
        //        Result += "</VisitorClientSession>";
        //        return Result;
        return Result;
    }

        this._trackPageview = function() {
        var url
        url = "/ServicesV3/TWD/REST/Tracking.svc/RecordPageView" + this.__GetURL();
        $.ajax({
            type: "GET",
            url: url,
            processData: true,
            contentType: "application/xml",
            dataType: "xml"
        });


    }


    this._trackProductView = function(tourCode, tourYear, infoPartId) {
        var url
        url = "/ServicesV3/TWD/REST/Tracking.svc/RecordProductView" + this.__GetURL();
        url += "&tourCode=" + escape(tourCode) + "&tourYear=" + escape(tourYear);
        if (infoPartId == null) {
            infoPartId = 10;
        }
        url += "&infoPartId=" + escape(infoPartId);

        $.ajax({
            type: "GET",
            url: url,
            processData: true,
            contentType: "application/xml",
            dataType: "xml"
        });
    }

    this._trackConversionByEmail = function(conversionSource, firstName, lastName, emailAddress) {
        var url
        url = "/ServicesV3/TWD/REST/Tracking.svc/RecordEmailConversion" + this.__GetURL();
        url += "&fn=" + escape(firstName) + "&ln=" + escape(lastName);
        url += "&em=" + escape(emailAddress) + "&src=" + escape(conversionSource);

        $.ajax({
            type: "GET",
            url: url,
            processData: true,
            contentType: "application/xml",
            dataType: "xml"
        });
    }

    this.__GetSessionObj = function() {

        var Result = new Object();
        Result.domainName = this.domainName;
        Result.visitorId = this.visitorId;
        Result.visitId = this.visitId;
        Result.pageUrl = this.pageUrl;
        Result.referrer = this.referrer;
        Result.Campaign = this.campaignname;
        Result.Medium = this.campaignmedium;
        Result.Source = this.trafficsource;
        Result.Content = this.campaigncontent;
        Result.Term = this.campaignterm;
        Result.appliedSource = this.appliedSourceCode;
        Result.clientIpAddress = this.clientIp;
        return Result;

    }



    this.alertProperties = function() {
        alert(this.doaminCode);
        alert(this.clientIp);
        alert(this.domainName);
        alert(this.pageUrl);
        alert(this.referrer);
        alert(this.appliedSourceCode);
        alert(this.visitorId);
        alert(this.visitId);
        alert(this.trafficsource);
        alert(this.campaignname);
        alert(this.campaignmedium);
        alert(this.campaignterm);
        alert(this.campaignid);
        alert(this.campaigncontent);
    }

    this.getCookie = function(check_name) {

        // with this test document.cookie.indexOf( 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_all_cookies[i].replace(/^\s+|\s+$/g, ''));
                    cookie_name = cookie_name + "=";
                    cookie_value = cookie_value.replace(cookie_name, "");
                    //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;
        }

    }

    this.setCookie = function(name, value, expires, path, domain, secure) {


        // set time, it's in milliseconds
        var today = new Date();
        today.setTime(today.getTime());

        /*
        if the expires variable is set, make the correct
        expires time, the current script below will set
        it for x number of days, to make it for hours,
        delete * 24, for minutes, delete * 60 * 24
        */
        if (expires) {
            expires = expires * 1000 * 60 * 60 * 24;
        }
        var expires_date = new Date(today.getTime() + (expires));

        document.cookie = name + "=" + escape(value) +
            ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
            ((path) ? ";path=" + path : "") +
            ((domain) ? ";domain=" + domain : "") +
            ((secure) ? ";secure" : "");
    }

    this.init = function(domainCode, clientIp) {
        try {

            this.doaminCode = domainCode;
            this.clientIp = clientIp;
            this.domainName = document.location.hostname;
            this.pageTracker = _gat._getTracker(this.doaminCode);
            this.googleDomainHash = _gat.t(this.domainName);
            this.pageUrl = location.href;
            this.referrer = document.referrer;
            this.appliedSourceCode = this.getCookie("IDENTIFIER");

            var curVal = "";

            this.trafficsource = curVal;
            this.campaignname = curVal;
            this.campaignmedium = curVal;
            this.campaignterm = curVal;
            this.campaigncontent = curVal;
            this.campaignid = curVal;

            var utma = this.getCookie("__utma");

            var parts = utma.split(".");
            this.visitorId = parts[1];
            this.visitId = parts[1] + "." + parts[4];

            var utmz = this.getCookie("__utmz");
            if (utmz != null) {
                try {
                    parts = utmz.split(".");
                    var infoAryStr = parts[4];

                    var infoAry = infoAryStr.split("|");
                    var name;

                    for (i = 0; i < infoAry.length; i++) {
                        name = infoAry[i].split("=")[0];
                        curVal = infoAry[i].split("=")[1];

                        switch (name) {
                            case 'utmcsr':
                                this.trafficsource = curVal;
                                break;
                            case 'utmccn':
                                this.campaignname = curVal;
                                break;
                            case 'utmcmd':
                                this.campaignmedium = curVal;
                                break;
                            case 'utmctr':
                                this.campaignterm = curVal;
                                break;
                            case 'utmcct':
                                this.campaigncontent = curVal;
                                break;
                            case 'utmcid':
                                this.campaignid = curVal;
                        }

                    }
                } catch (err) { }
            }

        } catch (err) { }
    }


    this.init(domainCode, clientIp);


}

/*
Copyright (c) 2008, Adam Vandenberg
All rights reserved.

Redistribution and use in source and binary forms, with or without 
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, 
this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright 
notice, this list of conditions and the following disclaimer in the 
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

