/*  menu.js  -  Implements cascading menu functionality.
 *  (C) Copyright 2003  Kars Meyboom <kars@kde.nl>
 *
 *  LICENSE:
 * 
 *  This code is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 * 
 *  This code is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 * 
 *  DESCRIPTION:
 * 
 *  This file contains several functions that together form a bar
 *  with buttons, which open cascading menus.
 * 
 *  The menu content should be specified in the global ``menu''
 *  variable.
 * 
 *  NOTES:
 * 
 *  Works only in Internet Explorer 5.x and up,
 *  or Mozilla 1.0 and up.
 */

// --
// -- Globals
// --

var hlColor = '#80c0f0';  // Highlight color for the menu items
var bgColor = '#50a0e0';  // Background color

var zIndex = 1;	// incremental z-index for cascades

// This stack contains all the layers in the current cascade.
var stack = new Array();

// --
// -- Menu Search Code
// --

// Searches the menu for the entry with the given URL.
// Returns the entry's index, or -1 if not found.
function findMenuEntry (url) {
	for (var i = 0; i < menu.length; i++) {
		if (menu[i].url == url) {
			return i;
		}
	}

	return -1;
}

// Searches back through the menu for the given menu entry's
// parent, or -1 if not found or index out of bounds.
function findParent (i) {
	if (i <= 0 || i >= menu.length) {
		return -1;
	}

	var level = menu[i].level;
	while (menu[i].level >= level) {
		i--;
	}

	return i;
}

// Generates a list of all the menu entry's ancestors.
function findAncestors (i) {
	if (i <= 0 || i >= menu.length) {
		return [];
	}

	var ancestors = [];
	var ancestor;
	while ( (ancestor = findParent(i)) >= 0) {
		push(ancestors, ancestor);
		i = ancestor;
	}

	return ancestors;
}

// --
// -- Layer Handling Code
// --

// Called when the mouse is placed over a menu button. Displays
// the corresponding menu canvas.
function createCascade (event) {
	target = getTarget(event);

	url = target.nextSibling.nextSibling.href;
	layerName = findLayer(url);

	x = imgX(target);
	y = imgY(target);

	//  show_props(target, 'target');
	layer = document.getElementById(layerName);
	if (layer.style.visibility == 'visible'
	&&  layer.style.left == ((x+8)+'px')
	&&  layer.style.top == ((y+8)+'px')) {
		destroyAll();
		return;
	}
	destroyAll();
	target.src = baseUrl+'images/darrow_dn.png';
	layer.style.left = (x)+'px';
	layer.style.top = (y+17)+'px';
	layer.style.visibility = 'visible';
	layer.style.zIndex = zIndex++;

	push(stack, layer);
}

// Called when the mouse is clicked outside a canvas or when
// the mouse is placed over a different menu button (causing another
// menu to be displayed). Hides all defined layers.
function destroyCascade () {
	zIndex = 1;
	while (stack.length > 0) {
		pop(stack).style.visibility = 'hidden';
	}
}

// resets every button image's src attribute to show the
// buttons in an unpressed state.
function resetDArrows () {
	buttons = document.getElementById('topbar').getElementsByTagName('IMG');
	for (i = 0; i < buttons.length; i++) {
		buttons.item(i).src = baseUrl+'images/darrow_up.png';
	}
}

function destroyAll (i) {
	destroyCascade();
	resetDArrows();

	var contextmenu = document.getElementById('contextLayer');
	if (contextmenu) {
		contextmenu.style.visibility = 'hidden';
	}

//  document.getElementById('googleDiv').style.visibility = 'hidden';
//  document.getElementById('rrPersonenDiv').style.visibility = 'hidden';
//  document.getElementById('rrAfdelingenDiv').style.visibility = 'hidden';
}

function extendCascade (event) {
	target = getTarget(event);

	url = (isIE || isBrokenMoz) ? target.href : target.parentNode.href;
	layerName = findLayer(url);

	srcPara = (isIE || isBrokenMoz) ? target.parentNode : target.parentNode.parentNode;
	srcLayer = srcPara.parentNode;

	x = parseInt(srcLayer.style.left) + srcPara.offsetLeft + srcPara.offsetWidth + 2;
	y = parseInt(srcLayer.style.top) + srcPara.offsetTop + srcPara.offsetHeight - 22;

	layer = document.getElementById(layerName);
	layer.style.left = x+'px';
	layer.style.top = y+'px';
	layer.style.visibility = 'visible';
	layer.style.zIndex = zIndex++;

	push(stack, layer);
}

function createLayer (i) {
	var level = menu[i].level;
	var layer = menu[i].layer;
	var topurl = menu[i-1].url;
	var toptitle = menu[i-1].title;
	var url = absUrl.match(/[^#]*/)[0];
	var cssclass;

	var code = '<div id="'+layer+'" '+
		   'name="'+layer+'" '+
		   'class="layer">'+
		   '<p class="menuitembold"><a '+
		   'href="'+topurl+'" '+
		   'onmouseover="highlight(event)" '+
		   'onmouseout="lowlight(event)">'+
		   toptitle+'</a></p>\n';

	while (i < menu.length && menu[i].level >= level) {
		if (menu[i].level > level) {
			i++;
			continue;
		}

		if (menu[i].url == url) {
			cssclass = 'selmenuitem';
		} else {
			cssclass = 'menuitem';
		}

		code += '<p class="'+cssclass+'"><a '+
			'id="item'+i+'" '+
			'href="'+menu[i].url+'" '+
			'onmouseover="highlight(event)" '+
			'onmouseout="lowlight(event)">'+
			menu[i].title+'</a>';

		if (menu[i+1] && menu[i+1].layer) {
			code += ' <img src="'+baseUrl+'images/rarrow.png" />';
		}

		code += '</p>\n';
		i++;
	}

	// Add special links to Home layer
	if (isIntern && layer == 'Layer1') {
	code +=
		// '<hr style="width: 100px" />'+
		'<p class="menuitem" style="border-top: 2px groove '+bgColor+'">'+
		'<a href="'+baseUrl+'leyendak/" '+
		'onmouseover="highlight(event)" '+
		'onmouseout="lowlight(event)">'+
		'Leyendak</a></p>';
	}

	code += '</div>\n';
	document.write(code);
}

function createLayers () {
	for (i = 0; i < menu.length; i++) {
		if (menu[i].layer) {
			createLayer(i);
		}
	}
}

function findLayer (url) {
	for (i = 0; i < menu.length; i++) {
		if (menu[i].url == url) {
			return menu[i+1].layer;
		}
	}
	return '';
}

// --
// -- Misc. Code
// --

function highlight (event) {
	target = getTarget(event);

	srcLayer = (isIE || isBrokenMoz) ? target.parentNode.parentNode : target.parentNode.parentNode.parentNode;
	lastLayer = pop(stack);

	while (stack.length && lastLayer != srcLayer) {
		lastLayer.style.visibility = 'hidden';
	//	alert('Removed '+lastLayer.id);
		lastLayer = pop(stack);
		zIndex--;
	}

	push(stack, lastLayer);

	if (isIE || isBrokenMoz) {
		target.parentNode.style.backgroundColor = hlColor;
		target.style.textDecoration = 'underline';
		target.style.color = 'blue';
		if (target.nextSibling) {
			extendCascade(event);
		}
	} else {
		target.parentNode.parentNode.style.backgroundColor = hlColor;
		target.parentNode.style.textDecoration = 'underline';
		target.parentNode.style.color = 'blue';
		if (target.parentNode.nextSibling) {
			extendCascade(event);
		}
	}
}

function lowlight (event) {
	if (isIE || isBrokenMoz) {
		target = getTarget(event);
		target.parentNode.style.backgroundColor = bgColor;
		target.style.textDecoration = 'none';
		target.style.color = '';
	} else {
		target = getTarget(event);
		target.parentNode.parentNode.style.backgroundColor = bgColor;
		target.parentNode.style.textDecoration = 'none';
		target.parentNode.style.color = '';
	}
}

// --
// -- menu navigation functions
// --

function getNavPages () {
	var url = absUrl.match(/[^#]*/)[0];
	var nav = {
		prevUrl:   '',
		prevTitle: '',
		nextUrl:   '',
		nextTitle: '',
		upUrl:     '',
		upTitle:   ''
	};

	for (var i = 0; i < menu.length; i++) {
		if (menu[i].url == url) {
			break;
		}
	}

	if (i == menu.length) {
		// not found
		return nav;
	}

	var j = i-1;
	while (j >= 0 && menu[j].url.match(/^javascript:/)) {
		j--;
	}

	if (j >= 0) {
		nav.prevUrl = menu[j].url;
		nav.prevTitle = snip(menu[j].title, maxTitleLength);
	}

	j = i-1;
	while (j >= 0 && (menu[j].url.match(/^javascript:/) || menu[j].level >= menu[i].level)) {
		j--;
	}

	if (j >= 0) {
		nav.upUrl = menu[j].url;
		nav.upTitle = snip(menu[j].title, maxTitleLength);
	}

	j = i+1;
	while (j < menu.length && menu[j].url.match(/^javascript:/)) {
		j++;
	}

	if (j < menu.length) {
		nav.nextUrl = menu[j].url;
		nav.nextTitle = snip(menu[j].title, maxTitleLength);
	}

	return nav;
}

// --
// -- menu bar ('topbar') code
// --

function createBar () {
	var out = new Array();
	var i, j;

	var url = absUrl.match(/[^#]*/)[0];
	for (i = 0; i < menu.length; i++) {
		if (menu[i].url == url) {
			break;
		}
	}

	j = 0;
	if (i < menu.length) do {
		var item = '';
		if (menu[i+1] && menu[i+1].layer) {
			item  = '<img src="'+baseUrl+'images/darrow_up.png" ';
			item += 'id="topbarbtn'+j+'" ';
			item += 'onmouseover="createCascade(event)" ';
			item += 'title="Dit is het \''+menu[i].title+'\' menu" ';
			item += 'alt="Dit is het \''+menu[i].title+'\' menu" /> ';
			j++;
		}
		item += '<a href="'+menu[i].url+'">'+snip(menu[i].title, maxTitleLength)+'</a>';
		push(out, item);

		var level = menu[i].level;
		while (i >= 0 && menu[i].level >= level) {
			i--;
		}
	} while (i >= 0) else {
		/* current page not listed in menu structure */
		var item = '';
		item  = '<img\n src="'+baseUrl+'images/darrow_up.png"\n ';
		item += 'id="topbarbtn0"\n onmouseover="createCascade(event)"\n ';
		item += 'alt="Dit is het \''+menu[0].title+'\' menu"\n ';
		item += 'title="Dit is het \''+menu[0].title+'\' menu"\n /> ';
		item += '<a href="'+menu[0].url+'">'+menu[0].title+'</a>';
		push(out, item);
	}  

	var doc = document;
	doc.write('<div id="topbar" name="topbar">');
	while (out.length > 0) {
		doc.write(pop(out));
		if (out.length > 0) {
			doc.write('<span class="sep"> :: </span>');
		}
	}
	doc.write('</div>');
}

// --
// -- navigation bar functions
// --

// write out HTML code for navigation buttons (< ^ >)
function createNavBar () {

	var nav = getNavPages();
	nav.prevTitle = (nav.prevTitle == '') ? '(geen voorgaande pagina)'
					: 'naar voorgaande pagina ('+nav.prevTitle+')';
	nav.nextTitle = (nav.nextTitle == '') ? '(geen volgende pagina)'
					: 'naar volgende pagina ('+nav.nextTitle+')';
	nav.upTitle = (nav.upTitle == '') ? '(geen bovenliggende pagina)'
				    : 'naar bovenliggende pagina ('+nav.upTitle+')';

	document.write('<div id="navbar">'+

		'<a href="'+nav.prevUrl+'"><img src="'+baseUrl+'images/nav_prev.png" '+
		'onmouseover="this.src=\''+baseUrl+'images/nav_prev_a.png\'" '+
		'onmouseout="this.src=\''+baseUrl+'images/nav_prev.png\'" '+
		'alt="'+nav.prevTitle+'" '+
		'title="'+nav.prevTitle+'" /></a>'+

		'<a href="'+nav.upUrl+'"><img src="'+baseUrl+'images/nav_up.png" '+
		'onmouseover="this.src=\''+baseUrl+'images/nav_up_a.png\'" '+
		'onmouseout="this.src=\''+baseUrl+'images/nav_up.png\'" '+
		'alt="'+nav.upTitle+'" '+
		'title="'+nav.upTitle+'" /></a>'+

		'<a href="'+nav.nextUrl+'"><img src="'+baseUrl+'images/nav_next.png" '+
		'onmouseover="this.src=\''+baseUrl+'images/nav_next_a.png\'" '+
		'onmouseout="this.src=\''+baseUrl+'images/nav_next.png\'" '+
		'alt="'+nav.nextTitle+'" '+
		'title="'+nav.nextTitle+'" /></a>'+

		'</div>');
}

function init_navbar () {
	var navbar = document.getElementById('navbar');
	navbar.style.left = '0px';
	navbar.style.top = '4px';
	var padding = (document.body.clientHeight != document.body.scrollHeight) ? 3 : 19;
	navbar.style.left = (document.body.clientWidth - 51 - padding) + 'px';
}

function update_navbar () {
	init_navbar();
}

// --
// -- Navigation Panel
// --

function printEntry (entry, indent, highlight) {
	var d = document;
	var t = entry.title;
	var u = entry.url;

	if (u.match(/^javascript:destroyAll/)) {
		return;
	}
	d.write('<tr><td onmouseover="this.style.backgroundColor=\''+hlColor+'\'"'+
	               ' onmouseout="this.style.backgroundColor=\'\'"');
	if (highlight) {
		d.write(' style="border: 1px dashed #e0f0ff">');
	} else {
		d.write('>');
	}
	d.write('<p style="padding-left: '+indent+'px">');
	d.write('<a onmouseover="this.style.textDecoration = \'underline\'"'+
	          ' onmouseout="this.style.textDecoration = \'\'"'+
		  ' href="'+u+'" '+
		  ' style="padding: 1px;');
	d.write('">'+t+'</a></p></td></tr>');
}

function fillPanelTopLevel () {
	for (var i = 0; i < menu.length; i++) {
		if (menu[i].level != 1) {
			continue;
		}
		var item = menu[i];
		var title = item.title;
		var url = item.url;
		printEntry(menu[i], 0, false);
	}
}

function fillPanelByLevel () {
	var entry = findMenuEntry(absUrl);
	if (entry < 0) {
		fillPanelTopLevel();
		return;
	}
	var ancestors = findAncestors(entry);
	pop(ancestors);
	if (menu.length) {
		pop(ancestors);
	}

	var d = document;

	// print "Home"
	printEntry(menu[0], 0, (entry == 0));

	var delta = 12;
	var indent = delta;
	for (var i = 1; i < menu.length; i++) {
		if (in_list(ancestors, i)) {
			indent += delta;
			printEntry(menu[i], indent, 0);
		} else if (i == entry) {
			if (parseInt(menu[i].level) > 1) {
				indent += delta;
			}
			printEntry(menu[i], indent, 1);
			indent += delta;
			var level = parseInt(menu[i].level);
			j = i+1;
			while (j < menu.length && menu[j].level > level) {
				if (parseInt(menu[j].level) == (level + 1)) {
					printEntry(menu[j], indent, 0);
				}
				j++;
			}
		} else {
			if (menu[i].level == 1) {
				printEntry(menu[i], delta, 0);
			}
		}
	}
}

function createNavPanel () {
	if (isIE) {
		var position = 'absolute';
	} else {
		var position = 'fixed';
	}

	var d = document;
	var google = 'http://www.google.com/search?cof='+escape('AH:center;S:http://www.leyenburg-ziekenhuis.nl;AWFID:f90c4a2fe8ff08ef;')+'&domains=www.leyenburg-ziekenhuis.nl&sitesearch=www.leyenburg-ziekenhuis.nl&q=';
	
	d.write('<div id="navPanel" style="position:'+position+'; display:none; left:0px; top:0px" onclick="destroyAll()">');
	d.write('<table border="0" cellspacing="0" cellpadding="0">'); // width="100%"
	d.write('<tr><td colspan="2" align="right">');
	d.write('<img id="navPanelClose" src="'+baseUrl+'images/close_menu.png" onclick="closeNavPanel()" onmouseover="this.src.match(/_menu[^_]/)?this.src=this.src.replace(/_menu/, \'_menu_a\'):1" onmouseout="this.src.match(/_menu_a/)?this.src=this.src.replace(/_menu_a/, \'_menu\'):1" alt="Menu sluiten" title="Menu sluiten" />');
	d.write('<img src="'+baseUrl+'images/ur-corner.png" /></td></tr>');
	d.write('<tr><td>');
	d.write('<table id="navPanelContent" width="100%" cellspacing="0" cellpadding="4">');
	//fillPanelByContext();
	fillPanelByLevel();
	d.write('<tr><td><input type="text" name="query" value="(zoeken)" size="12" onkeypress="((isIE && event.keyCode == 13) || (!isIE && event.which == 13)) && (window.location = \''+google+'\'+escape(this.value))" onfocus="this.value = \'\'" /></td></tr>');
	d.write('</table>');
	d.write('</td>');
	d.write('<td style="width: 8px; background: url('+baseUrl+'images/np-shadow-r.png); background-position: top right; background-repeat: repeat-y">&nbsp;</td>');
	d.write('</tr>');
	d.write('<tr><td style="background: url('+baseUrl+'images/np-shadow-d.png)" colspan="2" align="right"><img src="'+baseUrl+'images/lr-corner.png" /></td></tr>');
	d.write('</table></div>');
	d.write('<img id="navPanelOpen" src="'+baseUrl+'images/open_menu.png" style="display: none; position: '+position+'; left: 2px;" onclick="openNavPanel()" onmouseover="this.src.match(/_menu[^_]/)?this.src=this.src.replace(/_menu/, \'_menu_a\'):1" onmouseout="this.src.match(/_menu_a/)?this.src=this.src.replace(/_menu_a/, \'_menu\'):1" alt="Menu openen" title="Menu openen" />');
}

function placeNavPanel () {
	// var top = document.getElementById('bodydiv').offsetTop + 20;
	var top = document.getElementById('bodydiv').offsetTop;

	document.getElementById('navPanel').style.top = top+'px';
	document.getElementById('navPanelOpen').style.top = top+'px';

	var showPanel = getCookie('zhl_panel');
	if (showPanel == null) {
		showPanel = 1;
		setCookie('zhl_panel', '1');
	}

	var panel = document.getElementById('navPanel');
	var img = document.getElementById('navPanelOpen');

	if (parseInt(showPanel) > 0) {
		panel.style.display = '';
		img.style.display = 'none';
	} else {
		panel.style.display = 'none';
		img.style.display = '';
	}

	onupdate_handler();

	if (isIE) {
		at_timeout('updateNavPanel()');
	}
}

function updateNavPanel () {
	var panel = document.getElementById('navPanel');
	var bodydiv = document.getElementById('bodydiv');

	if (panel.offsetHeight > document.body.clientHeight) {
		return;
	}

	// var top1 = document.getElementById('bodydiv').offsetTop + 5;
	var top1 = document.getElementById('bodydiv').offsetTop;
	var top2 = document.body.scrollTop + 5;
	var pos = (top1 < top2) ? top2 : top1;

	document.getElementById('navPanel').style.top = pos+'px';
	document.getElementById('navPanelOpen').style.top = pos+'px';
}

function closeNavPanel () {
	//document.getElementById('navPanelContent').style.display = 'none';
	//document.getElementById('navPanel').style.width = '20px';
	document.getElementById('navPanel').style.display = 'none';
	document.getElementById('navPanelOpen').style.display = '';
	setCookie('zhl_panel', '0');

	var img = document.getElementById('navPanelClose');
	if (img.src.match(/_menu_a/)) {
		img.src = img.src.replace(/_menu_a/, '_menu');
	}

	onupdate_handler();
}

function openNavPanel () {
	//document.getElementById('navPanelContent').style.display = '';
	//document.getElementById('navPanel').style.width = '';
	document.getElementById('navPanelOpen').style.display = 'none';
	document.getElementById('navPanel').style.display = '';
	setCookie('zhl_panel', '1');

	var img = document.getElementById('navPanelOpen');
	if (img.src.match(/_menu_a/)) {
		img.src = img.src.replace(/_menu_a/, '_menu');
	}

	onupdate_handler();
}

// --
// -- Preload, init and update handlers
// --

function menu_preload () {
	createBar();
	createLayers();
	createNavBar();
	createNavPanel();
}

function menu_init () {
	init_navbar();
	placeNavPanel();
}

function menu_update () {
	init_navbar();

	var panel = document.getElementById('navPanel');
	var bodydiv = document.getElementById('bodydiv');
	if (panel.offsetHeight > document.body.clientHeight) {
		panel.style.position = 'absolute';
	} else {
		if (!isIE) {
			panel.style.position = 'fixed';
		}
	}
}

// --
// -- Initialisation Code
// --

for (var i = 0; i < menu.length; i++) {
	if (menu[i].url.match(/^javascript:/)) {
		continue;
	}

	menu[i].url = baseUrl + menu[i].url;

	if (menu[i].url.charAt(menu[i].url.length - 1) == '/') {
		menu[i].url += "index.html";
	}
}

at_preload('menu_preload()');
at_init('menu_init()');
at_update('menu_update()');


