const validationPage = "https://cloud.email.tefal.de/TEF_DE_CIP_v2_ParticipationCode_Validation";
$(document).ready(function () {

  // Method added to the validator for extra validation of the email
  $.validator.addMethod(
    /* The value you can use inside the email object in the validator. */
    "regex",
    /* The function that tests a given string against a given regEx. */
    function(value, element, regexp)  {
        /* Check if the value is truthy (avoid null.constructor) & if it's not a RegEx. (Edited: regex --> regexp)*/
        if (regexp && regexp.constructor != RegExp) {
           /* Create a new regular expression using the regex argument. */
           regexp = new RegExp(regexp);
        }
        /* Check whether the argument is global and, if so set its last index to 0. */
        else if (regexp.global) regexp.lastIndex = 0;
        /* Return whether the element is optional or the result of the validation. */
        return this.optional(element) || regexp.test(value);
    }
  );

  // Debounce function
  function debounce(func, wait) {
    let timeout;
    return function(...args) {
      clearTimeout(timeout);
      timeout = setTimeout(() => func.apply(this, args), wait);
    };
  }


  $("#form-validate").validate({
    onfocusout: function(element) {
      $(element).valid();
    },
   onkeyup: debounce(function(element) {
      $(element).valid();
    }, 500),
    rules: {
      EmailAddress: {
        required: true,
        minlength: 2,
        regex: /^\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i,
      },
      gender: {
        required: true,
      },
      firstname: {
        required: true,
        minlength: 2,
      },
      lastname: {
        required: true,
        minlength: 2,
      },
      "participation-code": {
        required: true,
        minlength: 2,
        remote: {
          url: validationPage,
          type: "GET",
          data: {
            ParticipationCode: function () {
              return $("#participation-code").val();
            },
            EmailAddress: function () {
              return $("#EmailAddress").val();
            }
          },
          dataFilter: function (response) {
            var json = JSON.parse(response);
            if (json.IsValidParticipationCode === false) {
              return JSON.stringify([false, json.ErrorType]);
              participationCodeValid = false;
            } else {
              return true;
              participationCodeValid = true;
            }
          },
        },
      },
    },
    messages: {
      EmailAddress: "Ungültiges E-Mail Format",
      gender: "Bitte Geschlecht auswählen",
      firstname: "Bitte Vorname eintragen",
      lastname: "Bitte Nachname eintragen",
      "participation-code": {
        required: "Bitte Teilnahmecode eintragen",
        minlength: "Bitte geben Sie mindestens 2 Zeichen ein",
      },
    },
    errorPlacement: function (error, element) {
      if (element.attr("name") == "participation-code") {
        error.insertAfter(element.parent());
      } else {
        error.insertAfter(element);
      }
    },
    submitHandler: function (form) {
      // Get the value of the participation code field
      var participationCode = $("#participation-code").val();

      // Perform the AJAX validation
      $.ajax({
        url: validationPage,
        type: "GET",
        data: {
          ParticipationCode: participationCode,
          EmailAddress: $("#EmailAddress").val(),
        },
        dataType: "json",
        success: function (response) {
          if (response.IsValidParticipationCode) {
            // The participation code is valid, submit the form
            form.submit();
          } else {
            // The participation code is not valid, show an error message
            $("#form-validate").valid(); // Activate the form validation
             $("#form-validate").validate().showErrors({
              "participation-code": response.ErrorType,
            });
          }
        },
        error: function (error, element) {
           $("#form-validate").validate().showErrors({
              "participation-code": response.ErrorType,
            });
        },
      });

      // Prevent the form from being submitted automatically
      return false;
    },
  });
});