$(document).ready(function () {
	// add buttons to menu
	$("#nav_categories div").each(function() {addMenuButton($(this));});	
});

function addMenuButton(button) {
	var basebackcolor = "#606060";
	var backcolor = basebackcolor; 

	if ($(button).hasClass('colour_Pink')) {
		var hovercolor = "#997CBE";
	}
	else {	
		var hovercolor = "#77A2A6";
	}	
	
	$(button).data('backcolor', backcolor);
	$(button).data('hovercolor', hovercolor);
	$(button).data('menuDisplayed', false);

	// if this is the current category..
	if ($(button).hasClass('current_cat')) {
		// display any submenu it has and also open up any parent menus
		$(button).next('ul').css('display', 'block');
		$(button).data('menuDisplayed', true);
		$(button).parents('ul').css('display', 'block');

		// set the background color of this button and parent buttons to be initial on state
		$(button).css('background-color', hovercolor);
		$(button).data('backcolor', hovercolor);

		$(button).parents('ul').each(function() {
			var p_button = $(this).parent('li').children('div');
			$(p_button).css('background-color', hovercolor);
			$(p_button).data('backcolor', hovercolor);
			$(p_button).data('menuDisplayed', true);
		});		
	}

	// toggle menu slide and set the background mouse out colour
	$(button).click(function() {		
		var menu = $(this).next('ul');
		// don't do any work if we don't have a submenu
		if (menu.length == 0) {return;}
		// toggle the submenu
		$(menu).slideToggle("medium");
		
		// is the menu displayed?
		var menuDisplayed = !$(button).data('menuDisplayed');
		$(button).data('menuDisplayed', menuDisplayed);

		// set the background colour to the hover color so the button stays 'stuck on' while menu is open
		if (menuDisplayed) {
			$(button).data('backcolor', hovercolor);
		}
		else {
			$(button).data('backcolor', basebackcolor);
		}

		// if this menu is displayed, then we want to toggle the other sibling buttons to hide any menu that is open
		if (menuDisplayed) {
			$(this).parent().siblings('li').each(function() {
				var nextbutton = $(this).children('div');				
				$(nextbutton).css("background-color", basebackcolor);
				$(nextbutton).data('backcolor', basebackcolor);
				var siblingMenuDisplayed = $(nextbutton).data('menuDisplayed');
				$(nextbutton).data('menuDisplayed', false);
				
				// hide sibling menu if its open
				if (siblingMenuDisplayed) {$(this).children('ul').slideToggle('medium');}				
			});
		}		
	});

	// background colour change
	$(button).hover(
		function() {
			$(this).css("background-color", $(this).data('hovercolor'));
		},
		function() {
			$(this).css("background-color", $(this).data('backcolor'));
		}
	);
}