$(document).ready(function() {
	var create_toggles = true;
	// Prepare the menu.
	if (create_toggles && $('.n .sitemap ul li.menu'))
	{
		// Get all link elements that are direct descendants of list item elements that act as menus.
		// And add a toggle button to each element.
		var menu_item_heights = [];
		var menu_item_states = [];
		$('.n .sitemap ul li.menu > a').each(function(){
			if ($(this).parent().hasClass('open'))
			{
				$(this).before('<a class="sitemap-menu-toggle" tabindex="0"><span>&#8722;</span></a>');
			}
			else
			{
				$(this).before('<a class="sitemap-menu-toggle" tabindex="0"><span>+</span></a>');
			}
			// Temporarily open the menu to get the height of the toggle. This cannot be done while the element is hidden.
			$(this).parent().parent().addClass('sitemap-toggle-height-helper');
			menu_item_heights[menu_item_heights.length] = $(this).height();
		});
		//alert(menu_item_heights);
		var i = 0;
		$('.n .sitemap ul li.menu > a.sitemap-menu-toggle').each(function(){
			$(this).parent().parent().removeClass('sitemap-toggle-height-helper');
			$(this).addClass('sitemap-toggle-reset');
			$(this).height(menu_item_heights[i]);
			$(this).custom_height_property = menu_item_heights[i];
			$(this).addClass('sitemap-toggle');
			i = i + 1;
		});
		$('.n .sitemap ul li.menu > a.sitemap-menu-toggle').click(function(){
			//alert($(this).custom_height_property);
			// Check heights of contained elements.
			//$('a', $(this)).each(function(){
			//	alert($(this).custom_height_property);
			//	$(this).height($(this).custom_height_property);
			//});
			$(this).parent().toggleClass('open');
			if ($(this).parent().hasClass('open'))
				$('span', $(this)).replaceWith('<span>&#8722;</span>');
			else
				$('span', $(this)).replaceWith('<span>+</span>');
			return false;
		});
		// Set the key event.
		$('.n .sitemap ul li.menu > a.sitemap-menu-toggle').keyup(function(event) {
			if (event.keyCode == 13 || event.keyCode == 32) // Return/enter or space.
			{
				$(this).parent().toggleClass('open');
				if ($(this).parent().hasClass('open'))
					$('span', $(this)).replaceWith('<span>&#8722;</span>');
				else
					$('span', $(this)).replaceWith('<span>+</span>');
				return false;
			}
		});
		$('.n .sitemap ul li.menu > a.sitemap-menu-toggle').mouseover(function(){
			if (!$(this).hasClass('hover'))
				$(this).addClass('hover');
		});
		$('.n .sitemap ul li.menu > a.sitemap-menu-toggle').mouseout(function(){
			if ($(this).hasClass('hover'))
				$(this).removeClass('hover');
		});
	}
});
