<script type="text/javascript">
  $(document).ready(function() {
    var beverage_labels, beverage_mapped;
    var beverage_complete_url = "{% url "kegadmin-autocomplete-beverage" %}";
    $('.beer-select').each(function() {
      var beverage_name = $(this).find('input[name=beverage_name]');
      var beverage_id = $(this).find('input[name=beverage_id]');
      var producer_name = $(this).find('input[name=producer_name]');
      var producer_id = $(this).find('input[name=producer_id]');
      var style = $(this).find('input[name=style_name]');

      beverage_name.typeahead({
        source: function (query, process) {
          $.get(beverage_complete_url, { q: query }, function (data) {
            beverage_labels = []
            beverage_mapped = {}

            $.each(data, function (i, item) {
              var name = item.name + " (" + item.producer_name + ")";
              beverage_mapped[name] = item;
              beverage_labels.push(name);
            })

            process(beverage_labels);
          })
        },
        updater: function (item) {
            producer_name.val(beverage_mapped[item].producer_name);
            style.val(beverage_mapped[item].style);
            beverage_id.val(beverage_mapped[item].id);
            producer_id.val(beverage_mapped[item].producer_id);
            return beverage_mapped[item].name;
        },
      });
    });

    var user_labels, user_mapped;
    var user_complete_url = "{% url "kegadmin-autocomplete-user" %}";
    $('.user-select').each(function() {
      var username = $(this).find('input[name=username]');

      username.typeahead({
        source: function (query, process) {
          $.get(user_complete_url, { q: query }, function (data) {
            user_labels = []
            user_mapped = {}

            $.each(data, function (i, item) {
              var name = item.display_name + " (" + item.email + ")";
              user_mapped[name] = item;
              user_labels.push(name);
            })

            process(user_labels);
          })
        },
        updater: function (item) {
            return user_mapped[item].username;
        },
      });
    });
  });
</script>