//refToTop via search.js
var intLoadDocumentInterval = -1;
var objWindow;

/*Highlight variables, used to store the settings for highlight.
  This way we can highlight docs when they are loaded from that document itself*/
var strHlightSearch    = "";
var blnHlightCase      = false;
var blnHlightWholeWord = false;
var blnHlightRegExp    = false;

var strPrevSearch       = "";
var blnPrevCase         = false;
var blnPrevWholeWord    = false;
var blnPrevRegExp       = false;
var blnPrevMetadata     = false;

function reportOnload() {
	document.getElementById("btnZoek").disabled=false;
}


function init() {
	document.getElementById("inpZoek").value="";
	document.getElementById("inpZoek").focus();
}

function initSearch(strSearch) {   
	var blnCase = document.getElementById("caseSensitive").checked;
	var blnWholeWord = document.getElementById("wholeWord").checked;
	var blnMetadata;
	elmMetadata = document.Searchform.metadata;
	for (var i = 0; i < elmMetadata.length; i++){
	    if (elmMetadata[i].checked == true){
	        if (elmMetadata[i].value == "yes"){
	            blnMetadata = true;
	        } else {
	            blnMetadata = false;
	        }
	    }
	}

	if (!(strPrevSearch == strSearch && blnPrevCase == blnCase && blnWholeWord == blnPrevWholeWord && blnMetadata == blnPrevMetadata)){
	    // New Search
	    refToTop.getSearchResultWindow().document.getElementById('divResults').innerHTML = getLanguage('msg_busysearching'); showSearch();
	    
	    // remember search info
	    strPrevSearch = strSearch;
	    blnPrevCase = blnCase;
	    blnPrevWholeWord = blnWholeWord;
	    blnPrevMetadata = blnMetadata;
	    
	    // search
	    
	    
	    setTimeout("doSearch()", 0);
	} else {
	    // Show previous results
	    showSearch();
	}
}

function doSearch() {   
    var objFile = document.getElementById("fraSearchIndex").contentWindow.document;
    
    if(blnPrevMetadata){
	    var arrResults = findMetadata(strPrevSearch, blnPrevWholeWord, blnPrevCase);
	    writeMetadataResults(arrResults);
	    //reset highlight vars, no highlight needed
	    strHlightSearch    = "";
	    blnHlightCase      = false;
	    blnHlightWholeWord = false;
	    blnHlightRegExp    = false;
    } else{
	    // the array returned contains HitMatch objects
	    var arrResults = find(strPrevSearch, blnPrevWholeWord, blnPrevCase, objFile);
	    writeResults(arrResults, strPrevSearch, blnPrevCase, blnPrevWholeWord);
	    //set the highlight vars
	    strHlightSearch    = strPrevSearch;
	    blnHlightCase      = blnPrevCase;
	    blnHlightWholeWord = blnPrevWholeWord;
	    blnHlightRegExp    = false;
    }
}

/*
	Returns the strPopup_name from the objHitmatch if there is one, or when it
	is not empty. Otherwise, the title is returned.
*/
function getSearchLabel(objHitMatch) {
	if(objHitMatch.getStrPopup_name()) {
		if(objHitMatch.getStrPopup_name() != "") {
			return objHitMatch.getStrPopup_name();
		}
	}
	
	return objHitMatch.getTitle();
}

// arrResults is an array of HitMatch objects
function writeResults(arrResults, strSearch, blnCase, blnWholeWord) {
	if (arrResults.length>0) {
		var strOutput="<table width='100%' cellpadding=2>";
		strOutput+="<tr><td class=header>" +getLanguage("lbl_document") + "</td><td class=header>" + getLanguage("lbl_hits") + "</td></tr>";

		var strLastBook=null;
		var strLastTabset=null;
		
		for (var i=0; i<arrResults.length; i++ ) {
			var objHitMatch = arrResults[i];
			
			if (strLastBook!=objHitMatch.getBookName() && objHitMatch.getBookName()!="" ) {
				//' a new book starts, write the name of the book
				strLastBook=objHitMatch.getBookName();
				strOutput+="<tr><td colspan=2><span style='position:relative; left:0px'><img src='images/book.gif'> " + strLastBook + "</span></td></tr>";
			}

			var strParentTabset=objHitMatch.getParentTabset();
			if (strLastTabset!=strParentTabset&& strParentTabset!="") {
				//' a new tabset starts, write the name of the tab
				strLastTabset=strParentTabset;
				strOutput+="<tr><td colspan=2><img src='images/tabdoc.gif'>" + strLastTabset + "</td></tr>";
			}
			
			strOutput += "<tr><td>";
			if (objHitMatch.getBookName()=="") {
				//' make sure that a intro document is displayed more to the left
				strOutput+="<span style='position:relative; left:0px'>";
			} else if (strParentTabset!="") {
				//' there is a parent tabset, indent a bit more
				strOutput+="<span style='position:relative; left:24px'>";
			} else {
			    // Normal document
			    strOutput+="<span style='position:relative; left:12px'>";
			}
			strOutput+=getImage(objHitMatch);
			
			var strMenuItemID =  objHitMatch.getMenuItemID();
			if (strMenuItemID == '') strMenuItemID = 'null';
			strOutput += '\n <a href="#" onClick="refToTop.ShowHighlights(); refToTop.openNewLink('
					  + objHitMatch.getDocumentID()			          +', '
					  + strMenuItemID + ', '
					  + '0'     //menuId
					  + ', \'' + objHitMatch.getStrCoId().replace(/\'/g,"\\'") + '\''
					  + ', ' + '\'' + objHitMatch.getTitle() + '\''
					  + ', ' + '\'' + objHitMatch.getStrPopup_url() +   '\''
					  + ', ' + '\'' + objHitMatch.getStrPopup_strFeats() +  '\''
					  + ', ' + '\'' + objHitMatch.getStrPopup_name() + '\'' 
					  + ')">'		  + getSearchLabel(objHitMatch)	+ '</a>\n';
			strOutput+="</span>";
			strOutput+= "</td><td>" + objHitMatch.getContentHitCount()  +"</td></tr>";

		}
		strOutput+="</table>";
		refToTop.getSearchResultWindow().document.getElementById("divResults").innerHTML = strOutput;
	} 
	else {
		refToTop.getSearchResultWindow().document.getElementById("divResults").innerHTML = getLanguage("msg_nosearchresults");
	}
}
function writeMetadataResults(arrProperties){
	if (arrProperties.length>0) {
		var strOutput="<table width='100%' cellpadding=2>";
		strOutput+="<tr><td class=header>" +getLanguage("lbl_document") + "</td></tr>";
		for (var i=0; i<arrProperties.length; i++ ) {
			var objHitMatch = arrProperties[i];
			strOutput += "<tr><td><span style='position:relative;left:-10px'>" + (objHitMatch.isTabSet()?"<img src='images/tabdoc.gif'>": "<img src='images/document.gif'>") + 
					"<a href='#' onClick=\"refToTop.openNewLink(" + objHitMatch.getDo_id() + ", " + objHitMatch.getMi_id() + ", 0, " + objHitMatch.getCo_id() + ", '" + objHitMatch.getLabel() + "')\" >";
//			strOutput += objHitMatch.getName() + '= ' + objHitMatch.getValue();
			strOutput += objHitMatch.getLabel() ;
			strOutput += "</a></span></td></tr>";
		}
		strOutput+="</table>";
//		alert(strOutput);
		refToTop.getSearchResultWindow().document.getElementById("divResults").innerHTML = strOutput;
	} 
	else {
		refToTop.getSearchResultWindow().document.getElementById("divResults").innerHTML = getLanguage("msg_nosearchresults");
	}
}

function getImage(objHitMatch) {
	if (objHitMatch.getStrPopup_strFeats()=="tree_document") {
		return "<img src='images/uitklapitem.gif'>";
	} else if (objHitMatch.getStrPopup_strFeats()=="knop_document") {
		return "<img src='images/buttonitem.gif'>";
	} else if (objHitMatch.isTabSet()) {
		return "<img src='images/tabdoc.gif'>";
	} else {
		return "<img src='images/document.gif'>";
	}
}
/*
	Highlight the document of the specified window. Highlight vars are set 
	above and used to determine what to hightlight.	Function is called in the 
	onload of a document, and only if the objWindow	is valid.
*/
function highlightDocAtReload(objWindow) {
    if(objWindow) {
		objWindow.highlight(strHlightSearch, objWindow.document.body, blnHlightCase, blnHlightWholeWord, blnHlightRegExp);
	}
}   

function highlightDoc(intDocumentID, intMenuItemID, strSearch, blnCase, blnWholeWord, strTitle
                     ,strMeId, strCoId, strPopup_url, strPopup_strFeats, strPopup_name) {
	//alert("highlightDoc("+intDocumentID+","+strSearch+","+blnCase+")");
	/* first give the document time to load in the correct context
	 so there are two options to commence: 
	 1) poll with an interval if the document is loaded
	 2) call a function from the index page, signalling it is ready	 
	 */
	refToTop.openNewLink(intDocumentID, intMenuItemID, strMeId, strCoId, strTitle
	               ,strPopup_url, strPopup_strFeats, strPopup_name);
	//var objDocumentWindow = parent.parent.parent.document.getElementById("right").contentWindow.document.getElementById("ce_main").contentWindow;
	//alert(objDocumentWindow.location);
	//objDocumentWindow.location.replace("documents/do_"+intDocumentID+ ".htm");
	//objWindow = objDocumentWindow;
	
	//if there is a popup, then highlight it there, otherwise in the top.document
	//var blnIsPopup = (strPopup_url != "") && (strPopup_url != null);
	var blnIsPopup = (strPopup_strFeats != "undefined") && (strPopup_strFeats != null) && (strPopup_strFeats != "");
	//alert("ispopup");
	if(blnIsPopup) {
	//find it, otherwise there is none to highlight...
		if(refToTop.getLastPopupWindowByName(strPopup_name) != null) {
			intLoadDocumentInterval = setInterval("loadDocumentPopup(\""+strSearch+"\", "+(blnCase? "true": "false")+", "+(blnWholeWord? "true": "false")+ ", " + "\"" + strPopup_name + "\"" + ");", 500);
		}
	}
	else {
		intLoadDocumentInterval = setInterval("loadDocument(\""+strSearch+"\", "+(blnCase? "true": "false")+", "+(blnWholeWord? "true": "false") +");", 500);
	}
}

function loadDocumentPopup(strSearch, blnCase, blnWholeWord, strPopup_name) {
	if(refToTop.getLastPopupWindowByName(strPopup_name).blnWindowLoaded) { //check if popup is loaded
			clearInterval(intLoadDocumentInterval);
			intLoadDocumentInterval = -1;
			/*var objWindow = top.getLastPopupWindowByName(strPopup_name);
			var intHighlights = objWindow.highlight(strSearch, objWindow.document.body, blnCase, blnWholeWord, false);*/
		}
}

function loadDocument(strSearch, blnCase, blnWholeWord) {
	//	alert("search: "+strSearch+"; case: "+blnCase+"; whole word: "+blnWholeWord); 
	if (refToTop.isDocumentLoaded()) {
//		alert("interval cleared: "+intLoadDocumentInterval);
		clearInterval(intLoadDocumentInterval);
		intLoadDocumentInterval = -1;
		/*var objWindow = top.getContentWindow();
//		var intHighlights = highlight(strSearch, blnCase, blnWholeWord, false, objWindow.document, objWindow.document.documentElement);		
		var intHighlights = objWindow.highlight(strSearch, objWindow.document.body, blnCase, blnWholeWord, false);*/
	}
}

function checkClick(e) {
	if (e.keyCode==13) {
		initSearch(document.getElementById("inpZoek").value);
		return false;
	}
	return true;
}
function writeLanguage(str) {
	document.write (getLanguage(str));
}
function getLanguage(str){
	try {	
		var s=eval(str);	
		return eval(str);
	} catch(e) {
		return str;
	}
}


var refToTop = window.parent.refToTop; //used in: zoek.htm

var oldString = "";
function hi(f) { f = f.elements;
 	f.find.value = highlight( f.q.value ) + 'x ' + f.q.value;
	window.setTimeout( 'document.forms.f.elements.find.value=" Find " ;', 2500 );
	if (oldString != "") unhighlight(oldString);
	oldString = f.q.value;
	return false;
}

function unhighlight(){
	var hlSpans = document.getElementsByTagName("span");
	for(var i=hlSpans.length-1; i >-1; i--){
		if(hlSpans[i].getAttribute("name") == "hls"){
			var elSpan = hlSpans[i];
			var parentNode = elSpan.parentNode;
			parentNode.insertBefore(elSpan.firstChild, elSpan);
			parentNode.removeChild(elSpan);
//			parentNode.normalize();
		}
	}
}

function highlight(s, el, blnCase, blnWholeWord, blnRegexp){
//	alert("highlight '" + s + "'");
	var blnPhrase = false;
	var objDocument = el.ownerDocument;
	var hlcount = 0;
//	var regexpParams = 'g' + (blnCase? '' : 'i');
	if( !s ) { return 0; }
	if( blnRegexp ) { s = s.replace( /([\\|^$()[\]{}.*+?])/g, '\\$1' ); }
	if( /^\s*$/.test(s) ) { return 0; }   
	if( blnPhrase ) { s = s.split( /\s+/ ).join( '|' ); }
	if( blnWholeWord ) { s = "\\b"+s+"\\b"; }
	
//function highlight(s, el){
	var re = new RegExp(s, 'g' + (blnCase? '' : 'i'));
	for(var i=0; i < el.childNodes.length; i++){
		// if textNode
		if(el.childNodes[i].nodeType == 3){
			var refNode = el.childNodes[i];
			var arrStr = regExpSplit(refNode.nodeValue, re);
			if(arrStr.length > 1){
				// at least one match has been found
				for(var k=0; k < arrStr.length; k++){
					if(arrStr[k].search(re) == 0){
						// string is one the matches, add a span around it
						var elSpan = objDocument.createElement("span");
						elSpan.className = "highlight";
						//elSpan.style.color = '#000';   
						//elSpan.style.backgroundColor = '#ff0000';
						elSpan.setAttribute("name", "hls");
						elSpan.appendChild(objDocument.createTextNode(arrStr[k]));
						el.insertBefore(elSpan, refNode);
						hlcount++;
					}
					else{
						// simply copy back the piece of text
//alert("no highlight '" + arrStr[k] + "'");
						if(arrStr[k] != ''){
							el.insertBefore(objDocument.createTextNode(arrStr[k]), refNode);
						}
					}
				}
				// remove the original textNode
				el.removeChild(refNode);
				// skip the nodes that have been added
				i = i + arrStr - 1;
			}
		}
		else if(el.childNodes[i].nodeType == 1){
			// node is an element, recursively go through its children
			hlcount += highlight(s, el.childNodes[i], blnCase, blnWholeWord, blnRegexp);
		}
	}
	return hlcount;
}
/*
	function returns an arraymatching the following partern:
	[string, regexp pattern, string, regexp pattern, etc.]
*/
function regExpSplit(str, re){
	var retArr = [];
	var matchArr = str.match(re);

	if(!matchArr){
		return [];
	}
	for(var i=0; i< matchArr.length; i++){
		var s = matchArr[i];
		retArr.push(str.substring(0, str.indexOf(s)));
		retArr.push(s);
		str = str.substr(str.indexOf(s) + s.length);
	}
	retArr.push(str);
	return retArr;
}

// return an array of HitMatch objects
function find(strSearch, blnWholeWord, blnCaseChecked, objElement, blnIncludingProperties ) {
	var blnPhraseChecked = true;
	var arrResults = new Array();
	if( !strSearch ) { return arrResults; }   var d = document;   
	strSearch = strSearch.replace( /([\\|^$()[\]{}.*+?])/g, '\\$1' );
	if( /^\strSearch*$/.test(strSearch) ) { return 0; }
	if( !blnPhraseChecked ) { strSearch = strSearch.split( /\s+/ ).join( '|' ); }
	if (blnWholeWord) strSearch = "\\b"+strSearch+ "\\b";
	objElement = [ objElement || d.documentElement || d.body ];
	var objRegExp = new RegExp( strSearch, blnCaseChecked ? 'g' : 'gi' ),     h = d.createElement('span'), i = 0, j, k, arrMatches, objNode, n=0, t; 
	do {
		if(i == 0) {//RR: added to keep source objElement unchanged
			objNode = (objElement[i].nodeName != "#document" ? objElement[i].cloneNode(true) : objElement[i].documentElement.cloneNode(true));
		} else {
			objNode = objElement[i];
		}
		if( objNode.nodeType == 3 ) {
			objRegExp.lastIndex = 0;       
			arrMatches = objRegExp.exec(objNode.nodeValue);       
			if( arrMatches != null ) {         
				k = arrMatches[0].length;         
				if( objRegExp.lastIndex > k ) {           
					objNode.splitText( objRegExp.lastIndex - k );           
					objNode = objNode.nextSibling;         
				}         
				if( objNode.nodeValue.length > k ) {           
					objNode.splitText(k);           
					objElement[i++] = objNode.nextSibling;         
				}
				//alert("search found in parent: "+objNode.parentNode.getAttribute("do_id"));
				//addHit(arrResults, objNode.parentNode.getAttribute("do_id"), objNode.parentNode.getAttribute("title"));
				addHit(arrResults, objNode, blnIncludingProperties);
			}     
		} 
		else {       
			j = objNode.childNodes.length;
			while (j) { 
				objElement[i++] = objNode.childNodes.item(--j); 
			}     
		}  
	}
	while(i--); 
	return arrResults;
}

function findMetadata(strSearch, blnWholeWord, blnCaseChecked){
	var blnPhraseChecked = true;
	var arrResults = new Array();
//alert("searching for " + strSearch);
	if( !strSearch ) { return arrResults; }
	strSearch = strSearch.replace( /([\\|^$()[\]{}.*+?])/g, '\\$1' );
	if( /^\strSearch*$/.test(strSearch) ) {alert("regexp test failed"); return 0; }
	if( !blnPhraseChecked ) { strSearch = strSearch.split( /\s+/ ).join( '|' ); }
	if (blnWholeWord) strSearch = "\\b"+strSearch+ "\\b";
	var objRegExp = new RegExp( strSearch, blnCaseChecked ? 'g' : 'gi' );
	var i = 0, j, k, arrMatches, objNode, n=0, t;
	var arrProperties = refToTop.properties;
	if(!arrProperties){
//		alert("no properties found");
		return arrResults;
	}
//	alert(objRegExp);
	for(var i=0; i<arrProperties.length; i++){
//		alert("propName: " + arrProperties[i].getName() + "\npropValue: " + arrProperties[i].getValue());
		if(objRegExp.exec(arrProperties[i].getName()) || objRegExp.exec(arrProperties[i].getValue())){
			// match found
			arrResults.push(arrProperties[i]);
		}
	}
	return arrResults;
}

//function addHit(arrResults, intDocumentID, strTitle) {
function addHit(arrResults, objNode, blnIncludingProperties) {
	// first detect whether the ancestor is 'content' or 'properties', the last is used for the metadata search
	var objParentNode = objNode.parentNode;
	var blnPropertiesParent = false;
	while (objParentNode.nodeName != "DIV " && (objParentNode.getAttribute("kind") != "content" &&  objParentNode.getAttribute("kind") != "properties")) {
		if (objParentNode.parentNode == null) {
			// this shouldn't happen
			return;
		}
		else objParentNode = objParentNode.parentNode;
	}
	var blnPropertiesParent = (objParentNode.getAttribute("kind") == "properties");
	// if matches for properties shouldn't be included we have to stop here
	if (!blnIncludingProperties && blnPropertiesParent) return;
	// now get the info of the parent DIV node
	objParentNode = objParentNode.parentNode;
	var intDocumentID = objParentNode.getAttribute("do_id");
	var intMenuItemID = objParentNode.getAttribute("mi_id");
	var strTitle = objParentNode.getAttribute("title");
	var strBookName = objParentNode.getAttribute("book_name");	
	var blnTabSet = objParentNode.getAttribute("tabbladenset");	
	var strParentTabset=	objParentNode.getAttribute("parenttabset");
	
	//these attributes are optional... only for knop documents (and later perhaps for knop alineas)
	var strPopup_url = "";	
	var strPopup_strFeats = objParentNode.getAttribute("popup_strFeatsType");
	var strPopup_name = "";
	var strCoId = "0";	
	try {
		//check if there is a popup_strFeatsType (either knop_document or knop_alinea
		if ((strPopup_strFeats != "undefined") && (strPopup_strFeats != null) && (strPopup_strFeats != "")) {		
			if(strPopup_strFeats == "knop_document") {
				strPopup_url = objParentNode.getAttribute("popup_url");
				strPopup_name = strTitle;
				strTitle = objParentNode.getAttribute("parent_do_name");
					
				//open parent, so adjust do_id etc.
				intDocumentID = objParentNode.getAttribute("parent_do_id"); 
				intMenuItemID = objParentNode.getAttribute("parent_mi_id");
				//strMeId = "0";
			}//if
			if(strPopup_strFeats == "knop_alinea") {
				strPopup_url = objParentNode.getAttribute("popup_url");
				strPopup_name = strTitle;
				strTitle = objParentNode.getAttribute("parent_do_name");
					
				//open parent, so adjust do_id etc.
				intDocumentID = objParentNode.getAttribute("parent_do_id"); 
				intMenuItemID = objParentNode.getAttribute("parent_mi_id");
				strCoId = objParentNode.getAttribute("co_id");
			}
			//if knop_alinea
		}//if
		else {//just to be sure no alinea is tries to be load
			strPopup_strFeats = "";
		}
	}//try
	catch(e) {
		//no popup is needed
	}
	
	//what does this do??
	for (var i=0; i < arrResults.length; i++ ) {
		if (arrResults[i].contains(intDocumentID, intMenuItemID)) {
			arrResults[i].addHit(blnPropertiesParent);
			return;
		}
	}				   
					   
	var objHit = new HitMatch(intDocumentID, intMenuItemID, strTitle
	                         ,strCoId, strPopup_url, strPopup_strFeats, strPopup_name, strBookName, blnTabSet, strParentTabset);
	objHit.addHit(blnPropertiesParent);
	arrResults.push(objHit);
}

