var ajaxCache = {};
var dataCache = {};
$(document).ready(function(){
$("input.auto_complete").autocomplete({
  source: function(request, response) {
    //what are we searching for
    //the cacheterm that we use to save it in the cache
    var cachedTerm = (request.term) . toLowerCase();
    //if the data is in the cache and the data is not too long, use it
    if (ajaxCache[cachedTerm] != undefined && ajaxCache[cachedTerm].length < 13) {
      //map the data into a response that will be understood by the autocomplete widget
      response($.map(ajaxCache[cachedTerm], function(item) {
         return { t: item.t, s: item.s , value: item.s}
      }));
    }
    //get the data from the server
    else {
      $.ajax({
         url: "/actions.php",
         dataType: "json",
         data: {
             action: 'search-autocomplete',
             q: request.term,
            output_type : 'json'
          },
         success: function(data) {
            //cache the data for later
            ajaxCache[cachedTerm] = data.data;
            //map the data into a response that will be understood by the autocomplete widget
           response($.map(data.data, function(item) {
              return { t: item.t, s: item.s, value: item.s }
            }));
          }
        });
       }

     },
     minLength: 3,
        //when you have selected something
    select: function(event, ui) {
                //close the drop down
                this.close
     },
        //show the drop down
        open: function() {
                $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
        },
        //close the drop down
 close: function() {
                $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        }
/*
  focus: function(event, ui) {
     var item = ui.item.data( "item.autocomplete" );
     alert(item.s);
  }
*/
});
});

