$(document).ready(function() {

	// Hide sub menus on load
	$('#nav ul').hide();
	
	// Handle clicks outside the menu
	$(document).click(function() {
	$('#nav li a').removeClass("selected");
	$('#nav ul').hide();
	});
	$('#nav').click(function(event){event.stopPropagation()});
	$('#nav ul').click(function(event){event.stopPropagation()});

	// sub menu function
	$('#nav li a').click(
	function() {

		// Highlight Active tab ONLY
		if ($(this).next().is(':hidden')) {
		$('#nav li a').removeClass("selected");
		$(this).addClass("selected");
		}

		// Hide Sub-menu if Parent menu is clicked and the sub menu is Visible
		if($(this).next().is(':visible')) {
		$(this).next().hide();
		return false;
		} else {

		// Continue...
		if( ($(this).next().is('ul')) && ($(this).next().is(':visible')) ) {
		return false;
		}

		if( ($(this).next().is('ul')) && (!$(this).next().is(':visible')) ) {
		$('#nav ul:visible').slideUp(1);
		$(this).next().slideDown(1);
		return false;
		}
		
		}

	});

});