function deleteFieldErrorMessages() {
  for (const property of document.getElementById('braintree-payment-form').elements) {
    property?.parentElement?.classList?.remove('has-error');
    if (property.nextSibling?.classList?.contains("help-block")) {
      property.nextSibling.remove();
    }
  }
}

function prepareAddressData() {
  var form = document.getElementById('braintree-payment-form');
  return JSON.stringify({
    "countryIso": form.elements['countryIso']?.value,
    "titleCode": form.elements['titleCode']?.value,
    "firstName": form.elements['firstName']?.value,
    "lastName": form.elements['lastName']?.value,
    "line1": form.elements['line1']?.value,
    "line2": form.elements['line2']?.value,
    "townCity": form.elements['townCity']?.value,
    "postcode": form.elements['postcode']?.value,
    "phone": form.elements['phone']?.value,
    "regionIso": form.elements['regionIso']?.value
  });
}

function handleAddressValidationErrors(err) {
  const currentSelectedOption = document.getElementById("billingAddressSelector")?.selectedOptions[0];
  if (currentSelectedOption?.value === "noAddress") {
    document.getElementById('billingAddressSelector').parentElement.classList.add('has-error');
  }
  showCustomAbsoluteErrorMessage("Please correct the errors below.");
  var json = JSON.parse(JSON.stringify(err));
  json.responseJSON.errors.forEach((element) => {
    document.getElementById('braintree-payment-form').elements[element.subject]?.parentElement.classList.add('has-error')

    var errorSpan = document.createElement("span");
    errorSpan.setAttribute("id", element.type);
    errorSpan.textContent = element.message;
    var errorDiv = document.createElement("div");
    errorDiv.setAttribute("class", "help-block");
    errorDiv.append(errorSpan);

    document.getElementById('braintree-payment-form').elements[element.subject]?.after(errorDiv);
  });

}
