//This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/2.0/ or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.

//The query string has the following format (each entry is encoded so that it can be transferred safely via URL) :
//"?" numberOfPages "," pageNumber "," searchPhrase "," numberOfMatches ","  ("y" | "n") ("y" | "n") 
// ((matchURI) ":" (title)? ":" (anchor)? ":" (documentInfo)? ":" (matchContext)? ",")*

//Frame in which to open search results.
var targetFrame = "_top";

//Text used in search results messages:
var noData_txt = "No search data were provided";
var yourSearch_txt = "Your search for";
var exactMatches_txt = "with exact matches only";
var excludingHTML_txt = "excluding HTML";
var yielded_txt = "yielded";
var closestAnchor_txt = "Closest anchor";
var docInfo_txt = "Document Info";
var context_txt = "Match Context";
var match_txt = "match";
var matches_txt = "matches";
var noMatches_txt = "No matches";

//Which elements should be displayed along with the results?
var displayAnchor = true;
var displayDocInfo = true;
var displayContext = true;
//If you do not want to display the context (you set displayContext to false),
//you should also set the applet parameters leadingcontextlength and 
//trailingcontextlength to zero to conserve memory and transmission space.

//Set the following variable to true if you want
//only the title to be displayed if it is available.
var preferTitleOnly = false;

//Set the following variable to true if you do not want the closest anchor
//to be displayed separately from the link to the matching document.
var anchorTheLink = false;

function writeParseError(message) {
    document.writeln("<em>Error with the search data: " + message + "</em>");
}

function formatFileSize(fileSize) {
    if (fileSize > 1024) {
        return Math.floor(fileSize / 1024) + "k";
    }
    else {
        return fileSize + "b";
    }
}


function formatDate(msSince1970) {
    return new Date(msSince1970).toLocaleDateString();
}

function writeResults() {
    var data = location.search;
    if (! data) {
        document.writeln("<em>" + noData_txt + "</em>");
        return;
    }
    else {
        data = data.substring(1);
    }

    var resultsHtml = "";
    var numberOfPagesEnd = data.indexOf(',');
    if (numberOfPagesEnd == -1) {
        writeParseError("Missing total number of pages");
        return;
    }
    var numberOfPages = data.substring(0, numberOfPagesEnd);
    var pageNumberEnd = data.indexOf(',', numberOfPagesEnd + 1);
    if (pageNumberEnd == -1) {
        writeParseError("Missing page number");
        return;
    }
    var pageNumber = data.substring(numberOfPagesEnd + 1, pageNumberEnd);
    var searchPhraseEnd = data.indexOf(',', pageNumberEnd + 1);
    if (searchPhraseEnd == -1) {
        writeParseError("Missing search phrase");
        return;
    }
    var searchPhrase = unescape(data.substring(pageNumberEnd + 1, searchPhraseEnd));
    var numberOfMatchesEnd = data.indexOf(',', searchPhraseEnd + 1);
    if (numberOfMatchesEnd == -1) {
        writeParseError("Missing total number of matches");
        return;
    }
    var numberOfMatches = data.substring(searchPhraseEnd + 1, numberOfMatchesEnd);


    resultsHtml += "<h1>Page " + pageNumber + " of " + numberOfPages + "</h1>";

    resultsHtml += "<dl><dt>" + yourSearch_txt + " <b>" + searchPhrase + "</b> ";
    
    if (data.charAt(numberOfMatchesEnd + 1) == 'y') { 
        resultsHtml += " (" + exactMatches_txt + ") ";
    }
    if (data.charAt(numberOfMatchesEnd + 2) == 'y') { 
        resultsHtml += " (" + excludingHTML_txt + ") "; 
    }
    resultsHtml += yielded_txt + " " + numberOfMatches
                    + " " + ((numberOfMatches == 1) ? match_txt : matches_txt) + "<p>";
    data = data.substring(numberOfMatchesEnd + 3);
    var resultEnd = -1;
    var previousResultEnd = -1;
    while ((resultEnd = data.indexOf(',', previousResultEnd + 1)) != -1) {
        var currData = data.substring(previousResultEnd + 1, resultEnd);
        previousResultEnd = resultEnd;
        
        var colonIndex = currData.indexOf(":");
        if (colonIndex != -1) {
        
            //Get the URL
            var myUrl = unescape(currData.substring(0, colonIndex));
      
            //Get the page's title
            var previousIndex = colonIndex;
            colonIndex = currData.indexOf(":", previousIndex + 1);
            
            var myTitle = unescape(currData.substring(previousIndex + 1, colonIndex));
            
            //Get the anchor
            previousIndex = colonIndex;
            colonIndex = currData.indexOf(":", previousIndex + 1);
            var anchor = unescape(currData.substring(previousIndex + 1, colonIndex));
            
            if (anchorTheLink && anchor.length > 0) {
                myUrl += "#" + anchor;
            }
            
            resultsHtml += "<dd><a href=\""+myUrl+"\" target=\"" + 
                            targetFrame + "\"><b>" + myTitle + "</b> ";
            if (!preferTitleOnly || myTitle.length == 0) {
                resultsHtml += "<b>(" + myUrl + ")</b>";
            }
                
            resultsHtml += "</a>";

            if (anchor.length > 0 && displayAnchor && !anchorTheLink) 
                resultsHtml += " <a href=\""+myUrl+"#"+anchor+"\" target=\"" + targetFrame + "\">[" + closestAnchor_txt +"]</a>";
            resultsHtml += "<br>";
      
            //Get document info
            var info = "";
            previousIndex = colonIndex;
            colonIndex = currData.indexOf(":", previousIndex + 1);
            var fileSize = currData.substring(previousIndex + 1, colonIndex);
            if (fileSize.length > 0) {
                info = formatFileSize(parseInt(fileSize));
            }
            
            
            previousIndex = colonIndex;
            colonIndex = currData.indexOf(':', previousIndex + 1);
            var lastModified = currData.substring(previousIndex + 1, colonIndex);
            if (lastModified.length > 0) {
                if (info.length > 0) {
                    info += " / ";
                }
                info += formatDate(parseInt(lastModified));
            }
            
            resultsHtml += "<small>";       
            if (info.length > 0 && displayDocInfo) {
                resultsHtml += "<b>" + docInfo_txt + "</b>: " + info + "&nbsp;&nbsp;&nbsp;&nbsp;";
            } 

            //Get the match context
            previousIndex = colonIndex;
            var context = unescape(currData.substring(previousIndex + 1, currData.length));
            if (context.length > 0 && displayContext) {
                resultsHtml += "<b>" + context_txt + "</b>: \"" + context + "\"";
            }
            resultsHtml += "</small>";
            resultsHtml += "<p>";
        }
    }
    resultsHtml += "</dl>";
    document.writeln(resultsHtml);
}

writeResults();