//------------------------------------
// Created on 5.1.2005
// (c) Jan Ptacek
//------------------------------------

// load our stylesheet
//addStyleSheet('menu.horizontal', 'menu.horizontal/style.css');

// register onload init
addListener(window, 'load', addBehavior);

//------------------------------------
//
//------------------------------------

function addBehavior() {
	// get menu roots
	var node;
	var i = 0;
	var k = 1;
	while((node = document.getElementsByTagName('UL').item(i++))) {
		if (node.className == 'hmenu') {
			for (var j = 0; j < node.childNodes.length;j++) {
				if (node.childNodes[j].tagName == 'LI')
					initMenuItem(node.childNodes[j], k++);
			}
		}
	}
}

function initMenuItem(li, num) {
	// to emulate :first-child
	if (num == 1) {
		li.style.borderTopWidth = '1px';
		li.style.borderLeftWidth = '1px';
	}

	for (var i = 0; i < li.childNodes.length;i++) {
		if (li.childNodes[i].tagName == 'UL') {
			var nodeUL = li.childNodes[i];
			li.cachedUL = nodeUL;
			// 1 + n-level submenu
			if (li.parentNode.className != 'hmenu') {
				// background arrow
				li.style.backgroundRepeat = 'no-repeat';
				li.style.backgroundImage = 'url("images/sub.gif")';
				li.style.backgroundColor = 'white';
				li.style.backgroundPosition = '99%';
			}
			addListener(li, 'mouseover', showSubmenu);
			addListener(li, 'mouseout',  hideSubmenu);

			var k = 1;
			for (var j = 0; j < nodeUL.childNodes.length;j++) {
				if (nodeUL.childNodes[j].tagName == 'LI')
					initMenuItem(nodeUL.childNodes[j], k++);
			}
		}
	}
}

function showSubmenu(e) {
	if (!e) var e = window.event;
	var target = getTarget(e);
	if (target.tagName == 'A')
		target = target.parentNode;
	if (target.cachedUL) {
		target.cachedUL.style.display = 'block';
	}
}

function hideSubmenu(e) {
	if (!e) var e = window.event;
	var target = getTarget(e);
	var related = getRelatedTarget(e);
	if (!related || related.tagName == 'HTML')
		related = document.getElementsByTagName('body')[0];

	// maybe mouse left only into successor, handle
	if (target.tagName == 'A')
		target = target.parentNode;
	if (isAncestor(target, related))
		return;
	// it left into ancestor
	// find ul upon related node or body
	var commonUL = related;
	while (commonUL.tagName != 'UL' && commonUL.tagName != 'BODY')
		commonUL = commonUL.parentNode;
	// iterate up the tree from target till commonUL and close submenu
	while (target != commonUL && target.tagName != 'BODY') {
		if (target.cachedUL)
			target.cachedUL.style.display = 'none';
		target = target.parentNode;
	}
}

function isAncestor(ancestor, child) {
	while (child != ancestor && child.nodeName != 'BODY')
		child = child.parentNode;
	return child == ancestor ? 1 : 0;
}

