function
check_enable_breadcrumb() 
{
    // Shows bottom breadcrumb bar if the page is long enough.
    var $bar = $('#breadcrumb-bottom')
    // Don't use $(window).height().  On Opera it doesn't return the right value.
    // http://dev.jquery.com/ticket/3046
    if ($(document).height() > window.innerHeight)
        $bar.show();
    else
        $bar.hide();
}


function
traverse_node(node, kw, enable)
{
    // TODO: jqueryify
    if (typeof(node.childNodes) == "undefined" || !node.childNodes)
        return;

    for (var i = 0; i < node.childNodes.length; i++) {
        var child = node.childNodes[i];
        if ((child.className && child.className.search(/\bp\b|\bunderlined-links\b|\bminitext\b/) != -1) ||
            child.id == "summary")
            enable = true;
        if (child.nodeName == "#text" && $.trim(child.nodeValue) != "" && enable) {
            var text = child.nodeValue;
            var found = false;
            for (var j = 0; j < kw.length; j++) {
                var re = new RegExp("\\b(" + kw[j] + ")\\b", "ig");
                if (text.search(re) != -1) {
                    text = text.replace(re, "<span class='keyword'>$1</span>");
                    found = true;
                }
            }
            if (!found)
                continue;

            var span = document.createElement("span");
            span.innerHTML = text;
            child.parentNode.replaceChild(span, child);
        }
        traverse_node(child, kw, enable);
    }
}

function
parse_args(line)
{
    // Parse the string into args, honoring quoted args.  This code is
    // ugly and C'ish, whereas a regexp would be even uglier and illegible
    // and probably not correct anyway.
    args = [];
    chars = line.split('');
    for (var s=0, e=0, q=false; e < line.length; e++) {
        if (chars[e] == '"' && (e == 0 || chars[e-1] != '\\')) {
            if (q)
                args.push($.trim(line.substring(s, e).replace(/\\"/g, '"')));
            q = !q;
            s = e + 1;
        } 
        else if ((chars[e] == ' ' && !q) || e == line.length-1) {
            if (e > s)
                args.push($.trim(line.substring(s, e+1)));
            s = e + 1;
        }
    }
    return args;
}

function 
highlight_query_keywords()
{
    var keywords = null;
    if (document.cookie) {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = $.trim(cookies[i]);
            if (cookie.indexOf("q=") != 0)
                continue;
            keywords = cookie.substring(2);
            // Delete the query keyword cookie -- only the first page after
            // search should have keywords highlighted.
            if (document.location.href.indexOf("/search/") == -1)
                document.cookie = "q=;path=" + SITE_TOPURL;
            break;
        }
    }
    if (document.referrer) {
        regexps = [
            // Google
            new RegExp("^https?:\/\/[^/]+google\.[^.]+\/search.*[&?]q=([^&]+)", "i")
            // Add more :)
        ];
        for (var i = 0; i < regexps.length; i++) {
            results = regexps[i].exec(document.referrer);
            if (results) {
                keywords = results[1];
                break;
            }
        }
    }
    if (!keywords)
        return;

    keywords = unescape(keywords.replace(/\+/g, " "));
    if (keywords[0] != "") {
        keywords = parse_args(keywords);
        traverse_node(get_id("content"), keywords, false);
    }
}

function
check_keywords_cookie()
{
    /* If we're on the search page, add the cookie that tracks search terms
     * for highlighting.  This function gets called when the pageshow event
     * fires (Firefox 1.5 only) or for the onload event.  Firefox 1.5 with
     * bfcache enabled won't fire the onload event when the user goes
     * back to the search list, but it does fire pageshow.  IE will fire
     * onload in any case (cached or not).  
     *
     * This allows the user to do a search, click a search result, click the
     * back button, click a different search result, and the search terms will
     * still get highlighted in the new result page.
     *
     * Like IE, Firefox 1.0 and Konqueror fire onload when clicking back, so 
     * this feature will work with them.  Unfortunately Opera does not fire 
     * onload when the page is in its bfcache, and it does not (hopefully yet)
     * support pageshow.  So this behavior is broken with Opera.
     */

    if (document.location.href.indexOf("/search") != -1) {
        if (typeof(search_terms) != "undefined")
            document.cookie = "q=" + search_terms + ";path=" + SITE_TOPURL;
    }
}

/* At this point, though, images have not yet loaded.  Call
 * check_enable_breadcrumb() again after page is fully loaded in case loaded
 * images will have caused scrollbar to appear.
 */

$(window)
    .bind('pageshow', function() {
        check_keywords_cookie();
    })
    .resize(function() {
        check_enable_breadcrumb();
    });


$(document)
    .load(function() {
        check_enable_breadcrumb();
    })

    .ready(function() {
        $('#submitbutton').click(function() {
            $('#searchform').submit();
        });

        check_keywords_cookie();
        highlight_query_keywords();
        check_enable_breadcrumb();

        if ($.browser.msie && $.browser.version < 7) {
            // TODO: jqueryify
            for (var i = 0; i < document.images.length; i++) {
                var img = document.images[i];
                if (img.className.search(/alpha-png/) != -1 && !img.style.filter)
                    fix_png(img);
            }
        }
    });

$('#topbar-title').click(function() {
    document.location = SITE_TOPURL;
});

