/*
 * The basic Google Analytics configuration only tracks clicks on internal links
 *
 * In order to track clicks on links that lead away from your site, you need to add an onClick event
 * handler to that link.
 *
 * This script will find external links automatically for you and add the relevant GA code
 *
 * Requires:
 *  Google Analytics
 *  jQuery
 *
 * parseUri code orignally by Steven Levithan <stevenlevithan.com>, used under MIT License
 * and modified for simplification
 *
 * This code free to all users for any use. Just don't be a jackass and pretend that you wrote it
 *
 * Dan Rumney <dancrumb@danrumney.co.uk>
 */

function EnableGA(tracker,mappings)
{
	this.tracker = tracker;
	this.mappings = mappings;
	
	this.parseOptions = {
		key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
		q:   {
			name:   "queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},
		parser: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/
	};
	
	var thisObj = this;
    $(document).ready(function(){thisObj.enable()});
}

EnableGA.prototype.enable = function()
{
	if(this.tracker)
	{
		var oThis = this;
		$("a").each(function()
		{
			var target = $(this).attr("href");
			if((target != null) && (target != ""))
			{
				var URL = oThis.parseUri(target);
				if ((URL.host == "") || (URL.host.search(window.location.hostname)>=0))
				{
					// Do nothing. Google Analytics already tracks local files
				}
				else
				{
					var pseudoLoc = oThis.getPseudoLoc(URL);
					if(pseudoLoc)
					{
						$(this).bind('click',function(evt)
						  {
							  evt.preventDefault();
							 // var pseudoLoc = oThis.getPseudoLoc(URL);
							  //pageTracker._trackPageview(pseudoLoc);
							  console.log(pseudoLoc);
							  evt.stopPropagation();
						  });
					}
				}
			}
		});		
	}
};

EnableGA.prototype.getPseudoLoc = function(url)
{
	//console.log(url);
	var response = "/UNK/"+[url.host,url.directory,url.file].join('');
		
	jQuery.each(this.mappings, function(plDir,regExp)
			{
				if(regExp.test(url.host))
				{
					if((url.path == "/") && (url.file == ""))
					{
						response = "/"+plDir+"/root";
					}
					else
					{
						response = "/"+plDir+"/"+[url.directory,url.file].join('/');
					}
				}	
			});
	
	return response;
};


EnableGA.prototype.parseUri = function(str)
{
	var	o   = this.parseOptions,
		m   = o.parser.exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};
