/**
 * dropDownMenu v1.0
 * 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+
 *
 * 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(element, options) {

		this.closeDelayTimer = null;
		this.closingMenuItem = null;
		this.fading = false;
		
		
		this.options = $H({
			collapseBorders: true,
			closeDelayTime: 5000,
			dropup: ((element.hasClassName("dropup")) ? true : false),
			fading: ((element.hasClassName("fading")) ? true : false)
        }).merge(options);
		
		this.rootContainer = new MenuContainer(element, this, 0);
		this.rootContainer.close(this.rootContainer,"init");
	},
	
	clearCloseTimer: function() {
		if (this.closeDelayTimer) window.clearTimeout(this.closeDelayTimer);
	},
	
	setCloseDelayTimer: function(obj) {
		this.clearCloseTimer();
		//this.closeDelayTimer = this.close.bind(this).delay(this.options.get('closeDelayTime') / 1000);
		
		this.closeDelayTimer = window.setTimeout(obj.root.close.bind(this,this), this.options.get('closeDelayTime'));
	},
	
	close: function(e) {
		this.rootContainer.close(this.rootContainer,"reset");
	}

}

var MenuContainer = Class.create();
MenuContainer.prototype = {
	initialize: function(element, parent, depth) {
		this.menuItems = [];
		this.element = element;
		this.parent = parent;
		this.depth = depth;
		this.parentMenu = (this.depth > 0) ? parent.parent : null;
		this.root = parent instanceof Menu ? parent : parent.root;
		this.parent = (this.depth == 0) ? null: this.parent;
		this.effect;

		if (this.depth == 0)
			this.menuType = "horizontal";
		else if (this.depth == 1)
			this.menuType = "dropdown";
		else
			this.menuType = "flyout";

		if (this.menuType == "flyout" || this.menuType == "dropdown") {
			Element.setStyle(this.element,{
				position: "absolute",
				top: "0px",
				left: "0px"});
		}
		

		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 && node.tagName.toLowerCase() == "li") {
				this.menuItems.push(new MenuItem(node, this, this.depth));
			}
		}

		if (this.menuType == "dropdown") {
			if (this.root.options.get("dropup")) {
				Element.setStyle(this.element, {
					left :(Position.positionedOffset(this.parent.element)[0]) + "px",
					top :(Position.positionedOffset(this.parent.element)[1]) - Element.getHeight(this.element) + "px"
				});
			} else {
				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.options.get('collapseBorders') ?  0 : parentMenuBorders["left"])) + "px"
				});
			} else {
				Element.setStyle(this.element,{
					left: (this.parentMenu.element.offsetWidth - parentMenuBorders["left"] - (this.root.options.get('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"
			});
		}
	},

	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() {
		
		this.root.clearCloseTimer();
		if (this.root.options.get("fading")) {
			this.effect = new Effect.Opacity(this.element, {duration:0.5, from: this.element.getOpacity() || 0, to:1.0});
		} else {
			Element.setStyle(this.element,{visibility: "visible"});
			Element.setStyle(this.element,{display: "block"});
		}
	},

	close: function(trigger,mode) {
		
		// Aufruf kommt von einem Child -> Aufruf nach oben weiterleiten und andere childs schließen
		if (this.parent != trigger) {
			
			if (this.parent) this.parent.close(this,mode);
			
			for (var i = 0; i < this.menuItems.length; ++i) {
				if (this.menuItems[i] != trigger) this.menuItems[i].close(this,mode);
			}
		}
		
		// Aufruf kommt von oben -> alle items schliessen
		if (trigger == this.parent) {
			if (this.depth > 0) {
				if (this.root.options.get("fading")) {
					Element.setStyle(this.element,{visibility: "visible"});
					if (mode == "init") {
						Element.setStyle(this.element,{opacity: 0});
						//Element.setStyle(this.element,{display: "none"});
					}
					//else Effect.Fade(this.element, { duration: 0.2 });
					else {
						this.effect = new Effect.Opacity(this.element, {duration:0.5, from: (this.element.getOpacity() != null) ? this.element.getOpacity() : 1.0, to: 0});
					}
				} else {
					Element.setStyle(this.element,{visibility: "visible"});
					Element.setStyle(this.element,{display: "none"});
				}
			}
			
			for (var i = 0; i < this.menuItems.length; ++i) {
				this.menuItems[i].close(this,mode);
			}
		}
	}

}


var MenuItem = Class.create();

MenuItem.prototype = {

	initialize: function(element, parent, depth) {
		this.element = element;
		this.parent = parent;
		this.depth = depth;
		this.root = parent.root;
		this.subMenu = null;
		
		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 && node.tagName.toLowerCase() == "ul") {
				this.subMenu = new MenuContainer(node, this, this.depth + 1);
			}
		}
		if (this.subMenu) {
			Element.addClassName(this.element,"parent");
		}
		
		Event.observe(this.element, 'mouseover', this.open.bindAsEventListener(this));
	
		var linkTag = this.element.getElementsByTagName("A")[0];
		if (linkTag) {
			this.link = linkTag;
			this.text = linkTag.text;
		}
		
		Event.observe(this.element,'mouseout', this.mouseOut.bindAsEventListener(this));
		if (this.subMenu) {
			Element.addClassName(this.link,'parent');
		}
	},
	
	mouseOut: function() {
		this.root.setCloseDelayTimer(this);
	},

	open: function() {
		
		this.root.clearCloseTimer();
		Element.addClassName(this.link,'act');
		this.close(this,false);
		if (this.subMenu) { this.subMenu.open(); }
	},

	close: function(trigger,mode) {
		if (trigger == this.parent) {
			// Aufruf kommt von oben -> alles schließen
			if (this.link) Element.removeClassName(this.link,'act');
			if ((mode == "reset" || mode == "init") && this.subMenu && Element.hasClassName(this.element,"openatreset")) {
				this.subMenu.open();
			} else 	if (this.subMenu) this.subMenu.close(this,mode);
		}
		if (trigger != this.parent) {
			// Aufruf kommt von einem submenu -> durchleiten
			this.parent.close(this,mode);
		}
	}
}


var swmenus = $H();

function initMenu() {
	
	$$("ul.swmenu").each(function(node){
		if (node.id == "") {
			alert("Menu has no ID!");
			return;
		}
		swmenus[node.id] = new Menu(node, {closeDelayTime: 500});
	});
	
  
}


Event.observe(window, 'load', initMenu, false);
