//Listing 10.4
function typeAheadInit() {
  //Listing 10.7
  document.getElementById("txtUserInput").obj = 
  	SetTypeAheadProperties(document.getElementById("txtUserInput"),
    	document.getElementById("hidden1"),
      true,true,true,true,"No matching Data",false,null);
}

//Listing 10.6
function SetTypeAheadProperties(xElem,xHidden,
  xignoreCase,xmatchAnywhere,xmatchTextBoxWidth,
  xshowNoMatchMessage,xnoMatchingDataMessage,xuseTimeout,
  xtheVisibleTime){
    var props={
      elem: xElem,
      hidden: xHidden,
      regExFlags: ( (xignoreCase) ? "i" : "" ),
      regExAny: ( (xmatchAnywhere) ? "" : "^" ),
      matchAnywhere: xmatchAnywhere,
      matchTextBoxWidth: xmatchTextBoxWidth,
      theVisibleTime: xtheVisibleTime,
      showNoMatchMessage: xshowNoMatchMessage,
      noMatchingDataMessage: xnoMatchingDataMessage,
      useTimeout: xuseTimeout
    };
    AddHandler(xElem);
    return props;
}

//Listing  10.8
var isOpera=(navigator.userAgent.toLowerCase().indexOf("opera")!= -1);
function AddHandler(objText){
  objText.onkeyup = GiveOptions;
  if(isOpera)objText.onkeypress = GiveOptions;
}

//Listing 10.9
var arrOptions = new Array();
var strLastValue = "";
var bMadeRequest;
var theTextBox;
var objLastActive;
var currentValueSelected = -1;
var bNoResults = false;
var isTiming = false;

//Listing 10.10
function GiveOptions(e){
  var intKey = -1;
  if(window.event){
    intKey = event.keyCode;
    theTextBox = event.srcElement;
  }
  else{
    intKey = e.which;
    theTextBox = e.target;
  }
  //If nothing is in the textbox anymore
  if(theTextBox.value.length == 0 && !isOpera){
    arrOptions = new Array();
    strLastValue = "";
    populateNavPanel();
    return false;
  }
  if(objLastActive == theTextBox){
    if(intKey == 13){ // Enter
      GrabHighlighted();
      return false;
    }
    else if(intKey == 38){ // Up
      MoveHighlight(-1);
      return false;
    }
    else if(intKey == 40){ // Down
      MoveHighlight(1);
      return false;
    }
    else if(intKey == 27) { // Escape
    	theTextBox.value = "";
    	arrOptions = new Array();
    	strLastValue = "";
    	populateNavPanel();
    	return false;
    }
    else{}
  }
    
  if(objLastActive != theTextBox ||
     theTextBox.value.indexOf(strLastValue) != 0 ||
     ((arrOptions.length==0 || arrOptions.length==15 ) && !bNoResults) ||
     (theTextBox.value.length <= strLastValue.length)){
       objLastActive = theTextBox;
       bMadeRequest = true
       TypeAhead(theTextBox.value)
  }
  else if(!bMadeRequest){
    BuildList(theTextBox.value);
  }
  strLastValue = theTextBox.value;
}



//Listing 10.11
function TypeAhead(xStrText){
	var type = "";

	if(navPanelState == NAV_OCCUPANT)
	{
		type = "oSearch";
	} else {
		type = "bSearch";
	}

	var strParams = "mapquery.php?type=" + type + "&value=" + xStrText;
	
	cObj = YAHOO.util.Connect.asyncRequest('POST',strParams,typeAhead_callback,null);
}

//Listing 10.12
var BuildChoices = function(o) {
  eval(o.responseText);
  BuildList(strLastValue);
  bMadeRequest = false;
}

var typeAhead_callback =
{
	success:BuildChoices,
	failure:responseFailure
}

//Listing 10.13
function BuildList(theText){
  var theMatches = MakeMatches(theText);
  theMatches = theMatches.join().replace(/\,/gi,"");
  if(theMatches.length > 0){
  document.getElementById("navPanelBody").innerHTML = theMatches;
   if(!showNavPanel) {
   	togglePanel();
   }
    
    
    document.getElementById(
      "OptionsList_0").className=
      "spanHighElement";
    currentValueSelected = 0;
    bNoResults = false;
  }
  else{
    currentValueSelected = -1;
    bNoResults = true;
    if(theTextBox.obj.showNoMatchMessage)    
	    document.getElementById("navPanelBody").innerHTML = theTextBox.obj.noMatchingDataMessage;
	 else HideTheBox();
  }
}

//Listing 10.15
var countForId = 0;

function MakeMatches(xCompareStr){
  countForId = 0;
  var matchArray = new Array();
  var regExp = new RegExp(theTextBox.obj.regExAny +
    xCompareStr,theTextBox.obj.regExFlags);
  for(i=0;i<arrOptions.length;i++){
    var theMatch = arrOptions[i][0].match(regExp);
    if(theMatch){
			if(navPanelState == NAV_BUILDING) {
      	matchArray[matchArray.length]= CreateUnderline(arrOptions[i][0], xCompareStr,i);
			} else {
      	matchArray[matchArray.length]= CreateUnderline(arrOptions[i][0], xCompareStr,i, arrOptions[i][2]);
			}
    }
  }

  return matchArray;
}


//Listing 10.16
var undeStart = "<span class='spanMatchText'>";
var undeEnd = "</span>";
var selectSpanStart = "<span style='width:100%;display:block;' class='spanNormalElement' onmouseover='SetHighColor(this)' ";
var selectSpanEnd ="</span>";

function CreateUnderline(xStr,xTextMatch,id) {
	return CreateUnderlien(xStr, xTextMatch, id, new Array());
}

function CreateUnderline(xStr,xTextMatch,id,array){
	var retval = "";
	
	selectSpanMid = "onclick='onclick=SetText(" + id + ")'" +
		"id='OptionsList_" + countForId + "' theArrayNumber='"+ id +"'>"; 
  
	var regExp = new RegExp(theTextBox.obj.regExAny + xTextMatch,theTextBox.obj.regExFlags);
	var aStart = xStr.search(regExp);
	var matchedText = xStr.substring(aStart, aStart + xTextMatch.length);
	countForId++;

	retval += selectSpanStart + selectSpanMid;
	if(navPanelState == NAV_OCCUPANT) {
		retval += "<em>";
	}
	retval +=	xStr.replace(regExp,undeStart + matchedText + undeEnd);
	if(navPanelState == NAV_OCCUPANT) {
		retval += "</em>";
	}
	retval += selectSpanEnd;
	if(navPanelState == NAV_OCCUPANT && array.length > 0) {
		retval += "<ul>";
		for(var j=0; j<array.length; j++) {
			selectSpanMid = "onclick='onclick=building(" + array[j][1] + ")'>";
			
			retval += "<li>";
	  	retval += selectSpanStart + selectSpanMid;
			retval +=	array[j][0];
			retval += selectSpanEnd;
			retval += "</li>";
		}
		retval += "</ul>";
	}
		
	return retval;
}

//Listing 10.17
function MoveHighlight(xDir){
  if(currentValueSelected >= 0){
    newValue = parseInt(currentValueSelected) + parseInt(xDir);
    if(newValue > -1 && newValue < countForId){
      currentValueSelected = newValue;
      SetHighColor (null);
    }
  }
}

function SetHighColor(theTextBox){
  if(theTextBox){
    currentValueSelected =
    theTextBox.id.slice(theTextBox.id.indexOf("_")+1,
    theTextBox.id.length);
  }
  for(i = 0; i < countForId; i++){
    document.getElementById('OptionsList_' + i).className =
      'spanNormalElement';
  }
  document.getElementById('OptionsList_' +
    currentValueSelected).className = 'spanHighElement';
}

//Listing 10.18
function SetText(xVal){
  theTextBox.value = arrOptions[xVal][0]; //set text value  
  theTextBox.obj.hidden.value = arrOptions[xVal][1];
  
  currentValueSelected = -1; //remove the selected index
  theTextBox.blur();
  displaySearch('hidden1');
  populateNavPanel();
  theTextBox.focus();
  theTextBox.select();
}
function GrabHighlighted(){
  if(currentValueSelected >= 0){
    xVal = document.getElementById("OptionsList_" +
    currentValueSelected).getAttribute("theArrayNumber");
    SetText(xVal);
  }
}
