/**
 * Connect input with a table or a list, to quickly filter it's content
 */
jQuery.fn.quickSearch = function(s) {
  var settings = jQuery.extend({
    'target' : null, 
    'rows' : 'tr', 
    'search_index_attribute' : '_search_index', 
    'success' : null
  }, s);
  
  return this.each(function() {
    var input = $(this);
    var target = $(settings['target']);
    
    if(target.length > 0) {
      var search_timeout;
      var applied_query = '';
      
      /**
       * Do the search
       */
      var do_search = function () {
        if (search_timeout) {
          clearInterval(search_timeout);
        } //if
        
        var selector = '';
        var query = $.trim(input.val().toLowerCase().replace(/\"/g, ''));
        
        if(query == applied_query) {
          return;
        } else {
          applied_query = query;
          
          $.each(query.split(' '), function (index, search_fragment) {
            if (search_fragment) {
              selector += '[' + settings['search_index_attribute'] + '*="' + search_fragment + '"]';
            } // if
          });
          
          target.find(settings['rows']).hide();
          target.find(settings['rows'] + selector).show();
          
          if(typeof(settings['success']) == 'function') {
            settings['success'].apply(input[0], [ target[0] ]);
          } // if
        } // if
      }; // do_search
      
      // Handle search input events
      input.bind('click keydown', function (event) {
        if (event.type == 'keydown' && event.keyCode == 27) {
          input.blur().attr('value', '').focus();
          do_search();
        } else if (event.type == 'keydown' && event.keyCode == 13) {
          do_search();
        } else {
          if (search_timeout) { 
            clearTimeout(search_timeout);
          } //if
          search_timeout = setTimeout(do_search, 300);
        } // if
      });
    } // if
  });
  
};