var top_level; /// Contains top level element of list
var current_menu_displayed; /// Current display level in selection mode
function hide_all () {
	$(top_level.find ('LI')).hide();
	$('#back').show();
}

function display_up_chain (item) {
	while ($(item).is ('LI')) {
		$(item).show();
		item = $(item).parent().parent();
	}
}

function process_search () {
	var value = $('#search').val ();
	// Set the mode, and restore selection mode if input empty.
	top_level.attr ('id', (value == '') ? 'selecting' : 'searching');
	if (value == '') {
		process_menu_click (current_menu_displayed);
		return;
	}
	hide_all ();
	$(top_level.find ('LI.document')).each (function (i, doc) {
		if ($(doc).text().toLowerCase().includes (value.toLowerCase())) {
			display_up_chain (doc);
		}
	});
}

function process_menu_click (item) {
	// Ignore clicks on menus in search mode.
	var value = $('#search').val ();
	if (value != '')
		return;

	// Check and handle top level/menu as a special case
	var target=$(item)
	if (!target.is ('LI')) {
		hide_all();
		current_menu_displayed = top_level;
		top_level.children().show();
	} else {
		// Update the shown level/menu
		current_menu_displayed = item;
		hide_all ();
		$(item).children ('UL').children ('LI').show();
		display_up_chain (item);
	}
}

// Mark all parent list elements are menus.
var element_number = 0;
function wire_menu_elements (item) {
	$(item).children ('LI').each (function (i, submenu) {
		var sm=$(submenu);
		var children = sm.children ('UL');
		if (children.length > 0) {
			sm.addClass ('menu');
			sm.attr ('id', 'hash' + (element_number++));
			sm.click (function (event) {
				if (event.target.id == sm.attr ('id')) {
					process_menu_click (sm);
				}
			});
			$(children).each (function (j, smulc) {
				wire_menu_elements (smulc);
			});
		} else {
			sm.addClass ('document');
		}
	});
};

$().ready (function () {
	wire_menu_elements ($('UL'));
	top_level = $($('BODY>UL')[1]);
	top_level.prepend ('<LI ID="back">&lt;&lt;&lt Back &lt;&lt;&lt;</LI>');
	current_menu_displayed = top_level;
	$('#back').click (function () {
		if ($('#search').val() != '') {
			$('#search').val ('');
			process_search();
		} else {
			process_menu_click ($(current_menu_displayed).parent().parent());
		}
	});
	$('#search').show().keyup (process_search);
	$('label[for=search]').show();
	process_search();
});


