(function(context) {
  var icons = {};


  icons.search = function () {
    var template = _.template($('#icon-collection').html());
    var icons = $('#base-set');
    var search = $('#search');
    var set = {}, total = 0;

    function find(phrase) {
      var matches = data.filter(function(p) {
        return _(phrase).filter(function(a) {
          return _(p.words).any(function(b) {
            return a === b || b.indexOf(a) === 0;
          });
        }).length === phrase.length;
      });
      return matches;
    }

    var data = _(window.Icons).chain()
    .compact()
    .map(function(p) {
      p.words = (p.icon.toLowerCase() +' '+ (p.tags.toString()).toLowerCase()).match(/(\w+)/g);
      return p;
    })
    .reject(function(i) {
      return i.tags[0] === 'deprecated';
    })
    .map(function(icon){
      set.title = icon.name;
      set.icon = icon.icon;
      total++;
      $('#base-set').append(template(set));
      return icon;
    })
    .value();

    $('input', search).focus(function() {
      $('.base-close').addClass('active');
      $('#base-set').addClass('active');
      $(this).val('');
      icons.animate({
        opacity: 1
      }, 400, function() {
      });
    });

    $('input', search).keyup(_(function() {
      $('#base-set').hide();
      $('#base-search').empty();

      var phrase = $('input', search).val();
      if (phrase.length >= 1) {
        var matches = find(phrase.toLowerCase().match(/(\w+)/g) || '');
        matches.forEach(function(p) {
          $('#base-search')
          .append(template(p));
        });
      }
      else {
        $('#base-search').empty();
        $('#base-set').show();
      }
      return false;
    }).debounce(100));

    $(document.documentElement).keydown(function (e) {
      if (e.keyCode === 27) { $('a.base-close').trigger('click'); }
    });

    $('a.base-close').click(function (e) {
      e.preventDefault();
      $('input', search).blur().val('');
      $('.base-close').removeClass('active');
      $('#base-search').empty();
      $('#base-set').show();
    });
  };
  $(icons.search);

  window.icons = icons;
})(window);
