/******************************************************************/
//Mark key words and, on hover, display their description
//
//Vind marktext xxx (xxx) xxx; xxx: xxx. 
// - Voorafgegaan door een spatie of (haakje. 
// - Met daarna een spatie, haakje), comma, puntcomma, dubbelepunt of punt
//
//Werking:
// - Loop through the HTML document, find all text nodes. 
// - For each node get the textContent, get the position of the
//   Mark-text with indexOf (with an optional case-insensitive)
//   Append everything before indexof as textNode, append the 
//   matched Text with a span.
//   Repeat for the rest of the textnode. 
//
// Works with UTF-* characters and entities like &auml;
/******************************************************************/
var CaseSensitiveSearch = false;
var MarkOnlyFirstOccurrence = true;

var firstmarked;
var ClassName = "definitionterm";

var terms = new Array();
var descr = new Array();

//Main function called to start marking terms
function MarkTerms(dlfn, marktext, description) {
	var container = document.getElementsByTagName("body")[0];	
	if (marktext) {
		
		//Use specifed single term
		firstmarked = false;
		iterator(container, marktext, description);
	}
	else {
		//Use terms array
		getDefinitionlist(dlfn, container);
			
		
	}
}

function getDefinitionlistCallback(cbValue, container){
	if(cbValue != ""){
		var content = cbValue.split(/term\s+id\s*=\s*"/g);
		var i, hlp, term, desc;
		for (i=1; i<content.length; i++) {
			hlp=content[i];
			term= hlp.substr(0,hlp.indexOf("\""));
			if (term!="") {
				terms.push(term)
				desc = hlp.substr(hlp.indexOf(">"));
				desc = desc.substr(1,desc.indexOf("</term>")-1);
				descr.push(desc)
			}
		}
		var j;
			for (j=0; j<terms.length; j++) { 
				firstmarked = false;
				iterator(container, terms[j], descr[j]);
			}
	}
}

//Load definitionlist from file dlfn
function getDefinitionlist(dlfn, container) {
	var content="";
	try {
		if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
			xhttp=new XMLHttpRequest();
		}
		else {// code for IE6, IE5
			xhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		xhttp.onreadystatechange = function(){
			if(this.readyState == 4 && this.status == 200){
				getDefinitionlistCallback(this.responseText, container);
				xhttp = null;
				
			}
			else if(this.readyState == 4 && this.status != 200){
				xhttp = null;
				
			}			
		};
		xhttp.open("GET",dlfn,true);
		xhttp.send();
		
		
	}	
	catch(e){
		console.log(e);
	}
}

//Iterate through text nodes
function iterator(p, marktext, description) {
	if (p === null) return;
	var children = Array.prototype.slice.call(p.childNodes), i, cur;
	if (children.length) {
		for (i = 0; i < children.length; i++) {
			cur = children[i];
			if (cur.nodeType === 3 && !(firstmarked)) {
				checkAndReplace(cur, marktext, description);
			}
			else if (cur.nodeType === 1) {
				iterator(cur, marktext,description);
			}
		}
	}
} 

function checkAndReplace(node, marktext, description) {
	var nodeVal = node.nodeValue, parentNode = node.parentNode;
	var i, j,
		foundIndex, foundMatch, MatchLength,beforetext, matchedText, end,
		textNode, span;
	var	isFirst = true;
	if (CaseSensitiveSearch) {
		//Vind marktext: 
		// - Voorafgegaan door een spatie of (haakje. 
		// - Met daarna een spatie, haakje), comma, puntcomma, dubbelepunt of punt
		re = new RegExp('[\\s(]'+marktext+'[\\s),;:.]')
	}
	else {
		re = new RegExp('[\\s(]'+marktext.toLowerCase()+'[\\s),;:.]')
	}
	MatchLength = marktext.length+1;
	while (true) {
		if (CaseSensitiveSearch) {
			foundIndex = nodeVal.search(re);
		}
		else {
			foundIndex = nodeVal.toLowerCase().search(re);
		}
		
		if (foundIndex == -1) {
			if (isFirst) break;
			if (nodeVal) {
				textNode = document.createTextNode(nodeVal);
				parentNode.insertBefore(textNode, node);
			}
			parentNode.removeChild(node);
			break;
		}
		isFirst = false;
		
		beforetext = nodeVal.substring(0, foundIndex+1 ); //beforetext: foundIndex+1 voor het voorafgaande re karakter [\\s(] voor de marktext
		//Plaats before-text voor de gevonden marktext
		if (beforetext) {
			textNode = document.createTextNode(beforetext);
			parentNode.insertBefore(textNode, node);
		}
		matchedText = nodeVal.substr(foundIndex, MatchLength);        //Get matched text (met behoud van oorspronkelijke case)
		matchedText = matchedText.replace(/^[\s(]|[\\s),;:.]]$/g, '');//Trim spaces () and ,;:. from matchedText

		if (firstmarked==false) {
			//Maak span
			span = document.createElement("span");
			span.className += ClassName;
			span.setAttribute("onMouseOut","hidetip()");
			span.setAttribute("onclick","showtip(event,'"+description+"')");

			//Plaats span
			span.appendChild(document.createTextNode(matchedText))
			parentNode.insertBefore(span, node);
		}
		else {
			textNode = document.createTextNode(matchedText);
			parentNode.insertBefore(textNode, node);
		}
		if (MarkOnlyFirstOccurrence) firstmarked = true
		//Ga verder met after-text
		nodeVal = nodeVal.substring(foundIndex + MatchLength);
	} // Whend
}

// ============================================================================================================
// popup tooltip
// ============================================================================================================
function showtip(e,content) { 
	if (hasClass(document.getElementById("tooltip"),"tooltip-show")) {
		hidetip()
		return;
	}
	else {
		var x = e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
		var y = e.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + 5;
		var wx= (document.body.clientWidth);
		var left = true;
		if (x >wx/2) {//place tooltip left of cursor (and therefore limit the width)
			x=wx-x;
			left = false;
		}
		if (navigator.userAgent.indexOf("MSIE") != -1) {
			x -= 20; //For IE subtract margin, as specified in the css for the body element
		}
		var frame= '<div class="ttip" style=""><span>'+content+'</span></div>';
		if (document.layers) {// Netscape 4.0+ 
			document.tooltip.document.write(frame); 
			document.tooltip.document.close(); 
			if (left) {document.tooltip.left=x;document.tooltip.right="";}
			else {document.tooltip.left="";document.tooltip.right=x;}
			document.tooltip.top=y;
			document.tooltip.visibility="show";
		} 
		else { 
			if(document.getElementById) {// Netscape 6.0+ and Internet Explorer 5.0+ 
				elm=document.getElementById("tooltip") ;
				elm.innerHTML=frame;
				if (left) {elm.style.left=x+"px";elm.style.right="";}
				else {elm.style.left="";elm.style.right=x+"px";}
				elm.style.top=y+"px";
				toggleClass(elm,"tooltip-hidden", "tooltip-show");
			} 
		} 
	}
} 
				
function hidetip(){ 
	if (document.layers) { // Netscape 4.0+
		document.tooltip.visibility="hidden"; 
	} 
	else { 
		if(document.getElementById) { // Netscape 6.0+ and Internet Explorer 5.0+ 
			var elm=document.getElementById("tooltip"); 
			toggleClass(elm,"tooltip-show", "tooltip-hidden");
		} 
	} 
} 



