var input = $('input[data-role="producer-search"]');
var list = $('[data-role="producer-list"]');
var letters = list.find('div');
var $showAll = $('[data-filter="show-all-manufacturers"]');
var $notFound = $('[data-filter="not-found"]');

// custom css expression for a case-insensitive contains()
jQuery.expr[':'].Contains = function(a, i, m) {
   return (a.textContent || a.innerText || '').toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};

var searchProducers = function() {
   var filter = $(input).val();
   wpj.domUtils.resetTimer('producers-search', 200, function() {
      if (filter) {
         list.find('li:not(:Contains(' + filter + '))').hide();
         var $foundProducers = list.find('a:Contains(' + filter + ')');

         if ($foundProducers.length) {
            $foundProducers.css('display', 'flex');
            letters
               .show()
               .not(letters.has('li:not(:hidden)'))
               .hide();
            $notFound.hide();
         } else {
            letters.hide();
            $notFound.show();
         }
         $('[data-most-wanted]:visible').slideUp();
      } else {
         list.find('li').show();
         letters.show();
         $('[data-most-wanted]:hidden').slideDown();
         $notFound.hide();
      }
   });
};

$showAll.on('click', function() {
   input.val('');
   searchProducers();
   return false;
});

input.on('keyup change', searchProducers);
