// More or less global CHPC cookie suffix.
// To change this to a persistent cookie, add 
// a GMT compatible expiration date.
var cookieSuffix = '; path=/;';

// Cookie string names
var altStyleCookie = 'altStyles';
var docTreeCookie = 'chpcdoctree';


//
//  GENERAL COOKIE CODE, USED BY EVERYTHING
//


// Returns the cookie string that matches cookieName
function getCookieString(cookieName)
{
    var cookieString = new String();
    var cookieStringStart = cookieName.length + 2;
    var cookieSubStrings = unescape(document.cookie).split(';');

    for(cIdx=0; cIdx<cookieSubStrings.length; cIdx++)
    {
        if(cookieSubStrings[cIdx].indexOf(cookieName) >= 0)
        {
            cookieString = cookieSubStrings[cIdx].substring(cookieStringStart,cookieSubStrings[cIdx].length);
            return cookieString;
        }
    }
}


//
// FUNCTIONS FOR THE DOC MENU TREE
//


// Collapse all submenus in the doc menu tree
function collapse()
{
    var images = document.getElementsByTagName('li');
    for(i=0;i<images.length;i++)
    {
        // Run hideShow on each LI with a class name of "dir" or
        // "lastdir". Specify this is a loading stage to avoid dinking
        // with the cookie.
        if((images[i].className == 'dir') || (images[i].className == 'lastdir')) hideShow(images[i],1);
    }
}


// Hide or show a submenu. "cont" is short for "container" and "onload" is
// a flag that is set if this function is run from "windows.onload" (there
// are things we don't want to do in these situations).
function hideShow(cont,onload)
{
    // We've either chosen an LI, or we've chosen something
    // within the LI
    if (cont.nodeName == 'LI') var thisLi = cont;
    else var thisLi = cont.parentNode;

    // INFORMATION:
    //
    // thisLi.childNodes: 0: +/- Branch IMG,  1: Folder IMG, 
	//		2: Anchor, 3: text (dir name), 4: submenu UL

    // Snag the UL within thisLi
    var childUl = thisLi.childNodes[4];

    // Get the "src" attributes containing the branch and folder images
    var branchImg = thisLi.childNodes[0].attributes.getNamedItem("src");
    var folderImg = thisLi.childNodes[1].attributes.getNamedItem("src");

    // Make sure the default display style (block) is set
    if (! childUl.style.display) childUl.style.display = 'block';

    // Switch the display settings
    if (childUl.style.display == 'block') 
    { 
        childUl.style.display = 'none'; 
        if (thisLi.className == 'lastdir') branchImg.nodeValue = '/images/TreeMenu/plusbottom.gif';
        else branchImg.nodeValue = '/images/TreeMenu/plus.gif';
        folderImg.nodeValue = '/images/TreeMenu/folder.gif';

        // Don't do any cookie manipulation if this is being 
        // executed from "windows.onload"
        if (onload != 1)
        {
            removeIdCookie(childUl.id,docTreeCookie);
        }
    }
    else 
    { 
        childUl.style.display = 'block'; 
        if (thisLi.className == 'lastdir') branchImg.nodeValue = '/images/TreeMenu/minusbottom.gif';
        else branchImg.nodeValue = '/images/TreeMenu/minus.gif';
        folderImg.nodeValue = '/images/TreeMenu/folder-expanded.gif';

        setIdCookie(childUl.id,docTreeCookie);
    }
}


// Remove an ID from the cookie 
function removeIdCookie(idName,cookieName)
{
    var ourCleanCookieString = new String();
    var ourCookieString = getCookieString(cookieName);

    // If the cookie exists and it contains something that 
    // looks like our ID...
    if((ourCookieString) && (ourCookieString.indexOf(idName) >= 0))
    {
        ourCookieSubStrings = ourCookieString.split(':');
        for(csIdx=0; csIdx<ourCookieSubStrings.length; csIdx++)
        {
            // If we don't have an exact match, add
            // ourCookieSubStrings[csIdx] to the cookie. (Has to be "!=="
            // or this won't work!)
            if(ourCookieSubStrings[csIdx] !== idName)
            {
                // Only add the substring if the ID exists in our
                // document. This is necessary to handle directory trees
                // that "suddenly" change, leaving orphaned IDs in the
                // cookie.
                if(document.getElementById(ourCookieSubStrings[csIdx]))
                    ourCleanCookieString = ourCleanCookieString + ourCookieSubStrings[csIdx] + ":";
            }
        }
        // When we're through rebuilding the cookie string, lose 
        // the trailing colon
        ourCleanCookieString = ourCleanCookieString.substring(0,ourCleanCookieString.length - 1);
    }
    else 
    {
        ourCleanCookieString = ourCookieString;
    }

    // Write or delete the cookie
    if((ourCleanCookieString) && (ourCleanCookieString.length > 0)) 
        document.cookie = cookieName + "=" + ourCleanCookieString + cookieSuffix;
    else document.cookie = cookieName + "=" + "; expires=Fri, 02-Jan-1970 00:00:00 GMT" + cookieSuffix;
}


// Add an ID to the cookie
function setIdCookie(idName,cookieName)
{
    var ourCookieString = new String();
    ourCookieString = getCookieString(cookieName);

    // Tricky... We need to check for IDs ending in ':'
    // and ';' (not at the same time, of course), so build 
    // two search strings and check for both of them
    var idSearchString1 = idName + ':';
    var idSearchString2 = idName + ';';

    if(ourCookieString != null)
    {
        if((ourCookieString.indexOf(idSearchString1) < 0) || (ourCookieString.indexOf(idSearchString2) < 0))
        {
            if(ourCookieString.length > 0) ourCookieString = ourCookieString + ":" + idName;
            else ourCookieString = idName;
        }
    }
    else ourCookieString = idName; 
    document.cookie = cookieName + "=" + ourCookieString + cookieSuffix;
}



//
// FUNCTIONS FOR DEALING WITH ALTERNATE STYLING
//


// SWAPPING ALTERNATE STYLES
//
//        (Knowledge of CSS and (X)HTML coding is assumed. 
//        If you don't have it, do what you can to get it.)
//
// Style swapping is used primarily to turn content on and off, like
// boxbody content appearing and disappearing when clicking on a +/-
// button or making a column of content disappear. In most cases, swapping
// two styles is sufficient: one style turns the display of the content
// on, the other turns it off. 
//
// We facilitate swapping styles by swapping IDs or classes with other IDs
// or classes of the same name but with "-alt" tacked onto the end. Both
// the "normal" and "alternate" styles need to exist in CSS.
//
// When an alternate style is set, it's saved in a cookie and is applied
// using Javascript every time the page is reloaded. Swapping back to a
// "normal" style removes the alternate style from the cookie. (Important
// note: ALL alternate style suffixes MUST begin with "-alt"!)
// 
// All non-navigation oriented content on the site needs to default to
// being displayed. This will let people access the content of the site
// even if Javascript is disabled. To do this, the "normal" styling MUST
// have a "display: ???;" attribute that is either "block" or "inline."
// Don't leave this out! If you do, you'll never switch the display of the
// element back on after turning it off with an alternate style.
//
//
// Swapping between two styles on one element...
// ---------------------------------------------
//
// The main style swap function - swapStyle(parent) - requires AT LEAST an
// ID (parent) name. If only an ID is given, the style will be swapped for
// the ID. If a class (child) is given in addition to an ID, the class'
// style will be swapped and the ID of its parent container will be left
// alone. You can not pass a class by itself to this function. 
//
// To facilitate this kind of swappage, add an "onclick=" attribute to
// your opening element of the tag containing your swap trigger (word,
// image, header graphic, whatever):
//
//    onclick='javascript:swapStyle("IDName");'
//    onclick='javascript:swapStyle("IDName","ClassName");'
//
// The first swaps a style on the element with an ID of "IDName"; the
// second swaps the style on the element within the "IDName" container
// that is assigned a class name of "ClassName."
//
// 
// Swapping between two styles on multiple ID'd elements...
// --------------------------------------------------------
//
// All this does is run swapStyle() on more than one element using one
// "onclick=" action. It only works with ID'd elements, though. No classes
// allowed. List the IDs in an array and pass the array to
// multiSwapStyle(). 
//
//    onclick="javascript:var idList = new Array ('IDName1','IDName2');
//             multiSwapStyle(idList);"
// 
//
// Swapping between more than two styles on one element...
// -------------------------------------------------------
//
// There will be rare occasions where an ID'd HTML element will have
// multiple alternate styles to choose from. A prime example is the
// "content" portion of the CHPC web site, which can be a narrow column in
// the middle of the web page or a column that stretches all the way to
// the left and/or right edge of the browser window. One "normal" style
// and one "alternate" style can not possibly cover all states.
//
// Also, because you never know which of the styles is currently in use,
// there's no easy way to determine the name of the ID'd element for which
// you're swapping styles. Going from "content" to "content-alt2" would be
// fairly simple, but what happens when you need to swap from
// "content-alt2" to "content-alt3"? 
//
//    onclick='javascript:swapStyleBySuffix("Current_ID","Name","Suffix");'


// Remove an alternate style from the alternate style cookie 
function removeAltStyleCookie(altStyle,cookieName)
{
    //var cookieName = "altStyles";
    var ourCleanCookieString = new String();
    var ourCookieString = getCookieString(cookieName);

    if(ourCookieString.indexOf(altStyle) >= 0)
    {
        ourCookieSubStrings = ourCookieString.split(':');
        for(csIdx=0; csIdx<ourCookieSubStrings.length; csIdx++)
        {
            if(ourCookieSubStrings[csIdx].indexOf(altStyle) < 0)
            {
                ourCleanCookieString = ourCleanCookieString + ourCookieSubStrings[csIdx] + ":";
            }
        }
        // Lose the trailing colon
        ourCleanCookieString = ourCleanCookieString.substring(0,ourCleanCookieString.length - 1);
    }
    else ourCleanCookieString = ourCookieString;

    // Write or delete the cookie
    if(ourCleanCookieString.length > 0) document.cookie = cookieName + "=" + ourCleanCookieString + cookieSuffix;
    else document.cookie = cookieName + "=" + "; expires=Fri, 02-Jan-1970 00:00:00 GMT" + cookieSuffix;
}


// Save the altStyle states in a cookie
function setAltStyleCookie(altStyle,cookieName)
{
    //var cookieName = "altStyles";
    var ourCookieString = new String();
    ourCookieString = getCookieString(cookieName);

    if(ourCookieString != null)
    {
        if(ourCookieString.indexOf(altStyle) < 0)
        {
            if(ourCookieString.length > 0) ourCookieString = ourCookieString + ":" + altStyle;
            else ourCookieString = altStyle;
        }
    }
    else ourCookieString = altStyle; 
    document.cookie = cookieName + "=" + ourCookieString + cookieSuffix;
}


// Swap styles on IDs or classes within IDs and update the requisite
// cookie.. You MUST give a cookie name and parent ID. The child class 
// is optional.
function swapStyle(cookieName,parent,child)
{
    // Build our altStyle string
    var altStyle = parent;
    if(child) altStyle = altStyle + "." + child;
    altStyle += "-alt";
    
    var startNode = document.getElementById(parent);

    if(child && startNode.hasChildNodes())
    {
        for(chIdx=0; chIdx<startNode.childNodes.length; chIdx++)
        {
            if((startNode.childNodes[chIdx].className != null) && 
                ((startNode.childNodes[chIdx].className.indexOf(child)) >= 0))
            {
                if(startNode.childNodes[chIdx].className.indexOf("-alt") >= 0)
                {
                    startNode.childNodes[chIdx].className = child;
                    if(cookieName != "NULL") removeAltStyleCookie(altStyle,cookieName);
                }
                else
                {
                    startNode.childNodes[chIdx].className = child + "-alt";
                    if(cookieName != "NULL")setAltStyleCookie(altStyle,cookieName);
                }
            }
        }
    }
    else
    {
        // Working with IDs is different... If the ID doesn't exist,
        // assume it's already an altStyle.
        if(document.getElementById(parent))
        {
            document.getElementById(parent).id = altStyle;
            if(cookieName != "NULL") setAltStyleCookie(altStyle,cookieName);
        }
        else
        {
            document.getElementById(altStyle).id = parent;
            if(cookieName != "NULL") removeAltStyleCookie(altStyle,cookieName);
        }
    }
}


// Swap styles on a list of IDs. Give the governing cookie's name first.
function multiSwapStyle(cookieName,idList)
{
    for (listIdx = 0; listIdx < idList.length; listIdx++)
    {
        if(cookieName != "NULL") swapStyle(cookieName,idList[listIdx]);
    }
}


// Unfortunately, the W3C doesn't allow us to identify divs using "name="
// attributes. That would make our task much simpler: we could simply name
// a div and read its ID whenever we need to switch the ID to something
// else. Because we can't, multiple (slow) document.getElementById() calls
// must be made - one for each alternate style/ID - and then the
// successful call needs to report the found ID to this function. Sloppy,
// but other than walking an XML tree and guessing how far back to go in
// the document's heirarchy, there's no other way that I know of to do
// this.


// Determination of the current style/ID for a div is performed outside
// this function. All we do here is swap the style and update the
// requisite cookie.
function swapStyleBySuffix(cookieName,currentId,idName,altSuffix)
{
    // Start by remove ALL cookie strings that contain the name 
    // of our element (name your IDs uniquely!).
    removeAltStyleCookie(idName,cookieName);

    // Start with the name as the ID/style
    var newStyle = idName;

    // Grab our element by its name
    //var namedElement = document.getElementsByName(idName)[0];

    // If there's no altSuffix, we're switching back to the "normal"
    // ID/style. If there is an altSuffix, set a new cookie string for it
    if (altSuffix) 
    {
        newStyle = newStyle + altSuffix;
        setAltStyleCookie(newStyle,cookieName);
    }

    // Set the ID/style, whatever it may be
    document.getElementById(currentId).id = newStyle;
}


// An unfortunate bit of custom code... Determine which of the possible
// "content" alternate IDs/styles to choose from when the left and/or
// right columns are clicked away.
//
// Alternates:
// 
//    content: Normal, both left and right columns displayed
//    content-alt1: No left column
//    content-alt2: No right column
//    content-alt3: No left or right column
//
// Possible cases: 
//
// 1) From default state to one column collapsed.
//
//    If the ID is "content" with no suffix, just load the "content-alt1"
//    (no left column) or "content-alt2" (no right column) ID/style.
//
// 2) From one column collapsed to both columns collapsed.
//
//    If the ID is either "content-alt1" or "content-alt2," load the
//    "content-alt3" ID/style.
//
// 3) From both columns collapsed to one column collapsed.
//
//    If the ID is "content-alt3", load the "content-alt1" (no left
//    column) or "content-alt2" (no right column) ID/style.
//
// 4) From one column collapsed to no columns collapsed.
//
//    If the ID is either "content-alt1" or "content-alt2," load the
//    "content" ID/style.
//
// This function must supply to the swapStyleBySuffix() function the
// current style/ID of the content div.
function expandContent(side)
{
	if (document.getElementById("content-alt1"))
	{
		if (side == "left") swapStyleBySuffix(cookieName,"content-alt1","content");
		if (side == "right") swapStyleBySuffix(cookieName,"content-alt1","content","-alt3");
	}
	else if (document.getElementById("content-alt2"))
	{
		if (side == "left") swapStyleBySuffix(cookieName,"content-alt2","content","-alt3");
		if (side == "right") swapStyleBySuffix(cookieName,"content-alt2","content");
	}
	else if (document.getElementById("content-alt3"))
	{
		if (side == "left") swapStyleBySuffix(cookieName,"content-alt3","content","-alt2");
		if (side == "right") swapStyleBySuffix(cookieName,"content-alt3","content","-alt1");
	}
	else       // currentIdName == "content"
	{
		if (side == "left") swapStyleBySuffix(cookieName,"content","content","-alt1");
		if (side == "right")  swapStyleBySuffix(cookieName,"content","content","-alt2");
	}
}


// Stuff to run whenever the page is loaded
startList = function() {

    // LOAD ALTERNATE STYLES, IF ANY

    // var cookieName = "altStyles";
    var ourCookieString = new String();
    var ourCookieString = getCookieString(altStyleCookie);

    if(ourCookieString != null)
    {
        var ourCookieSubStrings = ourCookieString.split(':');

        for(csIdx=0; csIdx<ourCookieSubStrings.length; csIdx++)
        {
            // Find the beginning of the alternate style suffix
            var elementIdEnd = ourCookieSubStrings[csIdx].indexOf("-alt");

            // Snag the alternate style suffix
            var altStyleSuffix = ourCookieSubStrings[csIdx].substr(elementIdEnd);

            // Snag the ID and, if necessary, the class
            var elementIdStrings = ourCookieSubStrings[csIdx].substring(0,elementIdEnd).split('.');

            // If we're not loading a typical alternate style, use
            // swapStyleBySuffix()
            if (altStyleSuffix != "-alt")
            {
                swapStyleBySuffix(altStyleCookie,elementIdStrings[0],elementIdStrings[0],altStyleSuffix);
            }
            else
            {
                // Are we swapping styles on a class or an ID?
                if(elementIdStrings.length > 1) 
                {
                    swapStyle(altStyleCookie,elementIdStrings[0],elementIdStrings[1]);
                }
                else 
                {
                    swapStyle(altStyleCookie,elementIdStrings[0]);
                }
            }
        }
    }

	// DEAL WITH THE DOC MENU TREE

    // Step 1: Collapse everything in the doc menu tree
    collapse();

    // Step 2: Expand branches listed in our cookie
    var ourCookieString = new String();
    ourCookieString = getCookieString(docTreeCookie);

    if((ourCookieString) && (ourCookieString.length > 0))
    {
        var ourCookieSubStrings = ourCookieString.split(':');

        for(csIdx=0; csIdx<ourCookieSubStrings.length; csIdx++)
        {
            // If the ID in the cookie string exists...
            if(document.getElementById(ourCookieSubStrings[csIdx]))
            {
                var ulElement = document.getElementById(ourCookieSubStrings[csIdx]);
                var ulParent = ulElement.parentNode;
                 
                // Get the "src" attribute for our branch and folder images
                var branchImg = ulParent.childNodes[0].attributes.getNamedItem("src");
                var folderImg = ulParent.childNodes[1].attributes.getNamedItem("src");

                ulElement.style.display = 'block'; 
                if (ulParent.className == 'lastdir') branchImg.nodeValue = '/images/TreeMenu/minusbottom.gif';
                else branchImg.nodeValue = '/images/TreeMenu/minus.gif';
                folderImg.nodeValue = '/images/TreeMenu/folder-expanded.gif';
            }
            else
            {
                removeIdCookie(ourCookieSubStrings[csIdx],docTreeCookie);
            }
        }
    }


    // Step 3: Make the doc tree menu visible
    if (document.getElementById("TreeMenu")) document.getElementById("TreeMenu").style.display = "block";


	// With all that done, turn on the display of main_left content. This
	// was turned off in the lc/page_left.inc.php file.
   	//window.alert("Turning on the display of main_left.");
   	//document.getElementById('main_left').style.display = "block";

}

window.onload=startList;
