$.createNamespace("rainier.account");
$(function() {
	/**
	 * This function sets up the registration form. It finds all required fields
	 * and make its label red. It also sets up the blur and the enter key for
	 * the fields.
	 */
	rainier.account.setupRegistrationForm = function() {
		$('.userRegistration .formInput').keyup(
				function(e) {
					if (e.keyCode == 13) {
						$('.registerForm .registerButton').click();
					}
				});
		
		$('.userRegistration').validate({
			rules: {
				email: {
					required: true,
					email: true,
					remote: rainier.root + '/Account/VerifyEmail'
				},
				password: {
					required: true,
					minlength: 5
				},
				password2: {
					required: true,
					minlength: 5,
					equalTo: "#password"
				}
			},
			messages: {
				email: {
					required: " ",
					email: "Please enter a valid email address",
					remote: jQuery.validator.format("Email address is already taken.")	
				},
				password: {
					required: "Please provide a password",
					minlength: "Your password must be at least 5 characters long"
				},
				password2: {
					required: "Please provide a password",
					minlength: "Your password must be at least 5 characters long",
					equalTo: "Please enter the same password as above"
				}
			}
		});
	};
	
	rainier.account.setupRegistrationLink = function() {
		$('.registerLink').attr('href', rainier.root + '/Account/RegisterPartial');
		$('.registerLink').fancybox({
			'hideOnContentClick': false,
			'callbackOnShow': rainier.account.setupRegistrationForm,
			'frameWidth': 350,
			'frameHeight': 400
		});
	};
	
	rainier.account.register = function(e) {
		if ($('.userRegistration').valid()) {
			var email = $('.userRegistration input[name=email]').attr('value');
			var password = $('.userRegistration input[name=password]').attr('value');
			$.jsonRpc('Account', 'Register', email, password, function(resp) {
				if (resp === true) {
					location.reload();
				}
			});
		}
		
		return false;
	}

	$(document).ready(function() {
		rainier.account.setupRegistrationLink();
		$('.registerButton').click(rainier.account.register);
	});
});
