// yams: Yet Another javascript Menu System
// Copyright (C) 2003  Wilfried Philips 
// http://telin.UGent.be/~philips/

// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.



DOM = (document.getElementById) ? 1 : 0;
NS4 = (document.layers) ? 1 : 0;
Opera = (navigator.userAgent.indexOf("Opera") > -1) ? 1 : 0;
Opera5 = (navigator.userAgent.indexOf("Opera 5") > -1 || navigator.userAgent.indexOf("Opera/5") > -1) ? 1 : 0;
Opera6 = (navigator.userAgent.indexOf("Opera 6") > -1 || navigator.userAgent.indexOf("Opera/6") > -1) ? 1 : 0;
Opera56 = Opera5 || Opera6;
IE = (document.all) ? 1 : 0;
IE4 = IE && !DOM;

//future additions
//add option for menuitem to be generated by javascript (now it only
//calls javascript)


function debug(msg,debug)
{
  if(!debug) debug=false;
  if(debug&&!IE)
    java.lang.System.out.println(msg);
  //  else   if(debug&&IE)
  //  window.status=msg;
}


function evalLogical(expr,vars)
{
  //  alert("expr="+expr);
  //temporary hack
  //  if(is_konqueror) return true;
  oldexpr=expr;
  var matches=new Array();
  matches=expr.match(/\w+|[ \|\&\(\)!]/g);
  var newexpr="";
  for(var i=0;i<matches.length;i++) {
    var name=matches[i].valueOf();
    var value="";
    //alert(name);
    low=name.toLowerCase();
    switch(low) {
    case ' ':    case '(':    case ')':
      value=low;
      break;
    case 'and':
      value="&&";
      break;
    case 'or':
      value="||";
      break;
    case 'not':
      value="!";
      break;
    case '|':
    case '&':
      value=low+low;
      break;
    case '!':
      value=name;
      break;
    case ' ':
      value=' ';
      break;
    default:
      if(low.charCodeAt(0)==32){ //hack for buggy ns4.7
	value=" ";
	break;
      }
      if(typeof(vars[name]!='undefined')) {
	value=vars[name]?"true":"false";
      } else { value="false"; }
      break;
    }
    //    alert(low+"->"+value);
    newexpr+=value;
  }
  //  alert("oldexpr="+oldexpr+" newexpr="+newexpr);
  //  alert("result="+newexpr+";");
  eval("result="+newexpr+";");
  //alert(oldexpr+"="+newexpr+"="+result+" VARS="+vars);
  return result;
}

function getElementDims(object) {
  var value = 0;
  var Dims=new Object();
  Dims.height=20;
  Dims.width=0;
  if(!object) 
    return Dims;
  if (DOM && !Opera56) {
    Dims.width = object.offsetWidth;
    Dims.height = object.offsetHeight;
    Dims.x=object.offsetLeft;
    Dims.y=object.offsetTop;
    var el=object;
    while((el=el.offsetParent) != null) {
      Dims.x+=el.offsetLeft;
      Dims.y+=el.offsetTop;
    }
    if (isNaN(Dims.height))
      Dims.height=20;
    if (isNaN(Dims.width)) {
      Dims.width = 0;
    }
  } else if (NS4) {
    Dims.width=object.document.width;
    Dims.height =object.document.height;
     
  } else if (Opera56) {
    Dims.width = object.style.pixelWidth;
    Dims.height = object.style.pixelHeight;
  }
  return (Dims);
}

function getWindowGeometry() {
  var geom = new Object();
  if (typeof(window.pageXOffset)!="undefined"
      &&typeof(window.innerWidth)!="undefined") {
    geom.XOffset = window.pageXOffset;
    geom.YOffset = window.pageYOffset;
    geom.width = window.innerWidth;
    geom.height = window.innerHeight;
  } else {	// IE
    if (document.documentElement && 
	document.documentElement.scrollLeft&&
	document.documentElement.clientWidth&&
	document.documentElement.clientHeight) {
 
	geom.XOffset = document.documentElement.scrollLeft;
	geom.YOffset = document.documentElement.scrollTop;
	geom.width = document.documentElement.clientWidth;
	geom.height = document.documentElement.clientHeight;
      } else if (document.body) {
      geom.XOffset= document.body.scrollLeft;
      geom.YOffset= document.body.scrollTop;
      geom.width = document.body.clientWidth;
      geom.height = document.body.clientHeight;
    }
  }
  if (isNaN(geom.width)) {
    geom.width = top.innerWidth;
  }
  if (isNaN(geom.height)) {
    geom.height = top.innerHeight;
  }
  return (geom);
}


function Yams_divExists(divName)
{
  if (this.use_gebi) {
    return document.getElementById(divName);
  }
  else if (this.use_css) { 
    return document.all[divName];
  }
  else if (this.use_layers) { 
    return document.layers[divName]; 
  }
  return false;
}



function MenuPane(name)
{
  this.base=PopupWindow;
  this.base(name);
}

function Yams_showHideForms(show)
{
  if(!window.is_gecko&&(NS4)) {
    for(var i in this.formsToHide) {
      hideLayer(show,this.formsToHide[i]);
    }
  }
}

function Yams_hideDeepestMenu()
{
  if(!this||this.currentLevel<=0) {
    debug("IMPLERROR hideDeepest");
    return;
  }
  debug("hideDeepest "+yams.currentLevel);
  yams.popups[yams.currentLevel--].hidePopup();
  if(yams.currentLevel>0)
    return;
  yams.showHideForms(true);
  if (NS4) {
      if(yams.oldonmousedown)
	document.onmousedown = yams.oldonmousedown;
  } else {
    
  }
  if(!NS4)
    yams.removeEvent(document,"keypress",this.keyPress);
  yams.removeEvent(document,"click",this.hideMenus);
}

function Yams_hideMenus()
{
  if(!window.yams) {
    debug("IMPLERROR no yams");
    return false;
  }
  debug("hide menus "+yams.currentLevel);
  while(yams.currentLevel>0) {
    yams.hideDeepestMenu();
  }
}








//[MainAnchor] <--- level 0
//[..pane 1..] <--- level 1
//[..pane 1..]
//[SubAnchor.][..pane 2..] <--- level 2
//[..pane 1..][..pane 2..]
//[..pane 1..][..pane 2..]
//            [..pane 2..]

//all stored coordinates are absolute w.r.t. window


function Yams_getAnchorPosition(anchorname)
{
  //the following implementation is more robuust
  var ret=new Object();
  ret.x=0;
  ret.y=0;
  if(this.use_gebi&&document.all&&!document.all[anchorname])
    return ret;
  else if(this.use_gebi&&!document.getElementById(anchorname))
    return ret;
  else if(this.use_css&&!document.all[anchorname])
    return ret;
  else 
    return getAnchorPosition(anchorname);
}


function Yams_stopEvent (ev) {
if(ev.stopPropagation){
    ev.stopPropagation();
  }
 else if (typeof(ev.cancelBubble)!='undefined') {
   ev.cancelBubble = true;
 } else  {
   alert("cannot cancel bubble");
 }
 if(ev.preventDefault){
   ev.preventDefault();
 } else   //if(typeof(ev.returnValue)!='undefined')
   ev.returnValue = false;
 // else {
 //   alert("cannot prevent default");
 // }
 return false;
}

function Yams_addEvent (el, evname, func) {
  if (el.attachEvent) {
    el.attachEvent("on" + evname, func);
  } else if(el.addEventListener) {
    el.addEventListener(evname, func, true);
  } 
  else {
    alert("cannot add event handler "+evname);
  }
}


function Yams_removeEvent (el, evname, func) {
  if(el.removeEventListener)
    el.removeEventListener(evname, func, true);
  else if (el.detachEvent) {
    el.detachEvent("on" + evname, func);
  } else {
    //alert("cannot remove event handler "+evname);
  }
}

function Yams_displayMainMenu(evt,menuname,currentUrl,currentQuery,
			      MainAnchor,
			      menuVars,currentJsFunc)
{
  evt=(evt)?evt:((event)?event:null);
  if(!evt) {
    return false;
  }
  if(typeof(currentJsFunc)=='undefined') currentJsFunc="";
  debug("displaymainmenu");
  this.hideMenus();
  if (NS4) {
    this.oldonmousedown=document.onmousedown;
    document.onmousedown = this.hideMenus;
  } else {
    this.stopEvent(evt);
    this.addEvent(document,"click",this.hideMenus);
    debug("set onclick to hideMenus");
  }
  debug("displaymainmenu:HHH");
  //if MainAnchor is not set, we are not called from the menubar
  this.showHideForms(false);
  this.currentLevel=0;
  this.rightToLeft=0;
  if(menuVars)
    this.menuVars=menuVars;
  else
    this.menuVars=this.defaultMenuVars;
  if(MainAnchor)
    this.MainAnchor=MainAnchor;
  else {
    this.MainAnchor=this.anchorBasename+menuname;
  }
  debug("MainAnchor="+this.MainAnchor);
  //debug(typeof(this.MainAnchor),true);
  if(typeof(this.MainAnchor)=="object"&&typeof(this.MainAnchor.x)!="undefined") {
    //debug("copying pos",true);
    pos={x:this.MainAnchor.x, y:this.MainAnchor.y};
  } else{
    pos=this.getAnchorPosition(this.MainAnchor);
  }
  debug("pos.x="+pos.x+" pos.y="+pos.y);
  //window.status="pos.x="+pos.x+" pos.y="+pos.y;

  //alert("pos.x="+pos.x+" pos.y="+pos.y+" anch="+this.MainAnchor);
  if(!DOM) {
    var dims=new Object();
    dims.width=100;
    dims.height = 18;
    dims.y=pos.y;
  } else {
    if(typeof(this.MainAnchor)=='object') {
      dims={width:0, height:0, x:pos.x, y:pos.y};
    } else {
      MainAnchorElement=document.getElementById(this.MainAnchor);
      if(!MainAnchorElement) 
	return ;
      if(!MainAnchor) {
	//parentNode is the menubar itself
	dims=getElementDims(MainAnchorElement.parentNode);
	//alert("SSdims.y="+dims.y+" dims.height="+dims.height,true);
      } else {
	dims=getElementDims(MainAnchorElement);      
	//debug("SSdims.y="+dims.y+" dims.height="+dims.height,true);
      }
    }
  }
  if(!dims)
    return false;
  if(!this.popupGeoms[0])
    this.popupGeoms[0]=new Object();
  //this.popupGeoms[0] refers to a non-existing box
  //The box's top-left corner coincides with that of the MainAnchor
  //The box's bottom side coincided with that of the menubar
  //The width has no meaning
  this.popupGeoms[0].x=pos.x;
  this.popupGeoms[0].y=pos.y;
  //debug("y="+pos.y+" dims.y="+dims.y+" dims.width="+dims.width);
  this.popupGeoms[0].width=dims.width;
  this.popupGeoms[0].height=dims.height-(pos.y-dims.y);
  //in browsers that support "fixed" positioning, 
  //we add the following correction to fix a bug, i.e., that
  //getAnchorPosition does not work correctly for "fixed" elements
  //on the other hand fixing getAnchorPosition slows down things too much

  //+document.body.scrollTop;
  t=this.popupGeoms[0];
  debug("menuname="+menuname+" x="+t.x+" y="+t.y+" w="+t.width+" h="+t.height);
  //  alert("menuname="+menuname+" x="+t.x+" y="+t.y+" w="+t.width+" h="+t.height,true);
  var currentTarget='';
  ret=this.displayMenu(menuname,this.MainAnchor,0,currentUrl,currentQuery,
			  currentTarget,currentJsFunc);
  if(!NS4)
    this.addEvent(document,"keypress",this.keyPress);
  return ret;
}



function Yams_hideSubMenu(level) {
  debug("HIDEMENU level="+level);
  while(this.currentLevel>=level) {
    this.popups[this.currentLevel].hidePopup();
    this.currentLevel--;
  }
}

function hasClassName(el, name) {

  var i, list;
  // Return true if the given element currently has the given class
  // name.
  if(!el.className) return false;
  list = el.className.split(" ");
  for (i = 0; i < list.length; i++)
    if (list[i] == name)
      return true;
  return false;
}



function positionArrows(menu)
{
  // Find the width of a menu item.
    itemList = menu.getElementsByTagName("A");
  //      menu.style.width=((menu.offsetWidth)+"px");
  if (itemList.length > 0)
    itemWidth = itemList[0].offsetWidth;
  else
    return;
  // For items with arrows, add padding to item text to make the
  // arrows flush right.
  var spanList;
  var textEl;
  var arrowEl;
  var maxleft=0;
  var arrowClass=(IE)?"menuItemArrowIE":"menuItemArrow";
  for (i = 0; i < itemList.length; i++) {
    spanList = itemList[i].getElementsByTagName("SPAN");
    arrowEl = null;
    for (j = 0; j < spanList.length; j++) {
      if (hasClassName(spanList[j], arrowClass)) {
        arrowEl = spanList[j];
	if(arrowEl.offsetLeft>maxleft) {
	  maxleft=arrowEl.offsetLeft;
	}
	break;
      }
    }
  }
  for (i = 0; i < itemList.length; i++) {
    spanList = itemList[i].getElementsByTagName("SPAN");
    textEl  = null;
    arrowEl = null;
    for (j = 0; j < spanList.length; j++) {
      if (hasClassName(spanList[j], "menuItemText"))
        textEl = spanList[j];
      if (hasClassName(spanList[j],arrowClass))
        arrowEl = spanList[j];
    }
    if (textEl != null && arrowEl != null) {
      // itemList[i].style.width=((itemList[i].offsetWidth)+"px");
      var padd=maxleft-arrowEl.offsetLeft;
      textEl.style.paddingRight = (padd+"px");
		    // (itemWidth 
		    //       - (textEl.offsetWidth + arrowEl.offsetWidth-1)) + "px";
    }
  }
  
  
}



function Yams_generateMenu(menu,divname,level,currentUrl,currentQuery,
			   currentTarget,currentJsFunc)
{
  var str="";
  var title="";
  var url="";
  var query="";
  var target="";
  var jsFunc="";
  var jsArgs=false;
  if(typeof(currentJsFunc)=="undefined") {
    currentJsFunc="";
  }
  //  if(level>1)
    //    alert("currentUrl="+currentUrl);
  for (var i in menu) {
    if(typeof(menu[i].cond)!="undefined") {
      cond=evalLogical(menu[i].cond,this.menuVars);
      if(!cond) {
	continue;
      }
    }
    subid=this.anchorBasename+"Sub"+(this.idcounter++);
    if(menu[i].tt)
      title=' title="'+menu[i].tt+'"';
    else
      title="";
    url=currentUrl;
    query=currentQuery;
    if(currentJsFunc) {
      jsFunc=currentJsFunc;
    }
    else
      jsFunc="";
    target=currentTarget;
    if(menu[i].uri&&menu[i].uri.length>0) {
      if(menu[i].uri.charAt(0)=='|')
	url+=menu[i].uri.slice(1);
      else
	url=menu[i].uri;
    }
    if(!url)
      url=this.baseUri;
    else if(!url.match("^([^:]*:)*/")) {
      //      alert("relative: "+url);
      url=this.baseUri+url;
      //  alert(url);
    } 
    if(typeof(menu[i].jsf)!="undefined")
      jsFunc=menu[i].jsf;
    if(menu[i].jsa)
      jsArgs=menu[i].jsa;
    if(menu[i].qu&&menu[i].qu.length>0) {
      //      debug("current="+currentQuery+" qu="+menu[i].qu);
      //      debug("charat="+menu[i].qu.charAt(0));
	if(menu[i].qu.charAt(0)=='|')
	  query=currentQuery+menu[i].qu.slice(1);
	else
	  query=menu[i].qu;
      debug("current="+currentQuery+" qu="+menu[i].qu+"->"+query);
    }
    if(menu[i].tg&&menu[i].tg.length>0) {
      target=menu[i].tg;
    }
    var tria=(window.is_gecko&&!NS4)?"&#9654;":"&gt;";
    var arrowClass=(IE)?"menuItemArrowIE":"menuItemArrow";
    if(IE)tria="4";
    if(menu[i].sm) {
	img='<span class="'+arrowClass+'">'+tria+'</span>\n';
      str=str+
	'<a class="menuItem" href="javascript:void(0);" '+
	'onmouseover="if(window.yams) yams.displayMenu('+
	"'" + menu[i].sm + "', '" +subid + "', " +level 
	+ ", '" + url+ "', '"+query+ "', '"+target+ "', '"+
	jsFunc+"');"+ '" ' 
	+'id="'+subid+'" name="'
	+subid+'"'+title+'>'+
	'<span class="menuItemText">'
	+menu[i].ti+' </span>' +img+'</a>'+"\n";
      
    } else {
      if(query) {
	var parts=query.split('?');
	if(parts.length==0)
	  query=false;
	else { 
	if(parts[0].length==0) {
	  if(parts.splice)
	    parts.splice(0,1);
	  else
	    parts=parts.slice(1); 
	}
	  if(parts.length==1)
	    query=parts[0];
	  else 
	    query=parts.join("&amp;");
	}
	debug("pppp="+parts[0]);
      }
      if(query)
	query=this.processRegExps(query);
      if(query) url+=("?"+query);
      var js="";
      if(jsFunc) {
	if(jsArgs===false)
	  js=" onclick=\""+jsFunc+"();\"";
	else
	  js=" onclick=\""+jsFunc+"('"+jsArgs+"');\"";
	url="javascript:void(0)";
      }
      img='<span class="'+arrowClass+'">&nbsp;</span>\n';
      if(target) target='target="'+target+'"';
      str=str+
	'<a class="menuItem" '+target+js+' href="'
	+url+'" id="'+subid+'" name="'
	+subid+'" '+
	'onmouseover="if(window.yams) yams.hideSubMenu('+(level+1)+');"'+title+
	'>'
	+'<span class="menuItemText">' +menu[i].ti+'</span>'+img+'</a>'+"\n";
	}
  }

  str= 
    '<div class="menu" >'
    +str+"</div>";
  //debug(str,true);
  return str;
}







function Yams_displayMenu(menuname,parentAnchor,parentlevel,currentUrl,currentQuery,currentTarget,currentJsFunc)
{
  if(currentUrl==null)
    currenUrl="";
  if(currentQuery==null)
    currentQuery="";
  if(currentTarget==null)
    currentTarget="";
  var menu=this.menu[menuname];
  this.hideSubMenu(parentlevel+1)
  divno= 1+((this.currentLevel)%this.maxLevel);
  var divname;
  if(this.currentLevel>=this.maxLevel)
    return;
  divname=this.divBasename+divno;
  if(!this.divExists(divname)) {
    this.maxLevel=this.currentLevel;
    //    alert("Implementation error: not enough divs to display submenu "+
    //	  "currentLevel="+(this.currentLevel+1));
    return;
  }
  this.currentLevel++;
  if(!this.popups[this.currentLevel]) 
    this.popups[this.currentLevel]=new MenuPane(divname);
  if(!this.popupGeoms[this.currentLevel])
    this.popupGeoms[this.currentLevel]=new Object();
  str=this.generateMenu(menu,divname,this.currentLevel,currentUrl,
			currentQuery,currentTarget,currentJsFunc);
  if(this.popups[this.currentLevel]) {
    this.popups[this.currentLevel].populate(str);
    this.popups[this.currentLevel].refresh();
  }
  if(!DOM) {
    box=getElementDims(document.layers[divname]);
  } else {
    box=getElementDims(document.getElementById(divname));
  }

  this.popupGeoms[this.currentLevel].width=box.width;
  this.popupGeoms[this.currentLevel].height=box.height;
  debug(divname+" WIDTH="+box.width+" HEIGHT="+box.height);

  wing=getWindowGeometry();
  //compute absolute y position
  var y;
  if(this.currentLevel==1) {
    y=this.popupGeoms[0].height+this.popupGeoms[0].y;
    //debug("TTy="+this.popupGeoms[this.currentLevel].height,true);
    if(y+this.popupGeoms[this.currentLevel].height>
       wing.height+wing.YOffset) {
      //menu  does not fit below the main anchor
      if(this.popupGeoms[0].y-this.popupGeoms[this.currentLevel].height
	 >=wing.YOffset) { //if the menu would fit above
	y=this.popupGeoms[0].y-this.popupGeoms[this.currentLevel].height;
      }
    }
    if(DOM&&typeof(this.MainAnchor)!='object') {
      var thisdiv=document.getElementById(this.MainAnchor).parentNode;
      var posStyle;
      //	alert(thisdiv.id+Opera);
      if(window.getComputedStyle) {
	var stl=getComputedStyle(thisdiv,"");
	posStyle=stl.getPropertyValue("position");
      } else if(thisdiv.currentStyle) {
	posStyle=thisdiv.currentStyle.position;
      } else if (Opera&&(thisdiv.id.indexOf("menuBar")>-1)) {
	posStyle="fixed";//hack
      } else {
	posStyle="";
	//	  alert("here");
      }
      //	alert(posStyle);
      if(posStyle=="fixed"){
	//      alert(document.body.scrollTop);
	y+=document.body.scrollTop;
      }
    }
    
  } else {
    if(NS4) {
      y=this.currentY;
      debug("KKKy="+y);
    } else {
      ppos=this.getAnchorPosition(parentAnchor);
      y=ppos.y;
    }
  }

  //if the menu extend below bottom of window
  if(y+this.popupGeoms[this.currentLevel].height>wing.height+wing.YOffset) {
    //if the menu is too big for the window
    if(this.popupGeoms[this.currentLevel].height>wing.height)
      y=wing.YOffset; //align with top
    else //allign with bottom
      y=wing.height+wing.YOffset-this.popupGeoms[this.currentLevel].height;
  }
    
  this.popupGeoms[this.currentLevel].y=y;


    //compute absolute x position
    var x=this.popupGeoms[this.currentLevel-1].x;
    if(this.currentLevel>1) {
      // absolute position of previous level
      x=this.popupGeoms[this.currentLevel-1].x;
      if(this.rightToLeft)
	x-=this.popupGeoms[this.currentLevel].width;
      else
	x+=this.popupGeoms[this.currentLevel-1].width;
    }
    //now x is the first guess for the absolute position of the current menu
    

    //if the menu extends beyond the left border, or if it is too big
    //for the window
    if(x<wing.XOffset||this.popupGeoms[this.currentLevel].width>=wing.width) {
      //align with left border
      x=wing.XOffset; this.rightToLeft=0; 
    } else if(x+this.popupGeoms[this.currentLevel].width>
	      wing.width+wing.XOffset){ //if it extends beyond the right margin
      x=wing.width+wing.XOffset-this.popupGeoms[this.currentLevel].width;
      //menu is aligned on right border.
      this.rightToLeft=1; 
    }
    
    this.popupGeoms[this.currentLevel].x=x;

    //relative positions
    this.popups[this.currentLevel].offsetX=x-this.popupGeoms[0].x;
    this.popups[this.currentLevel].offsetY=y-this.popupGeoms[0].y;
    debug("anchor="+this.MainAnchor+" level="+this.currentLevel+' x='+this.popups[this.currentLevel].offsetX
	  +" y="+this.popups[this.currentLevel].offsetY);
    this.popups[this.currentLevel].showPopup(this.MainAnchor);
    //    if(document.getElementById)
    // positionArrows(document.getElementById(divname));
    if(document.getElementById) {
      positionArrows(document.getElementById(divname));
    }
}


function Yams_makeDivs() {
  this.divsCreated=0;
  if(this.divsCreated) {
    alert("Yams_makeDivs called twice"); return;
  }
  this.divsCreated=1;
  for(var i=0;i<this.maxLevel;i++) {
    document.writeln('<div id="'+this.divBasename+i+'"'+
		     ' class="menuDivStyle">'+"\n&nbsp; </div>\n");
  }
}





function Yams_menuBar(menuName,menuVars,jsFunc) {
  //  var d=document.layers['mainMenu'];
  //d.document.open();
  //  alert("here"+d.id);
  //  alert(menuName+"_root");
  var menuId=this.menu[menuName+"_root"][0].sm;
  var menu=this.menu[menuId];
  var entries="";
  //  var menuBarID=NS4?' id="'+this.menuBarBasename+(this.idcounter++)+'"':
  //  "";
  if(menuVars)
    this.menuVars=menuVars;
  else
    this.menuVars=this.defaultMenuVars;
  if(typeof(jsFunc)=='undefined')
    jsFunc="";
  if(jsFunc)
    this.jsFunc=jsFunc;
  else
    this.jsFunc=this.defaultjsFunc;

  for(var i in menu) {
    if(typeof(menu[i].cond)!="undefined") {
      cond=evalLogical(menu[i].cond,this.menuVars);
      if(!cond) {
	continue;
      }
    }
    var uri=menu[i].uri;
    if(uri==null) uri="";
    var query=menu[i].qu;
    if(query==null) query="";
    entries+= 
      "<a class=\"menuButton\"  id=\""+
      this.anchorBasename+menu[i].sm
      +"\" name=\""+
      this.anchorBasename+menu[i].sm
      +"\"  "+
      "href=\"javascript:void(0)\" "+
      "onclick=\"if (window.yams) yams.displayMainMenu(event,'"+
      menu[i].sm + "', '"+ uri + "', '" +query 
      +"', '', '', '" + jsFunc + "');\" "+

      "onmouseover=\"if (window.yams &&yams.currentLevel>0) yams.displayMainMenu(event,'"+
      menu[i].sm + "', '"+ uri + "', '" +query 
      +"', '', '', '" + jsFunc + "');\" "+
      ">"+
      menu[i].ti       +"</a>&nbsp;\n";
  }
  var id='menuBar'+(this.idcounter++);
  var classname=NS4?"menuBarNS4":"menuBar";
  str=
    "<div id=\""+id+"\" class=\"" + classname+   "\">\n";
    str+=entries+
    "</div>\n";
  //  debug(str);
  document.writeln(str);

  //  d.document.close();
  //  d.visibility="visible";
}

function TreeImages_MakeImage(thisImage) {
  //needed for ie and other browsers
  extra=' width="18" height="18"';
  //  extra="";
  //preload image to eliminate problems in some browsers
  if(!this.imgs[thisImage]) {
    this.imgs[thisImage]=new Image(18,18);
    this.imgs[thisImage].src=this.imgBase+thisImage;
    //alert("made "+thisImage);
  }
  return('<img src="'  + this.imgBase+thisImage
	 + '" align="left" border="0" '+extra+'>');
  this.counter++;
}

function relUrl(url) {
  var re =new RegExp("(((http|https):)*(//[^/]*/[^/]*))");
  url="http://daria.mynet/acivs2004V2/tst/tstr.php";
  pp=url.replace(re,"");
  var re =new RegExp("/[^/]*$");
  nn=pp.replace(re,"");
  var re =new RegExp("/[^/]+","g");
  mm=nn.replace(re,"../");
  var re =new RegExp("/$");
  return mm.replace(re,"");
}

function TreeImages(imgbase) 
{ 
  this.counter=0;
  this.imgs=new Array();
  this.makeImage=TreeImages_MakeImage;
  this.imgBase=imgbase?imgbase:'images/';
  this.root=this.makeImage("menu_new_root.gif");
  this.bar=this.makeImage("menu_bar.gif");
  this.blank=this.makeImage("menu_pixel.gif");
  this.corner=this.makeImage("menu_corner.gif");
  this.tee=this.makeImage("menu_tee.gif");
  this.tee_minus=this.makeImage("menu_tee_minus.gif");
  this.tee_plus=this.makeImage("menu_tee_plus.gif");
  this.folder_open=this.makeImage("menu_folder_open.gif");
  this.folder_closed=this.makeImage("menu_folder_closed.gif");
  this.link_default=this.makeImage("menu_link_default.gif");
  this.link_external=this.makeImage("menu_link_external.gif");

}




function Yams_displayTreeMenuPane(root,start,level,imgs,
				  currentUrl,currentQuery,currentTarget,
				  currentJsFunc)
{

  // alert("root="+root+" start="+start);
  var menuStr="";
  var sub=null;
  var url="";
  var query="";
  var target="";
  var jsFunc="";
  var jsArgs=false;
  if(!level) level=0;
  if(!imgs) imgs="";
  if(!currentQuery)currentQuery="";
  if(!currentTarget)currentTarget="";
  if(!currentUrl)currentUrl="";
  if(typeof(currentJsFunc)=="undefined") {
    currentJsFunc="";
  }
  //  alert("pane");
  var levelStates=Array(); //in which states is each of the levels on this
  //line?
  var menu=yams.menu[start];
  var count=menu.length;
  for (var i in menu)
      {
	debug(i);
	obj=menu[i];
	if(typeof(obj.cond)!="undefined") {
	  var cond=evalLogical(obj.cond,this.menuVars);
	  if(!cond) {
	    continue;
	  }
	}	
	url=currentUrl;
	query="";//currentQuery;
	if(currentJsFunc) {
	  jsFunc=currentJsFunc;
	}
	else
	  jsFunc="";
 
	target=currentTarget;
	if(menu[i].uri&&menu[i].uri.length>0) {
	  if(menu[i].uri.charAt(0)=='|')
	    url+=menu[i].uri.slice(1);
	  else
	    url=menu[i].uri;
	}
	if(!url)
	  url=this.baseUri;
	else if(!url.match("^([^:]*:)*/")) {
	  url=this.baseUri+url;
	} 
	if(typeof(menu[i].jsf)!="undefined")
	  jsFunc=menu[i].jsf;
	if(menu[i].jsa)
	  jsArgs=menu[i].jsa;
	if(menu[i].qu&&menu[i].qu.length>0) {
	  //	  debug("current="+currentQuery+" qu="+menu[i].qu);
	  //      debug("charat="+menu[i].qu.charAt(0));
	  if(menu[i].qu.charAt(0)=='|')
	    query=currentQuery+menu[i].qu.slice(1);
	  else
	    query=menu[i].qu;
	  //	  debug("current="+currentQuery+" qu="+menu[i].qu+"->"+query);
	}
	if(menu[i].tg&&menu[i].tg.length>0) {
	  target=menu[i].tg;
	}
	var title="";
	if(menu[i].tt) {
	  title='title="'+(menu[i].tt?menu[i].tt:"")+'" ';
	} 	
	if(!obj.sm) {
	  if(query) {
	    var parts=query.split('?');
	    if(parts[0].length==0) {
	      if(parts.splice)
		parts.splice(0,1);
	      else
		parts=parts.slice(1);
	    }
	    if(parts.length==0)
	      query=false;
	    else if(parts.length==1)
	      query=parts[0];
	    else 
	      query=parts.join("&amp;");
	  }
	  
	  var js="";
	  if(jsFunc) {
	    if(jsArgs===false)
	      js="onclick=\""+jsFunc+"();\"";
	    else
	      js="onclick=\""+jsFunc+"('"+jsArgs+"');\"";
	    url="javascript:void(0)";
	  }

	  var tclass= (window.location.href.match(url+"$")) 
	    ?"treeItemSelected":"treeItem";
	  //  debug("tclass="+tclass+" url="+url+" l="+window.location.href);
	  var oc='onclick="return yams.changeColor(this);"';
	  var tg=(target!='')?' target="'+target+'"':'';
	  if(query) url+=("?"+query);
	  sub='<tr><td>'+imgs;
	  sub+=  ((i==count-1)?this.treeImages.corner:this.treeImages.tee);
	  sub+='<a class="'+tclass+'" ' 
	    +js+ oc+ ' href="'+url+'"'+title+tg+'>';
	  //alert("here"+url);
	  sub+= this.treeImages.makeImage(MTMFetchIcon(url))+obj.ti+'</a>';
	  sub+="</td></tr>\n";
	} else {
	  if(yams.visibleTreePanes[obj.sm]==null && level==0)
	    yams.visibleTreePanes[obj.sm]=false;
	  oc='onclick="if(window.yams) yams.clickTree(' + "'" + root +"', '" + 
	    obj.sm + "')" + ';" ';
	  om="onmouseover=\"javascript:window.status='"+
	    (yams.visibleTreePanes[obj.sm]?"Collapse ":"Expand ")
	    +(menu[i].tt?menu[i].tt:"item")
	    +"'; return true;\" ";

	  sub="<tr><td>"+imgs+
	    '<a class="treeItem" href="javascript:void(0);" '+title 
	    +oc+om +'>';
	  sub+= (yams.visibleTreePanes[obj.sm]
	  ?(this.treeImages.tee_minus+this.treeImages.folder_open)
	  :(this.treeImages.tee_plus+this.treeImages.folder_closed));
	  sub+=obj.ti+'</a>\n';
	  sub+="</td></tr>\n";
	  if(yams.visibleTreePanes[obj.sm])
	    sub+=this.displayTreeMenuPane(root,obj.sm,level+1,
			      imgs+((i==count-1)?this.treeImages.blank:
				    this.treeImages.bar),url,query,target,
					  currentJsFunc);
	}
	menuStr+= sub;
      }
  menuStr+="\n";
return menuStr;
}


function Yams_displayTreeMenu(whichMenu,menuVars)
{
  //hack for ie-bug which causes same image to load twice
  if(false&&IE)
    this.imgBase=relUrl(location.href)+this.imgBase;


  if(!this.visibleTreePanes) {
    this.visibleTreePanes=Array();
    var str=this.treeGetCookie();
    //    alert("cookie="+str);
    var parts=str.split(" ");
    for(i in parts) {
      this.visibleTreePanes[parts[i]]=true;
    }
  }
  if(menuVars)
    this.menuVars=menuVars;
  else
    this.menuVars=this.defaultMenuVars;
  
  //we switch between two panes because netscape on linux crashes
  //if we use only one
  if(!this.treeImages)this.treeImages=new TreeImages(this.imgBase);
  title=this.menu[whichMenu+'_root'][0].ti;
  if(this.treePanes[this.currentTreePane]) {
    this.treePanes[this.currentTreePane].hidePopup();
  }
  this.currentTreePane=(this.currentTreePane==0)?1:0;
  if(!this.treePanes[this.currentTreePane]) {     
    this.treePanes[this.currentTreePane]=
      new PopupWindow('TreeMenuDiv'
		      +this.currentTreePane);
  }
  str=this.displayTreeMenuPane(whichMenu,whichMenu);
  str='<div class="TreeMenuDiv">'+"\n<br>\n"
    +'<table border="0" cellpadding="0" cellspacing="0">'
    +"\n<tbody>\n"
    +"<tr><td>\n"
    +'<a class="treeItem" href="#" >'+this.treeImages.root+title+"</a>\n"
    +"</td></tr>\n"
    + str
    +"</tbody>\n</table>\n"
    +'</div>';

  //debug(str);
  
  this.treePanes[this.currentTreePane].populate(str);
  //this.treePanes[this.currentTreePane].refresh();
  if(IE&&!this.hasinited) {
    this.hasinited=true;
    //we can test each image using img.complete to check if images
    //  have indeed been loaded.
    schedIEBugFix(this.currentTreePane);
  }
else
  this.treePanes[this.currentTreePane].showPopup("treeMenuAnchor");

}

function schedIEBugFix(ctp) {
  var complete=true;
  var imgs=yams.treeImages.imgs;
  //kkcount++;
  for(var i in imgs) {
      // alert(i+"="+this.treeImages.imgs[i].complete);
    if(!imgs[i].complete)
	complete=false;
  }
  //alert("complete="+complete);
  if(!complete)
    setTimeout('schedIEBugFix('+ctp+');',500);
  else {
    //alert("doing it "+kkcount);
    yams.treePanes[ctp].showPopup("treeMenuAnchor");
  }
}

function Yams_clickTree(root,id)
{
  if(!yams.visibleTreePanes[id])
    yams.visibleTreePanes[id]=true;
  else
    yams.visibleTreePanes[id]=false;
  
  yams.displayTreeMenu(root);
  this.treeSetCookie();
}

function Yams_changeColor(item)
{
   if(item.className &&item.className!="treeItemSelected")
     item.className="treeItemSelected";
  //  alert(item.href);
  return true;
}


function Yams_treeMakeCookie()
{
  var str="";
  for(var i in yams.visibleTreePanes)
    {
      if(yams.visibleTreePanes[i])
	str+= (i+" ");
    }
  return str;
}



function Yams_treeSetCookie()
{
  expdate=new Date();
  expdate.setTime(expdate.getTime() + 365*24*60*60*1000); //cookie expires in 1 year
  var str=this.treeMakeCookie();
  //  alert("cookie "+ this.treeCookieName+" set to="+str);
  setCookie(this.treeCookieName, str, expdate, 0, 0, 0);
}

function Yams_treeGetCookie()
{
  //  alert("reading cookie from"+this.treeCookieName);
  return getCookie(this.treeCookieName);
}


function Yams_addTreeMenu(menuID)
{
  this.treeMenus[menuID]=menuID;
}

function Yams_init()
{
  if(this.initLock)
    return;		    
  this.initLock=true;
  for(i in yams.treeMenus) {
    yams.displayTreeMenu(i);
  }
  this.initLock=false;
  return true;
}



function Yams_processRegExps(str)
{
  var matches=str.match(/%%([^%]*)%%/g);
  var vnames=new Array();
  //  debug("str="+str,true);
  if(this.menuVars&&matches) {
    for(var i=0; i<matches.length;i++) {
      //      debug("i="+matches[i],true);
      str=str.replace(matches[i],
		      eval("this.menuVars."+
			   matches[i].slice(2,matches[i].length-2)));
      //      vnames[i]=matches[i].slice(1,matches[i].length-1);
    }
  }
  return str;
}


function Yams_keyPress(ev) {
  ev || (ev = window.event);
  yams.stopEvent(ev);
  debug("KEY="+ev.keyCode+" "+ev.charCode);
  if (ev.keyCode == 27) {
    if(window.yams)
      yams.hideDeepestMenu();
    return false;
  }
  var key = String.fromCharCode(IE ? ev.keyCode : ev.charCode).toLowerCase();
  if(false)
  for (var i = keys.length; --i >= 0;) {
    var k = keys[i];
    if (k[0].toLowerCase() == key)
      k[1].__msh.activate();
  }
}

function Yams_setBaseUri(val) 
{
  this.baseUri=val;
}

function Yams_setImgBase(val) 
{
  this.imgBase=val;
}

function Yams()
{

  this.menuVars=false;
  this.defaultMenuVars=false;
  this.defaultJsFunc=false;

  this.maxLevel=10; //maximum number of simultaneously displayed menus
                    //will be reduced to number of divs in html doc
  this.menu=new Array();
  this.divBasename="YamsDiv";
  this.anchorBasename="YamsA";
  this.menuBarBasename="YamsA";
  this.currentLevel=0; //number of curently popped up menupanes.
  this.popups=new Array(); //popup menus
  this.popupGeoms=new Array(); //positions and dimensions 
                               //of each popped-up menupane
                               //level 0 corresponds to current anchor
  this.idcounter=1;    //used to generate unique ids
  this.MainAnchor=""; //id of current anchor
  this.SubAnchor=""; //id of current anchor
  this.rightToLeft=0; //cascading menus are normally laid out left to right
                      //if rightToLeft=1 the opposite is true
  //Submenus should be placed on the right

  this.baseUri=""; //base for relative urls;
  this.imgBase="images/";

  this.treePanes= new Array(); //for tree menu
  this.currentTreePane=0; //for tree menu
  var temp=window.location.pathname.split("/");
  this.treeCookieName="/treemenu/"+temp[1]+"menu";
  


  this.formsToHide=Array();
  this.currentUrl="";
  this.currentQuery="";

  this.currentY=0;
  this.addEvent=Yams_addEvent;
  this.removeEvent=Yams_removeEvent;
  this.stopEvent=Yams_stopEvent;
  this.displayMainMenu=Yams_displayMainMenu;
  this.displayMenu=Yams_displayMenu;
  this.generateMenu=(NS4)?Yams_generateMenuNS4:Yams_generateMenu;
  this.hideSubMenu=Yams_hideSubMenu;
  this.hideDeepestMenu=Yams_hideDeepestMenu;
  this.hideMenus=Yams_hideMenus;
  this.setBaseUri=Yams_setBaseUri;
  this.setImgBase=Yams_setImgBase;
  this.divExists=Yams_divExists;
  this.getAnchorPosition=Yams_getAnchorPosition;
  this.menuBar=Yams_menuBar;
  this.makeDivs=Yams_makeDivs;
  this.showHideForms=Yams_showHideForms;
  //  this.menuBarOver=Yams_menuBarOver;
  this.displayTreeMenuPane=Yams_displayTreeMenuPane;
  this.displayTreeMenu=Yams_displayTreeMenu;
  this.clickTree=Yams_clickTree;
  this.changeColor=Yams_changeColor;
  this.treeMakeCookie=Yams_treeMakeCookie;
  this.treeSetCookie=Yams_treeSetCookie;
  this.treeGetCookie=Yams_treeGetCookie;
  this.addTreeMenu=Yams_addTreeMenu;
  this.processRegExps=Yams_processRegExps;
  this.keyPress=Yams_keyPress;
  this.init=Yams_init;
  this.initLock=false;
  this.treeMenus=Array();
  this.use_gebi = false;
  this.use_css = false;
  this.use_layers = false;
  if (document.getElementById) { this.use_gebi = true; }
  else if (document.all) { this.use_css = true; }
  else if (document.layers) { this.use_layers = true; }
  window.YamsOldOnloadHandler = window.onload;
  if (window.YamsOldOnloadHandler != null) {
    window.onload = new Function("window.YamsOldOnloadHandler(); Yams_init();");
  }
  else {
    window.onload = Yams_init;
  }
  if(NS4) {
    window.YamsOldOnResizeHandler = window.onresize;
    if (window.YamsOldOnResizeHandler != null) {
      window.onresize = new Function("window.YamsoldOnResizeHandler(); Yams_init();");
    }
    else {
      window.onresize = Yams_init;
    }
  }
}




if(!window.yams_included) {
  window.yams_included=true;
} else alert("Yams included twice");

//if(!window.yams)
  yams=new Yams();


//regular menu item: [ label,  url, tooltip ] 
//submenu item:      [ label, false, submenuid , tooltip ]
//tooltip is always optional


//the following functions were taken from Morten's JavaScript Tree Menu
// http://www.treemenu.com/

// Copyright (c) 2001, Morten Wang & contributors
// All rights reserved.

// This software is released under the BSD License which should accompany
// it in the file "COPYING".  If you do not have this file you can access
// the license through the WWW at http://www.treemenu.com/license.txt


function MTMIconList() {
	this.items = new Array();
	this.addIcon = MTMaddIcon;
}

function MTMaddIcon(item) {
	this.items[this.items.length] = item;
}

function MTMIcon(iconfile, match, type) {
	this.file = iconfile;
	this.match = match;
	this.type = type;
}

function MTMFetchIcon(testString) {
  var i;
  for(i = 0; i < MTMIconList.items.length; i++) {
    if((MTMIconList.items[i].type == 'any') && (testString.indexOf(MTMIconList.items[i].match) != -1)) {
      return(MTMIconList.items[i].file);
    } else if((MTMIconList.items[i].type == 'pre') && (testString.indexOf(MTMIconList.items[i].match) == 0)) {
      return(MTMIconList.items[i].file);
    } else if((MTMIconList.items[i].type == 'post') && (testString.indexOf(MTMIconList.items[i].match) != -1)) {
      if((testString.lastIndexOf(MTMIconList.items[i].match) + MTMIconList.items[i].match.length) == testString.length) {
	return(MTMIconList.items[i].file);
      }
    }
  }
  return("menu_link_default.gif");
}

MTMIconList = new MTMIconList();
MTMIconList.addIcon(new MTMIcon("menu_link_external.gif", "http://", "pre"));
MTMIconList.addIcon(new MTMIcon("menu_link_pdf.gif", ".pdf", "post"));



