/*  Prototype/Scriptaculous based toggable menu
 *
 *--------------------------------------------------------------------------*/

// create object with constructor function (Fl stands for FarmaLine)
function FlMenu (menu_id, options) {

    this.menu = $(menu_id);
    
    // set defaults for configurable properties
    this.__options = $H({
            'duration': 0.4,
            'toggler': 'span.icon'
        });

    // override if necessary
    if (options) {
        this.__options = this.__options.merge($H(options));
    }

    // toggle one element in the menu
    this.toggleElement = function (e) {
        e.stop();

        var handle = e.findElement().up('a');
        handle.addClassName('active');
        
        // close all nested ul 's
        var childs = this.menu.childElements();
        for (var i = 0; i < childs.length; i++) {
            if (childs[i].down('a').hasClassName('active')
                && childs[i].down('a') === handle
                && childs[i].down('div').visible() === false) {

                // open submenu of clicked element, if it wasn't open already
				childs[i].down('div').show();
				//new Effect.BlindDown(childs[i].down('div'), this.__getEffectProperties());

            } else if (childs[i].down('a').hasClassName('active')
                && childs[i].down('a') === handle
                && childs[i].down('div').visible() === true) {

                // close submenu of clicked element, if it was already open
				childs[i].down('div').hide();
				//new Effect.BlindUp(childs[i].down('div'), this.__getEffectProperties());

                // de-activate this element
                childs[i].down('a').removeClassName('active');

            } else if (childs[i].down('a').hasClassName('active') && childs[i].down('a') !== handle) {

                // close submenu of previous active element
                childs[i].down('a').removeClassName('active');
				childs[i].down('div').hide();
                //new Effect.BlindUp(childs[i].down('div'), this.__getEffectProperties());
                
            }
        }
		
		if (this.__options.get('postResize')) {
                    this.__options.get('postResize')();
		}

    };
    
    // initialize the menu by setting observers
    this.initialize = function () {
        this.menu.select(this.__options.get('toggler')).invoke('observe', 'click', this.toggleElement.bind(this));
    };
    this.initialize();

    // method to hide everything within the given selector
    this.hide = function (selector) {
      this.menu.select(selector).each(function (el) {
          
          if (el.next() && el.next().tagName === 'DIV') {
              el.next().hide();
          }
      }) ;
    };

    this.__getEffectProperties = function () {
      return {
          'duration': this.__options.get('duration')
      };
    };
	

}
