/********* 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,negativelist) {
	var negativearray = negativelist.split(',');
	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],negativelist);
		 }
	}); 
	return this;
}
function valuenotfound(needle, haystack) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    var found = true
	
    for (key in haystack) {
	//alert(haystack[key] + "=" + needle);
        if (haystack[key].toUpperCase() === needle.toUpperCase()) {
		//alert("match found: " + needle);
            found = false;
            break;
        }
    }
 
    return found;
}
/**
 * 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,negativelist) {
    // Starting node, parent to all nodes you want to search
	var negative_array = negativelist.split(',');
	
    var textContainerNode = element;
	// step through terms array
    for (var x = 0; x < terms.length; x++) {
			
		if (terms[x][0] == "") continue;
			
				//alert(terms[x][0]);
				  // 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");
				 // alert(terms[x][0]);
				  var tid = terms[x][0].replace(' ','+');
				  tid = tid.replace("%2B","+");
	  				tid = tid.replace("%C2%AE","%AE");
				  //var tid = encodeURIComponent(terms[x][0].replace(' ','+'));
				  if(valuenotfound(terms[x][0], negative_array)){
					  textContainerNode.innerHTML = textContainerNode.innerHTML.replace(regex,
							"$1$2<a class='glossaryterm' title='"+terms[x][1]+"' href='/rope_glossary/index.asp#"+tid+"'>$3</a>$4<");
					  //alert("hi2");
				  }
}
	
}
/**
 * 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);
}


