var timeoutID, lastPop;

function unpop(e) {
	$(e).removeClass("hover").find("ul").css("display", "none");
	$(".up").removeClass("up");
}

// add a wrapper within each of the visible links.
$("#sidebar>ul>li, #sidebar>h2").wrapInner('<span class="wrapper"></span>');
// add an addition wrapper inside elements with drop down menus
$("#sidebar li:has(ul)").addClass("submenu").find(".wrapper").wrapInner('<span class="expand"></span>');	
	
$("#sidebar li.submenu").mouseenter(function() {
	var popout = $(this).find("ul").eq(0).css("display", "block");
		
	// makes the menus go up instead of down if they're lower than the bottom of the screen.
	if (popout.offset().top + popout.height() > $(window).scrollTop() + $(window).height()) {
		popout.addClass("up");	
	}
	clearTimeout(timeoutID);
}).mouseleave(	function () {
	clearTimeout(timeoutID);
	lastPop = this;
	timeoutID = setTimeout(function() { unpop(lastPop); }, 350);
});

$("#sidebar li").mouseenter( function() {
	$("#sidebar .hover").not(this).not($(this).parents()).removeClass("hover").find("ul").eq(0).css("display", "none");
	$(this).addClass("hover");
});
