$(document).ready(function () {	
	checkURL();	//check if the URL has a reference to a page and load it
	setInterval("checkURL()",250);	//check for a change in the URL every 250 ms to detect if the history buttons have been used
	
	$('.card').live('click', function (event){
		var menuClicked = $(this).attr('id');
		var trigger = menuClicked + "Drop";		
		var url = window.location + "#" + menuClicked;			
		hideCards();	
		window.location = url;

		dropMenu(trigger);
		
		return false;
	});	

/* ...... Sub menu accordian manipulation! ...... */	
$('.menuType').live("click", function (event){
		var menu = $(this).attr('id');
		dropMenu(menu);
	});	

/* ...... Filter menu results client side! ...... */	

	 var $visMenu = $('#menuStage');     	 
	 $('ul.subMenu li').live("click", function(event) { 
	   	$('ul.subMenu li').removeClass('selected'); // remove the "selected" class from all items
	    var $this = $(this),  
	         type = $this.attr('class'); 	    
	    var title = $this.attr('title');
	    var header = "<div class='menuHeader'>" + title + "</div>"
	    
	     $visMenu.children()
	         .hide()  
	         .filter('.' + type)  
	         .show();  
	     $visMenu.children(':nth-child(1)').before(header);
	 	$(this).addClass('selected');	     
	     
	     return false;  
	 });
});
var current;
function dropMenu(menu){	
	if( menu != current){ // dont reopen menu if its already open
  		$('#'+current).children('ul').slideToggle('slow'); // hide current
  		if($('#'+menu).children().length != 0){ // make sure the menu has sub options
			$('#'+menu).find('ul').slideToggle('slow');
			$('.navMenu ul li ul li').removeClass('selected');
			$('#'+menu)
				.find('ul')
				.children(':nth-child(1)')
				.addClass('selected');
		}
	current = menu;
	}
}
function hideCards(){
	$('#cardList').css('display', 'none');
	$('#main.menus').css('background', 'none');
	$('.hidden').css('display', 'block');
	//$('#menuNav.navMenu').load('navMenu.html');
}
var lasturl = "";	//here we store the current URL hash
function checkURL(hash){
	if(!hash) hash = window.location.hash;
	if(lasturl == "" && hash != "")hideCards();
	if(hash != lasturl){
		lasturl = hash;
		if(hash == ""){
			$('#cardList').css('display', 'block');
			$('.hidden').css('display', 'none');
	 		$('#main.menus').css('background', '#282828');
		}
		else
		$('#menuStage').html('<br /><br /><div class="menuHeader">LOADING...</div><br /><br />');
		loadPage(hash);
	}

}
function loadPage(url){
	url = url.replace('#','');	//strip the # and leave only the page name
	$.ajax({	
		type: "POST",
		url: "loader.php",
		data: 'page='+url,	//with the page title as a parameter
		dataType: "html",	//expect html to be returned
		success: function(msg){
			if(parseInt(msg)!=0){	//if no errors
				$('#menuStage').html(msg);	//load the returned html into main div
			}
		}
	});
}