/**
 * @author Ant1j
 * 
 * Code inspired from jquery.suggest
 * Concept from Django Admin filter list : http://simonwillison.net/static/2008/xtech/ (slide 18)
 * 
 * Usage: $('select.filter').filterselect();
 * Options: minChars => minimum characters needed to filter
 */

(function($) {
  			$.filterselect = function (select, options) {
  				var originalrows = select.find('option');
  				var prevLength = 0;
  				var timeout = false;
				
  				select.id = select.attr('id');
  				select._width = select.width();
  				
				// Add an input
				select.wrap('<div></div>')
					.parent().css('width', select._width);
  				select.width(select._width);
				select.before('<input type="text" id="i_' + select.attr('id') + '" />');
				// Style input
				$input = $('#i_' + select.id).addClass('filter');
				$input.width(select._width-18);
  				
  				if ($.browser.mozilla)
					$input.keypress(processKey);	// onkeypress repeats arrow keys in Mozilla/Opera
				else
					$input.keydown(processKey);		// onkeydown repeats arrow keys in IE/Safari
			
				//
				function processKey(e) {
					if ($input.val().length != prevLength) {
						if (timeout) 
							clearTimeout(timeout);
						timeout = setTimeout(filtre, 300);
						prevLength = $input.val().length;	
					}		
					
					// Keep the "good" option tags
					function filtre() {	
						var q = $.trim($input.val());
						var rows = originalrows;
						if (q.length >= options.minChars)
							rows = parseRows(rows, q);
						select.html('');
						select.html(rows);
					}
					
					function parseRows(or, q) {
						return or.filter(function (i) {
							var txt = $(this).text();
							var re = new RegExp(q, 'ig');
					
							if (re.test(txt)) return $(this);
						});
					}
							
				}
		
  			};
  			
  			$.fn.filterselect = function (options) {
  				
  				var defaults = { minChars: 2 } ;
  				var $this = $(this);
  				var $options = $.extend({}, defaults, options); 
  				
  				this.each(function() {
					new $.filterselect($this, $options);
				});
				return this;
  			};
})(jQuery);
  	