Glossary = Class.create();

Glossary.prototype = {
	
	// Parameters are a hash of terms(key=word, value=definition)
	// and an XHTML element to search recursively.
	initialize: function(terms, root, opts) {
		this.terms = terms;
		this.root = root || $('body');
		this.opts = opts || { 'find_all': true }
		obj = this
		$H(terms).each(function(term) {
			term.found = term.found || false;
			$A(root.childNodes).each( function(n) {
				obj.search_node(n, term);
			});
		});
		
	},
	
	search_node: function(node, term) {
		
		obj = this;
		
		// If the element has childNodes, recursively search them.
		if( node.hasChildNodes ) {
			$A(node.childNodes).each(function(n) {
				obj.search_node(n, term);
			});
		}
		
		// Only search textNodes (nodeType == 3)
		if ( node.nodeType != 3 ) return; 
		
		// If the find_all options is false
		// and the term has already been found,
		// don't find it again.
		if (!this.opts.find_all && term.found) return;
		
		word = term.key;
		def = term.value;

		temp_nv = node.nodeValue.toLowerCase();
		temp_word = word.toLowerCase();

		// Return if the word isn't found.
		if ( temp_nv.indexOf(temp_word) == -1 ) return;		
		
		p = node.parentNode;

		nv = node.nodeValue;
		wi = temp_nv.indexOf(temp_word);
		before = document.createTextNode( nv.substring(0, wi) );
		m = temp_nv.match(new RegExp(temp_word + "\\w\s*"));
		word_val = nv.substring(wi, wi + m[0].length - 2)
/*		word_val = nv.substring( wi, wi + word.length - 1 );*/
		word_node = document.createTextNode(word_val);
		after = document.createTextNode( nv.substring(wi + word_val.length) );
		hiword = document.createElement('a');
		hiword.setAttribute('title', def);
		hiword.setAttribute('href', '#');	
		hiword.setAttribute('onmouseover', "return escape('<strong class=\"gloss_term_word\">" + word +":</strong> " + def + "')");
		hiword.className = 'glossary_term';
		hiword.appendChild(word_node);
		p.insertBefore(before, node);
		p.insertBefore(hiword, node);
		p.insertBefore(after, node);
		p.removeChild(node);
		term.found = true;				
	}
	
}
