/******************************************************************************
 *         This code is Copyright (C) 2006-2007 POP unless otherwise noted,   *
 *      and may not be used without explicit written permission from POP      *
 
 *  WARNING - THIS CODE IS CUSTOMIZED FOR MTC AND WILL NOT WORK   	      *
 *  ON OTHER SITES.  DO NOT ATTEMPT TO DUPLICATE OR YOUR ANALYTICS WILL BREAK *
 ******************************************************************************/


		/**
		 * CONFIGURATION SETTINGS
		 */
		PopJavaScriptFramework.v1B2.config = {
			root: "http://" + location.hostname + "/js",
			rootVirtual: "/"
		}
		/**
		 * Google Analytics Configuration information.
		 */
		PopJavaScriptFramework.v1B2.config.analytics = {
			enabled: true,
			clickLogging: false,	// Print clicklog instead of tracking?
			domains: [				// You must put all possible live domains in the domains array, including utmLinker domains
				location.hostname,
				// replace string.getHostName()
				PopJavaScriptFramework.v1B2.config.root.getHostname(),
				'mtc.com.au',
				'www.mtc.com.au',
				'trainyard.experiencepop.com'
				
			],
			UlinkDomains: [				// You must put all possible utmLinker domains in this array
				//	'othersite.com'
			],
			params: { // GA Variables
				_uacct: "UA-5370302-1",
				_udn: "mtc.com.au",
				_userv: "2",
				_uanchor: "true"				
				//_uhash: "off",
				//_ulink: "1"
			}
		}


		/**
		 * CUSTOM UTMLINKER FUNCTION
		 */
		function __utmLinker2(l,h) {
		 if (!_ulink) return;
		 var p,k,a="-",b="-",c="-",x="-",z="-",v="-";
		 var dc=_ubd.cookie;
		 
		 if (!l || l=="") return;
		 var iq = l.indexOf("?"); 
		 var ih = l.indexOf("#"); 
		 if (dc) {
		  a=_uES(_uGC(dc,"__utma="+_udh,";"));
		  b=_uES(_uGC(dc,"__utmb="+_udh,";"));
		  c=_uES(_uGC(dc,"__utmc="+_udh,";"));
		  x=_uES(_uGC(dc,"__utmx="+_udh,";"));
		  z=_uES(_uGC(dc,"__utmz="+_udh,";"));
		  v=_uES(_uGC(dc,"__utmv="+_udh,";"));
		  k=(_uHash(a+b+c+x+z+v)*1)+(_udh*1);
		  p="__utma="+a+"&__utmb="+b+"&__utmc="+c+"&__utmx="+x+"&__utmz="+z+"&__utmv="+v+"&__utmk="+k;
		 }
		 if (p) {
		  if (h && ih>-1) { 
			return; 
		  }
		  if (h) { 
			_udl.href2=l+"#"+p; 
		  }
		  else {
		   if (iq==-1 && ih==-1) {
				_udl.href2=l+"?"+p;
				return _udl.href2;
		   }
		   else if (ih==-1) {
				_udl.href2=l+"&"+p;
				return _udl.href2;
		   }
		   else if (iq==-1) {
				_udl.href2=l.substring(0,ih)+"?"+p+l.substring(ih);
				return _udl.href2;
		   }
		   else {
				_udl.href2=l.substring(0,ih-1)+"&"+p+l.substring(ih);
				return _udl.href2;
		   }
		  }
		 } else {
				_udl.href2=l;
				return _udl.href2;
		 }
		}

PopJavaScriptFramework.v1B2.analytics = {
	/**
	 * List of file suffixes to track as downloads
	 */
	dlSuffix: ["mov","mp3","wmv","wav","rm","doc","xls","zip","pdf","sit","sitx","tgz"],
	
	/**
	 * An array to hold trackable links
	 */
	links: [],

	/**
	 * Global alias to build()
	 * "this" scopes to "window", not PopJavaScriptFramework.v1B2.analytics.
	 */
	init: function() {
		PopJavaScriptFramework.v1B2.analytics.build();
	},
	/**
	 * Starts all aspects of GA tracking.
	 */
	build: function() {
		this.config = PopJavaScriptFramework.v1B2.config.analytics;
		this.links = this._collectLinks();
		for (var i=0; i<this.links.length; i++) {
			this._attachLinkTracker(this.links[i]);
		}
		
		// create variables for GA tracking
		var p = PopJavaScriptFramework.v1B2.analytics.config.params;
		for (var i in p) {
			window[i] = p[i];
		}
		
		// Call GA Tracker (included as seperate script element).
		if (typeof urchinTracker != "undefined") {
			urchinTracker();
		}
	},

	/**
	 * Collects all links to track on page
	 * @return {Array} Array of link elements to track
	 */
	_collectLinks: function() {
		// Find all A/AREA tags
		var a = $dom.getByTag('a', 'area');
		var links_to_track = [];
		for (var i=0; i < a.length; i++) {
			if (this._isUTMlinker(a[i]) || this._isOutbound(a[i]) || this._isDownload(a[i]) || this._isEmail(a[i]) || this._isJS(a[i])) {
				links_to_track.push(a[i]);
			}
		}
		return links_to_track;
	},
	/**
	 * Attaches clicktracker to each link OR returns the string that would be
	 * tracked it the tracker were attached to the link
	 * @param {Object} oLinkElement A link element to attach the clicktracker to
	 * @param {Boolean} bList Whether or not to return a string representation instead of tracking.
	 */
	_attachLinkTracker: function(oLinkElement, bList) {
		if (bList === true) {
			return this._getTrackerString(oLinkElement);
		} else {
			PopJavaScriptFramework.v1B2.event.add(oLinkElement,"click",PopJavaScriptFramework.v1B2.analytics.trackClick);
		}
	},
	/**
	 * Attached to each outbound link. "this" scopes to the "a" object.
	 */
	trackClick: function(e) {
		PopJavaScriptFramework.v1B2.analytics._trackClick(this,e);
	},
	_trackClick: function(a,e) {
		var o = this._getTrackerString(a);
		if (this.config.clickLogging) {
			// LOG, don't track
			try { // log in firebug
				console.info(o,a);
			} catch (err) { // alert everywhere else
				alert(o + '\n(' + a + ')');
			} 
			PopJavaScriptFramework.v1B2.event.stop(e);
		} else {
			if(this._isUTMlinker(a)) {
				//alert('UTM should work.');
				PopJavaScriptFramework.v1B2.event.stop(e);
				//var oU = __utmLinker2(o);
				// Track if urchinTracker function is found
				window.location = __utmLinker2(o);
				//alert('UTM should work. oU = '+oU);
			} else {
				// Track if urchinTracker function is found
				try {
					urchinTracker(o);
				} catch (err) {}
			}
		}
	},
	/**
	 * Get the string to pass to GA from an A element
	 * @param {Object} a An A or Area HTML Element
	 * @return {String} A string for to pass to GA for custom click-tracking
	 */
	_getTrackerString: function(a) {
		var o = '';
		switch (true) {
			case this._isUTMlinker(a):
				o = a.href;
				break;
			case this._isOutbound(a):
				o = '/outbound/' + this._removeProtocol(a.href);
				break;
			case this._isDownload(a):
				o = '/download/' + this._removeProtocol(a.href).replace(a.href.getHostname(),'').replace(/^\//,'');
				break;
			case this._isEmail(a):
				o = '/email/' + this._removeProtocol(a.href);
				break;
			case this._isJS(a):
				o = '/javascript/' + this._removeProtocol(a.href).replace(a.href.getHostname(),'').replace(/^\//,'');
				break;
		}
		return o.toLowerCase();
	},
	/**
	 * UTILITY: Remove Protocol from link
	 * @param {String} sHref
	 * @return {String} String without the beginning protocol
	 */
	_removeProtocol: function(sHref) {
		if (sHref.indexOf('mailto') == 0) {
			return sHref.replace(/^\w+\:/,"");
		} else {
			return sHref.replace(/^\w+\:\/\//,"");
		}
	},
	/**
	 * UTILITY: Check if an a's href is an OUTBOUND URL
	 * @param {Object} a Link or Area element
	 * @return {Boolean}
	 */
	_isOutbound: function(a) {
		// if URL domain is not in our domain list and it begins with 'http', it's external
		if ( (!this.config.domains.contains(a.href.getHostname())) && (a.href.indexOf('http') == 0) ) {
			return true;
		}
		return false;
	},
	
	/**
	 * UTILITY: Check if an a's href is an UTMLINKER URL
	 * @param {Object} a Link or Area element
	 * @return {Boolean}
	 */
	_isUTMlinker: function(a) {
		// if URL domain is not in our UTMlinker list, it's to be UTMlinker tagged
		if ( (this.config.UlinkDomains.contains(a.href.getHostname()))) {
			return true;
		}
		return false;
	},
	
	
	/**
	 * UTILITY: Check if an a's href is an DOWNLOAD URL
	 * @param {Object} a Link or Area element
	 * @return {Boolean}
	 */
	_isDownload: function(a) {
		var suff = a.href.split("?")[0];			// remove query strings
		suff = suff.split(".");
		suff = suff[suff.length - 1];				// isolate the suffix
		if (this.dlSuffix.indexOf(suff) > -1) {		// find out if it's a trackable suffix
			return true;
		}
		return false;
	},
	/**
	 * UTILITY: Check if an a's href is an EMAIL ADDRESS
	 * @param {Object} a Link or Area element
	 * @return {Boolean}
	 */
	_isEmail: function(a) {
		if (a.href.indexOf('mailto:') == 0) {
			return true;
		}
		return false;
	},
	/**
	 * UTILITY: Check if an a is designated as a JS LINK
	 * @param {Object} a Link or Area element
	 * @return {Boolean}
	 */
	_isJS: function(a) {
		return $dom.hasClass(a, 'ga_jslink');
	},
	/**
	 * DEBUGGING: Prints out a list of all links being tracked
	 */
	printTracked: function() {
		for (var i=0; i<this.links.length; i++) {
			console.log(this._attachLinkTracker(this.links[i], true), this.links[i]);
		}
	}
}

try {
	if (PopJavaScriptFramework.v1B2.config.analytics.enabled == true) {
		PopJavaScriptFramework.v1B2.event.add(window, "load", PopJavaScriptFramework.v1B2.analytics.init);
	}
} catch (e) {
	throw new Error("There is no 'analytics' section in PopJavaScriptFramework.config.");
}

_uacct = "UA-5370302-1";
_udn="mtc.com.au";
_userv="2";
_uanchor="true";
urchinTracker(); 