var filterForm = function(el)
{
	var filter = this;
	filter.counts = {};
	filter.form = [];
	filter.action = '';
	filter.submit = [];
	

	var update = function()
	{
		var data = {
			ajax	: 1,
			filter: 'update'
		};
		filter.form.find('select, input:hidden, input:checked').each(function()
		{
			data[this.name] = $(this).val();
		});
		
		//var loading = $('<span id="filter-loading"></span>').appendTo($(filter.submit.parent()));
		
		// submit and update the filter
		$.ajax({
			type		: 'POST',  
			url			: filter.action,
			data		: data,
			dataType: 'json',
			success	: function(response)
			{
				$.each(filter.counts, function(index)
				{
					var value = typeof response[index] === undefined ? '?' : response[index];
					var property = 'text';
					switch(this.get(0).tagName)
					{
						case 'INPUT':
							this.val( this.val().replace(/\((.+?)\)/, '(' + value + ')') );
							break;
						case 'SPAN':
						default:
							this.text( this.text().replace(/\((.+?)\)/, '(' + value + ')') );
							break;
					}
					
					//loading.remove();
					
				});
			}
		});
		
	}


	var init = function()
	{
		filter.form = $(el);
		filter.action = form.attr('action');
		filter.submit = filter.form.find('input:submit:first');
		
		filter.form.bind('update', update);
		
		form.find('span.count').each(function()
		{
			var el = $(this);
			filter.counts[el.attr('id')] = el;
		});
		filter.counts['count_total'] = filter.form.find('input:submit:first');
		form.find('input, select').bind('change', update);
	}
	
	init();
}




$().ready(function() {
	
	filterForm('form#filter');

});
