
// no user servicable parts below this line
///// gaUtils object
// (c) 2010 Panalysis Pty Ltd all rights reserved www.panalysis.com
// licensed to INSERT CLIENT NAME
// for alterations and support regarding this script please contact support@panalysis.com
// Version 1.02 - 17-02-2010


// Start GAUtils object
function gaUtils(d)
{
	// private property declarations
	var bDomain ="";
	var bDebug = false;
	//var bTrackExternalDomains = true;
	var bTrackLinkID = false;
	var dTypes = new Array(".pdf",".doc",".docx",".xls",".xlsx",".exe",".zip",".rtf",".jpg",".png",".gif",".tiff",".tif",".mp3",".wav",".swf",".mpg");
	var bHasFormInteraction = 0;
	var bIsMember = 0;
	var _gaPageTracker = null;
	var linkerSites = new Array();
	this.formFieldStatus = new Object();
	this.formCommenced = false;
	
	if(d != "")
		bDomain = d;
	
	// initialise the page tracker if this is available.
	if(typeof(pageTracker) != 'undefined')
		_gaPageTracker = pageTracker;
	
	this.PageTracker = _gaPageTracker;
	
	// Public method declarations
	
	// SetBaseDomain (string domain) - sets the base domain from which to identify external links
	this.SetBaseDomain = _gaSetBaseDomain;
	
	// SetDebug(bool) - turn on alerts when sending data to Google Analytics
	this.SetDebug = _gaSetDebug;
	
	// TrackLink(string path, bool opens in same window ) - tracks the click on the link and records this as a page in Google Analytics
	this.TrackLink = _gaTrackThis; 
	
	// AddDownloadType(string ext) - adds a new document to the list of downloads to track.
	this.AddDownloadType = _gaAddDownloadType;
	
	// RegisterPageTracker(pageTracker Object) - registers a custom pageTracker object to use instead of the standard one.
	this.RegisterPageTracker = _gaRegisterPageTracker;
	
	this.AddLinkedSite = _addLinkerDomain;
	
	this.AddEvent = _gaAddEvent;
	
	this.RemoveEvent = _gaRemoveEvent;
	
	this.Initialise = _init;
	
	if(bDomain == "")
	{
		// get domain if not set
		var cDomain = document.location.hostname.toLowerCase();
		// split the domain into its component parts
		var dp = cDomain.split(".");
	
		if(dp[dp.length-1].length==2 && dp.length>=3)
			bDomain = dp[dp.length-3] + "." + dp[dp.length-2] + "." + dp[dp.length-1]; // set to the current domain including country code
		else if(dp[dp.length-1].length>=3)
			bDomain = dp[dp.length-2] + "." + dp[dp.length-1]; // assume .com, .info, etc
	}
	
	if(document.location.hash.indexOf('debug')>=0)
		_gaSetDebug(true);
		
	var bannerParams = new Array('ac');
	

	function _init() {
		// set up link tracking
		_gaInitLinks();
		
		// is the user a member?
		_gaTestMember();
		
		// check whether the click is from a tagged link
		_gaCheckBannerClick(bannerParams);
		
	}
	
	// _gaSetDebug(bool) - turns on or off debug mode
	function _gaSetDebug(val)
	{
		bDebug = val;
	}
	
	// _gaSetBaseDomain(string domain) - sets the base domain from which to determine whether a link is external or not
	function _gaSetBaseDomain(val)
	{
		bDomain = val;
		_gaInitLinks();
	}
	
	// _gaTrim - trims leading and trailing whitespace
	function _gATrim(val){ return val.replace(/^\s+|\s+$/g, '') ; }
	
	// _gaRegisterPageTracker - use a non-standard pageTracker object
	function _gaRegisterPageTracker(obj) { _gaPageTracker = obj; }
	
	// _gaInitLinks - scan the DOM and associate an onclick handler for each link based on its content
	function _gaInitLinks()
	{
		var mL = document.getElementsByTagName("a");
		var myRegexp = /^http[s]?:\/\/(.*)/;
		for(var i=0;i<mL.length;i++)
		{
			var myRef = mL[i].href.toLowerCase();
			if(myRef == undefined)
				continue;
				
			var myMatch = myRegexp.exec(myRef);
			var lchar = myRef.substring(myRef.length-1);
			if((lchar=="#" && mL[i].onclick != "") || (myMatch != undefined && myMatch.length>1 && bDomain != undefined && myRef.indexOf(bDomain) < 0))
			{
				if(_useLinker(mL[i].hostname))
					_gaAddEvent(mL[i],"click",function () { _gaAddLinker(this); return false; });
				else
					_gaAddEvent(mL[i],"click",function () { _gaTrackThis(this.href,false); });
			}
			else
			{
				for(x=0;x<dTypes.length;x++)
				{
					if(myRef.indexOf(dTypes[x])>-1 && self.pageTracker)
					{
						if(mL[i].target != "")
							_gaAddEvent(mL[i],"click",function () { _gaTrackThis(this.href,false); });
						else
							_gaAddEvent(mL[i],"click",function () { _gaTrackThis(this.href,true); return false;});
							
						_gaAddEvent(mL[i],"mouseup",function (e) { _gaCheckRightClick(e,this); });
					}
				}
			}
		}
	}

	// _gaTrackThis(string path,bool has target attribute) - records clicks on pdf and other links. 
	// If the target is the same window, then dwell for 1/2 second before redirecting user.
	function _gaTrackThis(t,r)
	{
		myDest = t;
		var myMatch = myDest.match(/^http[s]?:\/\/(.*)/);
		if(myMatch && myDest.indexOf(bDomain) < 0)
		{
			t = "/outbound/" + myMatch[1];
		}
		else
			t = t.replace(/http[s]?:\/\/[^\/]*/,"");
	
		if(_gaPageTracker != null)
		{
			try {
				if(bDebug==true)
					alert(t);
				_gaPageTracker._trackPageview(t);
			}
			catch (err) { }
		}
		
		if(r==true)
		{
			setTimeout("document.location.href=myDest;",500); // delay for 1/2 second
			return false;
		}
		else
			return true;
	}

	// _gaCheckRightClick(event,object) - tests for the right mouseclick event
	function _gaCheckRightClick(e,o)
	{
		var button;
		// determine which button was clicked.
		if (e.which == null)
			/* IE case */
			button= (e.button < 2) ? "LEFT" : ((e.button == 4) ? "MIDDLE" : "RIGHT");
		else
			/* All others */
			button= (e.which < 2) ? "LEFT" : ((e.which == 2) ? "MIDDLE" : "RIGHT");
		
		// tracking the right mouse click isn't accurate as we can't reliably get whether the link was clicked. 
		if(button=="RIGHT")
		{
			_gaTrackThis(o.href,false);
		}
	}
	
	function _addLinkerDomain(d)
	{
		linkerSites.push(d);
	}
	
	function _useLinker(d)
	{
		var ul = false;
		if(linkerSites.length>0)
		{
			for(var i=0; i< linkerSites.length; i++)
			{
				if(d.toLowerCase().indexOf(linkerSites[i])>=0)
				{
					ul=true;
					break;
				}
			}
		}
		return ul;
	}
	
	function _gaAddLinker(o)
	{
		try
		{
			var l = o.href;
			o.href= pageTracker._getLinkerUrl(l);
			return false;
		}
		catch(err)
		{
			return true
		}
	}
	
	// _getHashParam - retrieves the a query parameter from the document hash
	function _gaGetHashParam(strParam){
		if(strParam =="")
			return "";
		var _pstr = document.location.hash.substring(1);
		var _uparams = _pstr.split("&");
		for(var i = 0; i < _uparams.length; i++){
			var np = _uparams[i].split("=");
			if(_gATrim(np[0].toLowerCase()) == strParam.toLowerCase())
			{
				return _gATrim(np[1]);
				break;
			}
		}
		return "";
	}
	
	// _gaGetParam - retrieves the a query parameter from the document URL
	function _gaGetParam(strParam){
		var _pstr = document.location.search.substring(1);
		var _uparams = _pstr.split("&");
		for(i = 0; i < _uparams.length; i++){
			var np = _uparams[i].split("=");
			if(_gATrim(np[0].toLowerCase()) == strParam.toLowerCase())
				return _gATrim(np[1]);
		}
		return "";
	}
	
	// _gaSetCookie(string Name, string Value, String Expire Days, String Domain) - sets a cookie
	function _gaSetCookie(cookieName,cookieValue,nDays,strDomain) {
		var today = new Date();
		var expire = new Date();
		var pdm = "";
		if (strDomain && strDomain!="") 
			pdm=" domain="+strDomain+";"; 
		else if(self._udn)
			pdm=" domain="+_udn+";";
			
		
		//if (nDays==null || nDays==0) nDays=1;
		if(nDays>0)
		{
			expire.setTime(today.getTime() + 3600000*24*nDays);
			document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString() + "; path=/;" + pdm;
		}
		else
			document.cookie = cookieName+"="+escape(cookieValue) + "; path=/;" + pdm;
	}

	// _gaGetCookie - retrieves a cookie from a name
	function _gaGetCookie(strParam){
		var _ucookies = document.cookie.split(";");
		for(i = 0; i < _ucookies.length; i++){
			var np = _ucookies[i].split("=");
			if(_gATrim(np[0].toLowerCase()) == strParam.toLowerCase())
			{
				var val ="";
				for(i=1;i<np.length;i++)
				{
					if(i>1)
						val += "=";
					
					val += np[i];
				}
				return _gATrim(val);
			}
		}
		return "";
	}
	
	// _gaTestMember - checks whether there is a im variable in the URL or whether the variable ismember is set as a Javascript variable
	function _gaTestMember()
	{
		var utmv = _gaGetCookie('__utmv');
		if(utmv != "" && utmv.indexOf('member')>0)
		{
			bIsMember=1;
			return true;
		}

		var isM =0;
		if(typeof('_galoginStatus') != "undefined")
		{
			try
			{
				if( _galoginStatus.toUpperCase()=="SUCCESS")
					isM=1;
			}
			catch(err) { }
		}
		if(typeof('_gaismember') != "undefined")
		{
			try
			{
				if( _gaismember == 1)
					isM=1;
			}
			catch(err) { }
		}
		
		var mq = _gaGetParam('im');
		if((mq != "" && mq.toLowerCase().indexOf('guest')<0) || isM==1 )
		{
			bIsMember=1;
			try
			{
				if(_gaPageTracker != null)
				{
					if(bDebug)
						alert("Member: Yes");
					_gaPageTracker._setCustomVar(1,"member","yes",1);
				}
			}
			catch(err) {}
		}
	}
	
	// _gaAddDownloadType(string t) - appends a new download type to the list
	function _gaAddDownloadType(t) 
	{
		if(t != "")
		{
			if(t.substr(0,1) != ".")
				t = "." + t;
			dTypes[dTypes.length] = t;
		}
	}
	
	// _gaCheckBannerClick(array str) - custom banner tracking
	function _gaCheckBannerClick(paramList)
	{
		for(i=0; i<paramList.length; i++)
		{
			var p = paramList[i];
			var b = _gaGetParam(p);
			var c = _gaGetHashParam(p);
			if(b != "" || c != "")
			{
				if (b=="")
					b = c; 
				
				if(bDebug)
					alert("Banner/Link: " + b);
				try
				{
					// set a page level custom variable to record the banner clicks
					_gaPageTracker._setCustomVar(2,"banner",b,3);
					// record an event to ensure that the click is tracked
					_gaPageTracker._trackEvent("Banners",b);
				} catch (err) {}
			}
		}
	}
	
	// _gaAddEvent - adds an event to the DOM. Correctly handles the pointer for "this"
	function _gaAddEvent( obj, type, fn ) {
		if ( obj.attachEvent ) {
			obj['e'+type+fn] = fn;
			obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
			obj.attachEvent( 'on'+type, obj[type+fn] );
		} else
			obj.addEventListener( type, fn, false );
	}
	
	// _gaRemoveEvent - removes an event from the DOM
	function _gaRemoveEvent( obj, type, fn ) {
		if ( obj.detachEvent ) {
			obj.detachEvent( 'on'+type, obj[type+fn] );
			obj[type+fn] = null;
		} else
			obj.removeEventListener( type, fn, false );
	}
}
