/*
	USAGE:  link in js file and call InitSelectFilter("selectid", "textid") passing 
	in the correct ids of the fields.  You can call InitSelectFilter multiple times if
	you have multiple select boxes on the page.
*/

/*
The KISS plan:  Copy all select options into a separate location, then clear the 
select list and copy the ones that match the filter back into the select.

We'll try something fancier if that turns out to be too slow.
*/

function linkFunctions(functionOne, functionTwo)
{
	return function(){
		if(functionOne){
			functionOne();
		}
		if(functionTwo){
			functionTwo();
		}
	}
}

function copyArray(source){
	var newArray = new Array(source.length);

	for(var i=0; i<source.length; i++){
		newArray[i] = source[i];
	}
	
	return newArray;
}

function addFilteredOptions(selectElement, optionArray, filter){
	selectElement.options.length=0;

	for(var i=0; i<optionArray.length; i++){
		if(startsWith(optionArray[i].text, filter)){
			selectElement.add(optionArray[i]);
		}
	}
}

function startsWith(search, prefix){
	if(prefix.length == 0){
		return true;
	}
	
	return search.substr(0, prefix.length) == prefix;
}


function InitSelectFilter(selectId, textId){
	var selectElement = document.getElementById(selectId);
	var textElement = document.getElementById(textId);
	
	var allOptions = copyArray(selectElement.options);
	addFilteredOptions(selectElement, allOptions, textElement.value.toUpperCase());

	textElement.onkeyup = linkFunctions(
		function(){
			var filterElement = (event.target) ? event.target: event.srcElement;
			addFilteredOptions(selectElement, allOptions, filterElement.value.toUpperCase());
			
			//alert(selectElement.options.length) ;
			if (selectElement.options.length == 1) {
				if ((selectElement.options(0).text != "No Compressor Selected") &&
					(selectElement.options(0).text != "Select a Model")) {
						//alert("Here:  " + document.all.item("selModel").options(0).text) ;
						__doPostBack('selModel','')
				}
			}
		},
		textElement.onkeyup
	)
}


