jQuery(document).ready(function($) {	
	if ($('#reqoutward').is(":checked")) {
		// do nothing
	} else {
		$('#outfields').hide();
	}
	
	if ($('#reqreturn').is(":checked")) {
		// do nothing
	} else {
		$('#retfields').hide();
	}
	
	if ($('#bd_address').val()) {
		// do nothing
	} else {
		$('#x_address').hide(); // hides the forms on loading
	}
	
	// if the first checkbox is clicked, check if the box is checked or not, and show or hide the form.
	$('#reqoutward').click(function(){
		if ($('#reqoutward').is(":checked")) {
			$('#outfields').slideDown('slow');
		} else {
			$('#outfields').slideUp('slow');
		}
	});
	
	$('#reqreturn').click(function(){
		if ($('#reqreturn').is(":checked")) {
			// need to check flag, if not set, copy data over
			if ($('#returncopy').val() == 0) {
				var selectedIndex = $('#pu_town').attr('selectedIndex'); 
				$('#ret_town').attr('selectedIndex', selectedIndex).change();
				var selectedIndex = $('#pu_adults').attr('selectedIndex'); 
				$('#ret_adults').attr('selectedIndex', selectedIndex).change();
				var selectedIndex = $('#pu_kids').attr('selectedIndex'); 
				$('#ret_kids').attr('selectedIndex', selectedIndex).change();
				var selectedIndex = $('#pu_dest').attr('selectedIndex'); 
				$('#ret_pickup').attr('selectedIndex', selectedIndex).change();
				$('#returncopy').val('1')
			}
			$('#retfields').slideDown('slow');
		} else {
			$('#retfields').slideUp('slow');
		}
	});
	
	$('#bd_getaddr').click(function() {
		var pcode = $('#bd_postcode').val();
		if (pcode != "") {
			$.post("/wp-content/themes/efcars/postcode-lookup.php", {pcode: pcode}, function(data) {
				if (data == 1) {
					// echo the error that the postcode is invalid
					$('#errormsg').html('<p>Your Postcode is invalid. Please check and try again.</p>');
				} else if (data == 2) {
					// postcode error or couldn't be found, so need manual address box
					$('#errormsg').html('<p>Unable to find your address. Please complete the address box below.</p>');
					$('#x_address').slideDown();
				} else {
					// select list created
					$('#errormsg').text('');
					$('#addressbox').html('<select id="bd_address" name="bd_address">' + data + '</select>');
					$('#x_address').slideDown();
				}
			});
		}
		return false;
	});
});
