/********* Cancord Glossary Script *************/
/**
 * jQuery plugin - call on parent node for search restriction, or
 * body to search full page.
 * @param  source   path to glossary source .xml file
 */
jQuery.fn.highlightTerms = function(source) {
	var self = this;
	$.ajax({ type: "GET", 
		 url: source, 
		 data: "", 
		 dataType: "xml",
		 async: false,
		 success: function(xml){
			var glossaryArr = [];
			$(xml).find('entry').each(function(i){
				glossaryArr[i] = [$('term',this).text(),$('dfn',this).text()];
			});
			highlightGlossaryTerms(glossaryArr.sort(maximalMunchOrder), self[0]);
		 }
	}); 
	return this;
}
/**
 * Does the heavy lifting by searching innerHTML of element
 * for each indiv. item in terms 
 * @param  terms  	2-d array [term string][definition string]
 * @param  element	DOM element: parent node to restrict search to
 */
function highlightGlossaryTerms(terms, element) {
    // Starting node, parent to all nodes you want to search
    var textContainerNode = element;
	// step through terms array
    for (var x = 0; x < terms.length; x++) {
      if (terms[x][0] == "") continue;
      // The regex is the secret, it prevents text within tag declarations to be affected,
      // and keeps the greedy match by dissallowing link text to be matched.
      var regex = new RegExp("(<(?:[^ah]|a[^ ]+)[^>]*>)([^<]*)?("+terms[x][0]+")([^a-z][^>]*)?<","i");
      var tid = encodeURIComponent(terms[x][0].replace(' ','+'));
	  tid = tid.replace("%2B","+");
	  tid = tid.replace("%C2%AE","%AE");
      textContainerNode.innerHTML = textContainerNode.innerHTML.replace(regex,
  			"$1$2<a class='glossaryterm' title='"+terms[x][1]+"' href='/rae-development/rope_glossary/index.asp#"+tid+"'>$3</a>$4<");
	  		
    }
}
/**
 * Sort by string length
 * @param  a  	array, compare string in index 0
 * @param  b	array, compare string in index 0
 */function maximalMunchOrder(a,b) {
	return (a[0].length > b[0].length) ? -1 : (a[0].length < b[0].length ? 1 : 0);
}
