$(document).ready(
	function (){
		// disable form submission and the makes and models lists
		// until user selects year, make and model data
		$('#button').attr("disabled", true); 
		$('#chrome_make').attr("disabled", true); 
		$('#chrome_model').attr("disabled", true); 
		$('#miles').attr("disabled", true); 


		// listen for changes to the year select-list; load available makes
		$('#chrome_year').change(function() { 
			$.ajax({url: '/chrome/query.php',  data: {year: $('#chrome_year').val()}, dataType: 'html', success: function(data) { make_update(data); }
			});
		});

		// listen for changes to the make select-list; load available models
		$('#chrome_make').change(function() { 
			$.ajax({
				url: '/chrome/query.php',  data: {year: $('#chrome_year').val(), make: $('#chrome_make').val()}, dataType: 'html', success: function(data) { model_update(data); }
			});
		});



		// submit the form using SEF URL values
		$('#button').click(function() { 
			// cause the Spry validation handlers to kick in
			$('#chrome_model').focus().blur();
			$('#miles').focus().blur(); 

			if ($('#chrome_year').val() && $('#chrome_make').val() && $('#chrome_model').val() && $('#miles').val())
			{
				$('#year').val($('#chrome_year').val());
				$('#make').val($('#chrome_make option:selected').text());
				$('#model').val($('#chrome_model option:selected').text());
			}
			
			return true;
		}); 


		
		/**
		 * update the makes-list
		 * @param string data: HTML string of <option> elements, including initial empty element
		 * @return void
		 */
		function make_update(data)
		{
			$('#chrome_make').empty();
			$('#chrome_make').append(data);
			$('#chrome_make').removeAttr('disabled'); 
		}
		
		
		
		/**
		 * update the models-list
		 * @param string data: HTML string of <option> elements, including initial empty element
		 * @return void
		 */ 
		function model_update(data)
		{
			$('#chrome_model').empty();
			$('#chrome_model').append(data);
			$('#chrome_model').removeAttr('disabled'); 
			$('#miles').removeAttr('disabled'); 
			$('#button').removeAttr('disabled'); 
		}
	}
);


