/* COPYRIGHT/LICENSE **********************************************************
Copyright (c) 2005 Tyler Karaszewski (http://tylerkaraszewski.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/

/* NOTE FROM THE AUTHOR *******************************************************
While I've licensed this code under the MIT license as you can see above, I'd
really appreciate a note via email (you can contact me at my website, from the
address listed at the top of the copyright notification) or a link on your site
back to mine if you find this software useful. Thanks, and I hope you like the
menu script!
*/

/* GENERAL SCRIPT INFORMATION *************************************************
A Better Javascript Dropdown Menu
Version: 1.0
Date: 5/18/2005
Author: Tyler Karaszewski
You can find more information on this script at:
http://tylerkaraszewski.com/experiments/better-javascript-menus/
******************************************************************************/

// Global variables are mostly used to preserve state during event propagation,
// or to keep track of global element IDs.
var menuHoverClassName = "menudivhover";
var menuId;
var noJSMenuId;
var menuClicked = false;
var menuItemClicked = false;
var isShowing = false;

// Gets the offest in pixels from the left edge of the window to the left edge
// of the element it's called on.
// Takes: element
// Returns: integer
function getOffsetLeft(el){
	var ol = 0;
	while(el){	
		ol += el.offsetLeft;
		el = el.OffsetParent;
	}
	return ol;
}

// Gets the offest in pixels from the top edge of the window to the top edge
// of the element it's called on. "Window" in this case refers to the page,
// and not the frame it's contained in. The signifigance of this is that this
// gets the distance from the top of the page's scrollable area, and not just
// the top of the visible area.
// Takes: element
// Returns: integer
function getOffsetTop(el){
	var ot = 0;
	while(el){	
		ot += el.offsetTop;
		el = el.OffsetParent;
	}
	return ot;
}

// Hides all visible menus in the global "menuId" element.
function hideAll(){
	var menus = document.getElementById(menuId).childNodes;
	for(var ii = 0; ii < menus.length; ii++){
		var menu = menus.item(ii);
		var children = menu.childNodes;
		for(var jj = 0; jj < children.length; jj++){
			if(children.item(jj).nodeName == "UL"){
				children.item(jj).style.visibility = "hidden";
			}
		}
	}
	isShowing = false;
}

// Hides a menu when one of it's items is clicked.
// Takes: onclick event
function hideClicked(e){
	menuItemClicked = true;
	hideAll();
	deselectAll();
}

// Runs every time the body or a sub-element is clicked on. The purpose of this
// is to hide menus after the body has been clicked on. Uses some of the
// globla menus to determine whether or not a menu was clicked on, and does the
// hiding appropriately.
// Takes: onclick event
function fixSelect(e){
	if(!menuClicked){
		hideAll();
		deselectAll();
	}
	menuClicked = false;
	menuItemClicked = false;
}

// Shows a menu when it's title is clicked, except when it was already visible,
// in which case it hides the menu. Maybe this function should have a better
// name.
// Takes: onclick event
function showMenu(e){
	menuClicked = !menuItemClicked;
	menuItemClicked = false;
	var wasShowing = isShowing;
	hideAll();
	if(!wasShowing) displayMenu(this);
}

// Shows a menu when it's title is moused-over, if another menu was already
// visible. Also sets the style of the menu title being hovered over with
// the mouse.
// Takes: onmouseover event
function showMenuHover(e){
	deselectAll();
	if(isShowing) displayMenu(this);
	this.className = menuHoverClassName;
}

// Makes it so none of the menu titles are showing thier "selected"
// appearance, and look unselected.
function deselectAll(){
	var menus = document.getElementById(menuId).childNodes;
	for(var ii = 0; ii < menus.length; ii++){
		menus.item(ii).className = "";	
	}	
}

// Stops highlighting a menu when the mouse moves off it. Does nothing if a
// menu is open, as the title should stay highlighted till the menu closes.
// Takes: onmouseout event
function stopMenuHover(e){
	if(!isShowing) this.className = "";
}

// Displays a menu, based on the element that contains it. This function should
// be passed an element thtat contains a single <ul> element (it can contain
// other elements, but only one <ul>). The <ul> is moved to the correct location
// and made visible.
// Takes: element
function displayMenu(el){
	var children = el.childNodes;
	var menu;
	hideAll();
	for(var ii = 0; ii < children.length; ii++){
		if(children.item(ii).nodeName == "UL") menu = children.item(ii);
	}
	if (window.innerWidth) //if browser supports window.innerWidth
		var ol = getOffsetLeft(menu.parentNode) + (window.innerWidth - 750)/2;
	else if (document.all) //else if browser supports document.all (IE 4+)
		var ol = getOffsetLeft(menu.parentNode) + (document.body.clientWidth- 750)/2;

	var ot = getOffsetTop(menu.parentNode);
	ot = menu.parentNode.offsetHeight + menu.parentNode.offsetTop + 175;
	menu.style.left = ol + "px";
	menu.style.top = ot + "px";
	menu.style.visibility = "visible";
	isShowing = true;
}

// Copies <ul> elemrnts from the non-javascript display element to the
// javascript-enabled element. Upon finishing copying, the non-javascript
// element is removed completely from the layout.
function copyULs(){
	var noJS = document.getElementById(noJSMenuId);
	var uls = noJS.childNodes;
	for(var ii = 0; ii < uls.length; ii++){
		cnulr(uls.item(ii));
	}		
	noJS.parentNode.removeChild(noJS);
}

// Recursive function to get UL elements out of non-javascript block, even 
// if they're not direct children of the non-js block. This lets you put ULs
// inside of divs to format the non-js block nicely.
function cnulr(el){
	if(el.nodeName == "UL") menuInsert(el);
	else{
		for(var ii = 0; ii < el.childNodes.length; ii++){
			cnulr(el.childNodes.item(ii));
		}
	}		
}

// Inserts a menu into the javascript-enabled menu. The menu is inserted inside
// a <div> element, and given a title based on the id of the list passed to
// this function. Menus are inserted after all existing menus, or other existing
// <div> elements. Any non-<div> elements in the "menuId" item end up being
// positioned after the menus.
// Takes: element (ul)
function menuInsert(list){
	menuName = list.id;
	var newMenu = document.createElement('div');
	newMenu.innerHTML = menuName;
	newMenu.appendChild(list);
	newMenu.unselectable = true;
	var menu = document.getElementById(menuId);
	if(menu.hasChildNodes){
		var nodeToInsertAfter = null;
		nodes = menu.childNodes;
		for(var ii = 0; ii < nodes.length; ii++){
			if(nodes.item(ii).nodeName == "DIV") nodeToInsertAfter = nodes.item(ii);
		}
		if(nodeToInsertAfter == null) menu.insertBefore(newMenu, menu.firstChild);
		else{
			var nodeToInsertBefore = nodeToInsertAfter.nextSibling;
			if(nodeToInsertBefore != null) menu.insertBefore(newMenu, nodeToInsertBefore);
			else menu.appendChild(newMenu);
		}
	}
	else{
		menu.appendChild(newMenu);
	}
}

// ****************************************************************************
// ***** THIS SHOULD RUN BEFORE ANY OTHER FUNCTION IN THIS FILE IS CALLED *****
// ****************************************************************************

// Registers all event handlers for menus and sub-elements. Also initializes
// the javascript menu from data contained in the non-javascript menu.
// Before completion, it registers an event handler for the <body> tag (of
// which there should exist exactly 1).
function registerMenus(noJS, divId){
	document.getElementById(noJS).style.display = "none";
	menuId = divId;
	noJSMenuId = noJS;
	copyULs();
	div = document.getElementById(divId);
	div.style.visibility = "visible";
	var menus = div.childNodes;
	for(var ii = 0; ii < menus.length; ii++){
		if(menus.item(ii).nodeName == "DIV"){
			menus.item(ii).onclick = showMenu;
			menus.item(ii).onmouseover = showMenuHover;
			menus.item(ii).onmouseout = stopMenuHover;
			var lists = menus.item(ii).childNodes;
			for(var hh = 0; hh < lists.length; hh++){
				if(lists.item(hh).nodeName == "UL"){
					var litems = lists.item(hh).childNodes;
					var lwidth = 0;
					lwidth = lists.item(hh).offsetWidth;
					for(var jj = 0; jj < litems.length; jj++){
						var links = litems.item(jj).childNodes;
						for(var kk = 0; kk < links.length; kk++){
							if(links.item(kk).nodeName == "A"){
								links.item(kk).onclick = hideClicked;
								links.item(kk).style.width = lwidth + "px";
							}
						}
					}
				}
			}           // Look at all those closing brackets! :P
		}
	}
	document.getElementsByTagName("body").item(0).onclick = fixSelect;
}