/**
 * @author   Christian Ringele christian.ringele [at] magnolia-cms.com
 * @version  1.0 2010-01-20
 * 
 * 
 * jquery.gatracker.js - Monitor events with Google Analytics ga.js tracking code
 * 
 * Requires jQuery 1.2.x or higher (for cross-domain $.getScript)
 * 
 * Used some elements of qGoogleAnalytics of David Simpson  david.simpson [at] nottingham.ac.uk
 * (http://davidsimpson.me/2008/06/18/jgoogleanalytics-google-analytics-integration-for-jquery/) 
 * who built upon gaTracker (c)2007 Jason Huck/Core Five Creative 
 * (http://devblog.jasonhuck.com/2007/11/19/google-analytics-integration-with-jquery/)
 *    http://plugins.jquery.com/files/jquery.gatracker.js_0.txt  
 * 
 * Implemented features by David Simpsons qGoogleAnalytics;
 * - clicks events
 * - form submit events
 * - cross subdomain
 * - cross domain (e.g. for eCommerce payment gateways hosted externally)
 * - new organic search engines
 * - all the features of Jason HuckÕs GA jQuery integration
 *      
 * Changes and added features to David Simpsons version of qGoogleAnalytics:
 * - tracking of anchor links on pages (href starting with #) 
 * - enabling/disabling possibilities of all link tracking options (external-, maitlo-, anchor- & download-links)
 * - standardizing the default values (null where no booelan is expected, null=not tracked)
 *  
 * @param {String} trackerCode
 * @param {Object} options see setings below
 *    
 * usage: 
 *	 $.qGoogleAnalytics( 'UA-XXXXXX-X');
 *	 $.qGoogleAnalytics( 'UA-XXXXXX-X', {trackLinksEnabled: true, pageViewsEnabled: false} );
 * 
 */

(function($) { // make available to jQuery only

	$.mgnlGoogleAnalytics = function (trackerCode, options)
	{
		
		settings = $.extend({
			//events tracking
			clickEvents:         null,          // e.g. {'.popup': '/popup/nasty'}
			evalClickEvents:     null,          // e.g. {'#menu li a': "'/tabs/'+ $(this).text()"}
			submitEvents:        null,          // e.g. {'#personUK': '/personsearch/uk'}
			evalSubmitEvents:    null,          // e.g. {'#menu li a': "'/tabs/'+ $(this).text()"}

			//link tracking
			trackLinksEnabled:   false,         // enables the link tracking (external-, maitlo-, anchor- & download-links)			
			externalPrefix:	     null,          // prefix to add to external links e.g. '/external/'
			mailtoPrefix:		 null,          // prefix to add to email addresses e.g. '/mailtos/'
			anchorPrefix:	     null,          // prefix to add to anchors (href starting with #) e.g. '/anchors/'
			downloadPrefix:	     null,          // prefix to add to downloads e.g. '/downloads/'
			downloadExtensions:  [              
					               'pdf','doc','xls','ppt','docx','xlsx','pptx',
					               'odt','odp','ods','csv','txt','jpg','jpeg','jpx',
					               'gif','png','bmp','swf','zip','gz','tar','rar',
					               'dmg','xml','js','mp3','wav','mov','mpg','mpeg','avi'
			                     ],	           // tracked files extensions of downloads
			                     
			//domain tracking                 
			crossDomainSelector: null,          // e.g. 'a.crossDomain'
			domainName:          null,          // e.g. 'nottingham.ac.uk'
			
			//misc tracking options
			organicSearch:       null,		    // e.g. {'search-engine': 'query-term', 'google.nottingham.ac.uk': 'q'}
			pageViewsEnabled:    true,          // can be disabled e.g. if only tracking click events
			sampleRate:          null           // e.g. 50 - set the sample rate at 50%
		});
		
		if (options)
		{
			$.extend(settings, options);
		} 
		
		init();
		



		/****** methods *******/
				
		/**
		 * Initialise the tracking code and add any optional functionality
		 */
		function setupTracking()
		{
			// Get the tracking code
			var 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);
			}
			
			// 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);		
		}
		
		/**
		 * 
		 */
		function addTracking(pageTracker)
		{		
			// 1. Track event triggered 'views'
					
			// loop thru each link on the page
			if (settings.trackLinksEnabled)
			{
				// From: http://plugins.jquery.com/files/jquery.gatracker.js_0.txt
				$('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);
									//console.debug('linkClick: ' + newLink);
								}
							);
						}
					}				
				});
			}
			
			// 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');		
			}
		}

		// From: http://plugins.jquery.com/files/jquery.gatracker.js_0.txt
		// Returns the given URL prefixed if it is:
		//		a) a link to an external site
		//		b) a mailto link
		//		c) a downloadable file
		//      d) a anchor link (starting with # in href)
		// ...otherwise returns an empty string.
		function decorateLink(uri)
		{
			var trackingUri = '';
			
			// check if internal link
			if (uri.indexOf('://') == -1 && uri.indexOf('mailto:') != 0)
			{
				// check if download links shall be tracked
				if(settings.downloadPrefix){
				
					// no protocol or mailto - internal link - check extension
					var ext = uri.split('.')[uri.split('.').length - 1];			
					var exts = settings.downloadExtensions;
					
					for(i=0; i < exts.length; i++)
					{
						if(ext == exts[i])
						{
							// external link - decorate
							trackingUri = settings.downloadPrefix + uri;
							break;
						}
					}		
				}
				
				//Check if anchors on page shall be tracked
				if(settings.anchorPrefix){
					if(uri.indexOf('#') == 0 && uri.length>1){
						//anchor link - decorate
						var pageUrl = window.location.pathname;
						var indexHtml = pageUrl.indexOf('.html');
						pageUrl = pageUrl.substring(0, indexHtml);
						trackingUri = settings.anchorPrefix+ pageUrl+'.'+ uri.substring(1);
					}
				}
			} 
			else // is not internal link -> mail or external link
			{
				// check if mailto link
				if (uri.indexOf('mailto:') == 0) 
				{
					//Check if mailto links shall be tracked
					if(settings.mailtoPrefix){
						// mailto link - decorate
						trackingUri = settings.mailtoPrefix + uri.substring(7);	
					}
				} 
				else // is external link
				{
					// check if external links shall be tracked
					if(settings.externalPrefix){
						// complete URL - check domain
						var regex     = /([^:\/]+)*(?::\/\/)*([^:\/]+)(:[0-9]+)*\/?/i;
						var linkparts = regex.exec(uri);
						var urlparts  = regex.exec(location.href);
											
						if (linkparts[2] != urlparts[2])
						{
							// external link - decorate
							trackingUri = settings.externalPrefix + uri;
						}
					}
				}
			}
			
			return trackingUri;			
		}
		
		/**
		 * load ga.js and add the tracking code
		 */		
		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';
				
				// load ga.js with caching
				return $.ajax({
					type: 'GET',
					url: gaUrl,  // Store the tracking JS locally & update weekkly (??)
					dataType: 'script',
					cache: true,
					success: function() {  
						// console.debug('ga.js loaded!'); 
						setupTracking(); 
					},
					error: function() { 
						// console.error('ajax GET failed'); 
					}
				});	
			} 
			catch(err) 
			{
				// log any failure
				// console.error('Failed to load Google Analytics:' + err);
			}	
			
			return false;		
		}	
	} 
	
	
})(jQuery);	
/*ends*/

