/* 

Given matching lists of links and target items, show only one item when link is clicked and hide rest.

Requires Glow 1.x.x with modules glow.dom, glow.events, and CSS to hide elements, e.g.:

	.glow-supported #items-article li.hidden { display:none }

Class "glow-supported" must be added to document.documentElement if Glow is supported, e.g. using

	<!--#include virtual="/schools/primaryhistory/includes/console-glow.sssi" -->

Adds to global namespace:

	ContentSelector

Include as:
	<script type="text/javascript" src="/schools/primaryhistory/scripts/content_selector.js"></script>

Call using glow.ready as:
	new ContentSelector(arguments)
	
where:
	argument.nav-items = selector of items containing anchors (only one anchor per list item)
	argument.items = selector of individual target items themselves

for example:
	<script type="text/javascript"> //<![CDATA[
		glow.ready(function() {
			new ContentSelector({ "nav-items": "#nav-article li", "items": "#items-article li"	});
			new ContentSelector({ "nav-items": "#nav-resources li", "items": "#items-resources > li"	});
		});
	//]]>
	</script>

*/

function ContentSelector(args) {

	this.dbg = false;

	this.ns_nav_items = glow.dom.get(args["nav-items"]);
	this.ns_items = glow.dom.get(args["items"]);

	if (this.dbg)
		alert("Found " + this.ns_nav_items.length + " link items ("+ args["nav-items"] + ")"
			+ "\nFound " + this.ns_items.length + " items (" + args["items"] + ")");

	this.init();

}
//-----

ContentSelector.prototype.init = function() {

	var that = this
		;

	this.ns_nav_items.each(function(i) {
		var ns_nav_item = glow.dom.get(this)
			, ns_anchor = ns_nav_item.get("a")
			;

		glow.events.addListener(ns_anchor, "click", on_link_click, ns_nav_item);
	});

	open_item(this.ns_nav_items.slice(0,1), this.ns_nav_items, this.ns_items);

	return this;

// FUNCTIONS

	// given a link item and list of all link items and target items,
	// open the given link and close the rest (in that order)
	// return true on success
	function open_item(ns_nav_item, ns_nav_items, ns_items) {

		var re_target_id = /(#[^#]+)$/ // get target id
			, a_matches = null // will hold matched target id
			;

		ns_nav_items.removeClass("selected");

		a_matches = re_target_id.exec(ns_nav_item.get("a").attr("href"));
		if (!a_matches) 
			return false;

		var ns_target_item = glow.dom.get(a_matches[1]);

		ns_target_item.removeClass("hidden");

		ns_items.each(function(i) {
			if (that.dbg) alert("Hiding item "+this.className + " : " + this.id);

			if (this != ns_target_item[0])
				glow.dom.get(this).addClass("hidden");
		});

		ns_nav_item.addClass("selected");

		return true;

	}
	//-----

	function on_link_click(glow_evt) {

		var ns_nav_item = this;

		if (!ns_nav_item.hasClass("selected"))
			if (!open_item(ns_nav_item, that.ns_nav_items, that.ns_items))
				return true; // allow default link action

		return false; // disable link
	}
	//-----

}
//-----


// end of script
