/**************************************************************************
* AJAX / Hash changer script
*
* Scott Wespi (scott@darkstardesign.com)
*
* Requires jQuery
**************************************************************************/
(function($){
	var settings = {ajax_target: 'ajax-target', index: 'index', onHashChange: false, onGPComplete: false, get: {}};
	var data = {alias: '', pendingAlias: '', loading: false, cache: {}, cache_count: 0};
		
	var methods = {
		init: function(options) {
			if (options) $.extend(settings, options);			
			$(window).hashchange(priv_methods._hashChange);
			if (window.location.hash.length == 0) {
				window.location.hash = '#/';
			} else {
				priv_methods._hashChange();
			}
		},
	
		getPage: function(alias, callback) {
			data.loading = true;
			data.alias = alias;
			if (data.cache[alias]) {
				priv_methods._gpComplete.call(data.cache[alias]);
			} else {
				var d = {'alias': alias};
				$.extend(d, settings.get);
				$.ajax({
					url: settings.ajax_target, 
					data: d,
					type: 'GET',
					success: function(d, x, y) {
						priv_methods._gpComplete.call(d);
					}
				});
			}
		},
		
		getData: function(key) {
			return data[key];
		},
		
		setData: function(key, value) {
			data[key] = value;
		}
	};
	
	var priv_methods = {		
		_hashChange: function() {
			var h = window.location.hash.substring(2); // drop #/ from the front
			if (h.length == 0) h = settings.index;
			
			data.pendingAlias = h;
			
			if (settings.onHashChange) {
				if (settings.onHashChange.call(data)) methods.getPage(data.pendingAlias, priv_methods._gpComplete);
			} else {
				methods.getPage(data.pendingAlias, priv_methods._gpComplete);
			}
		},
		
		_gpComplete: function() {
			data.loading = false;
			if (!data.cache[this.data[0].alias]) {
				data.cache[this.data[0].alias] = this;
				data.cache_count += 1;
			}
			if (settings.onGPComplete) settings.onGPComplete.call(this);
		}
	};

	$.fn.dsdHashJax = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.dsdHashJax' );
		}
	};
})(jQuery);
