// JavaScript Document

/*
 * This function checks a given character to see if it is a 
 * word delimiter. I am defining word delimiters as being 
 * either a space or any punctuation. This is to enable one
 * to limit highlighting to whole words or words using a 
 * trailing wildcard
 */
function wordDelimiterCheck(searchChar)
{
  var isWordDelimiter = false;
  var myRexExp = /\W/;
  if (searchChar.search(myRexExp) != -1) {
    isWordDelimiter = true;
    /*alert(searchChar + 'SearchChar is a WordDelimiter.');*/
  }
    else 
    {
    	isWordDelimiter = false;
    	/*alert(searchChar + 'SearchChar is NOT a WordDelimiter.');*/
    }
  return isWordDelimiter;
}

/*
 * 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, stBeginWord, stEndWord, highlightStartTag, highlightEndTag) 
{
  if (searchTerm == '')
  {
  	return bodyText;
  }
  else
  {
  // the stBeginWord, stEndWord, highlightStartTag and highlightEndTag parameters are optional
    if (!stBeginWord) {stBeginWord = false;}
    if (!stEndWord) {stEndWord = false;}
	if ((!highlightStartTag) || (!highlightEndTag)) 
	{
	  highlightStartTag = '<span class="searchhighlight">';
	  highlightEndTag = '</span>';
	}
	  
	  // 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();
	  var bodyTextLen = bodyText.length;
	  var searchTermLen = searchTerm.length;
	  
	  while (bodyText.length> 0) {
	  	/*bodyTextLen = bodyText.length;*/
	    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)) {
	          //skip anything inside an &...; html symbol block	
	          if (lcBodyText.lastIndexOf(";", i) >= lcBodyText.lastIndexOf("&", i)) {
	          	//Check to see that character before and after search term is a word delimiter
	    	/*alert('i is ' + i);*/
	    	/*alert('bodyTextLength is ' + bodyTextLen);
	    	alert('i + searchTermLen is ' + (i + searchTermLen));*/
	          	if (((stBeginWord && !stEndWord) && ((i==0) || (wordDelimiterCheck(bodyText.substr(i-1, 1)) == true))) ||
	          		((!stBeginWord && stEndWord) && ((bodyTextLen == i + searchTermLen) || (wordDelimiterCheck(bodyText.substr(i + searchTermLen, 1)) == true))) ||
					(!stBeginWord && !stEndWord) ||	          		
	          		((stBeginWord && stEndWord) && 
	          		 ((i==0) || (wordDelimiterCheck(bodyText.substr(i-1, 1)) == true)) && 
	          		 ((bodyTextLen == i + searchTermLen) || (wordDelimiterCheck(bodyText.substr(i + searchTermLen, 1)) == true)))
	          	   )
				{
				  /*alert('Search Term Beginning.');*/
		          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTermLen) + highlightEndTag;
		          bodyText = bodyText.substr(i + searchTermLen);
		          lcBodyText = bodyText.toLowerCase();
		          i = -1;
		          bodyTextLen = bodyText.length;
	          	}
	          }    
	        }
	      }
	    }
	  }
	  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.
 */
function highlightTerms(searchTermArray, sectionToHighlight, warnOnFailure, highlightStartTag, highlightEndTag)
{
  
  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;
  }
  if (searchTermArray.length == 0)
  {
  	alert('No terms were passed to highlightTerms()!');
  	return false;
  }
  else
  {
	  if ((!highlightStartTag) || (!highlightEndTag)) 
	  {
		highlightStartTag = '<span class="searchhighlight">';
		highlightEndTag = '</span>';
	  }
	  if (!sectionToHighlight) {sectionToHighlight = 'body';}
	  if (!warnOnFailure) {warnOnFailure = false;}
	
	  if (sectionToHighlight == 'body')
	  {
	  	var bodyText = document.body.innerHTML;
	  }
	  else
	  {
	  	var bodyText = document.getElementById(sectionToHighlight).innerHTML;
	  }
	  
	  for (var i = 0; i < searchTermArray.length; i++) {
	  	if (searchTermArray[i].substr(0,1) == '*') { var beginningwildcard = true;} else { var beginningwildcard = false;}
	  	if (searchTermArray[i].substr(searchTermArray[i].length -1 ,1) == '*') { var trailingwildcard = true;} else { var trailingwildcard = false;}
	  	if (trailingwildcard && beginningwildcard)
	  	{
	  		var st = searchTermArray[i].substr(1); // trim off wildcards
	  		st = st.substr(0,st.length-1);
	  		bodyText = doHighlight(bodyText, st, false, false, highlightStartTag, highlightEndTag);
	  	}
	  	else if (trailingwildcard)
	  	{
	  		var st = searchTermArray[i].substr(0,searchTermArray[i].length-1); // trim off wildcard
	  		bodyText = doHighlight(bodyText, st, true, false, highlightStartTag, highlightEndTag);
	  	}
	  	else if (beginningwildcard)
	  	{
	  		var st = searchTermArray[i].substr(1); // trim off wildcard
	  		bodyText = doHighlight(bodyText, st, false, true, highlightStartTag, highlightEndTag);
	  	}
	  	else
	  	{
	  		bodyText = doHighlight(bodyText, searchTermArray[i], true, true, highlightStartTag, highlightEndTag);
	  	}
	  }
	  if (sectionToHighlight == 'body')
	  {
	  	document.body.innerHTML = bodyText;
	  }
	  else
	  {
	  	document.getElementById(sectionToHighlight).innerHTML = bodyText;
	  }
  }
  return true;
}

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 = "<font style='color:" + textColor + "; background-color:" + bgColor + ";'>";
    highlightEndTag = "</font>";
  }
  
  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 highlightTerms(Array(searchText), 'body', true, highlightStartTag, highlightEndTag);
}

function toggleHighlighting(section, obj)
{
	/*alert('section = ' + section + ' and obj = ' + obj.id);*/
	if (obj.id == 'nohigh')
	{
		var spanList = document.getElementById(section).getElementsByTagName("span");
   		for (i = 0; i < spanList.length; i++) {
      		if (spanList[i].className == "searchhighlight")
      		{
      			spanList[i].className = "nohighlight";
      		}
   		}
	}
	else if (obj.id == 'addhigh')
	{
		var spanList = document.getElementById(section).getElementsByTagName("span");
   		for (i = 0; i < spanList.length; i++) {
      		if (spanList[i].className == "nohighlight")
      		{
      			spanList[i].className = "searchhighlight";
      		}
   		}
	}
   var inputList = document.getElementById(section).getElementsByTagName("input");
   for (i = 0; i < inputList.length; i++) {
      if (inputList[i].id == "nohigh")
      {
      	inputList[i].id = "addhigh";
      	inputList[i].value = "Add Highlighting";
      	inputList[i].src = "images/Restore_Highlighting.png"
      	/*alert("nohigh button found");*/
      }
      else if (inputList[i].id == "addhigh")
      {
      	inputList[i].id = "nohigh";
      	inputList[i].value = "Remove Highlighting";
      	inputList[i].src = "images/Remove_Highlighting.png"
      	/*alert("addhigh button found");*/
      }
   }
}
