var Search = (function () {
  'use strict';

  var searchContainer = $('.js-search');
  var searchIcon = $('.js-search-icon');
  var searchInput = $('.js-search-input');
  var searchTimeout;
  var currentSearchQuery = '';
  var isSearchOpen = false;

  return {
    init: init,
    search: search,
    show: show,
    hide: hide,
    reset: reset
  };

  function init() {
    searchInput.focus();
    searchInput.on('keyup search', onSubmitSearch);
  }

  function show() {
    searchContainer.removeClass('hidden');
  }

  function hide() {
    searchContainer.addClass('hidden');
  }

  function search(query) {
    searchInput.val(query);
    searchInput.focus();
    doSearch(query);
  }

  function onSubmitSearch(event) {
    var query = $(this).val();

    if (query == '' && currentSearchQuery != '') {
      closeSearch();
      return;
    }

    clearTimeout(searchTimeout);
    if (query == currentSearchQuery) {
      return;
    }
    searchTimeout = window.setTimeout(function() {
      doSearch(query);
    }, 200);
  }

  function doSearch(query) {
    Util.trackPage('search/' + query);
    window.scrollTo(0, 0);
    currentSearchQuery = query;
    PopularSearches.hide();
    openSearch();
    PhotoApi.get('search?query=' + query);
  }

  function openSearch() {
    if (isSearchOpen) {
      return;
    }
    isSearchOpen = true;
    Tabs.hide();
    searchIcon.addClass('search__icon--back');
    searchIcon.on('click', closeSearch);
  }

  function closeSearch() {
    reset();
    Tabs.openLastTab();
  }

  function reset() {
    isSearchOpen = false;
    currentSearchQuery = '';
    searchIcon.removeClass('search__icon--back');
    searchIcon.off('click', closeSearch);
    searchInput.val('');
  }

}());