//searchandmanipulate.js
/*

Search and Manipulate by Thomas David Baker
<http://bluebones.net/>
<mailto:bakert@gmail.com>

Very much nicked from Highlight v2 by Johann Burkard
<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>

MIT license.

*/

( function($) {
	// we can now rely on $ within the safety of our “bodyguard” function
	$(document).ready( function() {
		jQuery.highlight = function(node, texts, caseSensitive, callback) {
			var pos;
			var skip = 0;
			var ELEMENT_NODE = 1;
			var TEXT_NODE = 3;
			if (node.nodeType == TEXT_NODE) {
			   for (var i = 0; i < texts.length; i++) {
					var text = texts[i];
					pos = (caseSensitive ? node.data.indexOf(text) : node.data.toUpperCase().indexOf(text.toUpperCase()));
					if (pos >= 0) {
						// Break the text node into two at the start of the match, capturing the second part
						match = node.splitText(pos);
						// Break the second part into two at the end of the match
						// match is now a separate node containing only the matched text
						match.splitText(text.length);
						// Replace the matched text node with whatever the callback function provides
						match.parentNode.replaceChild(callback(match.nodeValue), match);
						skip = 1;
					}
				}
			} else if (node.nodeType == ELEMENT_NODE && node.childNodes && !/(script|style)/i.test(node.tagName)) {
				for (var i = 0; i < node.childNodes.length; ++i) {
					i += $.highlight(node.childNodes[i], texts, caseSensitive, callback);
				}
			}
			return skip;
		}

		// Add to jquery fn namespace allowing $('.whatever').highlight(function)
		jQuery.fn.highlight = function(texts, caseSensitive, callback) {
			if (typeof text == 'string') {
				texts = [texts];
			}
			$(this).each(function() {
				$.highlight(this, texts, caseSensitive, callback);
			});
		} 

		//XXX Does not work in this version
		jQuery.fn.removeHighlight = function() {
			this.find("span.highlight").each(function() {
				with (this.parentNode) {
					replaceChild(this.firstChild, this);
					normalize();
				}
			});
			return this;
		};

		jQuery.makeLinkCallback = function(urlGenerator) { 
			return function(text) {
				anchor = document.createElement('a');
				$(anchor).attr('href', urlGenerator(text));
				$(anchor).addClass('def');
				$(anchor).text(text);
				return anchor;
			}
		};

		jQuery.makeHighlightCallback = function(highlightClass) { 
			//XXX
		};
	});
} ) ( jQuery );
