/*
 * Last Modification Date: 	2011-02-18 						
 *
 * History: 2010-10-12 - Added engine.airtransat.xx for new ACE 2011 engines
 *			2010-10-25 - Uniformed for all european properties (CAF, ACE, FR)
 *			2011-02-18 - Added Web Property ID for airtransat.pt (new Portugal site)
 *
 * Written by:  Ecomerce Intelligence.  www.ecomiq.com
 *
 * Dependancies:Prototype javascript framework -   prototype.js
 *		Google Analytics tracking script - ga.js
 *
 * Usage:	This file should be included towards the top of all webpages,
 * 		but after prototype.js and ga.js.
 *
 * Purpose: 	This script does 2 things 			 		 
 *
 *		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.airtransat.fr'				:'UA-6277146-1',
		'vols.airtransat.fr'			:'UA-6277146-1',
		'www.transatfrance.fr'			:'UA-6277146-1',
		'secure.transatfrance.fr'		:'UA-6277146-1',

		'www.airtransat.be'				:'UA-6277181-1',
		'engine.airtransat.be'			:'UA-6277181-1',
		'www.airtransat.es'				:'UA-6277209-1',
		'www.airtransat.gr'				:'UA-6277227-1',
		'www.airtransat.de'				:'UA-6277254-1',
		'engine.airtransat.de'			:'UA-6277254-1',
		'www.airtransat.ch'				:'UA-6277275-1',
		'engine.airtransat.ch'			:'UA-6277275-1',
		'www.airtransat.co.uk'			:'UA-6277292-1',
		'www.airtransat.it'				:'UA-6277305-1',
		'www.airtransat.nl'				:'UA-6277314-1',
		'engine.airtransat.nl'			:'UA-6277314-1',
		'secure2.airtransat.nl'			:'UA-6277314-1',
		'www.airtransat.ie'				:'UA-6277355-1',
		'www.airtransat.at'				:'UA-6277380-1',
		'engine.airtransat.at'			:'UA-6277380-1',	
		'www.airtransat.pt'				:'UA-21508065-1',
		'secure.ogone.com'				:'UA-6381993-9',

		'www.exitnow.ca'				:'UA-6139577-1',
		'services.airtransat.com'		:'UA-6288865-1',
		'at.exitravel.com'				:'UA-6288921-1',
		'www.exitravel.com'				:'UA-6533487-1',
		'exi.sax.softvoyage.com'		:'UA-6288944-1',
		'booking.softvoyage.com'		:'UA-6288969-1',
		'www.transattravel.com'			:'UA-10078934-1',

		'www.transatholidays.com'		:'UA-6777270-1',
		'www.nolitours.com'				:'UA-6777258-1',
		'pp-www-vat.exitnow.ca'			:'UA-6381993-2',
		'pp-www.exitnow.ca'				:'UA-6381993-3',
		'acc-vat.exitnow.ca'			:'UA-6381993-4',
		'acc-wov.exitnow.ca'			:'UA-6381993-5',
		'dev-exit.exitnow.ca'			:'UA-6381993-6',
		'acc-exit.exitnow.ca'			:'UA-6381993-7',
		
		'at.purecobalt.com'				:'UA-8459370-1',
		'atat.purecobalt.com'			:'UA-8459370-2',
		'atbe.purecobalt.com'			:'UA-8459370-3',
		'atch.purecobalt.com'			:'UA-8459370-4',
		'atde.purecobalt.com'			:'UA-8459370-5',
		'ates.purecobalt.com'			:'UA-8459370-6',
		'atfr.purecobalt.com'			:'UA-8459370-7',
		'atgr-nouveau.purecobalt.com'	:'UA-8459370-8',
		'atie.purecobalt.com'			:'UA-8459370-9',
		'atit.purecobalt.com'			:'UA-8459370-10',
		'atnl.purecobalt.com'			:'UA-8459370-11',
		'atuk.purecobalt.com'			:'UA-8459370-12',
		'test.go-canada-direct.com'		:'UA-8459370-13',
		'atfr-nouveau.purecobalt.com'	:'UA-8459370-14',
		'valid.transatfrance.fr'		:'UA-8459370-15',
		'atpt.purecobalt.com'			:'UA-8459370-16'

		};


/*	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(
	'airtransat.fr', 
	'airtransat.be', 
	'airtransat.es', 
	'airtransat.gr', 
	'airtransat.de', 
	'airtransat.ch', 
	'airtransat.co.uk', 
	'airtransat.it', 
	'airtransat.nl', 
	'airtransat.ie', 
	'airtransat.at', 
	'airtransat.pt',
	'exitnow.ca', 
	'airtransat.com', 
	'exitravel.com', 
	'softvoyage.com', 
	'transatfrance.fr', 
	'ts-availability.com', 
	'canadianaffair.com', 
	'canadianaffair.ie',
	'tpscan.com',
	'transatholidays.com',
	'nolitours.com',
	'go-canada-direct.com',
	'purecobalt.com',
	'transattravel.com',
	'ogone.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();


/*	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  ============ */
/* ========================================================== */

// 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 (! accId){
	accId = caAccId;
}

var pageTracker = _gat._getTracker(accId);
pageTracker._setDomainName("none");
pageTracker._setAllowLinker(true); 
pageTracker._trackPageview();


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 Param.
		var qDomain = getQueryVal('profile_referrer');
		accountId = getAccId(qDomain);
		if (accountId){
			createCookie(cookieName,accountId);
			createCookie('profile_referrer',qDomain);
		}
	}

	if (! accountId){
		// Get from refferer.
		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);
		}
	}
	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;
	}
}

