
	
	
	/*
	Script for highlighting search terms within results from sml_facetedsearch

	Settings:
	- terms:		Comma-separated list of terms to highlight
	- subSelection:	jQuery selector for elements within the main element on which highlighting is to be applied. For complex
					selections, you can pass a function pointer that will return a jQuery object or collection.	This function
					takes the outer jQuery element as the first parameter and the settings object as the second.
					Defaults to "*".
	- wrapper:		Element that will surround the highlighted terms.
					Defaults to <em class="highlight"></em>.

*/

$j.scf.behavior.add("HighlightBehavior", {

	attach: function(el, settings, jq){
		if (!settings.terms) return;	// Nothing to highlight.
		if (!settings.subSelection) settings.subSelection = "*";
		if (!settings.wrapper) settings.wrapper = '<em class="highlight"></em>';

		var subSelection;
		if (typeof(settings.subSelection) == "function"){
			subSelection = settings.subSelection(jq, settings);
		} else {
			subSelection = $j(settings.subSelection ,jq)
		}

		highlightTerms(subSelection, settings.terms, settings.wrapper);

		function highlightTerms(jqElm, terms, wrapElm) {
			var wrap= $j('<u>$1</u>').wrapInner(wrapElm).html();	// u is helper tag, not used
			reTerms= terms.replace(/[\*\"\+]/g,"").replace(/\s*,\s*/g,",").replace(/([^\w\s,])/g,"\\$1").split(",").join("|");	// prepare terms for regexp
			//						remove *, " and +		trim each term			escape special chars

			reTerms = xmlEncode(reTerms);

			var re= new RegExp("("+reTerms+")", "gi");
			jqElm.contents().each(function() {
				if (this.nodeType==3) $j(this).replaceWith( xmlEncode(this.nodeValue).replace(re,wrap) );
			});
		}

		function xmlEncode(s) {
			return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
		}
	}
});


