window.onload = function() {
        //translateMath();
        //translate(true);
        searchHighlight();
        
        if (String(window.location).substr(0, 5) == "http:") {
            var parenttable = $("parentlist");
            var tds = parenttable.getElementsByTagName("td");
            if (tds && tds.length > 0) {
                var td1 = Builder.node("td",
                {"id": "showtoc", "class": "contents"},
                [
                    Builder.node("a", {
                        "id": "showtoca",
                        "href": "javascript:toggleToc()",
                    }, "Contents")
                ]);
                var td2 = Builder.node("td", {"class": "parentstartsep"});
                
                var first = tds[0];
                first.parentNode.insertBefore(td1, first);
                first.parentNode.insertBefore(td2, first);
            }
            Event.observe("sidebarspace", "click", hideToc);
            
            var h = $("header").getHeight();
            $("splitcontainer").style.top = h + "px";
            
            positionDivs();
        }
        
        if (window.filteruis) {
            for (var i = 0; i < window.filterids.length; i++) {
                var id = window.filterids[i];
                updateFilteredList(id)
            }
        }
        
        if (!window.googlesearchbox) {
            fieldTitle("q");
            window.searchcompleter = new QuickSearch(
            "q", "autocomplete_choices", "/find", {
                "paramName": "q",
                "frequency": 0.25,
                "minChars": 2,
                "method": "GET",
                "callback": function(element, entry) {
                    var c = $("chapter");
                    var p = (c && c.value != "") ? 
                        entry + "&chapter=" + c.value :
                        entry;
                    return p + "&template=/templates/quickfind.html";
                },
                "onShow": function(element, update) {
                    update.style.position = "absolute";
                    Position.clone(element, update, {
                        "setHeight": false,
                        "setWidth": false,
                        "offsetLeft": 0 - update.getWidth() + element.getWidth(),
                        "offsetTop": element.getHeight()
                    });
                    Effect.Appear(update, {"duration": 0.15});
                }
            });
        }
        
        var sectionselect = $("sectionselect");
        if (sectionselect) {
            var uidiv = sectionselect.parentNode;
            var html = uidiv.innerHTML;
            var prev = Builder.node("a", {"class": "prevtab", "href": "javascript:prevTab()"}, [Builder.node("span", "Prev")]);
            var next = Builder.node("a", {"class": "nexttab", "href": "javascript:nextTab()"}, [Builder.node("span", "Next")]);
            
            uidiv.insertBefore(prev, sectionselect);
            uidiv.appendChild(next);
            showTab(sectionselect.value);
        }
        
        if (window.pageType != "start") {
            loadUserNotes();
        } else {
            loadVideos();
        }
        
        var sam = $("seealsomore");
        if (sam) {
            sam.style.display = "none";
        }
        
        //var noteDiv = $("userNotes");
        //if (noteDiv) {
        //    getUserContribNotes();
        //}
}
window.onresize = function() {
    positionDivs();
    if (window.splitter) {
        window.splitter.setDividerHeight();
    }
}

function seeAlsoMore() {
    var sam = $("seealsomore");
    var sat = $("seealsotrigger");
    if (sam && sat) {
        sat.style.display = "none";
        sam.style.display = "inline";
    }
}

function positionDivs() {
    var hh = $("header").getHeight();
    var s = $("sidebar");
    var si = $("sidebarinside");
    var ss = $("sidebarspace");
    var ssi = $("sidebarspaceinside");
    var m = $("main");
    
    var wh = window.innerHeight - hh;
    
    s.style.height = wh + "px";
    ss.style.height = wh + "px";
    
    if (si && si.getHeight() < wh) {
        si.style.height = wh + "px";
    }
    if (ssi && ssi.getHeight() < wh) {
        ssi.style.height = wh + "px";
    }
    if (m) {
        m.style.minHeight = (window.innerHeight - m.offsetTop) + "px";
    }
}

function fieldTitle(el) {
    el = $(el);
    if (el) {
        var value = el.value;
        var title = el.getAttribute("title");
        
        if (value == '' || value == title) {
            el.addClassName("empty");
            el.value = title;
        }
        
        Event.observe(el, "focus", function() {
            if (el.value == title) {
                el.value = "";
                el.removeClassName("empty");
            }
        });
        Event.observe(el, "blur", function() {
            if (el.value == "") {
                el.value = title;
                el.addClassName("empty");
            }
        });
    }
}

function searchFilter(id) {
    try {
        var sel = $("chapter");
        if (sel.value != id) {
            sel.value = id;
        }
        var el = $("q");
        if (el)
            el.focus();
            if (el.value != "")
                window.searchcompleter.activate();
    } catch (e) {
        alert("searchFilter: "+e+" "+e.lineNumber);
    }
}

function tocFinished() {
    if (window.parentPaths && window.parentPaths.length > 1) {
        var head = window.parentPaths[0];
        if (head == "/") {
            window.toc.openList(window.parentPaths.slice(1, window.parentPaths.length));
        }
    }
}

function toggleToc() {
    if ($("splitcontainer").style.display != "block") {
        showToc();
    } else {
        hideToc();
    }
}
function showToc() {
    var a = $("showtoca");
    a.setAttribute("href", "javascript:hideToc()");
    var sc = $("splitcontainer")
    $("header").className = "open";
    if (!window.splitter) {
        window.splitter = new SplitPane("sidebar", 33.0, "sidebarspace", 33.0, 67.0, { active: true });
        window.splitter.set();
        
        window.toc = new Tree(null, $("tocTree"), {"isparent": true, "path": "/"}, tocFinished);
        window.toc.initialize();
        window.toc.loadChildren();
    }
    sc.style.visibility = "visible";
}
function hideToc() {
    var a = $("showtoca");
    a.setAttribute("href", "javascript:showToc()");
    $("header").className = "closed";
    $("splitcontainer").style.visibility = "hidden";
}

function showTab(id) {
    var found = false;
    var txt = $("text");
    var tabtable = $("sectiontabs")
    if (txt) {
        found = true;
        var e
        
        if (tabtable) {
            var tabs = tabtable.getElementsByTagName("td");
            for (i = 0; i < tabs.length; i++) {
                e = tabs[i];
                if (e.id == id + "_sectiontab") {
                    e.className = "currentsection";
                } else {
                    e.className = "";
                }
            }
        }
        
        for (i = 0; i < txt.childNodes.length; i++) {
            e = txt.childNodes[i];
            if (e.nodeType == 1) {
                if (id == null || id == "" || e.id == id) {
                    e.style.display = "block";
                } else {
                    e.style.display = "none";
                }
            }
        }
    }
    positionDivs();
    return !found;
}

function prevTab() {
    var select = $("sectionselect");
    var index = select.selectedIndex - 1;
    if (index < 0) index = select.options.length - 1;
    select.selectedIndex = index;
    showTab(select.value);
}
function nextTab() {
    var select = $("sectionselect");
    var index = select.selectedIndex + 1;
    if (index >= select.options.length) index = 0;
    select.selectedIndex = index;
    showTab(select.value);
}

function getSearchWords(url) {
    if (url.indexOf('?') == -1) return [];
    
    var queryString = url.substr(url.indexOf('?') + 1);
    var params = queryString.split('&');
    
    for (var p = 0; p < params.length; p++) {
        var param = params[p].split('=');
        if (param.length < 2) continue;
        
        if (param[0] == 'q' || param[0] == 'p') { // q= for Google, p= for Yahoo
            var query = decodeURIComponent(param[1].replace(/\+/g, ' '));
            if (query[0] == '!') query = query.slice(1);
            words = query.split(/(".*?")|('.*?')|(\s+)/);
            
            var words2 = new Array();
            for (var w = 0; w < words.length; w++) {
                var nword = String(words[w]).replace(/^\s+$/, '');
                if (nword != '') {
                    words2.push(nword.replace(/^['"]/, '').replace(/['"]$/, ''));
                }
            }
            return words2;
        }
    }
    return [];
}

function highlightWord(node, word, searchwordindex) {
    // If this node is a text node and contains the search word, highlight it by
    // surrounding it with a span element
    if (node.nodeType == 3) { // Node.TEXT_NODE
        word = word.toString()
        var pos = node.nodeValue.toLowerCase().indexOf(word.toLowerCase());
        if (pos >= 0 && !node.parentNode.className.indexOf("searchword") == 0) {
            var span = document.createElement("span");
            span.className = "searchword" + (searchwordindex % 5);
            
            span.appendChild(document.createTextNode(
            node.nodeValue.substr(pos, word.length)));
            
            node.parentNode.insertBefore(span, node.parentNode.insertBefore(
            document.createTextNode(node.nodeValue.substr(pos + word.length)),
            node.nextSibling));
            
            node.nodeValue = node.nodeValue.substr(0, pos);
            return true;
        }
    } else if (!node.nodeName.match(/button|select|textarea/i) && (!node.className || node.className.indexOf("searchword") < 0)) {
        // Recurse into child nodes
        for (var i = 0; i < node.childNodes.length; i++) {
            if (highlightWord(node.childNodes[i], word, searchwordindex)) i++;
        }
    }
    return false;
}

function clearHighlights(node) {
	if (node.nodeType == 1 && node.nodeName.toLowerCase() == "span" && node.className && node.className.indexOf("searchword") == 0) {
		var parent = node.parentNode;
		var textNode = node.childNodes[0];
		node.removeChild(textNode);
		parent.replaceChild(textNode, node);
		return true;
	} else if (node.nodeType == 1) {
		done = false;
		while (!done) {
			replaced = false;
			for (var i = 0; i < node.childNodes.length; i++) {
				replaced = replaced || clearHighlights(node.childNodes[i]);
			}
			done = !replaced;
		}
		node.normalize()
	}
}
  
function searchHighlight() {
    if (!document.createElement) return;
    
    var div = $("main") || $("content");
    if (!div) return;
    
    var words = getSearchWords(document.URL);
    if (!words.length) words = getSearchWords(document.referrer);
    
    if (words.length) {
        for (var w = 0; w < words.length; w++) {
            if (words[w].length) highlightWord(div, words[w], w);
        }
    }
}

function translateMath() {
    if (window.AMinitSymbols && window.AMprocessSpan) {
        var mathSpans = getElementsByTagAndClassName("span", "asciimath");
        if (mathSpans.length > 0) {
            AMinitSymbols();
            for (var i = 0; i < mathSpans.length; i++) {
                var span = mathSpans[i];
                AMprocessSpan(span, true);
            }
        }
    } else {
        //alert("AMprocessSpan not available");
    }
}

function getUserContribNotes(docPath, majorVer, minorVer, buildVer) {
    try {
        var docPath = docPath || window.docPath || window.location.pathname
        
        majorVer = majorVer || window.majorVer || 9;
        minorVer = minorVer || window.minorVer || 0;
        buildVer = buildVer || window.buildVer || 0;
    
        var specs = "?pageURL=" + docPath +
                    "&docsMajorVer=" + majorVer +
                    "&docsMinorVer=" + minorVer +
                    "&docsBuildVer=" + buildVer +
                    "&json=json";
        
        var target = userNotesViewUrl + specs;

        var hostname;
        try {
            hostname = window.location.hostname
        } catch (e) {
            // If window.location.hostname fails, it's probably
            // because this is a user-created helpcard, so we
            // fake-loaded it as a string, so it doesn't have a
            // network location.
            //
            // In that case, we'll just give up on user-contributed
            // notes for now.
            
            return;
        }

	// If hostname is blank, then we are running the help pages
	// as static HTML pages without a server.  Therefore, we
	// skip loading user-contributed notes because there is no way
	// for us to figure out what the document's virtual help path
	// is based solely on the web page's file path.
	if (hostname == "")
	    return;
        
        if (hostname == "www.sidefx.com") {
            // This chunk of code needs to be updated if we ever
            // move the online Houdini documentation to a different root path.
            root_path_exp = /^\/docs\/(current|houdini...)\//i;
            docPath = docPath.replace(root_path_exp, "/");
            target = "/docs/user_contrib/view.php" +
                "?path=" + docPath +
                "&docsMajorVer=" + majorVer +
                "&docsMinorVer=" + minorVer +
                "&docsBuildVer=" + buildVer;
        } else {
            target = "/user_notes" +
                "?path=" + docPath +
                "&major=" + majorVer +
                "&minor=" + minorVer +
                "&build=" + buildVer;
        }

        request = new XMLHttpRequest();
    
        request.onerror = function() {
            var e = document.getElementById('userNotesMessage');
            e.innerHTML = "<p>Error getting user-contributed notes:"
                + request.statusText + "<br/>"
                + request.responseText + "</p>";
        }

        request.onreadystatechange = function() {
            // We'll get ready states of 0 through 4.  4 means it's done.
            if (request.readyState != 4) return;
    
            var e = $('userNotesContent');
            
            // An http status of 200 means everything was ok.
            if (request.status == 200) {
                var resp = request.responseText;
                var json = resp.parseJSON()
                var notes = json.notes;
                
                var addNote = userNotesPostUrl + specs;
                var html = "<div id='userNotesAdd'><a href='" + addNote + "'>Add a note...</a></div>";
                
                if (!notes) {
                    html = "<div id='userNotesNA'>User notes not available</div>";
                } else if (notes.length > 0) {
                    html += "<table id='userNotesList' cellspacing='0'>";
                    for (var i = 0; i < notes.length; i++) {
                        var note = notes[i];
                        html += "<tr class='userNote'>";
                        html += "<td class='noteData'>";
                        html += "<p class='noteCreator'>" + note.creator + "</p>";
                        html += "<p class='noteDate'>" + note.date + "</p>";
                        html += "</td>";
                        html += "<td class='noteContent'>";
                        html += xformHtml(note.note);
                        html += "</td>";
                        html += "</tr>";
                    }
                    html += "</table>";
                }
                
                e.innerHTML = html;
            } else {
                e.innerHTML = "<p>Could not get user-contributed notes.</p>";
            }
        }

        // Send an asynchronous request.  We'll update the page once the
        // information is retrieved.
        request.open("GET", target, true);
        request.send(null);
    
    } catch (e) {
        alert("Error getting user-contributed notes: " + e);
    }
}

function clickAnim(e) {
    try {
        var p = e.parentNode;
        var c = p.className;
        var s = e.getAttribute("src");
        var t;
        if (c == "animationplaying") {
            s = s.replace(".gif", "_poster.gif");
            c = "animationstopped";
            t = "Click to play";
        } else {
            s = s.replace("_poster.gif", ".gif");
            c = "animationplaying";
            t = "Click to stop";
        }
        e.setAttribute("src", s);
        e.setAttribute("title", t);
        p.setAttribute("class", c);
    } catch (e) {
        alert("clickAnim: "+e);
    }
}

filterTimer = null;
function filterKey(id, event) {
    if (filterTimer) {
        clearTimeout(filterTimer);
    }
    if (event.keyCode == 27) {
        Event.stop(event);
        var e = Event.element(event);
        e.value = "";
        updateFilteredList(id);
    } else {
        filterTimer = setTimeout("updateFilteredList('" + id + "')", 200);
    }
}

function updateFilteredList(id, text) {
    if (window.filteruis) {
        var data = window.filteruis[id];
        if (data && typeof(data) != "function") {
            var idfield = data['idfield'];
            var pages = data['pages'];
            var filters = data['filters'];
            
            if (text == undefined) {
                var tbox = text = $(id + "_text")
                if (tbox) {
                    text = tbox.value;
                }
            }
            
            if (text == null || text == undefined) {
                text = "";
            }
            
            text = text.toLowerCase();
            words = text.split(/ +/);
            
            var filterElements = []
            if (filters) {
                for (var i = 0; i < filters.length; i++) {
                    filterElements.push($(id + "_" + filters[i]))
                }
            }
            
            var filtered = false;
            if (text != "") {
                filtered = true;
            } else {
                for (var i = 0; i < filterElements.length; i++) {
                    if (filterElements[i].value != "*") {
                        filtered = true;
                        break;
                    }
                }
            }
            
            // If the list is filtered, hide the category headings
            var categoryList = $(id + "_list");
            if (categoryList) {
                categoryElements = categoryList.getElementsByTagName("H3");
                for (var i = 0; i < categoryElements.length; i++) {
                    categoryElements[i].style.display = filtered ? "none" : "block";
                }
            }
            
            for (var i = 0; i < pages.length; i++) {
                var pg = pages[i]
                var e = $(id + "_" + pg[idfield]);
                var title = pg['title'];
                var summary = pg['summary'];
                
                if (e) {
                    matched = true;
                    
                    if (text != "") {
                        for (var j = 0; j < words.length; j++) {
                            var t = words[j];
                            matched = ((title && title.toLowerCase().indexOf(t) > -1) || (summary && summary.toLowerCase().indexOf(t) > -1));
                            if (!matched) break;
                        }
                    }
                    
                    if (matched) {
                        for (var j = 0; j < filterElements.length; j++) {
                            var name = filters[j];
                            var value = filterElements[j].value;
                            if (value == "*") continue;
                            if (!pg[name] || pg[name].indexOf(value) < 0) {
                                matched = false;
                                break;
                            }
                        }
                    }
                    
                    e.style.display = matched ? "block" : "none";
                }
            }
        }
    }
}

function clearFilters(id) {
    if (window.filteruis) {
        var data = window.filteruis[id];
        if (data) {
            var filters = data['filters'];
            
            $(id + "_text").value = "";
            
            for (var i = 0; i < filters.length; i++) {
                $(id + "_" + filters[i]).value = "*";
            }
            updateFilteredList(id);
        }
    }
}

function getInnerText(el) {
    if (typeof el == "string") return el;
    if (typeof el == "undefined") { return el };
    if (el.innerText) return el.innerText;  //Not needed but it is faster
    
    var str = "";
    var cs = el.childNodes;
    var l = cs.length;
    for (var i = 0; i < l; i++) {
        switch (cs[i].nodeType) {
            case 1: //ELEMENT_NODE
                str += getInnerText(cs[i]);
                break;
            case 3: //TEXT_NODE
                str += cs[i].nodeValue;
                break;
        }
    }
    return str;
}
function updateSort(id) {
    var ls = $(id);
    var cls = $(id + "_select").value;
    if (ls && cls) {
        var els = new Array();
        var kid = ls.firstChild;
        while (kid) {
            if (kid.nodeType == 1) {
                var es = kid.getElementsByClassName(cls);
                if (es && es.length > 0) {
                    var e = es[0];
                    var t = getInnerText(e);
                    els.push([t, kid]);
                }
            }
            ls.removeChild(kid);
            kid = ls.firstChild;
        }
        els.sort();
        for (var i = 0; i < els.length; i++) {
            ls.appendChild(els[i][1]);
        }
    }
}

function loadUserNotes(docPath, majorVer, minorVer, buildVer) {
    try {
        docPath = docPath || window.docPath || window.location.pathname;
        majorVer = majorVer || window.majorVer || 9;
        minorVer = minorVer || window.minorVer || 5;
        buildVer = buildVer || window.buildVer || 0;
        
        var hostname;
        try {
            hostname = window.location.hostname
        } catch (e) {
            // If window.location.hostname fails, it's probably
            // because this is a user-created helpcard, so we
            // fake-loaded it as a string, so it doesn't have a
            // network location.
            //
            // In that case, we'll just give up on user-contributed
            // notes for now.
            
            return;
        }

	// If hostname is blank, then we are running the help pages
	// as static HTML pages without a server.  Therefore, we
	// skip loading user-contributed notes because there is no way
	// for us to figure out what the document's virtual help path
	// is based solely on the web page's file path.
	if (hostname == "")
	    return;

        if (hostname == "www.sidefx.com") {
            // This chunk of code needs to be updated if we ever
            // move the online Houdini documentation to a different root path.
            root_path_exp = /^\/docs\/(current|houdini...)\//i;

            docPath = docPath.replace(root_path_exp, "/");
            target = "/docs/user_contrib/view.php" +
                "?pageURL=" + docPath +
                "&docsMajorVer=" + majorVer +
                "&docsMinorVer=" + minorVer +
                "&docsBuildVer=" + buildVer;
        } else {
            target = "/usernotes" +
                "?path=" + docPath +
                "&major=" + majorVer +
                "&minor=" + minorVer +
                "&build=" + buildVer;
        }

        var request = new XMLHttpRequest();
        request.onerror = function() {
            var e = $('usernotescontent');
            e.innerHTML = "<p>Error getting user-contributed notes:"
                + request.statusText + "<br/>"
                + request.responseText + "</p>";
        }
        request.onreadystatechange = function() {
            // We'll get ready states of 0 through 4.  4 means it's done.
            if (request.readyState != 4) return;
    
            var e = $('usernotescontent');
            converter = new Showdown.converter()
            
            // An http status of 200 means everything was ok.
            if (request.status == 200) {
                e.innerHTML = request.responseText;
                var notes = e.getElementsByTagName("blockquote");
                var converter = new Showdown.converter()
                for (var i = 0; i < notes.length; i++) {
                    var note = notes[i];
                    note.innerHTML = converter.makeHtml(note.innerHTML);
                }
            } else {
                //
            }
        }

        request.open("GET", target, true);
        request.send(null);
        
    } catch (e) {
        alert("Error getting user-contributed notes: " + e);
    }
}

function loadVideos() {
    try {
        var e = $("videos");
        if (e) {
            var request = new XMLHttpRequest();
            request.onerror = function() {
                e.innerHTML = "<p>Error getting videos:"
                    + request.statusText + "<br/>"
                    + request.responseText + "</p>";
            }
            request.onreadystatechange = function() {
                if (request.readyState != 4) return;
                e.innerHTML = request.responseText;
                Effect.Appear(e);
            }
            request.open("GET", "/videos", true);
            request.send(null);
        }
    } catch (e) {
        alert("loadVideos: "+e);
    }
}




