/*
 This is the jquery validation JSON object
*/

function getValidation() {
	var baseUrl = $("#baseUrl").text();
	return  {
		debug: true,
		rules: {
			"user.userName": {
				required: true,
				remote:  {
					url: baseUrl + "users/unique",
					type: "get",
					data : {
						"user.userName" : "",
						idNot: function() {
							var field = $("input[name='user.userName']").parents("form").find("input[name='user.id']");
							if (field.length > 0) {
								return field.val();
							} else {
								return "";
							} 
						},						
						userName: function() { return $("input[name='user.userName']").val(); }
					}
				}
			},
			
			"user.password": "required",
			
			"user.email": {
				required: true,
				email: true,
				remote:  {
					url: baseUrl + "users/unique",
					type: "get",
					data : {
						"user.email" : "",
						idNot: function() {
							var field = $("input[name='user.email']").parents("form").find("input[name='user.id']");
							if (field.length > 0) {
								return field.val();
							} else {
								return "";
							} 
						},
						email: function() { return $("input[name='user.email']").val(); }
					}
				}
			},
			
			"retypePassword": {
				equalTo: "#password"
			},
	   		
		    "retypeEmail": {
				equalTo: "#email"
			}
	  	},

		messages: {
			"user.userName": {
				required: "Enter a username",
				remote: "User name already taken"
			},
			
			"user.password": "Enter in a password",
			
			"user.email": {
				required: "Enter an e-mail address",
				email: "Enter a valid e-mail address",
				remote: "E-mail already taken"
			},
			
			"retypePassword": {
				equalTo: "Please type in the same password again"
			},
	   		
		    "retypeEmail": {
				equalTo: "Please type in the same e-mail again"
			}
		},
		
		submitHandler: function(form) {
			form.submit();
		}
	};
}

$(document).ready(function() {
	// Bind the buttons to on the admin page to show the form via ajax
	$(".showFormButton").click(function() {
		// Get the form responsible for triggering this
		var form = $(this).parents("form");
		
		// Rewrite the URL to use partial (ajax version)
		$(form).attr("action", "partial/" + $(form).attr("action"));

		// Get the target cell to retrieve the ajax form
		var targetCell = $(form).parents("tr").next().children();
		
									
		$(form).ajaxSubmit({
				"target": $(targetCell),
				"success": function() {
					$(form).parents("tr").hide();
					$(targetCell).parent().show();
							
					// See documentation:
					// http://docs.jquery.com/Plugins/Validation
					$(targetCell).children("form").validate(getValidation());
				}
			});

		return false;
	});
});
