/**
 * U.Va. A-Z Index Live Search
 * Observes a form, parses JSON, displays results 
 */
// global variables
var acListTotal   =  0;
var acDelay		  = 50;
var acURL		  = null;
var acSearchId	  = null;
var acResultsId	  = null;
var acSearchField = null;
var acResultsDiv  = null;
var acResultsServer = null;
function setAutoComplete(field_id, results_id){
	// register mostly used vars
//	acSearchField	= $('#az-index-search');
//	acResultsDiv	= $('#az-index-results');
	acSearchField = $(field_id);
	acResultsDiv = $(results_id);
	// on key up listener
	acSearchField.keyup(function (e) {
		// get keyCode (window.event is for IE)
		var keyCode = e.keyCode || window.event.keyCode;
		var lastVal = acSearchField.val();
		// check for an ENTER or ESC
		if(keyCode == 27){
			clearAutoComplete();
			return;
		}
		// if is text, call
		if(lastVal.length > 1) {
			setTimeout(function () {autoComplete(lastVal, 'keyword')}, acDelay);
		}
		if(lastVal.length == 1) {
			setTimeout(function() {autoComplete(lastVal, 'alpha')}, acDelay);
		}
	});
}
// treat the auto-complete action 
function autoComplete(lastValue, searchType) {
	// get the field value
	var part = acSearchField.val() != null ? acSearchField.val() : '';
		// if it's equal the value from the time of the call, allow
		if(lastValue != part){
			return;
		}
	// Replace spaces with a plus symbol
	var alphaURL 		= '/atoz/parametric/International/'+ part.replace(/\s/g, "+");
	var keywordURL		= '/atoz/parametric/International/'+ part.replace(/\s/g, "+");
	switch(searchType) {
		case "alpha":
			var jsonURL = alphaURL;
			break;
		case "keyword":
			var jsonURL = keywordURL;
			break;
		default: 
			var jsonURL = keywordURL;
			break;
		}	
	// get remote data as JSON
	$.getJSON(jsonURL, function(json){
		// get the total of results
		var ansLength = acListTotal = json.length;
		// if there are results populate the results div
		if(json.length > 0){
			acResultsDiv.show();
			var html = '<ul>';
			// create a li for each result
			for(var i=0; i < ansLength; i++) {
				html += '<li><a href="' + json[i]["url"] + '">' + json[i]["title"] + '</a>'
			}
			html += '</ul>';
			// update the results div
			acResultsDiv.html(html);
		} else {
			clearAutoComplete();
			html = '<p id="az-sorry"><a href="http://www.virginia.edu/search/results.html?cx=017593750330628318309%3Algfaqmeyqba&q=';
			html += part + '&sa=Search&cof=FORID%3A11#999">';
			html += 'No matching sites were found. Try your search on the U.Va. web &gt;&gt;</a></p>';
			acResultsDiv.html(html);
		}
	});
}
// clear auto complete box
function clearAutoComplete() {
	$('#az-index-results').html('');
}

