// (c) 2008, Joern Schou-Rode <jsr@malamute.dk>
// http://plugins.jquery.com/project/filterable

/*
 * Called as "$(var).filterable(options)" where 'options' is a JS object
 * with the following possible properties:
 *
 * affects : { '> *' | any_selector }
 *	Specifies the selector used to determine which elements are to
 *	be filtered.  The default selector says "all immediate children".
 * queryLabel : { '' | any_string }
 *	The value that should appear in front of the text field that is
 *	the filterable's query string.
 * queryButton : { '' | any_string }
 *	The button image that should appear after the filterable's text
 *	field that causes the filtering to take place.  Specifying this
 *	value replaces the filter-on-every-keystroke default.
 * queryPosition : { 'before' | 'after' }
 *	Where the new set of query elements (label, text field, button)
 *	should apear in relation to the element being filtered.
 * queryCss : { 'ui-filterable-query' | any_class }
 *	The CSS class used to control how query elements are rendered.
 */
(function($) {
    $.fn.filterable=function(options) {
	var o=$.extend({},$.fn.filterable.defaults,options);
	return this.each(function() {
	    var target=$(this);
	    var div=$('<div class="'+o.queryCss+'">');
	    switch (o.queryPosition) {
	    case 'before' :
		div.insertBefore(target);
		break;
	    case 'after' :
		div.insertAfter(target);
		break;
	    }
	    var txt=$('<input type="text" />').appendTo(div);
	    if (o.queryLabel)
		div.prepend('<label>'+o.queryLabel+'</label>');
	    var fn=function() {
		var query=txt.val().toLowerCase();
		target.find(o.affects).each(function() {
		    var item=$(this);
		    if (item.text().toLowerCase().indexOf(query) >= 0)
			item.show();
		    else
			item.hide();
		});
	    };
	    if (o.queryButton)
		$('<input type="button" value="'+o.queryButton+'" />')
		    .appendTo(div)
		    .click(fn);
	    else
		txt.keyup(fn);
	});
    };
    $.fn.filterable.defaults = {
	affects : '> *',
	queryLabel : '',
	queryButton : '',
	queryPosition : 'before',
	queryCss : 'ui-filterable-query'
    };
})(jQuery);
