 
var display = 'inline';

function showHide(id,show) {
	
	//hide all rows under this class...
	
	var child = $("#sideNav li."+id);
	
	child.each(function(index) {
		
		pId = 'p' + $(this).attr('id').replace('i','');
				
		if (show === false) {
			
			this.style.display = 'none';
					
		} else {
			
			this.style.display = display;
			
		}
		
	});
	
}

$(document).ready(function(){
	
	//get the top levels
	
	var links = $('#sideNav li a');
	
	if (typeof(links[0]) == 'undefined') return false;
		
	$(links).each(function(index) {
		
		//now see if it has chidren and hide the ones with them
				
		if ($(this).parent().hasClass('p0') === false) {
			
			//item has click state
			
			$(this).click(function() {
							
				var pId = 'p' + $(this).parent().attr('id').replace('i','');
								
				//does it have any children?
				
				return show_children(pId);
																
			});
			
			//hide children
			
			var pId = 'p' + $(this).parent().attr('id').replace('i','');
			
			showHide(pId,false);
		
		} else {
		
			display = this.style.display;
		
		}
	
	});
	
	showSelected();
	
});


function show_children(pId) {

		
	if ($("#sideNav li."+pId).length > 0) {
		
		//console.log(this);
		
		var oId = pId.replace('p','i');
		
		if ($('#'+oId).hasClass('expanded')) {
						
			//$(this).removeClass('expanded');
			
			//showHide(pId,false);
			
			return true;
			
		} else {
		
			$('#'+oId).addClass('expanded');
		
			showHide(pId,true);
			
			//return false;
			
		}
		
		return true;
		
	}

}


function showSelected() {
	
	var selected = $('#sideNav li.selected');
	
	if ($(selected).hasClass('p0') === false ) {
		
		selected.css('display',display);
		
		var pId = 'p' + selected.attr('id').replace('i','');
		
		//show the same level!
				
		showHide(pId,true);
				
		var lvl = selected.attr('class').match(/\bp[0-9]*/);
		
		if (typeof(lvl[0]) != 'undefined') {
			
			lvl  = lvl[0];
			
			show_parent(lvl);
			
		}
			
	}
	
}
  
function show_parent(lvl) {

	showHide(lvl,true);
	
	//now get the i id of the parent and show that and then show the same level and it's parents....
	
	var id = lvl.replace('p','i');
		
	var lvl = $('#'+id).attr('class').match(/\bp[0-9]*/);
	
	$('#'+id).addClass('expanded');
	
	if (typeof(lvl[0]) != 'undefined') {
		
		lvl  = lvl[0];
		
		if (lvl != 'p0' ) {
		
			show_parent(lvl);
			
		}
		
	}

}
