var Highlighter = new Class({
							
	options: 
	{
		element: document.body,
		highlightStartTag: '<span style="color:#FFFFFF; background-color:#A11515;">',
		highlightEndTag: '</span>',
		warnOnFailure: false
	},

	initialize: function(options)
	{
		this.setOptions(options);
		
		if(!$defined(this.options.element) || !$defined(this.options.element.innerHTML))
		{
			if(this.options.warnOnFailure)
			{
				alert('Sorry, for some reason the text of this page is unavailable. Searching will not work.');
			}
			return false;
		}
		
		this.html = this.options.element.innerHTML;
	},
	
	doHighlight: function(searchTerm) 
	{
		// 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 newHtml = '';
		var i = -1;
		var lcSearchTerm = searchTerm.toLowerCase();
		var lcHtml = this.html.toLowerCase();
		
		while(lcHtml.length > 0)
		{
			i = lcHtml.indexOf(lcSearchTerm, i + 1);
			if(i < 0) 
			{
				newHtml += this.html;
				this.html = '';
				break;
			} 
			else 
			{
				// skip anything inside an HTML tag
				if(this.html.lastIndexOf('>', i) >= this.html.lastIndexOf('<', i)) 
				{
					// skip anything inside a <script> block
					if(lcHtml.lastIndexOf("/script>", i) >= lcHtml.lastIndexOf("<script", i))
					{	
						newHtml += this.html.substring(0, i) + this.options.highlightStartTag + this.html.substr(i, searchTerm.length) + this.options.highlightEndTag;
						this.html = this.html.substr(i + searchTerm.length);
						lcHtml = this.html.toLowerCase();
						i = -1;
					}
				}
			}
		}	
		return newHtml;
	},
	
	highlightSearchTerms: function(searchText)
	{
		var withQuotation = searchText.match(/\"([^\"]*)\"/g) || [];
		for(var i = 0; i < withQuotation.length; i++)
		{
			withQuotation[i] = withQuotation[i].substring(1, withQuotation[i].length - 1);
		}
		searchText = searchText.replace(/\"([^\"]*)\"/g, '');
		var withoutQuotation = searchText.split(' ');
		
		searchPhrases = withQuotation.merge(withoutQuotation);
		
		for(var i = 0; i < searchPhrases.length; i++) 
		{
			if(searchPhrases[i].trim() == '') continue;
			this.html = this.doHighlight(searchPhrases[i]);
		}
		this.options.element.innerHTML = this.html;
	}
							
});
Highlighter.implement(new Options);