---
---
// builds lunr
var index = lunr(function () {
  this.field('title', {boost: 7})
  this.field('description', {boost:10})
  this.field('content', {boost: 2})
  this.ref('id')
  {% assign count = 0 %}{% for page in site.pages %}{% if page.page-category == "searchable" %}
  this.add({
    title: {{page.title | jsonify}},
    description: {{page.description | jsonify}},
    content: {{page.content | strip_html | jsonify}},
    id: {{count}}
  });{% assign count = count | plus: 1 %}{% endif %}{% endfor %}
});
// builds reference data
var store = [{% for page in site.pages %}{% if page.page-category == "searchable" %}{
  "title": {{page.title | jsonify}},
  "description": {{page.description | jsonify}},
  "link": {{ page.url | jsonify }},
}{% unless forloop.last %},{% endunless %}{% endif %}{% endfor %}]

var callback = function(){
  const resultdiv = document.querySelector('ul.search-results');
  const searchInput = document.querySelector('input#search-input');
  const searchContainer = document.querySelector('#search');

  // If there's a search term in the URL, put the term in input box
  var urlParams =  new URLSearchParams(window.location.search);
  searchInput.value = urlParams.get('search');

  // Add s keyboard shortcut to get to search.
  document.addEventListener('keyup', function (event) {
    if (document.getElementById('search-input') == document.activeElement || event.keyCode !== 83) {
      return;
    } else {
      document.getElementById('search-input').focus();
    }
  });

  // Clicks outside search results should close results
  document.addEventListener('click', function (event) {
    var isClickInside = searchContainer.contains(event.target);

      if (!isClickInside) {
        resultdiv.style.display = 'none';
      } else if (searchInput.value.length > 0) {
        resultdiv.style.display = 'inline-block';
      }
  });

  //handle up and down arrow navigation in search results
  searchInput.addEventListener('keydown', function(e) {
    //wait until there are actually search results
    if (resultdiv.children) {
      var selected = document.querySelector('.selected');
      // up 
      if (e.keyCode == 38) {
        selected.classList.remove('selected');
        if (selected.previousSibling !== null) {
          selected.previousSibling.classList.add('selected');
        } else {
          document.querySelector('ul.search-results').lastChild.classList.add('selected');
        }
      }
      // down
      if (e.keyCode == 40) {
        selected.classList.remove('selected');
        if (selected.nextSibling !== null) {
          selected.nextSibling.classList.add('selected');
        } else {
          document.querySelector('ul.search-results li').classList.add('selected');
        }
      }
      // enter
      if (e.keyCode == 13) {
        var selectedAnchor = document.querySelector('.selected a')
        document.location = selectedAnchor.getAttribute('href');
      }
    }
  });

  // Don't trigger the search on up, down, or enter
  searchInput.addEventListener('keyup', function(e){
    if (e.keyCode == 38 || e.keyCode == 40 || e.keyCode == 13) {
      return;
    }
    else {
      search();
    }
  }); 

  // URL search params get added to input, run search on focus
  searchInput.addEventListener('focus', search);

  function search() {
    if (searchInput.value.length == 0) {
      resultdiv.style.display = 'none';
    }
    if (searchInput.value.length < 3) return;
    // Get query
    var query = searchInput.value;
    // Search for it
    var result = index.search(query);
    // Show results
    resultdiv.innerHTML = '';
    if (result.length < 1) {
      // Add status
      resultdiv.insertAdjacentHTML('afterbegin','<li class="noresults">No results.</li>');
    } else {
      // Loop through, match, and add results
      for (var item in result) {
        var ref = result[item].ref;
        var searchitem = '<li><a href="' + "{{site.baseurl}}" + store[ref].link + "?search=" + query+ '">' + store[ref].title + ' <br /><span class="description">' + store[ref].description + '</span></a></li>';
        resultdiv.insertAdjacentHTML('beforeend', searchitem);
      }
    }
    //add .selected to first result if there are results.
    var firstResult = document.querySelector('ul.search-results li:not(.noresults)');
    if (firstResult !== null) { 
      firstResult.classList.add('selected'); 
    }
    resultdiv.style.display = 'inline-block';
  };
    
  searchInput.addEventListener('search', function () {
    resultdiv.style.display = 'none';
  });
};

if (
    document.readyState === "complete" ||
    (document.readyState !== "loading" && !document.documentElement.doScroll)
) {
  callback();
} else {
  document.addEventListener("DOMContentLoaded", callback);
}

