﻿var posx = 0;
var posy = 0;
var OpenedMenu = "";

//
// Open a popup menu
//
function ShowMenu(imgEl, id) {
    coord = getPageCoords(imgEl);

    var el = document.getElementById(id + "Menu");
    el.style.top = (coord.y + imgEl.offsetHeight) + "px";
    el.style.left = (coord.x) + "px";
    el.style.display = 'block';

    if (OpenedMenu != "" && OpenedMenu != id) {
        HideOpenMenu();
    }
    
    OpenedMenu = id;
    MenuTimerID = setTimeout("MenuCheck()", 10);
}

//
// Close the current menu
//
function HideOpenMenu() {
    document.getElementById(OpenedMenu + "Menu").style.display = 'none';
    OpenedMenu = "";
}

//
// Check the popup menu and close it when ready
//
function MenuCheck() {
    // Grab the element that is under the mouse
    var el = document.elementFromPoint(posx, posy);
    var id = el.id;
    
    // Check if is belonds to the current menu
    if (id.indexOf(OpenedMenu) == -1) {
        // This element doesn't belong to the menu, close the menu
        HideOpenMenu();
    }
    else {
        // Clear the current setup the highlight
        MenuHighlight(id);

        // Add back the timer        
        MenuTimerID = setTimeout("MenuCheck()", 20);
    }
}

//
// Highlight the popup menu's items
//
function MenuHighlight(id) {
    // Grab all the items from the popup menu
    var myEl = document.getElementById(OpenedMenu + "Menu");
    if (myEl != null) {
        var items = myEl.getElementsByTagName("img");

        // Highlight the item that the mouse is over
        for (i = 0; i < items.length; i++) {
            var el = items[i];
            var imageURL = el.src.substr(0, el.src.length - 5);
            if (el.id == id) {
                el.src = imageURL + "Y.png";
            }
            else {
                el.src = imageURL + "N.png";
            }
        }
    }
}

//
// Get the top left position of the passed element
//
function getPageCoords(element) {
    var coords = { x: 0, y: 0 };
    while (element) {
        coords.x += element.offsetLeft;
        coords.y += element.offsetTop;
        element = element.offsetParent;
    }
    return coords;
}

//
// Update the mouse cursor's location
//
function UpdateMousePos(e) {
	if (!e) var e = window.event;
    if (e.clientX || e.clientY)
	{
	    posx = e.clientX;  + document.body.scrollLeft + document.documentElement.scrollLeft;
	    posy = e.clientY;  + document.body.scrollTop + document.documentElement.scrollTop;
	}
	else if (e.pageX || e.pageY)
	{
	    posx = e.pageX;  //- document.body.scrollLeft - document.documentElement.scrollLeft;
	    posy = e.pageY;  //- document.body.scrollTop - document.documentElement.scrollTop;
	}
}

