
// Search and search complete JavaScript

var searchboxInFocus = false;
var uncompletedTerm = "";
var uncompletedTermInBox = false;

function autocomp(input, dictionary, searchBoxDiv, formId){
	uncompletedTerm = input;
	var request = createRequest();
	request.open('GET', "/AutoComplete.bsci?input=" + encodeURIComponent(input) + "&dictionary=" + dictionary, true);
	request.onreadystatechange = function(){autocompleteResponse(request, dictionary, searchBoxDiv, formId);};
	request.send(null);
}

// Helper function for autocomp

function createRequest(){
	var ajaxRequest; 
	try {
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		try {
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e)	{
			try {
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e)	{
				alert("Your browser does not support Ajax.  Please update your browser");
			}
		}
	}
	return ajaxRequest;
}

// Callback function when backend returns from the autosuggest server script



function autocompleteResponse(request, dictionary, searchBoxDivId, formId){
	// Return list
	
	if (request.readyState == 4){
		if (request.status == 200){
						
			var dictionary = dictionary.toLowerCase();
		
			// get data from server
			var xmlDoc = request.responseXML.documentElement;
			var mySuggestions = xmlDoc.getElementsByTagName("li");
						
			// get suggestions Div on page
			var searchBoxDiv = document.getElementById(searchBoxDivId);
			var suggestionsDiv = getElementsByClassName(searchBoxDiv,"autocomplete_" + dictionary + "_suggestions")[0];
				

			// clear out old data
			while (suggestionsDiv.firstChild){
				suggestionsDiv.removeChild(suggestionsDiv.firstChild);
			}

			// change class based on whether or not there is data
			if (mySuggestions.length > 0){
				suggestionsDiv.className = "autocomplete_" + dictionary + "_suggestions nonempty";
			} else {
				suggestionsDiv.className = "autocomplete_" + dictionary + "_suggestions empty";
			}

			// for each suggestion create a new div with that suggestion in it
			for (var i = 0; i < mySuggestions.length; i++){
				var newElement = document.createElement("div");
				newElement.id = searchBoxDivId + "_" + i;
				newElement.className = "autocompleteChoice";
				var newNode = document.createTextNode(mySuggestions[i].firstChild.nodeValue);
				newElement.appendChild(newNode);
				suggestionsDiv.appendChild(newElement);
			}

			for (var i = 0; i < mySuggestions.length; i++){
				document.getElementById(searchBoxDivId + "_" + i).onmouseover = new Function('autocompleteHighlight(' + i + ',' + mySuggestions.length + ',\'' + searchBoxDivId + '\')');
				document.getElementById(searchBoxDivId + "_" + i).onclick = new Function('autocompleteSelect(' + i + ',\'' + dictionary + '\',\'' + searchBoxDivId + '\',\'' + formId + '\')'); 
			}
			
			searchBoxDiv.getElementsByTagName('div')[0].scrollTop = 0;

		} else if (request.status != 0) {
			alert("Error!  Server unavailable.");
		}
	}
}


// controls highlighting as user rolls mouse over autocomplete choices

function autocompleteHighlight(selected, total, searchBoxDivId){
	document.getElementById(searchBoxDivId + "_" + selected).className = "selectedAutocompleteChoice";
	for (var i = 0; i < total; i++){
		if (i != selected)
			document.getElementById(searchBoxDivId + "_" + i).className = "autocompleteChoice";
	}
}

// controls selection of autocomplete choices when user selects one

function autocompleteSelect(selected, dictionary, searchBoxDivId, formId){

	
	var searchBoxDiv = document.getElementById(searchBoxDivId);
	var suggestionsDiv = getElementsByClassName(searchBoxDiv, "autocomplete_" + dictionary + "_suggestions")[0];

	var text = document.getElementById(searchBoxDivId + '_' + selected).firstChild.nodeValue;
	getElementsByClassName(searchBoxDiv, 'search')[0].value = text;

	// clear out old data
	while (suggestionsDiv.firstChild){
		suggestionsDiv.removeChild(suggestionsDiv.firstChild);
	}

	suggestionsDiv.className = "autocomplete_" + dictionary + "_suggestions empty";
	
	// call the normal search, as if button was clicked
	search(formId);
	
}


function searchAssistFocus(searchBoxDivId){
	var searchBoxDiv = document.getElementById(searchBoxDivId);
	getElementsByClassName(searchBoxDiv, 'search')[0].className = 'search searchAssistFocus';
}

function searchAssistBlur(searchBoxDivId){
	var searchBoxDiv = document.getElementById(searchBoxDivId);
	getElementsByClassName(searchBoxDiv, 'search')[0].className = 'search';
}

  function search(form){
	  var searchForm = document.getElementById(form);
	  var searchFieldValue = getElementsByClassName(searchForm,'search')[0].value;
	  var errMsgDiv = document.getElementById("ErrMsgLessThanThree");
	  
	  if(!searchFieldValue == ''){
		  searchForm.currentPage.value="1";
		  if (searchFieldValue.length < 3) {
			  window.alert(errMsgDiv.innerHTML);
		  } else {
			  searchForm.submit();
		  }  
  	}
  }

  // Not supported in IE6 so we have to manually define
  
  function getElementsByClassName(node, classname)
  {
      var a = [];
      var re = new RegExp('\\b' + classname + '\\b');
      var els = node.getElementsByTagName("*");
      for(var i=0,j=els.length; i<j; i++)
          if(re.test(els[i].className))a.push(els[i]);

      return a;
}
  
  
  function page(page) {
	 document.getElementById("SearchFormMain").currentPage.value=page;
	 document.getElementById("SearchFormMain").submit();
  }
  
  
  function searchtextFocus() {
  	searchboxInFocus = true;
  }
  
  function searchtextBlur(){
  	searchboxInFocus = false;
}

// Can scroll with arrow keys
function keypress (event, search_div) {
	//alert('keypress!  keyCode: ' + event.keyCode);
	if (event.keyCode == 38){
		up(search_div);
	} else  {
		if (event.keyCode == 40)
			down(search_div);
	}
}

// if there is a selected div and it is not the top div, then move the selected one one up
// if there is a selected div and it is top, then use the non autocompleted one
// if after that up is hit again, then scroll around to the last term
// if there is no selected div, make the first element selected

function up (search_div_name){
	if (searchboxInFocus){
		var search_div = document.getElementById(search_div_name);
		var dropdownbox = search_div.getElementsByTagName('div')[0];
		var inputbox = search_div.getElementsByTagName("input")[0];
		var options = dropdownbox.childNodes;

		for (var i = 0; i < options.length; i++){

			if (options[i].className == "selectedAutocompleteChoice"){
				if (i > 0){
					options[i].className = "autocompleteChoice";
					options[i-1].className = "selectedAutocompleteChoice";
					inputbox.value = options[i-1].firstChild.nodeValue;
					dropdownbox.scrollTop -= 15;		
				} else {
					if (uncompletedTermInBox){
						options[0].className = "autocompleteChoice";
						options[options.length - 1].className = "selectedAutocompleteChoice";
						inputbox.value = options[options.length - 1].firstChild.nodeValue;
						dropdownbox.scrollTop = (options.length - 1) * 15;
						uncompletedTermInBox = false;
					} else {
						inputbox.value = uncompletedTerm;
						uncompletedTermInBox = true;
						dropdownbox.scrollTop = (options.length - 1) * 15;
					}
				}
				return;
			} 
		}
		options[0].className = "selectedAutocompleteChoice";
		inputbox.value = options[0].firstChild.nodeValue;
	}
}

// if there is a selected div and it is not the bottom div, then move the selected one one down
// if there is a selected div and it is the bottom, then use the non autocompleted one
// if after that down is hit again, then scroll around to the first term
// if there is no selected div, make the first element selected

function down(search_div_name) {
	if (searchboxInFocus){
		var search_div = document.getElementById(search_div_name);
		var dropdownbox = search_div.getElementsByTagName('div')[0];
		var inputbox = search_div.getElementsByTagName("input")[0];
		var options = dropdownbox.childNodes;
		
		for (var i = 0; i < options.length; i++){
			if (options[i].className == "selectedAutocompleteChoice"){
				if (i < options.length - 1){
					options[i].className = "autocompleteChoice";
					options[i+1].className = "selectedAutocompleteChoice";
					inputbox.value = options[i+1].firstChild.nodeValue;
					dropdownbox.scrollTop += 15;		
				} else {
					if (uncompletedTermInBox){
						options[options.length - 1].className = "autocompleteChoice";
						options[0].className = "selectedAutocompleteChoice";
						inputbox.value = options[0].firstChild.nodeValue;				
						dropdownbox.scrollTop = 0;
						uncompletedTermInBox = false;
					} else {
						inputbox.value = uncompletedTerm;
						uncompletedTermInBox = true;
						dropdownbox.scrollTop = 0;
					}
				}
				return;
			}
		}
		options[0].className = "selectedAutocompleteChoice";
		inputbox.value = options[0].firstChild.nodeValue;		
	}
}

