// JavaScript Document
/*
 * jQuery.liveFilter
 *
 * Copyright (c) 2009 Mike Merritt
 *
 * Forked by Lim Chee Aun (cheeaun.com)
 * 
 */
 
(function($){
	$.fn.liveFilter = function(inputEl, filterEl, options){
		var defaults = {
			filterChildSelector: null,
			filter: function(el, val){
				return $(el).text().toUpperCase().indexOf(val.toUpperCase()) >= 0;
			},
			before: function(){},
			after: function(){}
		};
		var options = $.extend(defaults, options);
		
		var el = $(this).find(filterEl);
		if (options.filterChildSelector) el = el.find(options.filterChildSelector);

		var filter = options.filter;
		$(inputEl).keyup(function(){
			var val = $(this).val();

			var contains = el.filter(function(){
				result = filter(this, val);
				if(!result)
				{
					str = val.toLowerCase();	
					var from = "ã� áäâèéëêìíïîõòóöôùúüûñç·/_,:;";
					var to   = "aaaaaeeeeiiiiooooouuuunc------";
					for (var i=0, l=from.length ; i<l ; i++)
					{
						str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
					}
					
					straold = this.innerHTML;
					stra = "";
					if (this.textContent)
					{
						stra = this.textContent.toLowerCase();
					}
					else
					{
						stra = this.innerText.toLowerCase();	
					}
					var from = "ã� áäâèéëêìíïîõòóöôùúüûñç·/_,:;";
					var to   = "aaaaaeeeeiiiiooooouuuunc------";
					for (var i=0, l=from.length ; i<l ; i++)
					{
						stra = stra.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
					}
					//str = str.replace(/[^a-z0-9 -]/g, '').replace(/\s+/g, '-').replace(/-+/g, '-');
					
					if (this.textContent)
					{
						this.textContent = stra;
					}
					else
					{
						this.innerText = stra;
					}
					result = filter(this, str);
					this.innerHTML = straold;
					if(result)
					{						
						return true;
					}
					return false;
				}
				return result;
			});
			var containsNot = el.not(contains);
			if (options.filterChildSelector){
				contains = contains.parents(filterEl);
				containsNot = containsNot.parents(filterEl).hide();
			}
			
			options.before.call(this, contains, containsNot);
			
			containsNot.parent().parent().find('h3').hide();
			contains.parent().parent().find('h3').show();
			
			contains.show();
			//containsNot.hide();
			
			if (val === '') {
				contains.show();
				containsNot.show();
			}
			
			options.after.call(this, contains, containsNot);
		});
	}
})(jQuery);