/* 	gaTracker 1.0.1: jQuery Google Analytics Integration 
	A quicker, automated way to embed Google Analytics.
	(c)2007 Jason Huck/Core Five Creative
	
	* BETA Support for new Analytics API (ga.js) by Jamie Thompson - http://jamazon.co.uk
	* Requires jQuery 1.2.x or higher (for cross-domain $.getScript)
	* TODO: more testing, delay after $.getScript for Safari
	
	Usage:
	Only a tracking code is required:
	$.gaTracker('UA-XXXXX-XX');

	...but other options can be specified:
	$.gaTracker(
		'UA-XXXXX-XX',
		{
			vpath:		'/track',	<-- virtual path to stow tracking stats under
			external:	'/external/',
			mailto:		'/mailto/',
			download:	'/downloads/',
			statuscode:	200,
			emaillinks:	true,     <--- track any mailto: links
			extlinks:	true,     <--- track any http:// external links
			extensions:	[
				'pdf','doc','xls','csv','jpg','gif', 'mp3',
				'swf','txt','ppt','zip','gz','dmg','xml'		
			]
		}
	);

*/
var thisScript = null;
var gaAccountId = null;
// get our script src= attribute...
var scripts = document.getElementsByTagName('script');
thisScript = new String(scripts[scripts.length - 1].src);

(function($){
	$.gaTracker = function(code, opts){
		opts = jQuery.extend({
			vpath:		'/track',
			external:	'/external/',
			mailto:		'/mailtos/',
			download:	'/downloads',
			bookmark:	'/bookmarks',
			statuscode: 	200,
			emaillinks:	true,
			extlinks:	true,
			bookmarklinks:	false,
			defaultscript:	'index.php',
			extensions: [
					'pdf','doc','xls','csv','jpg','gif', 'mp3',
					'swf','txt','ppt','zip','gz','dmg','xml', 'js'		
			]
		}, opts);
		
		// Returns the given URL prefixed if it is:
		//		a) a link to an external site
		//		b) a mailto link
		//		c) a downloadable file
		// ...otherwise returns an empty string.
		function decorateLink(u){
			var trackingURL = '';
			
			// determine type of link
			linktype = 0;
			if (u.indexOf('http://') == 0) {		// http:// type external link
				linktype = 1;
			}
			else {
				if(u.indexOf('mailto:') == 0){		// mailto link
					linktype = 2;
				}
				else {
					if(u.indexOf('#') == 0){	// bookmark link
						linktype = 3;
					}
					else {
						linktype = 4;
					}
				}
			}
			switch(linktype) {
			case 1: //ext link
				// complete URL - check domain
				if (opts.extlinks) {	// track extlinks enabled ??
					var regex = /([^:\/]+)*(?::\/\/)*([^:\/]+)(:[0-9]+)*\/?/i;
					var linkparts = regex.exec(u);
					var urlparts = regex.exec(location.href);					
					if(linkparts[2] != urlparts[2]) trackingURL = opts.vpath + opts.external + linkparts[2];
				}
				break;
			case 2: //mailto link
				if (opts.emaillinks) {	// track mailto links enabled ??
					var emailaddr = u.substring(7);
					if (emailaddr.indexOf('?') > 0) {
						emailaddr = emailaddr.substring(0, emailaddr.indexOf('?'));
					}
					trackingURL = opts.vpath + opts.mailto + emailaddr;
				}
				break;
			case 3: // bookmark links
				if (opts.bookmarklinks) {	// track bookmark links enabled ??
					trackingURL = opts.vpath + opts.bookmark + document.location.pathname + '/' + u;
				}
				break;
			case 4:
				// no protocol or mailto - internal link - check extension
				var ext = u.split('.')[u.split('.').length - 1];			
				var exts = opts.extensions;
				
				for(i = 0; i < exts.length; i++){
					if(ext == exts[i]){	// matches one of recognised download filetypes
						trackingURL = opts.vpath + opts.download + u;
						break;
					}
				}
				break;
			}
			// go back with pseudo url representing this click event
			return trackingURL;
		}
		
		// add tracking code to the current page
		function addTracking(){
			
			if (typeof _gat != 'undefined') {
				debug('GA loaded for '+code);

				$.pageTracker = _gat._getTracker(code);
				$.pageTracker._initData();
				
				// main page tracker
				if (opts.statuscode == 200) {	// normal GA tracking code
					$.pageTracker._trackPageview();
				}
				else {				// 404 virtual tracking url
					trackURL = opts.vpath+'/errors/'+opts.statuscode+document.location.pathname + document.location.search + '?referrer=' + document.referrer;
					$.pageTracker._trackPageview(trackURL);
					debug('Tracking error '+trackURL);
				}
			
				// examine every link in the page
				$('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);
								debug('tracked click to '+newLink);
							});
						}
					}				
				});
			}
			else {
				throw "_gat is undefined";	// serInterval loading ??
			}
		}
		
		// include the external GA script in try/catch to play nice
		function initGA(){
			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 the script
				$.getScript(gaURL, function(){
					addTracking();
				});
			} catch(err) {
				// log any failure
				debug('Failed to load Google Analytics:' + err);
			}
		}
		
		initGA();
	}
	
	// print to firebug console if available
	function debug(message) {
		if(typeof console != 'undefined' && typeof console.debug != 'undefined') {
			console.debug(message);
		}
	}
	
})(jQuery);

// print to firebug console if available
function debug(message) {
	if(typeof console != 'undefined' && typeof console.debug != 'undefined') {
		console.debug(message);
	}
}
	
// do page tracking stuff upon DOM load
$(document).ready(function(){
	var parts = thisScript.split('?');
	if (parts.length > 1) {	// have querystring parms tagged to src 
		var parms = parts[1];
		var arg = parms.split('=');
		if (arg.length ==2 && arg[0] == 'id') gaAccountId = arg[1];
	}
	
	if (gaAccountId) {	// have we been given the GA account id via querystring ??
		// track pageview and add tracking handlers for every outbound link, email link
		$.gaTracker(gaAccountId);
		debug('tracked impression to '+gaAccountId);
	}

});

