/********************************************************************
 * Filename: submenuExpander.js                                     *
 * Language: JavaScript DOM (Document Object Model)                 *
 *                                                                  *
 * Author: Jason Liu                                                *
 *                                                                  *
 * Copyright (c) 2005-2006 Jason Liu. All rights reserved.          *
 * Copyright (c) 2005-2006 The University of Minnesota Department   *
 *                         of Electrical and Computer Engineering.  *
 * Copyright (c) 2005-2006 The University of Minnesota Institute of *
 *                         Technology.                              *
 * Copyright (c) 2005-2006 The Regents of the University of         *
 *                         Minnesota.                               *
 *                                                                  *
 * Legal Disclaimer:                                                *
 *                                                                  *
 *     [Originally taken from                                       *
 *         http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q3.5.html]  *
 *                                                                  *
 *     [In the following, "licensee" refers to the University of    *
 *      Minnesota Electrical and Computer Engineering Department,   *
 *      the University of Minnesota Institute of Technology, and    *
 *      the Regents of the University of Minnesota.]                *
 *                                                                  *
 *     This is UNPUBLISHED PROPRIETARY SOURCE CODE of Jason Liu;    *
 *     the contents of this file may not be disclosed to third      *
 *     parties, copied or duplicated in any form, in whole or in    *
 *     part, without the prior written permission of Jason Liu.     *
 *                                                                  *
 *     Permission is hereby granted solely to the licensee for use  *
 *     of this source code in its unaltered state. This source code *
 *     may not be modified by licensee except under direction of    *
 *     Jason Liu. Neither may this source code be given under any   *
 *     circumstances to non-licensees in any form, including source *
 *     or binary. Modification of this source constitutes breach of *
 *     contract, which voids any potential pending support          *
 *     responsibilities by Jason Liu. Divulging the exact or        *
 *     paraphrased contents of this source code to unlicensed       *
 *     parties either directly or indirectly constitutes violation  *
 *     of federal and international copyright and trade secret      *
 *     laws, and will be duly prosecuted to the fullest extent      *
 *     permitted under law.                                         *
 *                                                                  *
 *     This software is provided by Jason Liu "as is" and any       *
 *     express or implied warranties, including, but not limited    *
 *     to, the implied warranties of merchantability and fitness    *
 *     for a particular purpose are disclaimed. In no event shall   *
 *     the regents or contributors be liable for any direct,        *
 *     indirect, incidental, special, exemplary, or consequential   *
 *     damages (including, but not limited to, procurement of       *
 *     substitute goods or services; loss of use, data, or profits; *
 *     or business interruption) however caused and on any theory   *
 *     of liability, whether in contract, strict liability, or tort *
 *     (including negligence or otherwise) arising in any way out   *
 *     of the use of this software, even if advised of the          *
 *     possibility of such damage.                                  *
 *                                                                  *
 * Description:                                                     *
 *                                                                  *
 ********************************************************************/

/********************************************************************
 * While I would love to take credit for inventing the getCookie()  *
 * and setCookie() functions, the original copyright actually       *
 * belongs to Mark Wilton-Jones. Please see                         *
 * http://www.HowToCreate.co.uk/jslibs/htmlhigh/cookie.html for     *
 * information. I have renamed some of the variable names, however, *
 * to ones which I think are more descriptive.                      *
 ********************************************************************/
function getCookie(cookieName) {
	/* Retrieved in the format
	   "cookieName4=value; cookieName3=value; cookieName2=value;
	   cookieName1=value".
	   Only cookies for this domain and path will be retrieved. */
	var cookieJar = document.cookie.split("; ");
	for (var i = 0; i < cookieJar.length; i++) {
		var oneCookie = cookieJar[i].split("=");
		if (oneCookie[0] == escape(cookieName))
			return unescape(oneCookie[1]);
	}
	return null;
} // End of getCookie() function

function setCookie(cookieName, cookieValue, cookieExpires, cookiePath,
                   cookieDomain, isSecure)
{
	if (!cookieName) return false;
	if (cookieExpires == "delete") cookieExpires = -1;

	// Set the cookie as specified by the input parameters.
	document.cookie = escape(cookieName) + "=" + escape(cookieValue)
	                + (cookieExpires ?
	                   ";expires=" + (new Date((new Date()).getTime()
	                               + (1000 * cookieExpires))).toGMTString() :
	                   "")
	                + (cookiePath ? ";path=" + cookiePath : "")
	                + (cookieDomain ? ";domain=" + cookieDomain : "")
	                + (isSecure ? ";secure" : "");

	// Check to see if the cookie has been set or deleted as requested.
	if (cookieExpires < 0) {
		if (typeof(getCookie(cookieName)) == "string")
			return false;
		return true;
	}
	if (typeof(getCookie(cookieName)) == "string")
		return true;
	return false;
} // End of setCookie() function

function submenuExpander() {
	var submenuExpanderCookieValue = getCookie("navigation_submenus");
	var cookieValueAfterClick = "collapse";
	if (submenuExpanderCookieValue == "collapse")
		cookieValueAfterClick = "expand";

	this.anchor = document.createElement("a");
	this.anchor.style.verticalAlign = "middle";
	this.anchorTitleString = cookieValueAfterClick
	                       + " navigation submenus";
	this.anchorTitleString = this.anchorTitleString.substr(0,1).toUpperCase()
	                       + this.anchorTitleString.substr(1);
	this.anchor.setAttribute("title", this.anchorTitleString);
	this.anchor.setAttribute("href", "javascript:void(0)");
	this.anchor.setAttribute("id",   "submenuExpander");
	var eventType = "click";
	var eventAction = changeCookieValue;
	var useCapture = false;
	if (this.anchor.addEventListener) {
		this.anchor.addEventListener(eventType, eventAction,
		                             useCapture);
	} else if (this.anchor.attachEvent) {
		this.anchor.attachEvent("on" + eventType,
		                        eventAction);
	}
	with (this.anchor.style) {
		display = "block";
		marginBottom = "0.75em";
		fontSize = "smaller";
		verticalAlign = "middle";
	}

	this.anchorImgSrc = "collapsible_minus_icon.png";
	if (cookieValueAfterClick == "expand")
		this.anchorImgSrc = "expandable_plus_icon.png";

	this.anchorImg = document.createElement("img");
	this.anchorImg.setAttribute("alt", "");
	this.anchorImg.setAttribute("id",  "submenuExpanderImg");
	this.anchorImg.setAttribute("src",
	                            unescape("/media/images/" +
	                            this.anchorImgSrc));
	with (this.anchorImg.style) {
		width = "0.75em";
		height = "0.75em";
		verticalAlign = "middle";
	}
	this.anchor.appendChild(this.anchorImg);

	this.anchorText = document.createTextNode(" ");
	this.anchor.appendChild(this.anchorText);

	this.anchorSpan = document.createElement("span");
	this.anchorSpan.setAttribute("id", "submenuExpanderSpan");
	this.anchorSpan.style.verticalAlign = "middle";
	this.anchorSpanText = "Hide Submenus";
	if (cookieValueAfterClick == "expand")
		this.anchorSpanText = "Show Submenus";
	this.anchorSpanTextNode
	    = document.createTextNode(this.anchorSpanText);
	this.anchorSpan.appendChild(this.anchorSpanTextNode);
	this.anchor.appendChild(this.anchorSpan);
	var navRoot = document.getElementById("navigation");
	for (var i = 0; i < navRoot.childNodes.length; i++)
		if (navRoot.childNodes[i].nodeName == "UL" &&
		    navRoot.childNodes[i].className == "navmenu") {
			doSubmenuExpansionOrCollapse(submenuExpanderCookieValue,
			                             navRoot.childNodes[i]);
			break;
		}

	return this.anchor;
} // End of submenuExpander() function

function changeCookieValue() {
	if (getCookie("navigation_submenus") == "collapse") {
		var action = "expand";
		setCookie('navigation_submenus', action, '', '/');
	} else if (getCookie("navigation_submenus") == "expand") {
		var action = "collapse";
		setCookie('navigation_submenus', action, '', '/');
	}
	window.location.reload(false);
	return;
} // End of changeCookieValue() function

function doSubmenuExpansionOrCollapse(expandOrCollapse, currentNode) {
	// Terminal case
	if (currentNode.nodeName == "UL" &&
	    currentNode.className != "navmenu")
	{
		if (expandOrCollapse == "expand")
			currentNode.style.display = "block";
		return;
	}
	// Recursive case
	for (var i = 0; i < currentNode.childNodes.length; i++)
		doSubmenuExpansionOrCollapse(expandOrCollapse,
		                             currentNode.childNodes[i]);
	return;
} // End of doSubmenuExpansionOrCollapse() function

// This is the function that should be called by event handlers.
function createSubmenuExpander() {
	// First, check to see if the cookie already exists.
	var cookieAccepted = getCookie("navigation_submenus");
	if (!cookieAccepted)
		// The cookie doesn't exist, so try to set a cookie with
		// a default value.
		cookieAccepted = setCookie('navigation_submenus',
		                           'collapse', '',
		                           '/');
	if (cookieAccepted && document.getElementById) {
		var navRoot = document.getElementById("navigation");
		for (var i = 0; i < navRoot.childNodes.length; i++) {
			var node = navRoot.childNodes[i];
			if (node.nodeName == "UL") {
				var newNode = submenuExpander();
				navRoot.insertBefore(newNode, node);
				break;
			}
		}
		return true;
	}
	return false;
} // End of createSubmenuExpander() function

if (window.addEventListener) {
	window.addEventListener("load", createSubmenuExpander, false);
} else if (window.attachEvent) {
	window.attachEvent("onload", createSubmenuExpander);
}
