;(function($) {
	
	$.fn.extend({
		taghighlight: function(options) {
			if(options.text) {
				options = $.extend($.TagHighlight.defaults, options);
				
				return this.each(function() {
					new $.TagHighlight(this, options);
				});
			}
			
			return false;
		}
	});

	$.TagHighlight = function(input, options) {
		input = $(input);
		
		var tags = $(options.tag_query, input);
		tags.each(function(index, tag) {
			$(tag).click(function(event) {
				highlight(options.text, $(this).html());
				
				return false;
			});
		});
		
		function highlight(el, q) {
			removeHighlight();
			
			options.count = 0;
			
			el.each(function() {
				innerHighlight(this, q.toUpperCase());
			});
			
			//goto first result
			$(options.text).scrollTo("#highlight_1", 200, {axis:'y'});		
			totalCount = options.count;
			options.updateCount(totalCount);
		}
		
		function removeHighlight() {
			$('.' + options.highlight_class).each(function() {
				with(this.parentNode) {
					replaceChild(this.firstChild, this);
					normalize();
				}
			});
		}
		
		function innerHighlight(node, pat) {	
			var skip = 0;
			if (node.nodeType == 3) {
				var pos = node.data.toUpperCase().indexOf(pat);
				var nextChar = node.data.toUpperCase().charCodeAt(pos + pat.length);
				if (pos >= 0 && (nextChar < 65 || nextChar > 90)) {
					var spannode = document.createElement('span');
					spannode.className = options.highlight_class;
					options.count++;
					spannode.id = "highlight_"+options.count;					
					var middlebit = node.splitText(pos);
					var endbit = middlebit.splitText(pat.length);
					var middleclone = middlebit.cloneNode(true);
					spannode.appendChild(middleclone);
					middlebit.parentNode.replaceChild(spannode, middlebit);
					skip = 1;
				}
			} else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
				for (var i = 0; i < node.childNodes.length; ++i) {
					i += innerHighlight(node.childNodes[i], pat);
				}
			}
			return skip;
		}
	};


	$.TagHighlight.defaults = {
		highlight_class: 'highlighted',
		tag_query: 'a'
	};

})(jQuery);