// TODO: remove debug
var googleGADebug = false;

var googleGAAccount;
var googleGADomain;
var googleGAFileFromServer;
if (document.location.hostname.indexOf('.soundstrue.com') > -1) {
	googleGAAccount = 'UA-5276897-2';
	googleGADomain = '.soundstrue.com';
	googleGAFileFromServer = document.location.protocol + '//www.soundstrue.com/google/ga.js';
	// removed if (document.location.hostname.indexOf('.staging-soundstrue.com') > -1)
} else {
	googleGAAccount = 'UA-5276897-5';
	googleGADomain = '.staging-soundstrue.com';
	googleGAFileFromServer = document.location.protocol + '//www.staging-soundstrue.com/google/ga.js';
	//googleGAFileFromServer = document.location.protocol + '//www.google-analytics.com/ga.js';
}

if (typeof googleGAHost != 'undefined') {		
	googleGAFileFromServer = document.location.protocol + '//' + googleGAHost + '/google/ga.js';
}

assignGoogleAsync = true;
if (typeof googleAsync != 'undefined') {
	googleAsync == false ? assignGoogleAsync = false : assignGoogleAsync = true;
}

assignGoogleTrackPageview = null;
if (typeof googleTrackPageview != 'undefined') {
	assignGoogleTrackPageview = googleTrackPageview;
}

var _gaq = _gaq || [];
$(document).ready(function() {
    if(typeof googleDisableTracking == 'undefined') {
    	_gaq.push(['_setAccount', googleGAAccount]);
    	_gaq.push(['_setAllowHash', false]);
    	_gaq.push(['_setDomainName', googleGADomain]);
    	_gaq.push(['_setAllowLinker', true]);
    	if (assignGoogleTrackPageview != null) {
    		_gaq.push(['_trackPageview', assignGoogleTrackPageview]);
    	} else {
    		_gaq.push(['_trackPageview']);
    	}
    	_gaq.push(['_trackPageLoadTime']);
    }
    
    // assure all anchors with external link which don't have a onclick event have the event tracking 
    // and open in a new window if the current page is an ecom page
    applyAddLinkerToSelector('.applyAddLinker');
    
	//implementation in 1.3.x/1.6.0 turned off for the moment
	//setGACookieValuesOnForms();

});

if (window.googleAnalyticsTrack != undefined && googleAnalyticsTrack == false) {
	$(document).ready(function(){
		setTimeout(function(){
			(function() {
				var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = assignGoogleAsync;
				ga.src = googleGAFileFromServer;
				var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
				assignGoogleTrackPage();
			})();
		}, 500);
	});
} else {
	(function() {
		var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = assignGoogleAsync;
		ga.src = googleGAFileFromServer;
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
		assignGoogleTrackPage();
	})();
}

function applyAddLinkerToSelector(selector) {
	$(selector).each(function(){
		if($(this).attr('onclick') == undefined) {
			var clickString = "";
			if($(this).attr('href').indexOf('http://') == 0 && $(this).attr('href').indexOf(googleGADomain) == -1) {
				clickString += "if(typeof googleGATrackEvent == 'function'){googleGATrackEvent({'account':'" + googleGAAccount + "','domain':'" + googleGADomain + "','category':'outbound','label':'url','value':'" + $(this).attr('href') + "'});};";
				clickString += "_gaq.push(function() { var tracker = _gaq._getAsyncTracker(); window.open(tracker._getLinkerUrl('" + $(this).attr('href') + "')); });return false;"; 
			} else {
				clickString += "javascript:_gaq.push(['_link', '" + $(this).attr('href') + "']);"; 
			}
			$(selector).attr('onclick', clickString);
		}	
	});
}

function googleGATrackEvent(eventObject) {
	
	_gaq.push(['_trackEvent', eventObject.category, eventObject.label, eventObject.value]);
	
	// debug
	if(googleGADebug == true && typeof debugWithConsole == 'function') {
		debugWithConsole('== GA Event ==');
		debugWithConsole(eventObject);
	}
	
}

function assignGoogleTrackPage() {
	// debug
	if(googleGADebug == true && typeof debugWithConsole == 'function') {
		debugWithConsole('== GA PageTrack ==');
		debugWithConsole(_gaq);
	}
}

function debugWithConsole() {
	if(window.console && window.console.firebug) {
		console.log.apply(this, arguments);
	}
}

// function to set all forms with at class of emailSignupFormTrack to append GA related data on request.
function setGACookieValuesOnForms() {
	//$.cookie('__utmz', 'utmcsr=1|utmccn=2|utmcmd=3');
	var currentCookies = $.cookie();
	var append;
	if (currentCookies && currentCookies['__utmz']) {
		var splitValues = currentCookies['__utmz'].split('|');
		var keyValStack = {}
		for ( var i = 0; i < splitValues.length; i++) {
			var keyVal = splitValues[i].split('=');
			keyValStack[keyVal[0]] = keyVal[1];
		}
		append = getHiddenInputTagsForGACookies(keyValStack);
	} else {
		append = getHiddenInputTagsForGACookies({});
	}
	$('form.GATrackCampaign').append(append);
}

function getHiddenInputTagsForGACookies(keyValStack) {
	// build the post params
	var append = '<input name="GA_Source" type="hidden" id="GA_Source" value="' + (keyValStack['utmcsr'] ? keyValStack['utmcsr'] : 'NOT SET') + '" />';
	append += '<input name="GA_Name" type="hidden" id="GA_Name" value="' + (keyValStack['utmccn'] ? keyValStack['utmccn'] : 'NOT SET') + '" />';
	append += '<input name="GA_Medium" type="hidden" id="GA_Medium" value="' + (keyValStack['utmcmd'] ? keyValStack['utmcmd'] : 'NOT SET') + '" />';
	return append;
}


