/**
 * jQuery searcher plugin
 * This jQuery plugin add support to search filtering
 * @name jquery.filtering-0.1.js
 * @author Carlos Guedes - http://cguedes.workpress.com
 * @version 0.1
 * @date May 20, 2009
 * @category jQuery plugin
 * @copyright (c) 2009 Carlos Guedes
 * @license MIT
 * @example $("#Search").filtering("#studentsTable tbody tr", { minLength : 4, caseSensitive: true });
 */

(function($) {		
		
	// Extend the jquery expressions adding an Contains selector
	//  with the syntax :containsNoCase that matches the elements
	//  that contains the given text ignoring the case.
	// 
	// Font: http://stackoverflow.com/questions/187537/is-there-a-case-insensitive-jquery-contains-selector

	jQuery.expr[':'].inContains = function(a,i,m){ return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0; };


	/**
	* $ is an alias to jQuery object
	*
	*/
	$.fn.filtering = function(rowSelector, options) {
		
		// Extend our default options with those provided.
		// Note that the first arg to extend is an empty object -
		// this is to keep from overriding our "defaults" object.
		var opts = $.extend({}, $.fn.filtering.defaults, options);

		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object

		filter = function() {
			var text = jQueryMatchedObj.val();
			
			if (text.length < opts.minLength) {
				$(rowSelector).fadeIn();
				return;
			}
			
			// SCROLL TO TOP *** DELICI.EU MODIFIED
			if(opts.scrollto > 0){
				$.scrollTo( {top: opts.scrollto+'px'}, 800 );
			}

			// HIDE all elements that NOT matches the text
			$(rowSelector + ":not(:inContains('" + text + "'))").fadeOut();

			// SHOW all elements that matches the text
			$(rowSelector + ":inContains('" + text + "')").fadeIn();
		};

		if (opts.focus == true)
			this.focus();

		// Perform filtering with the current element state
		if(jQueryMatchedObj.val() != opts.default_value) { filter(); } 

		return this.keyup(filter);

	};

	// plugin defaults - added as a property on our plugin function
	$.fn.filtering.defaults = {
		minLength: 2,           // minimum length to perform search
		caseSensitive: false,   // sets if the search is case sensitive
		focus: false,
		scrollto: 0, 
		default_value: ''
	};

})(jQuery);                // Call and execute the function immediately passing the jQuery object
