var searchTimer; // for tracking keyup inactivity, search request will be sent only after 150 ms of inactivity
var searchTimestamp; // for tracking which request is the most recent

$(document).ready(function(){

  $('#searchForm input').focus(function() { $(this).val(''); $('#searchForm').find('ul li').remove(); });
  $('#searchForm input').keyup(function() {
    clearTimeout(searchTimer);
    if($(this).val().length > 0){
      $('#searchForm').addClass('searching'); // for the spinner
      query = $(this).val();
      timestamp = new Date().getTime();
      searchTimestamp = timestamp;
      searchTimer = setTimeout(function(){nrl_search(query,timestamp)},150);
    } else {
      $('#searchForm').removeClass('active searching').find('ul li').remove();
    }
  });
  $('#searchForm input').blur(function() {
    $(this).val('Search');
    setTimeout( "$('#searchForm').removeClass('active searching')", 250 ); // delay required for result links to work
  });

});


function nrl_search(query,timestamp) {
  console.log('in function');
  $.ajax({
    type: 'GET',
    dataType: 'jsonp',
    data: {'content-type':'application/json','q': query,'num': '3'},
    url: '/pages/search.php',
    complete: function(){
      $('#searchForm').removeClass('searching');
    },
    error: function(xhr) {
      listItems = '<li style="font-weight: bold;"><a>Search Unavailable</a></li>';
      listItems += '<li><a href="/pages/search.php?q='+encodeURI(query)+'&mode=fullsearch">Search all of NRL -></a></li>';
      $('#searchForm').removeClass('searching').addClass('active').find('ul').html(listItems);
    },
    success: function(data){
      if(timestamp == searchTimestamp){
        if($('#searchForm input').val().length > 0) {
          listItems = '';
          if(typeof data.RES != 'undefined' && typeof data.RES.R != 'undefined' && data.RES.R[0] != null){
            $.each(data.RES.R, function(i,item){
              listItems += '<li><a href="'+item.U+'">'+item.T+'</a></li>';
            });
          } else {
            listItems += '<li style="font-weight: bold;"><a>No Results Found</a></li>';
          }
          listItems += '<li><a href="/pages/search.php?q='+encodeURI(query)+'&mode=fullsearch">Search all of NRL -></a></li>';
          $('#searchForm').addClass('active').find('ul').html(listItems);
        } else {
          $('#searchForm').removeClass('active').find('ul li').remove();
        }
      }
    }
  });
}

