$(function() {
  function replaceCanvasWith(content) {
    $('#search_canvas>*:not(.search-box)').remove();
    $('#search_canvas').append(content);
  }
  function showResults(results) {
    var html = '<div id="search_results">';
    $.each(results, function(i, r){
      var clickurl = $('<div/>').text(r.clickurl).html(),
       url = $('<div/>').text(r.url).html();
      html+= '<div class="search-result" onclick="document.location=\''+clickurl+'\'; return false;">'+
        '<div class="search-result-title"><a href="'+url+'">'+r.title+'</a></div>'+
        '<div class="search-result-desc">'+r.abstract+'</div>'+
        '<div class="search-result-dispurl">'+r.dispurl+'</div>'+
        '</a></div>';
    });
    replaceCanvasWith(html+'</div>');    
  }
  function fallbackURL(terms) {
    return 'https://duckduckgo.com/?q=site:alanhogan.com%20'+encodeURIComponent(terms);
  }
  function noResults(){
    replaceCanvasWith('<p>Sorry, no results were returned. Try another search!</p>');
  }
  function searchFailed(terms){
    replaceCanvasWith(
      $('<p>Sorry, the search failed. </p>').append($('<a />', 
        {href:fallbackURL(terms), text:'Care to try this search on another engine?'})
      )
    );
  }
  
  function doSearch(terms) {
    $('.site-search').val(terms);
    replaceCanvasWith($('<i class=loading></i>').text('Searching…'));
    var url = '/files/ajax-search.php?q='+encodeURIComponent(terms);
    $.ajax(url, {
      timeout:12000,
      error: function(jqXHR, textStatus, errorThrown){
        if(window.console) {console.log(jqXHR); console.log(textStatus); console.log(errorThrown)}
        searchFailed(terms);
      },
      success: function(data){
        if(data.success && data.results && data.results.ysearchresponse) {
          var y = data.results.ysearchresponse;
          if (y.count && y.count !== "0") {
            try {
              showResults(y.resultset_web);
            } catch (e) {
              window.console&&console.log(e);
              // Unexpected error
              searchFailed(terms);
            }
          } else {
            noResults();
          }
        } else {
          // Unexpected response.
          if(window.console){console.log('Response did not include expected data.'); console.log(data); console.log(data.success+data.results+data.results.ysearchresponse)}
          searchFailed(terms);
        }
      }
    });
  }
  
  function inviteUserToSearch(){
    replaceCanvasWith($('<p class="search-prompt" />').text('Please enter a search term above and hit Return to search this website.'));
  }
  
  function searchFromHash(){
    var hash = ''+document.location.hash,
      searchPat = /^#q=(.+)$/,
      terms = null;
    if (hash.match(searchPat)) {
      try {
        terms = decodeURIComponent(searchPat.exec(hash)[1]);
        doSearch(terms);
        return false;
      } catch(e) {
        window.console&&console.log(e);
        // Do nothing — let code after this if statement execute
      }
    }
    // Didn’t actually search, so:
    inviteUserToSearch();
  }
  
  $('.search-result a').live('click', function(){
    $(this).closest('.search-result').click();
    return false;
  });
  
  // Listen to hashchange
  window.onhashchange = searchFromHash;
  
  // Initialize
  searchFromHash();
  $('.404-search').trigger('submit.ah');
});

