// JavaScript Document

/**
  *  Adds event handler for specified event to an element
  *  
  *  @param	element	Element to add event listener to
  *  @param	type		Event to listen for.  Do not prepend event with 'on', as the functions automatically prepends it
  *  @param	expression	Javascript function to execute on event.  Can be either a function name or anonymous function
  *  @param	bubbling	Sets whether to register the event on bubbling phase (true) or capturing phase (false).  Only applies to W3C compliant browsers.
  *  @return			True on success, false on failure
  */
function addListener(element, type, expression, bubbling)
{
	bubbling = bubbling || false;
	
	if(window.addEventListener) { // Standard
		element.addEventListener(type, expression, bubbling);
		return true;		
	} else if(window.attachEvent) { // IE
		element.attachEvent('on' + type, expression);
		return true;
	} else return false;
}

/**
  *  Adds link tracking to all PDF links.
  *  
  *  @param	downloadType	File Extensions to tag for download
  *  @return	true
  */
function addGATrackingToLinks(downloadType) {
	
	var anchors = document.getElementsByTagName('a');
	var child = null;
	
	var i = 0;
	
	for (i = 0; i < anchors.length; i++) {
		if (anchors[i].href.match('\.' + downloadType + '$') != null) {
			addListener(anchors[i], 'click', trackDownload, false);
		}	
	}
	
	return true;
}

/**
  *  Sends virtual page view request
  *  
  *  @param	e	Event object
  */
function trackDownload(evnt)
{
	var e = (evnt.srcElement) ? evnt.srcElement : this;
	
	while (e.tagName !== "A") {
		e = e.parentNode;
	}
	
	if (e.pathname == 'undefined')
		return;
	
	var lnk = (e.pathname.charAt(0) == "/") ? e.pathname : "/" + e.pathname; 
	
	lnk = lnk.replace(/%20/g, "_"); // replace space IE and FF
	lnk = lnk.replace(/ /g, "_"); // replace space Safari
	
	if (typeof pageTracker != "undefined" && e.hostname == location.host) {
		pageTracker._trackPageview(lnk);
	}
	
}

addListener(window, 'load', function (e) {addGATrackingToLinks('pdf')}, false);