$(function(){
    enableNavigationMenu();
});

function enableNavigationMenu() {
    var hideTimer;

    // prevent hiding of the submenu
    var stopHideTimer = function () {
        if (hideTimer) window.clearInterval(hideTimer);
        hideTimer = null;
    };

    // prevent clicking on the menu headers
    $('.dropdown').click(function (evt){ evt.preventDefault(); });

    // show submenu on hover
    $('.dropdown').click(function(){
        stopHideTimer.call();

        // hide other submenus
        var submenu = $(this).parent().next();
        $('.submenu').each(function(i){
            if ($(this).get(0) != $(submenu).get(0)) {
                $(this).hide();
            }
        });

        // position submenu under dropdown
        submenu.css({
            position:'absolute',
            top: ($(this).offset().top + $(this).height() + 4) + 'px',
            left: $(this).offset().left + 'px'
        });

        // drop down
        submenu.slideDown(300);

        // hide submenu when mouse out
        var mouseOutHandler = function() {
            if (hideTimer) return;

            var self = this;
            hideTimer = window.setTimeout(function () {
                if (! hideTimer) return;
                hideTimer = null;

                // hide submenu
                submenu.slideUp(300);
            }, 800);
        };

        // install event handlers
        submenu.mouseleave(mouseOutHandler);
        submenu.mouseenter(stopHideTimer);
        $(this).mouseleave(mouseOutHandler);
    });
}

