/*
This search routine is based on the free Recon Search Engine
by Jerry Bradenbaugh (http://www.serve.com/hotsyte/)
alterations have been made by Marc Reed (http://www.marcreed.com)
This script may be used for free
*/
/*
Further alterations were necessary for inclusion in the FM2HTML process.
Version:
4.0 - 2002-09-25 mmh -- added validation functions
						optimized output formatting
4.1 - 2002-09-26 mmh -- store searchField in top frame
4.2 - 2002-10-02 mmh -- removed validation functions
4.3 - 2002-12-05 mmh -- Make "Results" a variable
4.4 - 2003-01-13 mmh -- Remove title from search string, it is already in the long text
						Simplify result array (only one array)
						Remove search in URL and other useless subroutines
						Variable names clean-up
4.5 - 2002-01-21 mmh -- Expand ? to nbsp | any non white space char
						Expand * to zero or more non white space chars
						Expand dash to: dash|en dash|em dash|nb dash
						Removed old lines
4.6 - 2003-03-20 mmh -- Added / to chars to be escaped!
*/

//*************************************************************************
// Define global variables

// the maxResults variable determines how many results are displayed per page:
var maxResults=10;

var myMatches=new Array();
var splitline=new Array();
var indexer=0;
var srcCrit="any"; // may be overwritten
var vResults="Results"; // may be overwritten

//*************************************************************************
//Search Results page should call this function

function doSearch() {
	fullEntry=getQueryString('searchField'); // "+" converted to space
	if(fullEntry!="") {
		filteredEntry="";
		//Look for multiple spaces (white space = \s)
		filteredEntry=fullEntry.replace(/\s+/g," ");
		prepareSearch(filteredEntry);
	}
}

//*************************************************************************
// This generic function will return the value of a QueryString
// If a variable is available, it is used

function getQueryString(Val) {
	if(Val=='searchField'){
		if(top){
			if(top.searchField){
				if(top.searchField!=""){return top.searchField;}
			}
		}
	}
	if(Val=='searchMode'){
		if(top){
			if(top.searchMode){
				if(top.searchMode!=""){return top.searchMode;}
			}
		}
	}
	thisURLparamStr=document.location.search;
	//chop "?" off thisURLparamStr
	if(thisURLparamStr.charAt(0)=="?") thisURLparamStr=thisURLparamStr.substring(1,thisURLparamStr.length);
	returnStr="";
	if(thisURLparamStr!="") {
		//Build array out of thisURLparamStr using "&" as delimiter
		splitline=thisURLparamStr.split("&");
		for(i=0;i<splitline.length;i++) {
			splitparam=splitline[i].split("=");
			if(unescape(splitparam[0])==Val) returnStr=unescape(splitparam[1]);
		}
		returnStr=returnStr.replace(/\+/g," ");
	}
	return returnStr;
}

//*************************************************************************
//Determine any word/all words/phrase search

function prepareSearch(text) {
	//clean up spaces at beginning of string
	while(text.charAt(0)==' ') text=text.substring(1,text.length);
	//clean up spaces at end of string
	while(text.charAt(text.length-1)==' ') text=text.substring(0,text.length-1);
	if(text.length<1) {
		alert("ERROR: Please type some text before starting any search.");
		return;
	}
	// default srcCrit defined above;
	if (parseInt(getQueryString('searchMode'))==0||getQueryString('searchMode')=="any") srcCrit="any";
	if (parseInt(getQueryString('searchMode'))==1||getQueryString('searchMode')=="all") srcCrit="all";
	if (parseInt(getQueryString('searchMode'))==2||getQueryString('searchMode')=="phrase") srcCrit="phrase";
	var entry=text;
	if(entry.charAt(0)=="~") { // full RegExp search
		entry=entry.substring(1,entry.length);
	}
	else { // only * and ? wildcards
		entry=entry.replace(/([\/\\\^\$\+\{\}\.\(\)\|\[\]])/g,"\\$1");  // v4.6
		entry=entry.replace(/\*/g,"[^¶\\x20\\f\\n\\r\\t\\v<>]*");
		entry=entry.replace(/\?/g,"(&nbsp;|[^¶\\x20\\f\\n\\r\\t\\v<>])");
		entry=entry.replace(/-/g,"(\-|‑|–|—)");
	}
	entry=entry.replace(/\//g,"\\/");
	if(srcCrit=="phrase") {doSearchExactPhrase(entry,text);return;}
	else {
		// If not exact phrase, split the entry string into an array
		searchArray=entry.split(" ");
		if(srcCrit=="any") {doSearchAny(searchArray,text);return;}
		else if(srcCrit=="all") {doSearchAll(searchArray,text);return;}
	}
}

//*************************************************************
// Evoked if user searches ANY WORDS

// t: array of search terms
// text: original search text

function doSearchAny(t,text) {
	var matchesInLine=0;
	var refineAllString = "";
	for(i=0;i<profiles.length;i++) {
		// use only content part of profile
		var splitline=profiles[i].split("|");
		refineAllString=splitline[2].toUpperCase();
		matchesInLine=0;
		for(j=0;j<t.length;j++) {
			eval("myRE=/"+t[j]+"/gi");
			matchesArray=refineAllString.match(myRE);
			if(matchesArray!=null)matchesInLine=matchesInLine+matchesArray.length;
		}
		if(matchesInLine>0) {
			// Store only hits, title and URL
			myMatches[indexer]=(0-matchesInLine)+"|"+splitline[0]+"|"+splitline[3];
			indexer++;
		}
	}
	if(myMatches.length==0) {writeNoResultPage(text);return;}
	else {writeResultPage(myMatches,text);}
}

//*************************************************************
// Evoked if user searches ALL WORDS

// t: array of search terms
// text: original search text

function doSearchAll(t,text) {
	var matchesInLine=0;
	var refineAllString="";
	for(i=0;i<profiles.length;i++) {
		var allConfirmation=true;
		// use only content part of profile
		var splitline=profiles[i].split("|");
		refineAllString=splitline[2].toUpperCase();
		matchesInLine=0;
		for(j=0;j<t.length;j++) {
			eval("myRE=/"+t[j]+"/gi");
			matchesArray=refineAllString.match(myRE);
			if(matchesArray!=null) {
				matchesInLine=matchesInLine+matchesArray.length;
			}
			else {
				allConfirmation=false;
			}
		}
		if(allConfirmation) {
			// Store only hits, title and URL
			myMatches[indexer]=(0-matchesInLine)+"|"+splitline[0]+"|"+splitline[3];
			indexer++;
		}
	}
	if(myMatches.length==0) {writeNoResultPage(text);return;}
	else {writeResultPage(myMatches,text);}
}

//*************************************************************
// If user wants exact phrase

// t: search term
// text: original search text

function doSearchExactPhrase(t,text) {
	var matchesInLine=0;
	var refineAllString="";
	for(i=0;i<profiles.length;i++) {
		// use only content part of profile
		var splitline=profiles[i].split("|");
		refineAllString=splitline[2].toUpperCase();
		matchesInLine=0;
		eval("myRE=/"+t+"/gi");
		matchesArray=refineAllString.match(myRE);
		if(matchesArray!=null) {
			// Store only hits, title and URL
			matchesInLine=matchesInLine+matchesArray.length;
			myMatches[indexer]=(0-matchesInLine)+"|"+splitline[0]+"|"+splitline[3];
			indexer++;
		}
	}
	if(myMatches.length==0) {writeNoResultPage(text);return;}
	else {writeResultPage(myMatches,text);}
}

//*************************************************************
// Write no-results page

// text: original search text, not needed here

function writeNoResultPage(text) {
	document.writeln("<div class=\"ftslist\">"+vResults+": 0</div>");
	return true;
}

//*************************************************************
// Write successfull search results page

// passedArray[i]: "-Treffer|Titel|URL"
// text: original search text, not needed here

function writeResultPage(passedArray, text) {
	var thisPageNum=(getQueryString("range")!="") ? parseInt(getQueryString("range")):1;
	var beginResult=maxResults*(thisPageNum-1)+1; // initially 1
	var endResult=(parseInt(beginResult+maxResults-1)<passedArray.length) ? parseInt(beginResult+maxResults-1):passedArray.length;
	// write result summary
	document.writeln("<div class=\"ftslist\">"+vResults+":<br>");
	document.writeln(beginResult+"-"+endResult+"&nbsp;/&nbsp;"+passedArray.length+"</div>");
	document.writeln("<hr size=\"1\" />");
	passedArray.sort(compare); // see compare function below
	// write result lines
	for(i=(beginResult-1);i<endResult;i++) {
		splitline=passedArray[i].split("|");
		rank=parseInt(splitline[0]);
		if(rank<0)rank=0-rank;
		document.writeln("<div class=\"ftslist\"><a href=\""+splitline[2]+"\">"+splitline[1]+" ("+rank+")</a></div>");
	}
	//write results page numbers
	if (passedArray.length>maxResults) {
		maxPageNum=parseInt(passedArray.length/maxResults);
		if(passedArray.length/maxResults>maxPageNum)maxPageNum++;
		var pageLinks="<img src=\"nav/arr-item.gif\" border=\"0\" alt=\"\">";
		for(i=0;i<maxPageNum;i++) {
			thisLocation=(location.href.indexOf("&range=")>-1) ? changeParam("range",parseInt(i+1)):location.href+"&range="+parseInt(i+1);
			pageLinks+=(parseInt(i+1)!=thisPageNum) ? "<a href=\""+thisLocation+"\" target=\"_self\">"+(i+1)+"</a> ":"["+(i+1)+"] ";
		}
		document.writeln("<hr size=\"1\" />");
		document.writeln("<div class=\"ftslist\">"+pageLinks+"</div>");
		document.writeln("<hr size=\"1\" />");
	} 
	clearOut();
}

//*************************************************************
// Clear the arrays and variables generated from the current search

function clearOut() {
	myMatches.length = 0;
	splitline.length = 0;
	indexer = 0;
	all = false;
}

//*************************************************************************
// This function will parse the URL search string and change a name/value pair

function changeParam(whichParam, newVal) {
	newParamStr = "";
	thisURLstr = document.location.href.substring(0, document.location.href.indexOf("?"));
	thisURLparamStr = document.location.href.substring(document.location.href.indexOf("?") + 1, document.location.href.length);
	//Build array out of thisURLparamStr using "&" as delimiter
	splitline=(thisURLparamStr.split("&"))
	for (cnt=0; cnt < splitline.length; cnt++) {
		splitparam = splitline[cnt].split("=")
		if (splitparam[0] == whichParam) {
			// if we find whichParam in thisURLparamStr replace whichParam's value with newVal
			newParamStr = newParamStr + splitparam[0] + "=" + escape(newVal) + "&";
		} else {
			//leave other parameters intact
			newParamStr = newParamStr + splitparam[0] + "=" + splitparam[1] + "&";
		}
	}
	//strip off trailing ampersand
	if (newParamStr.charAt(newParamStr.length - 1) == "&") newParamStr = newParamStr.substring(0, newParamStr.length - 1);
	//apply new URL
 	return(thisURLstr + "?" + newParamStr);
}

//*************************************************************
// Sorts search results based on 1.Number of hits 2.alphabetically

function compare(a, b) {
	if (parseInt(a) - parseInt(b) != 0) {
		return parseInt(a) - parseInt(b)
	}else {
		var aComp = a.substring(a.indexOf("|") + 1, a.length)
		var bComp = b.substring(b.indexOf("|") + 1, b.length)
		if (aComp < bComp) {return -1}
		if (aComp > bComp) {return 1}
		return 0
	}
}
