// Hash highlighting

"use strict";

(function()
{
	// highlight and return the specified hash
	function highlight_active_hash(hash)
	{
		if (!hash)
			return null;
	
		var id = document.getElementById(hash);
		if (id)
		{
			id.className += (id.className ? ' ' : '') + 'active-hash';
			return id;
		}
		return null;
	}

	// Set onclick handlers for all current hash URLs on the page
	// closure allows us to save the last active hash
	var last_active_hash = null;

	var aList = document.getElementsByTagName('a');

	for (var a_num = 0; a_num < aList.length; a_num++)
	{
		var aObj = aList[a_num];

		// document.location gives us the redirected URL, not original
		// Can't use document.location.replace directly because it redirects
		var redirect_location = String(document.location);

		// Does the URL have a hash that is on our page?
		if (aObj.href &&
		    /#./.test(aObj.href) &&
		    aObj.href.replace(/^([^#]*).*$/, '$1') ==
		    redirect_location.replace(/^([^#]*).*$/, '$1'))
		{
			// add onclick handler
			aObj.onclick = function()
			{
				// remove previous hash highlighting
				if (last_active_hash != null)
				{
					last_active_hash.className =
						last_active_hash.className.replace(/\bactive-hash\b/, '');
					last_active_hash = null;
				}

				var hash = this.href.replace(/^.*#/, '');
				last_active_hash = highlight_active_hash(hash);

				return true;
			};
		}
	}

	// highlight an id based on the current URL hash
	var hash = window.location.hash.substr(1)
	last_active_hash = highlight_active_hash(hash);
})();

