/*
 * Housemate javascript application functions and classes
 *
 * @author Jiannis
 * @author Fotos
 *
 * Sense & Funtasia 2008
 */

//<![CDATA[

/**
 * Menu Class
 * 
 * @class
 * @constructor
 * 
 * @param {Object} container
 * @param {Object} options
 */
function Menu(container, options) {
    var me = this;
    
    //Menu container
    me.container = container;
    
    //Set options
    me.options = options || {};
    
    //Bind click events on submenu buttons
    $(me.container).getElementsBySelector('.submenu_button').invoke('observe', 'click', me.toggleSubmenu.bindAsEventListener(me));
    
    //Register a click event on the body element to hide open submenus
    Event.observe(document.body, 'click', me.hideSubmenus.bindAsEventListener(me));
};

/**
 * Toggles the visibility of the submenu that has been clicked
 * and hides other possibly open submenus
 * 
 * @param {Object} event
 */
Menu.prototype.toggleSubmenu = function(event) {
    var me = this;
    
    //Figure out which submenu button element triggered the event
    var element = Event.element(event);
    
    //Get the corresponding menu item
    var menuItem = element.up('.menu_item');
    
    //Get the corresponding submenu
    var submenu = menuItem.down('.submenu');

    //Toggle the visibility of this submenu
    submenu.toggle();

    //Toggle the current menu item class
    menuItem.toggleClassName('current');
    
    //Hide other possibly open submenus
    $(me.container).getElementsBySelector('ul.submenu').each(function(e){
        if (e != submenu)  {
         e.hide();
         e.up('.menu_item').removeClassName('current');
        }
    });

    //Capture the event
    Event.stop(event);
};

/**
 * Hides all submenus
 * 
 * @param {Object} event
 */
Menu.prototype.hideSubmenus = function(event) {
    var me = this;
    
    $(me.container).getElementsBySelector('ul.submenu').invoke('hide').each(function(element) { element.up('.menu_item').removeClassName('current') });
};

//]]>
