﻿doc.scripts['openMenu'] =  openMenu;

window.onload = function () { doc.runScripts() };

function openMenu()
{
    
    var menus = doc.css('menu');
    
    for (var i = 0; i < menus.length; i++)
    {
        function loopItems(items)
        {
            for(var j = 0; j < items.length; j++)
            {
                doc.setFunction(items[j], 'mousemove', openUnderlying);
                doc.setFunction(items[j], 'mouseout', timeOut);
                var sublists = items[j].getElementsByTagName("ul");
                for(var k = 0; k < sublists.length; k++)
                {
                    doc.setFunction(sublists[k], 'mousemove', killTimeOut);
                    doc.setFunction(sublists[k], 'mouseout', timeOut);
                }
            }
        }
        
        loopItems(menus[i].getElementsByTagName("li"));
        loopItems(menus[i].getElementsByTagName("a"));
    }
}

function openUnderlying(e)
{
    var rootElement = doc.target(e).tagName == 'A' ? doc.target(e).parentNode : doc.target(e);
    if(!rootElement.className.match(/(^| )active( |$)/))
        rootElement.className += " active";
    var children = rootElement.getElementsByTagName("ul");
    for(var i = 0; i < children.length; i++)
    {
        children[i].className = children[i].className.replace(/(^| )hidden( |$)/g, "");
    }
}

functionTimeOuts = {  }
functionTimeOuts.counter = 0;

function timeOut(e)
{
    var rootElement = doc.target(e);
    for(rootElement; !rootElement.parentNode.className.match(/(^| )menu( |$)/) || rootElement.tagName == "BODY"; rootElement = rootElement.parentNode) ;
    if(!isInFunctionTimeOuts(rootElement))
    {
        var index = ++functionTimeOuts.counter;
        functionTimeOuts['timeOut' + index] = [rootElement, setTimeout('closeUnderlying(' + index + ')', 300)];
    }
}

function closeUnderlying(timeOutNr)
{
    if(timeOutNr < 0)
        return;
    functionTimeOuts['timeOut' + timeOutNr][0].className = functionTimeOuts['timeOut' + timeOutNr][0].className.replace(/(^| )active( |$)/g, "");
    var children = functionTimeOuts['timeOut' + timeOutNr][0].getElementsByTagName("ul");
    for(var i = 0; i < children.length; i++)
    {
        children[i].className += " hidden";
    }
    delete functionTimeOuts['timeOut' + timeOutNr];
}

function killTimeOut(e)
{
    var rootElement = doc.target(e);
    for(rootElement; !rootElement.parentNode.className.match(/(^| )menu( |$)/); rootElement = rootElement.parentNode);
    
    if(isInFunctionTimeOuts(rootElement))
    {
        clearTimeout(functionTimeOuts[isInFunctionTimeOuts(rootElement)][1]);
        delete functionTimeOuts[isInFunctionTimeOuts(rootElement)];
    }
}

function isInFunctionTimeOuts(rootElement)
{
    for (var key in functionTimeOuts)
        if(functionTimeOuts[key][0] === rootElement)
            return key;
    return false;  
}
