let iframes;
let payoneFieldsConfig;
let payoneCreditcardCheckConfig;

let titleOptions = [];
let langTries = 0;
let transENTries = 0;
let currentLang = "";
let clientIdFromGtag = "";

(function ($) {

  // Function to get clientId for GA4 using a Promise
  const getClientIdFromGtag = new Promise((resolve, reject) => {
    if (typeof gtag === "function" || typeof gtag === "object") {
      gtag("get", "G-FXKWYDZ05T", "client_id", resolve);
    } else {
      reject("gtag is not defined");
    }
  });

  setTimeout(function () {
    getClientIdFromGtag.then((client_id) => {
      clientIdFromGtag = client_id ? client_id : "";
    });
  }, 3000);

  const getParameterByName = function (name) {
    name = name.replace(/[\[\]]/g, "\\$&");
    let url = window.location.href;
    let regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
    let results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return "";
    return decodeURIComponent(results[2].replace(/\+/g, " "));
  };

  function notReqField(selector, validate) {
    let $selector = $("[name='" + selector + "'");
    if ($selector.length > 0) {
      $selector.attr("data-parsley-required", "false").parsley();
      $selector.parents(".input-field").find(".is-required").text("");
      if (validate) $selector.parsley().validate();
    }
  }

  function doReqField(selector, validate) {
    let $selector = $("[name='" + selector + "'");
    if ($selector.length > 0) {
      $selector.attr("data-parsley-required", "true").parsley();
      $selector.parents(".input-field").find(".is-required").text("*");
      if (validate) $selector.parsley().validate();
    }
  }

  // function processCCSubmit(payoneCreditcardPreauthParams) { ... }
  // function processPaypalSubmit(payonePaypalCheckConfig) { ... }

  function hideOverlay() {
    $("#overlay").hide();
    $("#overlay_processing").hide();
  }

  async function processDoNext(clickedButton) {
    $("#overlay").show();
    $("#overlay_processing").show();

    $("#donation-step-1 .radio_input").removeAttr("disabled");
    $("#donation-step-1 textarea").removeAttr("disabled", "disabled");

    let transferData = $("#donation_form").serialize();

    $("#donation-step-1 .radio_input").attr("disabled", "disabled");
    $("#donation-step-1 textarea").attr("disabled", "disabled");

    let addressType = $('[name="addresstype"]').val();
    let hiddenName = "";

    if (addressType != "000") {
      switch (addressType) {
        case "110": //Unternehmen
          hiddenName = "company";
          break;
        case "012": //Kirche
          hiddenName = "church";
          break;
        case "018": //Schule
          hiddenName = "school";
          break;
        default:
          break;
      }
      if (hiddenName != "") {
        transferData = transferData.replace("organisation", hiddenName);
      }
    }

    let clientId = "";

    // Function to get clientId from Universal Analytics (ga)
    function getClientIdFromGa() {
      if (typeof ga === "function" || typeof ga === "object") {
        if (ga.getAll) {
          return ga.getAll()[0].get("clientId");
        }
      }
      return null; // Return null if ga is not properly defined or getAll is not available
    }

    // Async function to set clientId
    async function setClientId() {
      try {
        clientId = clientIdFromGtag;
      } catch (error) {
        clientId = getClientIdFromGa() || "";
      }
      return clientId;
    }

    // Call the async function to set clientId
    clientId = await setClientId();

    transferData += "&client_id" + "=" + clientId;
    transferData += "&" + clickedButton + "=1";
    transferData += "&do_ajax=1";

    $.ajax({
      url: $("#donation_form").attr("action"),
      type: "POST",
      data: transferData,
      success: function (result) {
        if (result.valid) {
          let selPaymentMethod = $('[name="paymentmethod"]').val();

          if (clickedButton == "do_next") {
            // if (selPaymentMethod == "paypal") {
            //   let payonePaypalParams = result.payoneParams;
            //   $("#payone_reference").val(payonePaypalParams.reference);
            //   processPaypalSubmit(payonePaypalParams);
            // } else if (selPaymentMethod == "creditcard") {
            //   let payoneCreditcardPreauthParams = result.payoneParams;
            //   $("#payone_reference").val( payoneCreditcardPreauthParams.reference );
            //   processCCSubmit(payoneCreditcardPreauthParams);
            // } else
            if (selPaymentMethod == "debit") {
              return processDoNext("do_donate");
            } else {
              hideOverlay();
            }
          } else if (clickedButton == "do_donate") {
            if (result.hasOwnProperty("redirect") && result.redirect != "") {
              window.location = result.redirect;
            } else {
              hideOverlay();
            }
          } else {
            hideOverlay();
            //window.location.reload();
          }
        } else {
          if (clickedButton === "do_error") {
            $("#overlay").hide();
            $("#overlay_processing").hide();
            $("#overlay_error .btn").attr("disabled", "true");
            $("#overlay_error").show();
            $("#overlay_error").addClass("show");

            let $payMethod = $("#ZAHLUNGSMETHODE");
            let value = $payMethod.val();

            console.log( "ZAHLUNGSMETHODE" , value);

            if (value === "creditcard") {
              $payMethod.val("creditcard");
              $payMethod.trigger("change");
            }

            // let $niceSelect = $("#ZAHLUNGSMETHODE")
            //   .parent()
            //   .find(".nice-select");
            // let value = $niceSelect.find(".selected").attr("data-value");
            // if (value === "creditcard") {
            //   $niceSelect.find('[data-value="debit"]').trigger("click");
            //   setTimeout(function () {
            //     $niceSelect
            //       .find('[data-value="' + value + '"]')
            //       .trigger("click");
            //     $("#overlay_error .btn").removeAttr("disabled");
            //   }, 1500);
            // } else {
            //   setTimeout(function () {
            //     $("#overlay_error .btn").removeAttr("disabled");
            //   }, 1000);
            // }

            setTimeout(function () {
              $("#overlay_error .btn").removeAttr("disabled");
            }, 1000);

            return false;
          } else {
            // remove old error classes
            $(".field_error").each(function (index) {
              $(this).removeClass("field_error");
            });

            $('[data-js="donation-step-prev-1"]').trigger("click");
            $('[data-js="donation-step-prev-2"]').trigger("click");
            $('[data-js="donation-step-prev-3"]').trigger("click");

            let formField = null;
            let errorList = "<ul>";

            $.each(result.validationMessages, function (field, msg) {
              formField = $("#donation_form input[name=" + field + "]");
              if (formField.length > 0) {
                formField.addClass("field_error");

                let errorContainer = formField.attr(
                  "data-parsley-errors-container"
                );
                for (let key in msg) {
                  if (msg.hasOwnProperty(key)) {
                    errorList += "<li>" + msg[key] + ".</li>";
                    $(errorContainer).text(msg[key]);
                  }
                }
              } else {
                // if (
                //   $("#donation_form select[name=" + field + "]").length > 0 &&
                //   $("#donation_form select[name=" + field + "]")
                //     .parent()
                //     .find(".nice-select").length > 0
                // ) {
                //   formField = $("#donation_form select[name=" + field + "]");
                //   //formField.parent().find('.nice-select').addClass('field_error');
                //   formField.addClass("field_error");
                //   let errorContainer = formField.attr(
                //     "data-parsley-errors-container"
                //   );
                //   for (let key in msg) {
                //     if (msg.hasOwnProperty(key)) {
                //       errorList += "<li>" + msg[key] + ".</li>";
                //       $(errorContainer).text(msg[key]);
                //     }
                //   }
                // }
              }
            });

            errorList += "</ul>";

            setTimeout(function () {
              $("#overlay_error p.general").text(
                "Im Formular wurden Fehler gefunden."
              );
              $("#overlay_error p.specific").html(errorList);
              $("#overlay").hide();
              $("#overlay_processing").hide();
              $("#overlay_error .btn").attr("disabled", "true");
              $("#overlay_error").show();
              $("#overlay_error").addClass("show");

              let target =
                document.body.scrollTop +
                $(".field_error")
                  .first()
                  .parents(".donation-form__field")
                  .offset().top -
                150;
              $("html,body").animate(
                {
                  scrollTop: target,
                },
                500
              );
            }, 1500);

            if (formField) {
              // console.log(formField);
              // console.log("scrolling!!");

              // formField.parent().parent()[0].scrollIntoView({behavior: "smooth", block: "start", inline: "start"});

              if (typeof formField.parent().parent().offset() != "undefined") {
                let offset = formField.parent().parent().offset();
                // offset.left -= 200;
                offset.top -= 200;
                $("html, body").animate({
                  scrollTop: offset.top,
                  scrollLeft: offset.left,
                });
              }
              formField.focus();
            }

            // Scroll into tab header
            $("#donation_form")[0].scrollIntoView({
              behavior: "smooth",
              block: "start",
              inline: "start",
            });

            setTimeout(function () {
              $("#overlay_error .btn").removeAttr("disabled");
            }, 3000);

            return true;
          }
        }
      },
      error: function (result) {
        $("#overlay").hide();
        $("#overlay_processing").hide();
        return false;
      },
    });
  }

  function saveOptionsTitle() {
    window.titles = $("#TITLE_1").html();
  }

  function saveOptionsSalutation() {
    window.salutations = $("#SALUTATION").html();
  }

  function updateSalutations(addressType) {
    $('select[name="salutation"]').html(window.salutations);
    switch (addressType) {
      case "110": //ADDRESSTYPE_COMPANY
      case "012": //ADDRESSTYPE_CHURCH
      case "018": //ADDRESSTYPE_SCHOOL
        if ($('select[name="salutation"]').val() > 2) {
          $('select[name="salutation"]').val(0);
        }
        $('select[name="salutation"] option').each(function () {
          if ($(this).val() == 3 || $(this).val() == 4) $(this).remove();
        });
        break;
      default:
        break;
    }
  }

  function updateGuiTitle(index, salutation) {
    let $titleSelect;
    if (index === 1) {
      $titleSelect = $('select[name="title"]');
    } else {
      $titleSelect = $('select[name="title' + index + '"]');
    }

    $titleSelect.find("option").each(function () {
      $(this).remove();
    });
    titleOptions.forEach(function (item) {
      $titleSelect.append(item);
    });

    $titleSelect.html(window.titles);
    switch (salutation) {
      case "1":
        // Men
        $titleSelect.find("option").each(function () {
          if ($(this).val() > 4) $(this).remove();
        });
        $("#zeile_titel").show();
        if ($titleSelect.val() > 4) $titleSelect.val(0);
        break;
      case "2":
        // Women
        $titleSelect.find("option").each(function () {
          if ($(this).val() > 0 && $(this).val() < 5) {
            $(this).remove();
          }
        });
        $("#zeile_titel").show();
        if ($titleSelect.val() < 5) $titleSelect.val(0);
        break;
      default:
        $("#zeile_titel").hide();
        $titleSelect.val(0);
    }
  }

  function updateMandatories(salutation, fn, name) {
    if ($(".donation-form select#NMERKMAL option:selected").val() == "000") {
      $("#mandatory_salutation").show();
      $("#mandatory_firstname").show();
      $("#mandatory_name").show();
    } else {
      if (salutation != 0) {
        $("#mandatory_firstname").show();
        $("#mandatory_name").show();
      } else if (fn != "") {
        $("#mandatory_salutation").show();
        $("#mandatory_name").show();
      } else if (name != "") {
        $("#mandatory_salutation").show();
        $("#mandatory_firstname").show();
      } else {
        //remove stern labels and error marks, if any
        $("#mandatory_salutation").hide();
        $("#mandatory_firstname").hide();
        $("#mandatory_name").hide();

        /*let dlTag = $("#donation_form select[name=salutation]").parent().find(".select2");
            dlTag.removeClass('field_error');

            $('input[name=firstname]').removeClass('field_error');
            $('input[name=name]').removeClass('field_error');*/
      }
    }
  }

  function checkLNameReq() {
    let nameReq = false;
    let name2Req = false;

    let val = $("#NMERKMAL").find("option:selected").val();
    if (val === "000" || val === "011") {
      nameReq = true;
    } else {
      if (
        $('input[name="firstname"]').val() !== "" ||
        $('input[name="name"]').val() !== "" ||
        $('select[name="salutation"] option:selected').val() !== "0"
      ) {
        nameReq = true;
      }
    }

    if (
      $('input[name="firstname2"]').val() !== "" ||
      $('input[name="name2"]').val() !== "" ||
      $('select[name="salutation2"] option:selected').val() !== "0"
    ) {
      name2Req = true;
    }

    if ($(".donation-form__second-person").hasClass("hide")) name2Req = false;

    // console.log("checkLNameReq nameReq", nameReq);
    if (nameReq) {
      doReqField("firstname", false);
      doReqField("name", false);
      doReqField("salutation", false);
    } else {
      notReqField("firstname", false);
      notReqField("name", false);
      notReqField("salutation", false);
    }

    // console.log("checkLNameReq nameReq2", name2Req);
    if (name2Req) {
      doReqField("firstname2", false);
      doReqField("name2", false);
      doReqField("salutation2", true);
    } else {
      notReqField("firstname2", false);
      notReqField("name2", false);
      notReqField("salutation2", true);
    }

    checkReqSigns();

    if (
      typeof $("#donation-step-2") != "undefined" &&
      $("#donation-step-2").length > 0
    ) {
      $("#donation-step-2").parsley().refresh();
    }
  }

  function checkReqSigns() {
    $("#donation-form .donation-form__field").each(function (e) {
      let $this = $(this);
      let needsSign = false;

      if ($this.hasClass("wrapper-company") && !$this.hasClass("hide")) {
        needsSign = true;
        if ($this.find(".is-required").length < 1) {
          $this
            .find(".input-field .input-field__label")
            .append('<span class="is-required"></span>');
        }
      }
      if ($this.find('[data-parsley-required="true"]').length > 0) {
        needsSign = true;
      }
      if ($this.find('[data-parsley-salutation-req="true"]').length > 0) {
        needsSign = true;
      }

      needsSign
        ? $this.find(".is-required").text("*")
        : $this.find(".is-required").text("");
    });
  }

  function translateSiteEN() {
    $.ajax({
      type: "get",
      dataType: "json",
      url: "https://www.brot-fuer-die-welt.de" + "/spenden/jetzt-helfen" + "/file/?component=CustomizationFoemi&ft=json&file=en.json",
      success: function (data) {
        data.translations.forEach(function (entry) {
          if (entry.text) {
            if (entry.attr) {
              $(entry.selector).attr(entry.attr, entry.text);
            } else {
              $(entry.selector).text(entry.text);
            }
          }
          if (entry.html) {
            $(entry.selector).html(entry.html);
          }
        });
      },
      error: function (request, status, error) {
        if (transENTries < 3) {
          setTimeout(function () {
            transENTries += 1;
            translateSiteEN();
          }, 1000);
        } else {
          $(".trans-en").prepend(
            '<div class="info" style="display: none;"><h5 style="margin-bottom:0;">Translation failed</h5></div>'
          );
          $(".trans-en > .info").slideDown();
        }
      },
    });
  }

  function checkLanguage() {
    $.ajax({
      type: "get",
      dataType: "json",
      url: "https://www.brot-fuer-die-welt.de" + "/spenden/jetzt-helfen" + "/file/?component=CustomizationFoemi&ft=json&file=en.json",
      success: function (data) {
        data.translations.forEach(function (entry) {
          if (entry.text) {
            if (entry.attr) {
              $(entry.selector).attr(entry.attr, entry.text);
            } else {
              $(entry.selector).text(entry.text);
            }
          }
          if (entry.html) {
            $(entry.selector).html(entry.html);
          }

          if (getParameterByName("hnl") === "1") {
            $("#donation-form .wrapper-newsletter")
              .hide()
              .next(".donation-form__hr")
              .hide();
          }

          setTimeout(function () {
            $('[data-js="donation-step-1"] .input-field__select').trigger(
              "change"
            );
            titleOptions = [];
            $('select[name="title"] option').each(function () {
              titleOptions.push($(this).get(0).outerHTML);
            });
            Parsley.setLocale("en");
            checkReqSigns();
            $("#donation-form > .info").slideUp();
            $("#donation-form > form").slideDown();
          }, 1000);
        });
      },
      error: function (request, status, error) {
        if (langTries < 3) {
          setTimeout(function () {
            langTries += 1;
            checkLanguage();
          }, 1000);
        } else {
          $("#donation-form").before(
            '<div class="language-error"><p>Language couldn`t be set / Sprache konnte nicht gewechselt werden</p></div>'
          );
        }
      },
    });
  }

  $(function () {
    let css =
      ".custom-donation {" +
      " -webkit-transition: all 300ms ease-in-out;" +
      "  -o-transition: all 300ms ease-in-out;" +
      "  transition: all 300ms ease-in-out;" +
      "  margin-bottom: 100px;" +
      "}" +
      ".barometer .text.is-loading {" +
      "    height: 3em !important;" +
      "    font-size: 1em !important;" +
      "    line-height: 1 !important;" +
      "    padding: 0.5em;" +
      "}" +
      ".info {" +
      "  text-align: center;" +
      "  padding: 40px 20px;" +
      "}" +
      ".loading-spinner {" +
      "  display: inline-block;" +
      "  width: 80px;" +
      "  height: 80px;" +
      "  margin-bottom: 20px;" +
      "  border: 6px solid rgba(235, 104, 10, 0.3);" +
      "  border-radius: 50%;" +
      "  border-top-color: #eb680a;" +
      "  animation: spin 1s ease-in-out infinite;" +
      "  -webkit-animation: spin 1s ease-in-out infinite;" +
      "}" +
      ".loading-spinner.small {" +
      "  width: 2.5em;" +
      "  height: 2.5em;" +
      "  margin: 0;" +
      "}" +
      "@keyframes spin {" +
      "  to {" +
      "    -webkit-transform: rotate(360deg);" +
      "    transform: rotate(360deg);" +
      "  }" +
      "}" +
      "@-webkit-keyframes spin {" +
      "  to {" +
      "    -webkit-transform: rotate(360deg);" +
      "    transform: rotate(360deg);" +
      "  }" +
      "}";
    let style = document.createElement("style");
    document.head.appendChild(style);
    style.appendChild(document.createTextNode(css));

    $("#donation_form").keydown(function (event) {
      if (event.keyCode === 13) {
        event.preventDefault();
        // ???
        // if ($(event.currentTarget.activeElement).hasClass('input').length > 0) {}
      }
    });

    if (
      $(".custom-donation").length < 1 &&
      $("#donation-form") &&
      $("#donation-form").attr("lang") === "en"
    ) {
      currentLang = "en";
      $("#donation-form").prepend(
        '<div class="info"><div class="loading-spinner"></div><h5 style="margin-bottom:0;"></h5></div>'
      );
      checkReqSigns();
      checkLNameReq();
      checkLanguage();
      checkLanguage();
    }

    if ($(".trans-en") && $(".trans-en").length > 0) {
      translateSiteEN();
    }

    // add specific handlers used i.e. on submit
    addEventhandlers();

    // save options
    saveOptionsTitle();
    saveOptionsSalutation();

    // Overlay used when waiting for backend requests
    $("body").append("<div id='overlay' style='display:none;'></div>");

    $(".spendenformular_nojavascript").hide();
    $(".spendenformular_inhalt").show();
    $(".spendenformular_reiter").show();

    $('select[name="title"] option').each(function () {
      titleOptions.push($(this).get(0).outerHTML);
    });

    let val = $(".spendenformular select#NMERKMAL option:selected").val();
    if (val == "110") {
      $("#zeile_firma").show();
      //$('#mandatory_salutation').hide();
      //$('#mandatory_firstname').hide();
      //$('#mandatory_name').hide();
      $("#zeile_kirche").hide();
      $("#zeile_schule").hide();
    } else if (val == "012") {
      $("#zeile_kirche").show();
      //$('#mandatory_salutation').hide();
      //$('#mandatory_firstname').hide();
      //$('#mandatory_name').hide();
      $("#zeile_firma").hide();
      $("#zeile_schule").hide();
    } else if (val == "018") {
      $("#zeile_schule").show();
      //$('#mandatory_salutation').hide();
      //$('#mandatory_firstname').hide();
      //$('#mandatory_name').hide();
      $("#zeile_firma").hide();
      $("#zeile_kirche").hide();
    } else {
      $("#zeile_firma").hide();
      $("#zeile_kirche").hide();
      $("#zeile_schule").hide();
      //$('#mandatory_salutation').show();
      //$('#mandatory_firstname').show();
      //$('#mandatory_name').show();
    }

    $('.donation-form select[name^="salutation"]').each(function (index) {
      const count = index + 1;
      let $salutation, $salutationSelected, $fn, $name;
      $salutation = $(this);
      $salutationSelected = $salutation.find("option:selected");

      if (index === 0) {
        $fn = $('input[name="firstname"]');
        $name = $('input[name="name"]');
      } else {
        $fn = $('input[name="firstname' + count + '"]');
        $name = $('input[name="name' + count + '"]');
      }

      if (
        $salutationSelected &&
        $salutationSelected[0] &&
        $fn &&
        $fn[0] &&
        $name &&
        $name[0]
      ) {
        updateMandatories(
          $salutationSelected[0].value,
          $fn[0].value.trim(),
          $name[0].value.trim()
        );
      }

      // console.log($("#NMERKMAL option:selected").val());
      updateSalutations(
        $(".donation-form select#NMERKMAL option:selected").val()
      );
      updateGuiTitle(count, $salutationSelected.val());

      $salutation.on("change", function () {
        updateGuiTitle(count, $(this).val());
        if ($fn && $fn.val && $name && $name.val) {
          updateMandatories(
            $(this).val(),
            $fn.val().trim(),
            $name.val().trim()
          );
        }
      });
    });

    $("#donation-step-2").on("change", function (e) {
      // console.log("#donation-step-2 change", e);
      checkLNameReq();
    });

    $("#BETRAG").trigger("focus");

    if (typeof $("#IBAN") != "undefined" && $("#IBAN").length > 0) {
      // remove whitespaces from IBAN
      $("#IBAN").on("keyup", function () {
        $(this).val($(this).val().trim());
      });

      $("#IBAN").on("paste", function () {
        setTimeout(function () {
          let string = $("#IBAN").val().replace(/\s/g, "");
          $("#IBAN").val(string);
        }, 100);
      });
    }

    $(".donation-form select#NMERKMAL")
      .off()
      .on("change", function () {
        let val = $(this).val();
        if (val === "011") {
          $(".wrapper-company").addClass("hide");
          notReqField("organisation", false);
        } else if (val === "110") {
          doReqField("organisation", false);
          $(".wrapper-company").removeClass("hide");
        }
        updateSalutations(val);
        checkLNameReq();
      });

    // if(val == "000") {
    // 	//for privatespende, show the mandatory fields
    // 	$('#mandatory_salutation').show();
    // 	$('#mandatory_firstname').show();
    // 	$('#mandatory_name').show();
    // 	$('#zeile_firma').hide();
    // 	$('#zeile_kirche').hide();
    // 	$('#zeile_schule').hide();
    // 	$('input[name=company]').val('');
    // 	$('input[name=church]').val('');
    // 	$('input[name=school]').val('');
    // } else {
    // 	let salutation = $('select[name=salutation]');
    // 	let fn = $('input[name=firstname]');
    // 	let name= $('input[name=name]');
    // 	if(salutation && fn && name) {
    // 		updateMandatories(salutation.val(), fn.val().trim(), name.val().trim());
    // 	}
    // }
    // if (val == "110") {
    // 	$('#zeile_firma').show();
    // 	$('#zeile_kirche').hide();
    // 	$('#zeile_schule').hide();
    // 	$('input[name=church]').val('');
    // 	$('input[name=school]').val('');
    // } else if (val == "012") {
    // 	$('#zeile_kirche').show();
    // 	$('#zeile_firma').hide();
    // 	$('#zeile_schule').hide();
    // 	$('input[name=company]').val('');
    // 	$('input[name=school]').val('');
    // } else if (val == "018") {
    // 	$('#zeile_schule').show();
    // 	$('#zeile_firma').hide();
    // 	$('#zeile_kirche').hide();
    // 	$('input[name=company]').val('');
    // 	$('input[name=church]').val('');
    // }
    // });

    //force correct amount input format
    /*$('input[name=amount]').change(function(e)
      {
        let regex  = /^\d+(?:\.\d{0,2})$/;
        let numberString = e.target.value;

        if (!regex.test(numberString + ".00")) {
          if (numberString.indexOf('.') !== -1) {
            numberString = numberString.replace(/\./gi, '');
          }
          if (numberString.indexOf(',') !== -1) {
            numberString = numberString.replace(/,/gi, '.');
          }
          if (regex.test(numberString + ".00")) {
            //Now valid
            e.target.value = numberString;
          } else {
            //Still not valid. Clear field value completely
            e.target.value = '';
          }
        }
      });*/
    /*
          $('input[name=firstname]').change(function() {
            updateMandatories($('select[name=salutation]').val(), $(this).val().trim(), $('input[name=name]').val().trim());
          });

          $('input[name=name]').change(function() {
            updateMandatories($('select[name=salutation]').val(), $('input[name=firstname]').val().trim(), $(this).val().trim());
          });*/

    $.fn.textWidthSpendenForm = function (text, font) {
      return (
        $.fn.textWidthSpendenForm.fakeElSpendenForm ||
          ($.fn.textWidthSpendenForm.fakeElSpendenForm = $(
            "<span class='width-dynamic-spendenform-dummy'>"
          )
            .hide()
            .appendTo(document.body)),
        $.fn.textWidthSpendenForm.fakeElSpendenForm
          .text(text || this.val() || this.text() || this.attr("placeholder"))
          .css("font", font || this.css("font")),
        $.fn.textWidthSpendenForm.fakeElSpendenForm.width() + 10
      );
    };

    $(".width-dynamic-spendenform")
      .on("input", function () {
        let inputWidth = $(this).textWidthSpendenForm();
        $(this).css({
          width: inputWidth + 30,
        });
      })
      .trigger("input");

    if ($("#kkarte")) {
      //RenderFormElementPayone::renderPayoneCreditCardJavascript
      if ($('[name="payone_pseudocardpan"]').val() == "") {
        jQuery.getScript(
          "https://secure.pay1.de/client-api/js/v1/payone_hosted_min.js",
          function () {
            payoneFieldsConfig = {
              fields: {
                cardtype: {
                  selector: "cardtype", // put name of your div-container here
                  cardtypes: ["V", "M"], // define possible cardtypes in PAYONE iFrame
                  style:
                    "font-size: 1.5em; border: 1px solid #000; width: 240px;",
                  iframe: {
                    width: "250px",
                  },
                },
                cardpan: {
                  selector: "cardpan", // put name of your div-container here
                  type: "text", // text (default), password, tel
                  style:
                    "font-size: 1.5em; border: 1px solid #000; width: 240px;",
                  iframe: {
                    width: "250px",
                  },
                },
                cardcvc2: {
                  selector: "cardcvc2", // put name of your div-container here
                  type: "password", // select(default), text, password, tel
                  style: "font-size: 1.5em; border: 1px solid #000;",
                  size: "4",
                  maxlength: "4",
                },
                cardexpiremonth: {
                  selector: "cardexpiremonth", // put name of your div-container here
                  type: "select", // select(default), text, password, tel
                  size: "2",
                  maxlength: "2",
                  iframe: {
                    width: "80px",
                  },
                },
                cardexpireyear: {
                  selector: "cardexpireyear", // put name of your div-container here
                  type: "select", // select(default), text, password, tel
                  iframe: {
                    width: "170px",
                  },
                },
              },
              defaultStyle: {
                input:
                  "font-size: 1.5em; border: 1px solid #000; width: 250px;",
                select: "font-size: 1.5em; border: 1px solid #000;",
                iframe: {
                  height: "50px",
                  width: "250px",
                },
              },
              error: "errorOutput", // area to display error-messages (optional)
              language: Payone.ClientApi.Language.de, // Language to display error-messages
              // (default: Payone.ClientApi.Language.en)
            };

            createCreditcardIframes(
              payoneCreditcardCheckConfig,
              payoneFieldsConfig
            );
          }
        );
      }
    }

    checkReqSigns();
    checkLNameReq();
  }); // End document.ready()

  // add event handlers
  function addEventhandlers() {
    $("form:not(.printform)").submit(function (event) {
      if (event.target.id !== "searchbox") return false;
    });

    $('input.standard[type="submit"]').click(function (event) {
      event.preventDefault();
      return processDoNext($(this).attr("name"));
    });

    $('input[name="do_newsletter"]').click(function (event) {
      event.preventDefault();
      return processDoJoinNewsletter($(this));
    });

    $(".form_input").keypress(function (e) {
      if (e.which == 13) e.preventDefault();
    });
  }

  // join newsletter
  function processDoJoinNewsletter(button) {
    if (button.data("processed") == 0) {
      button.val("Newsletter wird abonniert.");
      button.data("processed", 1);

      transferData = {
        id: $("#do_newsletter_id").val(),
        hash: $("#do_newsletter_hash").val(),
      };

      $.ajax({
        url: $("#do_newsletter_api").val(),
        type: "POST",
        data: transferData,
        success: function (result) {
          $("#newsletter_join").hide();
          $("#newsletter_joined").show();
          $("#newsletter_joined_message").html(
            "Vielen Dank für Ihr Interesse an unserer Arbeit. Sie erhalten nun eine Bestätigungs-E-Mail mit einem Link von uns. Bitte klicken Sie diesen Link an, um Ihre Newsletter-Registrierung abzuschließen."
          );
          return false;
        },
        error: function (result) {
          $("#newsletter_join").hide();
          $("#newsletter_joined").show();
          $("#newsletter_joined_message").html(
            "Newsletter konnte nicht abonniert werden."
          );
          return false;
        },
      });
    } else {
      $("#newsletter_join").hide();
      $("#newsletter_joined").show();
      $("#newsletter_joined_message").html("Newsletter bereits abonniert.");
    }
  }

  /////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //
  ////////////////////////////////////////////////////////////////////////////////////////////////////////////

  //RenderFormElementPayone::renderAdditionalJavascript

  $('input.payone[type="submit"]').click(function (event) {
    event.preventDefault();

    if ($(event.target).parents("#donation-form").length > 0) {
      // === inserted ===
      if (
        $("#donation-step-1").parsley().isValid() &&
        $("#donation-step-2").parsley().isValid()
      ) {
        if ($("select[name='paymentmethod']").val() == "creditcard") {
          if ($("#payone_pseudocardpan").val() != "") {
            return processDoNext($(this).attr("name"));
          } else {
            check();
          }
        } else {
          return processDoNext($(this).attr("name"));
        }
      }
    } else {
      // === original ===
      if ($("select[name='paymentmethod']").val() == "creditcard") {
        if ($("#payone_pseudocardpan").val() != "") {
          return processDoNext($(this).attr("name"));
        } else {
          check();
        }
      } else {
        return processDoNext($(this).attr("name"));
      }
    }
  });

  //RenderFormElementPayone::renderPayoneCreditCardJavascript
  function createCreditcardIframes(request, config) {
    iframes = new Payone.ClientApi.HostedIFrames(config, request);

    $("#payone_cardtype").onchange = function () {
      iframes.setCardType(this.value);
      // on change: set new type of credit card to process
    };
  }

  function check() {
    if (iframes !== undefined) {
      $("#overlay").show();
      if (iframes.isComplete()) {
        window.checkCallback = function (response) {
          if (response.status === "VALID") {
            $("#errorOutput").hide();

            $("#payone_pseudocardpan").val(response.pseudocardpan);
            $("#payone_truncatedcardpan").val(response.truncatedcardpan);
            $("#payone_cardtype").val(response.cardtype);
            $("#payone_cardexpiredate").val(response.cardexpiredate);
            $("#payone_status").val(response.status);

            return processDoNext("do_next");
          } else {
            $("html, body").animate(
              {
                scrollTop: $("#payone_integration").offset().top,
              },
              0
            );
            $("#overlay").hide();
            return false;
          }
        };
        iframes.creditCardCheck("checkCallback");
      } else {
        $("html, body").animate(
          {
            scrollTop: $("#payone_integration").offset().top,
          },
          0
        );
        $("#overlay").hide();
        let eo = $("#errorOutput");
        eo.hide();
        if (currentLang === "en") {
          eo[0].innerHTML = "Please fill in all necessary fields.";
        } else {
          eo[0].innerHTML = "Bitte füllen Sie alle Felder aus.";
        }
        eo.show();
      }
    } else {
      $("html, body").animate(
        {
          scrollTop: $("#payone_integration").offset().top,
        },
        0
      );
    }
  }

  //RenderFormElementPayone::renderSubmitCreditCardJavascript
  window.changecc = function () {
    $("#payone_reference").val("");
    $("#payone_pseudocardpan").val("");
    $("#payone_truncatedcardpan").val("");
    $("#payone_cardtype").val("");
    $("#payone_cardexpiredate").val("");
    $("#payone_status").val("");

    //$("input[name='do_save']").click();
  };

  //RenderFormSummaryElementPayone::renderPayonePaypalJavascript
  //RenderFormSummaryElementPayone::renderPayonePaypalSubmitJavascript
  window.processPayoneResponse = function (response) {
    if (response.get("status") == "APPROVED") {
      $("#payone_status").val(response.get("status"));
      $("#payone_txid").val(response.get("txid"));
      $("#payone_userid").val(response.get("userid"));
      return processDoNext("do_donate");
    } else if (response.get("status") == "ERROR") {
      $("#payone_status").val(response.get("status"));
      $("#payone_errorcode").val(response.get("errorcode"));
      $("#payone_errormessage").val(response.get("errormessage"));
      $("#payone_customermessage")
        .val(response.get("customermessage"))
        .css("display", "block");

      $("#overlay_error p.general").text(response.get("customermessage"));
      $("#overlay_error p.specific").text(response.get("errormessage"));

      return processDoNext("do_error");
    } else if (response.get("status") == "REDIRECT") {
      $("#payone_status").val(response.get("status"));
      $("#payone_txid").val(response.get("txid"));
      $("#payone_userid").val(response.get("userid"));
      $("#payone_redirect").val(response.get("redirecturl"));

      // console.log($("#payone_redirect").val());

      return processDoNext("do_donate");
    } else {
      $("#overlay").hide();
    }
  };

  $(document).ready(function () {
    $("#custom_donate_show_public-1").on("click", function (e) {
      $(e.target).parents(".donation-form__field").removeClass("no-next-sib");
      $(".container-wrapper-custom_donate_comment").slideDown();
    });
    $("#custom_donate_show_public-2").on("click", function (e) {
      $(e.target).parents(".donation-form__field").addClass("no-next-sib");
      $(".container-wrapper-custom_donate_comment").slideUp(function () {
        $("[name='custom_donate_comment']").val("");
      });
    });

    $("#want_certificate-1").on("click", function (e) {
      $("#address_container").css("display", "block");
      $("#address_container input").attr("data-parsley-required", "true");
    });
    $("#want_certificate-2").on("click", function (e) {
      $("#address_container").css("display", "none");
      $("#address_container input").attr("data-parsley-required", "false");

      //clear all address fields
      $("#address_container input").val("");
      $("#address_container select").val("");
    });
    $("#overlay_error .btn").on("click", function () {
      $("#overlay_error").hide();
      $("#overlay_error").removeClass("show");
      $("#overlay_error p.general").text("").show();
      $("#overlay_error p.specific").text("").show();
    });
  });
})(jQuery);
(function ($) {
  let debug = false;

  const baseUrl = "https://autocomplete2.postdirekt.de/autocomplete2";
  const baseSearchUrl = baseUrl + "/search/de/postalcodes_cities";
  const baseSelectUrl = baseUrl + "/select/de";
  const tokenUrl = "https://www.brot-fuer-die-welt.de/spenden/jetzt-helfen/api/getDataFactoryToken";

  const streetSel = "[id$='street_autocomplete']";
  const streetnumberSel = "[id$='streetnumber_autocomplete']";
  const citySel = "[id$='city_autocomplete']";
  const zipSel = "[id$='zip_autocomplete']";
  const countrySel = "[id$='LAND']";

  let token = "";
  let lastError = "";
  let timerID;

  // REST - token
  const getToken = function () {
    if (debug) console.log("getToken");
    $.ajax({
      type: "GET",
      url: tokenUrl,
      success: function (data) {
        if (data.token) token = "Bearer " + data.token;
      },
    });
  };

  const handleErrors = function (response) {
    if (!response.ok) {
      lastError = response.statusText;
      if (debug) console.log("handleErrors", response);
    } else {
      return response.json();
    }
  };

  $(function () {
    if (debug) console.log("ready");
    $(".donation-form__step-main").each(function (e) {
      let $this = $(this);
      let $street;
      let $streetnumber;
      let $city;
      let $zip;
      let $country;

      let $streetInput;
      let $cityInput;
      let $zipInput;

      let cityInputValue = "";
      let zipInputValue = "";
      let streetInputValue = "";

      function getInnerData(uuid) {
        if (debug) console.log("getInnerData");
        let data = { uuid: uuid };
        if ($cityInput.val() !== "") data.city = cityInputValue;
        if ($zipInput.val() !== "") data.postal_code = zipInputValue;
        if ($streetInput.val() !== "") data.street = streetInputValue;
        return data;
      }

      function updateInputs(result, focus) {
        if (debug) console.log("updateInputs");
        $cityInput.val(result.city);
        cityInputValue = result.city;
        $zipInput.val(result.postalCode);
        zipInputValue = result.postalCode;
        if ($streetInput.val() !== "") {
          $streetInput.val(result.street);
          streetInputValue = result.street;
        } else {
          if (focus === true) $streetInput.focus();
        }
      }

      if ($this.find(".autocomplete-input").length > 0) {
        $street = $this.find(streetSel);
        $streetnumber = $this.find(streetnumberSel);
        $city = $this.find(citySel);
        $zip = $this.find(zipSel);
        $country = $this.find(countrySel);

        $streetInput = $street.find(".autocomplete-input");
        $cityInput = $city.find(".autocomplete-input");
        $zipInput = $zip.find(".autocomplete-input");

        if (debug) console.log("$street", $street);
        if (debug) console.log("$streetnumber", $street);
        if (debug) console.log("$city", $city);
        if (debug) console.log("$zip", $zip);
        if (debug) console.log("$country", $country);
        if (debug) console.log("$streetInput", $streetInput);
        if (debug) console.log("$cityInput", $cityInput);
        if (debug) console.log("$zipInput", $zipInput);

        if (
          $streetInput.length > 0 ||
          $cityInput.length > 0 ||
          $zipInput.length > 0
        ) {
          getToken();
          timerID = setInterval(function () {
            getToken();
          }, 180 * 1000);

          // street autocomplete
          if ($street.length > 0) {
            new Autocomplete("#" + $street.attr("id"), {
              search: function search(input) {
                var minReq = true;
                streetInputValue = input.substring(0, 55);
                if (debug) console.log("street_autocomplete", streetInputValue);

                if ($country.val() !== "de") return [];

                $street.attr("data-loading", "true");
                let url =
                  baseSearchUrl +
                  "_streets?address_type=A&street=" +
                  streetInputValue;
                if ($cityInput.val() !== "") url += "&city=" + $cityInput.val();
                if ($zipInput.val() !== "" && $zipInput.val().length <= 5) url += "&postal_code=" + $zipInput.val();
                if ($cityInput.val() !== "" && $zipInput.val() !== ""  ) minReq = false;
                return new Promise(function (resolve) {
                  if (streetInputValue.length < 3 && minReq) return resolve([]);
                  fetch(url, { headers: { Authorization: token } })
                    .then(handleErrors)
                    .then(function (data) {
                      return data.addresses.length > 0
                        ? resolve(data.addresses)
                        : resolve([]);
                    })
                    .catch(function (error) {
                      return (lastError = error);
                    })
                    .finally(function () {
                      $street.attr("data-loading", "false");
                    });
                });
              },
              getResultValue: function getResultValue(result) {
                return (
                  result.street + ", " + result.postalCode + " " + result.city
                );
              },
              onSubmit: function onSubmit(result) {
                // console.log(result);
                if ($country.val() === "de") {
                  if (result !== undefined && result.uuid !== undefined) {
                    $.ajax({
                      url: baseSelectUrl + "/postalcodes_cities_streets",
                      type: "GET",
                      headers: { Authorization: token },
                      data: getInnerData(result.uuid),
                    }).then(function (data) {
                      // console.log(data);
                    });
                    updateInputs(result, false);
                    $streetnumber.find(".autocomplete-input").trigger("focus");
                  } else {
                    $streetnumber.attr("data-loading", "false");
                  }
                }
              },
            });
          }

          // zip autocomplete
          if ($zip.length > 0) {
            new Autocomplete("#" + $zip.attr("id"), {
              search: function search(input) {
                zipInputValue = input;
                if ($country.val() !== "de") return [];

                let url;
                $zip.attr("data-loading", "true");
                if ($streetInput.val() !== "") {
                  url = baseSearchUrl + "_streets?postal_code=" + input;
                } else {
                  url = baseSearchUrl + "?postal_code=" + input;
                }

                if ($streetInput.val() !== "")
                  url += "&street=" + $streetInput.val();
                if ($cityInput.val() !== "") url += "&city=" + $cityInput.val();
                return new Promise(function (resolve) {
                  if (input.length < 2 || input.length > 5) return resolve([]);
                  fetch(url, { headers: { Authorization: token } })
                    .then(function (response) {
                      return handleErrors(response);
                    })
                    .then(function (data) {
                      return data.addresses.length > 0
                        ? resolve(data.addresses)
                        : resolve([]);
                    })
                    .catch(function (error) {
                      return (lastError = error);
                    })
                    .finally(function () {
                      $zip.attr("data-loading", "false");
                    });
                });
              },
              getResultValue: function getResultValue(result) {
                if ($streetInput.val() !== "") {
                  return (
                    result.street + ", " + result.postalCode + " " + result.city
                  );
                } else {
                  return result.postalCode + " " + result.city;
                }
              },
              onSubmit: function onSubmit(result) {
                if ($country.val() === "de") {
                  if (result !== undefined && result.uuid !== undefined) {
                    let placeDefinition = "/postalcodes_cities";
                    if ($streetInput.val() !== "")
                      placeDefinition = "/postalcodes_cities_streets"; // submit selection back
                    // console.log(result);
                    $.ajax({
                      url: baseSelectUrl + placeDefinition,
                      type: "GET",
                      headers: { Authorization: token },
                      data: getInnerData(result.uuid),
                    }).then(function (data) {
                      // console.log(data);
                    });
                    updateInputs(result, true);
                  }
                }
              },
            });
          }

          // street autocomplete
          if ($city.length > 0) {
            new Autocomplete("#" + $city.attr("id"), {
              search: function search(input) {
                cityInputValue = input;
                if ($country.val() !== "de") return [];
                let url;
                $city.attr("data-loading", "true");
                if ($streetInput.val() !== "") {
                  url = baseSearchUrl + "_streets?city=" + input;
                } else {
                  url = baseSearchUrl + "?city=" + input;
                }
                if ($streetInput.val() !== "") {
                  url += "&street=" + $streetInput.val();
                }
                if ($zipInput.val() !== "" && $zipInput.val().length <= 5) {
                  url += "&postal_code=" + $zipInput.val();
                }
                return new Promise(function (resolve) {
                  if (input.length < 2) return resolve([]);
                  fetch(url, { headers: { Authorization: token } })
                    .then(handleErrors)
                    .then(function (data) {
                      return data.addresses.length > 0
                        ? resolve(data.addresses)
                        : resolve([]);
                    })
                    .catch(function (error) {
                      return (lastError = error);
                    })
                    .finally(function () {
                      $city.attr("data-loading", "false");
                    });
                });
              },
              getResultValue: function getResultValue(result) {
                if ($streetInput.val() !== "") {
                  return (
                    result.street + ", " + result.postalCode + " " + result.city
                  );
                } else {
                  return result.postalCode + " " + result.city;
                }
              },
              onSubmit: function onSubmit(result) {
                if ($country.val() === "de") {
                  if (result !== undefined && result.uuid !== undefined) {
                    let placeDefinition = "/postalcodes_cities";
                    if ($streetInput.val() !== "") {
                      placeDefinition = "/postalcodes_cities_streets"; // submit selection back
                    }
                    // console.log(result);
                    $.ajax({
                      url: baseSelectUrl + placeDefinition,
                      type: "GET",
                      headers: { Authorization: token },
                      data: getInnerData(result.uuid),
                    }).then(function (data) {
                      // console.log(data);
                    });
                    updateInputs(result, true);
                  }
                }
              },
            });
          }

          $(window).bind("beforeunload", function () {
            clearInterval(timerID);
          });
        }
      }
    });
  });
})(jQuery);
window.donation = "";

let backToStep;
let isSecondPersonAdded = false;
let isRecipientAdded = false;

(function ($) {
  // =========================================================================
  // EXTERNAL FUNCTIONS
  // =========================================================================
  editStep = function (num) {
    $("[data-js='donation-step-" + num + "']").removeClass("inactive");
    $("#donation-step-" + num + " .radio_input").removeAttr("disabled");
    if (num === 1) {
      $("#amount_currency").removeClass("hide");
    }
    if (num === 2) {
      $("*[data-hide='on-step-" + num + "']").each(function () {
        $(this).removeClass("hide");
        if ($("[name='want_certificate']")) {
          let wantC =
            $("[name='want_certificate']").length > 0
              ? $("input[name='want_certificate']:checked").val()
              : null;
          if (wantC) {
            $("[data-activate-value=" + wantC + "]").removeClass(
              "input-field__value"
            );
          }
        }
      });
    }
  };

  // =========================================================================
  // INTERNAL FUNCTIONS
  // =========================================================================
  function scrollToId(id, center = false) {
    const header = document.querySelector("header");
    const headerHeight = header ? header.offsetHeight : 0;
    const target = document.getElementById(id);
    if (target) {
      let targetPosition;
      if (center) {
        const viewportHeight = window.innerHeight;
        const elementHeight = target.offsetHeight;
        targetPosition =
          target.getBoundingClientRect().top +
          window.pageYOffset -
          (viewportHeight - elementHeight) / 2;
      } else {
        targetPosition =
          target.getBoundingClientRect().top +
          window.pageYOffset -
          headerHeight;
      }
      window.scrollTo({
        top: targetPosition,
        behavior: "smooth",
      });
    }
  }

  function checkStep(e, num) {
    let firstError = true;
    let scroll = true;
    let $step = $("#donation-step-" + num);
    $step.parsley().validate();
    if ($step.parsley().isValid()) {
      return true;
    } else {
      $step.parsley().on("field:error", function (fieldInstance) {
        if (scroll === true) {
          firstError = fieldInstance.$element.parent();
          firstError.scrollToMe();
        }
        scroll = false;
      });
      e.preventDefault();
      return false;
    }
  }

  function keepAlive() {
    let time = 5 * 60 * 1000;
    setTimeout(function () {
      $.ajax("https://www.brot-fuer-die-welt.de/spenden/jetzt-helfen/api/refresh")
        .done(function (resopnse) {
          $("[name='donate_csrf']").val(resopnse);
          keepAlive();
        })
        .fail(function () {
          if (
            confirm(
              "Ihre aktuelle Sitzung ist abgelaufen. Die Seite wird nun neu geladen."
            )
          ) {
            location.reload();
          } else {
            $(".donation-form__btn-next").remove();
          }
        });
    }, time);
  }

  // copy select.value to gray-mode span.value
  function initSelectValue(block) {
    $(block + " select.input-field__select").each(function () {
      let text = $(this).find("option:selected").text();
      $(this).parents(".input-field").find(".input-field__value").text(text);
    });
  }

  // copy input.value to gray-mode span.value
  function initInputValue(block) {
    $(block + " input.input-field__text").each(function () {
      let fieldValue = $(this).get(0).value;
      if ($(this).get(0).type === "date") {
        fieldValue = new Date(fieldValue).toLocaleDateString("de-DE", {
          day: "2-digit",
          month: "2-digit",
          year: "numeric",
        });
      }
      $(this)
        .parents(".input-field")
        .find(".input-field__value")
        .text(fieldValue);
    });
  }

  function checkErrorFieldRemove(e) {
    let elem = $("select[name=" + e.target.name + "]");
    if (elem.hasClass("field_error")) {
      elem.removeClass("field_error");
      $(e.target.attributes["data-parsley-errors-container"].nodeValue).text(
        ""
      );
    } else if (elem.hasClass("parsley-error")) {
      elem.removeClass("parsley-error");
      $(e.target.attributes["data-parsley-errors-container"].nodeValue).text(
        ""
      );
    }
  }

  // =========================================================================
  // INIT
  // =========================================================================
  $(function () {
    keepAlive();

    // Funktion zum komfortablen Scrollen zu einem gegebenen Objekt
    $.fn.extend({
      scrollToMe: function () {
        let x = jQuery(this).offset().top - 300;
        jQuery("html,body").animate({ scrollTop: x }, 500);
      },
    });

    const showSimplifiedDonation = function (show) {
      if (show) {
        $("#want_certificate_container").show();
      } else {
        $("#want_certificate_container").hide();
        $("#want_certificate-1").trigger("click");
      }
    };

    // cover image init
    $('*[data-js="cover-img"]').each(function () {
      $(this).addClass("cover-init");
      let imgSrc = $(this).find("img").attr("src");
      $(this).css("background-image", "url(" + imgSrc + ")");
    });

    // tooltip init
    $(".tooltip").tooltipster({
      theme: ["tooltipster-noir", "tooltipster-noir-customized"],
      trigger: "click",
    });

    // only allow integer value
    $('input[type="number"]').on("keyup", function (e) {
      let value = e.target.value;
      if (isNaN(value)) {
        value = window.donation;
      } else if (!isNaN(value)) {
        value = parseInt(value) || "";
        window.donation = value;
      }
      e.target.value = value;
    });

    // =========================================================================
    // STEP 1
    // =========================================================================
    if ($('[data-js="input-money"]').length > 0) {
      window.donation = $('[data-js="input-money"]').val();
    }

    $('[data-focus="1"]').trigger("focus");
    $('[data-js="input-money"]').on("focusout", function (e) {
      e.target.value = window.donation;
    });
    $('[data-js="input-money"]').on("focus", function (e) {
      e.target.value = window.donation;
    });

    // step 1 bearbeiten button click
    $('[data-js="donation-step-prev-1"]').on("click", function (e) {
      e.preventDefault();
      $('[data-js="donation-step-1"]').removeClass("inactive");
      $("#donation-step-1 .radio_input").removeAttr("disabled");
      $("#amount_currency").removeClass("hide");
    });

    // set custom Parsley validator (min 5 €)
    window.Parsley.addValidator("donationValue", {
      validateString: function (value, requirement) {
        let result =
          +value.slice(0, -2) >= +requirement || +value >= +requirement;
        return result;
      },
      messages: {
        en: "Minimum %s € required.",
        de: "Bitte beachten Sie, dass der Mindestbetrag einer Spende %s,00 € beträgt.",
      },
    });

    $('[data-js="donation-step-1 .input-field__select"]').on(
      "change",
      function (e) {
        checkErrorFieldRemove(e);
      }
    );

    function toStep2() {
      $('[data-js="donation-step-1"]').addClass("inactive");
      $('[data-js="donation-value"]').text(donation + ",00 €");
      $("#amount_currency").addClass("hide");

      initInputValue('[data-js="donation-step-1"]');
      initSelectValue('[data-js="donation-step-1"]');

      if (!$('[data-js="donation-step-2"]').hasClass("complete")) {
        $('[data-js="donation-step-2"]')
          .removeClass("inactive")
          .removeClass("disabled");
      }
      $("#donation-step-1 .radio_input").attr("disabled", "disabled");
    }

    // step 1 weiter button click
    $('[data-js="donation-step-next-1"]').on("click", function (e) {
      e.preventDefault();
      window.donation = $('[data-js="input-money"]').val();
      firstError = null;

      if (!checkStep(e, 1)) return;

      let sum = parseInt(donation, 10);
      if (sum >= 5000) {
        let $warning = $("#overlay_warning");
        $("#overlay_warning p.general").text(
          "Ist dieser Spendenbetrag korrekt?"
        );
        $("#overlay_warning p.specific").text(
          "" + sum.toLocaleString("de-DE") + ",00 €"
        );
        $warning.show();
        $warning.addClass("in");
        $("#overlay_warning .btn.btn-default").on("click", function () {
          $warning.removeClass("in");
          $warning.hide();
          $('[data-js="input-money"]').focus();
        });
        $("#overlay_warning .btn.btn-primary").on("click", function () {
          $warning.removeClass("in");
          $warning.hide();
          toStep2(donation);
        });
      } else {
        toStep2(donation);
      }

      setTimeout(function () {
        scrollToId("donation-step-2");
      }, 600);
    });

    // =========================================================================
    // STEP 2
    // =========================================================================
    // toggle second person
    $('[data-js="donation-form__add-person"]').on("click", function (e) {
      if (isSecondPersonAdded) {
        $(".wrapper-add-person .less").hide();
        $(".wrapper-add-person .more").show();
        $(".donation-form__second-person").addClass("hide");
        $("[name='salutation2']").attr("disabled", "true");
        $("[name='title2']").attr("disabled", "true");
        $("[name='firstname2']").attr("disabled", "true");
        $("[name='name2']").attr("disabled", "true");

        isSecondPersonAdded = false;
      } else {
        $(".wrapper-add-person .less").show();
        $(".wrapper-add-person .more").hide();
        $(".donation-form__second-person").removeClass("hide");
        $("[name='salutation2']").removeAttr("disabled");
        $("[name='title2']").removeAttr("disabled");
        $("[name='firstname2']").removeAttr("disabled");
        $("[name='name2']").removeAttr("disabled");

        isSecondPersonAdded = true;
      }
      $("#donation-step-2").trigger("change");
    });

    // show/hide organisation with the appropriate label
    $('[data-js="donation-step-2"] .input-field__select').on(
      "change",
      function (e) {
        let fieldValue = $(e.target).get(0).value;
        let name = $(e.target).get(0).name;
        let text = $(e.target).find("option:selected").text();

        if (name == "addresstype") {
          let hiddenElement = $('input[name="organisation"]').parent().parent();
          if (fieldValue != "" && fieldValue != "000") {
            // hiddenElement.removeClass("hide");
            hiddenElement.find(".input-field__text").removeAttr("disabled");
            hiddenElement.find(".input-field__label").text(text + ":");
          } else {
            // hiddenElement.addClass("hide");
            hiddenElement
              .find(".input-field__text")
              .val("")
              .attr("disabled", "disabled");
            hiddenElement.find(".input-field__label").text("");
          }
        }

        checkErrorFieldRemove(e);
      }
    );

    $('[name="phone"]').on("keyup", function (e) {
      let value = e.target.value;
      if (value.length > 0) {
        let apc = $("[name='allow_phone_contact']");
        apc.val("1");
        apc.prop("checked", true);
      }
      else {
        let apc = $("[name='allow_phone_contact']");
        apc.val("0");
        apc.prop("checked", false);
      }
    });

    // step 2 weiter button click
    $('[data-js="donation-step-next-2"]').on("click", function (e) {
      e.preventDefault();
      let $step2 = $("#donation-step-2");

      if (!checkStep(e, 2)) return;
      $step2.find(".donation-form__btn-prev").removeClass("hide");

      initSelectValue('[data-js="donation-step-2"]');
      initInputValue('[data-js="donation-step-2"]');

      $('[data-js="donation-step-2"]').addClass("complete inactive");
      $('[data-hide="on-step-2"]').addClass("hide");

      if ($('[name="want_certificate"]')) {
        let wantC =
          $('[name="want_certificate"]').length > 0
            ? $('input[name="want_certificate"]:checked').val()
            : null;
        if (wantC) {
          $("[data-activate-value=" + wantC + "]")
            .addClass("input-field__value")
            .removeClass("hide");
          $('input[name="want_certificate"]:not(:checked)')
            .parents(".radio__label")
            .hide();
        }
      }
      $('[data-js="donation-step-3"]').removeClass("inactive disabled");

      setTimeout(function () {
        scrollToId("donation-step-3", true);
      }, 600);
    });

    // step 2 bearbeiten button click
    $('[data-js="donation-step-prev-2"]').on("click", function (e) {
      e.preventDefault();
      $('[data-js="donation-step-2"]').removeClass("inactive");
      $('*[data-hide="on-step-2"]').each(function () {
        $(this).removeClass("hide");
        if ($('[name="want_certificate"]')) {
          let wantC =
              $('[name="want_certificate"]').length > 0
                  ? $('input[name="want_certificate"]:checked').val()
                  : null;
          if (wantC) {
            $("[data-activate-value=" + wantC + "]").removeClass(
                "input-field__value"
            );
          }
        }
      });
    });

    // =========================================================================
    // STEP 3
    // =========================================================================

    // set custom Parsley validator (payment method)
    window.Parsley.addValidator("errorIf", {
      validateString: function (value, requirement) {
        return +value > +requirement;
      },
      messages: {
        en: "Choose an existing payment method",
      },
    });

    window.Parsley.addValidator("salutationReq", {
      validateString: function (value) {
        return value !== "0";
      },
      messages: {
        en: "This value is required.",
        de: "Dies ist ein Pflichtfeld.",
      },
    });

    // form submit
    $("#donation_form .btn.submit").on("click", function (e) {
      if (!checkStep(e, 3)) return;

      // !!! only for development !!!
      // console.log("form");
      // console.log("step-1 -> ", $("#donation-step-1").parsley().isValid());
      // console.log("step-2 -> ", $("#donation-step-2").parsley().isValid());
      // console.log("step-3 -> ", $("#donation-step-3").parsley().isValid());
      // !!! only for development !!!

      if (
        $("#donation-step-1").parsley().isValid() &&
        $("#donation-step-2").parsley().isValid() &&
        $("#donation-step-3").parsley().isValid()
      ) {
        // !!! only for development !!!
        // let s = $('[data-js="donation-form"]').serializeArray();
        // console.log(s);
        // !!! only for development !!!
        $("#donation_form").trigger("submit");
      }
    });

    // validation scrolling
    let firstError = true;
    $("[data-js^='donation-step-']").each(function () {
      let $this = $(this);
      $this.parsley().on("form:validate", function () {
        firstError = false;
      });
    });
    $("[data-js^='donation-step-']").each(function () {
      let $this = $(this);
      $this.parsley().on("field:error", function (fieldInstance) {
        if (!firstError) firstError = fieldInstance.$element.parent();
      });
    });
    $("[data-js^='donation-step-']").each(function () {
      let $this = $(this);
      $this.parsley().on("form:error", function () {
        firstError.scrollToMe();
      });
    });

    function setInterval(val, e) {
      // 0: einmalig
      // 1: monatlich
      // 4: vierteljährlich
      // 12: jährlich
      switch (val) {
        case "0":
          // console.log('einmalig');
          // show donation without address
          showSimplifiedDonation(true);

          $('input[name="want_certificate"]').parents(".radio__label").show();

          // if (e) {
          //   setTimeout(function () {
          //     $(e.target).parent().find(".nice-select").removeClass("open");
          //   }, 50);
          // }

          break;
        case "1":
        case "4":
        case "12":
          // console.log('monatlich/vierteljährlich/jährlich');
          // hide donation without address
          showSimplifiedDonation(false);

          // if (e) {
          //   setTimeout(function () {
          //     $(e.target).parent().find(".nice-select").removeClass("open");
          //   }, 50);
          // }

          break;
        default:
          // console.log('monatlich/vierteljährlich/jährlich');
          // hide donation without address
          showSimplifiedDonation(false);

          // if (e) {
          //   setTimeout(function () {
          //     $(e.target).parent().find(".nice-select").removeClass("open");
          //   }, 50);
          // }

          break;
      }

      for (let i = 2; i < 4; i++) {
        if (e) {
          let $step = $(e.target)
            .parents("form")
            .find("#donation-step-" + i + "");
          // $step.trigger("reset");
          // $step.find('input').val('');
          // $step.find('select').val('0')
          $step.parsley().reset();
        }

        $(".want-certificate-label ").removeClass("input-field__value");
        $('[data-hide="on-step-' + i + '"]').removeClass("hide");
        $('[data-js="donation-step-' + i + '"]')
          .removeClass("complete")
          .addClass("inactive")
          .addClass("disabled");
      }
    }

    function initTabSession() {
      // load tab session id
      $.ajax({
        type: "GET",
        async: false,
        url: "https://www.brot-fuer-die-welt.de/spenden/jetzt-helfen/api/validateCurrentTabSession/new",
      })
        .done(function (response) {
          let hiddenInput = $("<input>").attr({
            type: "hidden",
            id: "tab_session",
            name: "tab_session",
            value: response,
          });
          // Append it to the form
          $("#donation_form").append(hiddenInput);
        })
        .fail(function () {
          alert(
            "Beim laden der Seite ist ein Fehler aufgetreten. Die Seite wird nun neu geladen."
          );
          window.location.reload();
        });
    }

    function validateTabSession() {
      // load tab session id
      $.ajax({
        type: "GET",
        async: false,
        url:
          "https://www.brot-fuer-die-welt.de/spenden/jetzt-helfen/api/validateCurrentTabSession/" +
          $("#tab_session").val(),
      })
        .done(function (response) {
          let hiddenInput = $("<input>").attr({
            type: "hidden",
            id: "tab_session",
            name: "tab_session",
            value: response,
          });
          // check if session is the one of the current tab
          if ($("#tab_session").val() != response) {
            var $tabChangedModal = $("#overlay_tab_changed");
            $tabChangedModal.show();
            $tabChangedModal.addClass("in");
            $("#overlay_tab_changed .btn.btn-default").on("click", function () {
              $tabChangedModal.removeClass("in");
              $tabChangedModal.hide();
            });
            $("#overlay_tab_changed .btn.btn-primary").on("click", function () {
              $tabChangedModal.removeClass("in");
              $tabChangedModal.hide();
              window.location.reload();
            });
          }
        })
        .fail(function () {
          alert(
            "Beim laden der Seite ist ein Fehler aufgetreten. Die Seite wird nun neu geladen."
          );
          window.location.reload();
        });
    }

    function doDataLayerPushes() {
      // check if form with class hiddenfields available
      if (typeof dataLayer !== undefined && $("form.hiddenfields").length > 0) {
        var dataArray = $("form.hiddenfields").serializeArray();
        var dataObj = {};
        $(dataArray).each(function (i, field) {
          dataObj[field.name] = field.value;
        });

        // check if field value wf is in one which needs to be pushed
        switch (parseInt(dataObj["wf"])) {
          case 99:
            dataLayer.push({
              event: "add_payment_info",
              ecommerce: {
                currency: "EUR",
                payment_type: dataObj["paymentmethod"],
                value: dataObj["total_transaction_amount"],
                tax: 0,
                items: [
                  {
                    item_id: dataObj["subject"],
                    item_name: dataObj["item_name"],
                    item_variant: dataObj["item_variant"],
                    price: dataObj["amount"],
                    item_category: dataObj["item_category"],
                    item_category2: dataObj["item_category2"],
                    item_category3: dataObj["projectUid"],
                    item_category4: dataObj["customDonateAction"],
                    quantity: dataObj["quantity"],
                  },
                ],
              },
            });

            dataLayer.push({
              event: "purchase",
              ecommerce: {
                currency: "EUR",
                transaction_id: dataObj["crmDonationformTransactionId"],
                value: dataObj["total_transaction_amount"],
                tax: 0,
                items: [
                  {
                    item_id: dataObj["subject"],
                    item_name: dataObj["item_name"],
                    item_variant: dataObj["item_variant"],
                    price: dataObj["amount"],
                    item_category: dataObj["item_category"],
                    item_category2: dataObj["item_category2"],
                    item_category3: dataObj["projectUid"],
                    item_category4: dataObj["customDonateAction"],
                    quantity: dataObj["quantity"],
                  },
                ],
              },
            });

            dataLayer.push({
              pt: {
                pagetype : 'spendenformular_spende_erfolgt',
                conversion_orderid : dataObj["crmDonationformTransactionId"],
                conversion_total : dataObj["total_transaction_amount"],
                productname : 'spende',
                productid: dataObj["subject"],
                productvariant: dataObj["item_variant"],
                productamount: dataObj["amount"],
              },
            });

            if (dataObj["newsletter"] == "1") {
              dataLayer.push({
                event: "gtmEvent",
                event_name: "newsletter_anmeldung_spendenformular",
                popup_id: "",
              });
            }
            break;
          default:
        }
      }
    }

    $(document).on("ready", function () {
      setInterval($("#INTERVALL").val());

      // hide / show depending on intervall
      $("#INTERVALL").on("change", function (e) {
        setInterval($(this).val(), e);
      });
    });

    initTabSession();
    doDataLayerPushes();

    document.addEventListener("visibilitychange", function () {
      if (document.visibilityState === "visible") {
        validateTabSession();
      }
    });

    if ($("#yearlyAmount").length > 0) {
      function checkYearlyAmount() {
        let currAmount = $(".input-field__inputmoney").val();
        let minVal = $(".input-field__inputmoney").attr(
          "data-parsley-donation-value"
        );
        minVal ? minVal = parseInt(minVal) : (minVal = 1);
        if (currAmount !== "") {
          currAmount = parseInt(currAmount);
          if (currAmount < minVal) {
            $("#yearlyAmount").slideUp();
          } else {
            let yearlyAmount = currAmount * 12;
            $("#yearlyAmount strong").text(yearlyAmount + ",00 €");
            $("#yearlyAmount").slideDown();
          }
        } else {
          $("#yearlyAmount").slideUp();
        }
      }

      checkYearlyAmount();

      $("[name='amount']").on("change", function () {
        checkYearlyAmount();
      });
      $("[name='amount']").on("keyup", function () {
        checkYearlyAmount();
      });
    }
  });
})(jQuery);
var Autocomplete=function(){"use strict";function t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function e(t,e){for(var n=0;n<e.length;n++){var i=e[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function n(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var i=function(t,e){return t.matches?t.matches(e):t.msMatchesSelector?t.msMatchesSelector(e):t.webkitMatchesSelector?t.webkitMatchesSelector(e):null},s=function(t,e){return t.closest?t.closest(e):function(t,e){for(var n=t;n&&1===n.nodeType;){if(i(n,e))return n;n=n.parentNode}return null}(t,e)},o=function(t){return Boolean(t&&"function"==typeof t.then)},u=function e(){var i=this,u=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},a=u.search,l=u.autoSelect,r=void 0!==l&&l,d=u.setValue,c=void 0===d?function(){}:d,h=u.setAttribute,p=void 0===h?function(){}:h,f=u.onUpdate,b=void 0===f?function(){}:f,v=u.onSubmit,g=void 0===v?function(){}:v,L=u.onShow,y=void 0===L?function(){}:L,w=u.onHide,m=void 0===w?function(){}:w,S=u.onLoading,x=void 0===S?function(){}:S,R=u.onLoaded,A=void 0===R?function(){}:R;t(this,e),n(this,"value",""),n(this,"searchCounter",0),n(this,"results",[]),n(this,"selectedIndex",-1),n(this,"handleInput",(function(t){var e=t.target.value;i.updateResults(e),i.value=e})),n(this,"handleKeyDown",(function(t){var e=t.key;switch(e){case"Up":case"Down":case"ArrowUp":case"ArrowDown":var n="ArrowUp"===e||"Up"===e?i.selectedIndex-1:i.selectedIndex+1;t.preventDefault(),i.handleArrows(n);break;case"Tab":i.selectResult();break;case"Enter":var s=i.results[i.selectedIndex];i.selectResult(),i.onSubmit(s);break;case"Esc":case"Escape":i.hideResults(),i.setValue();break;default:return}})),n(this,"handleFocus",(function(t){var e=t.target.value;i.updateResults(e),i.value=e})),n(this,"handleBlur",(function(){i.hideResults()})),n(this,"handleResultMouseDown",(function(t){t.preventDefault()})),n(this,"handleResultClick",(function(t){var e=t.target,n=s(e,"[data-result-index]");if(n){i.selectedIndex=parseInt(n.dataset.resultIndex,10);var o=i.results[i.selectedIndex];i.selectResult(),i.onSubmit(o)}})),n(this,"handleArrows",(function(t){var e=i.results.length;i.selectedIndex=(t%e+e)%e,i.onUpdate(i.results,i.selectedIndex)})),n(this,"selectResult",(function(){var t=i.results[i.selectedIndex];t&&i.setValue(t),i.hideResults()})),n(this,"updateResults",(function(t){var e=++i.searchCounter;i.onLoading(),i.search(t).then((function(t){e===i.searchCounter&&(i.results=t,i.onLoaded(),0!==i.results.length?(i.selectedIndex=i.autoSelect?0:-1,i.onUpdate(i.results,i.selectedIndex),i.showResults()):i.hideResults())}))})),n(this,"showResults",(function(){i.setAttribute("aria-expanded",!0),i.onShow()})),n(this,"hideResults",(function(){i.selectedIndex=-1,i.results=[],i.setAttribute("aria-expanded",!1),i.setAttribute("aria-activedescendant",""),i.onUpdate(i.results,i.selectedIndex),i.onHide()})),n(this,"checkSelectedResultVisible",(function(t){var e=t.querySelector('[data-result-index="'.concat(i.selectedIndex,'"]'));if(e){var n=t.getBoundingClientRect(),s=e.getBoundingClientRect();s.top<n.top?t.scrollTop-=n.top-s.top:s.bottom>n.bottom&&(t.scrollTop+=s.bottom-n.bottom)}})),this.search=o(a)?a:function(t){return Promise.resolve(a(t))},this.autoSelect=r,this.setValue=c,this.setAttribute=p,this.onUpdate=b,this.onSubmit=g,this.onShow=y,this.onHide=m,this.onLoading=x,this.onLoaded=A},a=0,l=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return"".concat(t).concat(++a)},r=function(t,e){var n=t.getBoundingClientRect(),i=e.getBoundingClientRect();return n.bottom+i.height>window.innerHeight&&window.innerHeight-n.bottom<n.top&&window.pageYOffset+n.top-i.height>0?"above":"below"},d=function(t,e,n){var i;return function(){var s=this,o=arguments,u=function(){i=null,n||t.apply(s,o)},a=n&&!i;clearTimeout(i),i=setTimeout(u,e),a&&t.apply(s,o)}},c=function(){function n(e,i,s){t(this,n),this.id="".concat(s,"-result-").concat(e),this.class="".concat(s,"-result"),this["data-result-index"]=e,this.role="option",e===i&&(this["aria-selected"]="true")}var i,s,o;return i=n,(s=[{key:"toString",value:function(){var t=this;return Object.keys(this).reduce((function(e,n){return"".concat(e," ").concat(n,'="').concat(t[n],'"')}),"")}}])&&e(i.prototype,s),o&&e(i,o),n}();return function e(i){var s=this,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=o.search,h=o.onSubmit,p=void 0===h?function(){}:h,f=o.onUpdate,b=void 0===f?function(){}:f,v=o.baseClass,g=void 0===v?"autocomplete":v,L=o.autoSelect,y=o.getResultValue,w=void 0===y?function(t){return t}:y,m=o.renderResult,S=o.debounceTime,x=void 0===S?0:S;t(this,e),n(this,"expanded",!1),n(this,"loading",!1),n(this,"position",{}),n(this,"resetPosition",!0),n(this,"initialize",(function(){s.root.style.position="relative",s.input.setAttribute("role","combobox"),s.input.setAttribute("autocomplete","off"),s.input.setAttribute("autocapitalize","off"),s.input.setAttribute("autocorrect","off"),s.input.setAttribute("spellcheck","false"),s.input.setAttribute("aria-autocomplete","list"),s.input.setAttribute("aria-haspopup","listbox"),s.input.setAttribute("aria-expanded","false"),s.resultList.setAttribute("role","listbox"),s.resultList.style.position="absolute",s.resultList.style.zIndex="1",s.resultList.style.width="100%",s.resultList.style.boxSizing="border-box",s.resultList.id||(s.resultList.id=l("".concat(s.baseClass,"-result-list-"))),s.input.setAttribute("aria-owns",s.resultList.id),document.body.addEventListener("click",s.handleDocumentClick),s.input.addEventListener("input",s.core.handleInput),s.input.addEventListener("keydown",s.core.handleKeyDown),s.input.addEventListener("focus",s.core.handleFocus),s.input.addEventListener("blur",s.core.handleBlur),s.resultList.addEventListener("mousedown",s.core.handleResultMouseDown),s.resultList.addEventListener("click",s.core.handleResultClick),s.updateStyle()})),n(this,"setAttribute",(function(t,e){s.input.setAttribute(t,e)})),n(this,"setValue",(function(t){s.input.value=t?s.getResultValue(t):""})),n(this,"renderResult",(function(t,e){return"<li ".concat(e,">").concat(s.getResultValue(t),"</li>")})),n(this,"handleUpdate",(function(t,e){s.resultList.innerHTML="",t.forEach((function(t,n){var i=new c(n,e,s.baseClass),o=s.renderResult(t,i);"string"==typeof o?s.resultList.insertAdjacentHTML("beforeend",o):s.resultList.insertAdjacentElement("beforeend",o)})),s.input.setAttribute("aria-activedescendant",e>-1?"".concat(s.baseClass,"-result-").concat(e):""),s.resetPosition&&(s.resetPosition=!1,s.position=r(s.input,s.resultList),s.updateStyle()),s.core.checkSelectedResultVisible(s.resultList),s.onUpdate(t,e)})),n(this,"handleShow",(function(){s.expanded=!0,s.updateStyle()})),n(this,"handleHide",(function(){s.expanded=!1,s.resetPosition=!0,s.updateStyle()})),n(this,"handleLoading",(function(){s.loading=!0,s.updateStyle()})),n(this,"handleLoaded",(function(){s.loading=!1,s.updateStyle()})),n(this,"handleDocumentClick",(function(t){s.root.contains(t.target)||s.core.hideResults()})),n(this,"updateStyle",(function(){s.root.dataset.expanded=s.expanded,s.root.dataset.loading=s.loading,s.root.dataset.position=s.position,s.resultList.style.visibility=s.expanded?"visible":"hidden",s.resultList.style.pointerEvents=s.expanded?"auto":"none","below"===s.position?(s.resultList.style.bottom=null,s.resultList.style.top="100%"):(s.resultList.style.top=null,s.resultList.style.bottom="100%")})),this.root="string"==typeof i?document.querySelector(i):i,this.input=this.root.querySelector("input"),this.resultList=this.root.querySelector("ul"),this.baseClass=g,this.getResultValue=w,this.onUpdate=b,"function"==typeof m&&(this.renderResult=m);var R=new u({search:a,autoSelect:L,setValue:this.setValue,setAttribute:this.setAttribute,onUpdate:this.handleUpdate,onSubmit:p,onShow:this.handleShow,onHide:this.handleHide,onLoading:this.handleLoading,onLoaded:this.handleLoaded});x>0&&(R.handleInput=d(R.handleInput,x)),this.core=R,this.initialize()}}();