/* jslint verified 2009.06.29 */
/*jslint browser: true, onevar: true, undef: true, white: false, eqeqeq: true, immed: true, cap: false  */
/*globals $, jQuery */

jQuery.validator.setDefaults({
	debug: true,
	success: 'valid'
});

$(document).ready(function (){
	var acceptTermsMsg = "You must agree to the Terms of Service",
		valObj = {
		// Note: the rules and messages should be kept in sync with joinProcess.inc
			rules: {
				contactName: {
					required: true,
					minlength: 3,
					maxlength: 100
				},
				contactEmail: {
					required: true,
					email: true,
					maxlength: 100
				},
				joinPassword: {
					required: true,
					minlength: 5
				},
				retypePassword: {
					required: true,
					minlength: 5,
					equalTo: '#joinPassword'
				},
				termsCheckbox: {
					required: true
				}
			},
			messages: {
				contactName: {
					required: 'Please enter a contact name',
					minlength: 'Your contact name must be between 3 and 100 characters',
					maxlength: 'Your contact name must be between 3 and 100 characters'
				},
				contactEmail: 'Please enter a valid email address',
				joinPassword: {
					required: "Please provide a password",
					minlength: "Your password must be at least 5 characters"
				},
				retypePassword: {
					required: "Please provide a password",
					minlength: "Your password must be at least 5 characters",
					equalTo: "Please enter the same password as above"
				},
				termsCheckbox: {
					required: acceptTermsMsg
				}
			},
			submitHandler: function (form) {
				form.createAccount.disabled = 'disabled';
				$(form.createAccount).addClass('disabled');
				form.submit();
			},
			invalidHandler: function(form, validator) {
				if (validator.errorMap && validator.errorMap.termsCheckbox) {
					$("#joinForm div.termsCheckBox").addClass('error');
				} else {
					$("#joinForm div.termsCheckBox").removeClass('error');
				}
			},
			errorPlacement: function (error, element) {
				// The error labels are already added in the DOM after the inputs, so just update them
				var errorLabel = element.next('label');
				errorLabel.replaceWith(error);
			}
		};
	if ($('#joinForm div.radio input[name=IODAmp3type]').length === 2) {
		valObj.rules.IODAmp3type = {required: true};
		valObj.messages.IODAmp3type = {required: "Please select an account type"};
	}
	$('#joinForm').validate(valObj);
	
	$("#termsCheckbox").click(function() {
		var errorLabel = $(this).parent().parent().next('label');
		if (!$(this).is(':checked')) {
			$("#joinForm div.termsCheckBox").addClass('error');
			errorLabel.addClass('error').removeClass('valid').text(acceptTermsMsg);
		} else {
			$("#joinForm div.termsCheckBox").removeClass('error');
			errorLabel.removeClass('error').addClass('valid').text('');
		}
	});
	
	$('#contactName').focus();
	
	// check if passwords still match after password changed
	//$('#joinPassword').blur(function () {
	//	$('#retypePassword').valid();
	//});
});