var iframes;
var payoneFieldsConfig;
var 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");
    }
  });

  $("#paypal-express-redirect").on("click", function () {
    $("#donation-step-1").parsley().validate();
    if ($("#donation-step-1").parsley().isValid()) {
      return processDoNext("do_paypalexpress");
    }
  });

  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 processCCSubmit(payoneCreditcardPreauthParams) {
    $("#next").html($(this).attr("name"));
    if (
      typeof $("#overlay_processing") !== "undefined" &&
      $("#overlay_processing").length > 0
    ) {
      if (typeof $("#overlay_processing").modal !== "undefined") {
        $("#overlay_processing").modal("show");
      } else {
        $("#overlay_processing").show();
      }
    }

    if (payoneCreditcardPreauthParams) {
      var data = payoneCreditcardPreauthParams;
      var options = {
        return_type: "object",
        callback_function_name: "processPayoneResponse",
      };

      jQuery.getScript(
        "https://secure.pay1.de/client-api/js/ajax.js",
        function () {
          var request = new PayoneRequest(data, options);
          request.checkAndStore();
        }
      );
    }
  }

  function processPaypalSubmit(payonePaypalCheckConfig) {
    $("#next").html($(this).attr("name"));
    if (
      typeof $("#overlay_processing") != "undefined" &&
      $("#overlay_processing").length > 0
    ) {
      if (typeof $("#overlay_processing").modal != "undefined") {
        $("#overlay_processing").modal("show");
      } else {
        $("#overlay_processing").show();
      }
    }

    if (payonePaypalCheckConfig) {
      var data = payonePaypalCheckConfig;
      var options = {
        return_type: "object",
        callback_function_name: "processPayoneResponse",
      };

      $.getScript("https://secure.pay1.de/client-api/js/ajax.js", function () {
        var request = new PayoneRequest(data, options);
        request.checkAndStore();
      });
    }
  }

  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");

    var 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);
      }
    }

    var 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";

    // console.log(transferData);
    $.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" ||
            clickedButton == "do_paypalexpress"
          ) {
            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();

            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"]').click();
            $('[data-js="donation-step-prev-2"]').click();
            $('[data-js="donation-step-prev-3"]').click();

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

            $.each(result.validationMessages, function (field, msg) {
              formField = $("#donation_form input[name=" + field + "]");
              if (formField.length) {
                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 &&
                //   $("#donation_form select[name=" + field + "]")
                //     .parent()
                //     .find(".nice-select").length
                // ) {
                //   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();

              let target = document.body.scrollTop;
              let firstError = $(".field_error")
                .first()
                .parents(".donation-form__field");
              if (firstError.length > 0) {
                target = target + firstError.offset().top;
              }
              target = target - 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();

        /*var 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;

    if ($("#NMERKMAL").find("option:selected").val() === "000") {
      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 (nameReq) {
      $('input[name="firstname"]').attr("data-parsley-required", "true");
      $('input[name="name"]').attr("data-parsley-required", "true");
      $('select[name="salutation"]').attr(
        "data-parsley-salutation-req",
        "true"
      );
    } else {
      $('input[name="firstname"]')
        .attr("data-parsley-required", "false")
        .parsley()
        .validate();
      $('input[name="name"]')
        .attr("data-parsley-required", "false")
        .parsley()
        .validate();
      $('select[name="salutation"]')
        .removeAttr("data-parsley-salutation-req")
        .parsley()
        .validate();
    }

    if (name2Req) {
      $('input[name="firstname2"]').attr("data-parsley-required", "true");
      $('input[name="name2"]').attr("data-parsley-required", "true");
      $('select[name="salutation2"]').attr(
        "data-parsley-salutation-req",
        "true"
      );
    } else {
      $('input[name="firstname2"]')
        .attr("data-parsley-required", "false")
        .parsley()
        .validate();
      $('input[name="name2"]')
        .attr("data-parsley-required", "false")
        .parsley()
        .validate();
      $('select[name="salutation2"]')
        .removeAttr("data-parsley-salutation-req")
        .parsley()
        .validate();
    }

    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 () {
      let $this = $(this);
      let needsSign = false;

      if ($this.hasClass("wrapper-company")) {
        if ($this.find(".is-required").length < 1) {
          $this
            .find(".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;
      }

      if (needsSign) {
        $this.find(".is-required").text("*");
      } else {
        $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=Customization&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=Customization&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()
        );
      }

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

      $salutation.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 () {
      checkLNameReq();
    });

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

    if (typeof $("#IBAN") != "undefined" && $("#IBAN").length > 0) {
      // remove whitespaces from IBAN
      $("#IBAN").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 === "000" || val === "") {
          $(".wrapper-company").addClass("hide");
          // notReqField("organisation", false);
        } else {
          // doReqField("organisation", false);
          $(".wrapper-company").removeClass("hide");
        }
        updateSalutations(val);
        checkLNameReq();
      });

    /*$('.donation-form select#NMERKMAL').change(function () {

			let val = $(this).val();
			updateSalutations(val);

			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 () {
        var 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();
        var 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("");
      });
    });
    if ($("#custom_donate_show_public-1")) {
      if ($("#custom_donate_show_public-1").prop("checked")) {
        $("#custom_donate_show_public-1").trigger("click");
      }
    }
    $("#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 p.general").text("").show();
      $("#overlay_error p.specific").text("").show();
    });
  });
})(jQuery);
(function ($) {
   const debug = false;

   const baseUrl = "https://autocomplete2.postdirekt.de/autocomplete2/search/";
   const baseSelectUrl = "https://autocomplete2.postdirekt.de/autocomplete2/select/";
   const tokenUrl = "https://www.brot-fuer-die-welt.de/spenden/jetzt-helfen/api/getDataFactoryToken";
   let token = "";
   let country = "de";
   let lastError = "";
   let $streetInput,
      $cityInput,
      $zipInput,
      cityInputValue = "",
      zipInputValue = "",
      streetInputValue = "",
      timerID;

   // REST - token
   const getToken = function () {
      if (debug) console.log("getToken");

      $.ajax({
         type: "GET",
         url: tokenUrl,
         success: function (data) {
            if (data.token) token = data.token;
         }
      });
   }

   const getInnerData = function (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;
   }

   const updateInputs = function (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();
      }
   }

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

   $(document).ready(function () {
      if (debug) console.log("ready");

      $streetInput = $("#street_autocomplete .autocomplete-input");
      $cityInput = $("#city_autocomplete .autocomplete-input");
      $zipInput = $("#zip_autocomplete .autocomplete-input");

      if (debug) console.log("$streetInput", $streetInput.length);
      if (debug) console.log("$cityInput", $cityInput.length);
      if (debug) console.log("$zipInput", $zipInput.length);

      if ($streetInput.length > 0 || $cityInput.length > 0 || $zipInput.length > 0) {

         // may need event-hook for form
         country = $("#LAND").val();
         $("#LAND").on("select, change", function () {
            country = $(this).val();
         });

         if (debug) console.log(country);

         getToken();
         timerID = setInterval(function () {
            getToken();
         }, 180 * 1000);

         // street autocomplete
         if ($("#street_autocomplete").length > 0) {
            new Autocomplete("#street_autocomplete", {
               search: function search(input) {
                  var minReq = true;
                  streetInputValue = input.substring(0, 55);
                  if (debug) console.log("street_autocomplete", streetInputValue);
                  if (country !== "de") return [];

                  var url = baseUrl + "de/postalcodes_cities_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": "Bearer " + token
                        }
                     }).then(handleErrors).then(function (data) {
                        return data.addresses.length > 0 ? resolve(data.addresses) : resolve([]);
                     }).catch(function (error) {
                        return lastError = error;
                     });
                  });
               },
               getResultValue: function getResultValue(result) {
                  return result.street + ", " + result.postalCode + " " + result.city;
               },
               onSubmit: function onSubmit(result) {
                  if (country === "de") {
                     // console.log(result);
                     if (result !== undefined && result.uuid !== undefined) {
                        $.ajax({
                           url: baseSelectUrl + "de/postalcodes_cities_streets",
                           type: "GET",
                           headers: {
                              "Authorization": "Bearer " + token
                           },
                           data: getInnerData(result.uuid)
                        }).then(function (data) {
                           // console.log(data);
                        });
                        updateInputs(result, false);
                        $("#streetnumber_autocomplete .autocomplete-input").focus();
                     }
                  }
               }
            });
         }

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

                  var url;
                  if ($streetInput.val() !== "") {
                     url = baseUrl + "de/postalcodes_cities_streets?postal_code=" + input;
                  } else {
                     url = baseUrl + "de/postalcodes_cities?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": "Bearer " + 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;
                     });
                  });
               },
               getResultValue: function getResultValue(result) {
                  // console.log(result)
                  if ($streetInput.val() !== "") {
                     return result.street + ", " + result.postalCode + " " + result.city;
                  } else {
                     return result.postalCode + " " + result.city;
                  }
               },
               onSubmit: function onSubmit(result) {
                  if (country === "de") {
                     if (result !== undefined && result.uuid !== undefined) {
                        var placeDefinition = "/postalcodes_cities";
                        if ($streetInput.val() !== "") placeDefinition = "/postalcodes_cities_streets"; // submit selection back
                        // console.log(result);
                        $.ajax({
                           url: baseSelectUrl + "de" + placeDefinition,
                           type: "GET",
                           headers: {
                              "Authorization": "Bearer " + token
                           },
                           data: getInnerData(result.uuid)
                        }).then(function (data) {
                           // console.log(data);
                        });
                        updateInputs(result, true);
                     }
                  }
               }
            });
         }

         // street autocomplete
         if ($("#city_autocomplete").length > 0) {

            new Autocomplete('#city_autocomplete', {
               search: function search(input) {
                  cityInputValue = input;
                  if (country !== "de") return [];

                  var url;
                  if ($streetInput.val() !== "") {
                     url = baseUrl + "de/postalcodes_cities_streets?city=" + input;
                  } else {
                     url = baseUrl + "de/postalcodes_cities?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": "Bearer " + token
                        }
                     }).then(handleErrors).then(function (data) {
                        return data.addresses.length > 0 ? resolve(data.addresses) : resolve([]);
                     }).catch(function (error) {
                        return lastError = error;
                     });
                  });
               },
               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 === "de") {
                     if (result !== undefined && result.uuid !== undefined) {
                        var placeDefinition = "/postalcodes_cities";
                        if ($streetInput.val() !== "") placeDefinition = "/postalcodes_cities_streets"; // submit selection back
                        // console.log(result);
                        $.ajax({
                           url: baseSelectUrl + "de" + placeDefinition,
                           type: "GET",
                           headers: {
                              "Authorization": "Bearer " + token
                           },
                           data: getInnerData(result.uuid)
                        }).then(function (data) {
                           // console.log(data);
                        });
                        updateInputs(result, true);
                     }
                  }
               }
            });
         }

         $(window).bind('beforeunload', function () {
            clearInterval(timerID);
         });
      }
   });
})(jQuery);
(function ($) {
  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 Session abgelaufen. Die Seite wird nun neu geladen."
            )
          ) {
            location.reload();
          } else {
            $(".donation-form__btn-next").remove();
          }
        });
    }, time);
  }

  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 () {
    keepAlive();

    /*
     * Funktion zum komfortablen Scrollen zu einem gegebenen Objekt
     */
    $.fn.extend({
      scrollToMe: function () {
        var 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").click();
      }
    };

    // cover image init
    $('*[data-js="cover-img"]').each(function () {
      $(this).addClass("cover-init");
      var imgSrc = $(this).find("img").attr("src");

      $(this).css("background-image", "url(" + imgSrc + ")");
    });

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

    // step 1 events
    var isSecondPersonAdded = false;
    window.donation = "";

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

    var step1data = (function () {
      var _tmpObj = {};
      $('[data-js="donation-step-1"] select.input-field__select').each(
        function () {
          //console.log($(this));
          var name = $(this).get(0).name,
            value = $(this).find("option:selected").val(),
            text = $(this).find("option:selected").text();
          _tmpObj[name] = text;
        }
      );
      return _tmpObj;
    })();

    // donation value handler
    $('[data-js="input-money"]').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;
    });

    $('[data-focus="1"]').focus();

    $('[data-js="donation-step-1"] .input-field__select').on(
      "change",
      function (e) {
        step1data[e.target.name] = $(e.target).find("option:selected").text();

        //cleanup backend markup error and text, if any
        let targetElem = $("select[name=" + e.target.name + "]");
        //console.log(targetElem);
        if (targetElem.hasClass("field_error")) {
          targetElem.removeClass("field_error");
          $(
            e.target.attributes["data-parsley-errors-container"].nodeValue
          ).text("");
        } else if (targetElem.hasClass("parsley-error")) {
          targetElem.removeClass("parsley-error");
          $(
            e.target.attributes["data-parsley-errors-container"].nodeValue
          ).text("");
        }
      }
    );

    $('[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");
      $("#donation-step-1 textarea").removeAttr("disabled");
      if ($("#custom_donate_show_public-1")) {
        if ($("#custom_donate_show_public-1").prop("checked")) {
          $("#custom_donate_show_public-1").trigger("click");
        }
      }
      $("#amount_currency").removeClass("hide");
    });

    // set custom Parsley validator (min 5 €)
    window.Parsley.addValidator("donationValue", {
      validateString: function (value, requirement) {
        var 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.",
      },
    });

    function toStep2() {
      $('[data-js="donation-step-1"]').addClass("inactive");
      $('[data-js="donation-value"]').text(donation + ",00 €");
      $("#amount_currency").addClass("hide");
      $('[data-js="donation-project-name"]').text(step1data["subject"]);
      $('[data-js="donation-project-duration"]').text(step1data["interval"]);
      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");
      $("#donation-step-1 textarea").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;

      $("#donation-step-1").parsley().validate();

      if ($("#donation-step-1").parsley().isValid()) {
        var sum = parseInt(donation, 10);
        if (sum >= 5000) {
          var $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 events

    // toggle second person
    // used var isSecondPersonAdded = false;
    $('[data-js="donation-form__add-person"]').on("click", function (e) {
      if (!isSecondPersonAdded) {
        isSecondPersonAdded = true;
        $(".donation-form__second-person").removeClass("hide");
        $(this)
          .find(".donation-form__add-person")
          .addClass("donation-form__add-person--minus");
        $(this).find(".input-field__label.more").hide();
        $(this).find(".input-field__label.less").show();

        $('select[name="salutation2"]').removeAttr("disabled");
        $('select[name="salutation2"]').attr("data-parsley-required", "true");

        $('input[name="firstname2"]')
          .attr("data-parsley-required", "true")
          .removeAttr("disabled");
        $('input[name="name2"]')
          .attr("data-parsley-required", "true")
          .removeAttr("disabled");
      } else {
        isSecondPersonAdded = false;

        $('select[name="salutation2"]').attr("data-parsley-required", "false");
        $('select[name="salutation2"]').val("0");
        $('select[name="salutation2"]').attr("disabled", "disabled");

        $('input[name="firstname2"]')
          .attr("data-parsley-required", "false")
          .attr("disabled", "disabled");
        $('input[name="name2"]')
          .attr("data-parsley-required", "false")
          .attr("disabled", "disabled");

        $('input[name="firstname2"]').val("");
        $('input[name="name2"]').val("");

        $(".donation-form__second-person").addClass("hide");
        $(this)
          .find(".donation-form__add-person")
          .removeClass("donation-form__add-person--minus");
        $(this).find(".input-field__label.less").hide();
        $(this).find(".input-field__label.more").show();
      }
    });

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

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

        //cleanup backend markup error and text, if any
        let targetElem = $("select[name=" + e.target.name + "]");
        //console.log(targetElem);
        if (targetElem.hasClass("field_error")) {
          targetElem.removeClass("field_error");
          $(
            e.target.attributes["data-parsley-errors-container"].nodeValue
          ).text("");
        } else if (targetElem.hasClass("parsley-error")) {
          targetElem.removeClass("parsley-error");
          $(
            e.target.attributes["data-parsley-errors-container"].nodeValue
          ).text("");
        }
      }
    );

    $('[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);
      }
    });

    // copy select.value to gray-mode span.value
    function initSelectValue(block) {
      var _block = !block ? "" : block;
      $(_block + " select.input-field__select").each(function () {
        // var fieldValue = $(this).get(0).value;
        var 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) {
      var _block = !block ? "" : block;
      $(_block + " input.input-field__text").each(function () {
        var fieldValue = $(this).get(0).value;
        $(this).prev().text(fieldValue);
        if ($(this).parents(".input-field__wrapper").length > 0) {
          $(this)
            .parents(".input-field")
            .find(".input-field__value")
            .text(fieldValue);
        } else {
          if ($(this).parent().hasClass("flex-1")) {
            $(this).parent().prev().text(fieldValue);
          }
        }
      });
    }

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

      if ($("#donation-step-2").parsley().isValid()) {
        initSelectValue('[data-js="donation-step-2"]');
        initInputValue('[data-js="donation-step-2"]');
        $('[data-js="donation-step-2"]').addClass("complete inactive");
        $('[data-js="donation-step-prev-2"]').removeClass("hide");
        $('*[data-hide="on-step-2"]').each(function () {
          $(this).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"
            );
          }
        }
      });
    });

    // 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.",
      },
    });

    // -- step3 events
    $('[data-js="donation-step-3"]').on(
      "change",
      ".input-field__select",
      function (e) {
        let val = $(this).get(0).value,
          text = $(this).find("option:selected").text();

        if (val == "debit") {
          $("#einzug").removeClass("hide");
          $("#kkarte").addClass("hide");

          changecc();
        } else {
          if (val == "creditcard") {
            $("#einzug").addClass("hide");
            $("#kkarte").removeClass("hide");

            $('input[name="iban"]').val("");
          } else if (val == "paypal") {
            $("#einzug").addClass("hide");
            $("#kkarte").addClass("hide");

            $('input[name="iban"]').val("");
            changecc();
          } else {
            $("#einzug").addClass("hide");
            $("#kkarte").addClass("hide");
          }
        }

        //cleanup backend markup error and text, if any
        let targetElem = $("select[name=" + e.target.name + "]");
        //console.log(targetElem);
        if (targetElem.hasClass("field_error")) {
          targetElem.removeClass("field_error");
          $(
            e.target.attributes["data-parsley-errors-container"].nodeValue
          ).text("");
        } else if (targetElem.hasClass("parsley-error")) {
          targetElem.removeClass("parsley-error");
          $(
            e.target.attributes["data-parsley-errors-container"].nodeValue
          ).text("");
        }
      }
    );

    // form submit
    $('[data-js="donation-form"]').on("submit", function (e) {
      let interval = $('select[name="interval"]').val();
      let paymentmethod = $('select[name="paymentmethod"]').val();

      if (interval && interval != 0 && paymentmethod != "debit") {
        $("#INTERVALL").val("");
        // $('select[name="interval"]')
        //   .parent()
        //   .find(".nice-select.input-field__select")
        //   .val("")
        //   .change();
        $("#interval-error-field").html(
          "Mehrmalige Spende sind nur möglich bei Lastschrifteinzug"
        );

        return;
      }

      $("#donation-step-3").parsley().validate();

      // only for development !!!
      //console.log('form');
      //console.log("step-1 validation -> ", $('#donation-step-1').parsley().isValid());
      //console.log("step-2 validation -> ", $('#donation-step-2').parsley().isValid());
      //console.log("step-3 validation -> ", $('#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 !!!
        // var s = $('[data-js="donation-form"]').serializeArray();
        //console.log(s);
        // only for development !!!
      }
      // only for development !!!
      // e.preventDefault();
      // only for development !!!
    });

    // validation scrolling

    var firstError = true;
    if ($("#donation-step-1").length > 0) {
      $("#donation-step-1")
        .parsley()
        .on("form:validate", function (fieldInstance) {
          firstError = false;
        });
    }
    if ($("#donation-step-2").length > 0) {
      $("#donation-step-2")
        .parsley()
        .on("form:validate", function (fieldInstance) {
          firstError = false;
        });
    }
    if ($("#donation-step-1").length > 0) {
      $("#donation-step-1")
        .parsley()
        .on("field:error", function (fieldInstance) {
          if (!firstError) {
            firstError = fieldInstance.$element.parent();
          }
        });
    }

    if ($("#donation-step-2").length > 0) {
      $("#donation-step-2")
        .parsley()
        .on("field:error", function (fieldInstance) {
          if (!firstError) {
            firstError = fieldInstance.$element.parent();
          }
        });
    }

    if ($("#donation-step-1").length > 0) {
      $("#donation-step-1")
        .parsley()
        .on("form:error", function () {
          firstError.scrollToMe();
        });
    }
    if ($("#donation-step-2").length > 0) {
      $("#donation-step-2")
        .parsley()
        .on("form:error", function () {
          firstError.scrollToMe();
        });
    }

    function setInterval(val, e) {
      // 0: einmalig
      // 1: monatlich
      // 4: vierteljährlich
      // 12: jährlich
      let cdc = $("#custom_donate_container");
      if (cdc && cdc !== null && cdc.length && cdc.length > 0) {
        console.log("force paypal express container show");
        $("#paypal-express-container").removeClass("d-none").addClass("d-flex");
        return;
      }
      switch (val) {
        case "0":
          //console.log('einmalig');
          $('#ZAHLUNGSMETHODE option[value="debit"]').show();
          $('#ZAHLUNGSMETHODE option[value="creditcard"]').show();
          $('#ZAHLUNGSMETHODE option[value="paypal"]').show();

          $('li[data-value="debit"]').show();
          $('li[data-value="creditcard"]').show();
          $('li[data-value="paypal"]').show();

          $("#kkarte").addClass("hide");
          $("#ZAHLUNGSMETHODE")
            .parent()
            .find(".current")
            .html("- bitte wählen -");

          //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);
          // }

          $("#paypal-express-container")
            .removeClass("d-none")
            .addClass("d-flex");

          break;
        case "1":
        case "4":
        case "12":
          //console.log('monatlich/vierteljährlich/jährlich');
          $('#ZAHLUNGSMETHODE option[value="debit"]').show();
          $('#ZAHLUNGSMETHODE option[value="creditcard"]').hide();
          $('#ZAHLUNGSMETHODE option[value="paypal"]').hide();

          $('li[data-value="debit"]').show();
          $('li[data-value="creditcard"]').hide();
          $('li[data-value="paypal"]').hide();

          $("#kkarte").addClass("hide");
          $("#ZAHLUNGSMETHODE")
            .parent()
            .find(".current")
            .html("- bitte wählen -");

          //hide donation without address
          showSimplifiedDonation(false);

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

          $("#paypal-express-container")
            .removeClass("d-flex")
            .addClass("d-none");

          break;
        default:
          //console.log('monatlich/vierteljährlich/jährlich');
          $('#ZAHLUNGSMETHODE option[value="debit"]').show();
          $('#ZAHLUNGSMETHODE option[value="creditcard"]').hide();
          $('#ZAHLUNGSMETHODE option[value="paypal"]').hide();

          $('li[data-value="debit"]').show();
          $('li[data-value="creditcard"]').hide();
          $('li[data-value="paypal"]').hide();

          $("#kkarte").addClass("hide");
          $("#ZAHLUNGSMETHODE")
            .parent()
            .find(".current")
            .html("- bitte wählen -");

          //hide donation without address
          showSimplifiedDonation(false);

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

          $("#paypal-express-container")
            .removeClass("d-flex")
            .addClass("d-none");

          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).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 (
        $("#payone_ppe_workorderid").length > 0 &&
        $("#payone_ppe_workorderid").val() !== ""
      ) {
        if ($("#donation-step-2").hasClass("inactive")) {
          $("#donation-step-1 .btn.donation-form__btn-next").trigger("click");
          setTimeout(function () {
            var x = $("#donation-step-2").offset().top - 50;
            $("html,body").animate({ scrollTop: x }, 500);
          }, 500);
        }
      }

      // donation-step-next-2
    });
  });
})(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()}}();