// Tint search terms.
YAHOO.namespace('forumsTintText');
YAHOO.forumsTintText = function() {
	function genStemsFromKeywords(keywords) {
		var key_re_arr = new Array();

		// Split the search string into terms and "exact phrases".
		var raw_key_arr = keywords.match(/"[^"]+"|[^"\s]+/g);
		if (!raw_key_arr) { return(key_re_arr); }

		for (var i = 0; i < raw_key_arr.length; i++) {
			var key = raw_key_arr[i];

			// Skip one letter terms.
			if (key.length == 1) { continue; }
			// Skip or terms: OR.
			if (key == "OR") { continue; }
			// Skip NOT terms: -term.
			if (key.charAt(0) == "-") { continue; }

			// Remove dquotes from exact phrases.
			key = key.replace(/\x22/g, "");

			// Stemming: Split off the stemmed endings.
			// XXX - only for key.length > 4?
			// ally - personally => person
			// al - personal => person
			// ant - coolant, radiant
			// ing - pinging => ping
			key = key.replace(/(\S\S\S)(ally|al|(a)nt|ance|ed|ely|ent|er|e|ities|ies|ing|ion|ize|or)?s?()$/, "$1$3");
			key_re_arr.push(key);
		}

		return(key_re_arr);
	}

	// Highlight search terms.
	// Clean the search terms by taking only the root word/fragment
	// Then highlight any occurance of the root + any suffix.
	// XXX - this sometimes breaks html by highlighting part of a url
	// XXX - ideally we'd strip the html out, highlight, then replace it.
	function tintClass(classname, container, stem_re) {
		if (!stem_re) { return; }
		var els = YAHOO.util.Dom.getElementsByClassName(classname, container);
		for (var i = 0; i < els.length; i++) {
			var text = els[i].innerHTML;
			var tint_text = text.replace(stem_re, '$1<strong style="color:black;background-color:#ffff66">$2<' + '/strong>');
			if (tint_text.length != text.length) {
				els[i].innerHTML = tint_text;
			}
		}
	}

return({
	tint: function(keywords) {
		if (!keywords) { return; }
		var stem_arr = genStemsFromKeywords(unescape(keywords));
		if (!stem_arr || !stem_arr.length) { return; }
		// Join the root words into a single RE.
		var stem_re_text = stem_arr.join("|");
		var stem_re = new RegExp('(^|[^\\w])((' + stem_re_text + ')\\w*)', "ig");

		tintClass('postText', 'span', stem_re); // post body
		tintClass('forumstitle', 'span', stem_re); // post title
		tintClass('forumstitle', 'a', stem_re); // discussion title
	}
});
}();
