/**
 * SearchHighlight plugin for jQuery
 * 
 * Thanks to Scott Yang <http://scott.yang.id.au/>
 * for the original idea and some code
 *    
 * @author Renato Formato <renatoformato@virgilio.it> 
 *  
 * @version 0.33
 *
 */

(function($){
  jQuery.fragmentSearch = function() {
    var escapeRegEx = /((?:\\{2})*)([[\]{}*?|])/g;
		var q = unescape(self.document.location.hash);
		q = q.replace(/[@#]/g,"");
		if(!q || q.length == 0) {return;}
		var regex = q.replace(escapeRegEx,"$1\\$2");
		regex = '\\b\\w*('+regex+')\\w*\\b';
		FragmentSearch.regex = new RegExp(regex, "gi");
    el = $("body");
		el.each(function(){
			FragmentSearch.hiliteTree(this);
			$(".FragmentSearchMatch").css("background-color","yellow");
			window.scroll(0,$(".FragmentSearchMatch").offset().top);
		});
	};

var FragmentSearch = {
	regex: [],
	hiliteTree : function(el) {
		for(var startIndex=0,endIndex=el.childNodes.length;startIndex<endIndex;startIndex++) {
			var item = el.childNodes[startIndex];
			if ( item.nodeType != 8 ) {
				if(item.nodeType==3) {
					var text = item.data;
					var newtext="",match,index=0;
					FragmentSearch.regex.lastIndex = 0;
					while(match = FragmentSearch.regex.exec(text)) {
						alert("test");
						newtext += text.substr(index,match.index-index)+'<span class="FragmentSearchMatch">'+text.substr(match.index,match[0].length)+"</span>";
						index = match.index+match[0].length;
					}
					if(newtext) {
						//add the last part of the text
						newtext += text.substring(index);
						var repl = $.merge([],$("<span>"+newtext+"</span>")[0].childNodes);
						endIndex += repl.length-1;
						startIndex += repl.length-1;
						$(item).before(repl).remove();
					}                
				} else {
					if(item.nodeType==1)
						FragmentSearch.hiliteTree(item);
				}	
			}
		}    
	}
};
})(jQuery)
