/**
 * Callback that reacts on hash changes.
 *
 * @todo Find a way to set the active trail.
 * @todo Save each Ajax response to client side cache for some minutes.
 */

// disable Google analytics tracker
$.address.tracker(null);

$.address.change(
    function(event) {
		if (this.count == undefined) {
			this.count = 1;
		}
		
		var hash = location.hash;
		var path = (event.path == '/') ? location.pathname : event.path;
		var index, rel;
		if (hash != '' || this.count != 1) {
			$('ul.menu, li, a').each(function(i) {
				if ($(this).parent().hasClass('ajax')) {
					rel = $(this).attr('rel');
					rel = rel.slice(rel.indexOf(':') + 1);
					index = rel.indexOf('?');
					rel = (index > -1) ? rel.substr(0, index) : rel;
					if (rel == path) {
						$(this).parent().addClass('active');
					} else {
						$(this).parent().removeClass('active');
					}
				}
			});
		}
		
		if ((hash != '' || this.count != 1) && (path.substr(0, 1) == '/')) {
			$('#bodySpinner').show();

			$.get(path, {}, function(response) {
			    $('#bodyContent').html(response);
				$('#bodySpinner').hide();
			});
		} else if (hash) {
			//window.scrollBy(0, -36);
		}
		
		this.count++;
	}
);
