
window.INGREDIENT_API = {};

(function($) {

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

    var $typeahead = $ingredientForm.find(".ndbn_typeahead");

    $typeahead.typeahead_search({
      searchUrl: '/ingredients/usda_food_search.html',
      resultsContainer: $ingredientForm.find(".ndbn_results")
    },{
      name: 'usdaFoods',
      source: usdaFoodSearchEngine,
      limit: 20,
      display: function(datum) {
        return datum.name;
      }
    });

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

    $ingredientForm.on("click", ".ndbn_results .food_result", function(evt) {
      var $item = $(evt.target);
      var ndbn = $item.data("ndbn");
      selectNdbn($ingredientForm, ndbn);
      return false;
    });
  }

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

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

    $ingredientForm.submit();
  }

  function customTokenizer(str) {
    if (str) {
      var cleaned = str.replace(/,/g, "");
      return Bloodhound.tokenizers.whitespace(cleaned);
    } else {
      return [];
    }
  }

  window.INGREDIENT_API.initialize = function() {
    var $ingredientForm = $("#ingredient_form");

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

  var usdaFoodSearchEngine = new Bloodhound({
    initialize: false,
    datumTokenizer: function(datum) {
      var str = datum ? datum.name : null;
      return customTokenizer(str);
    },
    queryTokenizer: customTokenizer,
    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("turbolinks:load", function() {
    window.INGREDIENT_API.initialize();
  });

})(jQuery);