$(function(){
	/* Credit: http://jquery-howto.blogspot.com/2009/06/find-select-all-external-links-with.html */
	$.expr[':'].external = function(obj){
			return obj.href && !obj.href.match(/^mailto\:/i)
							&& (obj.hostname != location.hostname);
	};

	$.expr[':'].mailto = function(obj){
			return obj.href && obj.href.match(/^mailto\:/i);
	};

	$("a:external").click(function externalLink(ev) {
		var url = $(ev.target).attr('href');
    _gat._getTrackerByName()._trackEvent('external-link', url.replace(/https?\:\/\//i, ""));
  });

	$("a:mailto").click(function mailtoLink(ev) {
		var url = $(ev.target).attr('href');
    _gat._getTrackerByName()._trackEvent('mailto-link', url.replace(/^mailto\:/i, ""));
  });

	/** This delays links to give the tracking a chance to run. We have to do this on the document
	 ** to allow any other logic which might want to prevent the default behaviour to run first, 
	 ** otherwise javascript popup code might open the link in both a pop up and in the current
	 ** window
	*/
	$(document).click(function delayLink(ev) {
		// If any modifiers are down ignore in case that means open in new tab for this browser
		// Accept we may lose some clicks in this case, but if it is actually opening in a new
		// tab we'll have time for the background request to complete anyway
		if(ev.altKey || ev.ctrlKey || ev.metaKey || ev.shiftKey) {
			return;
		}

		// TODO: We should also ideally handle the link target
		if(!ev.isDefaultPrevented() && $(ev.target).is("a:external, a:mailto")) 
		{
			console.log(ev);
			var url = $(ev.target).attr('href');
    	setTimeout('document.location = "' + url + '"', 100);
			ev.preventDefault();
			return false;
		}
	});
});

