$(document).ready(function (e) {

  $("#password-change").on("submit", function (e) {
    
    e.preventDefault();
    
    const pass1 = document.getElementById("c-password1").value;
    const pass2 = document.getElementById("c-password2").value;
    
    let result = confirm(
      "Are you sure you want to change your password?"
    );
    
    if (pass1 !== pass2) {
        alert('Your new passwords does not match');
        document.getElementById("c-password1").value = '';
        document.getElementById("c-password2").value = '';
        return;
    }
    
    if (pass1.length < 8){
        alert('Your password is less than 8 characters');
        document.getElementById("c-password1").value = '';
        document.getElementById("c-password2").value = '';
        return;
    }

    if (result === false) {
      return;
    }

    let form = document.getElementById("password-change");

    document.getElementById("passwordSubmit").disabled = true;
    document.getElementById("passwordSpinner").classList.add("spinner-grow");
    document.getElementById("passwordSpinner").classList.add("spinner-grow-sm");

    $.ajax({
      type: "POST",
      url: "./api/password.php",
      data: new FormData(form),
      contentType: false,
      cache: false,
      processData: false,
      success: function (resp) {
        if (resp.data == 1) {
          alert(resp.message);
        } else {
          alert("Something Wrong Happened! Please contact Support!");
        }
      },
      fail: function (xhr, textStatus, errorThrown) {
        alert("Password change failed");
      },
      error: function (e) {
        alert("Password change failed");
        done();
      },
    }).done(function () {
      done();
    });
  });
});

function done() {
  document.getElementById("passwordSubmit").disabled = false;
  document.getElementById("passwordSpinner").classList.remove("spinner-grow");
  document.getElementById("passwordSpinner").classList.remove("spinner-grow-sm");
  document.getElementById("password").value = '';
  document.getElementById("c-password1").value = '';
  document.getElementById("c-password2").value = '';
}
