/*
 * jQuery Highlight Regex Plugin
 *
 * Based on highlight v3 by Johann Burkard
 * http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
 *
 * (c) 2009 Jacob Rothstein
 * MIT license
 */
var foundWordOnce = false;
var oldWord = "xxxxxx";
var currWord = "";
var tmpCtr = 0;
(function($){
  $.fn.highlightRegex = function(regex) {
	 
	 //alert("jere");
    if(regex == undefined || regex.source == '') {
      $(this).find('span.highlight').each(function(){
        $(this).replaceWith($(this).text());
        $(this).parent().each(function(){
          node = $(this).get(0);
          if(node.normalize) node.normalize();
        });
      });
    }
	else {
		var tmpArray = Array();
		var found = false;
		
		$(this).each(function(){
        	elt = $(this).get(0)
        	elt.normalize();
        	$.each($.makeArray(elt.childNodes), function(i, node){
				if(node.nodeType == 3) {
					var searchnode = node
					//
					var pos = searchnode.data.search(regex);
					//alert(pos);
					if(pos >= 0) {
						//
							match = searchnode.data.slice(pos).match(regex)[0];
							//tmpArray.push(match);
							//if(match.length == 0) break;
							currWord = match;
							currWord = currWord.toLowerCase();
							oldWord = oldWord.toLowerCase();
							if(currWord != oldWord) {
								//alert(currWord + "--------" + oldWord);
								foundWordOnce = false;	
							}
							//alert(pos + " -- " + match);
							if(!foundWordOnce) {
								var spannode = document.createElement('span');
								spannode.className = 'highlight';
								spannode.id = 'highlight_' + tmpCtr;
								tmpCtr++;
								var middlebit = searchnode.splitText(pos);
								var searchnode = middlebit.splitText(match.length);
								var middleclone = middlebit.cloneNode(true);
								spannode.appendChild(middleclone);
								searchnode.parentNode.replaceChild(spannode, middlebit);
								//alert(match + "::" + foundWordOnce);
								foundWordOnce = true;
								//alert(match + "::" + foundWordOnce);
								currWord = match;
								oldWord = match;
								
								currWord = currWord.toLowerCase();
								oldWord = oldWord.toLowerCase();
							}
							
						//}

					} //end while
					//for (x in tmpArray)
					//{
					//	alert(tmpArray[x]);
					//}
				}
				else {
					$(node).highlightRegex(regex);
				}
        	}) //end each
      	}) //end each
    }
    return $(this);
  }
})(jQuery);
