// Copyright 2011 Matrix Group International
// http://www.matrixgroup.net

//
// Add this to your header or CSS file:
//
//   <style>.solrhilite { background: #FFFF40; }</style>
//   <script type="text/javascript" src="highlightSolrSearch.js"></script>
//
// Add this to your footer:
//   <script type="text/javascript">matrixgroup.highlightSolrSearch.init(); matrixgroup.highlightSolrSearch.highlight();</script>

var matrixgroup = matrixgroup?matrixgroup:{loaded: true};
matrixgroup.highlightSolrSearch = new function(){
	// Object "Constructor"
	var me = this;
	var myScript = document.getElementsByTagName('script'); 
	myScript = myScript[myScript.length-1].getAttribute('src');
	var myPath = myScript.substring(0,myScript.lastIndexOf('/')) + '/';	
	
	// private vars	for various methods
	var QueryString;
	
	//  Public "Constructor"
	this.init = function (){
		QueryString.keys = new Array();
		QueryString.values = new Array();
		parseQueryString();
	}
	
	// Public methods - to access from within this namespace pre-pend "me." to function name as in me.XXXX()
	this.highlight = function(){
		if (!"".match)	// check if browser supports regexp match() function
			return;	
		//var x = document.body;
		var content = document.getElementById('zone1'); // look in Zone 1 Div for Carnegie ...
		if (! content) content = document.body;
		if (content){
			var contentHtml=findHiLites(content.innerHTML);
			if (contentHtml) content.innerHTML = contentHtml;
			if (QueryString("solr_jump") == 'true') me.scrollToHiLite();
		}
	}
	
	this.scrollToHiLite = function(){
		var d = locateFirstHiLite("solrhilite");
		if(d)
		{
				var hiLiteLocation = findPosY(d) - 30;
				if ( hiLiteLocation < 30 )  hiLiteLocation = 1;
				window.scrollTo(0,hiLiteLocation); 
		}
	}
	
		
	// Private methods
	function QueryString(key){
		var value = null;
		for (var i=0;i<QueryString.keys.length;i++)
		{
			if (QueryString.keys[i]==key)
			{
				value = QueryString.values[i];
				break;
			}
		}
		return value;
	}
	
	function parseQueryString(){
		var query = window.location.search.substring(1);
		var pairs = query.split("&");
	
		for (var i=0;i<pairs.length;i++)
		{
			var pos = pairs[i].indexOf('=');
			if (pos >= 0)
			{
				var argname = pairs[i].substring(0,pos);
				var value = pairs[i].substring(pos+1);
				QueryString.keys[QueryString.keys.length] = argname;
				QueryString.values[QueryString.values.length] = value;
			}
		}
	}
	
	function locateFirstHiLite(id){
		var elementArray = document.getElementsByName(id);
		if (elementArray) return(elementArray[0]);
		
		return null;
	}
	
	function findPosY(obj){
		var curtop = 0;
		if (obj.offsetParent)
		{
			while (obj.offsetParent)
			{
				curtop += obj.offsetTop
				obj = obj.offsetParent;
			}
		}
		else if (obj.y)
			curtop += obj.y;
		return curtop;
	}
	
	function findHiLites(text){
		var SearchAsSubstring = 0;
		var hl;
	
		hl = QueryString("solr_hilite");
		if (hl == "" || hl == null)
		{
			return null;
		}
		if (document.charset && document.charset.toLowerCase() == "utf-8" )
			hl = decodeURIComponent(hl);
		else
			hl = unescape(hl);
		hl = hl.toLowerCase();
					
		// create array of terms        
		var term = hl.split("+"); 
		// EGM 05/06/2011 - use the plit on + instead of below so you can hilight multiple terms not adjacent to each other
		//var re = /\"(.*?)\"|[^\\+\"]+/g;
		//var term = hl.match(re);    
	   
		// convert terms in regexp patterns
		for (var i=0;i<term.length;i++) // take each term in turn
		{       
			if(term[i] != "")
			{                   
				if (term[i].indexOf("\"") != -1)
				{
					// contains double quotes               
					term[i]=term[i].replace(/\"/g,"");
					term[i]=term[i].replace(/\+/g," "); 
				}
				else
				{
					term[i]=term[i].replace(/\+/g,"");  
				}                           
	
				if (term[i].indexOf("*") != -1 || term[i].indexOf("?") != -1)
				{
					// convert wildcard pattern to regexp
					term[i] = term[i].replace(/\\/g, " ");
					term[i] = term[i].replace(/\^/g, " ");
	
					//term[i] = term[i].replace(/\+/g, " "); // split on this so no point in looking
	
					term[i] = term[i].replace(/\#/g, " ");
					term[i] = term[i].replace(/\$/g, " ");
					term[i] = term[i].replace(/\./g, " ");
					
					// check if search term only contains only wildcards
					// if so, we will not attempt to highlight this term
					var wildcards = /\w/;
					if (wildcards.test(term[i]))
					{
						term[i] = term[i].replace(/\*/g, "[^\\s]*");
						term[i] = term[i].replace(/\?/g, "[^\\s]"); // insist upon one non whitespace
					}                
					else                
						term[i] = "";                
				}
				
				if (term[i] != "")
				{
					if (SearchAsSubstring == 0)
					{	                
						term[i] = "(>[\\s]*|>[^<]+[\\b\\W])("+term[i]+")(<|[\\b\\W][^>]*<)";
					}
					else
					{
						// if term leads with wildcard then allow it to match preceeding text in word
						var strWB="";
						if(term[i].substr(0,7)=="[^\\s]*") strWB="\\b";
						term[i] = "(>|>[^<]+)"+strWB+"("+term[i]+")([^>]*<)";
					}
				}	        
			}
		}
	
		text=text.replace(/&amp;/ig, '&');
		text=text.replace(/&nbsp;/ig, '');
	
		for (var i=0;i<term.length;i++) // take each term in turn
		{
			if(term[i] != "")
			{        	        	
				// we need a loop for the main search to catch all between ><
				// and we add  before each found to ignore those done etc
				// todo: develop reliable single pass regexp and dispose of loop
				var l = 0;
				re = new RegExp(term[i], "gi");
				var count = 0; // just incase
				text = ">" + text + "<"; // temporary tag marks
				do 
				{
					l=text.length;
                	text=text.replace(re, '$1<span class="solrhilite" name="solrhilite">$2</span>$3');
					count++;
				}
				//while(re.lastIndex>0 && count<100); lastIndex not set properly under netscape
				while(l!=text.length && count<100);
				text = text.substring(1, text.length-1); // remove temporary tags
			}
		}        
		text = text.replace(eval("//g"), '');        
		text = text.replace(eval("//g"), '&nbsp;');    
		   
		return(text);
	}
	
}
	





