
/*
 * File: search.js
 * Auth: C.Wharton, SRA 1/9/2004
 * Desc: Javascript to manage a textbox and menu item that provide
 *       'incremental' searches - as the user types letters in the
 *       textbox the menu shrinks to only display entries starting
 *       with those letters. 
 *       Derived from this code:
 *         http://www.activewidgets.com/messages/121-3.htm
 *
 */

// Build the initial list, either because is first time
// page has been displayed, or because textbox does not
// contain any search characters yet
function bldInitial() {
	/* OLD VERSION - STARTS WITH EMPTY LIST
	document.forms[this.formname][this.selname].options.length = 0
	*/

	/* NEW VERSION - START WITH FULL LIST */
	for (var i=0; i<this.optionSet.length; i++) {
		document.forms[this.formname][this.selname].options[i]
			= new Option(this.optionSet[i].text, this.optionSet[i].value);
	}
	document.forms[this.formname][this.selname].options.length = i;
	document.forms[this.formname][this.textname].focus()
}

// Invoked whenever a user presses a key in the textbox. Updates
// the menu item to only show those entries that start with the
// letters in the textbox
function bldUpdate() {
// alert("value = " + document.forms[this.formname][this.textname].value);
	var str = document.forms[this.formname][this.textname].value.replace(/^\s*/,'');
	// No characters left - reset to initial state
	if(str == '') {
		this.bldInitial()
	// Characters found
	} else {
		var j = 0;
		pattern1 = new RegExp("^"+str,"i");
		// Iterate through all options in array, copying into new
		// menu item if they match characters in search textbox
		for(var i=0;i<this.optionSet.length;i++) {
			if(pattern1.test(this.optionSet[i].text)) {
				document.forms[this.formname][this.selname].options[j++]
				= new Option(this.optionSet[i].text, this.optionSet[i].value);
			} else {
				// remove following line if list is not ordered by its text
				if(j>0) { break; }
			}
		}
		document.forms[this.formname][this.selname].options.length=j;
	}
}

// Initialise global variables holding the names of the
// form items we will be working with
function setUp() {
	// menuform is the name of the form you use
	// itemlist is the name of the select pulldown menu you use
	// entry is the name of text box you use for typing in
	this.formname = 'frmSearch';
	this.selname = 'intChemicalId';
	this.textname = 'strChemicalName';
	this.bldInitial(); 
}

