(function($){
	
/*

copyright 2008 rebecca murphey
http://blog.rebeccamurphey.com
licensed under creative commons share alike 3.0: http://creativecommons.org/licenses/by-sa/3.0/
usage instructions at http://blog.rebeccamurphey.com

*/

$.fn.clicktrack = function(config) {
	
	if (typeof(config) == 'string') { 
		var options = { remoteScript: config }; 
	} else if (typeof(config) == 'object') {
		var options = config;
	} else {
		return $(this); // need to have a remote script to do anything; abort if we don't have one
	}

	// you can override the defaults by passing a configuration object when calling the plugin. 
	// for example: 
	//
	//		$('a.clicktrack').clicktrack({remote_script: 'foo.php', sendOnce: false});
	//
	// this will send the clicktrack to the server every time the link is clicked, rather than sending it once
	
	var defaults = {
		remoteScript: null,	// the location of the remote script on your server; 
								// this can also be passed as a string argument (see above)
		prefix: 'ct_',			// the prefix for additional class names that should be passed to the server  
		extraData: null,		// extra data to be sent to the remote script
		callback: function() {},	// a callback function to be executed when the remote script succeeds
		dataType: 'json',			// the format of the data you expect to get back from the remote script
		sendOnce: true,			// whether clicktracks should be sent once (true) or for every click (false)
		preventDefault: false	// whether clicks on clicktrack links should be prevented from taking the user to another page (true)
								// or be followed as expected (false)
	};
	
	var settings = $.extend(defaults,options,true);
	
	var source = document.location.toString();
	
	return $(this).click(function(e) {
		
		if (settings.preventDefault) { e.preventDefault(); }

		var $this = $(this);

		
		if (! $this.hasClass('js_no_clicktrack')) {

			if (settings.sendOnce) { $this.addClass('js_no_clicktrack'); }

			var href = $this.attr('href');
	
			var classNames = $this.attr('class').split(' ');
			var classArray = [];
	
			$.each(classNames, function(i,v){
				if (v.match(settings.prefix)){
					classArray.push(v);
				}
			});
	
			var default_data = {
				classes: classArray,
				source: source,
				target: href
			};
	
			var clicktrack_data = $.extend(default_data,settings.extraData);
			
			$.post(
				settings.remoteScript,
				clicktrack_data,
				settings.callback,
				settings.dataType
			);
		}
		
		if (settings.preventDefault) { return false; } else { return true; }
		
		window.location = href; 
	})	
}

})(jQuery)
