// jQuery's function launched when everything is ready
$(document).ready(function() {
	
	// Focus first field
	$('#birthYear').focus();
	
	
	// Show province or state for Canada or USA
	$('#countryCode').change(function() {

		$('#StateInput').fadeOut("fast");
		$('#ProvinceInput').fadeOut("fast");
		
		$('#usState').val('');
		$('#canadianProvince').val('');
		
		if ( $('#countryCode').val() == 'CA' ) {
			$('#ProvinceInput').fadeIn("fast");
		} else if ( $('#countryCode').val() == 'US' ) {
			$('#StateInput').fadeIn("fast");
		}
		
	});
	
	
	// Attaches desired validation to form elements
	// 
	// Note: US states and Canadian provinces are not mandatory. This is to allow 
	// non-javascript enabled browsers to still be able to use the form
	$("#survey").validate({
	    
	    errorElement: "p",
	    
	    errorPlacement: function(error, element) {
           element.parent().before(error);
        },
	    
		rules: {
			birthYear: "required",
			countryCode: "required",
		 	email: "email",
		 	weight: "weight",
		 	height: "height"
	   }
						  
	});

	
	jQuery.validator.addMethod("weight", function( value, element ) {
	    
	    var result = false;
	    
	    if (document.getElementById('survey').weightUnit.value == 'pound') {
	        if (value >= 66 && value <= 1300) { result = true}
	    } else {
	        if (value >= 30 && value <= 600) { result = true}
	    }
	    
	    if (value == '') { result = true; }

		return result;
	}, "Invalid weight");
	
	
	jQuery.validator.addMethod("height", function( value, element ) {
	    
	    var result = false;
	    
	    if (document.getElementById('survey').heightUnit.value == 'inch') {
	        if (value >= 20 && value <= 105) { result = true}
	    } else {
	        if (value >= 50 && value <= 275) { result = true}
	    }
	    
	    if (value == '') { result = true; }

		return result;
	}, "Invalid height");
	
	
	
    // Make sure only numbers are entered for weight and height (using jQuery
    // AlphaNumeric plug-in)
    $('#weight, #height').numeric();

	   
}); // end ready