SWITCH_CONTAINER = 'span'
DEAD_SWITCH = '&bull;'

function switch_on(el) {
	el.html = "+"
}

function switch_off(el) {
	el.html = "-"
}

function prepare_menu(div) {
	if (location.href.match(/preview/)) { return }
	div = $("#" + div)
	div.find('li').attr('onclick', 'expand(this)')
	setToggles(div)
	open_menu(div)
}

function open_menu(div) {
	if (loc.match(/preview/)) { PREVIEW = 'true'}

	current = find_list_item(div, location.href)
	
	if (current) {
		function bubbleUp(li) {
			expand(li);
			if (li.parent().parent().is('li')) {
				bubbleUp(li.parent().parent());
			}
		}
		bubbleUp(current);
	}
}

function setToggles(el) {
	$.each(el.find('li'), 
		function(i, li) {
			if (!hasChildren(li)) {
				li.children(SWITCH_CONTAINER).html(DEAD_SWITCH);
				li.children(SWITCH_CONTAINER).css('cursor', 'default');
				li.children(SWITCH_CONTAINER).attr('class', 'dead')
				li.removeAttr('onclick')
			}
		});
}

function collapse(e) {
	e = $(e)
	if (hasChildren(e)) {
		switch_on(e.children(SWITCH_CONTAINER));
		e.children('ul:first').css('display', 'none');
		e.attr('onclick', 'expand(this)')
	}
}

function expand(e) {
	e = $(e)
	if (hasChildren(e)) {
		switch_off(e.children(SWITCH_CONTAINER));
		e.children('ul:first').css('display', 'block');
		e.attr('onclick', 'collapse(this)')
	}
	
	$.each(e.siblings('li'), function(i, li) { collapse(li) } )
}

function hasChildren(el) {
	return (el.children('ul').length > 0 && el.children('ul').children('li').length > 0)
}