function findValue(li) {
  if( li == null ) return alert("No match!");

  // if coming from an AJAX call, let's use the id as the form action
  if( !!li.extra ) {
    var sValue     = li.extra[0];
    var sType      = li.extra[1];
    var sTitle     = li.extra[2];
    var sUrlFormat = li.extra[3];

    // jump to page
    if (!!sUrlFormat) {
      //change the action of the form (just in case)
      $('#ks4searchform').attr('action','/key-stage-four'+ sUrlFormat);
      location.href='/key-stage-four'+ sUrlFormat;
    } else {

    }
    //alert('li extra' + sValue + 'extra[1] = ' + li.extra[1]+ 'extra[2] = ' + li.extra[2]);
  }  else {
    // otherwise, let's just display the value in the text box
    var sValue = li.selectValue;
  }

  sValue; /// <<<<-- this is the Id in the database. Hurrah!

}

function selectItem(li) {
  findValue(li);
}

function formatItem(row) {
  return row[0] + " (" + row[2] + " :" + row[3] + ")";
}

function lookupAjax(){
  var oSuggest = $(".ks4autocomplete")[0].autocompleter;
  oSuggest.findValue();
  return false;
}

function lookupLocal(){
  var oSuggest = $(".ks4autocomplete")[0].autocompleter;
  oSuggest.findValue();
  return false;
}


$(document).ready(function() {
  $(".ks4autocomplete").autocomplete(
  "/auto-complete-ks4.php",
  {
  delay:6,
  minChars:3,
  matchSubset:true,
  matchContains:true,
  cacheLength:10,
  onItemSelect:selectItem,
  onFindValue:findValue,
  formatItem:formatItem,
  autoFill:false,
  highlight:true,
  width:250
  }
  );
});


/**
* These are for displaying the selected options in a seperate list.
**/


function addToList(){
  var sValue = document.getElementById("autocomplete").value;
  $.ajax ({url: '/handson/ajax/add-to-keyword-list.php',
           type: 'GET', success: addToListResult,
           data : {'word' : sValue },
           dataType : 'text' });
}

function addToListResult(sResult){
  var aResult = sResult.split('||');
  if (document.getElementById('divkeyword_'+aResult[0])==null) {
    document.getElementById('keywordlist').innerHTML +=
    '<div id="divkeyword_'+aResult[0]+'"><span class="remover" onclick="removekeyword('+aResult[0]+')"><img src="/img/handson/icons/cross.gif" alt="remove this keyword" title="remove this keyword"/></span>'+aResult[1]+'<input type="hidden" value="t" name="keyword['+aResult[0]+']" id="keyword_'+aResult[0]+'" /></div>';
    document.getElementById('autocomplete').value='';
    document.getElementById('autocomplete').focus();
  }
}

function removekeyword(nId){
  document.getElementById('keywordlist').removeChild(document.getElementById('divkeyword_'+nId));
}