﻿var delayValue = 500;
var delayTimer = null;
var dropDownId = null;

jQuery.fn.menu = function(callback) {
    //Add CSS classes to menu items
    if (!this.hasClass('menu')) {
        this.addClass('menu');
    }

    this.children('li')
        .addClass('menu-item')
        .addClass('ui-corner-all');

    this.find('ul')
        .addClass('menu-drop-down')
        .addClass('ui-widget-content')
        .addClass('ui-corner-all')
        .find('li')
        .addClass('menu-drop-down-item')
        .addClass('menu-drop-down-state-default')
        .addClass('ui-corner-all');

    //Add ID values to the drop down menus
    this.find('ul').each(function(index) {
        $(this).attr('id', 'drop-down-' + index)
    });

    //Add the mouse events to the top level list item elements
    this.children('li').mouseover(function() {
        //Cancel the close timer
        if (delayTimer) {
            window.clearTimeout(delayTimer);
            delayTimer = null;
        }

        //Only act if the drop down should be changed
        var dropDown = $(this).find('ul:first');
        if (dropDown.attr('id') != dropDownId) {
            //Hide the previous drop down            
            closeDropDown();
            //Show this drop down
            dropDown.show();
            //Track which drop down is visible
            dropDownId = dropDown.attr('id');
        }
    });

    this.children('li').mouseout(function() {
        delayTimer = window.setTimeout(closeDropDown, delayValue);
    });

    //If the user clicks anywere on the document, the current drop down should close
    $(document).click(function() { closeDropDown(); });

    //Apply hover effects
    this.find('.menu-item')
    .hover(
	    function() { $(this).addClass('ui-state-hover'); },
	    function() { $(this).removeClass('ui-state-hover'); }
    );

    this.find('.menu-drop-down-item')
    .hover(
	    function() { $(this).removeClass('menu-drop-down-state-default').addClass('menu-drop-down-state-hover'); },
	    function() { $(this).removeClass('menu-drop-down-state-hover').addClass('menu-drop-down-state-default'); }
    );

    //Execute the callback function
    if (callback) {
        callback();
    }
};

function closeDropDown() {
    $('#' + dropDownId).hide();
    dropDownId = null;
};