var holdResults = 0;
function highSuggest(theNum) {
	
	//don't allow slow results to come and erase current progress
	holdResults = 1;
	
	if (!theNum) {
		theNum = sNum;
	}
	
	//remove class from others
	for (var i = 0; theLen > i; i++) {
		var takeI = i + 1;
		$("#" + baseId + takeI).removeClass("onSuggestion");
	}
	
	//add class
	$("#" + baseId + theNum).addClass("onSuggestion");
	
	//set global so that mousing over and keyboard is consistent
	sNum = theNum;
	
}

var regPart = "";
function keySuggest(e, id) {

	var actualLen = theLen - 1;				
		
	//$("#keyCatch").html(e.keyCode + " - sNum: " + sNum + " - actualLen: " + actualLen);							
	if (e.keyCode == 13 || e.keyCode == 39) {  
		
		if (sNum != 0) {
			var theVal = $("#"+baseId+sNum).html();
			setSuggest(theVal, id, 1, 1);
			
			//capture return to avoid ding in IE
			if (e.keyCode == 13 && regPart == "welcome" && id == "city") {
				e.preventDefault();	
				submitLanding();							
			}
			else if (e.keyCode == 13 && id == "contextText") {
				e.preventDefault();	
				preSubmit();							
			}
			else if (e.keyCode == 13) {
				e.preventDefault();
				return false;
			}
			
		}
		
	} 
	else if (e.keyCode == 37) {  
		//left key			
		holdResults = 0;
		closeSuggest();		
					
	}
	else if (e.keyCode == 38) {  
		//up key			
		
		if (sNum == 0) {
			sNum = theLen;				
		}
		else if (sNum == 1) {
			sNum = theLen;
		} 
		else {
			sNum--;
		}
		
		highSuggest();	
		var theVal = $("#"+baseId+sNum).html();
		setSuggest(theVal, id, 0, 0);	
					
	}
	else if (e.keyCode == 40) {  
		//down key			
		
		//catch to make sure it doesnt go over
		if (sNum > actualLen) {
			sNum = 1;								
		} else {
			sNum++;			
		}
		
		highSuggest();	
		var theVal = $("#"+baseId+sNum).html();
		setSuggest(theVal, id, 0, 0);
		
	} 	
			
}

function filterSuggest(e, suggestType, id) {
		
	if (e.keyCode != 13 && e.keyCode != 39 && e.keyCode != 38 && e.keyCode != 40 && e.keyCode != 37) {  
		
		//don't hold results since they are typing again
		holdResults = 0;
		
		//if they are typing then quit the waiting soon
		setTimeout("endWaiting()", 300);
		
		if (nowWaiting == 0) {
			getSuggest(suggestType, id);
		}
		
	}
	 
}

//bind the suggestion inputs for suggestions when document is ready 
$(document).ready(function() {
	
	//start fresh
	$("#fName").bind("focus", function(e) { startFresh("fName"); });
	$("#lName").bind("focus", function(e) { startFresh("lName"); }); 
	$("#city").bind("focus", function(e) { startFresh("city"); });  		
	
	//end fresh
	$("#fName").bind("blur", function(e) { endFresh(); });
	$("#lName").bind("blur", function(e) { endFresh(); }); 
	$("#city").bind("blur", function(e) { endFresh(); });  		
	
	//allow for traversing the suggestions
	$("#fName").bind("keydown", function(e) { keySuggest(e, "fName"); });
	$("#lName").bind("keydown", function(e) { keySuggest(e, "lName"); }); 
	$("#city").bind("keydown", function(e) { keySuggest(e, "city"); });  
	
	//dont pull more results from arrow keys or enter that allow for traversing
	$("#fName").bind("keyup", function(e) { filterSuggest(e, 1, "fName"); });
	$("#lName").bind("keyup", function(e) { filterSuggest(e, 2, "lName"); }); 
	$("#city").bind("keyup", function(e) { filterSuggest(e, 3, "city"); });
	
	//set focus on first name (must be after binding)
	$("#fName").focus();
  

});

function closeSuggest(wait) {
	//allow new results
	holdResults = 0;
	sNum = 0;
	theLen = 0;
	//should clear and reset too
	$("#putResults").html("");
	$("#suggestResults").css("display", "none");
}

function setSuggest(val, id, closeIt, forwardNext) {
	
	if (val != null) {
		$("#" + id).val(unescape(val));
	}
	
	if (closeIt == 1) {
		closeSuggest();
	}	
	
	//forward focus to next form field or back to self
	if (id == "fName") {
		nextId = "lName";
	}
	else if (id == "lName") {
		nextId = "city";
	}
	else if (id == "city") {
		nextId = "city";
	} 
	else {
		nextId = "";
	}
			
	if (forwardNext == 1 && nextId != "") {
		$("#" + nextId).focus();
	}	
	
}

function endWaiting() {
	nowWaiting = 0;
}

var currId = "";
function startFresh(id) {
	
	//set up right id
	currId = id;
	
	//new field gets focus so allow new
	holdResults = 0;
	closeSuggest();
}

function endFresh() {
	//make sure lagging requests dont come back
	holdResults = 1;
	currId = "";
	setTimeout("closeSuggest()", 1000); //otherwise the mouse click on result doesn't register
}

var sNum = 0;
var theLen = 0;
var baseId = "s";
var nowWaiting = 0;
function getSuggest(type, entryId) {
	
	//get entry
	var entry = $("#" + entryId).val();
	
	if (entry.length < 2) {
		return false;//make sure to do this before waiting
	} 
		
	//show if we are waiting
	nowWaiting = 1;
	
	//set timeout in to restore in case of net error
	setTimeout("endWaiting()", 1000);		
	
	$.getJSON("ajax/suggest.php", { t: type, e: entry }, function(json){
		
		//show we aren't waiting
		nowWaiting = 0;
		
		//only show if they aren't traversing (also make sure still focused)
		if (holdResults == 0 && currId == entryId) {
			
			var items = json.r;
			
			items = items.split('%2C');
			
			var currLen = items.length; 
			var out = '';
			
			//fix for sending empty item with no results
			if (items[0] != "") {
			
				for (var i = 0; currLen > i; i++) {	
					var itemNice = unescape(items[i]);
					var showI = i + 1;
					out += "<div onMouseover=\"highSuggest(" + showI + ");\" onClick=\"setSuggest('" + items[i] + "', '" + entryId + "', 1, 1)\" class='suggestion' id='s" + showI + "'>" + itemNice + "</div>"; 
				}						
			
			} else {
				//edit this out if you want people to see their last best result (helps with typos)
				closeSuggest();
			}
			
			if (out != '') {			
				$("#putResults").html(out);	
				place(entryId, 'suggestResults', 'bottom', 0, 0);
				
				//reset selections (if no results, we keep the old up with the old len)		
				sNum = 0;
				theLen = currLen;			
			}
			
		}
		
	});
		
}
