/*!
* jQuery Predictive Search v1.0
*
* Copyright 2011, Seamless Solutions
* 
* Date: Mon May 30, 2011 02:50PM
*/
(function ($) {
    $.fn.PredictiveSearch = function (settings) {
    // Settings to configure the jQuery Predictive Search plugin how you like
    settings = jQuery.extend({
      //Seamless options
      searchInput:  '.searchbox',
      searchButton:  '.searchboxsubmit',
      outputdiv:    '.predictiveResults',
      resultItem:    'li',
      searchdlvname:  'Predictive Search'
    },settings);
    
    var feedURL = '/feed.rss?listname='+settings.searchdlvname+'&dlv_'+settings.searchdlvname+'=(keyword=';
    var currentRequest=null;
    var thisObject = this;
    
      try {
        $(settings.searchInput)[0].setAttribute("autocomplete","off");
      }
      catch(ex) {
      }
    // 1. Listen to keystrokes in the textbox
      $(settings.searchInput).click(function() {
        this.value='';
        this.setAttribute("autocomplete","off");
      });

      $(settings.searchInput).blur(function(event) {
        $(settings.outputdiv).delay(2000).fadeOut(500, function() {
          this.innerHTML='';
        });
      });
        
      $(settings.searchInput).focus(function(event) {
        $(settings.outputdiv).clearQueue();
        /*$(settings.outputdiv).show();*/
      });
      
      $(settings.searchInput).keypress(function(event) {
        // Ping for result
        if(event.which != 13
          && event.which != 0)
          thisObject.fetchResults(this.value+String.fromCharCode(event.which));
        else
        {
          event.stopPropagation();
          event.preventDefault();
        }
      });
      
      $(settings.searchInput).keydown(function(event) {
        if(event.which == 13)
        {
          event.stopPropagation();
          event.preventDefault();
          event.cancelBubble = true;
          event.returnValue = false;
          return false;
        }
      });
      
      $(settings.searchInput).keyup(function(event) {
        if(event.which == 40)
        {
          // Down Arrow
          thisObject.moveBy(1);
        }
        else if(event.which ==38)
        {
          // Up Arrow
          thisObject.moveBy(-1);
        }
        else if(event.which == 8 || event.which == 46)
        {
          // Backspace
          thisObject.fetchResults(this.value);
        }
        else if(event.which == 13)
        {
          // Enter Key
          event.stopPropagation();
          event.preventDefault();
          if($(settings.outputdiv+' '+ 
               settings.resultItem+'.selected').length > 0)
          {
            thisObject.navigateOut();
          }
          else
          {
            try {
              $(this).find(settings.searchButton)[0].click();
            }
            catch(ex) { }
          }
        }
      });
      
      thisObject.moveBy = function(diff) {
        var selectedItem = $(settings.outputdiv+' '+settings.resultItem+'.selected');
        var selectedIndex = -1;
        var allItems = $(settings.outputdiv+' '+settings.resultItem)
        if(selectedItem.length > 0)
        {
          selectedIndex = $(settings.outputdiv+' '+settings.resultItem).index(selectedItem[0]);
        }
        var nextIndex = selectedIndex + diff;
        nextIndex += allItems.length;
        nextIndex %= allItems.length;
        thisObject.moveTo(allItems[nextIndex]);
      };
      
      thisObject.moveTo = function(item) {
        $(settings.outputdiv+' '+settings.resultItem).removeClass('selected');
        item.className+=' selected';
      }
      
      thisObject.navigateOut = function() {
        var selectedItem = $(settings.outputdiv+' '+ settings.resultItem+'.selected');
        document.location = $(selectedItem[0]).find('a')[0].href;
      };
      
      thisObject.fetchResults = function(keyword) {
        if(currentRequest!=null)
        {
          currentRequest.abort();
        }
        
        if(keyword.length < 3)
        {
          $(settings.outputdiv).html('');
          return;
        }
        
        $(settings.outputdiv).show();
        $(settings.outputdiv).html('<p>Loading...</p>');
        thisObject.currentIndex = 0;
        
        currentRequest = jQuery.ajax({
          url: feedURL+keyword+')',
          type:"GET",
          dataType: "html",
          context: document.body,
          success: function(data) {
            $(settings.outputdiv).html(data);
            $(settings.outputdiv+' '+settings.resultItem).mouseover(function(){
              thisObject.moveTo(this);
            });
          },
          error: function() {
            $(settings.outputdiv).html('<p>Error retrieving results from server</p>');
          }
        });
      };
    }
})(jQuery);
