﻿var currentLi;
var subToHide;
var hideTimeoutId;
var currentSubMenu;
var hidingElems = [];
var showingElems = [];
var $nav;

function initMenu() {
    if ($nav == null) {
        $nav = $('#nav');
    }   //if

    $nav.find('ul li:not(.sep)').each(function () {
        $(this).hover(
            function () {
                var subId = getSubMenuId($(this));
                $sub = $(subId);
                $li = $(this);

                if (currentSubMenu != null) {
                    if (currentSubMenu.attr('id') == $sub.attr('id')) {
                        clearTimeout(hideTimeoutId);
                    }
                    else {
                        subToHide = currentSubMenu;
                        hideSubMenu();
                    }
                }

                if ($sub.length > 0) {
                    showSubMenu($sub, $li);

                    $sub.unbind();
                    $sub.hover(
                        function () {
                            clearTimeout(hideTimeoutId);
                        },
                        function () {
                            subToHide = $sub;
                            hideTimeoutId = setTimeout('hideSubMenu()', 50);
                        }
                    );
                }   //if
            },
            function () {
                var subId = getSubMenuId($(this));
                $sub = $(subId);

                if ($sub.length > 0) {
                    subToHide = $sub;
                    hideTimeoutId = setTimeout('hideSubMenu()', 300);
                }   //if
            }
        );
    });
}

function showSubMenu(subMenu, parent) {
    if (!currentSubMenu || subMenu.attr('id') != currentSubMenu.attr('id')) {
        positionSubMenu(subMenu, parent);

        if (subMenu.css('display') == 'none') {
            subMenu.css({
                display: 'block',
                opacity: 0
            });
        }

        subMenu.animate({
            opacity: 1,
            marginLeft: getParentLeftPosition(parent) + 10
        }, 300);

        currentSubMenu = subMenu;
    }   //if
}

function hideSubMenu(callback) {
    subToHide.animate({
        opacity: 0
    }, 100, function () {
        currentSubMenu = null;
        subToHide.css('display', 'none');
    });

    if (callback != null) {
        callback();
    }
}

function positionSubMenu(subMenu, parent) {
    subMenu.css({
        marginLeft: getParentLeftPosition(parent) - 10
    });
}

function getParentLeftPosition(parent) {
    return parent.position().left + (parent.width() / 4);
}

function getSubMenuId(parentElem) {
    var subId = parentElem.attr('id');
    return '#sub' + subId.charAt(0).toUpperCase() + subId.substring(1);
}
