/**
	Class: 
		GADownloadTracker
	Author: 
		Scott Arbeitman
	Description: 
		Creating an instance of the GADownloadTracker and calling the trackDownloadsIn(element) method
		will add an onclick event (if one doesn't already exist) to all the anchor tags that 
		are children of the element that have a path which match the downloadMatch object's isDownloadLink 
		method.
		
		When this onclick event happens, the _trackingFunction_ will be called with a URL that is
		based on the path name or name attribute of this link and the current page.
	Example(s):
		new GADownloadTracker(new FarCryDownloadMatcher(), function(text) { alert(text); }).trackDownloadsIn(document);
		
		More complicated to track clicks in selected sections only.
		
		tracker = new GADownloadTracker(new FarCryDownloadMatcher(), urchinTracker);
		tracker.trackDownloadsIn(document.getElementById("left-side"));
		tracker.trackDownloadsIn(document.getElementById("footer"));
		
	Dependancies: 
		None

*/

function FarCryDownloadMatcher() {
	this.isDownloadLink = function(elem) {
		return elem.pathname && elem.search && elem.pathname.match(/\/?download\.cfm/) && elem.search.match(/^\?DownloadFile=[^&]+/);
	}
}

function GADownloadTracker(downloadMatcher, trackingFunction) {

	this.trackingFunction = trackingFunction;
	this.downloadMatcher = downloadMatcher;
	
	var oThis = this;

	this.trackDownloadsIn = function(element) {
		var links = element.getElementsByTagName("A");
		for (var i = 0; i < links.length; i++) 
			if (downloadMatcher.isDownloadLink(links[i])) 
				if (!links[i].onclick)  //add an onclick behaviour if it isn't defined
					links[i].onclick = trackDownloadClick;
	};
	
	var trackDownloadClick = function(event) {
		var aLink = (event ? event.target : window.event.srcElement);
		var linkText = constructTrackingUrlFromLink(aLink);
		oThis.trackingFunction(linkText); 
	};
	
	var constructTrackingUrlFromLink = function(aLink) { 
		var humanName = "";
		
		if (aLink.name) {
			humanName = aLink.name;
		} else { //use the inner text of this tag as the text which hopefully indicates what document this is
			humanName = (aLink.innerText ? aLink.innerText : aLink.text);
		}
		
		if (humanName.length == 0) {
			humanName = "Untitled Download";
		}
		
		if (aLink.pathname.charAt(0) != "/") { //IE first slash removing wierdness. Add it back if it's not there.
			aLink.pathname = "/" + aLink.pathname;
		}
		
		return aLink.pathname+aLink.search+"&human_name="+humanName;		
	};
	
}