var current_menu = "";

function openMenu(element)
{
	var id = element.id;
	var popup = document.getElementById(id+"-popup");

	if(current_menu == id)
	{
		closeMenu(current_menu);
		return false;
	}
	else if(current_menu)
	{
		closeMenu(current_menu);
	}

	//  Set menu position
	elemOffsetTop = offsetTop(element);
	elemOffsetLeft = offsetLeft(element);
	popup.style.position = "absolute";
	popup.style.zIndex = 10;
	popup.style.top = (elemOffsetTop+element.offsetHeight-1)+"px";
	popup.style.left = (elemOffsetLeft)+"px";

	// Right align menu if it is going to be off screen
	if(popup.style.width)
	{
		menuWidth = parseInt(popup.style.width);
	}
	else
	{
		menuWidth = popup.offsetWidth;
	}
	if(elemOffsetLeft+menuWidth >= document.body.clientWidth)
	{
		popup.style.left = (elemOffsetLeft+element.offsetWidth-menuWidth-2)+"px";
		if(isIE)
		{
			popup.style.left = (parseInt(popup.style.left)-6)+"px";
		}
	}

	// Attach our listeners
	attachListener(popup, "mouseover", handleOverOut);
	attachListener(popup, "mouseout", handleOverOut);
	document.onclick = handleOverOut;
	
	popup.style.display = "block";

	current_menu = id;

	return false;
}

function closeMenu(id)
{
	if(!id && current_menu)
	{
		// If no id, assume current menu
		id = current_menu;
	}
	var element = document.getElementById(id);
	var popup = document.getElementById(id+"-popup");
	popup.style.display = "none";

	// Remove listeners
	removeListener(popup, "mouseout", handleOverOut);
	removeListener(popup, "mouseover", handleOverOut);
	document.onclick = "";

	current_menu = "";
}
function handleOverOut(event)
{
	if(typeof(event) != "undefined" && event.type == "mouseover")
	{
		document.onclick = "";
	}
	else
	{
		document.onclick = handleClick;
	}
}

function handleClick(element)
{
	closeMenu("");
}


