/**
 * Script adapted from original found in 
 * "Google Analytics" by Justin Cutroni
 * available at http://www.oreilly.com/catalog/9780596514969/
 *
 */

/*
 * By default, this script will track links to the following file
 * types: .doc, .xls, .exe, .zip and .pdf
 *
 */
var fileTypes = (".doc",".xls",".exe",".zip",".pdf");

/* 
 * This is a debug mode flag. In debug mode the script will display 
 * an alert box and skip sending data to Google Analytics.
 *
 */
var debug = 0;

/*
 * This variable controls how outbound links will appear in
 * the GA reports. By default, external links will appear as
 * '/outbound/<URL>' where <URL> is the URL in the anchor tag.
 *
 */
var extIdentifier = '/outbound/';


if (document.getElementsByTagName) {
	// Initialize external link handlers
	var hrefs = document.getElementsByTagName('a');
	for (var i = 0; i < hrefs.length; i++) {
		//protocol, host, hostname, port, pathname, search, hash
		if (hrefs[i].hostname == location.host) {
			var path = hrefs[i].pathname;
			if (path.indexOf(fileTypes) != -1) startListening(hrefs[i],"click",trackDocuments);
		} 
		else {
			startListening(hrefs[i],"click",trackExternalLinks);
		}
	}
}

function startListening (obj,evnt,func) {
	if (obj.addEventListener) { obj.addEventListener(evnt,func,false); } 
	else if (obj.attachEvent) { obj.attachEvent("on" + evnt,func); }
}

function trackDocuments (evnt) {
	var url = (evnt.srcElement) ? "/" + evnt.srcElement.pathname : this.pathname;
	if (typeof(pageTracker._trackPageview) == "function") {
		if (!debug) { pageTracker._trackPageview(url); } 
		else { 
			alert(url);
			return false;
		}
	}
}

function trackExternalLinks (evnt) {
	var lnk;
	if (evnt.srcElement) {
		var elmnt = evnt.srcElement;
		while (elmnt.tagName != "A") {
			var newelmnt = elmnt.parentNode;
			elmnt = newelmnt;
		}
		lnk = extIdentifier +elmnt.hostname + "/" + elmnt.pathname + elmnt.search;
	} 
	else {
		lnk = extIdentifier + this.hostname + this.pathname + this.search;
	}
	if (typeof(pageTracker._trackPageview) == "function") {
		if (!debug) {
			pageTracker._trackPageview(lnk);
		} 
		else {
			alert(lnk);
			return false;
		}
	}
}
