// --------------------------------------------------------
// Javascript functions needed for searchable lists.
//
// --------------------------------------------------------

/*
	returns 0 if str1 = str2, 
	1 if str1>str2, 
	-1 if str1<str2
*/
function compareStrings(str1, str2) {
	for(var i=0; i<str1.length; i++) {
		if(i >= str2.length) {
			return 1;
		}
		if(str1.charAt(i) > str2.charAt(i)) {
			return 1;
		}
		else if(str1.charAt(i) < str2.charAt(i)) {
			return -1;
		}
	}
	if(i < str2.length) {
		return -1;
	}
	return 0;
}

			
/**
 * Selects the item in list that most closely matches the contents of searchBox
 * @param searchBox: a form element containing the text to search for.
 * @param list: the list to search.
 */
function selectList(searchBox, list) {
	
	var searchStr = searchBox.value.toUpperCase();
	var listLen = list.options.length;
	var first = 0;
	var last = listLen-1;
	var curIndex = 0;
		
	while(first < last) {
		curIndex = Math.floor((first+last)/2);
		
		var compareVal;
		compareVal = compareStrings(searchStr, list.options[curIndex].text.toUpperCase());
		
		//alert("First: "+'first: '+list.options[first].text+"\n"+
		//	'Last: '+list.options[last].text+"\n"+
		//	"\""+searchStr+"\",\""+list.options[curIndex].text+"\", "+curLetter+" = "+compareVal);
		
		if(compareVal == -1) {
			if(curIndex == first || curIndex == last) {
				break;
			}
			last = curIndex;
		}
		else if(compareVal == 1) {
			if(curIndex == first || curIndex == last) {
				curIndex++;
				break;
			}
			first = curIndex;
		}
		else {
			break;
		}
	}
	
	list.selectedIndex = curIndex;
	
	//alert('first: '+list.options[first].text);
	//alert('last: '+list.options[last].text);

}

function submitenter(myfield,e,submitter) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13 && submitter != null) {
   		submitter.click();
   		return false;
   	}
	else
	   return true;
}