﻿Event.observe(window, 'load', function() {
	PopulateTerms(g_aTerms);
	Event.observe("divTerms", 'mousedown', OnChooseTerm);
	Event.observe("divTerms", "selectstart", function() { return false; });
	if (Prototype.Browser.Gecko)
	{
		setInterval(function()
		{
			var strHash = window.location.hash;
			strHash = strHash && strHash.substr(0, 1) == '#' ? strHash.substr(1) : strHash;
			if (strHash && strHash != g_strCurrentTerm)
				DisplayTerm(strHash);
		}, 500);
	}
});

var g_strCurrentTerm = "";

function OnChooseTerm(evt)
{
	var strId = Event.element(evt).id;
	if (strId != "divTerms")
		DisplayTerm(strId);
}

function PopulateTerms(aTerms)
{
	// not necessary to dynamically generate the side-menu; we had to put it in statically to support non-JS users
	// $("divTerms").innerHTML = aTerms.collect(function(objTerm) { objTerm.id = objTerm.URL.substr(0, objTerm.URL.length - 4); return ["<a class='term' id='_", objTerm.id ,"' href='#", objTerm.id, "'><img width='75' height='38' id='__", objTerm.id, "' src='thumbnails/", objTerm.id, ".jpg' />", objTerm.Title, "<div class='clear'></div></a>"].join(""); }).join("");

	// start them all off as hidden
	aTerms.each(function(objTerm) { objTerm.id = objTerm.URL.substr(0, objTerm.URL.length - 4); $(objTerm.id).style.display = "none"; });

	// if something in the anchor matches a term, display it; otherwise display the first item
	var strSearch = window.location.hash && window.location.hash.substr(0, 1) == '#' ? window.location.hash.substr(1) : window.location.hash;
	if (strSearch && aTerms.any(function(objTerm) { return objTerm.URL == strSearch + ".htm"; }))
		DisplayTerm(strSearch, true);
	else
		DisplayTerm(aTerms[0].URL.substr(0, aTerms[0].URL.length - 4), true);
}

function DisplayTerm(strTermID, bHideAnchor)
{
	// strip the single or double underscore prefix, but still allow underscores in the strTermID
	if (strTermID.startsWith("_")) strTermID = strTermID.substr(1, strTermID.length - 1);
	if (strTermID.startsWith("_")) strTermID = strTermID.substr(1, strTermID.length - 1);
		
	// style the new term as selected & unstyle the old one
	if ($("_" + g_strCurrentTerm)) $("_" + g_strCurrentTerm).removeClassName("current");
	if ($("_" + strTermID))
		$("_" + strTermID).addClassName("current");
	
	//new Ajax.Updater("entry", strTermID + ".htm", { method: "get" });
	if ($(g_strCurrentTerm))
		$(g_strCurrentTerm).style.display = "none";
	if ($(strTermID))
		$(strTermID).style.display = "block";
	
	g_strCurrentTerm = strTermID;
	if (!bHideAnchor)
		window.location.hash = strTermID;
}