//This powers a local suggestion engine for job titles.
//We could use AJAX for this, but it seems like a really big waste of server and database CPU.
//Better to download all the titles (a few hundred at most) and sift through them on the client side.

var jobbox = document.getElementById("JobName");
var joblist = document.getElementById("JobID");
var lastval = "";

jobbox.onkeyup = suggestList;
jobbox.onkeypress = moveSelection;
jobbox.onfocus = function() { this.select(); }
joblist.onclick = function() { jobbox.focus(); setTimeout('doAutocomplete(joblist.selectedIndex)', 10); }

//Thanks to a bug in IE, we have to actually remove the options if they don't match.
//Store the complete list in a copy of the select element's tree.
var backuplist = new Array(joblist.options.length);
for (var optidx = 0; optidx < backuplist.length; optidx++) {
	backuplist[optidx] = new Option(joblist.options[optidx].text, joblist.options[optidx].value, false, false);
}

function getKeyCode(evt) {
	if (!evt) evt = window.event;
	if (evt.keyCode)
		return evt.keyCode;
	else if (evt.which)
		return evt.which;
	else
		return 0;
}

function doAutocomplete(listidx) {
	//Only up and down arrow presses get this far.
	if (joblist.options[listidx].value == 0)
		//Don't autocomplete the "create new job..." option.
		return;

	//This will also prevent the combo box from changing if we moved around it, which is good.
	jobbox.value = lastval = joblist.options[listidx].text;
	jobbox.select();
}

function moveSelection(evt) {
	//Check to see whether we're pressing an arrow key. If so, move the selection around.	
	var code = getKeyCode(evt);
	
	switch (code) {
		case 38:	//Up.
			if (joblist.selectedIndex > 0)
				joblist.selectedIndex--;
			break;
		case 40:	//Down.
			if (joblist.selectedIndex < joblist.options.length - 1)
				joblist.selectedIndex++;
			break;
		default:
			return true;		//If not an arrow, don't autocomplete.
	};
	
	doAutocomplete(joblist.selectedIndex);
	return false;
}

function suggestList() {
	//Check if we actually modified the text.
	if (this.value == lastval)
		return;

	//Add everything in the temp list back first...
	joblist.length = 0;
	for (var opt = 0; opt < backuplist.length; opt++) {
		try {
			//Compliant browsers.
			joblist.add(backuplist[opt], null);
		}
		catch (dummy) {
			//Nice job following the specs, IE.
			joblist.add(backuplist[opt], joblist.length);
		}
	}

	//Now remove what doesn't match.
	var optidx = 0;
	while (optidx < joblist.options.length) {
		var opt = joblist.options[optidx];
		if (opt.value != 0 && opt.text.substring(0, this.value.length).toLowerCase() != this.value.toLowerCase()) {
			joblist.remove(optidx);
		}
		else {
			optidx++;
		}
	}

	//Only set the selection index if the value actually changed.
	joblist.selectedIndex = 0;
	lastval = this.value;
}
