$('document').ready(function(){
	/* Loads the makes into the dropdown if the user goes back to do a re-search. */
	if($('#make').val().length || $('#engine').val().length){
		updateForm();			
	}
	
	$('#make').change(function(){
		$('#model').empty();
			
		if(!allClear()){
			updateForm();	
		}else{
			$('#counter').css('visibility','hidden');
		}
	});
	
	$('#engine').change(function(){
		$('#model').empty();
			
		if(!allClear()){
			updateForm();	
		}else{
			$('#counter').css('visibility','hidden');
		}
	});
	
	$('#capacity').keyup(function(){
		$('#model').empty();
		
		if (!allClear()){
			updateForm();
		}
	});
	

	// Truck Store search form - update on change of any form fields
	function updateForm(){
		// Call the models for this selection
		$.ajax({
			type: "POST",
			url: "/getModels.cfm",
			data: { 'make': $('#make').val(),
					'truckType': $('#searchType').val(),
					'engine': $('#engine').val(),
					'capacity': $('#capacity').val()
			},
			success: function(data){
				if(data.length > 0){
					var valueArray = data.split(',');
					var options = '';
					
					for(var i=0; i < valueArray.length; i++){
	  					 options += '<option value="' + valueArray[i] + '">' + valueArray[i] + '</option>';
					}
					
					$('#model').html(options);
				}
			}
		});
		
		// Update the counter result
		$.ajax({
			type: "POST",
			url: "/getModels.cfm?count=1",
			data: { 'make': $('#make').val(),
					'truckType': $('#searchType').val(),
					'engine': $('#engine').val(),
					'capacity': $('#capacity').val()					
			},
			success: function(data){
				if(data.length > 0){
					$('#counter').css('visibility','visible');
					$('#counter span').html(data);
				}
			}
		});
	};
	
	function allClear(){
		if(!$('#make').val().length && !$('#engine').val().length){
			return true;
		}else{
			return false;
		}
	}
});