/**************************************************************
* Name : GATracking.js
* Goal : Initialize and track the page with google analytics
*		 (this file override the referrer when the browser got
*		  the wrong one).
**************************************************************/
var _googleInterval; // Interval between each check
var _googleUA;		 // The google analytics UA
var pageTracker		 // The page tracker
/**************************************************************
* Name : addGoogleTracking
* Goal : Initialize the google tracking
* Params :
* - UA : The UA to track
**************************************************************/
function addGoogleTracking(UA){
	var sc = document.createElement('script');
	_googleUA = UA;
	sc.type = 'text/javascript';
	sc.src = 'http://www.google-analytics.com/ga.js';
	document.getElementsByTagName("head").item(0).appendChild(sc);
	_googleInterval = setInterval(activateGoogle,250);
}
/**************************************************************
* Name : activateGoogle
* Goal : Check if the google analytics library is ready
* 		  and track the correct referrer
**************************************************************/
function activateGoogle(){
	if(typeof _gat != 'undefined') {
		clearInterval(_googleInterval);
		pageTracker = _gat._getTracker(_googleUA);
		//*************************************************/
		var js = getUrlVars()['js'] == 'true';
		var altReferrer = unescape(getUrlVars()['altReferrer']);	
        // URL Double decode if some % stays
        if(altReferrer.search("%") > -1){
            altReferrer = unescape(altReferrer);
        }
		var browser = navigator.appName;
		if(!altReferrer){
			altReferrer = 'unknownReferrer';
		}
		
		if (js){
			if (!document.referrer) {
				pageTracker._setReferrerOverride(altReferrer);
			}
		}else {
			if (!document.referrer || !(navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Opera") != -1)){
				pageTracker._setReferrerOverride(altReferrer);
			}
		}
		//******************************************************/
		pageTracker._trackPageview();				
	}
}
/**************************************************************
* Name : getUrlVars
* Goal : Return the get url vars
**************************************************************/
function getUrlVars(){
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++)
	{
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	} 
	return vars;
}
