/*
* Date: 	2011-06-20 						
*
* Written by:  	Ecommerce Intelligence.  www.ecomiq.com
* Modified by: 	michel.bertrand@transat.com
*
* Dependencies:	Prototype javascript framework 		-  	prototype.js
*					Google Analytics tracking script 	- 	ga.js
* 					Cossette's Super Cookie code 		-	ga-campaign-stacking.js
 
* Usage:			This file should be included towards the top of all webpages,
* 					but after prototype.js and ga.js.
*
* Purpose: 		This script does the following: 			 		 
*
*		1) Determines the correct Google Analytics account id to
*		which all page tracking data, for a particular user session will be sent.  
* 		This is determined by the website the user's session begins
* 		on. This account id and will be preserverd for the entire user
* 		session as he hops to different transat websites through the checkout process.  
*
*		2) Automatically tags links, with Google Analytics' session
*		tagging function. In order to preserve a users session as he
*		hops from one domain to another. links to different transat
*		URLs will be tagged with that users' session data and
*		account id. 
*		
*		3) Creates the Google Analytics page tracking object with the
*		proper account Id and tracks the pageview.
*/



/*	domain2Id:
*  	Mapping of domain name to Google Analytics account id.  This is used to
*  	determine which Google Analytics account id a users session should be
*  	reported to.  It chooses the account id based on which of the below
*  	websites the users session is STARTED from.  Once the account id is chosen
*  	a cookie is set, and passed via the link tagging function to all other
*  	transat websites.  If a users session begins on a website not listed
*  	below, a Catch All' account id will be used.  
*/
var domain2Id = {
    'www.transatholidays.com': 'UA-6777270-1',
    'pp.transatholidays.com': 'UA-6777270-1',
    'qa.transatholidays.com': 'UA-6777270-1',
    'www.nolitours.com': 'UA-6777258-1',
    'pp.nolitours.com': 'UA-6777258-1',
    'qa.nolitours.com': 'UA-6777258-1',
    'www.transattravel.com': 'UA-10078934-1',
    'pp.transattravel.com': 'UA-10078934-1',
    'qa.transattravel.com': 'UA-10078934-1',
    'services.airtransat.com': 'UA-6288865-1'

};


/*	tagDomains:
* 	URLs within the transat network of websites, which should be tagged. All
* 	links from any of the URLs listed below, to any other of the URLs listed below
* 	will be automatically tagged with Google Analytics' built in session
* 	tagging script.  This is to preservere the users session information as he
* 	hops from one transat website to another.  Links to all Subdomains of the
* 	below domains will also be tagged.
*/
var tagDomains = new Array(
		'transatholidays.com',
		'nolitours.com',
		'transattravel.com',
		'airtransat.com'
	);


/*	noTagDomains:
* 	Any Subdomains of the domains listed in the tagDomains array which should
* 	not be tagged, should be included as part of this array.
*/
var noTagDomains = new Array(
	);

/*	rootDomains: (MB_2011-05-30 - new functionality)
* 	These domains are the main websites, and should always get their GA account
* 	number from the domain2Id array, regardless if we land on one of its pages
*  from a multi-domain tagged-link.
*  2011-06-20: added pp and qa domains in here for testing purposes
*/
var rootDomains = new Array(
		'www.transatholidays.com',
		'pp.transatholidays.com',
		'qa.transatholidays.com',
		'www.nolitours.com',
		'pp.nolitours.com',
		'qa.nolitours.com'
	);



/*	cookieName:
* 	Name of cookie which will store the Transat account id listed in domain2Id
* 	above.
*/
var cookieName = 'transatGAId';


/*	caAccId:
* 	Catchall Account Id.  The Default Analytics account id which will be used,
* 	if a user's session begins on a website not listed in domain2Id above.
*/
var caAccId = 'UA-6381993-1';


/* ========================================================== */
/* =============== Do Not Alter Below This Line  ============ */
/* ========= (not that anyone ever listens to me... ========= */
/* ==================== (... oh well...) ==================== */
/* ========================================================== */

// Set Auto tagging to fire once the DOM is loaded.  
// This Must come AFTER page tracking, as it uses the pageTracker object.

//  Get account Id, create tracker object and track pageview.
var accId = getGAId();

//  If the account Id could not be found, default to a "catch all" account Id
if (!accId) {
    accId = caAccId;
}

var pageTracker = _gat._getTracker(accId);
pageTracker._setDomainName("none");
pageTracker._setAllowLinker(true);

// This is Cossette's Super Cookie code - make sure ga-campaign-stacking.js is called in the webpage!
var cs1 = getCampaignStacking(pageTracker._getVisitorCustomVar(1), "medium");
var cs2 = getCampaignStacking(pageTracker._getVisitorCustomVar(2), "mediumsource");
var cs3 = getCampaignStacking(pageTracker._getVisitorCustomVar(3), "mediumkeyword");
if (getNumberOfPageviews() == "0") {
    pageTracker._setCustomVar(1, "CSmedium", cs1, 1);
    pageTracker._setCustomVar(2, "CSmedsrc", cs2, 1);
    pageTracker._setCustomVar(3, "CSmedkwd", cs3, 1);
}

pageTracker._trackPageview();

// Wait for the DOM to load, then tag all appropriate links
document.observe("dom:loaded", function () {

    // Read DOM and tag all appropriate links & iframe sources.
    try {

        // Get profile_referrer domain.
        var prDomain = getCookieVal('profile_referrer');

        if (!prDomain) {
            prDomain = new String(window.location);
            prDomain = cleanURL(prDomain);
            prDomain = prDomain.replace(/^www\./, '');
        }

        // Links
        var links = $$('a');
        links.each(function (element) {
            if (needsTagging(element.href)) {
                var newHref = pageTracker._getLinkerUrl(element.href);
                newHref += '&profile_referrer=' + prDomain;
                element.setAttribute('href', newHref);
            }
        });

        // iFrames
        var iframes = $$('iframe');
        iframes.each(function (element) {
            if (needsTagging(element.src)) {
                var newSrc = pageTracker._getLinkerUrl(element.src);
                newSrc += '&profile_referrer=' + prDomain;
                element.setAttribute('src', newSrc);
            }
        });

        // Forms
        var forms = $$('form');
        forms.each(function (element) {
            if (needsTagging(element.action)) {
                var newSrc = pageTracker._getLinkerUrl(element.action);
                newSrc += '&profile_referrer=' + prDomain;
                element.setAttribute('action', newSrc);
            }
        });

        // Image Maps
        var maps = $$('area');
        maps.each(function (element) {
            if (needsTagging(element.href)) {
                var newSrc = pageTracker._getLinkerUrl(element.href);
                newSrc += '&profile_referrer=' + prDomain;
                element.setAttribute('href', newSrc);
            }
        });

    } catch (err) { }
});


/* ========================================================== */
/* ========== Begin Auto Account Id Functions =============== */
/* ========================================================== */

function getGAId() {

    // See if cookie is set
    var accountId = getCookieVal(cookieName);

    if (!accountId) {
        // Get from Query Parameter.
        var qDomain = getQueryVal('profile_referrer');
        accountId = getAccId(qDomain);
        if (accountId) {
            createCookie(cookieName, accountId);
            createCookie('profile_referrer', qDomain);
        }
    }

    if (!accountId) {
        // Get from referrer domain.
        var rDomain = getReferrerDomain();
        accountId = getAccId(rDomain);
        if (accountId) {
            createCookie(cookieName, accountId);
            createCookie('profile_referrer', rDomain);
        }
    }

    if (!accountId) {
        // Get from Current URI.
        var cDomain = getCurrentDomain();
        accountId = getAccId(cDomain);
        if (accountId) {
            createCookie(cookieName, accountId);
            createCookie('profile_referrer', cDomain);
        }
    }

    // MB_2011-06-08
    // If the referring domain is a "root" domain, we want to make sure that we send
    // stats to that root domain Google Analytics account, regardless of the referral method.
    if (typeof (rootDomains) != 'undefined') {
        var rDomain = getQueryVal('profile_referrer');
        if (!rDomain) {
            var rDomain = getReferrerDomain();
        }
        if (rootDomains.length) {
            for (var i = 0; i < rootDomains.length; i++) {
                if ((rootDomains[i].length) && (rDomain.indexOf(rootDomains[i]) >= 0)) {
                    accountId = getAccId(rootDomains[i]);
                    if (accountId) {
                        createCookie(cookieName, accountId);
                        createCookie('profile_referrer', rDomain);
                    }
                }
            }
        }
    }

    // MB_2011-05-30
    // If this page is on a "root" domain, we want to make sure that we send
    // stats to its own Google Analytics account, regardless of the referral method.
    if (typeof (rootDomains) != 'undefined') {
        var cDomain = getCurrentDomain();
        if (rootDomains.length) {
            for (var i = 0; i < rootDomains.length; i++) {
                if ((rootDomains[i].length) && (cDomain.indexOf(rootDomains[i]) >= 0)) {
                    accountId = getAccId(rootDomains[i]);
                    if (accountId) {
                        createCookie(cookieName, accountId);
                        createCookie('profile_referrer', cDomain);
                    }
                }
            }
        }
    }

    return accountId;
}

function getCurrentDomain() {
    var url = window.location.toString();
    url = cleanURL(url);
    return url;
}

function getReferrerDomain() {
    var url = document.referrer;
    url = cleanURL(url);
    return url;
}

function cleanURL(url) {
    url = url.replace(/http[s]?:\/\//, '');
    url = url.substring(0, url.indexOf('/'));
    url = url.toLowerCase();
    return url;
}

function getQueryVal(param) {
    var qString = location.search.substring(1);
    var qParams = qString.split('&');
    for (var i = 0; i < qParams.length; i++) {
        var pos = qParams[i].indexOf('=');
        if (pos > 0) {
            var key = qParams[i].substring(0, pos);
            var val = qParams[i].substring(pos + 1);
            if (key == param) {
                return val;
            }
        }
    }
    return false;
}

function getAccId(Dom) {
    if (typeof (domain2Id[Dom]) == 'undefined') {
        return false;
    } else {
        return domain2Id[Dom];
    }
}

function createCookie(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 getCookieVal(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 false;
}


/* ========================================================== */
/* ============== Begin Auto Tagging Functions ============== */
/* ========================================================== */

function needsTagging(link) {
    if (!link) { return false; }

    link = cleanURL(link);

    // First check, if it's in the list of URLs to skip.
    if (typeof (noTagDomains) != 'undefined') {
        if (noTagDomains.length) {
            for (var i = 0; i < noTagDomains.length; i++) {
                if ((noTagDomains[i].length) && (link.indexOf(noTagDomains[i]) >= 0)) {
                    return false;
                }
            }
        }
    }

    // Get Current URL and clean up.
    var thisURL = window.location.hostname.toString();

    // Don't tag links to current domain.
    if (thisURL == link) {
        return false;
    }

    for (var i = 0; i < tagDomains.length; i++) {
        // if (link.indexOf(tagDomains[i]) >= 0){
        // if ( (link == tagDomains[i])  || (link.match(regExp))){
        var regExp = new RegExp("\\." + tagDomains[i] + '$', 'i');
        if (link.match(regExp) || (link == tagDomains[i])) {
            return true;
        }
    }

    // If we got this far, link shouldn't be tagged.
    return false;
}

function cleanURL(link) {

    // Get rid of http:// and querystring in link (if exists).
    if (link.indexOf('://') > 0)
        link = link.substring(link.indexOf('://') + 3);

    if (link.indexOf('?') > 0)
        link = link.substring(0, link.indexOf('?'));

    if (link.indexOf('/') > 0)
        link = link.substring(0, link.indexOf('/'));

    return link;
}

function tagUrlGA(url) {
    if (needsTagging(url)) {
        var newURL = pageTracker._getLinkerUrl(url);
        var prDomain = getCookieVal('profile_referrer');
        if (prDomain) {
            newURL = newURL + '&profile_referrer=' + prDomain;
        }
        return newURL;
    } else {
        return url;
    }
}

