var tw; //total width
var goingLeft = false;
var docTitle = document.title;
$(document).ready(function() {
	$("#block-menu-menu-sitemenu").find("li.expanded").hover(
		function() {
			$(this).find("ul.menu:first").css("display","block");
			var pos = $(this).find("ul.menu:first").offset();
			var ew = $(this).find("ul.menu:first").width();
			
			if(!goingLeft) {
				//flyout will fly too far out to the right
				if( ((pos.left + ew - 20)) > $(window).width() ) {
					goingLeft = true;
				}
			}
			if(goingLeft) {
				var w = $(this).width();
				var parentLIs = $(this).find("ul:first").parents('li').length;
				if( parentLIs == 1 ) { //this is the first flyout menu
					w = $(this).find("a:first").width();
					tw = ew - w;
				} else {				//these are children flyouts
					tw = w;
					tw += parseInt($(this).css("padding-right"),10) + parseInt($(this).css("padding-left"),10) + 4;
				}
				//document.title = "New left: " + (pos.left - tw);
				//if(pos.left - tw >= 0)
				$(this).find("ul.menu:first").css("left", (tw*-1)+"px");
				if($(this).find("ul.menu:first").offset().left < 0) {
					$(this).find("ul.menu:first").removeAttr("style");
					goingLeft = false;
				}
			}
		},
		function() {
			goingLeft = false;
			$(this).find("ul.menu:first").removeAttr("style"); //try left = auto
		}
	);
});