"use strict";

document.addEventListener("DOMContentLoaded", () => {
  const handler = (event) => {
    if (!event.target.checkValidity()) {
      event.preventDefault();
      event.stopPropagation();
    }

    event.target.classList.add("was-validated");
  };

  const addValidation = () => {
    const forms = document.querySelectorAll(".needs-validation");

    Array.from(forms).forEach((form) => {
      form.addEventListener("submit", handler, false);
    });
  };

  const removeValidation = () => {
    const forms = document.querySelectorAll(".needs-validation");

    Array.from(forms).forEach((form) => {
      form.removeEventListener("submit", handler, false);
    });
  };

  const switchHandler = () => {
    _switch.checked ? addValidation() : removeValidation();
    document.cookie = `validation=${_switch.checked}`;
  };

  const _switch = document.getElementById("clientSideValidate");
  _switch.addEventListener("change", switchHandler);
  switchHandler();
});
