// Add extra Google Analytics functionality to the page
// This script will track all document downloads, and outbound links
// Samuel Sweitzer <sam@tkg.com>

    function gaAddEventTracking() { // add Google Analytics event tracking to all document links on the page (link must also be hosted on this site to be tracked).
		if (window.attachEvent){intWayToAddOnClickEvent=1;} else if (window.addEventListener) {intWayToAddOnClickEvent=2;}
		var aryLinks = document.links; // find all links on the page
		for (var aryLinks_counter = 0; aryLinks_counter < aryLinks.length; aryLinks_counter++){
			try{ //protocol, host, hostname, port, pathname, search, hash
				if (aryLinks[aryLinks_counter].hostname == location.host) { //make sure it is a link on this site.
					var strLinkPath = aryLinks[aryLinks_counter].pathname + aryLinks[aryLinks_counter].search;
					var bolTrackDocument = strLinkPath.match(/\.(?:txt|doc|pdf|dwg|xls|ppt|zip|rar)($|\&|\?)/);
					if (bolTrackDocument){
						switch (intWayToAddOnClickEvent) {
							case 1:
								aryLinks[aryLinks_counter].attachEvent("onClick","gaTrackEvent(this, 'Document Download', '" + ((strLinkPath).substring((strLinkPath).lastIndexOf('/') + 1)) + "', '" + ((location.pathname).substring((location.pathname).lastIndexOf('/') + 1)) + "');return false;");
								break;
							case 2:
								aryLinks[aryLinks_counter].setAttribute("onClick","gaTrackEvent(this, 'Document Download', '" + ((strLinkPath).substring((strLinkPath).lastIndexOf('/') + 1)) + "', '" + ((location.pathname).substring((location.pathname).lastIndexOf('/') + 1)) + "');return false;");
								break;
							default:
								//do nothing
						}						
					}
				}else{ //outbound links
					var strLinkPath = aryLinks[aryLinks_counter].href;
					switch (intWayToAddOnClickEvent) {
						case 1:
							aryLinks[aryLinks_counter].attachEvent("onClick","gaTrackEvent(this, 'Outbound Links', '" + strLinkPath + "', '" + ((location.pathname).substring((location.pathname).lastIndexOf('/') + 1)) + "');return false;");
							break;
						case 2:
							aryLinks[aryLinks_counter].setAttribute("onClick","gaTrackEvent(this, 'Outbound Links', '" + strLinkPath + "', '" + ((location.pathname).substring((location.pathname).lastIndexOf('/') + 1)) + "');return false;");
							break;
						default:
							//do nothing
					}					
				}
			}catch(err){continue;}		
		}
	}
	
	function gaTrackEventFollowLink(link){
		if(link.target=="_blank"){ // check to see if the link openes in a new window or this one.
			window.open(link.href);
		}else{
			document.location=link.href;
		}	
	}
	
	
	function gaTrackEvent (link, category, action, label){ // function to track on the onClick event of a link and send info to Google Analytics
		try{
			pageTracker._trackEvent(category, action, label); // track the link click
			gaTrackEventFollowLink(link).delay(100);
		}catch(err){
			//error
		}
	}
	
	
	
	

