/*
 * Notice of code origin and change history
 * ----------------------------------------
 * This file appears to be based on code published in 2003 at
 * http://www.nsftools.com/misc/SearchAndHighlight.htm
 *
 * Minor changes in January 2009 or earlier by unidentified coder
 *
 * Major changes in April 2009 by Hallvarsson & Halvarsson
 *   -- Function doHighlight replaced by doHighlightElement, which
 *      works on DOM tree text nodes instead of innerHTML and thus does
 *      not destroy events added to HTML elements before highlighting
 *   -- Function highlightSearchTerms changed to use doHighlightElement
 *   -- Function highlightGoogleSearchTerms changed to suppress
 *      highlighting while on the search page itself
 */

function doHighlightElement(startElement, searchTerm, highlightStartTag, highlightEndTag) 
{
  if ( startElement == null || (startElement.nodeName != null && startElement.nodeName.match(/^script$/i)) ) {
    return;
  }
  var a, e, f, i, n;
  for (i=0; i<startElement.childNodes.length; i++) {
    n = startElement.childNodes[i];
    if ( n.nodeName.match(/^#text$/i) ) {
      if ( (a = searchTerm.exec(n.nodeValue)) != null && a.length > 3 ) {
        // the highlightStartTag and highlightEndTag parameters are optional
        if ((!highlightStartTag) || (!highlightEndTag)) {
          highlightStartTag = "<span class='searchHighlight'>";
          highlightEndTag = "</span>";
        }
        e = document.createTextNode(a[1]);
        f = document.createElement("DIV");
        f.innerHTML = highlightStartTag + a[2] + highlightEndTag;
        n.nodeValue = a[3];
        startElement.insertBefore(e, n);
        startElement.insertBefore(f.firstChild, n);
        i++;
      }
    } else {
      doHighlightElement(n, searchTerm, highlightStartTag, highlightEndTag);
    }
  }
}


/*
 * This is sort of a wrapper function to the doHighlight function.
 * It takes the searchText that you pass, optionally splits it into
 * separate words, and transforms the text on the current web page.
 * Only the "searchText" parameter is required; all other parameters
 * are optional and can be omitted.
 */
function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)
{
  // if the treatAsPhrase parameter is true, then we should search for 
  // the entire phrase that was entered; otherwise, we will split the
  // search string so that each word is searched for and highlighted
  // individually
  if (treatAsPhrase) {
    searchArray = [searchText];
  } else {
    searchArray = searchText.split("#");
	if(searchArray[searchArray.length-1] == "" || searchArray[searchArray.length-1] == " "){
		searchArray.pop();//remove last empty item
	}
  }
  
  if (!document.body || typeof(document.body.innerHTML) == "undefined") {
    if (warnOnFailure) {
      alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
    }
    return false;
  }
  
  // Changes in April 2009 by Hallvarsson & Halvarsson
  var e = document.getElementById("content");
  if ( e != null ) {
    for (var i = 0; i < searchArray.length; i++) {
      doHighlightElement(e, new RegExp("^(.*?)(" + searchArray[i].replace(/([.*+?(|){}\[\]^$\\])/g, "\\$1") + ")(.*)$", "i"), highlightStartTag, highlightEndTag);
    }
  }

  return true;
}


/*
 * This displays a dialog box that allows a user to enter their own
 * search terms to highlight on the page, and then passes the search
 * text or phrase to the highlightSearchTerms function. All parameters
 * are optional.
 */
function searchPrompt(defaultText, treatAsPhrase, textColor, bgColor)
{
  // This function prompts the user for any words that should
  // be highlighted on this web page
  if (!defaultText) {
    defaultText = "";
  }
  
  // we can optionally use our own highlight tag values
  if ((!textColor) || (!bgColor)) {
    highlightStartTag = "";
    highlightEndTag = "";
  } else {
    highlightStartTag = "<span style='color:" + textColor + "; background-color:" + bgColor + ";'>";
    highlightEndTag = "</span>";
  }
  
  if (treatAsPhrase) {
    promptText = "Please enter the phrase you'd like to search for:";
  } else {
    promptText = "Please enter the words you'd like to search for, separated by spaces:";
  }
  
  searchText = prompt(promptText, defaultText);

  if (!searchText)  {
    alert("No search terms were entered. Exiting function.");
    return false;
  }
  
  return highlightSearchTerms(searchText, treatAsPhrase, true, highlightStartTag, highlightEndTag);
}


/*
 * This function takes a referer/referrer string and parses it
 * to determine if it contains any search terms. If it does, the
 * search terms are passed to the highlightSearchTerms function
 * so they can be highlighted on the current page.
 */
function highlightGoogleSearchTerms(referrer)
{
  // This function has only been very lightly tested against
  // typical Google search URLs. If you wanted the Google search
  // terms to be automatically highlighted on a page, you could
  // call the function in the onload event of your <body> tag, 
  // like this:
  //   <body onload='highlightGoogleSearchTerms(document.referrer);'>
  
  //var referrer = document.referrer;
  if (!referrer) {
    return false;
  }
  
  var queryPrefix = "q=";
  var startPos = referrer.toLowerCase().indexOf(queryPrefix);
  if ((startPos < 0) || (startPos + queryPrefix.length == referrer.length)) {
    return false;
  }
  
  // Changes in April 2009 by Hallvarsson & Halvarsson
  if ( document.URL.match(new RegExp("^[^#]*[?&]" + queryPrefix)) ) {
    return false;
  }
  
  var endPos = referrer.indexOf("&", startPos);
  if (endPos < 0) {
    endPos = referrer.length;
  }
  
  var queryString = referrer.substring(startPos + queryPrefix.length, endPos);
  // fix the space characters
  //queryString = queryString.replace(/^\s+/,'');
  //queryString = queryString.replace(/\s+$/,'');
  queryString = queryString.replace(/%20/gi, "#");
  queryString = queryString.replace(/\+/gi, "#");
  // remove the quotes (if you're really creative, you could search for the
  // terms within the quotes as phrases, and everything else as single terms)
  queryString = queryString.replace(/%22/gi, "");
  queryString = queryString.replace(/\"/gi, "");
  
  return highlightSearchTerms(queryString, false);
}


/*
 * This function is just an easy way to test the highlightGoogleSearchTerms
 * function.
 */
function testHighlightGoogleSearchTerms()
{
  var referrerString = "" + document.referrer;
  //referrerString = prompt("Test the following referrer string:", referrerString);
  return highlightGoogleSearchTerms(referrerString);
}