// Version 1.3
// Allows CMS downloads to track file paths
// Version 1.2
// Fixed an issue where directly uploaded files weren't tracked.

var trackDownloads = true;
var trackExternalLinks = false;
var trackMailToLinks = false;
	
var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i;
//var cmsdownload = /_@@_(.*)\&/i;
var cmsdownload = /viewfile\.as(p|h)x\?filepath=(.*)\&/i;

// on page load, start adding our events to links
var $j = jQuery.noConflict();

$j(document).ready(function(){
	if(pageTracker){

		$j("a").each(function() {
			var href = $j(this).attr('href');
			if (href) {
				// check whether we're dealing with an external link
				if ((href.match(/^https?\:/i)) && !(location.hostname.replace("www.", "").match(this.hostname.replace("www.", "")))) {
					
					if (trackExternalLinks) {
						$j(this).click(function(event) {
							var extLink = href.replace(/https?:\/\/(.*)/,"$1");		// remove the leading 'http' from the link
							pageTracker._trackPageview('/external/' + extLink);
						});
					}
					
				} else if (href.match(/^mailto\:/i)) {  	// otherwise if it's a mailto link
				
					if (trackMailToLinks) {
						$j(this).click(function(event) {  
							var mailLink = href.replace(/^mailto\:/i, '');  
							pageTracker._trackPageview('/email' + mailLink);  
						});
					}
					
				} else if (href.match(cmsdownload)) {	// otherwise it might be a CMS download
		
					if (trackDownloads) {
						$j(this).click(function(event) {  
							var filePath = cmsdownload.exec(href)[2]; // extract the file path from the link
							if (filePath.indexOf('\\') != -1)
							{
							  filePath = filePath.substring(filePath.lastIndexOf('\\')+1); // grab the filename from the path
							//} else {
							  //filePath = filePath.substring(filePath.lastIndexOf('/')+1);  // grab the filename from the path
							}
							//var extension = (/[.]/.exec(filePath)) ? /[^.]+$/.exec(filePath) : undefined;  
							pageTracker._trackPageview('/download/' + filePath);  
						});  
					}
				
				} else if (href.match(filetypes)) {  // or if it's one of our download filetypes
				
					if (trackDownloads) {
						$j(this).click(function(event) {  
							//var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;  
							var filePath = href.replace(/^https?\:\/\/[-\d]+\//i, '');  
							pageTracker._trackPageview('/download/' + filePath);  
						});  
					}
				} 
			}
		});
	}
});

