var Menu = [];
Slidemenu.aniLen = 350;
Slidemenu.showDelay = 500;
Slidemenu.hideDelay = 1000;

function Slidemenu(li, ul) {
  this.ul    = ul;
  ul.style.display = "block";
  this.height = ul.offsetHeight - 20;
  this.accel = this.height / Slidemenu.aniLen / Slidemenu.aniLen;
  this.id    = Menu.length;
  this.open  = false;
  Menu.push(this);
  
  this.start = function(direction) {
    this.open = direction;
    this.direction = direction;
    this.startTime = (new Date()).getTime();
    this.timer = window.setInterval("Menu[" + this.id + "].slide()", 10);
    ul.style.padding = "10px 0";
    ul.style.margin = "0 0 3px 0";
  }
  
  this.slide = function() {
    var elapsed = (new Date()).getTime() - this.startTime;
    if (elapsed > Slidemenu.aniLen)
      this.end();
    else {
      var d = Math.round(Math.pow(Slidemenu.aniLen - elapsed, 2) * this.accel);
      if (this.direction) {
        //alert(this.height - d + "px");
        this.ul.style.height = this.height - d + "px";
      } else {
        //alert(d + "px");
        this.ul.style.height = d + "px";
      }
    }
  }
  
  this.end = function() {
    window.clearInterval(this.timer);
    if (!this.open) {
      ul.style.padding = 0;
      ul.style.margin = 0;
    }
  }
  
  this.show = function() {
    for(var i=0; i<Menu.length; i++)
      if(Menu[i] != this) 
        Menu[i].hide();
   	if (this.timerHide) window.clearTimeout(this.timerHide)
      this.timerHide = 0
    if (!this.open)
      this.start(true);
  }
  
  this.hide = function() {
    if (this.open)
      this.start(false);
  }
  
  this.showDelayed = function() {
    if (this.timerShow) 
      window.clearTimeout(this.timerShow);
	  this.timerShow = window.setTimeout("Menu[" + this.id + "].show()", Slidemenu.showDelay);
  }
  
  this.hideDelayed = function() {
    if (this.timerHide) 
      window.clearTimeout(this.timerHide);
    if (this.timerShow) 
      window.clearTimeout(this.timerShow);
	  this.timerHide = window.setTimeout("Menu[" + this.id + "].hide()", Slidemenu.hideDelay);
  }
  
  var m = this;
  if (li.className.indexOf('selected') < 0) {
    ul.style.height = 0;
    ul.style.margin = 0;
    ul.style.padding = 0;
    ul.style.display = "block";
    li.onmouseover = function() { m.showDelayed() };
    li.onmouseout  = function() { m.hideDelayed() };
  }
}

function initmenu(id) {
  var menu = document.getElementById(id);
  if (!menu) return;
  var li = childsTag(childsTag(menu, 'UL')[0], 'LI');
  for(var i=0; i < li.length; i++) {
    var ul = childsTag(li[i], 'UL');
    if(ul.length > 0) {
      new Slidemenu(li[i], ul[0]);
    }
  }
  //menu.style.visibility = "visible";
}

function childsTag(node, tagName) {
  var childs = [];
  for(var i=0; i < node.childNodes.length; i++) {
    var c = node.childNodes[i];
    if (c.nodeType == 1 && c.tagName == tagName) {
      childs.push(c);
    }
  }
  return childs;
}

