var req;
var conrefId;
var thCookie = getTotalHelpCookie();
var imgPrefix = (window.location.toString().indexOf("http", 0) == 0) ? "" : "css/images/";


function doShowHide(foo) {

    if (document.getElementById('div' + foo).className == 'show') {
        document.getElementById('div' + foo).className = 'hide';
        if (document.getElementById('img' + foo) != null) {
            document.getElementById('img' + foo).src = imgPrefix + 'plus.gif';
            document.getElementById('img' + foo).alt = ' + ';
            document.getElementById('img' + foo).title = ' + ';
        }
    }
    else {
        document.getElementById('div' + foo).className = 'show';
        if (document.getElementById('img' + foo) != null) {
            document.getElementById('img' + foo).src = imgPrefix + 'minus.gif';
            document.getElementById('img' + foo).alt = ' - ';
            document.getElementById('img' + foo).title = ' - ';
        }
    }
}

function doShowHideAjax(foo) {
    if (document.getElementById('div' + foo).className == 'showbuttons') {
        document.getElementById('div' + foo).className = 'hide';
        document.getElementById('bg/' + foo).style.background = 'url(images/opentriangle.gif) no-repeat 0 0';
    }
    else {
        document.getElementById('bg/' + foo).style.background = 'url(images/closetriangle.gif) no-repeat 0 0';
        document.getElementById('div' + foo).className = 'showbuttons';
    }
}

function doShowHideTopic(foo) {
    if (document.getElementById('div' + foo).className == 'topicshow') {
        document.getElementById('div' + foo).className = 'topichide';
        document.getElementById('img' + foo).src = imgPrefix + 'IconFolder.gif';
        document.getElementById('img' + foo).alt = ' + ';
        document.getElementById('img' + foo).title = ' + ';
        document.getElementById('topicbox' + foo).style.background = 'transparent';
        document.getElementById('topicbox' + foo).style.borderTop = 'none';
        document.getElementById('topicbox' + foo).style.marginTop = '0px';
    }
    else {
        document.getElementById('div' + foo).className = 'topicshow';
        document.getElementById('img' + foo).src = imgPrefix + 'IconFolderOpen.gif';
        document.getElementById('img' + foo).alt = ' - ';
        document.getElementById('img' + foo).title = ' - ';
        document.getElementById('topicbox' + foo).style.borderTop = 'dashed #ccc 1px';
        document.getElementById('topicbox' + foo).style.marginTop = '-1px';
        document.getElementById('topicbox' + foo).style.backgroundPosition = 'top';
        document.getElementById('topicbox' + foo).style.backgroundRepeat = 'repeat-x';
    }
}

function doShowHideResults(foo) {
    if (document.getElementById('div' + foo).className == 'show') {
        document.getElementById('div' + foo).className = 'hide';
    }
    else {
        document.getElementById('div' + foo).className = 'show';
        var oNodeToRemove = document.getElementById('txt' + foo);
        oNodeToRemove.parentNode.removeChild(oNodeToRemove);
        oNodeToRemove = document.getElementById('spn' + foo);
        if (oNodeToRemove != null) oNodeToRemove.parentNode.removeChild(oNodeToRemove);
    }
    findLiveHeight();
}

function putFocus(formInst, elementInst) {
    if (document.forms.length > 0) {
        try { document.forms[formInst].elements[elementInst].focus(); } catch (Error) {}
    }
}

function popUp(URL) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=600,left = 240,top = 212');");
}

function popUpPrint(URL) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=600,left = 240,top = 212');");
}

function findLiveHeight() {

    var browser = navigator.appName
    var b_version = navigator.appVersion
    var version = parseFloat(b_version)

    viewPort = (document.body.clientHeight) ? document.body.clientHeight : window.innerHeight;

    var headHeight = (document.getElementById('header')) ? (document.getElementById('header').offsetHeight == 0 ? 72 : document.getElementById('header').offsetHeight) : 0;
    if (document.getElementById('breadcrumb')) breadHeight = document.getElementById('breadcrumb').offsetHeight == 0 ? 35 : document.getElementById('breadcrumb').offsetHeight;
    if (document.getElementById('indexhead')) indexHeadHeight = document.getElementById('indexhead').offsetHeight == 0 ? 50 : document.getElementById('indexhead').offsetHeight;

    if (document.getElementById('generated') != null) {
        if (!document.getElementById('breadcrumb')) {
            if (document.getElementById('footer') != null) generatedHeight = (viewPort - 133 > 0) ? viewPort - 133 : 0;
            else generatedHeight = (viewPort - headHeight - 20 > 0) ? viewPort - headHeight - 20 : 0;
        } else {
            if (!document.getElementById('indexhead')) generatedHeight = (viewPort - 23 - (breadHeight + headHeight) > 0) ? viewPort - 23 - (breadHeight + headHeight) : 0;
            else generatedHeight = (viewPort - 23 - (breadHeight + indexHeadHeight + headHeight) > 0) ? viewPort - 23 - (breadHeight + indexHeadHeight + headHeight) : 0;
        }
        document.getElementById('generated').style.height = generatedHeight + 'px';
    }

    if (document.body.clientHeight != null) {
        if (document.getElementById('content') != null && !document.getElementById('relatedbody')) {
            if (!document.getElementById('breadcrumb')) contentHeight = (viewPort - 110 > 0) ? viewPort - 110 : 0;
            else contentHeight = (viewPort - 23 - (breadHeight + headHeight) > 0) ? viewPort - 23 - (breadHeight + headHeight) : 0;
            document.getElementById('content').style.height = contentHeight + 'px';
        }
        if (document.getElementById('errorboxdiv') != null) {
            document.getElementById('generated').style.height = viewPort - 20 + 'px';
        }
    }

    if (!thCookie.highlightOn) {

        //Get the search terms from the thCookie object.
        var keywords = thCookie.searchTerms;
        document.getElementsByName('queryString').item(0).value = keywords;
        myArray3 = parseSearchTerms(keywords);
        for (y = 0; y < myArray3.length; y++) {
            highlight(myArray3[y].term.replace('\(', '\[\(\]').replace('\)', '\[\)\]'));
        }
   }
    
    if (document.title.indexOf("Index") >= 0) {
        if (typeof filterIndex != "undefined") filterIndex(thCookie.indexFilter, true);
    }

    var podHeight = (viewPort - 110) > 300 ? viewPort - 110 : 300;
    //createCSS("#sidebar .box div", "max-height:" + podHeight.toString() + "px;");
    return (null);
}

function createCSS(selector, declaration) {
    // test for IE
    var ua = navigator.userAgent.toLowerCase();
    var isIE = (/msie/.test(ua)) && !(/opera/.test(ua)) && (/win/.test(ua));

    // create the style node for all browsers
    var style_node = document.createElement("style");
    style_node.setAttribute("type", "text/css");
    style_node.setAttribute("media", "screen");

    // append a rule for good browsers
    if (!isIE) style_node.appendChild(document.createTextNode(selector + " {" + declaration + "}"));

    // append the style node
    document.getElementsByTagName("head")[0].appendChild(style_node);

    // use alternative methods for IE
    if (isIE && document.styleSheets && document.styleSheets.length > 0) {
        var last_style_node = document.styleSheets[document.styleSheets.length - 1];
        if (typeof (last_style_node.addRule) == "object") last_style_node.addRule(selector, declaration);
    }
};

function setHighlightIcon() {
    var unh = document.getElementById('highlight');
    if (unh != null) {
        unh.className = (!thCookie.highlightOn) ? "on" : "off";
        unh.title = (!thCookie.highlightOn) ? "Remove highlighting" : "Highlight search terms";
    } 
}

function toggleHighlights() {
    thCookie.highlightOn = !thCookie.highlightOn;
    setTotalHelpCookie();
    window.location.reload();
}

function loadXMLDoc(url) {
    conrefId = url;
    targetList = document.getElementById(conrefId + '/incoming');
    if (targetList.hasChildNodes()) {
        while (targetList.firstChild) {
            targetList.removeChild(targetList.firstChild);
        }
    }

    var para = document.createElement('p');
    targetList.appendChild(para);

    var img = document.createElement('img');
    para.appendChild(img);
    img.setAttribute("src", "images/live_com_loading.gif");

    var wait = document.createTextNode(' Please Wait...');
    para.appendChild(wait);

    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
        req.open("GET", 'http://lngdaywebd008:8090/tabula-rasa/conrefs/' + url, true);
        req.send(null);
    }

    // branch for IE/Windows ActiveX version
    else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
            req.open("GET", 'http://lngdaywebd008:8090/tabula-rasa/conrefs/' + url, true);
            req.send();
        }
    }
}


function processReqChange() {
    // only if req shows "complete"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {


            // ...processing statements go here...
            response = req.responseXML.documentElement;
            conrefs = response.getElementsByTagName('conref');
            targetList = document.getElementById(conrefId + '/incoming');

            if (targetList.hasChildNodes()) {
                while (targetList.firstChild) {
                    targetList.removeChild(targetList.firstChild);
                }

                for (var x = 0; x < conrefs.length; x++) {
                    var project = conrefId.split('/');
                    var conref = document.createTextNode(conrefs[x].firstChild.data);
                    var item = document.createElement('p');
                    targetList.appendChild(item);
                    var link = document.createElement('a');

                    var tokens = conrefs[x].firstChild.data.split('\.');
                    var attr = document.createAttribute('href');
                    attr.value = 'translation?product=' + project[0] + '&source=' + tokens[0] + '.xml#' + tokens[1];
                    link.setAttributeNode(attr);

                    item.appendChild(link);
                    targetList.appendChild(item);
                    link.appendChild(conref);
                }
            }

            if (conrefs.length == 0) {
                var item = document.createElement('p');
                targetList.appendChild(item);
                var text = document.createTextNode('None');
                item.appendChild(text);

            }

        }


        else {
            alert("There was a problem retrieving the XML data:\n" + req.statusText);
        }
    }
}

function getTotalHelpCookie() {
    wArray = (window.location.toString().indexOf("http", 0) == 0) ? document.cookie.split(";") : window.name.split(";");
    for (i = 0; i < wArray.length; i++) {
        itemArray = wArray[i].split("=");
        while (itemArray[0].indexOf(" ") == 0) itemArray[0] = itemArray[0].substr(1);
        switch (itemArray[0]) {
            case "fontSize":
                this.size = itemArray[1];
                break;
            case "searchTerms":
                this.searchTerms = itemArray[1];
                break;
            case "indexFilter":
                this.indexFilter = itemArray[1];
                break;
            case "highlightOn":
                this.highlightOn = (itemArray[1] == "true");
                break;
            case "indexScroll":
                this.indexScroll = itemArray[1];
                break;
        }
    }
    if (!this.size) this.size = 1;
    if (!this.searchTerms) this.searchTerms = "";
    if (!this.indexFilter) this.indexFilter = "";
    if (!this.highlightOn) this.highlightOn = false;
    if (!this.indexScroll) this.indexScroll = 0;
    return this;

}

function setTotalHelpCookie() {
    if (window.location.toString().indexOf("http", 0) == 0 || document.location.toString().indexOf("http", 0) == 0) {
        var today = new Date();
        var exp = new Date(today.getTime() + (365 * 24 * 60 * 60 * 1000)); //the cookie will expire in one year
        document.cookie = "fontSize=" + thCookie.size + "; expires=" + exp.toGMTString() + "; path=/";
        document.cookie = "searchTerms=" + thCookie.searchTerms + "; path=/";
        document.cookie = "indexFilter=" + thCookie.indexFilter + "; path=/";
        document.cookie = "highlightOn=" + thCookie.highlightOn + "; path=/";
        document.cookie = "indexScroll=" + thCookie.indexScroll + "; path=/";
    }
    else {
        cookie = "fontSize=" + thCookie.size + ";";
        cookie += "searchTerms=" + thCookie.searchTerms + ";";
        cookie += "indexFilter=" + thCookie.indexFilter + ";";
        cookie += "highlightOn=" + thCookie.highlightOn + ";";
        cookie += "indexScroll=" + thCookie.indexScroll;
        window.name = cookie;
    }
}

function parseSearchTerms(sTerms) {
    myTerms = new Array();
    SearchTermsList = new Array();
    bBeginQuote = false;
    sTerm = "";

    for (tmp = 0; tmp < sTerms.length; tmp++) {
        if (sTerms.charAt(tmp) == "\"") bBeginQuote = !bBeginQuote;
        else {
            if (bBeginQuote) sTerm += sTerms.charAt(tmp);
            else {
                if (sTerms.charAt(tmp) == " ") {
                    myTerms[myTerms.length] = sTerm;
                    sTerm = "";
                }
                else sTerm += sTerms.charAt(tmp);
            }
        }
    }

    if (sTerm != "") myTerms[myTerms.length] = sTerm;

    for (tmp = 0; tmp < myTerms.length; tmp++) {
        if (tmp < myTerms.length) {
            switch (myTerms[tmp]) {
                case "AND":
                case "OR":
                case "NOT":
                    if (SearchTermsList.length > 0) SearchTermsList[SearchTermsList.length - 1].connector += myTerms[tmp];
                    break;
                default:
                    SearchTermsList[SearchTermsList.length] = new searchTerm(myTerms[tmp]);
            }
        }
    }

    return SearchTermsList;
}

// Constructor for search terms.
function searchTerm(term) {
    this.term = term;
    this.connector = "";
    this.topics = new Array();
    return this;
}

// The following function is based on the original version of the highlight function found here:
// http://4umi.com/web/javascript/hilite.php
// Adapted by Jared C. 5/1/2008

function highlight(s) {
    if (s.indexOf("[") < 0 && s.indexOf("\\") < 0 && s.indexOf("^") < 0 && s.indexOf("$") < 0 && s.indexOf(".") < 0 && s.indexOf("|") < 0 && s.indexOf("?") < 0 && s.indexOf("*") < 0 && s.indexOf("+") < 0 && s.indexOf("(") < 0 && s.indexOf(")") < 0) {
        if (!s || /^\s*$/.test(s)) { return 0; }

        var d = window.document;
        o = [d.body];

        h = d.createElement('span');
        h.className = "highlight";        

        var r = new RegExp(s, 'gi'), h, i = 0, j, k, l, m, t;

        do {
            m = o[i];
            if (m.nodeType === 3) {
                r.lastIndex = 0;
                l = r.exec(m.nodeValue);
                if (l !== null) {
                    k = l[0].length;
                    if (r.lastIndex > k) {
                        m.splitText(r.lastIndex - k);
                        m = m.nextSibling;
                    }
                    if (m.nodeValue.length > k) {
                        m.splitText(k);
                        o[i++] = m.nextSibling;
                    }
                    t = h.cloneNode(true);
                    t.appendChild(d.createTextNode(l[0]));
                    m.parentNode.replaceChild(t, m);
                }
            } else {
                j = m.childNodes.length;
                while (j) { o[i++] = m.childNodes.item(--j); }
            }
        } while (i--);
    }
}

/* The following functions handle the scrolling sidebar feature. */

var timerScroll = ""

function SubscribeScrollbar() {
// Disabled for now. The currentTarget object in wheel doesn't work right in IE.
//    if (document.getElementById("sidebar")) {
//    var elem = document.getElementById("sidebar").getElementsByTagName("div");
//    for (var i = 0; i < elem.length; i++) {
//        if (elem[i].addEventListener) elem[i].addEventListener('DOMMouseScroll', wheel, false);
//        elem[i].onmousewheel = wheel;
//        }
//    }
}

function scrollDiv(id, step) {
    clearTimeout(timerScroll);
    document.getElementById(id).scrollTop += step;
    timerScroll = setTimeout("scrollDiv('" + id + "'," + step + ")", 10);
}

function scrollDivStop() {
    clearTimeout(timerScroll);
}

function wheel(event) {
    var delta = 0;
    if (!event) event = window.event;
    if (event.wheelDelta) {
        delta = event.wheelDelta / 120;
        if (window.opera) delta = -delta;
    } else if (event.detail) {
        delta = -event.detail / 3;
    }
    event.currentTarget.scrollTop -= delta * 50;

    if (event.preventDefault) event.preventDefault();
    event.returnValue = false;
}