// JavaScript Document
$(document).ready(function() {
	// validate signup form
	// remove text from default error messages
	jQuery.validator.messages.required = "";
	jQuery.validator.messages.email = "";
	jQuery.validator.messages.equalTo = "";
	$("#kRegForm").validate({
		// define rules
		rules: {
			kRUser: {
				required: true
			},
			kRPass: {
				required: true
			},
			kRPassConf: {
				required: true,
				equalTo: "#kRPass"
			},
			kREmail: {
				required: true,
				email: true
			},
			recaptcha_response_field: {
				required: true
			}
		},
		// put the default error labels in the error box for non-use
		errorPlacement: function(error, element) {
			error.appendTo($("#reg-error-box"));
		},
		// highlight the faulty fields
		highlight: function(element, errorClass) {
			if($(element).attr("name")=="recaptcha_response_field") {
				$("label[for='recaptcha_response_field']").addClass("red");
			} else {
				$(element).prevAll("label").addClass("red");
			}
		},
		// unhighlight the faulty fields
		unhighlight: function(element, errorClass) {
			if($(element).attr("name")=="recaptcha_response_field") {
				$("label[for='recaptcha_response_field']").removeClass("red");
			} else {
				$(element).prevAll("label").removeClass("red");
			}
		},
		// control the error box. tell how many errors there are
		showErrors: function(errorMap, errorList) {
			if(this.numberOfInvalids()>1) {
				$("#reg-error-box").html("Your registration contains " + this.numberOfInvalids() + " errors.");
			} else if(this.numberOfInvalids()==1) {
				$("#reg-error-box").html("Your registration contains " + this.numberOfInvalids() + " error.");
			} else {
				$("#reg-error-box").html("* Required fields");
			}
			this.defaultShowErrors();
		},
		// submit when it's ready
		submitHandler: function() {
			$.post("includes/k-register.php", $("#kRegForm").serialize(), function(data) {
				if(data) {
					// give the user the problem in the error box
					$("#reg-error-box").html(data);
					if(data=="The reCAPTCHA wasn't entered correctly. Please try again.") {
						$("#kRegForm label[for='recaptcha_response_field']").addClass("red");
						$("#recaptcha_response_field").val("");
						Recaptcha.reload();
					} else if((data=="A user is already registered with this username.") || (data=="Please choose a username with only letters and numbers.")) {
						$("#userLabel").addClass("red");
						$("#kRegForm input[name='kRUser']").focus();
					}
				} else {
					window.location = "user-command.php";
				}
			});
		}
	});
});