/**
 * dropDownMenu v0.5 sw edition
 * An easy to implement dropDown Menu for Websites, that may be based on styled list tags
 *
 * Works for IE 5.5+ PC, Mozilla 1+ all Plattforms, Opera 7+
 *
 * Copyright (c) 2004 Knallgrau New Medias Solutions GmbH, Vienna - Austria
 *
 * Original written by Matthias Platzer at http://knallgrau.at
 *
 * Modified by Sven Wappler http://www.wappler.eu
 *
 * Use it as you need it
 * It is distributed under a BSD style license
 */


/**
 * Container Class (Prototype) for the dropDownMenu
 *
 * @param idOrElement     String|HTMLElement  root Node of the menu (ul)
 * @param name            String              name of the variable that stores the result
 *                                            of this constructor function
 * @param customConfigFunction  Function            optional config function to override the default settings
 *                                            for an example see Menu.prototype.config
 */
var Menu = Class.create();
Menu.prototype = {

	initialize: function(idOrElement, name, customConfigFunction) {

		this.name = name;
		this.type = "menu";
		this.closeDelayTimer = null;
		this.closingMenuItem = null;

		this.config();
		if (typeof customConfigFunction == "function") {
			this.customConfig = customConfigFunction;
			this.customConfig();
		}
		this.rootContainer = new MenuContainer(idOrElement, this);
	},

	config: function() {
	  this.collapseBorders = true;
	  this.quickCollapse = true;
	  this.closeDelayTime = 500;
	}

}

var MenuContainer = Class.create();
MenuContainer.prototype = {
	initialize: function(idOrElement, parent) {
		this.type = "menuContainer";
  		this.menuItems = [];
		this.init(idOrElement, parent);
	},

	init: function(idOrElement, parent) {
	  this.element = $(idOrElement);
	  this.parent = parent;
	  this.parentMenu = (this.type == "menuContainer") ? ((parent) ? parent.parent : null) : parent;
	  this.root = parent instanceof Menu ? parent : parent.root;
	  this.id = this.element.id;

	  if (this.type == "menuContainer") {
	  	if (this.element.hasClassName("level1")) this.menuType = "horizontal";
		else if (this.element.hasClassName("level2")) this.menuType = "dropdown";
		else this.menuType = "flyout";

	    if (this.menuType == "flyout" || this.menuType == "dropdown") {
	      this.isOpen = false;
		  Element.setStyle(this.element,{
	      	position: "absolute",
	      	top: "0px",
	      	left: "0px",
	      	visibility: "hidden"});
	    } else {
	      this.isOpen = true;
	    }
	  } else {
	    this.isOpen = this.parentMenu.isOpen;
	  }

	  var childNodes = this.element.childNodes;
	  if (childNodes == null) return;

	  for (var i = 0; i < childNodes.length; i++) {
	    var node = childNodes[i];
	    if (node.nodeType == 1) {
	      if (this.type == "menuContainer") {
	        if (node.tagName.toLowerCase() == "li") {
	          this.menuItems.push(new MenuItem(node, this));
	        }
	      } else {
	        if (node.tagName.toLowerCase() == "ul") {
	          this.subMenu = new MenuContainer(node, this);
	        }
	      }
	    }
	  }
	},

	getBorders: function(element) {
	  var ltrb = ["Left","Top","Right","Bottom"];
	  var result = {};
	  for (var i = 0; i < ltrb.length; ++i) {
	    if (this.element.currentStyle)
	      var value = parseInt(this.element.currentStyle["border"+ltrb[i]+"Width"]);
	    else if (window.getComputedStyle)
	      var value = parseInt(window.getComputedStyle(this.element, "").getPropertyValue("border-"+ltrb[i].toLowerCase()+"-width"));
	    else
	      var value = parseInt(this.element.style["border"+ltrb[i]]);
	    result[ltrb[i].toLowerCase()] = isNaN(value) ? 0 : value;
	  }
	  return result;
	},

	open: function() {
	  if (this.root.closeDelayTimer) window.clearTimeout(this.root.closeDelayTimer);
	  this.parentMenu.closeAll(this);
	  this.isOpen = true;
	  if (this.menuType == "dropdown") {
		Element.setStyle(this.element,{
			left: (Position.positionedOffset(this.parent.element)[0]) + "px",
			top: (Position.positionedOffset(this.parent.element)[1] + Element.getHeight(this.parent.element)) + "px"
		});

	  } else if (this.menuType == "flyout") {
	    var parentMenuBorders = this.parentMenu ? this.parentMenu.getBorders() : new Object();
	    var thisBorders = this.getBorders();
	    if (
	      (Position.positionedOffset(this.parentMenu.element)[0] + this.parentMenu.element.offsetWidth + this.element.offsetWidth + 20) >
	      (window.innerWidth ? window.innerWidth : document.body.offsetWidth)
	    ) {
			Element.setStyle(this.element,{
	      		left: (- this.element.offsetWidth - (this.root.collapseBorders ?  0 : parentMenuBorders["left"])) + "px"
			});
	    } else {
			Element.setStyle(this.element,{
	    		left: (this.parentMenu.element.offsetWidth - parentMenuBorders["left"] - (this.root.collapseBorders ?  Math.min(parentMenuBorders["right"], thisBorders["left"]) : 0)) + "px"
			});
	    }
		Element.setStyle(this.element,{
	    	top: (this.parent.element.offsetTop - parentMenuBorders["top"] - this.menuItems[0].element.offsetTop) + "px"
		});
	  }
	  Element.setStyle(this.element,{visibility: "visible"});
	},

	close: function() {
		Element.setStyle(this.element,{visibility: "hidden"});
		this.isOpen = false;
		this.closeAll();
	},

	closeAll: function(trigger) {
		for (var i = 0; i < this.menuItems.length; ++i) {
			this.menuItems[i].closeItem(trigger);
		}
	}

}


var MenuItem = Class.create();

Object.extend(Object.extend(MenuItem.prototype, MenuContainer.prototype), {
	initialize: function(idOrElement, parent) {
		var menuItem = this;
		this.type = "menuItem";
		this.subMenu;
		this.init(idOrElement, parent);
		if (this.subMenu) {
			this.element.onmouseover = function() {
				menuItem.subMenu.open();
			}
		} else {
		if (this.root.quickCollapse) {
		  this.element.onmouseover = function() {
			menuItem.parentMenu.closeAll();
		  }
		}
		  }
		  var linkTag = this.element.getElementsByTagName("A")[0];
		  if (linkTag) {
		 linkTag.onfocus = this.element.onmouseover;
		 this.link = linkTag;
		 this.text = linkTag.text;
		  }
		  if (this.subMenu) {
                    this.element.onmouseout = function() {
                      if (menuItem.root.openDelayTimer) window.clearTimeout(menuItem.root.openDelayTimer);
                      if (menuItem.root.closeDelayTimer) window.clearTimeout(menuItem.root.closeDelayTimer);
                      eval(menuItem.root.name + ".closingMenuItem = menuItem");
                      menuItem.root.closeDelayTimer = window.setTimeout(menuItem.root.name + ".closingMenuItem.subMenu.close()", menuItem.root.closeDelayTime);
                    }
		  }
	},
	openItem: function() {
	  this.isOpen = true;
	  if (this.subMenu) { this.subMenu.open(); }
	},

	closeItem: function(trigger) {
	  this.isOpen = false;
	  if (this.subMenu) {
	    if (this.subMenu != trigger) this.subMenu.close();
	  }
	}
});

/*this part is changed by russ - rbsantos@kanati.com.ph*/
/*remove ugly mouse events handling*/

KanatiMenuItem = Class.create();

Object.extend(KanatiMenuItem.prototype,{
	initialize: function(idOrElement, parent) {
		var menuItem = this;                
		this.type = "menuItem";
		this.subMenu;
		this.init(idOrElement, parent);
                
                //bind event methods:
                this._onmouseout = this._onmouseout.bindAsEventListener(this);
                this._onmouseover = this._onmouseover.bindAsEventListener(this);
                //bind closeer
                this._closeMenu = this._closeMenu.bind(this);                
                 Event.observe(this.element,'mouseover',this._onmouseover,false);
		 var linkTag = this.element.getElementsByTagName("A")[0];
		 if (linkTag) {
                     Event.observe(linkTag,'focus',this._onmouseover,false)                     
                     this.link = linkTag;
                     this.text = linkTag.text;
		  }
		  if (this.subMenu) {
                      Event.observe(this.element,'mouseout',this._onmouseout,false);
		  }
	},
        _onmouseover:function(e){            
            if (this.subMenu){                
                
                this.subMenu.open();    
            }else if( this.root.quickCollapse){
                this.parentMenu.closeAll();
            }
            
        },
        _closeMenu:function(){
            this.root.closingMenuItem.subMenu.close();
        },
        _onmouseout : function() {
            try{
          var menuItem = this;
          if (menuItem.root.openDelayTimer) window.clearTimeout(menuItem.root.openDelayTimer);
          if (menuItem.root.closeDelayTimer) window.clearTimeout(menuItem.root.closeDelayTimer);
          menuItem.root.closingMenuItem = menuItem;
          //this._closeMenu();
          this._closeMenu.delay;
          menuItem.root.closeDelayTimer = this._closeMenu.delay(menuItem.root.closeDelayTime/1000);
          //menuItem.root.closeDelayTimer = this._closeMenu.delay(menuItem.root.closeDelayTime);
          var v = this;
          }catch(e){
              console.log(e);
          }
        }
        
});
KanatiMenuContainer = Class.create();
//add effects to MenuContaier
Object.extend(KanatiMenuContainer.prototype,{
        super_initialize: MenuContainer.prototype.initialize,
        initialize:function(idOrElement,parent){
            this.super_initialize(idOrElement,parent);
            this.close = this.close.bind(this);
            this._afterSlideDownEffect = this._afterSlideDownEffect.bindAsEventListener(this);
            this._beforeSlideUpEffect = this._beforeSlideUpEffect.bindAsEventListener(this);
        },
        init: function(idOrElement, parent) {
	  this.element = $(idOrElement);
          this.element.removeClassName('noscript');
	  this.parent = parent;
	  this.parentMenu = (this.type == "menuContainer") ? ((parent) ? parent.parent : null) : parent;
	  this.root = parent instanceof Menu ? parent : parent.root;
	  this.id = this.element.id;

	  if (this.type == "menuContainer") {
	  	if (this.element.hasClassName("level1")) this.menuType = "horizontal";
		else if (this.element.hasClassName("level2")) this.menuType = "dropdown";
		else this.menuType = "flyout";

	    if (this.menuType == "flyout" || this.menuType == "dropdown") {
	      this.isOpen = false;
		  Element.setStyle(this.element,{});
	    } else {
	      this.isOpen = true;
	    }
	  } else {
	    this.isOpen = this.parentMenu.isOpen;
	  }          
	  var childNodes = this.element.childNodes;
	  if (childNodes == null) return;

	  for (var i = 0; i < childNodes.length; i++) {
	    var node = childNodes[i];
	    if (node.nodeType == 1) {
	      if (this.type == "menuContainer") {
	        if (node.tagName.toLowerCase() == "li") {
	          this.menuItems.push(new MenuItem(node, this));
	        } else if (node.tagName.toLowerCase() == 'div'){
                    //reset loop
                    i = -1;
                    childNodes = node.childNodes;
                }
	      } else {
	        if (node.tagName.toLowerCase() == "ul") {
	          this.subMenu = new MenuContainer(node, this);
	        } 
                
	      }
	    }
	  }           
	},

        close:function (){
            var wasOpen = this.isOpen;
            this.isOpen = false;
            this.closeAll();
             if( this.menuType=='dropdown' ){
                if( this.downEffect ){
                    this.downEffect.cancel();
                    this.downEffect = null;
                }
                
                if( wasOpen ){
                    if( !this.upEffect ){
                        Element.setStyle(this.element,{'height':'auto'});
                        this.upEffect = new Effect.BlindUp(this.element,
                            {beforeStart:this._beforeSlideUpEffect,
                             fps:20,duration:.5,
                             transition:Effect.Transitions.SwingFrom});

                    }

                } 
            }else if(this.menuType =='flyout')  {
                if( this.downEffect ){
                    //this.downEffect.cancel();
                    this.downEffect = null;
                }                
                Element.setStyle(this.element,{visibility: "hidden"});
            }else  {                
                Element.setStyle(this.element,{visibility: "hidden"});
            }
                       
                       
        },
        _afterSlideDownEffect:function(){
            
        },
        _beforeSlideDownEffect:function(){
        },
        _beforeSlideUpEffect:function(){
           
            /*
            var elementDimensions = $(this.element).getDimensions();
            this.scaleMode= {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width};
             */
        },
    	open: function() {
          if (this.root.closeDelayTimer) window.clearTimeout(this.root.closeDelayTimer);
	  //moved close delay timer to affter effect is over
	  this.parentMenu.closeAll(this);
          var wasOpen = this.isOpen;
	  this.isOpen = true;
	  if (this.menuType == "dropdown") {              
                /* not needed anymore
		Element.setStyle(this.element,{
			left: (Position.positionedOffset(this.parent.element)[0]) + "px",
			top: (Position.positionedOffset(this.parent.element)[1] + Element.getHeight(this.parent.element)) + "px"
		});
                */
                if( !wasOpen ){
                    if( this.upEffect ){
                        this.upEffect.cancel();
                        this.upEffect = null
                    }
                    if( !this.downEffect ){
                        Element.setStyle(this.element,{'height':'auto'});
                        this.downEffect = new Effect.BlindDown(this.element,
                            {beforeStart:this._beforeSlideDownEffect.bind(this),
                             afterFinish:this._afterSlideDownEffect,duration:.5,fps:20,
                             transition:Effect.Transitions.SwingTo,
                             afterSetup:function(effect){
                                 effect.element;
                                 effect.element.makeClipping().setStyle({height: '0px',visibility:'visible'});
                                 effect.element.show(); 
                                 effect.element;
                             }});
                    }
                }                

              
              //new Effect.SlideDown(this.element);

	  } else if (this.menuType == "flyout") {
                if( !wasOpen ){
                    if( this.upEffect ){
                        this.upEffect.cancel();
                        this.upEffect = null
                    }
                    if( !this.downEffect ){
                        Element.setStyle(this.element,{'height':'auto'});
                        this.downEffect = new Effect.BlindDown(this.element,
                            {
                             scaleX:true,scaleY:false,
                             beforeStart:this._beforeSlideDownEffect.bind(this),
                             afterFinish:this._afterSlideDownEffect,duration:.5,fps:20,
                             transition:Effect.Transitions.SwingTo,
                             afterSetup:function(effect){
                                 effect.element;
                                 effect.element.makeClipping().setStyle({width: '0px',visibility:'visible'});
                                 effect.element.show(); 
                                 effect.element;
                             }});
                    }
                }              
           /*
	    var parentMenuBorders = this.parentMenu ? this.parentMenu.getBorders() : new Object();
	    var thisBorders = this.getBorders();
	    if (
	      (Position.positionedOffset(this.parentMenu.element)[0] + this.parentMenu.element.offsetWidth + this.element.offsetWidth + 20) >
	      (window.innerWidth ? window.innerWidth : document.body.offsetWidth)
	    ) {
			Element.setStyle(this.element,{
	      		left: (- this.element.offsetWidth - (this.root.collapseBorders ?  0 : parentMenuBorders["left"])) + "px"
			});
	    } else {
			Element.setStyle(this.element,{
	    		left: (this.parentMenu.element.offsetWidth - parentMenuBorders["left"] - (this.root.collapseBorders ?  Math.min(parentMenuBorders["right"], thisBorders["left"]) : 0)) + "px"
			});
	    }
		Element.setStyle(this.element,{
	    	top: (this.parent.element.offsetTop - parentMenuBorders["top"] - this.menuItems[0].element.offsetTop) + "px"
		});
             */
	  }
	  //Element.setStyle(this.element,{visibility: "visible"});
	}
});


Object.extend(MenuContainer.prototype,KanatiMenuContainer.prototype);
Object.extend(MenuItem.prototype,KanatiMenuItem.prototype)
function configMenu() {
  this.closeDelayTime = 300;
}
Menu.options = {autoLoad:true,elem:null}
Menu._onLoad = function (){
    if( Menu.options.autoLoad == false) return;
    var elem = this.options.elem;
    if( elem != null){
        if( elem[0] == null){
            elem = [elem];
        }
        for( var i=0; i < elem.length;i++){            
            var element = elem[i];
            element.object = this.initMenu(element.element_id,element.name,
                    element.configMenu);    
        }
        
    }
    
}
Menu._onUnload = function (){
    //nothing...let Prototype take care of cleaning objects.
}
Menu.initMenu = function ( elementId,name,configMenu ) {
  var menu = new Menu(elementId, name, configMenu);
  window[name] = menu;
  return menu;
}


Event.observe(window, 'load', Menu._onLoad.bind(Menu), false);

/*change by russ*/
Event.observe(window,'unload',Menu._onUnload.bind(Menu),false);
