﻿// Script to search and highlight the contents provided in DIV elements.
var originalText = "";
var contents = null;

/*
 * This is the function that actually highlights a text string by
 * adding HTML tags before and after all occurrences of the search
 * term. You can pass your own tags if you'd like, or if the
 * highlightStartTag or highlightEndTag parameters are omitted or
 * are empty strings then the default <font> tags will be used.
 */
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) 
{
  // the highlightStartTag and highlightEndTag parameters are optional
  if ((!highlightStartTag) || (!highlightEndTag)) {
    highlightStartTag = "<font style='background-color:yellow;'>";
    highlightEndTag = "</font>";
  }
  
  // find all occurences of the search term in the given text,
  // and add some "highlight" tags to them (we're not using a
  // regular expression search, because we want to filter out
  // matches that occur within HTML tags and script blocks, so
  // we have to do a little extra validation)
  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;
}


/*
 * 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.
 */
// This for table content.
function highlightSearchTermsForDiv(SearchText, divElementId , 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
  
  var divElement = document.getElementById(divElementId);
  
     
  if (treatAsPhrase) {
    searchArray = [SearchText];
  } else {
    searchArray = SearchText.split(" ");
  }
 
  if (!divElement || typeof(divElement.innerHTML) == "undefined") {
    if (warnOnFailure) {
      alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
    }
    return false;
  }
  
  var bodyText = divElement.innerHTML;
  
  for (var i = 0; i < searchArray.length; i++) {
    bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
  }

  divElement.innerHTML = bodyText;
  
  return true;
}
// Trims all spaces to the left of a specific string
function LTrim(str)
{
        var whitespace = new String(" \t\n\r ");
        // last space character is not a space, but alt+0160,
        // another invisible char.
        var s = new String(str);
        if (whitespace.indexOf(s.charAt(0)) != -1) {
            // We have a string with leading blank(s)...
            var j=0, i = s.length;
            // Iterate from the far left of string until we
            // don't have any more whitespace...
            while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
                j++;
            // Get the substring from the first non-whitespace
            // character to the end of the string...
            s = s.substring(j, i);
        }
        return s;
}
// Trims all spaces to the right of a specific string
function RTrim(str)
{
        // We don't want to trip JUST spaces, but also tabs,
        // line feeds, etc.  Add anything else you want to
        // "trim" here in whitespace
        var whitespace = new String(" \t\n\r ");
        // last space character is not a space, but alt+0160,
        // another invisible char.
        var s = new String(str);
        if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
            // We have a string with trailing blank(s)...
            var i = s.length - 1;       // Get length of string
            // Iterate from the far right of string until we
            // don't have any more whitespace...
            while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
                i--;
            // Get the substring from the front of the string to
            // where the last non-whitespace character is...
            s = s.substring(0, i+1);
        }
        return s;
}
                                                                                                                        
// Trims all spaces to the left and right of a specific string by calling RTim
// and LTrim
function Trim(str)
{
        return RTrim(LTrim(str));
}

/* Method to search and highlight the searched contents. It will traverse through
 * all DIV elements that contains matter to be searched. Inside this function it
 * it repeatedly call the function to search each contents provided in DIV elemetsnts.
 */
function searchFunction()
{
    var textToSearch = "";      // Hold the text to search.
    var searchAsPhrase = true   // Hold the option for search as phrase.
    
    // Refresh the content to wipe out the previous results.
    refreshFunction();
    // First checking of the existance of the content. 
    if(ItContains() == false)
    {
        alert("No results found. Clear your search and try again.");
        return;    
    }

    // Get the text to search.
    textToSearch = Trim(document.getElementById("SearchText").value);
    // Set the value after triming.
    document.getElementById("SearchText").value = textToSearch;

    // Check for the input.
    if(textToSearch != "")
    {
        //highlightSearchTermsForDiv(document.getElementById("SearchText").value);
        for(content in contents)
        {
            // Search and highlight the content.
            highlightSearchTermsForDiv(textToSearch, content, searchAsPhrase);
        }
    }
    else
    {
        alert("Please enter content to search.");
    }
    document.getElementById("SearchText").focus();
}
function refreshFunction()
{
    for(content in contents)
    {
        document.getElementById(content).innerHTML = contents[content];
    }
    document.getElementById("SearchText").focus();
}
function clearSearch()
{
    document.getElementById("SearchText").value = "";
    refreshFunction();
}
// Function to preserve the original texts of DIVs.
// This is used to replace the orignal content when the we click the clear the search button.
function PreserveOrginalText()
{
    // Check for the content, it has array like struture which contains "innerHTML"s of divs that
    // that are to be searched for requested content. It will will be null when the page gets loaded.
    if(contents == null)
    {
        contents = new Object();
        contents["searchContentDiv"] = document.getElementById("searchContentDiv").innerHTML;
        document.getElementById("SearchText").focus();
        //contents["Div2"] = document.getElementById("Div2").innerHTML;
        //contents["Div3"] = document.getElementById("Div3").innerHTML;
    }
    // To disable the Login link if the window is popup. 
    if(typeof(window.opener)!="undefined") 
    {
        document.getElementById('loginTd').style.display='none';
    }
}
function ItContains()
{
    var textToSearch = "";      // Hold the text to search.

    // Get the text to search.
    textToSearch = Trim(document.getElementById("SearchText").value);
    
    if(contents != null)
    {
        for(content in contents)
        {
            if(contents[content].toLowerCase().indexOf(textToSearch.toLowerCase()) != -1)
            {
                return true;
            }
        }   
    }
    
    return false;
}
