// 
// This code was written by Jason Wall.  Feel free to use, and if you can, include a link back to www.walljm.com
// Jason@walljm.com // www.walljm.com
//

function myFind() {
	find(document.getElementById("search").value);
}

function find(query) {
	query = query.toLowerCase();
	var qs = query.split(" ");
	var refs;
	var words = buildIndexArray().sort();
	var results = new Array();
	
	// Loop through each query term.
	for (i=0; i<qs.length; i++) 
	{
		var q = qs[i];
		// For each query term, figure out which xml file it is in, and get it.  
		//   getSearchRefs returns an array of references.  
		for (var w = 0; w < words.length; w++) 
		{
			// If we are at the end of the array, we want to use a different test.
			if (w == words.length) 
			{
				if (q >= words[w]) 
				{
					results.unshift(getSearchRefs("index/i" + words[w] + ".xml", q));
					break;
				}
			} else {
        if ( q>=words[w] && q<words[w+1] ) 
				{
    			results.unshift(getSearchRefs("index/i" + words[w] + ".xml", q));
					break;
        }
			}
		} 
	} // End of loop through query terms
	
	// Now we need to test results.  If there is more than one item in the array, we need to find the set 
	//  that is shared by all of them.  IF not, we can just return those refs.
	if (results.length == 1)
	{
		writeResults(results[0], query);
	} else {
	  writeResults(findSharedSet(results), query);
	}

  if (navigator.appName=="Netscape") 
  {
  	document.getElementById("searchresults").style.height = window.innerHeight-290 + "px;";
  }
	document.getElementById('ref').value += query+"; "; 
	return false;
}

function getSearchRefs(url, query) 
{ // getSearchRefs takes a url and uses ajax to retrieve the references and returns an array of references.
	
	var doc = loadXMLDocSync(url);
	var result = Array();	

	// find the right word
	var words = doc.getElementsByTagName("item");
	for (var i=0; i<words.length; i++)
	{
		if (words.item(i).getAttribute("word") == query) 
		{
			var refs = words.item(i).getElementsByTagName("ref");
			for (var j=0; j<refs.length; j++)
			{
				result.push([refs.item(j).getAttribute("b"), refs.item(j).getAttribute("ch"), refs.item(j).getAttribute("v")]); 
			}
			break;
		}
	}
	
	return result;
}


function writeResults(results, query) {
	// writeResults takes a single array of references and write out the html to the results div.
	document.getElementById("searchTotal").innerHTML = "(" + results.length + ")";
	var result = document.getElementById('searchresults');
	var text = "Query: <a href=\"#\" onclick=\"getQuery('" + query + "')\">'" + query + "'</a><ul>";
	for (var i =0; i<results.length; i++)
	{
		var r = results[i];
		text += "<li /><a href='#' onclick='getVersesByRef(" + r[0] + ", " + r[1] + ", " + r[2] + ", " + r[2] + "); return false;'>" + bookName(r[0]) + " " + r[1] + ":" + r[2] + "</a>";
	}
	text += "</ul>";
	result.innerHTML = text;
	return false;
}
	



function findSharedSet(results) {
// findSharedSet takes an array of reference arrays, and figures out which references are shared 
//  by all arrays/sets, then returns a single array of references.

	for (var j in results)
	{
		var refs = results[j];
		
		for (var i=0; i<refs.length; i++)
		{
			var r = refs[i];
			// convert references to single integers.
			//  Book * 100000, Chapter * 1000, Verse remains same, add all together.
			var ref = parseInt(r[0]) * 100000000;
			ref = ref + parseInt(r[1]) * 10000;
			ref = ref + parseInt(r[2]);
			results[j][i] = ref;
		}
	}
	
	// get the first result
	var result = results[0];
	
	// for each additional result, get the shared set
	for (var i=1; i<results.length; i++)
	{
		result = ReturnSharedSet(results[i], result);
	}
	
	// convert the references back into book, chapter and verse.
	for (var i=0; i<result.length; i++)
	{
		var ref = result[i];
		result[i] = [parseInt(ref/100000000), parseInt((ref%100000000)/10000), ((ref%100000000)%10000)];
	}
		
	return result;
}
function SortNumeric(x,y)
{
	return x-y
}
function ReturnSharedSet(x, y) {
/// <summary>
///  Takes two javascript arrays and returns an array
///  containing a set of values shared by arrays.
/// </summary>

  // declare iterator
  var i = 0;

  // declare terminator
  var t = (x.length < y.length) ? x.length : y.length
	
  // sort the arrays
  x.sort(SortNumeric);
  y.sort(SortNumeric);

  // in this loop, we remove from the arrays, the
  //  values that aren't shared between them.
  while ( i < t) {
    if (x[i] == y[i]) {
      i++;
    }
    if (x[i] < y[i]) {
      x.splice(i, 1);
    }
    if (x[i] > y[i]) {
      y.splice(i, 1);
    }
    t = (x.length < y.length) ? x.length : y.length;

  // we have to make sure to remove any extra values
    // at the end of an array when we reach the end of 
    // the other.
    if (t == i && t < x.length) { x.splice(i, x.length-i);}
    if (t == i && t < y.length) { y.splice(i, x.length-i);}
  }
  // we could return y, because at this time, both arrays
  // are identical.
  return x;
}

function buildIndexArray() 
{
	var words = new Array();
	words.unshift('abhorring');
  words.unshift('abinoam');
  words.unshift('abounding');
  words.unshift('acceptest');
  words.unshift('accuseth');
  words.unshift('acquainting');
  words.unshift('addeth');
  words.unshift('admonition');
  words.unshift('adulteries');
  words.unshift('affected');
  words.unshift('afterwards');
  words.unshift('aharah');
  words.unshift('ahio');
  words.unshift('aijalon');
  words.unshift('aliah');
  words.unshift('alms');
  words.unshift('amad');
  words.unshift('amerce');
  words.unshift('amos');
  words.unshift('ancestors');
  words.unshift('annas');
  words.unshift('antothite');
  words.unshift('apostleship');
  words.unshift('apples');
  words.unshift('arabia');
  words.unshift('ardites');
  words.unshift('ark');
  words.unshift('array');
  words.unshift('asarelah');
  words.unshift('ashkelon');
  words.unshift('aspatha');
  words.unshift('assurance');
  words.unshift('athenians');
  words.unshift('augment');
  words.unshift('await');
  words.unshift('azem');
  words.unshift('baana');
  words.unshift('backslider');
  words.unshift('balah');
  words.unshift('baptism');
  words.unshift('bark');
  words.unshift('basin');
  words.unshift('bazluth');
  words.unshift('beauties');
  words.unshift('beelzebub');
  words.unshift('beggar');
  words.unshift('beholdeth');
  words.unshift('belong');
  words.unshift('benjamite');
  words.unshift('berothai');
  words.unshift('bethel');
  words.unshift('bewailed');
  words.unshift('bilhah');
  words.unshift('biteth');
  words.unshift('blasphemers');
  words.unshift('blind');
  words.unshift('boanerges');
  words.unshift('bold');
  words.unshift('booties');
  words.unshift('boughs');
  words.unshift('bracelet');
  words.unshift('breakest');
  words.unshift('bride');
  words.unshift('broken');
  words.unshift('bucklers');
  words.unshift('bulwarks');
  words.unshift('bush');
  words.unshift('cab');
  words.unshift('calleth');
  words.unshift('canaanitish');
  words.unshift('carbuncle');
  words.unshift('carpenter');
  words.unshift('casteth');
  words.unshift('ceased');
  words.unshift('chain');
  words.unshift('changers');
  words.unshift('chariots');
  words.unshift('chedorlaomer');
  words.unshift('cherished');
  words.unshift('child');
  words.unshift('choosest');
  words.unshift('cinnamon');
  words.unshift('claudius');
  words.unshift('climb');
  words.unshift('cluster');
  words.unshift('color');
  words.unshift('comings');
  words.unshift('commonly');
  words.unshift('compassed');
  words.unshift('conceit');
  words.unshift('condition');
  words.unshift('confirming');
  words.unshift('consent');
  words.unshift('consultation');
  words.unshift('content');
  words.unshift('convert');
  words.unshift('cord');
  words.unshift('corruptly');
  words.unshift('countenances');
  words.unshift('covenants');
  words.unshift('crag');
  words.unshift('cried');
  words.unshift('crowns');
  words.unshift('cups');
  words.unshift('cuth');
  words.unshift('dalmatia');
  words.unshift('darda');
  words.unshift('dawning');
  words.unshift('deaths');
  words.unshift('deceiver');
  words.unshift('decrees');
  words.unshift('defer');
  words.unshift('deliciously');
  words.unshift('den');
  words.unshift('descendeth');
  words.unshift('despair');
  words.unshift('determinate');
  words.unshift('dew');
  words.unshift('diggedst');
  words.unshift('dip');
  words.unshift('disciple');
  words.unshift('disguised');
  words.unshift('displease');
  words.unshift('dissolvest');
  words.unshift('divideth');
  words.unshift('doers');
  words.unshift('doubled');
  words.unshift('drawers');
  words.unshift('drinking');
  words.unshift('drunken');
  words.unshift('dwellers');
  words.unshift('earthquakes');
  words.unshift('edar');
  words.unshift('eglon');
  words.unshift('elder');
  words.unshift('eliashib');
  words.unshift('elishua');
  words.unshift('elymas');
  words.unshift('emptied');
  words.unshift('encumbereth');
  words.unshift('enfolding');
  words.unshift('enos');
  words.unshift('entrance');
  words.unshift('ephesian');
  words.unshift('eranites');
  words.unshift('eshcol');
  words.unshift('esteeming');
  words.unshift('euroclydon');
  words.unshift('evilfavoredness');
  words.unshift('exceeding');
  words.unshift('execution');
  words.unshift('expound');
  words.unshift('ezbon');
  words.unshift('fainted');
  words.unshift('familiar');
  words.unshift('fasted');
  words.unshift('favorable');
  words.unshift('feedest');
  words.unshift('fence');
  words.unshift('fifteenth');
  words.unshift('filthy');
  words.unshift('firstfruit');
  words.unshift('flags');
  words.unshift('fleshhooks');
  words.unshift('floweth');
  words.unshift('followeth');
  words.unshift('forbore');
  words.unshift('foreseeth');
  words.unshift('forgiveness');
  words.unshift('fort');
  words.unshift('fountains');
  words.unshift('freed');
  words.unshift('front');
  words.unshift('fully');
  words.unshift('gad');
  words.unshift('galilaeans');
  words.unshift('garmite');
  words.unshift('gaze');
  words.unshift('genealogy');
  words.unshift('geshurites');
  words.unshift('gideon');
  words.unshift('girding');
  words.unshift('glass');
  words.unshift('gnasheth');
  words.unshift('gog');
  words.unshift('gorgeously');
  words.unshift('grasshopper');
  words.unshift('greediness');
  words.unshift('grinding');
  words.unshift('guests');
  words.unshift('habergeons');
  words.unshift('hadst');
  words.unshift('hakupha');
  words.unshift('hammer');
  words.unshift('handkerchiefs');
  words.unshift('hanun');
  words.unshift('hare');
  words.unshift('harpers');
  words.unshift('hashum');
  words.unshift('hateth');
  words.unshift('hazael');
  words.unshift('healed');
  words.unshift('hearth');
  words.unshift('hedged');
  words.unshift('helez');
  words.unshift('hena');
  words.unshift('heresy');
  words.unshift('hewed');
  words.unshift('higher');
  words.unshift('hiram');
  words.unshift('hodaiah');
  words.unshift('holy');
  words.unshift('hopeth');
  words.unshift('horseback');
  words.unshift('household');
  words.unshift('humiliation');
  words.unshift('hurl');
  words.unshift('hypocrisy');
  words.unshift('idolatry');
  words.unshift('imagined');
  words.unshift('impoverish');
  words.unshift('increasest');
  words.unshift('inflicted');
  words.unshift('inkhorn');
  words.unshift('instructor');
  words.unshift('into');
  words.unshift('is');
  words.unshift('islands');
  words.unshift('ithmah');
  words.unshift('jaalam');
  words.unshift('jadon');
  words.unshift('jakeh');
  words.unshift('jarkon');
  words.unshift('jeaterai');
  words.unshift('jehieli');
  words.unshift('jehudijah');
  words.unshift('jerimoth');
  words.unshift('jesse');
  words.unshift('jeziah');
  words.unshift('joed');
  words.unshift('jona');
  words.unshift('josiphiah');
  words.unshift('juda');
  words.unshift('justification');
  words.unshift('kedemoth');
  words.unshift('kernels');
  words.unshift('kindle');
  words.unshift('kishion');
  words.unshift('knocketh');
  words.unshift('laban');
  words.unshift('lady');
  words.unshift('lancets');
  words.unshift('lasea');
  words.unshift('lawfully');
  words.unshift('leannoth');
  words.unshift('led');
  words.unshift('leopard');
  words.unshift('lewdly');
  words.unshift('liest');
  words.unshift('lign');
  words.unshift('lintels');
  words.unshift('lo');
  words.unshift('lofty');
  words.unshift('lords');
  words.unshift('lowering');
  words.unshift('lusty');
  words.unshift('maaziah');
  words.unshift('magicians');
  words.unshift('mahol');
  words.unshift('maktesh');
  words.unshift('manaen');
  words.unshift('maoch');
  words.unshift('marred');
  words.unshift('masrekah');
  words.unshift('matthew');
  words.unshift('measured');
  words.unshift('meet');
  words.unshift('melita');
  words.unshift('mentioned');
  words.unshift('merodach');
  words.unshift('messes');
  words.unshift('michmash');
  words.unshift('mijamin');
  words.unshift('minds');
  words.unshift('mirth');
  words.unshift('missing');
  words.unshift('mock');
  words.unshift('moneychangers');
  words.unshift('mosera');
  words.unshift('mouths');
  words.unshift('munition');
  words.unshift('mustereth');
  words.unshift('nabal');
  words.unshift('naioth');
  words.unshift('naturally');
  words.unshift('nebo');
  words.unshift('neglecting');
  words.unshift('nephtoah');
  words.unshift('new');
  words.unshift('nineteenth');
  words.unshift('noon');
  words.unshift('nourishing');
  words.unshift('obed');
  words.unshift('obtained');
  words.unshift('offenses');
  words.unshift('oldness');
  words.unshift('ono');
  words.unshift('oppress');
  words.unshift('ordinary');
  words.unshift('our');
  words.unshift('overcometh');
  words.unshift('overtaken');
  words.unshift('ozias');
  words.unshift('palace');
  words.unshift('paphos');
  words.unshift('part');
  words.unshift('pass');
  words.unshift('patience');
  words.unshift('peaceable');
  words.unshift('pelonite');
  words.unshift('perfect');
  words.unshift('perizzite');
  words.unshift('persons');
  words.unshift('pethor');
  words.unshift('philemon');
  words.unshift('pictures');
  words.unshift('pine');
  words.unshift('pithon');
  words.unshift('planters');
  words.unshift('please');
  words.unshift('plucketh');
  words.unshift('pommels');
  words.unshift('portray');
  words.unshift('pound');
  words.unshift('pray');
  words.unshift('prepare');
  words.unshift('presume');
  words.unshift('princess');
  words.unshift('prochorus');
  words.unshift('progenitors');
  words.unshift('prophesyings');
  words.unshift('proverb');
  words.unshift('psalm');
  words.unshift('pulse');
  words.unshift('purim');
  words.unshift('puttest');
  words.unshift('quickened');
  words.unshift('rachal');
  words.unshift('raiser');
  words.unshift('ransomed');
  words.unshift('readeth');
  words.unshift('rebel');
  words.unshift('reckoned');
  words.unshift('redeemedst');
  words.unshift('refuse');
  words.unshift('reigneth');
  words.unshift('remainest');
  words.unshift('rendered');
  words.unshift('repentest');
  words.unshift('reproofs');
  words.unshift('reserve');
  words.unshift('restoreth');
  words.unshift('revealeth');
  words.unshift('revolt');
  words.unshift('richly');
  words.unshift('rinsed');
  words.unshift('roaring');
  words.unshift('rohgah');
  words.unshift('rottenness');
  words.unshift('ruins');
  words.unshift('s');
  words.unshift('sadducees');
  words.unshift('salcah');
  words.unshift('samaritans');
  words.unshift('sapphire');
  words.unshift('satyr');
  words.unshift('scabbed');
  words.unshift('scoff');
  words.unshift('scribes');
  words.unshift('seas');
  words.unshift('seduced');
  words.unshift('seir');
  words.unshift('sending');
  words.unshift('serah');
  words.unshift('settest');
  words.unshift('shaalbonite');
  words.unshift('shalim');
  words.unshift('shammah');
  words.unshift('sharpeneth');
  words.unshift('sheaves');
  words.unshift('sheepskins');
  words.unshift('shemidaites');
  words.unshift('sheth');
  words.unshift('shimeath');
  words.unshift('shiphrah');
  words.unshift('shoco');
  words.unshift('shoulders');
  words.unshift('shubael');
  words.unshift('sibbecai');
  words.unshift('sighs');
  words.unshift('silverlings');
  words.unshift('single');
  words.unshift('sitnah');
  words.unshift('skippedst');
  words.unshift('sleeper');
  words.unshift('slowly');
  words.unshift('smooth');
  words.unshift('soberness');
  words.unshift('sold');
  words.unshift('soothsayer');
  words.unshift('sosipater');
  words.unshift('space');
  words.unshift('spears');
  words.unshift('spikenard');
  words.unshift('spokes');
  words.unshift('sprinkled');
  words.unshift('stalled');
  words.unshift('staves');
  words.unshift('steward');
  words.unshift('stocks');
  words.unshift('storehouse');
  words.unshift('strangled');
  words.unshift('striker');
  words.unshift('struck');
  words.unshift('subjection');
  words.unshift('suchathites');
  words.unshift('summer');
  words.unshift('supply');
  words.unshift('sustenance');
  words.unshift('swellings');
  words.unshift('syntyche');
  words.unshift('tachmonite');
  words.unshift('tales');
  words.unshift('tarea');
  words.unshift('taunting');
  words.unshift('tekoa');
  words.unshift('temple');
  words.unshift('teresh');
  words.unshift('thahash');
  words.unshift('themselves');
  words.unshift('thick');
  words.unshift('thirteenth');
  words.unshift('threatening');
  words.unshift('throughout');
  words.unshift('tidings');
  words.unshift('timnathserah');
  words.unshift('tittle');
  words.unshift('tolerable');
  words.unshift('tormentors');
  words.unshift('trading');
  words.unshift('translated');
  words.unshift('treason');
  words.unshift('tribulations');
  words.unshift('troublest');
  words.unshift('tubal');
  words.unshift('twins');
  words.unshift('uncircumcised');
  words.unshift('undertook');
  words.unshift('unleavened');
  words.unshift('unsearchable');
  words.unshift('upbraideth');
  words.unshift('uriel');
  words.unshift('uzai');
  words.unshift('vaniah');
  words.unshift('venture');
  words.unshift('vilely');
  words.unshift('virtuous');
  words.unshift('vowedst');
  words.unshift('waketh');
  words.unshift('wanton');
  words.unshift('wash');
  words.unshift('watchtower');
  words.unshift('wayfaring');
  words.unshift('weather');
  words.unshift('well');
  words.unshift('when');
	words.unshift('which');
  words.unshift('whips');
  words.unshift('whoremongers');
  words.unshift('willing');
  words.unshift('winneth');
  words.unshift('withdraw');
  words.unshift('wives');
  words.unshift('woods');
  words.unshift('worshiped');
  words.unshift('wrath');
  words.unshift('wrongeth');
  words.unshift('yoke');
  words.unshift('zaccai');
  words.unshift('zareth');
  words.unshift('zedad');
  words.unshift('zereda');
  words.unshift('ziklag');
  words.unshift('zoba');
	return words;
}
