//Javascript to highlight search terms on page
// Created Apr 6, 2011 Fred Gaumont

function highlightSearch() {   

	// Get search string   
	var searchString = getSearchString();     
	var currPage = window.location.href;

	if (searchString != "") {

		// Get the starting node, parent to all nodes you want to search     
		//  (note: can only get element by id, not class, so created a new dummy wrapper to use for searching)
		var textContainerNode = document.getElementById("ContentBodyWrapper");

	       	// Split search terms on '|' and iterate over resulting array
		var searchTerms = searchString.split('|');
		for (var i in searchTerms)  {
	        	// The regex is the secret, it prevents text within tag declarations to be affected
	        	var regex = new RegExp(">([^<]*)?("+searchTerms[i]+")([^>]*)?<","ig");
		        highlightTextNodes(textContainerNode, regex, i);
		}

		// Count the anchors that were created by the matching process
		var searchTagsFound = 0;

		for (i = 0; i < document.anchors.length; i++) {
			if (document.anchors[i].name == 'SearchResult') {
				searchTagsFound = searchTagsFound + 1;
			}
		}

		// Create floating div showing the number of search results found (use document.anchors.length for count)
		if (searchTagsFound > 0) {

			var searchTermDiv = document.createElement("div");
		        var searchMsg = '<span class="HighlightBlue">Number of matches found: [' + searchTagsFound + ']</span>'
			if (searchTagsFound > 1) {
				searchMsg = searchMsg + '<br> Scroll down if not all results are visible ';
			}
			searchTermDiv.className = 'SearchPopup';
			searchTermDiv.innerHTML = searchMsg;

			// Insert as a new child at the end of the searched node    
			textContainerNode.appendChild(searchTermDiv);  
	
			//Jump to first anchor (unless there already is a specified bookmark)

			var tagStart = window.location.hash.substring(1,4);
			if (tagStart != 'FAQ')  {
				window.location.replace(currPage + '#SearchResult');
			}
		}
	}
}	


// Pull the search string out of the URL 
function getSearchString() {   
	// Return sanitized search string if it exists   	
	var rawSearchString = window.location.search.replace(/[a-zA-Z0-9\?\&\=\%\#\_]+SearchTerm\=(\w+)(\&.*)?/,"$1");   
	// Replace '+' with '|' for regex   
	// Also replace '%20' if your cms/blog uses this instead (credit to erlando for adding this)   	

	//alert ("SearchString =" + rawSearchString)
	rawSearchString.replace(/\%20|\+/g," "); 
	rawSearchString.replace(/\%7c|\+/g,"|"); 
	return rawSearchString; 

}  


// Format the matching terms - use a special span class and add anchor to each match
function highlightTextNodes(element, regex, termid) {   
	var tempinnerHTML = element.innerHTML;   
	// Do regex replace   
	element.innerHTML = tempinnerHTML.replace(regex,'>$1<a name="SearchResult"><span class="SearchTerm">$2</span></a>$3<'); 
}   




