var myDest="";

document.onload= new function () {
_gaUtil = new gaUtils('natlib.govt.nz');

//// Uncomment the following line to turn on debug messages
//_gaUtil.SetDebug(true);

}

// no user servicable parts below this line
///// gaUtils object
// (c) 2009 Panalysis Pty Ltd all rights reserved www.panalysis.com
// licensed to New Zealand National Library 
// for alterations and support regarding this script please contact support@panalysis.com
// version 1.01 12-12-2009

// Start GAUtils object
function gaUtils(d)
{
	// private property declarations
	var bDomain ="";
	var bDebug = false;
	var bTrackExternalDomains = false;
	var bTrackLinkID = false;
	var dTypes = new Array(".pdf",".doc",".docx",".xls",".xlsx",".exe",".zip",".rtf",".jpg",".png",".gif",".tiff");
	var dVURL="";
	var bHasFormInteraction=0;
	
	if(d != "")
		bDomain = d;
	// 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;
	
	// GetVirtualURL() - returns any URL constructed by any function
	this.GetVirtualURL = _gaGetVirtualURL;
	
	// initialisation
	var cDomain = document.location.hostname.toLowerCase();
	// split the domain into its component parts
	var dp = cDomain.split(".");
	if(bDomain == "")
		bDomain = dp[dp.length-3] + "." + dp[dp.length-2] + "." + dp[dp.length-1]; // set to the current domain including country code
	
	if(document.location.hash.indexOf('debug')>=0)
		_gaSetDebug(true);
		
	_gaInitLinks();
	if(document.location.host.toLowerCase().indexOf('find.natlib')!= -1)
		_gaFindNatLibURLMods();

	// track form start events
	_gaTrackFormStart(); 
	
	// _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, '') ; }
	
	// _gaGetVirtualURL() - returns any virtual URL that this code has manufactured.
	// e.g. find.natlib.govt.nz search results.
	function _gaGetVirtualURL()
	{
		if(dVURL != "")
			return dVURL;
		else
			return "";
	}
	
	// _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))
			{
				_gaAddEvent(mL[i],"click",function () { _gaTrackThis(this.href,false); });
			}
			else
			{
				for(x=0;x<dTypes.length;x++)
				{
					if(myRef.indexOf(dTypes[x])>-1)
					{
						if(mL[i].target != "")
							_gaAddEvent(mL[i],"click",function () { _gaTrackThis(this.href,false); });
						else
							_gaAddEvent(mL[i],"click",function () { _gaTrackThis(this.href,false); return false;});
					}
				}
			}
		}
	}

	// _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(self.pageTracker)
		{
			if(bDebug==true)
				alert("pageTracker: " + t);
			pageTracker._trackPageview(t);
		}
		else if(self.urchinTracker)
		{
			if(bDebug==true)
				alert("Urchin Tracker: " + t);
			urchinTracker(t);
		}
		
		if(r==true)
		{
			setTimeout("document.location.href=myDest;",500); // delay for 1/2 second
			return false;
		}
		else
			return true;
	}

	// _getHashParam - retrieves the a query parameter from the document hash
	function _gaGetHashParam(strParam){
		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 (nDays==null || nDays==0) nDays=1;
		expire.setTime(today.getTime() + 3600000*24*nDays);
		if (strDomain && strDomain!="") 
			pdm=" domain="+strDomain+";"; 
		else if(_udn)
			pdm=" domain="+_udn+";";
		document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString() + "; 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 "";
	}

	// _gaAddDownloadType(string ext) - adds a new file type to track downloads
	function _gaAddDownloadType(t) //TODO check syntax
	{
		if(t != "")
			dTypes[dTypes.length] = t;
	}
	
	// _gaFindSiteURL() - sets up URLs to track search results
	
	function _gaFindNatLibURLMods()
	{
		// this function reconstructs the URL based on the user's search query parameters
		// expected format:
		// /[eng|mi]/search/[core|extended]/[collection name]/[look for]?query=USER+QUERY&matchtype=[contains|phrase]&field=[anywhere|title...]
		
		var dU="";
		var la="eng";
		var lDiv = document.getElementById("languagesDiv");
		if(lDiv.innerHTML.toLowerCase().indexOf('ingarihi')!=-1)
			la = "mi"; // if the language div includes ingarihi the set the lang to mi
		
		dU = "/" + la + "/";
		if(document.location.href.toLowerCase().indexOf('primo_library/libweb/action/search.do') != -1 )
		{
			dU += "search/";
			/*// check which search tab is used
			*var st = _gaGetParam("tab");
			*if(st.toLowerCase()=="remote_search")
			*	dU += "extended sources/";
			*else
			*	dU += "core sources/";
			*/
			// identify the collection
			
			var col = unescape(_gaGetParam("scp.scps"));
			var scp = unescape(_gaGetParam("vl(6491435UI1)"));

			var dSel = document.getElementById("lookIn");
			for(i=0;i<dSel.options.length; i++)
			{
				if(dSel.options[i].value==col)
					dU += dSel.options[i].text;
			}
			/*
			*var dSelType = document.getElementById("input_6491435UI1");
			*for(i=0;i<dSelType.options.length; i++)
			*{
			*	if(dSelType.options[i].value==scp)
			*		dU += dSelType.options[i].text ;
			*}
			*/
			dU += document.location.search;
			dVURL = dU;
		}
	}
	
	
	// _gaTrackFormStart() - records the start of a form when the user has entered a value into any text field
	function _gaTrackFormStart()
	{
		if(document.forms.length>0)
		{
			for(i=0; i<document.forms.length;i++)
			{
				var f = document.forms[i];
				var tf=0;
				// if the form has an action in the specified list of forms to track then add it
				
				if(typeof(_gaformlist) != "undefined")
				{
					for(var a=0; a<_gaformlist.length; a++)
					{
						if(_gaformlist[a].toLowerCase()==f.action.toLowerCase())
							tf=1;
					}
				}
				if(f.className=="formtrack" || tf==1)
				{
					flist = f.elements;
					for(var l=0; l<flist.length; l++)
					{
						var fEl = flist[l];
						try
						{
							if(fEl.type.toLowerCase()=="text" || fEl.type.toLowerCase()=="textarea")
							{
								_gaAddEvent(fEl,"keypress",function() { _gaTestInput(this);});
							}
						}
						catch(err) {}
					}
				}
			}
		}
	}
	
	function _gaTestInput(fID)
	{
		if(fID.value  != undefined && fID.value.length>0 && bHasFormInteraction==0)
		{
			var d ="?";
			if(fID.form.action.indexOf("?")>=0) d="&";
			
			if(typeof(urchinTracker) !="undefined")
			{
				if(bDebug==true)
					alert("Urchin: " + fID.form.action + d + "formstarted=1");
				urchinTracker(fID.form.action + d + "formstarted=1");
			}
			
			if(typeof(pageTracker)  !="undefined")
			{
				if(bDebug==true)
					alert("pageTracker: " + fID.form.action + d + "formstarted=1");
				pageTracker._trackPageview(fID.form.action + d + "formstarted=1");
			}
			bHasFormInteraction=1;
		}
	}
	
	// _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 );
	}
}
