/**
 * Hash Navigation module monitors the URL hash for changes, and executes a
 * provided function when such changes are detected.
 * 
 * @author    Tharsan Bhuvanendran <tbhuvanendran@360i.com>
 * @copyright 360i
 * @version   1.0
 * @revision  $Id$
 */

var hashNav = {
	/**
	 * Time interval between checking for a change in the URL hash (in ms).
	 * 
	 * @var int
	 */
	monitorInterval: 100,

	/**
	 * Last observed URL hash value.
	 * 
	 * @var string
	 */
	lastHash: '',

	/**
	 * Callback function to be executed when a hash change has been detected.
	 * 
	 * @var function
	 */
	onHashChange: null,

	/**
	 * Setup the Hash Navigation module.
	 * 
	 * @param callback A function to be executed when a hash change has been detected.
	 * @monitorInterval The Time interval between checking for a change in the URL hash (in ms).
	 * @returns nothing
	 */
	init: function(callback, monitorInterval) {
		if($.isFunction(callback))
			hashNav.onHashChange = callback;

		if(monitorInterval)
			hashNav.monitorInterval = monitorInterval;

		// look for an anchor tag in the current URL
		if(location.href.indexOf('#/') > -1 && hashNav.onHashChange)
			hashNav.onHashChange(location.href.substring(location.href.indexOf('#/')+2));

		hashNav.checkHash();
	},

	/**
	 * Check the current URL hash against the last observed URL hash for a change.
	 * When a different has is encountered, execute the configured callback function.
	 * 
	 * @returns nothing
	 */
	checkHash: function() {
		if(location.hash != hashNav.lastHash && location.hash.indexOf('#/') > -1)
			hashNav.onHashChange(location.hash.substring(location.hash.indexOf('#/')+2));

		hashNav.lastHash = location.hash;
		setTimeout(hashNav.checkHash, hashNav.monitorInterval);
	}
}

