// setup ga variable in the global scope
var pageTracker;
var ga_account = 'UA-7724538-1'

// add event listener to install ga on body load
if (window.addEventListener) {
	window.addEventListener('load', cmsInstallGAstart, false);
} else if (window.attachEvent) {
	window.attachEvent('onload', cmsInstallGAstart);
}
// end add event listener

function cmsInstallGAstart() {
	// this should fire on document load
	// this function actually need to call antother function with the value of
	//		the ga_account variable created by google_install.js.php
	//		optionally, for a site not on this CMS you could simple supply the accoun number here
	cmsInstallGA(ga_account);
} // end function cmsInstallGAstart

function cmsInstallGA(trackerCode) {
	// install GA and add event onclicks
	var settings = new Object();
	settings.anchorClick = true;									// adds click tracking to *all* anchors
	settings.clickEvents = null;									// e.g. {'.popup': '/popup/nasty'}
	settings.crossDomainSelector = false;					// e.g. 'a.crossDomain'
	settings.domainName = false;									// e.g. 'nottingham.ac.uk'
	settings.evalClickEvents = null;							// e.g. {'#menu li a': "'/tabs/'+ $(this).text()"}
	settings.evalSubmitEvents = null;							// e.g. {'#menu li a': "'/tabs/'+ $(this).text()"}
	settings.extensions = ['pdf','doc','xls',
												 'csv','jpg','gif',
												 'mp3','swf','txt',
												 'ppt','zip','gz',
												 'dmg','xml', 'vcf']	;					// download extensions to track
	settings.external = '/external/';							// prefix to add to external links
	settings.mailto = '/mailto/';									// prefix to add to email addresses
	settings.download = '/download/';							// prefix to add to downloads
	settings.organicSearch = null;								// e.g. {'search-engine': 'query-term', 'google.nottingham.ac.uk': 'q'}
	settings.pageViewsEnabled = true;							// can be disabled e.g. if only tracking click events
	settings.sampleRat = null;										// e.g. 50 - set the sample rate at 50%
	settings.submitEvents = null;									// e.g. {'#personUK': '/personsearch/uk'}
	
	
	init();
	
	function init() {
		try {
			// determine whether to include the normal or SSL version
			var gaUrl = (location.href.indexOf('https') == 0 ? 'https://ssl' : 'http://www');
			gaUrl += '.google-analytics.com/ga.js';
			// include ga.js 
			// insert the script tag into the page
			//var headEl = document.getElementsByTagName('head');
			var scriptEl = document.createElement('script');
			scriptEl.type = 'text/javascript';
			scriptEl.src = gaUrl;
			scriptEl.onreadystatechange = function() {
				if (scriptEl.readyState == "loaded" ||
            scriptEl.readyState == "complete") {
					scriptEl.onreadystatechange = null;
					setupTracking();
    		}
			}
			scriptEl.onload = function() {
				setupTracking();
			}
			
			document.getElementsByTagName('head')[0].appendChild(scriptEl);
			
		} 
		catch(err) {
		}
	}	
	
	function setupTracking() {
		//alert('here4');
		// Get the tracking code
		pageTracker = _gat._getTracker(trackerCode);
			
		// Track visitor across subdomain
		if (settings.topLevelDomain) {
			pageTracker._setDomainName(settings.topLevelDomain);
		}
		
		// Set the sample rate - for very busy sites
		if (settings.sampleRate) {
			pageTracker._setSampleRate(settings.sampleRate);
		}
		
		/*
		I'll deal with this later
		// Track visitor across domains		
		if (settings.crossDomainSelector) {
			// ignore domain names
			pageTracker._setDomainName('none');
			pageTracker._setAllowLinker(true);
			
			// Add submit event to form selector e.g. form.crossDomain
			$('form' + settings.crossDomainSelector).submit(
				function()
				{
					pageTracker._linkByPost(this);
					// console.debug('crossDomain ._linkByPost');
				}
			);
			// Add a click event to anchor selector e.g. a.crossDomain
			$('a' + settings.crossDomainSelector).click(
				function()
				{
					pageTracker._link( $(this).attr('href') );
					// console.debug('crossDomain ._link: ' + $(this).attr('href'));
				}
			);
			
			// Add click event to link
		}
		
		// Add organic search engines as required
		if (settings.organicSearch)
		{
			$.each(
				settings.organicSearch, 
				function(key, val)
				{
					pageTracker._addOrganic(key, val);
					// console.debug('_addOrganic: ' + key);
				}
			);
		}
		
		*/
		// check that this is the correct place
		pageTracker._initData();
		// console.debug('_initData');
		
		addTracking(pageTracker);		
		
	} // end function setupTracking
	
	function addTracking(pageTracker) {		
		// 1. Track event triggered 'views'
		var loc = 'http://'+location.host;
		var sLen = loc.length+1;
		
		// loop thru each link on the page
		if (settings.anchorClick) {
			// From: http://plugins.jquery.com/files/jquery.gatracker.js_0.txt
			// get all a elements in page
			// loop through all elements and add code
			anchors = document.getElementsByTagName('a');
			aLength = anchors.length;
			for (var i=0; i<aLength; i++) {
				var u = anchors[i].href; 
				if (u.indexOf(loc) == 0) {
					// strip it off
					u = u.substring(sLen);
				}
				//alert(u);
				var newLink = decorateLink(u);
				//alert(newLink);
				if (newLink.length) {
					// add event listener to link
					anchors[i].track = newLink;
					//alert(anchors[i].track);
					if (window.addEventListener) {
						// most browsers
						anchors[i].addEventListener('click', function(){pageTracker._trackPageview(this.track);}, false);
					} else if (window.attachEvent) {
						// windows/IE
						anchors[i].attachEvent('onclick', function(){pageTracker._trackPageview(this.track);});
					}
				}
			}
			
			/*$('a').each(function(){
				var u = $(this).attr('href');
				
				if(typeof(u) != 'undefined'){
					var newLink = decorateLink(u);
	
					// if it needs to be tracked manually,
					// bind a click event to call GA with
					// the decorated/prefixed link
					if (newLink.length)
					{
						$(this).click(
							function()
							{
								pageTracker._trackPageview(newLink);
								//alert('here');
								// console.debug('anchorClick: ' + newLink);
							}
						);
					}
				}				
			});*/
		}
		
		/* I'll deal with this whole thing later
		
		// loop thru the clickEvents object
		if (settings.clickEvents)
		{
			$.each(settings.clickEvents, function(key, val){
				$(key).click(function(){
					pageTracker._trackPageview(val);
					// console.debug('clickEvents: ' + val);
				})
			});
		}
	
		// loop thru the evalClickEvents object
		if (settings.evalClickEvents)
		{
			$.each(settings.evalClickEvents, function(key, val){
				$(key).click(function(){
					evalVal = eval(val)
					if (evalVal != '')
					{
						pageTracker._trackPageview(evalVal);
						// console.debug('evalClickEvents: ' + evalVal);
					}
				})
			});			
		}
		
		// loop thru the evalSubmitEvents object
		if (settings.evalSubmitEvents)
		{
			$.each(settings.evalSubmitEvents, function(key, val){
				$(key).submit(function(){
					evalVal = eval(val)
					if (evalVal != '')
					{
						pageTracker._trackPageview(evalVal);
						// console.debug('evalSubmitEvents: ' + evalVal);
					}						
				})
			});
		}
		
		// loop thru the submitEvents object
		if (settings.submitEvents)
		{
			$.each(settings.submitEvents, function(key, val){
				$(key).submit(function(){
					pageTracker._trackPageview(val);
					// console.debug('submitEvents: ' + val);
				})
			});
		}
		*/
		
		// 2. Track normal page views
		if (settings.pageViewsEnabled) {
			pageTracker._trackPageview();	
			// console.debug('pageViewsEnabled');
		} else {
			// console.debug('pageViewsDisabled');		
		}
	} // end function addTracking
	
	function decorateLink(u) {
		var trackingURL = '';
		// we need to check if the current domain == the domain in u
		// if it does we need to strip it out
		// problem is that some browsers report the full domain name in all links
		// even local ones
		
		if (u.indexOf('://') == -1 && u.indexOf('mailto:') != 0) {
			
			// no protocol or mailto - internal link - check extension
			var ext = u.split('.')[u.split('.').length - 1];			
			var exts = settings.extensions;
			
			for(var i=0; i<exts.length; i++) {
				if(ext == exts[i]) {
					trackingURL = settings.download + u;
					break;
				}
			}			
		} else {
			if (u.indexOf('mailto:') == 0) {
				// mailto link - decorate
				trackingURL = settings.mailto + u.substring(7);					
			} else {
				// complete URL - check domain
				var regex = /([^:\/]+)*(?::\/\/)*([^:\/]+)(:[0-9]+)*\/?/i;
				var linkparts = regex.exec(u);
				var urlparts = regex.exec(location.href);
									
				if (linkparts[2] != urlparts[2]) {
					trackingURL = settings.external + u;
				}
			}
		}
		
		return trackingURL;			
	}
	
} // end cmsInstallGA


/*

// remove the event listener example, not really needed
	if (window.removeEventListener) {
		window.removeEventListener('load', cmsInstallGAstart, false);
	} else if (window.detachEvent) {
		window.detachEvent('load', cmsInstallGAstart);
	}
*/

// end of file
