$(document).ready(function(){
  
  // Form validation for our 'get in touch' page
  $("form#enquiry_form, form#join_our_club").validate({
    rules: {
      'content[name]': 'required',
      'content[email]': {required: true, email: true}
    },
    success: function(label) {
      label.text("Success!").addClass("success");
    },
    invalidHandler: function(form) {
      form_error(form.currentTarget, "Please fill in the required fields.")
        },
    submitHandler: function(form) {
      if($(form).valid()) {
        $.ajax({
          url:      $(form).attr('action'),
          data:     $(form).serializeArray(),
          type:     "post",
          success: function(data) {
            if (data.errors == null) {
              $('#enquiry_form').fadeOut(function(){
                $('#enquiry_thanks').fadeIn();
              })
                } else {
                  form_error(form, "Sorry, something went wrong. We will look into this as soon as possible.")
                    }
          },
          error: function(data) { 
            form_error(form, "Sorry, something went wrong. We will look into this as soon as possible.")
              }
        })
          }
      return false;
    }
  });
  
});

function form_error(form, message) {
  $(form).find('.errormessage').show().html(message)
}
