// A navigation system that creates collapsing menus out of existing lists
// the lists must be of the form,
//	<ul>
//	  <li>
//	    <ul>
//          etc.

// Main function that takes the UL that defines the
// entire menu, and sets the properties for the
// nested UL's within it using the recursive function
// createMenuHelper()

// this can be easily made more generic, but is suited specifically for
// the nav.css style.
//
// on your page, call createMenu(x) where x is the id of the top level UL
// highlightActiveLink(x) where x is the id of the top level UL
// preloadNavImages()


var shouldOpenToActiveLink = true;
var shouldAutoCollapse = true;

function createMenu(menuTopLevelUL) {
    var topUL = document.getElementById(menuTopLevelUL);
    createMenuHelper(topUL);
    if (shouldOpenToActiveLink) {
        openBranchToActiveLink(topUL);
    }
}

// Helper function that actually collapses all of the underlying
// menus. An underlying menu is a <li> that encapsulates a <ul>.
// We first hide/collapse the underlying <ul>, add a span that will
// hold an icon in the <li> tag, and change the onclick property
// of the <a> tag in the <li> tag to do some operation on the menu.
// this is just a depth-first operation, recursing over the entire menu
// structure.

// while we're building the menu from your cookie and checking how many
// pages you have visited, we'll calculate your completion progress

var totalPagesVisited = 0;

function createMenuHelper(thisUL) {
    // do a depth first traveral of the menu, (as defined as a list)
    // iterating over each <li> in the menu and definining the
    // properties for the inner <ul>s
    
    // array of li tags for this UL
    var liTags = thisUL.childNodes;
    // iterate over liTags, creating the necessary span tags
    for (var i = 0; i < liTags.length; i++) {
        if (liTags[i].tagName) {
            var nextULTag = liTags[i].getElementsByTagName('ul') [0];
            // if we actually have a UL tag to process (ie, we
            // aren't at the bottom of the menu, and there
            // exists another submenu
            if (nextULTag) {
                // collapse the menu for this <li>
                nextULTag.style.display = 'none';
                // get the link that corresponds to this <li>
                // and create the onclick function for it to
                // act as a menu operation.
                //var correspondingLiLink = liTags[i].getElementsByTagName('a')[0];
                //correspondingLiLink.onclick = new Function(
                //'if(!this.previousSibling.className.match(/exp/)) {' +
                //	'clickHandler(this.previousSibling);}'
                //);
                
                
                // create a span class to hold the icon used for
                // collapsing and expanding menus.
                var aTags = nextULTag.getElementsByTagName('a');
                for (var j = 0; j < aTags.length; j++) {
                    //do checkmarks based on cookie:
                    //create an hmmPage from the link so we can getPageCompletion()
                    if (aTags[j].className.toString() .indexOf('folder') == - 1) {
                        var hPage = new hmmPage;
                        hPage[ "topicString" ] = topicTitle;
                        var aPageString = aTags[j].href.split("/");
                        var thisPageString = aPageString[aPageString.length - 1];
                        hPage[ "pageString" ] = thisPageString;
                        hPage[ "topicID" ] = topicToID[hPage[ "topicString" ]];
                        hPage[ "pageID" ] = pageToID[hPage[ "topicString" ]][hPage[ "pageString" ]];
                        hPage.setTopic(decToHex(hPage[ "topicID" ]));
                        hPage.setPage(decToHex(hPage[ "pageID" ]));
                        var visited = hbspCookie.getPageCompletion(hPage);
                        if (visited == 1) {
                            if ( ! aTags[j].className.match(/visited/)) {
                                totalPagesVisited++;
                                aTags[j].className = aTags[j].className + 'visited';
                            }
                        }
                    }
                }
                var spanIcon = document.createElement('span');
                spanIcon.className = 'nav_toggle';
                spanIcon.onclick = new Function('clickHandler(this); return false;');
                spanIcon.onmouseover = new Function('rolloverImgChange(this); return true;');
                spanIcon.onmouseout = new Function('rolloutImgChange(this); return true;');
                
                // insert the span tag that we just created into
                // the current <li> tag
                liTags[i].insertBefore(spanIcon, liTags[i].childNodes[0]);
                
                createMenuHelper(nextULTag);
            }
        }
    }
}


// This function handles the onclick events that are called when
// either using the navigation icon span tags directly, or indirectly via <a>
// tags that in turn call the events on their sibling spans.

// algorithm for clickHandler->
//   *if icon is expanded -> we want to stop displaying the underlying ul and
//			     change the icon's class/background
//   *if icon is collapsed -> we want to collapse all other sibling menus,
//			      and change the icon's class/background

function clickHandler(spanTag) {
    var parentLiTag = spanTag.parentNode;
    // is this span (and consequently, menu) expanded?
    if (spanTag.className == 'nav_toggle_exp' || spanTag.className == 'nav_toggle_exp_hover') {
        // yes, so we want to collapse this list, and change
        // the icon to collapsed version
        // hide the menu
        parentLiTag.getElementsByTagName('ul') [0].style.display = 'none';
        // change the icon to [+]
        spanTag.className = 'nav_toggle';
        if (iContainActiveLink(parentLiTag)) {
            shouldOpenToActiveLink = false;
        } else {
            collapseSiblingBranches(parentLiTag);
        }
    } else {
        //no, so we want to expand the list, collapse sibling lists,
        //and change the icon to expanded version
        parentLiTag.getElementsByTagName('ul') [0].style.display = 'block';
        //animateMenu(parentLiTag.getElementsByTagName('ul')[0]);
        // change the icon to [-]
        spanTag.className = 'nav_toggle_exp';
        if (iContainActiveLink(parentLiTag)) {
            shouldOpenToActiveLink = true;
        }
        collapseSiblingBranches(parentLiTag);
    }
    
    if (shouldOpenToActiveLink) {
        openBranchToActiveLink(document.getElementById('NAV_ITEMS'));
    }
}


// we will highlight all levels of the menu that contain the active
// link within their heirarchy. we will iterate over all of the <li>
// tags in the menu. checking to see if the active link resides inside of
// that tag. If it does, we selfhighlight it's own sibling link, and any
// links beneath it that also contain the link.
function highlightActiveLink(menuTopLevelUL) {
    var currentUL = document.getElementById(menuTopLevelUL);
    if (currentUL) {
        var liTags = currentUL.getElementsByTagName('li');
        for (var i = 0; i < liTags.length; i++) {
            if (iContainActiveLink(liTags[i])) {
                if ( ! liTags[i].getElementsByTagName('a') [0].className.match(/selfhighlight/)) {
                    liTags[i].getElementsByTagName('a') [0].className =
                    liTags[i].getElementsByTagName('a') [0].className + 'selfhighlight';
                }
                var ulTag = liTags[i].getElementsByTagName('ul') [0];
                // if there is a submenu, recurse and keep highlighting
                if (ulTag) {
                    highlightActiveLink(ulTag);
                }
            }
        }
    }
}


// checks to see if the menu associated with the given spanTag contains
// the active page/link. Iterate over all of the links inside of a <li> tag,
// and see if one of the links is the active link. If we find a match, highlight
// that link.
function iContainActiveLink(liTag) {
    var links = liTag.getElementsByTagName('a');
    for (var i = 0; i < links.length; i++) {
        if (links[i].getAttribute('href') && ! links[i].href.match(/#$/) &&
        getRealAddress(links[i]) == getRealAddress(location)) {
            if ( ! links[i].className.match(/selfhighlight/)) {
                links[i].className =
                links[i].className + 'selfhighlight';
            }
            //	links[i].className = 'selfhighlight';
            return true;
        }
    }
    return false;
}


// this function opens the menu to the currently active link
function openBranchToActiveLink(currentUL) {
    if (currentUL) {
        var liTags = currentUL.getElementsByTagName('li');
        for (var i = 0; i < liTags.length; i++) {
            if (iContainActiveLink(liTags[i])) {
                var spanTag = liTags[i].getElementsByTagName('span') [0];
                if (spanTag && ! spanTag.className.match(/exp/)) {
                    var parentLiTag = spanTag.parentNode;
                    if (spanTag.className == 'nav_toggle_exp' || spanTag.className == 'nav_toggle_exp_hover') {
                        // yes, so we want to collapse this list, and change
                        // the icon to collapsed version
                        // hide the menu
                        parentLiTag.getElementsByTagName('ul') [0].style.display = 'none';
                        // change the icon to [+]
                        spanTag.className = 'nav_toggle';
                    } else {
                        //no, so we want to expand the list, collapse sibling lists,
                        //and change the icon to expanded version
                        parentLiTag.getElementsByTagName('ul') [0].style.display = 'block';
                        // change the icon to [-]
                        spanTag.className = 'nav_toggle_exp';
                        
                    }
                }
                var ulTag = liTags[i].getElementsByTagName('ul') [0];
                // if there is a submenu, recurse and keep opening
                if (ulTag) {
                    openBranchToActiveLink(ulTag);
                }
                break;
            }
        }
    }
}

function collapseSiblingBranches(currentLi) {
    if (shouldAutoCollapse) {
        var siblingLiTags = currentLi.parentNode.getElementsByTagName('li');
        for (var i = 0; i < siblingLiTags.length; i++) {
            var spanTag = siblingLiTags[i].getElementsByTagName('span') [0];
            if (siblingLiTags[i] != currentLi && spanTag && spanTag.className.match(/exp/)) {
                var parentLiTag = spanTag.parentNode;
                if (spanTag.className == 'nav_toggle_exp' || spanTag.className == 'nav_toggle_exp_hover') {
                    // yes, so we want to collapse this list, and change
                    // the icon to collapsed version
                    // hide the menu
                    parentLiTag.getElementsByTagName('ul') [0].style.display = 'none';
                    // change the icon to [+]
                    spanTag.className = 'nav_toggle';
                } else {
                    //no, so we want to expand the list, collapse sibling lists,
                    //and change the icon to expanded version
                    parentLiTag.getElementsByTagName('ul') [0].style.display = 'block';
                    // change the icon to [-]
                    spanTag.className = 'nav_toggle_exp';
                    
                }
            }
        }
    }
}


//////////////////////////
// OTHER NAV FUNCTIONS ///
//////////////////////////

var REVIEWING = false;

// Function that will display the 'return to results' tag on a page if given
// cookie exists.
function displayResultsTag() {
    var reviewingAnswers = getCookie('reviewingAnswers');
    // don't display results tab if you are on the results page.
    if (pageURL != 'results.html') {
        if (reviewingAnswers != null && reviewingAnswers.indexOf('true') != - 1) {
            var contentDiv = document.getElementById('CONTENT');
            var parentDiv = contentDiv.getElementsByTagName('div') [0];
            var elementToInsertAfter = parentDiv.getElementsByTagName('h2') [0];
            var resultsTag = document.createElement('h3');
            resultsTag.className = "results_flag";
            var resultsLink = document.createElement('a');
            resultsLink.href = "results.html";
            resultsLink.innerHTML = "Back to Results &raquo;";
            resultsLink.onclick = new Function("setCookie('reviewingAnswers','',0);");
            resultsTag.appendChild(resultsLink);
            if (parentDiv != null && elementToInsertAfter != null) {
                parentDiv.insertBefore(resultsTag, elementToInsertAfter.nextSibling);
            }
        }
    }
}

// this function hides the linear nav at the bottom of question pages when you
// travel from the results page to fix/view an answer.

// MODIFICATION 01.17.2008
// add lines to specify the cookie name

function hideLinearNavIfReviewing() {
    var reviewingAnswers = getCookie('reviewingAnswers');
	ty_cookie_name = "HMMty"+topicIDNum;
    var tyCookie = getCookie(ty_cookie_name);
    if (reviewingAnswers != null && reviewingAnswers.indexOf('true') != - 1) {
        REVIEWING = true;
        var divs = document.getElementsByTagName('div');
        for (var i = 0; i < divs.length; i++) {
            if (divs[i].className.toLowerCase() == "linear_nav") {
                divs[i].style.visibility = "hidden";
            }
        }
    }
    // now, go and populate the user's previous answer. Only do this if you
    // are on a question page.
    if (onPracticePage) {
        var questionDiv = document.getElementById('HELP') .parentNode;
        var questionNumber = questionDiv.id;
        questionNumber = parseInt(questionNumber.substring(questionNumber.indexOf('_') + 1));
        var response = extractResponse(questionNumber, tyCookie);
        if (response != - 1) {
            var siblingLiTag = document.getElementById('P_FB' + response);
            if (siblingLiTag != null) {
                var realLiTag = siblingLiTag.previousSibling;
                realLiTag.getElementsByTagName('a') [0].onclick();
                realLiTag.getElementsByTagName('a') [0].focus();
            }
        }
    }
    
}

function blastReviewingAnswersCookie() {
    if (pageURL != 'results.html') {
        setCookie('reviewingAnswers', '', 0);
    }
}


function exitPrevious() {
    var link = document.getElementById("exit_activity_previous");
    if (link != null) {
        window.location = link.href;
    }
}

function exitNext() {
    var link = document.getElementById("exit_activity_next");
    if (link != null) {
        window.location = link.href;
    }
}
/*
if(exitType == 'reload') {
var link = document.getElementById("exit_activity");
if(link != null) {
window.location = link.href; }
}*/

///////////////////////
// UTILITY FUNCTIONS //
///////////////////////


// unfortunately, we need these global variables because we are doing
// lots of recursion using setTimeout in the next section, and setTimeout
// doesn't like parameters passed to it's argument function
var ulTagToAnimate;
var ulHeight;
var ulHeightOriginal;
var spanTags;
var speed;

function animateMenu(ulTag) {
    ulTag.style.overflow = "hidden";
    ulTagToAnimate = ulTag;
    ulHeight = 0;
    ulHeightOriginal = ulTag.scrollHeight;
    speed = ulHeightOriginal / 5;
    spanTags = ulTag.getElementsByTagName('span');
    for (var i = 0; i < spanTags.length; i++) {
        spanTags[i].style.display = "none";
    }
    animateMenuHelper();
}

function animateMenuHelper() {
    if (ulHeight > ulHeightOriginal) {
        ulTagToAnimate.style.height = "auto";
        setTimeout("reshowIcons()", 1);
    }
    else {
        ulTagToAnimate.style.height = ulHeight + "px";
        ulHeight += speed;
        setTimeout("animateMenuHelper()", 10);
    }
}

function reshowIcons() {
    spanTags = ulTagToAnimate.getElementsByTagName('span');
    for (var i = 0; i < spanTags.length; i++) {
        spanTags[i].style.display = "block";
    }
}


// This method preloads all of the navigation images for
// advanced caching.
function preloadNavImages() {
    var navImages = new Array('../img/nav_toggle_a_col_up.png',
    '../img/nav_toggle_a_col_hover.png',
    '../img/nav_toggle_a_exp_hover.png',
    '../img/nav_toggle_a_exp_up.png',
    '../img/nav_toggle_collapsed.gif',
    '../img/nav_toggle_collapsed_hover.gif',
    '../img/nav_toggle_expanded.gif',
    '../img/nav_visited_check.gif');
    objImage = new Image();
    for (var i = 0; i < navImages.length; i++) {
        objImage.src = navImages[i];
    }
}

// Both of these functions use the slick CSS property of
// using the nesting level of an element to choose its
// image. see nav.css

// Used to change the images in the left navigation
// panel when rolled over
function rolloverImgChange(spanTag) {
    switch (spanTag.className) {
        case "nav_toggle" :
        spanTag.className = "hover";
        break;
        case "nav_toggle_exp" :
        spanTag.className = "nav_toggle_exp_hover";
        break;
        default : return true;
    }
}

// Used to change the images in the left navigation
// panel when rolled out.
function rolloutImgChange(spanTag) {
    switch (spanTag.className) {
        case "hover" :
        spanTag.className = "nav_toggle";
        break;
        case "nav_toggle_exp_hover" :
        spanTag.className = "nav_toggle_exp";
        break;
        default : return true;
    }
}

function disableExploreFurtherLinks()
  {
 
    if(!DISABLE_EXPLORE_FURTHER_LINKS){return;}
    var content =  document.getElementById("TEXT_AREA");
    if (content.hasChildNodes())
      {
        var children = content.childNodes;
        for (var i = 0; i < children.length; i++) 
        {
          var child = children[i];
          if(child.className == "article")
          {
            var externalLink = child.firstChild;
            if(externalLink.getAttribute("href").indexOf("http://harvardbusinessonline.hbsp.harvard.edu") != -1){
            var text = document.createElement("span");
    text.innerHTML = externalLink.innerHTML;
    
            child.removeChild(externalLink);
            child.appendChild(text);
                   }
           }
        }
      }
  }

function getRealAddress(oOb) {
    return oOb.protocol + ((oOb.protocol.indexOf(':') + 1) ? '' : ':') +
    oOb.hostname + ((typeof (oOb.pathname) == typeof (' ') && oOb.pathname.indexOf('/') != 0) ? '/' : '') +
    oOb.pathname + oOb.search;
}