/*jslint browser:true, white:true, onevar:false, nomen:true, indent:false,
         bitwise:false */
/*globals window, juvo:true, jQuery */

if (!('juvo' in window)) {
    window['juvo'] = { 'ui': {} };
} else if (!('ui' in window['juvo'])) {
    window['juvo']['ui'] = {};
}

(function ($) {

var menu = function (element, options) {
    var self = this;

    this.options = $.extend({}, menu.defaults, options || {});
    this.element = $(element);
    this.items   = this.element.children('li');
    this.labels  = this.element.children('li').children('span,a');
    this.subMenus = this.element.find('ul');
    this.activeItem = null;
    this.close();

    this.items.bind('mouseover', function (e) { 
        self.show(this); 
    });
    
    this.items.not(':has(ul)').bind('mouseout', function (e) { 
        $(this).removeClass('juvo-state-hover');
        $(this).children('span,a').removeClass('juvo-state-hover');
    });

    this.items.has('ul')
        .addClass('juvo-menu-has-submenu')
        .append('<div class="ui-icon ui-icon-triangle-1-e"></div>')
        .bind('mouseout', function (e) {
            self.clearTimer();
            self.timer = setTimeout(function () { 
                self.close(); 
            }, self.options.timeout);
        });

    $(document).bind('click', function () { 
        // Sending this time setTimeout with a very short delay, which should help the browser
        // deprioritize this action. No need to burn cycles doing a fadeOut when the user's trying
        // to leave the page.
        if (self.timer) {
            self.clearTimer();
            setTimeout(function () { self.close(); }, 0);
        }
    });
};

$.extend(menu.prototype, {
    options:    {},
    element:    null,
    subMenus:   null,
    active:     null,
    timer:      false,
    activeItem: null,
    labels:     null,

    clearTimer: function () {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = false;
        }
    },
    show: function (item) {
        this.clearTimer();
        this.close(true);
        this.activeItem = $(item);
        $(item).addClass('juvo-state-hover');
        $(item).children('span,a').addClass('juvo-state-hover');
        $(item).children('ul:first').show();
    },
    close: function (noEffects) {
        if (this.activeItem) {
            this.activeItem.removeClass('juvo-state-hover');
            this.activeItem = null;
        }

        this.labels.removeClass('juvo-state-hover');

        if (noEffects) {
            this.subMenus.hide();
        } else {
            this.subMenus.fadeOut(500);
        }
    }
});

$.extend(menu, {
    defaults: {
        timeout: 500
    }
});

window['juvo']['ui']['menu'] = menu;

}(jQuery));
