$(document).ready(function() {
    
    /*
     * Sets up hover event for all popup menus.
     */
    $('.popup').hover(popupHoverIn, popupHoverOut);
    
});

/*
 * Called when the user hovers in a popup element.
 */
function popupHoverIn(e) {

    /* Set class to indicate user is hovering */
    $(this).addClass('hovering');

    /* Show corresponding popup */
    var popupName = $(this).data('popup')
    showPopup('#' + popupName, $(this));
    
}

/*
 * Called when the user hovers out of a popup menu.
 */
function popupHoverOut(e) {

    /* Remove class to indicate user is no longer hovering */
    $(this).removeClass('hovering');
    
    setTimeout(function() {
        
        /* Hide popup menu if user is no longer hovering any popup elements */
        var popupName = $(e.target).data('popup')
        var isHovering = $("[data-popup='" + popupName + "']").hasClass('hovering');
        if (!isHovering) {
            hidePopup('#' + popupName);
        }

    }, 50);
    
}

/*
 * Shows the specified popup menu if not already visible.
 */
function showPopup(id, anchor) {

    /* Move into place and display, if not already shown */
    if (!$(id).is(':visible')) {
        $(id).css({ top: 0, left: 0 }).position({ my: "center top", at: "center bottom", of: anchor });
        $(id).fadeIn('fast');
    }
    
}

/*
 * Hides the specified popup menu.
 */
function hidePopup(id) {

    $(id).fadeOut('fast');
    
}
