/**
 * Options
 * - liMatch (defaults null)
 * - offsetY (defaults 0)
 * - delay (defaults 100)
 * - duration (defautls 'normal')
 * - effects: (defaults true)
 * - transition: 'sine:in:out'
 */

var ulNavigation = new Class({

  Implements: [Options],

  options: {
    liMatch: null
  },

  initialize: function(ul, options)
  {
    /* Config */
    this.setOptions(options);
    this.listItems = new Array();
    var listItems = document.id(ul).getChildren(this.options.liMatch);

    /* ListItems mit Objekten Versehen */
    for(var i = 0; i < listItems.length; i++)
    {
      if(listItems[i].getElement('ul'))
      {
        new ulNavigationListItem(listItems[i], this.options);
      }
    }
  }

});

var ulNavigationListItem = new Class({

  Implements: [Options, Events],

  options: {
    offsetX: 0,
    offsetY: 0,
    delay: 100,
    duration: 'normal',
    effects: true,
    transition: 'sine:in:out',
    zIndex: 100
  },

  initialize: function(li, options)
  {
    this.setOptions(options);
    this.li = document.id(li);
    this.ul = this.li.getElement('ul');
    this.a = this.li.getChildren('a');
    this.delayTimer = null;

    // Trick to get the dimension of the Submenue
    this.ul.setStyles({
      'display': 'block',
      'visibility': 'hidden',
      'position': 'absolute',
      'top': '0px',
      'left': '0px',
      'z-index': this.options.zIndex
    });
    this.ul.store('height', (this.ul.getSize().y));
    this.ul.setStyles({
      'display': 'none',
      'visibility': 'visible'
    });
    
    this.a.addEvents({
      'mouseover': this.showSubMenue.bind(this),
      'mouseout':  this.hideSubMenue.bind(this)
    });
    this.ul.addEvents({
      'mouseover': function(){ clearInterval(this.delayTimer); }.bind(this),
      'mouseout':  this.hideSubMenue.bind(this)
    });
  },

  showSubMenue: function(e)
  {
    e.stop();
    clearInterval(this.delayTimer);

    if(this.ul.getStyle('display') == 'none')
    {
      var pos = this.li.getPosition();
      pos.y = pos.y.toInt() + this.li.getSize().y.toInt() + this.options.offsetY.toInt();
      pos.x = pos.x.toInt() + this.options.offsetX.toInt();

      this.ul.setStyle('display', 'block').setPosition(pos);

      if(this.options.effects)
      {
        var y = this.ul.getSize().y;
        this.ul.setStyle('height', '0px');
        this.ul.set('morph', { 'duration': this.options.duration, 'transition': this.options.transition });
        this.ul.morph({ 'height': this.ul.retrieve('height') + 'px' });
      }
    }
  },

  hideSubMenue: function(e)
  {
    this.delayTimer = function()
    {
      this.ul.setStyle('display', 'none');
      clearInterval(this.delayTimer);
    }.bind(this, e).delay(this.options.delay);
  }

});
