// Changes by Diana Estrada May 2009
// I took this script and change it in a way that the nested submenus are not UL's, instead they are called using the
//   'rel' attribute
// So even though this script is based on the dynamicdrive.com the changes make it a complete new one

//** All Levels Navigational Menu- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com
//** Script Download/ instructions page: http://www.dynamicdrive.com/dynamicindex1/levelsMenu/
//** Usage Terms: http://www.dynamicdrive.com/notice.htm

//** July 7th, 08'- Creation Date

//** July 16th, 08'- Updated to v 1.3:
	//1) Adds "Side Bar" orientation option.
	//2) Drop Down Menus now auto adjust their positioning if too close to either right or bottom window edges.
	//3) Enhanced IFRAME shim "coverage" on the page.

//** July 19th, 08'- Updated to v 1.31: Drop down menu now positions at top of window edge if there's neither room downwards or upwards to settle.
//** Aug 13th, 08'- v1.32: Moved "rel" attribute from menu's <li> elements to inner <a>, for validation reasons

//** Sept 10th, 08'- Updated to v 1.4:
	//1) Added optional "sliding" animation when sub menus are revealed.
	//2) Arrow images now dynamically positioned, instead of relying on CSS's "right" property

//** Oct 11th, 08'- Updated to v 1.5:
	//1) Sliding animation behavior tweaked
	//2) Added ability to disable iframeshim, customize speed of sliding animation

//** Dec 23rd, 08'- Updated to v 2.0:
	//1) Animation speed refined to be function of time (ie: 1 sec)
	//2) Added two animations that can be individually enabled/disabled- "slide in" and "fade in".
	//3) Script now automatically moves HTML for all sub menus to the end of the page, to avoid any containership issues if they are nested in other elements.

//** Jan 12, 09'- Updated to v 2.1:
	//1) Added ability to disable the arrow images from the top level items (see option "showArrow")
	//2) For Top Level Menu items containing a SPAN element (for sliding doors technique), arrow images are inserted inside SPAN.

var levelsMenu={

enableShim: false, //enable IFRAME shim to prevent drop down menus from being hidden below SELECT or FLASH elements? (tip: disable if not in use, for efficiency)

arrowPointers:{
	downArrow: ["/images/styles/arrow-down.gif", 11,7], //[path_to_down_arrow, arrowwidth, arrowheight]
	rightArrow: ["/images/styles/arrow-right.gif", 12,12], //[path_to_right_arrow, arrowwidth, arrowheight]
	showArrow: {topLevel: true, subLevel: true} //Show arrow images on top level items and sub level items, respectively?
},
hideinterval: 200, //delay in milliseconds before entire menu disappears onmouseout.
effects: {enableswipe: true, enablefade: true, duration: 500},
httpsiframesrc: "blank.htm", //If menu is run on a secure (https) page, the IFRAME shim feature used by the script should point to an *blank* page *within* the secure area to prevent an IE security prompt. Specify full URL to that page on your server (leave as is if not applicable).

///No need to edit beyond here////////////////////

subMenus: {}, //object array containing all submenus
parentChild: {},
submenuIndex: 0,
hideTimers: {}, //object array timer
shimAdded: false,
shimmy: {},
nonFF: !/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent), //detect non FF browsers

getPosition:function(el){
	var obj = el
	var currentLeft = currentTop = 0;
	if (obj.offsetParent) {
    do {
			currentLeft += obj.offsetLeft;
			currentTop += obj.offsetTop;
    } while (obj = obj.offsetParent);

  }
  el._offsets = {left:currentLeft , top: currentTop}
},

isContained:function(m, e){
	var e=window.event || e
	var c=e.relatedTarget || ((e.type=="mouseover")? e.fromElement : e.toElement)
	while (c && c!=m)try {c=c.parentNode} catch(e){c=m}
	if (c==m)
		return true
	else
		return false
},

isLinkActive:function(m, mouseEvent){
	var menuName;
	var allLinks;
	var contained = false;
	if (m.getAttribute('rel')) {
	  var e=window.event || mouseEvent;
	  var c=e.relatedTarget || e.toElement;
	  if (c) {
	    if (c.id && (c.id == m.getAttribute('rel')))
	      return true;
	    else {
	      menuName=document.getElementById(m.getAttribute('rel'));
	      allLinks=menuName.getElementsByTagName("a");
	      for (var i=0; i<allLinks.length; i++){
	      	if (allLinks[i] == c)
	      	  contained = true;
	      }
	    }
	  }
	}
	return contained;
},

isSubMenuActive:function(m, mouseEvent){
	var menuName;
	var allLinks;
	var contained = false;
	if (m.id) {
		if(window.event) // IE check
      var to = window.event.toElement;
    if(mouseEvent && mouseEvent.target){ // standard-compliant browsers
      var to = mouseEvent.relatedTarget || mouseEvent.toElement;
      //to = to.relatedTarget || to.toElement;
    }
	  //var e=window.event || mouseEvent;
	  //var to=e.relatedTarget || e.toElement;
	  if (to){
	  	if (to.parentNode){
	  	  d=to.parentNode; // if mouse goes to a member of the same menu returns true
	      if (d.parentNode) {
	        if (m.id == d.parentNode.id){
	          return true;
	        }
	      }

	  	  menuName=document.getElementById(m.id);  // if mouse goes to a menu linked to the actual menu returns true
	      allLinks=menuName.getElementsByTagName("a");
	  	  for (var i=0; i<allLinks.length; i++){
	      	if (allLinks[i].getAttribute('rel') && (allLinks[i].getAttribute('rel') == to.id)){
	      	  return true;
	      	}
	      }

	      if (d.parentNode) {  // if mouse goes to a member of a linked menu returns true
	        if (d.parentNode.id) {
	          for (var i=0; i<allLinks.length; i++){
	          	if (allLinks[i].getAttribute('rel') == d.parentNode.id){
	          	  return true;
	          	}
	          }
	        }
	      }
	    }
	  }
	}
	return contained;
},

addPointer:function(target, imgclass, imginfo, BeforeorAfter){
	var pointer=document.createElement("img")
	pointer.src=imginfo[0]
	pointer.style.width=imginfo[1]+"px"
	pointer.style.height=imginfo[2]+"px"
	if(imgclass=="rightarrowpointer"){
		pointer.style.left=target.offsetWidth-imginfo[2]-2+"px"
	}
	pointer.className=imgclass
	var target_firstEl=target.childNodes[target.firstChild.nodeType!=1? 1 : 0] //see if the first child element within A is a SPAN (found in sliding doors technique)
	if (target_firstEl && target_firstEl.tagName=="SPAN"){
		target=target_firstEl //arrow should be added inside this SPAN instead if found
	}
	if (BeforeorAfter=="before")
		target.insertBefore(pointer, target.firstChild)
	else
		target.appendChild(pointer)
},

css:function(el, targetclass, action){
	//alert(el)
	var needle=new RegExp("(^|\\s+)"+targetclass+"($|\\s+)", "ig")
	if (action=="check")
		return needle.test(el.className)
	else if (action=="remove")
		el.className=el.className.replace(needle, "")
	else if (action=="add" && !needle.test(el.className))
		el.className+=" "+targetclass
},

addShimmy:function(target){
	var shim=(!window.opera)? document.createElement("iframe") : document.createElement("div") //Opera 9.24 doesnt seem to support transparent IFRAMEs
	shim.className="ddiframeshim"
	shim.setAttribute("src", location.protocol=="https:"? this.httpsiframesrc : "about:blank")
	shim.setAttribute("frameborder", "0")
	target.appendChild(shim)
	try{
		shim.style.filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'
	}
	catch(e){}
	return shim
},

positionshim:function(header, submenu, dir, scrollX, scrollY){
	if (header._isTopLevel){
		var scrollY=window.pageYOffset? window.pageYOffset : this.standardBody.scrollTop
		var topgap=header._offsets.top-scrollY
		var bottomgap=scrollY+this.docheight-header._offsets.top-header._dimensions.h
		if (topgap>0){
			this.shimmy.topshim.style.left=scrollX+"px"
			this.shimmy.topshim.style.top=scrollY+"px"
			this.shimmy.topshim.style.width="99%"
			this.shimmy.topshim.style.height=topgap+"px" //distance from top window edge to top of menu item
		}
		if (bottomgap>0){
			this.shimmy.bottomshim.style.left=scrollX+"px"
			this.shimmy.bottomshim.style.top=header._offsets.top + header._dimensions.h +"px"
			this.shimmy.bottomshim.style.width="99%"
			this.shimmy.bottomshim.style.height=bottomgap+"px" //distance from bottom of menu item to bottom window edge
		}
	}
},

hideshim:function(){
	this.shimmy.topshim.style.width=this.shimmy.bottomshim.style.width=0
	this.shimmy.topshim.style.height=this.shimmy.bottomshim.style.height=0
},


buildMenu:function(mainMenuId, header, subMenu, subMenuPos, isTopLevel, dir){
	header._master=mainMenuId //Indicates which top menu this header is associated with
	header._pos=subMenuPos //Indicates pos of sub menu this header is associated with
	header._isTopLevel=isTopLevel
	header._dimensions={w:header.offsetWidth, h:header.offsetHeight, subMenuW:subMenu.offsetWidth, subMenuH:subMenu.offsetHeight}
	this.subMenus[mainMenuId][subMenuPos]=subMenu
	this.getPosition(header)
	this.addEvent(header, function(e){ //mouseover event
		if (!levelsMenu.isContained(this, e)){
			//document.getElementById('text').innerHTML = document.getElementById('text').innerHTML + " peper " + this._pos;
			var subMenu=levelsMenu.subMenus[this._master][parseInt(this._pos)]
			//if (this._isTopLevel){
				levelsMenu.css(this, "selected", "add")
			clearTimeout(levelsMenu.hideTimers[this._master][this._pos])
			//}
			levelsMenu.getPosition(header)
			var scrollX=window.pageXOffset? window.pageXOffset : levelsMenu.standardBody.scrollLeft
			var scrollY=window.pageYOffset? window.pageYOffset : levelsMenu.standardBody.scrollTop
			//alert ("left " + this._offsets.left + " right " + this._offsets.top)
			var submenurightedge=this._offsets.left + this._dimensions.subMenuW + (this._isTopLevel && dir=="topbar"? 0 : this._dimensions.w)
			var submenubottomedge=this._offsets.top + this._dimensions.subMenuH
			//Sub menu starting left position
			var menuleft=(this._isTopLevel? this._offsets.left + (dir=="sidebar"? this._dimensions.w : 0) : this._offsets.left + (dir=="sidebar"? this._dimensions.w : 0))
			if (submenurightedge-scrollX>levelsMenu.docwidth){
				menuleft+= -this._dimensions.subMenuW + (this._isTopLevel && dir=="topbar" ? this._dimensions.w : -this._dimensions.w)
			}
			subMenu.style.left=menuleft+"px"
			//Sub menu starting top position
			//var menutop=(this._isTopLevel? this._offsets.top + (dir=="sidebar"? 0 : this._dimensions.h) : this.offsetTop)
			var menutop=this._offsets.top + (dir=="sidebar"? 0 : this._dimensions.h);
			if (submenubottomedge-scrollY>levelsMenu.docheight){ //no room downwards?
				if (this._dimensions.subMenuH<this._offsets.top+(dir=="sidebar"? this._dimensions.h : 0)-scrollY){ //move up?
					menutop+= - this._dimensions.subMenuH + (this._isTopLevel && dir=="topbar"? -this._dimensions.h : this._dimensions.h)
				}
				else{ //top of window edge
					menutop+= -(this._offsets.top-scrollY) + (this._isTopLevel && dir=="topbar"? -this._dimensions.h : 0)
				}
			}
			subMenu.style.top=menutop+"px"
			if (levelsMenu.enableShim && (levelsMenu.effects.enableswipe==false || levelsMenu.nonFF)){ //apply shim immediately only if animation is turned off, or if on, in non FF2.x browsers
				levelsMenu.positionshim(header, subMenu, dir, scrollX, scrollY)
			}
			else{
				subMenu.FFscrollInfo={x:scrollX, y:scrollY}
			}
			levelsMenu.showMenu(header, subMenu, dir)
		}
	}, "mouseover")
	this.addEvent(header, function(e){ //mouseout event
		if (!levelsMenu.isLinkActive(this, e)){
			//document.getElementById('text').innerHTML = document.getElementById('text').innerHTML + " peper " + this._pos;
		  var subMenu=levelsMenu.subMenus[this._master][parseInt(this._pos)];
		  subMenu._header = header;
		  levelsMenu.hideMenu(subMenu);
		}
	}, "mouseout")
},

setopacity:function(el, value){
	el.style.opacity=value
	if (typeof el.style.opacity!="string"){ //if it's not a string (ie: number instead), it means property not supported
		el.style.MozOpacity=value
		if (el.filters){
			el.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity="+ value*100 +")"
		}
	}
},

showMenu:function(header, submenu, dir){
	if (this.effects.enableswipe || this.effects.enablefade){
		if (this.effects.enableswipe){
			var endpoint=(header._isTopLevel && dir=="topbar")? header._dimensions.subMenuH : header._dimensions.subMenuW
			submenu.style.width=submenu.style.height=0
			submenu.style.overflow="hidden"
		}
		if (this.effects.enablefade){
			this.setopacity(submenu, 0) //set opacity to 0 so menu appears hidden initially
		}
		submenu._curanimatedegree=0
		submenu.style.visibility="visible"
		clearInterval(submenu._animatetimer)
		submenu._starttime=new Date().getTime() //get time just before animation is run
		submenu._animatetimer=setInterval(function(){levelsMenu.revealMenu(header, submenu, endpoint, dir)}, 10)
	}
	else{
		submenu.style.visibility="visible"
	}
},

revealMenu:function(header, submenu, endpoint, dir){
	var elapsed=new Date().getTime()-submenu._starttime //get time animation has run
	if (elapsed<this.effects.duration){
		if (this.effects.enableswipe){
			if (submenu._curanimatedegree==0){ //reset either width or height of sub menu to "auto" when animation begins
				submenu.style[header._isTopLevel && dir=="topbar"? "width" : "height"]="auto"
			}
			submenu.style[header._isTopLevel && dir=="topbar"? "height" : "width"]=(submenu._curanimatedegree*endpoint)+"px"
		}
		if (this.effects.enablefade){
			this.setopacity(submenu, submenu._curanimatedegree)
		}
	}
	else{
		clearInterval(submenu._animatetimer)
		if (this.effects.enableswipe){
			submenu.style.width="auto"
			submenu.style.height="auto"
			submenu.style.overflow="visible"
		}
		if (this.effects.enablefade){
			this.setopacity(submenu, 1)
			submenu.style.filter=""
		}
		if (this.enableShim && submenu.FFscrollInfo) //if this is FF browser (meaning shim hasn't been applied yet
			this.positionshim(header, submenu, dir, submenu.FFscrollInfo.x, submenu.FFscrollInfo.y)
	}
	submenu._curanimatedegree=(1-Math.cos((elapsed/this.effects.duration)*Math.PI)) / 2
},

hideMenu:function(submenu){
	if (typeof submenu._pos!="undefined"){ //if submenu is outermost UL drop down menu
		this.css(submenu._header, "selected", "remove");
		if (this.enableShim)
			this.hideshim()
	}
	clearInterval(submenu._animatetimer)
	submenu.style.left=0
	submenu.style.top="-1000px"
	submenu.style.visibility="hidden"
},

hideSubMenuParent:function(subMenu){
	clearInterval(subMenu._animatetimer)
	subMenu.style.left=0
	subMenu.style.top="-1000px"
	subMenu.style.visibility="hidden"
},

hideSubMenusAux:function(subMenu){
	//document.getElementById('text').innerHTML = document.getElementById('text').innerHTML + "<br/>" +
	//                                            subMenu.id +" pos "+ subMenu._pos;

	this.hideTimers[subMenu._mainMenu][subMenu._pos]=setTimeout(function(){
	  levelsMenu.hideSubMenuParent(subMenu)
	}, this.hideinterval);
},

hideSubMenu:function(subMenu, e){
	var counter = this.parentChild[subMenu._mainMenu].length;
	var mainMenu = subMenu._mainMenu;
	var tempMenu;
	var flag = false;
	if (counter){
		var tempChild = this.getMenuPosition(subMenu._master, subMenu.id);
		//document.getElementById('text').innerHTML = "<br/>"+document.getElementById('text').innerHTML + "<br/>subMenu " +subMenu.id;
		var tempParent = this.parentChild[subMenu._mainMenu][counter-1].parent;
	  var tempParentName = this.parentChild[subMenu._mainMenu][counter-1].parentName;

	  while (counter >0) {
	  	//document.getElementById('text').innerHTML = document.getElementById('text').innerHTML + "<br/>tempChild " +tempChild +
	  	//                                            " counter " + counter;
	    if (tempChild == (counter-1)) {
	    	if (this.parentChild[subMenu._mainMenu][counter-1].parent != -1){
	    		//document.getElementById('text').innerHTML = document.getElementById('text').innerHTML + "<br/>" +
	        //                                            this.parentChild[subMenu._mainMenu][counter-1].parent + " "+
	        //                                            tempChild + " "+
	        //                                            this.parentChild[subMenu._mainMenu][counter-1].parentName;
	        tempParent = this.parentChild[subMenu._mainMenu][counter-1].parentName;
	        tempSubMenu=document.getElementById(tempParent);
	        tempSubMenu._mainMenu = mainMenu;
	        tempSubMenu._pos = tempChild;
	        //document.getElementById('text').innerHTML = document.getElementById('text').innerHTML + "<br/>-" +counter;

	        if (!this.isSubMenuActive(tempSubMenu, e))
	          this.hideSubMenusAux(tempSubMenu);
	        else
	    	    flag=true;
	      }
	      tempChild = this.parentChild[subMenu._mainMenu][counter-1].parent;
	    }
	      if (flag)
	        counter = 0;
	      else
	        counter = counter-1
	  }
  }
	clearInterval(subMenu._animatetimer)
	subMenu.style.left=0
	subMenu.style.top="-1000px"
	subMenu.style.visibility="hidden"
},


addEvent:function(target, functionref, tasktype) {
	if (target.addEventListener)
		target.addEventListener(tasktype, functionref, false);
	else if (target.attachEvent)
		target.attachEvent('on'+tasktype, function(){return functionref.call(target, window.event)});
},


getMenuPosition:function(mainMenu, menuId) {
	for (var i=0; i < this.parentChild[mainMenu].length; i++){
		if (this.parentChild[mainMenu][i].childName == menuId)
		  return this.parentChild[mainMenu][i].child;
	}
},


getSubmenus:function(menuId, dir, isMainMenu, mainMenuId, parent){
	var menuName=document.getElementById(menuId);
	var allLinks=menuName.getElementsByTagName("a");
	var position;
	for (var i=0; i<allLinks.length; i++){
		if (allLinks[i].getAttribute('rel')){

			this.submenuIndex++;
			var menuLink=allLinks[i];
			var subMenu=document.getElementById(menuLink.getAttribute('rel'));
			if (subMenu) {
			  this.parentChild[mainMenuId].push({parent:parent, parentName:menuId, child:this.submenuIndex, childName:menuLink.getAttribute('rel')});
			  subMenu.style.zIndex=2000; //give drop down menus a high z-index
			  subMenu._master=mainMenuId;  //Indicate which main menu this main submenu is associated with
			  subMenu._pos=this.submenuIndex; //Indicate which main menu item this main UL is associated with
			  subMenu._position=this.submenuIndex;
			  //document.getElementById('text').innerHTML = document.getElementById('text').innerHTML + "<br/>_pos " +subMenu._pos;
			  subMenu._mainMenu=mainMenuId;
			  this.buildMenu(mainMenuId, menuLink, subMenu, this.submenuIndex, isMainMenu, dir); //build top level menu
			  //document.getElementById('text').innerHTML = document.getElementById('text').innerHTML + " peper " + subMenu.id;
			  subMenu.onmouseover=function(){
			  	clearTimeout(levelsMenu.hideTimers[this._master][this._position]);
			  }
			  this.addEvent(subMenu, function(e){ //hide menu if mouse moves out of main UL element into open space
			  	if (!levelsMenu.isSubMenuActive(this, e)){
			  		var subMenu=this;
			  		if (levelsMenu.enableShim)
			  			levelsMenu.hideshim()
			  	  position = levelsMenu.getMenuPosition(subMenu._master, this.id);
			  	  //document.getElementById('text').innerHTML = document.getElementById('text').innerHTML + "_position " +position;

			  		levelsMenu.hideTimers[this._master][position]=setTimeout(function(){
			  			//document.getElementById('text').innerHTML = document.getElementById('text').innerHTML + "<br/> subMenu " + subMenu.id;
			  		  levelsMenu.hideSubMenu(subMenu,e)
			  		}, levelsMenu.hideinterval)
			  		//document.getElementById('text').innerHTML = document.getElementById('text').innerHTML + "<br/> casita " + position;
			  	}
			  }, "mouseout")
			  this.getSubmenus(menuLink.getAttribute('rel'), dir, false, mainMenuId, this.submenuIndex);
			}

		}
	} //end for loop
},


init:function(mainMenuId, dir){
	this.standardBody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body;
	this.submenuIndex =-1;
	this.subMenus[mainMenuId]=[]; //declare array on object
	this.parentChild[mainMenuId]=[];
	this.hideTimers[mainMenuId]=[]; //declare hide entire menu timer
	if (this.enableShim && !this.shimAdded){
		this.shimmy.topshim=this.addShimmy(document.body); //create top iframe shim obj
		this.shimmy.bottomshim=this.addShimmy(document.body); //create bottom iframe shim obj
		this.shimAdded=true;
	}
	this.getSubmenus(mainMenuId, dir, true, mainMenuId, "-1");
},

setup:function(mainMenuId, dir){
	this.addEvent(window, function(){levelsMenu.init(mainMenuId, dir)}, "load");
}
}
