Navigation = Class.create({
  element:null,

  initialize: function(elem) {
    this.element = $(elem);
    if (!this.element) return;

    this.build();
    this.setupObservers();
  },

  build: function() {
    this.subnavs = this.element.select('.level-0');
    this.currentSubnav = this.element.down('.active');
  },

  setupObservers: function() {
    this.subnavs.each(function(elem) {
      elem.down('a').observe('click', this.toggleSubnav.bindAsEventListener(this));
    }.bind(this));
  },

  toggleSubnav: function(evt) {
    evt.stop(); // prevent default clickthrough to wait for animation
    var element = Event.element(evt); // find the thing that was clicked on
    this.hideSubnav(); // hide current
    this.showSubnav(element);
  },

  showSubnav: function(element) {
    var li = element.up('li');
    var subnav = li.down('.subnavigation');
    if (subnav) {
      new Effect.Parallel([
        new Effect.Morph(this.element, {style: 'top: -17px;', sync: true }),
        new Effect.Morph(subnav, { style: 'height: 18px;', sync: true })
        ], {
        duration: Interface.TWEEN_SPEED,
        beforeStart: function() {
          subnav.setStyle({height: '0', display: 'block', overflow: 'hidden'});
          li.addClassName('active'); // select current
        },
        afterFinish: function() {
          this.currentSubnav = li;
          window.location.href = element.href;
        }.bind(this)
      });
    } else {
      new Effect.Morph(this.element, {
        style: 'top: 0px;',
        duration: Interface.TWEEN_SPEED,
        beforeStart: function() {
          li.addClassName('active'); // select current
        },
        afterFinish: function() {
          window.location.href = element.href;
        }.bind(this)
      });
    }
  },

  hideSubnav: function(subnav) {
    var subnavLocal = subnav || this.currentSubnav;
    if (subnavLocal) {
      subnavLocal.removeClassName('active'); // deselect all
      var subnavDiv = subnavLocal.down('.subnavigation');
      if (subnavDiv) subnavDiv.hide();
    }
  }
  
});