/* 
# v2.31
# 31 Jan 2011
# xtrtrkr
# url: http://www.conversionworks.co.uk/
*/
var xtrtrkr = new function() {
  
	/*
	# Global Variables
	*/
	this.domains = [
		[
			//production domains
			{name:'www.tottenhamhotspur.com',UA:'UA-7935519-2', subdomain:'.tottenhamhotspur.com'},
			{name:'investorrelations.tottenhamhotspur.com',UA:'UA-7935519-2', subdomain:'.tottenhamhotspur.com'},
			{name:'stadiumtours.tottenhamhotspur.com',UA:'UA-7935519-2', subdomain:'.tottenhamhotspur.com'},
			{name:'hospitality.tottenhamhotspur.com',UA:'UA-7935519-2', subdomain:'.tottenhamhotspur.com'},
			{name:'soccerschools.tottenhamhotspur.com',UA:'UA-7935519-2', subdomain:'.tottenhamhotspur.com'},
			{name:'foundation.tottenhamhotspur.com',UA:'UA-7935519-2', subdomain:'.tottenhamhotspur.com'}
		],[
			//Test domains
			{name:'livesite1.spurs.autonomycloud.com',UA:'UA-27773498-1', subdomain:'.spurs.autonomycloud.com'},
			{name:'runtime.spurs.autonomycloud.com',UA:'UA-27773498-1', subdomain:'.spurs.autonomycloud.com'}			
		],[
			//dev domain
			{name:'tagless.panther.webexpectations.net',UA:'UA-27773498-1', subdomain:''}
		]
	];
	this.fourohfour = false;
	this.splash = false;
	this.Docs = ['.doc','.xls','.pdf'];
	this.Srcs = ['twitter','facebook','youtube','t.co'];
	this.Links = [];
	this.Tracked = false;
	this.ignoredForms = [];
	this.ignoredElements = ['button','submit','fieldset'];
	this.ie7orbelow = (document.all && !window.opera && window.XMLHttpRequest) ? true : false;
	this.dirtyLinks = ['#','javascript','youtube'];
	this.urchin_source = '';
	this.urchin_medium = '';
	this.urchin_term = '';
	
	/*
	# init
	*/	
	this.init = function()
	{
		
		// Reference self so no loss of scope
		var self = xtrtrkr;
		
		/*
		# Xtrtrkr native functions
		*/
		self.organiseLinks();
		self.cleanForms();
		self.FormTrack();
		self.SocialTrack();
		self.cleanLinks();
		self.videoTrack();
		//self.CleanerInPageAnalytics();

		/*
		# Generic trackPageview
		*/
		//is this a four oh four page?
		if((document.title.toString().indexOf('Error')>-1) && (this._fourohfourtextfound()==true)){
			self.fourohfour=true;
			self._fourohfour();
		}
		
		//is this a four oh four page?
		if((window.location.pathname.toString().indexOf('/spurs/Splash')>-1) && (this._fourohfourtextfound()==false)){
			self.splash=true;
			self._splash();
		}
		
		//if this is not a splash or a 404 then normal page tracking
		if ( self.Tracked == false && self.fourohfour == false && self.splash == false) {
			_gaq.push(['_trackPageview']);
		}				
	};
	
	/*
	# Extra Tracker Native Functions **************************************************************** 
	*/
	/*
	# Track Page
	*/
	this.PageTrack = function(URL)
	{
		var self = xtrtrkr;
		if ( self.Tracked == false ) {
			_gaq.push(['_trackPageview',URL]);
		}
		self.Tracked = true;
	};
	
	/*
	# Does not look to see if the page tracker has already been called
	*/
	this._PageTrack = function(URL)
	{
		var self = xtrtrkr;
		_gaq.push(['_trackPageview',URL]);
	}
	
	/*
	# Track Events 
	*/
	this._Event = function(category, action, label, value)
	{
		var self = xtrtrkr;
		_gaq.push(['_trackEvent', category, action, label]);
	}
	
	/*
	# Essentially for flash forms
	*/
	this.FieldTrack = function(URL)
	{
		var self = xtrtrkr;
		_gaq.push(['_trackPageview',URL]);
	}
	
	/*
	# Organise Links
	*/
	this.organiseLinks = function()
	{
		var self = xtrtrkr;
		$('a').each(function(i,el)
		{
			if ( $(el).attr('href') ) {
				if ( $(el).attr('href').indexOf('http') != -1 )
				{	
					$(el).addClass('xtexit');
					$(el).click(function(e) {
						e.preventDefault();
						self.PageTrack( '/exit/' + i + ' ' + $(this).attr('href') );
            var link_url = $(el).attr('href');
						
						if(self.Tracked){
							if ( $(el).attr('target') == '_blank' ) {
								self.Tracked = false;
								window.open( link_url,'_blank' );
							} else {
								setTimeout(function(){
									window.location.href = $(el).attr('href');
								}, 100);
							}
					  }
					});
				}
				else if ( $(this).attr('href').indexOf('mailto') != -1 )
				{
					$(this).addClass('mailto');
					$(this).click(function(e) {
						self.PageTrack( '/mailto/' + $(this).attr('href') );
					});
				}
				else if ( 
						$(this).attr('href').indexOf('.doc') != -1 || 
						$(this).attr('href').indexOf('.xls') != -1 || 
						$(this).attr('href').indexOf('.pdf') != -1
					)
				{
					$(this).addClass('download');
					$(this).click(function(e) {
						self.PageTrack( '/download/' + $(this).attr('href') );
					});
				}
			}
		});
	}
		
	/*
	# 404
	*/
	this._fourohfour = function()
	{
		var self = xtrtrkr;
		if ( self.fourohfour == true )
		{
			self.PageTrack( '/404/' + window.location.pathname );
		}
	}
	
	this._fourohfourtextfound = function()
	{
		var self = xtrtrkr;
		textfound = false;
		htwos = jQuery('h2');
		jQuery(htwos).each(function(i,htwo) {		
		  if ( jQuery(htwo).html().indexOf('404 ERROR')>-1 ){
			  textfound = true;
		  }
		});
		return textfound;
	}
	
	/*
	# splash
	*/
	this._splash = function()
	{
		var self = xtrtrkr;
		if ( self.splash == true )
		{
			splash_vpv = window.location.pathname.match(/\/spurs\/Splash(\/.*)\.page.*/);
			self.PageTrack( '/splash/' + splash_vpv[1] );
		}
	}
	
	/*
	# If the user has come from a social networking site reference in self.Srcs track via cookies and a custom var
	*/
	
	function extractParamFromUri(uri, paramName) {
	  if (!uri) {
	    return;
	  }
	  var uri = uri.split('#')[0];  // Remove anchor.
	  var parts = uri.split('?');  // Check for query params.
	  if (parts.length == 1) {
	    return;
	  }
	  var query = decodeURI(parts[1]);

	  // Find url param.
	  paramName += '=';
	  var params = query.split('&');
	  for (var i = 0, param; param = params[i]; ++i) {
	    if (param.indexOf(paramName) === 0) {
	      return unescape(param.split('=')[1]);
	    }
	  }
	}
	
	this.SocialTrack = function()
	{
		var self = xtrtrkr;
		
		try {
	    if (FB && FB.Event && FB.Event.subscribe) {
	      FB.Event.subscribe('edge.create', function(targetUrl) {
	        _gaq.push(['_trackSocial', 'facebook', 'like',targetUrl, opt_pageUrl]);
	      });
	
				FB.Event.subscribe('edge.remove', function(targetUrl) {
				  _gaq.push(['_trackSocial', 'facebook', 'unlike', targetUrl]);
				});
				
				FB.Event.subscribe('message.send', function(targetUrl) {
				  _gaq.push(['_trackSocial', 'facebook', 'send', targetUrl]);
				});
	    }
	  } catch(e) {}
		
		try{
  		twttr.events.bind('tweet', function(event) {
	  	  if (event) {
		      var targetUrl;
		      if (event.target && event.target.nodeName == 'IFRAME') {
		        targetUrl = extractParamFromUri(event.target.src, 'url');
		      }
		      _gaq.push(['_trackSocial', 'twitter', 'tweet', targetUrl]);
		    }
		  });
		} catch(e) {}
		
		for ( var i = 0; i < self.Srcs.length; i++ ) {
			
			if( document.referrer && document.referrer.indexOf(self.Srcs[i])>= 0 ) {
				var social_firstclick = self.get_utm_value(document.cookie, '__utmv=', ';','social_first_click=([a-zA-Z]*)');
				if( social_firstclick != '' ) {	
					_gaq.push(['_setCustomVar',3,'social_first_click',self.Srcs[i],1]);
				} else {	
					var social_history = self.get_utm_value(document.cookie, '__utmv=', ';','social_influencer=([a-zA-Z]*)');
					if ( social_history!='' && social_history.indexOf(self.Srcs[i]) < 0 ) {
						_gaq.push(['_setCustomVar',4,'social_influencer',social_history+'-'+self.Srcs[i],1]);
					} else {
						_gaq.push(['_setCustomVar',4,'social_influencer',self.Srcs[i],1]);
					}
				}
			}
		}
		return true;
	};
	this.videoTrack = function()
	{
		var self = xtrtrkr;
		
		jQuery('.vjs-play-control').live("click", function(){
			_gaq.push(['_trackEvent','video',document.title,'play']);
		});
		
		jQuery('.vjs-big-play-button').live("click", function(){
			_gaq.push(['_trackEvent','video',document.title,'play']);
		});
	}

	/*
	# Method to build and return an array of forms not to be ignored
	*/
	this.cleanForms = function()
	{
		var self = xtrtrkr;
		var forms = document.getElementsByTagName('form');
		var cleanedForms = [];
		for(var i = 0; i < forms.length; i++){ 
			var cleanForm = true;
			for(var j = 0; j < self.ignoredForms.length; j++){ 
				if(forms[i].id.toString().indexOf(self.ignoredForms[j])>=0){
					cleanForm = false;
				}
			}
			if(cleanForm){cleanedForms.push(forms[i]);}
		}
		self.cleanedForms = cleanedForms;
	};
	
	/*
	# Method to track form that are not ignored
	*/
	this.FormTrack = function()
	{
		
		var self = xtrtrkr;
		if ( self.cleanedForms && self.cleanedForms.length > 0 ) {
			$(self.cleanedForms).each(function(i,cleanForm) {
				var elements = cleanForm.elements;
				var trackElement = false;
				$(elements).each(function(i,element) {
					$(self.ignoredElements).each(function(i,ignoredElement) {
						if ( element.type != ignoredElement ) {
							trackElement = true
						}
					});
					if ( trackElement ) {
						$(element).focus(function() {
							_gaq.push(['_trackEvent', 'Form Events', document.location.pathname, $(element).attr('id')]);
						});
					}
				});
			});
		}
	};
	
	/*
	# Build and return an array of links that are not to be ignored
	*/
	this.cleanLinks = function()
	{
		var self = xtrtrkr;
		var cleanedLinks = [];
		$('a').each(function(i,link) {
			if ( $(link).attr('href') ) {
				var cleanLink = true;
				$(self.dirtyLinks).each(function(k,dirtyLink) {
					if ( $(link).attr('href').indexOf(dirtyLink) >= 0 )
					{
						cleanLink = false;
					}
				});
				if(cleanLink){ self.Links.push( $(link) ); }
			}
		});
		return cleanedLinks;
	};
	

	/*
	# Adds additional details to the anchor
	*/
	this.CleanerInPageAnalytics = function()
	{
		var self = xtrtrkr;
		var tracked = self.Links[0];
		var extra_param = 0;
		var unique = true;
		$(self.Links).each(function(i,link) {
			unique = true;
			if ( 
				( $(link).toString().length>0 ) && 
				( $(link).toString().indexOf('extra=')<0 ) &&
				( tracked.valueOf().toString().indexOf( $(link).toString() ) > -1)
			) {
				unique=false;
			}
			if(!unique){
				if( $(link).toString().indexOf('?') > 0) {
					$(link).attr('href', $(link).attr('href') + '&extra='+extra_param);
				} else {
					$(link).attr('href', $(link).attr('href') + '?extra='+extra_param);
				}
			} else {
				tracked.push(link);
			}
			extra_param++;
		});
	};

	/*
	# Track printing links
	*/
	this.PrintTrack = function(Links)
	{
		var self = xtrtrkr;
		for(var i = 0; i < Links.length; i++){
			if(Links[i].href.indexOf("printContent();") > -1){
				if(!self.ie7orbelow){
					Links[i].setAttribute("onclick","xtrtrkr.PageTrack('/print/" + Links[i].href + "')");
				}else{
					Links[i].onclick=function() { self.PageTrack('/print/'+this.href); };
				}
			}
		}
	};
	
	/*
	# Real Time Tracker
	Call this when pages are to be tracked in a REAL TIME profile.  REAL TIME profiles inly include pageview that start with /realtime/
	If this functionality is used, make sure non-realtime profiles EXCLUDE pagviews that start with /realtime/
	Failure to include/exclude /realtime/ pageviews correctly will destroy your analytics data
	*/
	this.rt = function(rt_uri)
	{
		var self = xtrtrkr;
    self.PageTrack('/realtime/'+rt_uri);
	};
	
	
	/*
	# Helper methods
	*/	
	this.get_UA = function()
	{
		var self = xtrtrkr;
		var UA = '';
		//g = domain group index
		//i = domain index
		for(var g = 0; g < self.domains.length; g++){
			for(var i = 0; i < self.domains[g].length; i++){  
				if(document.location.toString().indexOf(self.domains[g][i].name) > -1){	  
					UA = self.domains[g][i].UA;
					if(typeof(self.domains[g].subdomain) != undefined){
						self.subdomain = self.domains[g].subdomain;
					}
					return UA;
				}
			}
		}
		return UA;
	};

	this.getParameterByName = function(name)
	{
		var self = xtrtrkr;
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		if( results == null )
			return "";
		else
			return decodeURIComponent(results[1].replace(/\+/g, " "));
	};

	this.get_utm_value = function(l,n,s,vregex)
	{
		if (!l || l=="" || !n || n=="" || !s || s=="") return "-";
		var i, i2, i3, c="-";
		var regex = new RegExp(vregex);
		i=l.indexOf(n);
		i3=n.indexOf("=")+1;
		if (i > -1){
			i2=l.indexOf(s,i);
			if (i2 < 0){i2=l.length;}
			c=l.substring((i+i3),i2);
		}
		vout = regex.exec(c) == null ? '' : regex.exec(c)[1];
		return vout;
	};

	/*
	# Grab varaible and return it
	*/
	this.uGC = function(l, n, s)
	{
		if (!l || l == "" || !n || n == "" || !s || s == "") return "-";
		var i, i2, i3, c = "-";
		i = l.indexOf(n);
		i3 = n.indexOf("=") + 1;
		if (i > -1) {
			i2 = l.indexOf(s, i);
			if (i2 < 0) {
				i2 = l.length
			}
			c = l.substring((i + i3), i2)
		}
		return c
	};

	/*
	# Grab variables out of the cookie
	*/
	this.grabReferrer = function()
	{
		var self = xtrtrkr;
		var z = _uGC(document.cookie, "__utmz=", ";");
		self.urchin_source = self.uGC(z, "utmcsr=", "|");
		self.urchin_medium = self.uGC(z, "utmcmd=", "|");
		self.urchin_term = _self.uGC(z, "utmctr=", "|");
		var gclid = self.uGC(z, "utmgclid=", "|");
		if (gclid != '-') {
			self.urchin_source = "google";
			self.urchin_medium = "cpc"
		}
	};
	

	/*
	# Method for creating a cookie
	*/
	this.createCookie = function(name,value,days)
	{
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	};

	/*
	# Method for reading a cookie
	*/
	this.readCookie = function(name)
	{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	};
	
// End of class
}

/*
# API Calls Below Here
**********************************************************************
*/

/*
# Call xtrtrkr functionality as needed
*/
var _gaq = _gaq || [];	
_gaq.push(['_setAccount', xtrtrkr.get_UA()]);

/*
# If we are using a sub domain
*/
if(document.location.toString().indexOf(xtrtrkr.subdomain)>0)
{
	_gaq.push(['_setDomainName',xtrtrkr.subdomain]);
	_gaq.push(['_setAllowHash',false]);
}
/*
# Include Google Analytics
*/
(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

jQuery(document).ready(function() {
	xtrtrkr.init();
});

