// parse searchPhrase.js wordlist array into two-dimensional array (from faked 2D array of strings) for faster searching and for adding word variants to second-dimensional array entry:
for(i=0; i<wordArray.length; i++){
	tempVariants = wordArray[i].split("|");
	wordArray[i] = tempVariants;
}

timeoutID = "";
timesThrough = 0;
// load requested definition file - if definitions frame is not currently loaded, open file and wait until it is loaded to load defintion..
function loadDefFile(theFile){
	// check if definitions frame is loaded..
	if(!parent.toc.word_info){
		if(timesThrough == 0){
			parent.toc.location.href = "frameset_dic.htm";
		}
		timeoutID = setTimeout("loadDefFile('"+theFile+"')",250);
	} else {
		timesThrough = 0;
		if(timeoutID != ""){
			clearTimeout(timeoutID);
		}
		if(theFile.indexOf("/index.htm") >= 0){
			parent.toc.word_info.location.href = theFile;
		} else if(theFile == "search_results"){
			parent.toc.word_info.location.href = "about/search_results.htm";
		} else {
			parent.toc.word_info.location.href = theFile.charAt(0)+"/"+theFile;
		}
	}
	timesThrough++;
}

// parses wordArray looking for a match to search phrase..
function getDefFilename(searchPhrase){
	// parse variants for each entry of wordArray, if one matches then return filename..
	for(i=0; i<wordArray.length; i++){
		for(j=0; j<wordArray[i].length; j++){
			if(wordArray[i][j].toLowerCase() == searchPhrase.toLowerCase()){
				// convert first entry of word variants to usable filename - replace spaces with "_" and append ".htm"
				splitWord = wordArray[i][0].split("");
				for(k=0;k<splitWord.length;k++){
					if(splitWord[k] == " "){
						splitWord[k] = "_";
					}
				}
				return splitWord.join("")+".htm";
			}
		}
	}
	// haven't found the word at this point, so we'll try some pattern matching, etc.  This will take more processing time, so we need to make sure that it doesn't take TOO much time before it fails.
	
	// array to store words which are closely related to searchPhrase, according to Levenshtein Distance algorithm..
	closeMatchArr = new Array();
	var prevMatch = -1;
	for(i=0; i<wordArray.length; i++){
		for(j=0; j<wordArray[i].length; j++){
			// check Levenshtein Distance between searchPhrase and each entry of searchPhraseList..
			var dist = LD(searchPhrase, wordArray[i][j]);
			if(dist <= 2){
				closeMatch = i + "|" + dist;
				// only enter one entry for each word (if variants of that word are also matches for searchPhrase)..
				if(i != prevMatch){
					closeMatchArr.push(closeMatch);
				}
				prevMatch = i;
			}
		}
	}
	if(closeMatchArr.length){
		return closeMatchArr;
	} else {
		// If doesn't come up with anything, then fail gracefully.
		return "";
	}
}

// redirect def_list frame to definition matching search phrase (if such exists)..
function redirect(){
	// reset timesThrough..
	timesThrough = 0;
	searchPhrase = document.forms[0].Keycode.value;
	searchPhrase = searchPhrase.replace(/^\s*/, "").replace(/\s*$/, "");
	if(searchPhrase == null || searchPhrase == ""){
		alert("You must enter a search phrase.");
		return false;
	}
	filename = getDefFilename(searchPhrase.toLowerCase());
	// if searchPhrase is an exact match, send user directly to that word..
	if( typeof(filename) != "object" && filename != ""){
		loadDefFile(filename);
	// if searchPhrase is close to one (or more) of our words
	} else if(typeof(filename) == "object"){
		// if searchPhrase is close to only ONE word, send user to that word..
		if(filename.length == 1){
			// pull this close match from searchPhrase wordArray..
			var tempArr = filename[0].split('|');
			var tempWord = wordArray[tempArr[0]][0];
			// replace any spaces in word with underscores..
			splitWord = tempWord.split("");
			for(k=0;k<splitWord.length;k++){
				if(splitWord[k] == " "){
					splitWord[k] = "_";
				}
			}
			loadDefFile( splitWord.join("") + '.htm' );
		// else if multiple possibilities, give user choice to go to those words..
		} else {
			loadDefFile("search_results");
		}
	// otherwise give alert() error message and redirect to word list for first letter of search phrase..
	} else {
		alert("\"" + searchPhrase + "\" cannot be found.");
		theLetter = searchPhrase.toLowerCase().substring(0,1);
		if(theLetter >= "a" && theLetter <= "z"){
			loadDefFile(theLetter + "/index.htm")
		}
		return false;
	}
}

// subroutine of LD(), determines matrix value
function Minimum(a, b, c) {
	var mi;
	mi = a;
	if (b < mi)
		mi = b;
	if (c < mi)
		mi = c;
	return mi;
}

// determine the Levenshtein Distance between two words (s and t) - derived from code by Lukasz Stilger
function LD(word1, word2) {
	var d = new Array();
	var n; // length of word1
	var m; // length of word2
	var i; // iterates through s
	var j; // iterates through t
	var word1_i; // ith character of s
	var word2_j; // jth character of t
	var cost; // cost

	// Step 1 - initialize variables
	n = word1.length;
	m = word2.length;
	if (n == 0) {
		return m;
	}
	if (m == 0) {
		return n;
	}
	// create array for matrix
	for(i=0; i<=n; i++){
		d[i] = new Array();
	}
	// Step 2 - initialize matrix
	for (i = 0; i <= n; i++) {
		d[i][0] = i;
	}
	for (j = 0; j <= m; j++) {
		d[0][j] = j;
	}
	// Step 3 - examine each character of word1
	for (i = 1; i <= n; i++) {
		word1_i = word1.charAt(i - 1);
		// Step 4 - examine each character of word2
		for (j = 1; j <= m; j++) {
			word2_j = word2.charAt(j - 1);
			// Step 5 - determine costs
			if (word1_i == word2_j) {
				cost = 0;
			} else {
				cost = 1;
			}
			// Step 6 - set matrix values
			d[i][j] = Minimum(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + cost);
		}
	}
	// Step 7 - return Levenshtein Distance
	return d[n][m];
}

