
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) {
  var newText = "";
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();

  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i+1);
    if (i < 0) {
      newText += bodyText;
      bodyText = "";
    } else {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        // skip anything inside a <script> block
        if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }
  return newText;
}

function highlightSearchTerms(searchText, treatAsPhrase, destid, highlightStartTag, highlightEndTag) {
  if (treatAsPhrase) {
    searchArray = [searchText];
  } else {
    searchArray = searchText.split(" ");
  }

  if (!document.body || typeof(document.getElementById(destid).innerHTML) == "undefined") {
    return false;
  }

  var dest = document.getElementById(destid);
  var bodyText = dest.innerHTML;

  for (var i = 0; i < searchArray.length; i++) {
    bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
  }

  dest.innerHTML = bodyText;
  return true;
}

function getHighlightStyle() {
    var inlineSS = document.styleSheets[document.styleSheets.length-1];
    var inlineRules = inlineSS.cssRules ? inlineSS.cssRules: inlineSS.rules;
    return inlineRules[0];
}

function toggleHighlight() {
    var hls = getHighlightStyle();
    hls.style.backgroundColor = hls.style.backgroundColor ? '' : 'yellow';
}

function highlight(searchText,noresults) {
    var sText=searchText.replace(/\"+|\'+/g,'').replace(/^\ +|\ +$/g,'');
    if (!noresults) {
        var treatAsPhrase = false;
        var destid = 'searchresults';
        var highlightStartTag = '<span class="highlight">';
        var highlightEndTag = '</span>';
        getHighlightStyle().style.backgroundColor = 'yellow';
        highlightSearchTerms(sText, treatAsPhrase, destid, highlightStartTag, highlightEndTag)
    }
}

