$(document).ready(function(){
    var url = 'http://' + window.location.hostname + '/index.php?id=' + $('#filter input[name=resultPid]').val() + '&tx_peproducts_pi1[action]=ajax&type=1299484812';
    
	$('#filter p.numberOfProducts').hide();
    $('#filter select').change(function(){
	var data = $('#filter').serialize();
	
	$('.loaderImg').show();
	$.ajax({
	    type:	'POST',
	    url:	url, 
	    data:	data, 
	    dataType:	'json',
	    success:	function(e){
			    $('.loaderImg').hide();
			    if(e.category) {
				$('#filter select[name=\'tx_peproducts_pi1[category]\']').disableOptions(e.category);
			    }
			    if(e.model){
				$('#filter select[name=\'tx_peproducts_pi1[model]\']').disableOptions(e.model);
			    }
			    if(e.year){
				$('#filter select[name=\'tx_peproducts_pi1[year]\']').disableOptions(e.year);
			    }
			    if(e.hours){
				$('#filter select[name=\'tx_peproducts_pi1[hours]\']').disableOptions(e.hours);
			    }
			    $('#filter input[name=\'products\']').val(e.products);
			    $('#filter input[name=\'years\']').val(e.year);
			    $('#filter input[name=\'models\']').val(e.model);
			    $('#filter input[name=\'hourss\']').val(e.hours);
			    $('#filter input[name=\'categories\']').val(e.category);

			    $('#filter input[name=\'tx_peproducts_pi1[resultUids]\']').val(e.products);
			    $('#filter p.numberOfProducts').show();
			    $('#filter span.filterResults span').html(e.count);
			    if(e.count == '1') {
				$('#filter select').attr('disabled','disabled');
			    }
			}
	});
	$(this).attr('disabled','disabled');
	// Since a selection is present now, enable the submit button
	$('#filter input[type=submit]').removeAttr('disabled');
    });
    // Reset form 
    $('#filter span.reset').click(function(){
	$('#filter').get(0).reset();
	$('#filter select').removeAttr('disabled');
	$('#filter option').show();
	$('#filter input[name=\'products\']').val('');
	$('#filter input[name=\'years\']').val('');
	$('#filter input[name=\'models\']').val('');
	$('#filter input[name=\'hourss\']').val('');
	$('#filter input[name=\'categories\']').val('');
	$('#filter p.numberOfProducts').hide();
    });
});

(function( $ ){
    $.fn.disableOptions=function(e) {
	    jQuery(this).find('option').hide();
	    jQuery(this).find('option:eq(0)').show();
	    jQuery.each(e, function(index, value){
		jQuery('option:[value='+value+']').show();
	    });
    };
})( jQuery );
