﻿var lastMenu;
var x_fudge = -7
var y_fudge = 3;

// show a menu
function showMenu( el )
{

    // start at the LI
    if (el.tagName=="A") el=el.parentNode;
    
    // find the nested UL
    var ul;
    for(var i=0; i<el.childNodes.length; i++)
    {
        //alert(i +": "+ el.childNodes[i].tagName);
        if (el.childNodes[i].tagName=="UL") ul=el.childNodes[i];
    }
        
    // hide previous menu
    hideMenu();
    
    // exit if no submenu
    if (typeof(ul.tagName)!="undefined") 
    {
        // update last menu
        lastMenu = ul;
        
        // position submenu and show it
        var pos = getElementPosition(el);
        setElementPosition(ul,pos[0],pos[1]);
    }
}


// hide the previous menu
function hideMenu()
{
    // exit if no last menu
    if (typeof(lastMenu)=="undefined") return;
    
    // if not object, assume ID has been passed in
    if (typeof(lastMenu)!="object") lastMenu = document.getElementById(lastMenu);
    lastMenu.style.display = 'none';
}




function getElementPosition(el)
{
    
    // if not object, assume ID has been passed in
    if (typeof(el)!="object") el = document.getElementById(el);

	// position the element (by walking up the DOM and summing all offset positions.)
	var x = 0;
	var y = el.offsetHeight;
	while (el.offsetParent && el.tagName.toUpperCase() != 'BODY')
	{
		x += el.offsetLeft;
		y += el.offsetTop;
		el = el.offsetParent;
	}
	x += el.offsetLeft;
	y += el.offsetTop;
	
	return new Array(x,y);
}

function setElementPosition(el,x,y)
{
    // if not object, assume ID has been passed in
    if (typeof(el)!="object") el = document.getElementById(el);
    
    // position element
    el.style.left = x + x_fudge + 'px';
	el.style.top = y + y_fudge + 'px';
	el.style.display = 'block';
}



// attach hide menu function to body click event
var onloadCache = window.onload;
window.onload = function()
{
	if (onloadCache) onloadCache();
	
	// get body ref
	var body = document.getElementsByTagName("body");
	body = body[0];
	
	// attach event: dom method, then msie specific
	if(window.addEventListener)
	    { body.addEventListener('click', hideMenu, false); }
	else
	    { body.attachEvent('onclick', hideMenu); }
}

