// Close all inactive submenus on start, and allow submenu display to toggle

"use strict";

// open anonymous function
(function()
{
	function toggle()
	{
		// find first submenu of parent
		var ulObj = this.parentNode.getElementsByTagName('ul')[0];
		if (!ulObj)
			return false;
		var ulStyle = ulObj.style;
	
		var menuText = this.firstChild;
	
		// toggle menu marker display
		if (ulStyle.display == 'none')
		{
			// '' resets to defaut
			ulStyle.display = '';
			// remove arrow; replace() does not work, perhaps because entities are already replaced
			menuText.nodeValue = menuText.nodeValue.substring(0, menuText.nodeValue.length-1) + ' ';
		}
		else
		{
			ulStyle.display = 'none';
			menuText.nodeValue = menuText.nodeValue.substring(0, menuText.nodeValue.length-1) + '\xBB';
		}
	
		this.blur();	// needed to remove 'outline' after click
		
		return false;  // disable link activation
	}

	// close inactive menus

	var window_location_dir = window.location.pathname.replace(/[^\/]*$/, '');

	var aMenu =  document.getElementById('sidebar-menu').getElementsByTagName('a');

	for (var a_num = 0; a_num < aMenu.length; a_num++)
	{
		// format is submenu-'path'
		if (/\bsubmenu\b/.test(aMenu[a_num].className))
		{
			// set onclick handlder for submenu 'a' tags
			// we assign so the object owns the event, e.g. 'this'
			// http://www.quirksmode.org/js/this.html
			aMenu[a_num].onclick = toggle;
	
			// add space and spot for arrow
			aMenu[a_num].firstChild.nodeValue += '  ';

			// get all child 'a' records
			var aChildren = aMenu[a_num].parentNode.getElementsByTagName('a');

			var dir_match = false;

			// If any submenu a.href directory matches our window url, show the submenu
			// zero is our own submenu
			for (var a_child_num = 0; a_child_num < aChildren.length; a_child_num++)
			{
				if (/\bsubmenu\b/.test(aChildren[a_child_num].className))
					continue;

				// remove file part of patch; only compare directories
				// in case we are viewing a file that isn't on the menu
				// but in the same directory as a menu file
				var a_child_path = aChildren[a_child_num].href.replace(/[^\/]*$/, '');
				a_child_path = a_child_path.replace(/^.*\/\/[^\/]*\//, '/');

				// does the 'a' directory match our current window path?
				if (a_child_path == window_location_dir.substr(0, a_child_path.length))
				{
					dir_match = true;
					break;
				}
			}

			if (!dir_match)
				// close menu
				toggle.call(aMenu[a_num]);
		}
		// there can be multiple matching menus, so no 'break'
	}

	/* there is a delay in the update of the submenus when loading blogs */

// close anonymous function
})();


