var LunrSearch = (function() {

'use strict';

function LunrSearch(elem, options) {
  this.$elem = elem;
  this.$searchInput = elem.find('input');
  this.$results = elem.find('[data-results="true"]');
  this.$entries = elem.find('[data-entries="true"]');
  this.emptyMsg = options.emptyMsg;
  this.classContext = options.classContext;
  this.showQueryResults = options.showQueryResults;

  this.initialize();
}

LunrSearch.prototype.initialize = function() {
  this.bindEvents();
  this.populateSearchFromQuery();
};

LunrSearch.prototype.bindEvents = function() {
  var self = this;
  var oldValue = this.$searchInput.val();

  this.$searchInput.on('keyup', function() {
    var newValue = self.$searchInput.val();
    if (newValue !== oldValue) {
      self.search(newValue);
    }

    oldValue = newValue;
  });

  // Allow use of arrow keys to navigate results
  this.$elem.on('keydown', function(e) {
    var firstLinkFocused = $(this).find('a:first-child:focus');
    var firstLink = $(this).find('a:first-child');
    var focuedLink = $(this).find('a:focus');

    if (e.keyCode === 40 && focuedLink.length) {
      e.preventDefault();
      e.stopPropagation();
      focuedLink.next().focus();
    } else if (e.keyCode === 40) {
      e.preventDefault();
      e.stopPropagation();
      firstLink.focus();
    }

    if (e.keyCode === 38 && firstLinkFocused.length) {
      e.preventDefault();
      e.stopPropagation();
      self.$searchInput.focus();
    } else if (e.keyCode === 38) {
      e.preventDefault();
      e.stopPropagation();
      focuedLink.prev().focus();
    }
  });
};

LunrSearch.prototype.search = function(query) {
  if (query.length < 3) {
    this.$results.hide();
    this.$entries.empty();
  } else {
    var results = window.idx.search(query);
    this.displayResults(results);
  }
};

LunrSearch.prototype.displayResults = function(entries) {
  var self = this;
  var $entries = this.$entries;
  var $results = this.$results;

  //Wait for data to load
  window.data.then(function(loaded_data) {

    $entries.empty();

    // Are there any results?
    if (entries.length) {

      // Iterate over the results
      entries.forEach(function(result) {
        var item = loaded_data[result.ref];
        var appendString = '<a class="' + self.classContext + '__searchResult" href="' + item.url + '">' + item.title + '</a>';

        // Add it to the results
        $entries.append(appendString);
      });
    } else {
      $entries.html('<div class="' + self.classContext + '__searchResult' + ' ' + self.classContext + '__searchResult--notFound">' + self.emptyMsg + '</div>');
    }
  });
  $results.show();
};

LunrSearch.prototype.populateSearchFromQuery = function() {
  var uri = new URI(window.location.search.toString());
  var queryString = uri.search(true);

  if (queryString.hasOwnProperty('q')) {
    this.$searchInput.val(queryString.q);
  }
};

return LunrSearch;

})();

$.fn.lunrSearch = function(options) {

// apply default options
options = $.extend({}, $.fn.lunrSearch.defaults, options);
var search = new LunrSearch(this, options);

return this;

};

$.fn.lunrSearch.defaults = {

emptyMsg: 'No results found',
classContext: 'search',
showQueryResults: true,

};

$(function() {

$('.heroBanner__search').lunrSearch({
  classContext: 'heroBanner'
});

$('.navSearch').lunrSearch({
  classContext: 'navSearch'
});

});