document.observe("dom:loaded", function() {
  $$('#root > li.hasChilds > a').each(function(o) {Event.observe(o, "click", openMenu.bind(this, o));});
});

function openMenu(o, e) {
  //console.log($$('#root > li.hasChilds > a'));
  oUl = o.up('li').down('ul');
  $$('#root > li.hasChilds > a').each(function(oA){
    oUl2 = oA.up('li').down('ul');
    if(oUl != oUl2) {
      oUl2.removeClassName('visible');
    }
  });
  if(!oUl.hasClassName("visible")) {
    oUl.addClassName("visible");
    var e2 = (e.findElement().nodeName.toLowerCase() == "span" ? e.findElement().up('a') : e.findElement());
    Event.observe(document, "click",  function(o) {if(!o.findElement().descendantOf(e2.up('li'))) {closeMenu(e2, e);}});
    Event.stop(e);
  }
}

function closeMenu(o, e) {
  if(oUl.hasClassName("visible")) {
    oUl.removeClassName("visible");
    Event.stop(e);
  }
  Event.stopObserving(document, 'click');
}

/*document.observe("dom:loaded", function() {
  $$('#root > li.hasChilds > a').each(function(o) {Event.observe(o, "click", openMenu.bind(this, o));});
});

function openMenu(o, e) {
	console.log($$('#root > li.hasChilds > a'));
  oUl = o.up('li').down('ul');
  if(!oUl.hasClassName("visible")) {
    oUl.addClassName("visible");
    var e2 = (e.findElement().nodeName.toLowerCase() == "span" ? e.findElement().up('a') : e.findElement());
    Event.observe(document, "click",  function(o) {if(!o.findElement().descendantOf(e2.up('li'))) {closeMenu(e2, e);}});
    Event.stop(e);
  }
}

function closeMenu(o, e) {
  oUl = o.up('li').down('ul');
  if(oUl.hasClassName("visible")) {
    oUl.removeClassName("visible");
    Event.stop(e);
  }
  Event.stopObserving(document, 'click');
}*/
