/*
 * Simple plug in for filtering the options in a select box
 * usage:
 * $.selectfilter.filter('[ID of select to filter]' ,  '[id of input that contains the text to filter on]');
 * 
 * Dependancies:
 * jquery.select.js
 */

( function($) {
	
	var __dictionary 	= {};
	var __refresh		= false;
	
	$.extend
	({
		selectfilter	: {
				filter	: function( selectID , filterID , displayID )//filters the selection option
				{
					var sSelect	= "#" + selectID;
					var sFilter	= "#" + filterID;
					var sDisplay	= "#" + displayID;
					
					var elemSelect	= $( sSelect );
					var elemDisplay	= $( sDisplay );
					
					var filterText	= $( sFilter ).val();
					
					if( !__dictionary[ selectID  ] || __refresh == true )//save the original optionlist
					{
						__dictionary[ selectID ] = { options : $( sSelect + " > option " ) , count : 0 };
						__refresh = false;
					}
					//empty the select
					elemSelect.removeOption(/./);
					//loop over the options
					__dictionary[ selectID ].count = 0;
					for( var i = 0 ; i < __dictionary[ selectID ].options.length ; i++ )
					{
						if( testFilter( __dictionary[ selectID ].options[ i ] , filterText ) )
						{
							thisElem = $( __dictionary[ selectID ].options[i] ); //wrap it in jQuery goodness
							elemSelect.addOption( thisElem.val() ,thisElem.attr("text"));
							__dictionary[ selectID ].count++;
						}
					}
					
					elemDisplay.html( __dictionary[ selectID ].count );
				}
			,	refresh	: function( value )
				{
					if( value ) __refresh = value;
					return __refresh;
				}
			,	total	: function( selectID )
				{
					return __dictionary[ selectID ].options.length;
				}
			, 	count	: function( selectID )
				{
					return __dictionary[ selectID ].count;
				}
		}
	});
	
	
	var testFilter = function( option , text )
	{
		var bReturnValue = ( $( option ).attr("text").toLowerCase().indexOf( text.toString().toLowerCase() ) != -1 );
		return bReturnValue;
	}
}

)( jQuery )