$(document).ready(function()
{
	/* On a refresh, make sure the first select is not already set */
	if(document.getElementById('category_id'))
	{
		$('#category_id')[0].selectedIndex = 0;
	}


	/* Update first select box */
	$('#category_id').livequery('change', function()
	{
		$('#prices').slideUp('fast', function()
		{
			$('#prices').html('');
		});
		fetchData('manufacturers', $(this).val());
	});


	/* Update second select box */
	$('#manufacturer').livequery('change', function()
	{
		fetchData('prices', $('#category_id').val(), $(this).val());
	});


	/* Fetch the results */
	function fetchData(action, category_id, manufacturer)
	{
		if(action == 'prices' && parseInt(manufacturer) == 0)
		{
			$('#' + action).slideUp('fast', function()
			{
				$('#' + action).html('');
			});
		}
		else if(parseInt(category_id) == 0)
		{
			$('#' + action).slideUp('fast', function()
			{
				$('#' + action).html('');
			});
		}
		else
		{
			$('#' + action).html('<div style="text-align: center; padding-top: 15px;">Even geduld a.u.b.</div>');
			$('#' + action).slideDown('fast');
			
			var arguments = 'id=' + category_id;
			if(manufacturer !== undefined) arguments += '&m=' + manufacturer;
			
			$.ajax(
			{
				type: "POST",
				url: '/dbt_search/' + action,
				data: arguments,
				success: function(result)
				{
					if(result == '0')
					{
						$('#' + action).slideUp('fast');
					}
					else $('#' + action).html(result);
				}
			});
		}
	}


	/* Submit the search request */
	$('#dbtSearchSubmit').livequery('click', function()
	{
		var category_id = $('#category_id').val();
		var manufacturer_id = $('#manufacturer').val();
		var price_range = $('#price_range').val();
		
		if(manufacturer_id === undefined) 	manufacturer_id = 0;
		if(price_range === undefined) 		price_range = 0;
		
		$.ajax(
		{
			type: "GET",
			url: '/dbt_search/results',
			data: 'ajax=true&id=' + category_id + '&m=' + manufacturer_id + '&range=' + price_range,
			success: function(result)
			{
				if(document.getElementById('text')) 			$('#text').html(result);		/* If located on a dbt_search page */
				else if(document.getElementById('catalogus'))	$('#catalogus').html(result); 	/* If located on a normal page */
			}
		});
	});
});
