searchbar = {};
searchbar.init = function()
{
  var fuseOptions =
  {
    shouldSort: true,
    threshold: 0.3,
    location: 0,
    distance: 50,
    maxPatternLength: 128,
    minMatchCharLenth: 2,
    tokenize: true,
    matchAllTokens: true
  }
  window.zoneFuse = new Fuse(moment.tz.names(), fuseOptions);
  window.zfInput = "";
  window.zfResult = {};
  window.zfResultStr = "";
  window.zfChoice = "";
  window.zfList = {};
  window.zfSelect = {};
  window.zfNum = 1;
  $("#tzSearchBox").on("input", searchbar.update);
  $("#tzSearchButton").on("click", table.addRow);
  $("#tzSearchBox").on("keydown", searchbar.update);
  $("#tzSearchBox").on("keypress", searchbar.update);
}

searchbar.getZones = function(r)
{

  var i = 0;
  var ret = ""
  for (var x of r)
  {
    ret += '<input type="button" value="' + zones[x] + '">';
    i++;
    if (i >= 10)
      break;
  }
  return ret;
}

searchbar.update = function(e)
{
  zfInput = $("#tzSearchBox").val();
  zfResult = window.zoneFuse.search(zfInput);
  zfResultStr = searchbar.getZones(zfResult);

  $("#tzSearchResults").html(zfResultStr);
  $("#tzSearchResults").css("display", "block");
  $("#tzSearchResults input").on('click', function()
  {
    zfChoice = $(this).val();
    table.addRow();
  })

  if ( $("#tzSearchBox").val() == "" )
    $( "#tzSearchResults").css("display", "none");

  if (e.which == 38)
  {
    zfNum--;
    $("#tzSearchResults input").removeClass();
    zfSelect = $("#tzSearchResults input:nth-child("+zfNum+")");
    zfSelect.addClass("activeButton");
    zfChoice = zfSelect.val();
    $("#tzSearchResults").animate({ scrollTop: (zfNum - 1)*zfSelect.css("height")}, 200);
  }
  else if (e.which == 40)
  {
    zfNum++;
    $("#tzSearchResults input").removeClass();
    zfSelect = $("#tzSearchResults input:nth-child("+zfNum+")");
    zfSelect.addClass("activeButton");
    zfChoice = zfSelect.val();
    $("#tzSearchResults").animate({ scrollTop: (zfNum - 1)*zfSelect.css("height")}, 200);
  }
  else if (e.which == 13)
     table.addRow();
  
  else
  {
    zfNum = 1;
    zfList = $("#tzSearchResults input");
    zfSelect = zfList.first();
    zfSelect.addClass("activeButton");
    zfChoice = zfSelect.val();
  }

    
}

searchbar.clear = function()
{
  zfResult = new Array();
  zfResultStr = "";
  $("#tzSearchBox").blur();
  $("#tzSearchBox").val("");
  $("#tzSearchResults").html("");
  $("#tzSearchResults").css("display", "none");
}
