var isDOM = (document.getElementById ? true : false); 
var isIE4 = ((document.all && !isDOM) ? true : false);
var isNS4 = (document.layers ? true : false);
var menu = new Array();
var topEdge = 130;

function getRef(id) {
	if (isDOM) return document.getElementById(id);
	if (isIE4) return document.all[id];
	if (isNS4) return document.layers[id];
}

function getStyle(id) {
	return (isNS4 ? getRef(id) : getRef(id).style);
}

// Hide timeout.
var popTimer = 0;
// Array showing highlighted menu items.
var litNow = new Array();
function popOver(menuNum, itemNum) {
	clearTimeout(popTimer);
	hideAllBut(menuNum);
	litNow = getTree(menuNum, itemNum);
	changeCol(litNow, true);
	targetNum = menu[menuNum][itemNum].target;
	if (targetNum > 0) {
		thisX = parseInt(menu[menuNum][0].ref.left) + parseInt(menu[menuNum][itemNum].ref.left);
		thisY = parseInt(menu[menuNum][0].ref.top) + parseInt(menu[menuNum][itemNum].ref.top);
		with (menu[targetNum][0].ref) {
			left = parseInt(thisX + menu[targetNum][0].x);
			top = parseInt(thisY + menu[targetNum][0].y);
			visibility = 'visible';
		}
	}
}

function popOut(menuNum, itemNum) {
	if ((menuNum == 0) && !menu[menuNum][itemNum].target)
		hideAllBut(0)
	else
		popTimer = setTimeout('hideAllBut(0)', 500);
}

function getTree(menuNum, itemNum) {

	// Array index is the menu number. The contents are null (if that menu is not a parent)
	// or the item number in that menu that is an ancestor (to light it up).
	itemArray = new Array(menu.length);

	while (1) {
		itemArray[menuNum] = itemNum;
		// If we've reached the top of the hierarchy, return.
		if (menuNum == 0) return itemArray;
		itemNum = menu[menuNum][0].parentItem;
		menuNum = menu[menuNum][0].parentMenu;
	}
}

// Pass an array and a boolean to specify colour change, true = over colour.
function changeCol(changeArray, isOver) {
	for (menuCount = 0; menuCount < changeArray.length; menuCount++) {
		if (changeArray[menuCount]) {
			// Change the colours of the div/layer background.
			newCol = isOver ? menu[menuCount][0].overCol : menu[menuCount][0].backCol;
			with (menu[menuCount][changeArray[menuCount]].ref) {
				if (isNS4)
					bgColor = newCol;
				else
					backgroundColor = newCol;
			}
			// Change the colours of the link text.
			var txt = getRef('menu' + menuCount + 'item' + changeArray[menuCount]);
			while (txt != null && txt.nodeName != 'TD') txt = txt.firstChild;
			if (txt.firstChild == null)
				txt = txt.nextSibling.firstChild;
			else
				txt = txt.firstChild;
			txt.attributes['class'].value = txt.attributes['class'].value.substring(0,3) + (isOver ? 'Over' : 'Text');
			// Change color of indicator
			var arrow = txt.parentNode.nextSibling;
			if (arrow != null) {
				arrow = arrow.firstChild;
				arrow.src = (isOver ? 'http://www.stylusstudio.com/images/white.gif' : 'http://www.stylusstudio.com/images/black.gif');
			}
		}
	}
}

function hideAllBut(menuNum) {
	var keepMenus = getTree(menuNum, 1);
	for (count = 0; count < menu.length; count++)
		if (!keepMenus[count])
	menu[count][0].ref.visibility = 'hidden';
	changeCol(litNow, false);
}

// *** MENU CONSTRUCTION FUNCTIONS ***

function Menu(isVert, x, y, width) {
	// True or false - a vertical menu?
	this.isVert      = isVert;
	// Position and size settings.
	this.x           = x;
	this.y           = y;
	this.width       = width;
	// Colours of menu and items.
	this.overCol     = (isVert ? '#336699' : '#EBEDF0');
	this.backCol     = (isVert ? '#EBEDF0' : '#336699');
	// The stylesheet class used for item borders and the text within items.
	this.textClass   = (isVert ? 'popText' : 'barText');
	// Parent menu and item numbers, indexed later.
	this.parentMenu  = null;
	this.parentItem  = null;
	// Reference to the object's style properties (set later).
	this.ref         = null;
}

function Item(text, href, frame, height, submenu) {
	this.text    = text;
	this.href    = href;
	this.frame   = (frame == undefined ? null : frame);
	this.height  = height;
	this.target  = submenu;
	// Reference to the object's style properties (set later).
	this.ref     = null;
}

function writeMenus() {
	if (!isDOM && !isIE4 && !isNS4) return;

	var subwidth = 190; // submenu width
	var barweight = 4; // the larger the number, the more evenly-spaced the menu bar items will be

	var ta = getRef("menuLinks");
	ta.attributes["class"].value = "menuHide";
	var tb = ta.firstChild;
	while (tb.nodeName != 'TBODY') tb = tb.nextSibling;
	var tr = tb.firstChild;
	var me = 0;
	var mbc = 0; // menu-bar characters, used for relative spacing
	while (tr != null) {
		if (tr.nodeName == 'TR') {
			var td = tr.firstChild;
			var mi;
			menu[me] = new Array();
			var xofs = (me > 0 && tr.align == 'right' ? subwidth + 1 : 0);
			var yofs = (me == 0 || tr.align == 'right' ? 0 : 23);
			var mwid = subwidth;
			if (tr.attributes != null)
				for (mi=0; mi<tr.attributes.length; mi++)
					if (tr.attributes[mi].name == 'width') mwid = tr.attributes[mi].value;
			menu[me][0] = new Menu(me > 0, xofs, yofs, mwid);
			mi = 0;
			while (td != null) {
				if (td.nodeName == 'TD') {
					lk = td.firstChild;
					while (lk.nodeName != 'A') lk = lk.nextSibling;
					var ix = lk.id == null ? -1 : lk.id.indexOf('menu');
					menu[me][++mi] = new Item(lk.firstChild.nodeValue, lk.href, lk.target, 19, (ix == -1) ? 0 : lk.id.substring(ix + 4) );
					if (me == 0) mbc += lk.firstChild.nodeValue.length + barweight;
				}
				td = td.nextSibling;
			}
			me++;
		}
		tr = tr.nextSibling;
	}

	var mblast = menu[0][0].width - menu[0].length + 2;
	var mbthis;
	var mbloop;
	for (mbloop = 1; mbloop < menu[0].length; mbloop++) {
		mbthis = Math.floor((menu[0][mbloop].text.length + barweight) * menu[0][0].width / mbc);
		if (mbloop == menu[0].length - 1)
			menu[0][mbloop].height = mblast;
		else
			menu[0][mbloop].height = mbthis;
		mblast -= mbthis;
	}

	for (currMenu = 0; currMenu < menu.length; currMenu++) with (menu[currMenu][0]) {
		// Variable for holding HTML for items and positions of next item.
		var str = '', itemX = 0, itemY = 0;

		// Remember, items start from 1 in the array (0 is menu object itself, above).
		// Also use properties of each item nested in the other with() for construction.
		for (currItem = 1; currItem < menu[currMenu].length; currItem++) with (menu[currMenu][currItem]) {
			var itemID = 'menu' + currMenu + 'item' + currItem;

			// The width and height of the menu item - dependent on orientation!
			var w = (isVert ? width : height);
			var h = (isVert ? height : width);

			// Create a div or layer text string with appropriate styles/properties.
			// Thanks to Paul Maden (www.paulmaden.com) for helping debug this in IE4, apparently
			// the width must be a miniumum of 3 for it to work in that browser.

			if (isDOM || isIE4) {
				str += '<div id="' + itemID + '"'
					+  ' style="position: absolute;'
					+  ' left: ' + itemX + ';'
					+  ' top: ' + itemY + ';'
					+  ' width: ' + w + ';'
					+  ' border-top: 0;'
					+  ' border-left: 0;'
					+  ' border-right: solid 1px white;'
					+  ' border-bottom: solid 1px white;'
					+  ' visibility: inherit; ';
				if (backCol) str += 'background: ' + backCol + '; ';
				str += '" ';
			}
			else
			if (isNS4) {
				str += '<layer id="' + itemID + '"'
					+  ' left="' + itemX + '"'
					+  ' top="' + itemY + '"'
					+  ' width="' + w + '"'
					+  ' border="0"'
					+  ' visibility="inherit" ';
				if (backCol) str += 'bgcolor="' + backCol + '" ';
			}

			// Add mouseover handlers and finish div/layer.
			str += 'onMouseOver="popOver(' + currMenu + ',' + currItem + ')"'
				+ ' onMouseOut="popOut(' + currMenu + ',' + currItem + ')">';

			// Add contents of item (default: table with link inside).
			// In IE/NS6+, add padding if there's a border to emulate NS4's layer padding.
			// If a target frame is specified, also add that to the <a> tag.

			str += ''
				+ '<table'
				+ ' width="' + (isVert ? '100%' : w) + '"'
				+ ' border="0"'
				+ ' cellspacing="1"'
				+ ' cellpadding="0"'
				+ ' onMouseOver="window.status=\'' + href + '\'";'
				+ (frame
				  ? ' onClick="window.open(\'' + href + '\',\'' + frame + '\')";'
				  : ' onClick="window.open(\'' + href + '\',\'_self\')";'
				  ) + '>'
				+ '<tr>'
				+ (isVert ? '<td width="5" class="subMenu"></td>' : '')
				+ '<td class="' + (isVert ? 'pop' : 'bar') + 'Menu" '
				+ 'align="' + (isVert ? 'left' : 'center') + '">'
				+ '<a class="' + textClass + '" href="' + href + '"' + (frame ? ' target="' + frame + '"' : '') + '>'
				+ text
				+ '</a>'
				+ '</td>'
				+ '';
			if (target > 0) {
				// Set target's parents to this menu item.
				menu[target][0].parentMenu = currMenu;
				menu[target][0].parentItem = currItem;

				// Add a popout indicator.
				if (isVert) str += '<td align="right" class="subMenu"><img src="http://www.stylusstudio.com/images/black.gif"></td>';
			}
			str += '</tr></table>'
				+ (isNS4 ? '</layer>' : '</div>');
			if (isVert)
				itemY += height + 4;
			else
				itemX += height + 1;
		}
		if (isDOM) {
			var obdy = document.getElementsByTagName('body').item(0);
			var newDiv = document.createElement('div');
			obdy.appendChild(newDiv);
			newDiv.innerHTML = str;
			ref = newDiv.style;
			ref.position = 'absolute';
			ref.visibility = 'hidden';
		}

		// Insert a div tag to the end of the BODY with menu HTML in place for IE4.
		if (isIE4) {
			document.body.insertAdjacentHTML('beforeEnd',
				'<div id="menu' + currMenu + 'div" '
				+ 'style="position: absolute; visibility: hidden">'
				+ str + '</div>');
			ref = getStyle('menu' + currMenu + 'div');
		}

		// In NS4, create a reference to a new layer and write the items to it.
		if (isNS4) {
			ref = new Layer(0);
			ref.document.write(str);
			ref.document.close();
		}

		for (currItem = 1; currItem < menu[currMenu].length; currItem++) {
			itemName = 'menu' + currMenu + 'item' + currItem;
			if (isDOM || isIE4) menu[currMenu][currItem].ref = getStyle(itemName);
			if (isNS4) menu[currMenu][currItem].ref = ref.document[itemName];
		}
	}
	with(menu[0][0]) {
		ref.left = x;
		ref.top  = y;
		ref.visibility = 'visible';
	}
	resizeHandler();
}


// *** OPTIONAL CODE FROM HERE DOWN ***

// These two lines handle the window resize bug in NS4. See <body onResize="...">.
// I recommend you leave this here as otherwise when you resize NS4's width menus are hidden.

var popOldWidth = 0

function getWindowWidth()
{
	if (window.innerWidth) return window.innerWidth;
	return document.body.offsetWidth;
}

function resizeHandler()
{
	var popNewWidth = getWindowWidth();
	if (popOldWidth == popNewWidth) return;
	if (isNS4) {
		location.reload();
	} else {
		var root = menu[0][0];
		var tp = topEdge; // this is how far the menu bar should be from the top of the page
		//var lf = Math.floor(Math.max(0,popNewWidth / 2 - root.width / 2));
		var lf = document.images[0].offsetLeft;
		root.ref.top  = tp + "px";
		root.ref.left = lf + "px";
	}
	popOldWidth = popNewWidth;
}


// This is a quick snippet that captures all clicks on the document and hides the menus
// every time you click. Use if you want.

if (isNS4) document.captureEvents(Event.CLICK);
document.onclick = clickHandle;

function clickHandle(evt)
{
	if (isNS4) document.routeEvent(evt);
	hideAllBut(0);
}

