/*
A simple little script that will manage the class attributes of navigation
links as the user clicks around. The use case here is that the page does NOT
reload and clicking on a link will just update a iframe or portion of the
page using Ajax

When a link in the navigation is clicked the latest grandchild <li> of the
closest <li> ancestor will be given the class "on". All other <li> ancestors
of the "on" <li> will be given the class "open". All other <li> in the
navigation scope will have "on" and "open".

Also any links in the "on" state will be disabled until that "on" state is
removed.
*/

var NavMarker = Class.create();
Object.extend(NavMarker.prototype, {
	initialize: 	function(navigation_tree) {
		// Save elements for quick reference
		this.navigation_tree = $(navigation_tree);
		this.nodes = $$('#'+this.navigation_tree.id+' li');

		// For disabling "on" links
		this.disable_link = (function(event) {
			Event.stop(event);
		}).bindAsEventListener(this);

		// Register event handlers
		this.nodes.each((function(node) {
			Event.observe(node, 'click',
				this.click.bindAsEventListener(this));
		}).bind(this));
	},
	click:		function(event) {
		// Clear previous state
		this.nodes.each((function(node) {
			node.addClassName('closed');
			node.removeClassName('open');
			node.removeClassName('on');
			this.removeDisableLinks(node);
		}).bind(this));

		// Find bottom most <li> from the element clicked
		var clicked_element = Event.element(event);
		var node = clicked_element.tagName.toLowerCase() == 'li' ?
			clicked_element : clicked_element.up('li');
		while( node.down('li') ) {
			node = node.down('li');
		}

		node.addClassName('on');
		this.addDisableLinks(node);
		var ancestor = node;
		while(ancestor = ancestor.up('li')) {
			if( !ancestor.descendantOf(this.navigation_tree) ) break;
			ancestor.addClassName('open');
			ancestor.removeClassName('closed');
		}
	},
	addDisableLinks:		function(node) {
		$A(node.getElementsByTagName('a')).each((function(link) {
			Event.observe(link, 'click', this.disable_link);
		}).bind(this));
	},
	removeDisableLinks:	function(node) {
		$A(node.getElementsByTagName('a')).each((function(link) {
			Event.stopObserving(link, 'click', this.disable_link);
		}).bind(this));
	}
});
