(function($) {

  function initializeEditor($ingredientForm) {
    usdaFoodSearchEngine.initialize(false);

    var $typeahead = $ingredientForm.find(".ndbn_typeahead");
    var $usdaModal = $("#link_ndbn_modal");
    var $name = $ingredientForm.find(".name");
    var $ndbn = $ingredientForm.find("input.ndbn");
    var $ndbn_group = $ingredientForm.find(".ndbn_group");

    if ($ndbn.val()) {
    }

    $typeahead.typeahead_search({
      searchUrl: '/ingredients/usda_food_search.html',
      resultsContainer: '#link_ndbn_modal .results'
    },{
      name: 'usdaFoods',
      source: usdaFoodSearchEngine,
      display: function(datum) {
        return datum.name;
      }
    });

    $typeahead.on("typeahead_search:selected", function(evt, item) {
      selectNdbn(item.ndbn);
    });

    $usdaModal.on("shown.bs.modal", function() {
      var $this = $(this);
      $typeahead.typeahead("val", $name.val());
      $typeahead.focus();
      $typeahead.select();
    });

    $ingredientForm.on("click", "#link_ndbn_modal .results .food_result", function(evt) {
      var $item = $(evt.target);
      var ndbn = $item.data("ndbn");
      selectNdbn(ndbn);
    });
  }

  function selectNdbn(ndbn) {
    var $ingredientForm = $("#ingredient_form");
    var id = $ingredientForm.find("input.id").val();

    $ingredientForm.find("input.ndbn").val(ndbn);
    $ingredientForm.attr("action", "/ingredients/" + id + "/select_ndbn").attr("data-remote", "true");

    $("#link_ndbn_modal").modal('hide').on('hidden.bs.modal', function() {
      $ingredientForm.submit();
    });
  }

  var usdaFoodSearchEngine = new Bloodhound({
    initialize: false,
    datumTokenizer: function(datum) {
      var str = datum ? datum.name : null;
      return str ? str.split(/[\s,]+/) : [];
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    identify: function(datum) { return datum.ndbn; },
    sorter: function(a, b) {
      if (a.name < b.name) {
        return -1;
      } else if (b.name < a.name) {
        return 1;
      } else {
        return 0;
      }
    },
    remote: {
      url: '/ingredients/usda_food_search.json?query=%QUERY',
      wildcard: '%QUERY'
    }
  });

  $(document).on("ready page:load", function() {
    var $ingredientForm = $("#ingredient_form");

    if ($ingredientForm.length) {
      initializeEditor($ingredientForm);
    }
  });

})(jQuery);