$(function(){
	
	// Validate forms, accounting for multiple forms on the same page.
	$('.custom-user-form').each(function(){
		$(this).submit(function(e) {
			e.preventDefault();
		}).validate({
			submitHandler: function(form){
				var formId = $(form).data('form-id');
				var postData = {
					data: $(form).serializeArray(),
					action: 'submit_custom_form',
					form_id: formId,
				}
				$.post('/ajax.forms', postData, function(res){
					displayResult(res, formId);
				});
				//console.log("---> Posting Custom Form!");
				//console.log(postData);
				//console.log("===========================================");
			}
		});
	});
	
	// Custom handling for required checkboxes
	jQuery.validator.addClassRules('cb-custom-req', {
		required: true,
		minlength: 1,
	});
	
	function displayResult(response, formId){
		$("#custom-result-msg-"+formId).html(response.message);
		$("#custom-result-msg-"+formId).slideDown(function(){
			if(response.success == 1){
				$("#custom-user-form-"+formId).slideUp();
				// Scroll to put success message in view
				var scrollTarget = $("#custom-result-msg-"+formId).parent().find('.custom-user-form-title').offset().top - 180;
				$('html, body').animate({
					scrollTop: scrollTarget
				}, 250);
			}
		});
	}
});