/****************************************************************************
 * Author: Joe Reynoldson
 * Date: 12/1/05
 * Description: The following code searches organisms by calling a CGI program
 * on the server and loading the results into a div on the page.
 * *************************************************************************/

var aSleep = false;
var lastQuery = '';

function processMsg()
{
	document.getElementById('msgTag').innerHTML = 'Searching....';
	document.getElementById('msgTag').style.background = '#444';
}

function doneMsg()
{
	document.getElementById('msgTag').innerHTML = '&nbsp;';
	document.getElementById('msgTag').style.background = '#fff';
}

function compareStrings(a, b) {
  if ( a < b ) return -1;
  if ( a > b ) return 1;
  return 0;
}

function loadMatches( divID, org_list )
{
	var divObj = document.getElementById('result_list');
	divObj.innerHTML = '';
	var i = 0;
	var orgs = new Array();
	for (org in org_list)
	{
		orgs[i++] = org;
	}
	orgs.sort();
	for (i = 0; i < orgs.length; i++)
	{
		var matchElem = "<div class='match_item' ";
		matchElem += "onclick=\"addRow('blast_db',document.match_list['"+orgs[i]+"'])\" ";
		matchElem += "onmouseover=\"this.className='highlighted'\" ";
		matchElem += "onmouseout=\"this.className='match_item'\">";
		matchElem += orgs[i] + "</div>\n";
		divObj.innerHTML += matchElem;
	}
	divObj.style.display = "block";
	document.getElementById('msgTag').innerHTML = '&nbsp;';
	document.getElementById('msgTag').style.background = '#fff';
}

function search( keyPressed, queryID )
{
	var thisQuery = document.getElementById(queryID).value;

	if(thisQuery == "") return false; //doesn't work?

	// don't update the match list immediately after a keystroke
	// set the timeout, and wait to see if the query string changes
	if(keyPressed){
		aSleep = true;
		setTimeout("search(false,'" + queryID + "')",250);
	}
	// called by timeout, so check to see if the query has changed
	// and do nothing if it hasn't
	else if( thisQuery != lastQuery ){
		// if still sleeping, set a timeout to try again later
		if(aSleep){
			aSleep = false;
			setTimeout("search(false,'" + queryID + "')",250);
		}
		// not sleeping, build a script element and write it to the div
		else{
			var scriptUrl = "matchOrganism.cgi?query_string=" + thisQuery;
			new net.ContentLoader(scriptUrl,evalScript);
			lastQuery = thisQuery;
		}
	}
}

/** Taken from AJAX in Action: evaluates the javascript returned by the CGI
 * program loading the JS into the page context */
function evalScript()
{
	var script = this.req.responseText;
	eval(script);
}

/** clear button callback
 *  clears current search results */
function clearSearch(){
	document.getElementById('query_string').value = '';
	document.getElementById('result_list').innerHTML = '&nbsp;';
	document.getElementById('result_list').style.display = "none";
	return false;
}
