/* Client-side Javascript for sidebar */
/* Copyright 2009,2010 Disk Depot */
/*
 * New version alters behaviour so that you have to click on titles to expand (rather than just hover);
 * the old version is in sidebar-client-ORIGINAL.js and as of 1 March 2010 can be drop-in-replaced/restored by changing
 * the filename to sidebar-client.js */

var		BASE_ID = 'pmn',
		SELECTED_BG = '#dddddd',
		UNSELECTED_BG = 'white',
		INCLUDE_ANCESTOR_SIBLINGS = true,
		HELP_POPUP_HTML = "<div style='width:100px; background-color:#ffffdd; border:solid 1px black; padding:4px; font-size:75%;' id='sidebarHelp'>Click title to see subsections, or click arrow to visit section itself.</div>";
var		sbSelectedElm = null,
		sbUnfoldedElm = null,
		helpPopupCount = 0;

	function elmBg(elm, selected)
	{
		if (elm !== null) {
			/* elm.style.backgroundColor = selected ? SELECTED_BG : UNSELECTED_BG; */
			elm.className = selected ? "sbMenuItemHl" : "sbMenuItemUl";
		}
	}

	function displayHelpPopup(id, x, y) {
		//alert(id + "/" + x + "/" + y);
		var	invokingElm = document.getElementById(id);

		if (invokingElm != sbSelectedElm)	/* Things have changed since we requested this popup? Ignore. */
			return;

		var	helpDiv = document.getElementById('help_' + id);

		if (helpPopupCount++ < 2) {
			helpDiv.style.top = y;
			helpDiv.style.left = x;
			helpDiv.style.zIndex = 100;

			helpDiv.style.display = "block";
		}
	}

	function sidebarMouseOver(e, elmId)
	{
		var	elm = document.getElementById(elmId),
			arrowImg = document.getElementById('arrow_' + elmId);
		
		/* IE / FF use bubbling by default, so stop at lowest level (as desired) */
		e.cancelBubble = true;
		if (e.stopPropagation) {
			e.stopPropagation();
		}

		if (arrowImg) {
			arrowImg.src = '/sidebarjs/arrowanim.gif'; 
			//alert(arrowImg.x);

			var	xCoord = arrowImg.x,
				yCoord = arrowImg.y;

			if (typeof(xCoord) == 'undefined') {
				xCoord = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft + 50;
				yCoord = e.clientY + document.body.scrollTop + document.documentElement.scrollTop + 0;
			} 

			setTimeout("displayHelpPopup('" + elmId + "', " + (xCoord + 25) + ", " + (yCoord - 30) + ")", 2000);
		}

		elmBg(sbSelectedElm, false);
		elmBg(sbSelectedElm = elm, true);
	}

	function sidebarMouseOut(e, elmId)
	{
		var	elm = document.getElementById(elmId),
			arrowImg = document.getElementById('arrow_' + elmId),
			helpDiv = document.getElementById('help_' + elmId);

		e.cancelBubble = true;
		if (e.stopPropagation) {
			e.stopPropagation();
		}

		if (sbSelectedElm == elm) {
			sbSelectedElm = null;
		}

		if (arrowImg) {
			arrowImg.src = '/sidebarjs/arrow.gif'; 

			helpDiv.style.display = "none";
		}

		elm.className='sbMenuItemUl';
	}

	/**
	  * baseId: BASE_ID
	  * level: Always 0 for users calling this
	  * reatainBranchId: ID of an element, all of whose parent nodes will also stay displayed
	  *			if this value isn't set to null
	  *	hideOnlyBelow: If true, only entries below retainBranchId are hidden; required if current elm to remain in same position under pointer */
	function hideAllElms(baseId, level, retainBranchId, hideOnlyBelow)
	{
		level += 1;
	
		var	i = 1, elm;
		do {
			var	childId = baseId + "_" + i;
			if (elm = document.getElementById(childId)) {	/* Assign & check */
				/* if (retainBranchId !== null) {
					isAncestorOf(retainBranchId, childId, INCLUDE_ANCESTOR_SIBLINGS);
				} */
				
				/* if ((level > 1) &&((retainBranchId == null) || (!isAncestorOf(retainBranchId, childId, INCLUDE_ANCESTOR_SIBLINGS, true)))) {
					elm.style.display = 'none';
				} */
				
				if (level > 1) {						/* TODO: Merge conditions? */
					if (retainBranchId == null) {
							elm.style.display = 'none';
					} else if (!isAncestorOf(retainBranchId, childId, INCLUDE_ANCESTOR_SIBLINGS, true)) {
						if (!hideOnlyBelow  || !isAbove(retainBranchId, childId)) {
							elm.style.display = 'none';
						}
					}
				}

				hideAllElms(childId, level, retainBranchId, hideOnlyBelow);
			}
			
			++i;
		} while (elm);
	}

	/* Determine if elm "thisId" appears above "otherId" on the list via ID */
	function isAbove(thisId, otherId)
	{
		var	thisAr = thisId.split("_"),
			otherAr = otherId.split("_");

		for (var i = 1; (i < thisAr.length) && (i < otherAr.length); ++i) {
			if (parseInt(otherAr[i]) != parseInt(thisAr[i])) {
				return parseInt(otherAr[i]) < parseInt(thisAr[i]);
			}
		}
			
		return otherAr.length < thisAr.length;
	}

	/* Determine if element parentId is an ancestor of element myId */
	function isAncestorOf(myId, parentId, includeSiblingsOfAncestors, includeSelf)
	{
		if (myId == parentId)
			return includeSelf;
		if (myId.match(parentId + "_"))
			return true;
			
		/* If counting siblings of "true" ancestors" as ancestors, determine if parent is ancestor */
		if (includeSiblingsOfAncestors) {
			var	parentParentId = getParentId(parentId);
			return isAncestorOf(myId, parentParentId, false, false);
		}
				
		return false;
	}

	function getParentId(elmId)
	{
		var	matchPat = /_[0-9]*$/g;
		
		parentId = elmId.replace(matchPat, "");
		
		return (parentId == BASE_ID) ? null : parentId;
	}

	function showSubtree(e, id)
	{
		var	elm = document.getElementById(id);

		hideAllElms(BASE_ID, 0, id, true);
		
		if (sbUnfoldedElm != elm) {
			childNodesDisp(elm, true);
			sbUnfoldedElm = elm;
		} else {
			sbUnfoldedElm = null;
		}
	}

	function sidebarHtmlRoot(root, level, myId)
	{
		var	result = "";		
		var	style = "";
		var	onMouseOver = "onmouseover='sidebarMouseOver(event, \"" + myId + "\")'";
		var	onClick = "onclick='showSubtree(event, \"" + myId + "\")'";
		var	onMouseOut = "onmouseout='sidebarMouseOut(event, \"" + myId + "\");' ";
		var	bright = 16 - 2 * level;
		var	brightAll = (bright * 256) + (bright * 16) + bright;
		var	brightHex = brightAll.toString(16);
		var	hasChildren = (root.c  &&  root.c["1"]);
		
		style += (level > 1) ?
				"margin-left:10px;" :
				"margin-left:10px; margin-right:10px;";
		style += (level > 1) ? "font-size:90%;" : "";
		style += (level > 1) ? "font-weight:normal;" : "font-weight:bold;";
		/* style += "background-color:#" + brightHex + ";"; */
		style += "class:sbMenuItemUl;";
		style += (level == 1) ? "width:125px;" : "";
		style += (level > 1) ? "display:none" : "";

		result += "<div class='sbMenuItemUl' style='" + style + "' id='" + myId + "' >";
		
		//for (var i = 0; i < (level - 1) * 5; ++i) {	result += "&nbsp;"; }
		var	nSplit = root.n.split(" "),
			nFinal = nSplit[nSplit.length -1];
		nSplit.length -= 1;

		var	aClass = (level == 1  ||  hasChildren) ? "sbnonleaf" : "sbleaf";

		/* var	escUrl = urlEscapeForPerlRedirects("http://www.diskdepot.co.uk/acatalog/" + root.u); */
		var	escUrl = urlEscapeForPerlRedirects(root.u);

		/* document.write(escUrl + "/"); */

		var	dynamicUrl = "http://www.diskdepot.co.uk/cgi-bin/ss000001.pl?SECTIONID=" + escUrl + "&NOLOGIN=1";
		var	wantedUrl;

		if (wantRedirectedTreeLinks) {							/* Used for two-level redirects when linking from blog */
			wantedUrl = "http://www.diskdepot.co.uk/acatalog/redirect.asp?redirectsiteurl=" + escape(dynamicUrl);
		} else if (wantStaticTreeLinks) {						/* Static link direct to page */
			wantedUrl = "http://www.diskdepot.co.uk/acatalog/" + root.u;
		} else {									/* Default is single-level ss000001.pl redirected link */
			wantedUrl = dynamicUrl;
		}

		if (hasChildren) {
			result += ("<span class='" + aClass + "' " + onMouseOver + " " + onClick + " " + onMouseOut + ">" + nSplit.join(" ") + " <span style='white-space:nowrap;'>" + nFinal);
			result += "&nbsp;&nbsp;<a href='" + wantedUrl + "'><img border='none' src='http://www.diskdepot.co.uk/sidebarjs/arrow.gif' width='6' height='9' style='vertical-align:bottom;' id='arrow_" + myId + "' /></a></span><div id='help_" + myId + "' style='display:none; position:absolute; left:20px;top:-20px;'>" + HELP_POPUP_HTML + "</div></span>";
			result += "" + sidebarHtmlChild(root.c, level, myId) + "";
		} else {
			result += ("<a href='" + wantedUrl + "' class='" + aClass + "' " + onMouseOver + " " + onMouseOut + ">" + nSplit.join(" ") + " <span style='white-space:nowrap;'>" + nFinal);
			result += "</span></a>";
		}

		result += "</div>";

		return result;
	}
	
	function sidebarHtmlChild(pChild, level, parentId)
	{
		var	result = "";
	
		for (var i in pChild) {
			result += sidebarHtmlRoot(pChild[i], level + 1, parentId + "_" + i);
		}
		
		return result;
	}

	function fetchChildren(nodeElm)
	{
		var	i,
			id = nodeElm.id,
			result = new Array(),
			temp;

		i = 1;
		while (temp = document.getElementById(id + "_" + i)) { /* Assigned value null? */
			result.push(temp);
			++i;
		}
		
		return result;
	}
	
	function elmDisplay(elm, show)
	{
		elm.style.display = show ? "block" : "none";
	}
	
	function elmsDisplay(elms, show)
	{
		for (var x in elms) {
			elmDisplay(elms[x], show);
		}
	}

	function childNodesDisp(elm, show)
	{
		var	children = fetchChildren(elm);
		elmsDisplay(children, show);	
	}

	/* Escape urls that are accessed via a perl redirect page */
	function urlEscapeForPerlRedirects(url)
	{
		var	result = encodeURIComponent(url);

		result = result.replace(/\./g, "%2e");	

		return result;
	}
