/* Minification failed. Returning unminified contents.
(33,12-17): run-time warning JS1010: Expected identifier: catch
(36,12-19): run-time warning JS1010: Expected identifier: finally
(36,12-19): run-time error JS1137: 'finally' is a new reserved word and should not be used as an identifier: finally
(33,12-17): run-time error JS1137: 'catch' is a new reserved word and should not be used as an identifier: catch
 */
(function ($) {
  "use strict";
  var $formModal = $("#lot-enquiry-form-modal").modal({
      onHidden: function () {
        $(".field-validation-error").empty();
        $sendForm.validate().resetForm();
        $message.val("");
        $recaptchaToken.val("");
      },
    }),
    $successMessageModal = $("#lot-enquiry-success-message-modal"),
    $failureMessageModal = $("#lot-enquiry-failure-message-modal"),
    $sendForm = $("#lot-enquiry-send-form"),
    $message = $("#userLotEnquiryMessage", $sendForm),
    actionUrl = $sendForm.attr("action"),
    $sendButton = $("#lot-enquiry-form-submit-button"),
    reCaptchaTimeout = +$("#ReCaptchaTimeout").val() * 1000,
    reCaptchaSiteKey = $("#ReCaptchaSiteKey").val(),
    reCaptchaAction = $("#ReCaptchaAction").val(),
    $recaptchaToken = $("#ReCaptchaToken");

    $sendButton.on("click", function () {
        $message.val($message.val().stripHtml());

        if (!$sendForm.valid()) {
            return false;
        }

        timeoutPromise(reCaptchaTimeout, getReCaptchaToken())
          .then(function (token) {
            $recaptchaToken.val(token);
          })
          .catch(function (e) {
            logError(e, "Cannot get reCaptcha token");
          })
          .finally(function () {
            sendForm().success(function (data) {
              if (data.success) {
                $successMessageModal.modal("show");
              } else {
                $failureMessageModal.modal("show");
              }
            });
          });

        return false;
  });

  function getReCaptchaToken() {
    return new Promise(function (resolve, reject) {
      try {
        grecaptcha.enterprise.ready(function () {
          grecaptcha.enterprise
            .execute(reCaptchaSiteKey, { action: reCaptchaAction })
            .then(function (token) {
              resolve(token);
            });
        });
      } catch (e) {
        reject(e);
      }
    });
  }

  function sendForm() {
    return $.ajax({
      type: "POST",
      url: actionUrl,
      data: $sendForm.serialize(),
      headers: Gap.Common.Ajax.GetAntiForgeryTokenHeader(
        "#lotEnquiryToken input[name='__RequestVerificationToken']"
      ),
      error: function () {
        $failureMessageModal.modal("show");
      },
    });
  }

  function logError(e, message) {
    if (window.appInsights) {
      var data = {
        type: "ReCaptcha error",
        message: message,
      };

      window.appInsights.trackException(e, null, data);
      window.appInsights.flush();
    }
  }

  function timeoutPromise(timeoutMs, promise) {
    var timeout = new Promise(function (_, reject) {
      var timeoutId = setTimeout(function () {
        clearTimeout(timeoutId);
        reject(new Error("Promise timed out"));
      }, timeoutMs);
    });

    return Promise.race([timeout, promise]);
  }

  $(
    '#lot-enquire-main-button[data-tab!="tab-login"],#lot-enquire-mobile-button[data-tab!="tab-login"]'
  ).on("click", function (e) {
    $formModal.modal("show");
    e.preventDefault();
  });

  $("#lot-enquiry-form-close-button").on("click", function () {
    $formModal.modal("hide");
  });

  $("#lot-enquiry-success-message-close-button").on("click", function () {
    $successMessageModal.modal("hide");
  });

  $("#lot-enquiry-failure-message-close-button").on("click", function () {
    $failureMessageModal.modal("hide");
  });
})(jQuery);
;