var bidspiritApi;

(function($) {
  var BIDSPIRIT_SERVER = window.bidSpiritServer,
    BIDSPIRIT_API_BASE = BIDSPIRIT_SERVER + "api/thirdparty/v1/",
    REST_API_BASE = "/wp-json/bidspirit/v1/",
    LANG = window.bidSpiritLang,
    currencySymbol =
      window.bidSpiritCurrency !== "" ? window.bidSpiritCurrency : "$",
    bidspiritSessionId,
    bidspiritAuthToken,
    bidspiritUser,
    currentAuctionNumber,
    currentLotIndex,
    allIncrementsPrices = null,
    currentItemInfoResponse = null,
    currentItemInfo = null,
    auctionApprovalState = null,
    auctionHouseData = {
      name: null,
      phone: null,
      email: null,
      vat: null,
      noVatByDefault: null,
      noVatOnCommission: null,
      info: null
    },
    auctionInfo = {
      approvalRequired: null,
      paymentMethodRequired: null,
      absenteeBidsEnabled: null,
      address: null,
      automaticAuction: null,
      commission: null,
      commissionInfo: null,
      currency: null,
      days: null,
      displayStartPriceInCatalog: null,
      id: null,
      info: null,
      lastCatalogUpdate: null,
      name: null,
      number: null,
      showEstimatedPriceInItemsList: null,
      state: null
    },
    paymentMethods = [],
    auctionSettingsData = {
      requireUserId: null,
      requireTaxNumber: null,
      documentUrlBase: null,
      stripePublicKey: null,
      bidspiritPortal: null,
      alertsEnabled: null
    },
    imageBlank = (typeof AuctionForgePlugin !== "undefined" && AuctionForgePlugin.imageBlank) ? AuctionForgePlugin.imageBlank : "/wp-content/plugins/uco-auctions/img/not_found.jpg",
    triggerClass = "is-load-earlier";
  bidspiritApi = {
    lang: LANG,
    getBidspiritSessionId: function() {
      return bidspiritSessionId;
    },
    setBidspiritSessionId: function(sessionId) {
      if (sessionId === undefined) {
        try {
          sessionId = localStorage.getItem("bidspiritSessionId") || "";
        } catch (e) {
          console.error("Local storage disabled");
        }
      }

      bidspiritSessionId = sessionId;
    },
    getAuthToken: function(apiAction) {
      if (
        apiAction !== undefined &&
        apiAction === "users/initSession" &&
        bpGetQueryParams("authToken") !== null
      ) {
        return bpGetQueryParams("authToken");
      }
      try {
        bidspiritAuthToken = localStorage.getItem("bidspiritAuthToken");
      } catch (e) {
        console.error("Local storage disabled");
        bidspiritAuthToken = "";
      }
      return bidspiritAuthToken;
    },
    setAuthToken: function(authToken) {
      try {
        localStorage.setItem("bidspiritAuthToken", authToken);
      } catch (e) {
        console.error("Local storage disabled");
      }
      bidspiritAuthToken = authToken;
    },
    getBidspiritUser: function() {
      return bidspiritUser;
    },
    setBidspiritUser: function(user) {
      bidspiritUser = user;

      let successMessage = "";
      if (bidspiritUser !== undefined) {
        if (bidspiritUser.honorific === undefined) {
          bidspiritUser.honorific = "";
        }

        if (bidspiritUser.firstName === undefined) {
          bidspiritUser.firstName = "";
        }

        if (bidspiritUser.lastName === undefined) {
          bidspiritUser.lastName = "";
        }

        successMessage =
          window.bs_lang.login_success_hello + ", " + bidspiritUser.firstName;

        if (bidspiritUser.honorific !== "") {
          successMessage = window.bs_lang.login_success_full_hello
            .replace(/%s1/, bidspiritUser.honorific)
            .replace(/%s2/, bidspiritUser.firstName)
            .replace(/%s3/, bidspiritUser.lastName);
        }

        if (
          window.bs_lang.login_success_hello_custom !== "" &&
          bidspiritUser.honorific !== ""
        ) {
          successMessage = window.bs_lang.login_success_hello_custom
            .replace(/%s1/, bidspiritUser.honorific)
            .replace(/%s2/, bidspiritUser.firstName)
            .replace(/%s3/, bidspiritUser.lastName);
        } else if (
          window.bs_lang.login_success_hello_custom_default !== "" &&
          bidspiritUser.honorific === ""
        ) {
          successMessage = window.bs_lang.login_success_hello_custom_default
            .replace(/%s1/, bidspiritUser.firstName)
            .replace(/%s2/, bidspiritUser.lastName);
        }
        bidspiritUser.successMessage = successMessage;
      }
    },
    getAuctionApprovalState: function() {
      return auctionApprovalState;
    },
    setAuctionApprovalState: function(value) {
      auctionApprovalState = value;
    },
    getAuctionHouseData: function() {
      return auctionHouseData;
    },
    setAuctionHouseData: function(value) {
      auctionHouseData = value;
    },
    getAuctionInfo: function() {
      return auctionInfo;
    },
    setAuctionInfo: function(value) {
      auctionInfo = value;
    },
    setIncrementsPrices: function(callback) {
      if (allIncrementsPrices === null) {
        bidspiritQuery(
          "items/getIncrementsSteps",
          {
            sessionId: bidspiritSessionId
          },
          function(data) {
            if (data.response !== undefined) {
              hangUpEvent("bp:get-increment-load-steps", data.response);
            }

            allIncrementsPrices = data.response;
            callback(data.response);
          }
        );
      } else {
        callback(allIncrementsPrices);
      }
    },
    getIncrementsPrices: function() {
      return allIncrementsPrices;
    },
    stripeLoad: function(callback) {
      var classTrigger = "stripe-load";

      if (document.body.classList.contains(classTrigger)) {
        callback();
      } else {
        $.getScript("https://js.stripe.com/v3/")
          .done(function(script, textStatus) {
            callback();
            console.info(textStatus + " Stripe load");
            document.body.classList.add(classTrigger);
          })
          .fail(function(jqxhr, settings, exception) {
            console.error("Error Stripe load", jqxhr, settings, exception);
          });
      }
    },

    getLinkOnLive() {
      let lat = "";

      if (
        bidspiritUser !== undefined &&
        bidspiritUser.liveAuctionToken !== undefined
      ) {
        lat = "?lat=" + bidspiritUser.liveAuctionToken;
      }

      return BIDSPIRIT_SERVER + lat;
    },

    bidspiritQuery: bidspiritQuery,
    bidspiritPostQuery: bidspiritPostQuery,
    init: init,
    doLogout: doLogout,
    checkError: checkError,
    initIncrementSteps: initIncrementSteps,
    checkErrorForm: checkErrorForm,
    auctionInfoInit: auctionInfoInit,
    hangUpEvent: hangUpEvent,
    saveFirebaseUser: saveFirebaseUser,
    updateUserDisplay: updateUserDisplay,
    updateDisplay: updateDisplay,
    loginLink: loginLink,
    submitRegister: submitRegister,
    getDataForm: getDataForm
  };

  function ajaxQuery(
    params,
    apiAction,
    data,
    callback,
    errorCallback,
    alwaysCallback
  ) {
    $.ajax(params)
      .done(function(response) {
        if (callback !== undefined) {
          callback(response);
        }
      })
      .fail(function() {
        if (errorCallback !== undefined) {
          errorCallback();
        }
      })
      .always(function() {
        if (alwaysCallback !== undefined) {
          alwaysCallback();
        }
      });
  }

  function restQuery(apiCall, method, data, callback) {
    var xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        if (callback !== undefined) {
          callback(this.responseText);
        }
      }
    };

    apiCall =
      REST_API_BASE + apiCall + "?" + new URLSearchParams(data).toString();
    xhttp.open(method, apiCall, true);
    xhttp.setRequestHeader("Content-type", "application/json");
    xhttp.send();
  }

  function bidspiritQuery(
    apiAction,
    data,
    callback,
    errorCallback,
    alwaysCallback
  ) {
    if (bpGetQueryParams("sessionId") !== null) {
      data.sessionId = bpGetQueryParams("sessionId");
    }

    ajaxQuery(
      {
        url: BIDSPIRIT_API_BASE + apiAction + ".api",
        data: data,
        timeout: 0,
        beforeSend: function(request) {
          request.setRequestHeader(
            "BIDSPIRIT-AUTH-TOKEN",
            bidspiritApi.getAuthToken(apiAction)
          );
        },
        xhrFields: {
          withCredentials: true
        }
      },
      apiAction,
      data,
      callback,
      errorCallback,
      alwaysCallback
    );
  }

  function bidspiritPostQuery(
    apiAction,
    data,
    callback,
    errorCallback,
    alwaysCallback
  ) {
    if (bpGetQueryParams("sessionId") !== null) {
      data.sessionId = bpGetQueryParams("sessionId");
    }

    ajaxQuery(
      {
        url: BIDSPIRIT_API_BASE + apiAction + ".api",
        data: data,
        type: "POST",
        timeout: 0,
        beforeSend: function(request) {
          request.setRequestHeader(
            "BIDSPIRIT-AUTH-TOKEN",
            bidspiritApi.getAuthToken(apiAction)
          );
        },
        xhrFields: {
          withCredentials: true
        }
      },
      apiAction,
      data,
      callback,
      errorCallback,
      alwaysCallback
    );
  }

  function hangUpEvent(name, data, target) {
    var event = jQuery.Event(name);
    event.response = data;
    if (target === undefined) {
      $("body").trigger(event);
    } else {
      target.trigger(event);
    }
  }

  function urldecode(url) {
    return decodeURIComponent(url.replace(/\+/g, " "));
  }

  function passwordShowAction() {
    let profilePasswordIcons = $(".bp_show_password-action");
    if (profilePasswordIcons.length > 0) {
      profilePasswordIcons.each(function(index, elem) {
        $(elem)
          .off("click")
          .on("click", ".bp_show_password", function(event) {
            let profilePasswordIcon = event.target,
              fieldPassword = $(elem).find(".bp-form-control_eye");

            if (fieldPassword[0].type === "password") {
              fieldPassword[0].type = "text";
              profilePasswordIcon.classList.remove("svg-eye");
              profilePasswordIcon.classList.add("svg-eye-slash");
            } else {
              fieldPassword[0].type = "password";
              profilePasswordIcon.classList.remove("svg-eye-slash");
              profilePasswordIcon.classList.add("svg-eye");
            }
          });
      });
    }
  }

  function checkPoint(name, clear) {
    if (clear !== undefined) {
      document.body.classList.remove(name);
      setCookie(name, false, -1);
    } else {
      document.body.classList.add(name);
      setCookie(name, true, 1);
    }
  }

  function setCookie(cname, cvalue, exdays) {
    var d = new Date();

    if (exdays === -1) {
      d.setTime(d.getTime() + exdays);
    } else {
      d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
    }

    var expires = "expires=" + d.toUTCString();
    document.cookie =
      cname + "=" + cvalue + ";" + expires + ";path=/;SameSite=Lax";
  }

  function getCookie(cname) {
    var name = cname + "=",
      data = document.cookie.split(";");

    for (var i = 0; i < data.length; i++) {
      var item = data[i];

      while (item.charAt(0) === " ") {
        item = item.substring(1);
      }

      if (item.indexOf(name) === 0) {
        return item.substring(name.length, item.length);
      }
    }

    return "";
  }

  function addBodyClass(className) {
    // $("body").addClass(className);
    document.body.classList.add(className);
  }

  function searchGetParam(param) {
    var name = param.replace(/[\[\]]/g, "\\$&"),
      regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
      results = regex.exec(window.location.href);

    if (!results) {
      return null;
    }

    if (!results[2]) {
      return "";
    }

    return decodeURIComponent(results[2].replace(/\+/g, " "));
  }

  function fireSwall(message, confirmCallback, deniedCallback) {
    Swal.fire({
      html: message,
      showDenyButton: true,
      showCancelButton: true,
      confirmButtonText: "Ok",
      denyButtonText: "Cancel"
    }).then(result => {
      if (result.isConfirmed) {
        if (confirmCallback !== undefined) {
          confirmCallback();
        }
      } else if (result.isDenied) {
        if (deniedCallback !== undefined) {
          deniedCallback();
        }
      }
    });
  }

  function loadTemplate(
    elem,
    idTemplate,
    data,
    visible,
    callback,
    append,
    prepend
  ) {
    var jElem = $(elem);

    if (typeof elem === "string" && elem.match(/\#/)) {
      elem = elem.replace(/\#/, "");
      jElem = $(document.getElementById(elem));
    }

    var html = _.template(document.getElementById(idTemplate).innerHTML),
      hiddenClass = window.bs_data.hidden_class;

    if (visible) {
      jElem.removeClass(hiddenClass);
    }

    if (append !== undefined) {
      if (prepend !== undefined) {
        jElem.prepend(html(data));
      } else {
        jElem.append(html(data));
      }
    } else {
      jElem.html(html(data));
    }

    if (callback !== undefined) {
      callback();
    }
  }

  function loadTemplateInsert(
    elem,
    idTemplate,
    data,
    append,
    prepend,
    callback
  ) {
    var jElem = $(elem),
      html = _.template(document.getElementById(idTemplate).innerHTML);

    if (append !== undefined) {
      if (prepend !== undefined) {
        jElem.prepend(html(data));
      } else {
        jElem.append(html(data));
      }
    } else {
      jElem.html(html(data));
    }

    if (callback !== undefined) {
      callback();
    }
  }

  function bPcheckError(responseData) {
    if (!responseData || responseData.response == null) {
      noticeSwall(modal, window.bs_lang.error, window.bs_lang.empty_response);
      return true;
    }

    if (responseData.response.errorCode) {
      noticeSwall(
        window.bs_lang.error,
        responseData.response.errorCode,
        responseData.response.errorMessage
      );

      if (responseData.response.errorCode == "SESSION_ENDED") {
        bidspiritUser = null;
        updateDisplay();
      }

      return true;
    }

    return false;
  }

  function checkError(responseData, modal) {
    if (!responseData || responseData.response.success) {
      return false;
    }

    if (!responseData) {
      noticeSwall(modal, "error", "empty response");
      return true;
    }

    hangUpEvent("bp:check-error", responseData.response);

    if (responseData.response.errorCode) {
      noticeSwall("error", "error", responseData.response.errorMessage);

      if (responseData.response.errorCode === "SESSION_ENDED") {
        bidspiritUser = null;
      }

      console.error(responseData.response.errorMessage);
      return true;
    }

    return false;
  }

  function checkErrorForm(form, responseData) {
    var groupContainerSelector = ".errors-group",
      submitButton = $(form).find("[type=submit]"),
      status = false;
    $(form)
      .find(groupContainerSelector)
      .addClass(window.bs_data.hidden_class);

    if (!!submitButton) {
      submitButton[0].disabled = true;
    }

    function printError(form, message) {
      var groupContainer = $(form).find(groupContainerSelector);

      if (groupContainer.hasClass(window.bs_data.hidden_class)) {
        groupContainer.removeClass(window.bs_data.hidden_class);
      }

      groupContainer.empty().append("<p>" + bp_t(message) + "</p>");
      if (!!submitButton) {
        submitButton[0].disabled = false;
      }
    }

    if (!responseData || responseData.response == null) {
      printError(form, "empty response");
      status = true;
    }

    if (
      responseData.response.errorCode == "USER_EXIST" &&
      window.bs_lang.user_exist !== undefined
    ) {
      printError(form, window.bs_lang.user_exist);
      status = true;
    } else if (responseData.response.errorCode) {
      printError(form, responseData.response.errorMessage);
      status = true;
    }

    hangUpEvent("bp:checkErrorForm", responseData);
    return status;
  }

  function calculateCommission(price, auctionCommission, isFull) {
    var secondPercent = auctionHouseData.vat,
      pricePercent = parseFloat(price) * parseFloat(auctionCommission / 100),
      varPercent = 0;

    if (!auctionHouseData.noVatOnCommission) {
      if (isFull) {
        varPercent = (parseFloat(price) + pricePercent) * (secondPercent / 100);
      } else {
        varPercent = pricePercent * (secondPercent / 100);
      }
    } else if (auctionHouseData.noVatOnCommission && isFull) {
      varPercent = price * (secondPercent / 100);
    }

    return (parseFloat(price) + pricePercent + varPercent).toFixed(2);
  }

  function getCommissionPrice(price, fullPriceVat, auctionCommission) {
    if (fullPriceVat === undefined) {
      var singleLot = $("#single-lot"),
        fullPriceVat = Boolean(parseInt(singleLot.attr("data-full-price-vat"))),
        auctionCommission = $(singleLot).attr("data-auction-commission");
    }

    return calculateCommission(price, auctionCommission, fullPriceVat);
  }

  function renderCommissionPrice(price) {
    var fullPrice = getCommissionPrice(price),
      target = $("#bid-commission");

    if (target.length) {
      target.html(formattedPrice(fullPrice, currencySymbol));
    }
  }

  function galleryInitial() {
    function featureGallery(galleryMainSlider, galleryThumbs) {
      var bidspiritUser = bidspiritApi.getBidspiritUser(),
        galleryInfo = $("#gallery-info");

      if (window.bs_data.only_for_user_auth && bidspiritUser !== undefined) {
        var imageWrapper = $("#wrpLotImages");
        galleryInfo.remove();

        if (imageWrapper.length) {
          var imageList = imageWrapper.attr("data-image-list"),
            imageTemplate = imageWrapper.attr("data-image-template"),
            imgTemplate = "",
            isCloned = Boolean(
              parseInt(imageWrapper.attr("data-image-cloned"))
            );

          try {
            imageTemplate = JSON.parse(imageTemplate);
            imageList = imageList.split(/\,/);
            imgTemplate = imageTemplate.uncloned.custom;

            if (Array.isArray(imageList)) {
              imageList.splice(0, 1);
            }

            if (isCloned) {
              imgTemplate = imageTemplate.cloned.custom;
            }

            var mainSlide = [],
              thumbSlide = [];
            imageList.forEach(function(elem, index) {
              var imgSrc = "";
              imgSrc = imgTemplate.replace(/\$1/g, elem);
              imgSrc = imgSrc.replace(/\$2/g, elem.replace(/\D+/, ""));
              var thumbsTemplate = `<div data-slide="${index +
                  1}" class='grid-slide swiper-slide' style='background-image:url("${imgSrc}")'></div>`,
                slideTemplate = `<a href="${imgSrc}" data-fancybox-bp="gallery" class="swiper-slide" style="background-image:url('${imgSrc}')"></a>`;
              mainSlide.push(slideTemplate);
              thumbSlide.push(thumbsTemplate);
            });

            if (mainSlide.length > 0) {
              galleryMainSlider.appendSlide(mainSlide);

              if (typeof galleryThumbs.appendSlide === "function") {
                galleryThumbs.appendSlide(thumbSlide);
              } else {
                galleryThumbs.append(thumbSlide);
              }
            }
          } catch (e) {
            console.error(e);
          }
        }
      } else {
        galleryInfo.removeClass(window.bs_data.hidden_class);
      }
    }

    var gallerySelector = ".bp-gallery-thumbs",
      topGallerySelector = ".bp-gallery-top",
      topGalleryConfig = {
        spaceBetween: 10,
        navigation: {
          nextEl: ".swiper-button-next",
          prevEl: ".swiper-button-prev"
        }
      },
      gridGalleryThumbs = ".bp-gallery-thumbs-grid",
      galleryMainSlider = null,
      galleryThumbs = null;

    if ($(gallerySelector).length) {
      galleryThumbs = new SwiperBP(".bp-gallery-thumbs", {
        spaceBetween: 10,
        slidesPerView: 4,
        freeMode: true,
        centeredSlidesBounds: true,
        slideToClickedSlide: true,
        watchSlidesVisibility: true,
        watchSlidesProgress: true
      });

      if ($(topGallerySelector).length) {
        topGalleryConfig.thumbs = {
          swiper: galleryThumbs
        };
        galleryMainSlider = new SwiperBP(topGallerySelector, topGalleryConfig);
      }
    } else {
      if ($(topGallerySelector).length) {
        (galleryMainSlider = new SwiperBP(
          topGallerySelector,
          topGalleryConfig
        )),
          (galleryThumbs = $(".bp-gallery-thumbs-grid .swiper-wrapper"));

        if (gridGalleryThumbs.length) {
          $(gridGalleryThumbs).on("click", ".swiper-slide", function(item) {
            var slide = $(this).attr("data-slide");
            galleryMainSlider.slideTo(slide);
          });
        }
      }
    }

    $(window).on("bp:after-init", function(data) {
      featureGallery(galleryMainSlider, galleryThumbs);
    });
    $(window).on("bp:after-login", function(data) {
      featureGallery(galleryMainSlider, galleryThumbs);
    });
  }

  function initIncrementSteps(
    incrementsStepPrices,
    minPrice,
    enablePrebidsUnderStartPrice
  ) {
    allIncrementsPrices = [];
    var startStep = null,
      price = 0,
      bidLength = 200,
      bidCount = 0;

    if (
      enablePrebidsUnderStartPrice !== undefined &&
      enablePrebidsUnderStartPrice === true
    ) {
      allIncrementsPrices.push(1);
    }

    for (var j = 0; j < incrementsStepPrices.length; j++) {
      if (incrementsStepPrices[j][0] >= price) {
        if (incrementsStepPrices[j - 1] !== undefined) {
          startStep = incrementsStepPrices[j - 1][0];
          break;
        } else {
          startStep = incrementsStepPrices[j][0];
          break;
        }
      }
    }

    for (var i = 0; i < incrementsStepPrices.length; i++) {
      var increment = incrementsStepPrices[i],
        step = increment[1],
        nextPart = null;

      if (incrementsStepPrices[i + 1] !== undefined) {
        nextPart = incrementsStepPrices[i + 1][0];

        while (nextPart > price) {
          price += step;

          if (price > minPrice) {
            allIncrementsPrices.push(price);
            bidCount++;
          }

          if (bidLength === bidCount) {
            return;
          }
        }
      } else {
        while (bidLength >= bidCount) {
          price += step;

          if (price > minPrice) {
            allIncrementsPrices.push(price);
            bidCount++;
          }
        }
      }
    }
  }

  function listIncrementSteps(incrementsStepPrices, minPrice) {
    if (incrementsStepPrices === null) {
      return [];
    }

    let incrementsPrices = [],
      price = 0,
      bidCount = 0;

    for (var i = 0; i < incrementsStepPrices.length; i++) {
      var increment = incrementsStepPrices[i],
        step = increment[1],
        nextPart = null;

      if (incrementsStepPrices[i + 1] !== undefined) {
        nextPart = incrementsStepPrices[i + 1][0];

        while (nextPart > price) {
          price += step;
          incrementsPrices.push(price);
          bidCount++;
        }
      }
    }

    return incrementsPrices;
  }

  function select2ToolsInit() {
    function toolsInit(formTools) {
      var formSearch = $("#bp-from-tools .bp-btn-search"),
        inputSearch = formTools.find("[name=phrase_by]"),
        inputPerPage = formTools.find("[name=per_page]"),
        inputFilter = $(".bp-form_category"),
        btnClear = formTools.find(".bp-btn-close");
      var settingsSelect2 = {
        width: "resolve",
        theme: "default bp-custom-select",
        minimumResultsForSearch: -1,
        dropdownParent: $(".bp-form_sorter .bp-form-group__inner")
      };
      var settingsSelect2PerPage = {
        width: "resolve",
        theme: "default bp-custom-select",
        minimumResultsForSearch: -1,
        dropdownParent: $(".bp-form_per_page .bp-form-group__inner")
      };
      var settingsSelect2Category = {
        width: "resolve",
        theme: "default bp-custom-select",
        // minimumResultsForSearch: -1,
        dropdownParent: $(".bp-form_category .bp-form-group__inner"),
        placeholder: window.bs_lang.select_value,
        allowClear: true
      };

      if (formTools.length) {
        formSearch.on("click", ".bp-btn-search", function(event) {
          event.preventDefault();
          formTools.submit();
        });
        inputSearch.on("input, change", function(event) {
          btnClear.removeClass(window.bs_data.hidden_class);
        });
        btnClear.on("click", function(event) {
          event.preventDefault();
          inputSearch.val("");
          $(this).addClass(window.bs_data.hidden_class);
          formTools.submit();
        });
        formSearch.on("submit", function(event) {
          event.preventDefault();
        });
        var currentValue = inputSearch.val();

        if (currentValue !== "") {
          inputSearch.trigger("change");
        }
      }

      var selectField = $(".bp-form_sorter .bp-filter-select2");

      if (formTools.length && selectField.length) {
        selectField.select2(settingsSelect2);
        selectField.on("select2:select", function(event) {
          formTools.submit();
        });
      }

      if (inputFilter.length) {
        var selectFieldCategory = $(".bp-form_category .bp-filter-select2");
        selectFieldCategory.select2(settingsSelect2Category);
        selectFieldCategory.on("select2:clear", function(event) {
          formTools.submit();
        });
        selectFieldCategory.on("select2:select", function(event) {
          formTools.submit();
        });
      }

      if (formTools.length && inputPerPage.length) {
        var selectFieldPerPage = $(".bp-form_per_page .bp-per-page-select2");
        selectFieldPerPage.select2(settingsSelect2PerPage);
        selectFieldPerPage.on("select2:select", function(event) {
          formTools.submit();
        });
      }

      if ($(".bp-day-switcher").length) {
        var daysSwitcher = $(".bp-day-switcher");
        daysSwitcher.select2({
          width: "resolve",
          theme: "default bp-custom-select",
          minimumResultsForSearch: -1
        });
        daysSwitcher.on("select2:select", function(event) {
          let data = event.params.data,
            value = data.element.getAttribute("value");
          if (value !== undefined) {
            window.location = value;
          }
        });
      }
    }

    function toolsInitOutdated() {
      var formFilter = $("#bp-from-filter"),
        formSearch = $("#bp-from-search"),
        inputSearch = formSearch.find("[name=bp_auction_search]"),
        inputSearchHidden = $("#bp_auction_search"),
        inputFilter = $(".bp-form_category"),
        btnClear = formSearch.find(".bp-btn-close"),
        inputSorter = $(".bp-form_sorter");
      var settingsSelect2 = {
        width: "resolve",
        theme: "default bp-custom-select",
        minimumResultsForSearch: -1,
        dropdownParent: $(".bp-form_sorter .bp-form-group__inner")
      };
      var settingsSelect2Category = {
        width: "resolve",
        theme: "default bp-custom-select",
        minimumResultsForSearch: -1,
        dropdownParent: $(".bp-form_category .bp-form-group__inner"),
        placeholder: window.bs_lang.select_value,
        allowClear: true
      };

      if (formSearch.length) {
        formSearch.on("click", ".bp-btn-search", function(event) {
          event.preventDefault();
          formFilter.submit();
        });
        inputSearch.on("input, change", function(event) {
          btnClear.removeClass(window.bs_data.hidden_class);
        });
        btnClear.on("click", function(event) {
          event.preventDefault();
          inputSearch.val("");
          inputSearchHidden.val("");
          $(this).addClass(window.bs_data.hidden_class);
          formFilter.submit();
        });
        formSearch.on("submit", function(event) {
          event.preventDefault();
        });
        inputSearch.on("keypress", function(event) {
          if (event.keyCode === 13) {
            inputSearchHidden.val(inputSearch.val());
          }
        });
        var currentValue = inputSearch.val();

        if (currentValue !== "") {
          inputSearch.trigger("change");
        }
      }

      if (inputSorter.length) {
        var selectField = $(".bp-form_sorter .bp-filter-select2"),
          filterParam = searchGetParam("sort_by");
        selectField.select2(settingsSelect2);

        if (filterParam !== null) {
          var select = selectField.find('option[value="' + filterParam + '"]');

          if (select.length) {
            selectField.val(filterParam);
            selectField.trigger("change");
          }
        }

        selectField.on("select2:select", function(event) {
          formFilter.submit();
        });
      }

      if (inputSearch.length) {
        inputSearch.on("input, change", function(event) {
          inputSearchHidden.val($(this).val());
        });
      }

      if (inputFilter.length) {
        var selectFieldCategory = $(".bp-form_category .bp-filter-select2"),
          filterParamCategory = searchGetParam("category_by");
        selectFieldCategory.select2(settingsSelect2Category);

        if (filterParamCategory !== null) {
          var selectCategory = selectFieldCategory.find(
            'option[value="' + filterParamCategory + '"]'
          );

          if (selectCategory.length) {
            selectFieldCategory.val(filterParamCategory);
            selectFieldCategory.trigger("change");
          }
        }

        selectFieldCategory.on("select2:clear", function(event) {
          formFilter.submit();
        });
        selectFieldCategory.on("select2:select", function(event) {
          formFilter.submit();
        });
      }
    }

    var formTools = $("#bp-from-tools");

    if (formTools.length > 0) {
      toolsInit(formTools);
    } else {
      toolsInitOutdated();
    }
  }

  function select2init() {
    function loadStepSelect() {
      bidspiritQuery(
        "items/getIncrementsSteps",
        {
          sessionId: bidspiritSessionId
        },
        function(data) {
          var select = $("#bidFormPrice"),
            minBidPrice = 1,
            enablePrebidsUnderStartPrice = false;

          if (data.response !== undefined) {
            hangUpEvent("bp:get-increment-steps", data.response);
          }

          if (currentItemInfo !== null) {
            var itemInfo = currentItemInfo,
              houseInfo = bidspiritApi.getAuctionHouseData();
            select.empty();

            if (
              itemInfo.leadingBid !== undefined &&
              itemInfo.leadingBid.isSelf &&
              itemInfo.selfAbsenteeBid !== undefined
            ) {
              minBidPrice = itemInfo.selfAbsenteeBid.price - 1;
            } else if (itemInfo.leadingBid !== undefined) {
              minBidPrice = itemInfo.leadingBid.price;
            } else if (
              houseInfo.enablePrebidsUnderStartPrice !== undefined &&
              houseInfo.enablePrebidsUnderStartPrice === true
            ) {
              enablePrebidsUnderStartPrice = true;
              if (
                data.response[0][0] !== undefined &&
                data.response[0][0] > 0
              ) {
                minBidPrice = data.response[0][0] - 1;
              } else {
                minBidPrice = 0;
              }
            } else if (itemInfo.startPrice !== undefined) {
              minBidPrice = itemInfo.startPrice;
              select.append(
                '<option value="' +
                  minBidPrice +
                  '">' +
                  formattedPrice(minBidPrice.toLocaleString(), currencySymbol) +
                  "</option>"
              );
            } else {
              select.append(
                '<option value="0">' +
                  formattedPrice(0, currencySymbol) +
                  "</option>"
              );
            }

            if (!checkError(data)) {
              initIncrementSteps(data.response, minBidPrice);
            }

            for (var i = 0; i < allIncrementsPrices.length; i++) {
              var stepPrice = allIncrementsPrices[i];

              if (stepPrice !== undefined) {
                select.append(
                  '<option value="' +
                    stepPrice +
                    '">' +
                    formattedPrice(stepPrice.toLocaleString(), currencySymbol) +
                    "</option>"
                );
              }
            }
          }
        }
      );
    }

    loadStepSelect();
    var settingsSelect2 = {
      width: "resolve",
      theme: "default bp-custom-select",
      minimumResultsForSearch: -1,
      templateSelection: function(data, container) {
        renderCommissionPrice(data.id);
        return data.text;
      }
    };
    $(".bp-select2").each(function(index, elem) {
      $(elem)
        .select2(settingsSelect2)
        .trigger("change");
    });
  }

  function select2build(elemId, items) {
    return $(elemId).select2({
      data: items,
      minimumResultsForSearch: -1,
      width: "resolve"
    });
  }

  function setInvitationsEnabled(value) {
    bidspiritQuery("users/setInvitationsEnabled", {
      sessionId: bidspiritSessionId,
      isEnabled: value
    });
  }

  function updateUserDisplay() {
    (function() {
      var userFront = $("#userFront");

      if (bidspiritUser && userFront.length) {
        loadTemplate(
          "#modal-profile-content",
          "user-profile-form",
          bidspiritUser
        );
      }
    })();
  }

  function someCode() {
    var singleLogin = $(".bp-single-login-btn");

    if (singleLogin.length && bidspiritUser !== undefined) {
      singleLogin.addClass(window.bs_data.hidden_class);
    }

    if (bidspiritUser !== undefined) {
      $(".bp-register-api, .bp-login-api").each(function(index, elem) {
        if (
          elem.name === "bp_short_login_form" ||
          elem.name === "bp_short_register_form"
        ) {
          elem.innerHTML = '<div class="bs-loader-small"></div>';
          window.location = window.bs_data.link_profile;
        } else {
          elem.innerHTML =
            "<p class='bp-notice'>" +
            window.bs_lang.login_success_hello +
            ", " +
            bidspiritUser.firstName +
            "!</p>";
        }
      });
    }
  }

  function noticeUser(bidspiritUser) {
    var mainContentContainer = $(".bp-main-container");

    if (
      bidspiritUser !== undefined &&
      bidspiritUser.approvalState !== null &&
      bidspiritUser.approvalState !== "APPROVED" &&
      mainContentContainer.length
    ) {
      mainContentContainer.empty();
      loadTemplateInsert(
        mainContentContainer,
        "main-notice-template",
        {
          type: bidspiritUser.approvalState,
          emailConfirmed: bidspiritUser.emailConfirmed
        },
        true,
        true,
        function() {
          resendEmailAction();
        }
      );
    }
  }

  function renderVatField(auctionHouseData) {
    var fullVatPrice = Boolean(
      parseInt($("#single-lot").attr("data-full-price-vat"))
    );

    if (auctionHouseData.noVatOnCommission && !fullVatPrice) {
      $(".vat-field").remove();
    } else if (auctionHouseData.noVatOnCommission && fullVatPrice) {
      $(".vat-field span").html(window.bs_lang.vat_lot_price_commission);
    }
  }

  function initApp() {
    var firebaseTokenFCM = getCookie("FCM_TOKEN");
    if (firebaseTokenFCM !== "") {
      try {
        localStorage.setItem("token_firebase_push_id", firebaseTokenFCM);
      } catch (e) {
        console.error("Local storage disabled");
      }
    }
  }

  function init() {
    $("#bsLoader").removeClass(window.bs_data.hidden_class);
    bidspiritApi.setBidspiritSessionId();
    bidspiritQuery(
      "users/initSession",
      {
        sessionId: bidspiritApi.getBidspiritSessionId(),
        language: LANG
      },
      function(data) {
        if (data.response !== undefined) {
          function initCore(data) {
            updateUserDisplay();
            updateDisplay();
            loginLink();
            someCode();
            hangUpEvent("bp:after-init", data.response);

            checkPoint("bp-init");
            if (bidspiritUser !== undefined) {
              checkPoint("bp-login");
              if (
                bidspiritUser.approvalState !== undefined &&
                bidspiritUser.approvalState === "APPROVED"
              ) {
                checkPoint("bp-approved-user");
              }
            }
          }

          if (data.response.user !== undefined) {
            bidspiritApi.setAuthToken(data.response.user.authToken);
          }
          try {
            bidspiritSessionId = localStorage.bidspiritSessionId =
              data.response.sessionId;
          } catch (e) {
            console.error("Local storage disabled");
            bidspiritSessionId = "";
          }
          bidspiritQuery(
            "settings/getHouseInfo",
            {
              sessionId: bidspiritSessionId,
              language: LANG
            },
            function(data) {
              auctionHouseData = data.response;
              bidspiritApi.setAuctionHouseData(auctionHouseData);
            }
          );
          bidspiritApi.setBidspiritUser(data.response.user);

          if (window.bs_data.bids_in_catalog) {
            bidspiritApi.setIncrementsPrices(function() {
              initCore(data);
            });
          } else {
            initCore(data);
          }
        }

        bidspiritQuery(
          "settings/getSettings",
          {
            sessionId: bidspiritSessionId,
            language: LANG
          },
          function(data) {
            auctionSettingsData = data.response;
          }
        );

        passwordShowAction();
      },
      function(data) {
        disableLoader();
      }
    );
  }

  function loadBid(lotIndex, currentAuctionNumber) {
    if (currentAuctionNumber === "") {
      return;
    }
    bidspiritQuery(
      "items/getAuctionItem",
      {
        sessionId: bidspiritSessionId,
        auctionId: currentAuctionNumber,
        itemIndex: lotIndex,
        language: LANG
      },
      function(data) {
        String.prototype.allReplace = function(obj) {
          var retStr = this;

          for (var x in obj) {
            retStr = retStr.replace(new RegExp("\\" + x, "g"), obj[x]);
          }

          return retStr;
        }; //oversea

        if (data.response !== undefined) {
          hangUpEvent("bp:get-auction-item", data.response);
        }
      }
    );
    bidspiritQuery(
      "items/getItemsInfo",
      {
        sessionId: bidspiritSessionId,
        auctionId: currentAuctionNumber,
        lotIndexes: lotIndex
      },
      function(data) {
        if (!checkError(data)) {
          if (data.response !== undefined) {
            hangUpEvent("bp:get-items-info", data.response);
          }

          if (data.response.notFoundLots[0] === lotIndex) {
            console.error("error", "Lot " + lotIndex, window.bs_lang.not_found);
            disableLoader();
          } else {
            currentItemInfoResponse = data.response;
            currentItemInfo = data.response.itemsInfo[lotIndex];

            if (bpIsset(currentItemInfo)) {
              if (
                bpIsset(currentItemInfo.isFavorite) &&
                currentItemInfo.isFavorite
              ) {
                $("#single-lot")
                  .find(".bp__wishlist")
                  .addClass("bp__wishlist-active");
              }

              displayBidFormData(currentItemInfo);
              buyoutAction(
                currentItemInfoResponse,
                lotIndex,
                currentAuctionNumber
              );
              postSaleAction(
                currentItemInfoResponse,
                lotIndex,
                currentAuctionNumber
              );
              renderVatField(auctionHouseData);
              hangUpEvent(
                "bp:after-getItemsInfo-content-item",
                currentItemInfo,
                $("#single-lot")
              );
            } else {
              noticeSwall("info", window.bs_lang.not_found);
              disableLoader();
            }
          }
        } else {
          disableLoader();
        }
      }
    );
  }

  function buyoutAction(currentItemInfoResponse, lotIndex, auctionNumber) {
    var currentItemInfo = currentItemInfoResponse.itemsInfo[lotIndex],
      preSaleSectionSelector = "#preSale-section",
      auctionCommission = $(preSaleSectionSelector).attr(
        "data-auction-commission"
      ),
      modalPreSaleForm = "#modal-pre-sale-content",
      fullPriceVat = Boolean(
        parseInt($(preSaleSectionSelector).attr("data-full-price-vat"))
      ),
      isShop = Boolean(
        parseInt($(preSaleSectionSelector).attr("data-auction-commission"))
      );

    if (
      currentItemInfoResponse.state === "ENDED" ||
      currentItemInfoResponse.state === "ARCHIVED"
    ) {
      return;
    }

    if (
      currentItemInfoResponse.auctionIsLive === true ||
      currentItemInfo.buyoutPrice === undefined
    ) {
      return;
    }

    if (
      currentItemInfo.leadingBid !== undefined &&
      currentItemInfo.leadingBid.price !== undefined &&
      currentItemInfo.leadingBid.price >= currentItemInfo.buyoutPrice
    ) {
      return;
    }

    if (
      currentItemInfo.soldBid !== undefined &&
      currentItemInfo.soldBid.price !== undefined
    ) {
      return;
    }

    $(modalPreSaleForm).on("click", "#agreeSaleBid", function(event) {
      event.preventDefault();
      let $this = $(this);
      $this.prop("disabled", true);
      $this.addClass("bp-disabled");
      bidspiritPostQuery(
        "items/buyout",
        {
          sessionId: bidspiritSessionId,
          auctionId: auctionNumber,
          lotIndex: lotIndex,
          price: currentItemInfo.buyoutPrice
        },
        function(data) {
          if (!checkError(data)) {
            if (data.response.success === true) {
              MicroModal.close("modal-pre-sale");
              $(modalPreSaleForm).empty();
              $(preSaleSectionSelector).empty();
              loadTemplate(
                modalPreSaleForm,
                "modal-presale-confirm-template",
                {
                  data: auctionHouseData
                },
                false,
                function() {
                  MicroModal.show("modal-pre-sale", microModalInitConfig());
                }
              );
              loadBid(lotIndex, auctionNumber);
            }
          } else {
            MicroModal.close("modal-pre-sale");
            noticeSwall("info", data.response.errorMessage);
            $(preSaleSectionSelector).empty();
          }
        },
        function() {},
        function() {
          $this.prop("disabled", false);
          $this.removeClass("bp-disabled");
        }
      );
    });

    if (
      currentItemInfo.buyoutPrice > 0 &&
      currentItemInfo.buyoutPrice >= currentItemInfo.startPrice
    ) {
      var commissionPrice = calculateCommission(
        currentItemInfo.buyoutPrice,
        auctionCommission,
        fullPriceVat
      );
      loadTemplate(
        preSaleSectionSelector,
        "pre-sale-template",
        {
          currentItemInfo: currentItemInfo,
          currentCurrency: currencySymbol,
          price: currentItemInfo.buyoutPrice,
          commissionPrice: commissionPrice,
          isShop: isShop
        },
        true,
        function() {
          $(preSaleSectionSelector).on("click", "#pre-sale-action", function(
            event
          ) {
            event.preventDefault();

            if (!bidspiritUser) {
              try {
                MicroModal.show("modal-login", microModalInitConfig());
              } catch (e) {
                console.error(e);
              }

              return;
            }

            var lotName = $(modalPreSaleForm).attr("data-name"),
              lotLinkTerm = window.bs_data.page_terms;
            MicroModal.show("modal-pre-sale", microModalInitConfig());
            loadTemplate(
              modalPreSaleForm,
              "modal-presale-template",
              {
                index: currentItemInfo.lotIndex,
                name: lotName,
                currentCurrency: currencySymbol,
                price: currentItemInfo.buyoutPrice,
                linkTerms: lotLinkTerm,
                commissionPrice: commissionPrice,
                buyoutAction: true,
                auctionHouseData: auctionHouseData,
                fullPriceVat: fullPriceVat
              },
              false,
              function() {
                $(modalPreSaleForm).on("click", "#dontAgreeSaleBid", function(
                  event
                ) {
                  event.preventDefault();
                  MicroModal.close("modal-pre-sale");
                });
                $(modalPreSaleForm).on("click", ".modal__close", function(
                  event
                ) {
                  event.preventDefault();
                  MicroModal.close("modal-pre-sale");
                });
              }
            );
          });
        }
      );
    } else {
      console.info("not for pre sold");
    }
  }

  function postSaleAction(
    currentItemInfoResponse,
    lotIndex,
    currentAuctionNumber
  ) {
    var currentItemInfo = currentItemInfoResponse.itemsInfo[lotIndex],
      postSaleSectionSelector = "#postSaleBid",
      auctionCommission = $(postSaleSectionSelector).attr(
        "data-auction-commission"
      ),
      fullPriceVat = Boolean(
        parseInt($(postSaleSectionSelector).attr("data-full-price-vat"))
      ),
      postAuctionSaleOpenedUntil = Boolean(
        parseInt(
          $(postSaleSectionSelector).attr("data-post-auction-sale-opened-until")
        )
      ),
      wrpNotice = $(postSaleSectionSelector).parents(".bp-control__notice"),
      modalPostSaleForm = "#modal-post-sale-content",
      commissionPrice = calculateCommission(
        currentItemInfo.postSalePrice,
        auctionCommission,
        fullPriceVat
      );

    if (
      currentItemInfoResponse.state !== "ENDED" &&
      currentItemInfoResponse.state !== "ARCHIVED"
    ) {
      return;
    }

    console.log(postAuctionSaleOpenedUntil);

    if (!postAuctionSaleOpenedUntil) {
      return;
    }

    if (
      currentItemInfo.soldBid !== undefined &&
      currentItemInfo.soldBid.price !== undefined
    ) {
      return;
    }

    addBodyClass("bp_sale_action");
    $(modalPostSaleForm).on("click", "#agreeSaleBid", function(event) {
      event.preventDefault();
      let $this = $(this);
      $this.prop("disabled", true);
      $this.addClass("bp-disabled");
      bidspiritPostQuery(
        "items/postSalePurchase",
        {
          sessionId: bidspiritSessionId,
          auctionId: currentAuctionNumber,
          lotIndex: lotIndex,
          price: currentItemInfo.postSalePrice
        },
        function(data) {
          if (!checkError(data)) {
            if (data.response.success === true) {
              MicroModal.close("modal-pre-sale");
              $(postSaleSectionSelector).empty();
              $(modalPostSaleForm).empty();
              loadTemplate(
                modalPostSaleForm,
                "modal-post-sale-confirm-template",
                {
                  data: auctionHouseData
                },
                false,
                function() {
                  MicroModal.show("modal-post-sale", microModalInitConfig());
                }
              );
              loadBid(lotIndex, currentAuctionNumber);
            }
          } else {
            MicroModal.close("modal-post-sale");
            noticeSwall("info", data.response.errorMessage);
            $(modalPostSaleForm).empty();
          }
        },
        function() {},
        function() {
          $this.prop("disabled", false);
          $this.removeClass("bp-disabled");
        }
      );
    });

    if (
      currentItemInfo.postSaleDisabled !== undefined &&
      currentItemInfo.postSaleDisabled === false &&
      (currentItemInfoResponse.state === "ENDED" ||
        currentItemInfoResponse.state === "ARCHIVED")
    ) {
      wrpNotice.addClass("bp-control__notice-mod");
      loadTemplate(
        postSaleSectionSelector,
        "post-sale-template",
        {
          currentItemInfo: currentItemInfo,
          currentCurrency: currencySymbol,
          price: currentItemInfo.postSalePrice
        },
        true,
        function() {
          $(postSaleSectionSelector).on("click", "#post-sale-action", function(
            event
          ) {
            var lotName = $(modalPostSaleForm).attr("data-name"),
              lotLinkTerm = window.bs_data.page_terms;

            if (!bidspiritUser) {
              try {
                MicroModal.show("modal-login", microModalInitConfig());
              } catch (e) {
                console.error(e);
              }

              return;
            }
            MicroModal.show("modal-post-sale", microModalInitConfig());

            loadTemplate(
              modalPostSaleForm,
              "modal-post-sale-template",
              {
                index: currentItemInfo.lotIndex,
                name: lotName,
                currentCurrency: currencySymbol,
                price: currentItemInfo.postSalePrice,
                linkTerms: lotLinkTerm,
                commissionPrice: commissionPrice,
                buyoutAction: false,
                auctionHouseData: auctionHouseData,
                fullPriceVat: fullPriceVat
              },
              false,
              function() {
                $(modalPostSaleForm).on("click", "#dontAgreeSaleBid", function(
                  event
                ) {
                  event.preventDefault();
                  MicroModal.close("modal-post-sale");
                });
              }
            );
          });
        }
      );
    }

    hangUpEvent("bp:auction-sales", {
      currentItemInfoResponse,
      lotIndex,
      currentAuctionNumber
    });
  }

  function displayBidFormData(itemInfo) {
    currentItemInfo = itemInfo;
    let houseInfo = bidspiritApi.getAuctionHouseData();

    function price(itemInfo) {
      var obj = {
        price: itemInfo.startPrice,
        leader: false
      };

      if (
        itemInfo["selfAbsenteeBid"] !== undefined &&
        itemInfo["leadingBid"] !== undefined
      ) {
        if (
          itemInfo["selfAbsenteeBid"].price &&
          itemInfo["leadingBid"].isSelf
        ) {
          obj.price = itemInfo["selfAbsenteeBid"].price;
          obj.leader = true;
        } else if (itemInfo["selfAbsenteeBid"].price) {
          obj.price = itemInfo["selfAbsenteeBid"].price;
        } else {
          obj.price = itemInfo["leadingBid"].price;
        }
      } else if (itemInfo["leadingBid"] !== undefined) {
        obj.price = itemInfo["leadingBid"].price;
      }

      return obj;
    }

    var visible = false,
      priceData = price(itemInfo);

    if (
      currentItemInfoResponse.state === "ENDED" ||
      currentItemInfoResponse.state === "ARCHIVED"
    ) {
      visible = true;
    }

    if (
      currentItemInfoResponse["itemsInfo"][currentLotIndex].leadingBid !==
        undefined ||
      currentItemInfoResponse["itemsInfo"][currentLotIndex].soldBid !==
        undefined
    ) {
      visible = true;
    }

    if (
      currentItemInfoResponse["itemsInfo"][currentLotIndex].selfAbsenteeBid !==
        undefined &&
      currentItemInfoResponse["itemsInfo"][currentLotIndex].selfAbsenteeBid
        .price !== undefined
    ) {
      visible = true;
    }

    var singleLotSection = $("#single-lot"),
      hiddenPrice = false;

    if (singleLotSection !== undefined) {
      hiddenPrice = Boolean(
        parseInt(singleLotSection.attr("data-hidden-price"))
      );
    }

    loadTemplate(
      "#leadingBid",
      "leadingBid-template",
      {
        currencySymbol: currencySymbol,
        item: currentItemInfoResponse["itemsInfo"][currentLotIndex],
        itemInfo: currentItemInfoResponse,
        obj: priceData,
        hiddenPrice: hiddenPrice
      },
      visible
    );

    loadTemplate(
      "#houseInfo-section",
      "house-info-template",
      {
        auctionHouseData: bidspiritApi.getAuctionHouseData()
      },
      visible
    );

    if (
      (currentItemInfoResponse !== undefined &&
        currentItemInfoResponse["itemsInfo"][currentLotIndex].soldBid ===
          undefined &&
        currentItemInfoResponse["itemsInfo"][currentLotIndex].startPrice > 0) ||
      (houseInfo.enablePrebidsUnderStartPrice !== undefined &&
        houseInfo.enablePrebidsUnderStartPrice == true)
    ) {
      auctionIsLive(
        currentItemInfoResponse,
        currentItemInfoResponse["itemsInfo"][currentLotIndex]
      );
    } else if (
      currentItemInfoResponse !== undefined &&
      currentItemInfoResponse["itemsInfo"][currentLotIndex].startPrice === 0 &&
      houseInfo.enablePrebidsUnderStartPrice !== undefined &&
      houseInfo.enablePrebidsUnderStartPrice == false
    ) {
      if (!getCookie("bs_read_notice")) {
        noticeSwall(
          "warning",
          window.bs_lang.auction_preview_title,
          window.bs_lang.auction_preview_notice,
          {},
          function() {
            setCookie("bs_read_notice", true, 7);
          }
        );
      }
    }

    disableLoader();
  }

  function auctionIsLive(dataResponse, item) {
    loadTemplate("#auctionIsLive-section", "auctionIsLive-template", {
      isLive: dataResponse.auctionIsLive,
      auctionInfo: bidspiritApi.getAuctionInfo(),
      linkLive: bidspiritApi.getLinkOnLive(),
      state: dataResponse.state,
      auctionHouseData: bidspiritApi.getAuctionHouseData()
    });

    function checkShowcaseEnable(showcaseEnable) {
      if ($("#dateTimeField").length) {
        let dateTimeField = $("#dateTimeField"),
          timeBegin = dateTimeField.attr("data-time"),
          dateStart = timeShift(new Date(Date.parse(timeBegin))),
          dateNow = new Date(),
          timeToStart = (dateStart - dateNow) / 1000 / 3600;
        showcaseEnable = Boolean(
          parseInt(dateTimeField.attr("data-showcase-enable"))
        );

        if (
          parseInt(timeToStart) < parseInt(window.bs_data.auto_close_showcase)
        ) {
          showcaseEnable = false;
        }
      }

      return showcaseEnable;
    }

    let showcaseEnable = window.bs_data.is_showcase_enable;

    if (checkShowcaseEnable(showcaseEnable)) {
      let showcase = $("#showcase-section");
      showcase.removeClass(window.bs_data.hidden_class);
    }

    if (dataResponse.state === "PRE_AUCTION") {
      disableLoader();
    }

    select2init();

    if (dataResponse !== undefined) {
      hangUpEvent("bp:auction-is-live", dataResponse);
    }

    $("#bp-showcase").on("click", function(event) {
      event.preventDefault();

      if (!checkShowcaseEnable(showcaseEnable)) {
        return;
      }

      let $this = $(this),
        title = $("#single-lot h1").text(),
        skuCode = $("#single-lot").attr("data-lot-index");
      $this.addClass(window.bs_data.loader_class);
      $.ajax({
        url: window.wp_data.ajax_url,
        type: "POST",
        dataType: "json",
        data: {
          action: "do_showcase",
          security: window.wp_nonce,
          skuCode: skuCode
        }
      })
        .done(function(response) {
          if (response.success) {
            noticeSwall(
              "success",
              window.bs_lang.showcase_success_title.replace(/#title#/, title),
              window.bs_lang.showcase_success_notice,
              {},
              function() {
                if (
                  response.data !== undefined &&
                  response.data.cart_url !== undefined
                ) {
                  window.location = response.data.cart_url;
                }
              }
            );
          } else {
            noticeSwall("error", "", response.data.notice);
          }
        })
        .fail(function() {
          noticeSwall("error", window.bs_lang.error);
        })
        .always(function() {
          $this.prop("disabled", true);
          $this.removeClass(window.bs_data.loader_class);
        });
    });
  }

  function getDataForm(id) {
    var dataForm = {},
      form = document.forms[id];

    if (document.forms[id] !== undefined) {
      Array.prototype.forEach.call(form.elements, function(elem, index) {
        /*if (!elem.disabled) {

        }*/
        if (elem.type === "checkbox" || elem.type === "radio") {
          dataForm[elem.name] = elem.checked.toString();
        } else {
          dataForm[elem.name] = elem.value;
        }
      });
    }

    return dataForm;
  }

  function submitLogin(event) {
    var formParent = $(event.target),
      formSelector = formParent.attr("name"),
      dataLogin = getDataForm(formSelector);
    dataLogin.sessionId = bidspiritSessionId;
    bidspiritPostQuery("users/login", dataLogin, function(data) {
      hangUpEvent("bp:before-login", {
        data: dataLogin,
        response: data
      });

      if (!checkErrorForm(event.target, data)) {
        bidspiritUser = data.response;
        MicroModal.close("modal-login");
        MicroModal.close("modal-register");
        bidspiritApi.setBidspiritUser(bidspiritUser);

        if (bidspiritUser.authToken !== undefined) {
          bidspiritApi.setAuthToken(bidspiritUser.authToken);
        }

        updateUserDisplay();
        updateDisplay();
        loginLink();
        var position = $("body").hasClass("rtl") ? "top-start" : "top-end",
          successMessage = bidspiritUser.successMessage;

        noticeSwall("success", successMessage, "", {
          position: position,
          showConfirmButton: false,
          timer: 1500
        });
        var form = document.forms[formSelector];
        form.innerHTML = "<p class='title'>" + successMessage + "</p>";
        saveFirebaseUser();
        hangUpEvent("bp:after-login", bidspiritUser);

        checkPoint("bp-login");
        if (
          bidspiritUser.approvalState !== undefined &&
          bidspiritUser.approvalState === "APPROVED"
        ) {
          checkPoint("bp-approved-user");
        }
      }
    });
  }

  function submitRegister(event) {
    var formParent = $(event.target),
      formSelector = formParent.attr("name"),
      dataRegister = getDataForm(formSelector);
    dataRegister.sessionId = bidspiritSessionId;
    dataRegister.postConfirmationLink = formParent.attr("action");
    bidspiritPostQuery("users/register", dataRegister, function(data) {
      hangUpEvent("bp:before-register", {
        data: dataRegister,
        response: data
      });

      if (!checkErrorForm(event.target, data)) {
        bidspiritUser = data.response;
        MicroModal.close("modal-register");
        MicroModal.close("modal-login");

        if (bidspiritUser.authToken !== undefined) {
          bidspiritApi.setAuthToken(bidspiritUser.authToken);
        }

        noticeSwall(
          "success",
          window.bs_lang.register_title,
          window.bs_lang.register_notice
        );
        updateUserDisplay();
        updateDisplay();
        loginLink();
        var form = document.forms[formSelector];
        form.innerHTML =
          "<p class='title'>" +
          window.bs_lang.register_title +
          "</p><p>" +
          window.bs_lang.register_notice +
          "</p>";
        saveFirebaseUser();
        hangUpEvent("bp:after-register", bidspiritUser);
      }
    });
  }

  function getMinBidPriceFromIncrementSteps(itemInfo, incrementsStepPrices) {
    var price = itemInfo.startPrice,
      isStartPrice = true,
      houseInfo = bidspiritApi.getAuctionHouseData();

    if (
      itemInfo.leadingBid !== undefined &&
      itemInfo.leadingBid.isSelf &&
      itemInfo.selfAbsenteeBid !== undefined
    ) {
      price = itemInfo.selfAbsenteeBid.price;
      isStartPrice = false;
    } else if (itemInfo.leadingBid !== undefined) {
      price = itemInfo.leadingBid.price;
      isStartPrice = false;
    } else if (
      houseInfo.enablePrebidsUnderStartPrice !== undefined &&
      houseInfo.enablePrebidsUnderStartPrice === true
    ) {
      price = 0;
      isStartPrice = false;
    }

    if (isStartPrice) {
      return itemInfo.startPrice;
    }

    var startStep = 0;

    for (var j = 0; j < incrementsStepPrices.length; j++) {
      if (incrementsStepPrices[j][0] >= price) {
        if (incrementsStepPrices[j - 1] !== undefined) {
          startStep = price + incrementsStepPrices[j - 1][1];
          break;
        } else {
          startStep = incrementsStepPrices[j][0];
          break;
        }
      }
    }

    return startStep;
  }

  function updateBidsInfoDisplay(bidsInfoData, items, catalogSection, slug) {
    if (bidsInfoData.notFoundLots.length) {
      Array.prototype.forEach.call(bidsInfoData.notFoundLots, function(
        elem,
        index
      ) {
        var trashItem = $("#lot-" + elem);

        if (trashItem.length) {
          trashItem.remove();
        }
      });
      console.info("info", "Failed to find lots", bidsInfoData.notFoundLots);
    }

    if (!slug) {
      slug = false;
    }

    if (bidsInfoData.auctionIsLive) {
      var liveData = {
        bidsInfoData: bidsInfoData,
        linkLive: bidspiritApi.getLinkOnLive()
      };
      loadTemplate("#modal-islive-content", "modal-islive-template", liveData);
      loadTemplate("#userFront", "auction-live-template", liveData);
      MicroModal.init(microModalInitConfig());
      disableLoader();
      MicroModal.show("modal-islive", microModalInitConfig());
    }

    var auctionData = bidspiritApi.getAuctionInfo(),
      hiddenPrice = false,
      showEstimatedPriceInItemsList = auctionData.showEstimatedPriceInItemsList,
      displayStartPriceInCatalog = auctionData.displayStartPriceInCatalog,
      bidsInCatalog = window.bs_data.bids_in_catalog,
      houseInfo = bidspiritApi.getAuctionHouseData();

    var isShop = false;
    if (catalogSection !== undefined) {
      hiddenPrice = Boolean(parseInt(catalogSection.attr("data-hidden-price")));
      showEstimatedPriceInItemsList = Boolean(
        parseInt(catalogSection.attr("data-showEstimatedPrice"))
      );
      displayStartPriceInCatalog = Boolean(
        parseInt(catalogSection.attr("data-displayStartPrice"))
      );
      isShop = Boolean(parseInt(catalogSection.attr("data-is-shop")));
    }

    let incrementStepsList = listIncrementSteps(
      bidspiritApi.getIncrementsPrices()
    );

    if (items.length > 0) {
      for (var i = 0; i < items.length; i++) {
        var itemIndex = items[i],
          itemRow = "";

        if (slug !== false) {
          itemRow = $(document.getElementById("lot-" + slug + "-" + itemIndex));
        } else {
          itemRow = $(document.getElementById("lot-" + itemIndex));
        }

        var itemInfo = undefined;

        if (bidsInfoData.itemsInfo[itemIndex] !== undefined) {
          itemInfo = bidsInfoData.itemsInfo[itemIndex];

          if (
            bidsInfoData.itemsInfo[itemIndex].isFavorite !== undefined &&
            bidsInfoData.itemsInfo[itemIndex].isFavorite
          ) {
            itemRow.find(".bp__wishlist").addClass("bp__wishlist-active");
          }
        }

        var elemId = "";

        if (slug !== false) {
          elemId = "#lot-" + slug + "-" + itemIndex + "-content";
        } else {
          elemId = "#lot-" + itemIndex + "-content";
        }

        var content = "";

        try {
          var dataContent = itemRow.attr("data-content");

          if (dataContent !== undefined) {
            content = JSON.parse(urldecode(itemRow.attr("data-content")));
          }
        } catch (e) {
          console.error("error parse content of lot");
        }

        if (itemInfo === undefined) {
          continue;
        }

        var incrementSteps = bidspiritApi.getIncrementsPrices(),
          nextMinBid = itemInfo.price;

        if (bidsInCatalog) {
          nextMinBid = getMinBidPriceFromIncrementSteps(
            itemInfo,
            incrementSteps
          );
        }

        loadTemplate(
          elemId,
          "lot-content-template",
          {
            auctionInfo: bidsInfoData,
            auctionData: bidspiritApi.getAuctionInfo(),
            itemInfo: itemInfo,
            title: itemRow.find(".bp-lot__title").html(),
            link: itemRow.find(".img-block").attr("href"),
            content: content,
            estimatedPrice: itemRow.attr("data-estimated-price"),
            currency: currencySymbol,
            postAuctionSaleOpenedUntil: Boolean(
              parseInt(
                catalogSection.attr("data-post-auction-sale-opened-until")
              )
            ),
            hiddenPrice: hiddenPrice,
            showEstimatedPriceInItemsList: showEstimatedPriceInItemsList,
            displayStartPriceInCatalog: displayStartPriceInCatalog,
            bidsInCatalog: bidsInCatalog,
            nextMinBid: nextMinBid,
            bidspiritUser: bidspiritUser,
            houseInfo: houseInfo,
            isShop: isShop
          },
          true,
          function() {
            var lot = $(elemId).parents(".bp-lot");
            hangUpEvent("bp:after-getItemsInfo-content-item", itemInfo, lot);
            let bids = [];
            Array.prototype.forEach.call(incrementStepsList, function(elem, i) {
              if (elem >= nextMinBid) {
                bids.push({
                  id: elem,
                  text: formattedPrice(elem.toLocaleString(), currencySymbol)
                });
              }
            });
            let selectBid = select2build(lot.find(".js-data-bid-list"), bids);
            $(lot)
              .off("click")
              .on("click", ".bp-btn", function(event) {
                event.preventDefault();
                var auctionId = catalogSection.attr("data-auction-id"),
                  lotId = lot.attr("data-lot-index");
                bidspiritQuery(
                  "items/getItemsInfo",
                  {
                    sessionId: bidspiritSessionId,
                    auctionId: auctionId,
                    lotIndexes: lotId
                  },
                  function(data) {
                    if (
                      data.response.itemsInfo !== undefined &&
                      data.response.itemsInfo[lotId] !== undefined
                    ) {
                      var itemInfo = data.response.itemsInfo[lotId],
                        minBidPrice = 0;
                      minBidPrice = getMinBidPriceFromIncrementSteps(
                        itemInfo,
                        incrementSteps
                      );

                      if (selectBid.val() > minBidPrice) {
                        minBidPrice = selectBid.val();
                      }

                      submitBidCatalog(lot, minBidPrice, data);
                    }
                  }
                );
              });
          }
        );
      }

      hangUpEvent("bp:after-getItemsInfo-item", bidsInfoData);
    }

    disableLoader();
  }

  function paymentMethodUpdate(callback) {
    new Promise((resolve, reject) => {
      bidspiritPostQuery(
        "users/paymentMethods/getPaymentMethods",
        {
          sessionId: bidspiritSessionId
        },
        function(data) {
          paymentMethods = data.response;
          resolve();
        }
      );
    }).then(function() {
      callback();
    });
  }

  function paymentMethodList(callback) {
    var paymentMethodSelector = "#payment-methods-list";

    if ($(paymentMethodSelector).hasClass("select2")) {
      $(paymentMethodSelector).select2("destroy");
    }

    new Promise((resolve, reject) => {
      bidspiritPostQuery(
        "users/paymentMethods/getPaymentMethods",
        {
          sessionId: bidspiritSessionId
        },
        function(data) {
          paymentMethods = data.response;
          console.log("resolve");
          resolve();
        }
      );
    }).then(function() {
      let items = [];
      Array.prototype.forEach.call(paymentMethods, function(elem, i) {
        items.push({
          id: elem.id,
          text: elem.number
        });
      });
      select2build(paymentMethodSelector, items);

      if (callback !== undefined) {
        callback();
      }
    });

    /*bidspiritPostQuery("users/paymentMethods/getPaymentMethods", {
      sessionId: bidspiritSessionId
    }, function (data) {
      let items = [];
      paymentMethods = data.response;


    });*/
  }

  function modalRequestApprovalShow() {
    MicroModal.show("modal-request-approval", {
      onShow: function(modalBlock) {
        var $modalBlock = $("#modal-payment-method"),
          footer = $modalBlock.find("footer");
        footer.find("#autoChargingCreditCardMessage-block").remove();
        footer.prepend(
          '<p id="autoChargingCreditCardMessage-block" class="bp-text-red bp-mb-0">' +
            autoChargingCreditCardMessage(auctionSettingsData) +
            "</p>"
        );

        if (!$modalBlock.hasClass(triggerClass)) {
          $modalBlock.addClass(triggerClass);
          $("#addPaymentMethod").on("click", addPaymentMethodCallback);
        }
      },
      onClose: function(modalBlock) {}
    });
  }

  function approvalInfo(auctionId) {
    var data = {
        sessionId: bidspiritSessionId,
        auctionId: auctionId
      },
      bidspiritUser = bidspiritApi.getBidspiritUser();

    if (
      !bidspiritUser ||
      bidspiritUser.approvalState === "INCOMPLETE_PROFILE"
    ) {
      return;
    }

    console.log(bidspiritUser);
    if (bidspiritUser.approvedToBidInAllAuctions === true) {
      bidspiritApi.setAuctionApprovalState("APPROVED");
      loadTemplate(
        elemId,
        "approval-info-approved-template",
        {},
        false,
        function() {}
      );
      return;
    }

    bidspiritPostQuery("approvals/getAuctionApprovalState", data, function(
      data
    ) {
      //APPROVAL_REQUESTED, NOT_REQUESTED or APPROVED
      var response = data.response,
        elemId = "#auctionApprovalInfo";
      bidspiritApi.setAuctionApprovalState(response.approvalState);
      console.log("approvals/getAuctionApprovalState query");
      switch (response.approvalState) {
        case "NOT_REQUESTED":
          loadTemplate(
            elemId,
            "approval-info-not-requested-template",
            {
              auctionInfo: auctionInfo
            },
            false,
            function(data) {
              paymentMethodList();
              $("#requestApprovalAction").on("click", function(event) {
                event.preventDefault();
                var data = getDataForm("request-approval-form");
                data.sessionId = bidspiritSessionId;
                data.auctionId = auctionId;
                auctionInfo = bidspiritApi.getAuctionInfo();

                if (
                  data.paymentMethodId === undefined &&
                  auctionInfo.paymentMethodRequired
                ) {
                  noticeSwall(
                    "info",
                    "",
                    window.bs_lang.payment_method_required
                  );
                  return;
                }

                bidspiritPostQuery(
                  "approvals/requestToParticipateInAuction",
                  data,
                  function(data) {
                    if (!checkError(data)) {
                      MicroModal.close("modal-request-approval");
                      approvalInfo(auctionId);
                    }
                  }
                );
              });
            }
          );

          break;

        case "APPROVAL_REQUESTED":
          loadTemplate(
            elemId,
            "approval-info-approval-requested-template",
            {},
            false,
            function(data) {}
          );
          break;

        case "APPROVED":
          loadTemplate(
            elemId,
            "approval-info-approved-template",
            {},
            false,
            function(data) {}
          );
          break;
      }

      if (!!document.getElementById("notRequestedActionBP")) {
        $("#notRequestedActionBP").on("click", function(event) {
          event.preventDefault();
          paymentMethodUpdate(function() {
            if (paymentMethods !== undefined && paymentMethods.length === 0) {
              addPaymentMethodCallback();
            } else {
              modalRequestApprovalShow();
            }
          });
        });
      }

      if (!!document.getElementById("notRequestedActionTermsBP")) {
        $("#notRequestedActionTermsBP").on("click", function(event) {
          event.preventDefault();
          showTermsCondModal();
        });
      }

      //MicroModal.init(microModalInitConfig());
    });
  }

  function updateAuctionPage(catalogSection, itemIndexes, slug) {
    currentAuctionNumber = catalogSection.attr("data-auction-index");

    if (currentAuctionNumber === "") {
      return;
    }

    if (!bidspiritUser) {
      $(".bp__wishlist").removeClass("bp__wishlist-active");
    }

    if (!slug) {
      slug = false;
    }

    var items = [];

    if (itemIndexes === undefined) {
      catalogSection.find(".bp-lot").each(function(index, elem) {
        items.push($(elem).attr("data-lot-index"));
      });
    } else {
      items = itemIndexes;
    }

    bidspiritQuery(
      "items/getItemsInfo",
      {
        sessionId: bidspiritSessionId,
        auctionId: currentAuctionNumber,
        lotIndexes: items + ""
      },
      function(data) {
        if (!checkError(data)) {
          updateBidsInfoDisplay(data.response, items, catalogSection, slug);
        } else {
          disableLoader();
        }
      }
    );
  }

  function toggleAuctionAlert(auctionNumber) {
    if (auctionNumber === "") {
      return;
    }
    var alertCheckbox = $("input#auctionAlertEnabled"),
      bidspiritUser = bidspiritApi.getBidspiritUser(),
      wrapperBlock = $("#auctionNoticeInfo"),
      data = {
        sessionId: bidspiritSessionId,
        auctionId: auctionNumber
      };

    if (!bidspiritUser) {
      wrapperBlock.addClass(window.bs_data.hidden_class);
    } else {
      wrapperBlock.removeClass(window.bs_data.hidden_class);
      bidspiritQuery("auctions/checkAuctionAlert", data, function(response) {
        response = response.response;

        if (response.success) {
          alertCheckbox.prop({
            checked: response.hasAlert
          });
        }
      });
    }

    alertCheckbox.off("change").on("change", function(event) {
      var isOn = $(this).is(":checked"),
        data = {
          sessionId: bidspiritSessionId,
          auctionId: auctionNumber,
          isOn: isOn
        };
      bidspiritQuery("auctions/setAuctionAlert", data, function(response) {
        bPcheckError(response);
      });
    });
  }

  function updateWidgetLots() {
    $(".widget-lots").each(function(index, elem) {
      var $this = $(elem);
      currentAuctionNumber = $this.attr("data-auction-number");
      var items = [];
      $this.find(".bp-lot").each(function(i, element) {
        items.push($(element).attr("data-lot-index"));
      });
      bidspiritQuery(
        "items/getItemsInfo",
        {
          sessionId: bidspiritSessionId,
          auctionId: currentAuctionNumber,
          lotIndexes: items + ""
        },
        function(data) {
          if (!checkError(data)) {
            var bidsInfoData = data.response,
              hiddenPrice = Boolean(parseInt($this.attr("data-hidden-price")));

            if (items.length > 0) {
              for (var i = 0; i < items.length; i++) {
                var itemIndex = items[i],
                  itemRow = $("#widget-lot-" + itemIndex);

                if (bidsInfoData.itemsInfo[itemIndex] !== undefined) {
                  var itemInfo = bidsInfoData.itemsInfo[itemIndex];

                  if (
                    bidsInfoData.itemsInfo[itemIndex].isFavorite !==
                      undefined &&
                    bidsInfoData.itemsInfo[itemIndex].isFavorite
                  ) {
                    itemRow
                      .find(".bp__wishlist")
                      .addClass("bp__wishlist-active");
                  }
                }

                loadTemplate(
                  "#widget-lot-" + itemIndex + "-content",
                  "lot-content-template",
                  {
                    auctionInfo: bidsInfoData,
                    auctionData: bidspiritApi.getAuctionInfo(),
                    itemInfo: itemInfo,
                    title: itemRow.find(".bp-lot__title").html(),
                    link: itemRow.find(".img-block").attr("href"),
                    currency: currencySymbol,
                    hiddenPrice: hiddenPrice,
                    showEstimatedPriceInItemsList: false,
                    displayStartPriceInCatalog: false
                  },
                  true,
                  function() {
                    if (itemInfo !== undefined) {
                      hangUpEvent(
                        "bp:after-getItemsInfo-content-item",
                        itemInfo,
                        itemRow
                      );
                    }
                  }
                );
              }

              hangUpEvent("bp:after-getItemsInfo-item", bidsInfoData);
            }
          }
        }
      );
    });
  }

  function savePaymentMethod(
    bidspiritSessionId,
    stripePaymentMethodId,
    callback
  ) {
    bidspiritPostQuery(
      "users/paymentMethods/checkPaymentMethodSaved",
      {
        sessionId: bidspiritSessionId,
        stripePaymentMethodId: stripePaymentMethodId
      },
      function(data) {
        function reload() {
          showPaymentMethodsList();
          MicroModal.close("modal-payment-method");
        }

        var response = data.response;

        if (response.errorCode) {
          noticeSwall(
            "error",
            response.errorCode,
            "error while trying to save payment method"
          );
          reload();
        } else if (response.success) {
          reload();
        } else if (response.pending) {
          setTimeout(function() {
            savePaymentMethod(
              bidspiritSessionId,
              stripePaymentMethodId,
              callback
            );
          }, 1000);
        }

        if (callback !== undefined) {
          callback();
        }
      }
    );
  }

  function showPaymentMethodsList() {
    bidspiritPostQuery(
      "users/paymentMethods/getPaymentMethods",
      {
        sessionId: bidspiritSessionId
      },
      function(data) {
        var methodsList = "#section-payment-method-list";
        $(methodsList).empty();
        loadTemplate(
          methodsList,
          "payment-methods-list-template",
          {
            data: data.response
          },
          true,
          function() {
            $(methodsList)
              .find(".bp-method-row")
              .each(function(index, elem) {
                var row = $(elem),
                  deleteBtn = row.find(".bp-method-delete");
                deleteBtn.on("click", function(event) {
                  event.preventDefault();
                  fireSwall(window.bs_lang.remove_payment_method, function() {
                    bidspiritPostQuery(
                      "users/paymentMethods/removePaymentMethod",
                      {
                        sessionId: bidspiritSessionId,
                        paymentMethodId: row.attr("data-id")
                      },
                      function(data) {
                        if (data.response === "ok") {
                          row.remove();
                          showPaymentMethodsList();
                        } else {
                          noticeSwall(
                            "error",
                            data.response.errorCode,
                            data.response.errorMessage
                          );
                        }
                      }
                    );
                  });
                });
              });
          }
        );
      }
    );
  }

  function btnActionPaymentMethods(stripe, stripeElements) {
    $("#addPaymentMethodAction").on("click", function() {
      var $this = $(this),
        modalContainer = $this.parents(".modal__container");
      modalContainer.append('<div class="bs-loader-fill"></div>');
      stripe
        .confirmSetup({
          elements: stripeElements,
          confirmParams: {
            return_url: window.location.href
          },
          redirect: "if_required"
        })
        .then(function(response) {
          try {
            savePaymentMethod(
              bidspiritSessionId,
              response.setupIntent.payment_method,
              function() {
                modalContainer.find(".bs-loader-fill").remove();
                clearStripeForm();
                paymentMethodList(function() {
                  if (!!paymentMethods[0]) {
                    let auction = document.querySelector("[data-auction-id]");
                    let data = {
                      sessionId: bidspiritSessionId,
                      paymentMethodId: paymentMethods[0].id
                    };
                    if (!!auction) {
                      data.auctionId = auction.getAttribute("data-auction-id");
                    }
                    bidspiritPostQuery(
                      "approvals/requestToParticipateInAuction",
                      data,
                      function(response) {
                        updateDisplay();
                        /*try {
                        } catch (e) {
                          window.location = window.location.href;
                        }*/
                      }
                    );
                  }
                });
                MicroModal.init(microModalInitConfig());
              }
            );
          } catch (e) {
            modalContainer.find(".bs-loader-fill").remove();
            console.error(e);
            noticeSwall("error", "error", response.error.message);
          }
        });
    });
  }

  function clearStripeForm() {
    var stripePaymentElement = $("#stripePaymentElement");

    if (stripePaymentElement.length) {
      stripePaymentElement
        .empty()
        .append('<div class="bs-loader-small"></div>');
    }
  }

  function loadStripeForm(apiAction, nodeContainer) {
    bidspiritPostQuery(
      apiAction,
      {
        sessionId: bidspiritSessionId
      },
      function(data) {
        if (data.response.clientSecret !== undefined) {
          var options = {
            clientSecret: data.response.clientSecret,
            locale: LANG,
            appearance: {
              theme: "stripe"
            }
          };
          bidspiritApi.stripeLoad(function() {
            var stripeNode = "#stripePaymentElement",
              stripe = Stripe(auctionSettingsData.stripePublicKey),
              stripeElements = stripe.elements(options),
              paymentElement = stripeElements.create("payment");
            paymentElement.mount(stripeNode);
            paymentElement.on("ready", function() {
              $(nodeContainer)
                .find("footer")
                .removeClass(window.bs_data.hidden_class);
            });
            btnActionPaymentMethods(stripe, stripeElements);
          });
        } else {
          noticeSwall("error", "Unknown error", response.errorMessage);
          clearStripeForm();
        }
      },
      function() {},
      function() {}
    );
  }

  function addPaymentMethodCallback() {
    MicroModal.show("modal-payment-method", {
      onShow: function(modalBlock) {
        var $modalBlock = $("#modal-payment-method"),
          footer = $modalBlock.find("footer");
        footer.find("#autoChargingCreditCardMessage-block").remove();
        footer.prepend(
          '<p id="autoChargingCreditCardMessage-block" class="bp-text-red bp-mb-0">' +
            autoChargingCreditCardMessage(auctionSettingsData) +
            "</p>"
        );
        loadStripeForm(
          "users/paymentMethods/getStripeSetupSecret",
          $modalBlock.find(".modal__container")
        );
        $modalBlock.addClass(triggerClass);
      },
      onClose: function(modalBlock) {
        var $modalBlock = $(modalBlock);
        $modalBlock.append('<div class="bs-loader-small"></div>');
        clearStripeForm();
        $modalBlock.find("footer").addClass(window.bs_data.hidden_class);
        $modalBlock.removeClass(triggerClass);
      }
    });
  }

  function paymentMethodAction(apiAction, container, bidspiritUser) {
    if (
      bidspiritUser !== undefined &&
      bidspiritUser.approvalState === "INCOMPLETE_PROFILE"
    ) {
      loadTemplate(container, "account-empty-template", {
        message: window.bs_lang.access_denied
      });
    } else {
      loadTemplate(container, "payment-methods-template", {}, true, function() {
        $("#addPaymentMethod").on("click", addPaymentMethodCallback);
        showPaymentMethodsList();
      });
    }
  }

  function auctionInfoInit(bidspiritSessionId, currentAuctionNumber) {
    if (currentAuctionNumber === "") {
      return;
    } else {
      console.log(bidspiritSessionId, currentAuctionNumber);
      bidspiritQuery(
        "auctions/getAuctionInfo",
        {
          sessionId: bidspiritSessionId,
          auctionId: currentAuctionNumber
        },
        function(data) {
          if (!checkError(data)) {
            bidspiritApi.setAuctionInfo(data.response);
            var response = data.response;

            if (
              response.approvalRequired !== undefined &&
              response.approvalRequired
            ) {
              approvalInfo(currentAuctionNumber);
            }
          }
        }
      );
    }
  }

  function autoChargingCreditCardMessage(auctionSettingsData) {
    var additionalMessage = "";

    if (auctionSettingsData.autoPaymentDays !== undefined) {
      additionalMessage = window.bs_lang.auto_charge_x_days_after.replace(
        /#days#/,
        auctionSettingsData.autoPaymentDays
      );
    }

    return additionalMessage;
  }

  (function() {
    function loadMoreLots() {
      var triggerEvent = true,
        totalLots = catalogSection.attr("data-lot-count");
      $(window, ".st-content").scroll(function(event) {
        var st = $(this).scrollTop(),
          wHeight = $(window).height(),
          catalogSection = $("#catalog-section"),
          catalogBlockHeight = catalogSection.height(),
          catalogOffset = catalogSection.offset(),
          endCatalog = catalogBlockHeight + catalogOffset.top,
          midTriggerHeight = st + wHeight + 1000,
          bgColor = catalogSection.attr("data-bg-color"),
          count = catalogSection.find(".bp-lot").length,
          part = catalogSection.attr("data-auction-part"),
          loaderTemplate = $("#loadMore-template").html(),
          lang = window.bs_data.lang;

        var sortBy = function() {
          return searchGetParam("sort_by");
        };

        var categoryBy = function() {
          return searchGetParam("category_by");
        };

        var phraseBy = function() {
          return searchGetParam("phrase_by");
        };

        var perPage = function() {
          return searchGetParam("per_page");
        };

        if (
          midTriggerHeight > endCatalog &&
          triggerEvent &&
          count < totalLots
        ) {
          catalogSection.append(loaderTemplate);
          triggerEvent = false;
          $.ajax({
            type: "post",
            dataType: "json",
            url: window.wp_data.ajax_url,
            data: {
              action: "do_load_more",
              security: window.wp_nonce,
              auctionId: catalogSection.attr("data-auction-index"),
              termId: catalogSection.attr("data-term-id"),
              count: count,
              part: part,
              lang: lang,
              sort_by: sortBy(),
              category_by: categoryBy(),
              phrase_by: phraseBy(),
              per_page: perPage()
            }
          })
            .done(function(response) {
              var indexes = [];
              $.each(response.data.lots, function(index, elem) {
                indexes.push(elem.itemIndex);
              });
              loadTemplate(
                catalogSection,
                "lotsLoadMore-template",
                {
                  lots: response.data.lots,
                  currency: currencySymbol,
                  bgColor: bgColor,
                  showEstimatedPriceInItemsList: Boolean(
                    parseInt(response.data.showEstimatedPriceInItemsList)
                  ),
                  displayStartPriceInCatalog: Boolean(
                    parseInt(response.data.displayStartPriceInCatalog)
                  )
                },
                false,
                function() {},
                true
              );
              count = catalogSection.find(".bp-lot").length;
              totalLots = response.data.total;
              updateAuctionPage(catalogSection, indexes);
              triggerEvent = true;
            })
            .fail(function() {
              console.error("Fatal error");
            })
            .always(function() {
              $("#bsLoaderCatalog").remove();
            });
        }
      });
    }

    var catalogSection = $("#catalog-section"),
      pagination = window.bs_data.use_pagination;

    if (catalogSection.length && pagination === "off") {
      loadMoreLots();
    }
  })();

  function updateDisplay() {
    var singleLot = $("#single-lot"),
      catalogSection = $("#catalog-section"),
      profile = $("#profile-page");

    (function() {
      if (catalogSection.length) {
        var currentAuctionNumber = catalogSection.attr("data-auction-id");
        auctionInfoInit(bidspiritSessionId, currentAuctionNumber);
        updateAuctionPage(catalogSection);
        toggleAuctionAlert(currentAuctionNumber);
      }
    })();

    (function() {
      if (singleLot.length) {
        var lot = $("#single-lot"),
          dateTime = $("#dateTimeField");
        currentLotIndex = lot.attr("data-lot-index");
        currentAuctionNumber = lot.attr("data-auction-index");
        auctionInfoInit(bidspiritSessionId, currentAuctionNumber);
        loadBid(currentLotIndex, currentAuctionNumber);

        if (dateTime.length) {
          getLeftDate(dateTime.attr("data-time"));
        }
      }
    })();

    (function() {
      function profileQuery(apiAction, lotList) {
        bidspiritQuery(
          apiAction,
          {
            sessionId: bidspiritSessionId,
            language: LANG
          },
          function(data) {
            if (data.response.count > 0) {
              loadTemplate(
                lotList,
                "account-items-template",
                {
                  items: data.response.items,
                  currency: currencySymbol,
                  imageBlank: imageBlank,
                  bgColor: $("#profile-page").attr("data-bg-color")
                },
                false,
                function() {
                  $(lotList + " .bp-lots .bp-lot").each(function(index, elem) {
                    var $this = $(elem),
                      wishBtn = $this.find(".bp__wishlist");
                    $this.find("a").on("click", function(event) {
                      event.preventDefault();
                      event.stopPropagation();
                      $.ajax({
                        type: "post",
                        dataType: "json",
                        url: window.wp_data.ajax_url,
                        data: {
                          action: "do_link",
                          security: window.wp_nonce,
                          bidSpirit: {
                            lot_id: $this.attr("data-lot-id")
                          }
                        }
                      })
                        .done(function(response) {
                          if (
                            response.data !== undefined &&
                            response.success === true
                          ) {
                            window.location = response.data.link;
                          } else {
                            noticeSwall("error", window.bs_lang.not_found);
                          }
                        })
                        .fail(function(response) {
                          noticeSwall("error", window.bs_lang.not_found);
                        });
                    });
                    wishBtn.on("click", function(event) {
                      event.preventDefault();
                      event.stopPropagation();
                      toggleFavorite(
                        $this,
                        wishBtn,
                        $this.attr("data-auction-number"),
                        true
                      );
                    });
                  });
                }
              );
            } else {
              loadTemplate(lotList, "account-empty-template", {
                message: "Lot list empty"
              });
            }
          },
          function(data) {
            noticeSwall(
              "error",
              "The request failed",
              "Your account may have been logged in earlier."
            );
          }
        );
      }

      function buildFields(user) {
        function checkField(field) {
          return field !== undefined ? field : "";
        }

        var fields = {
            honorific: {
              value: checkField(user.honorific),
              label: "Honorific",
              required: false,
              type: "text"
            },
            firstName: {
              value: checkField(user.firstName),
              label: "First Name",
              required: true,
              type: "text"
            },
            lastName: {
              value: checkField(user.lastName),
              label: "Last Name",
              required: true,
              type: "text"
            },
            email: {
              value: checkField(user.email),
              label: "Email",
              required: true,
              type: "email"
            },
            password: {
              value: "",
              label: "Password",
              required: false,
              type: "password"
            },
            phone: {
              value: checkField(user.phone),
              label: "Phone",
              required: true,
              type: "phone"
            },
            secondPhone: {
              value: checkField(user.secondPhone),
              label: "Second phone",
              required: false,
              type: "phone"
            },
            taxNumber: {
              value: checkField(user.taxNumber),
              label: "Tax number",
              required: false,
              type: "text"
            }
          },
          fieldsAddress = {
            countryCode: {
              value: "",
              label: "Country",
              required: true,
              type: "select"
            },
            state: {
              value: "",
              label: "State",
              required: false,
              type: "select",
              hidden: true
            },
            province: {
              value: "",
              label: "State",
              required: false,
              type: "text",
              hidden: true
            },
            city: {
              value: "",
              label: "City",
              required: true,
              type: "text"
            },
            address: {
              value: "",
              label: "Address",
              required: true,
              type: "text"
            },
            zipCode: {
              value: "",
              label: "Zip Code",
              required: true,
              type: "text"
            }
          };

        if (user.address !== undefined) {
          fieldsAddress = {
            countryCode: {
              value: checkField(user.address.countryCode),
              label: "Country",
              required: true,
              type: "select"
            },
            state: {
              value: checkField(user.address.state),
              label: "State",
              required: false,
              type: "select",
              hidden: true
            },
            province: {
              value: checkField(user.address.state),
              label: "State",
              required: false,
              type: "text",
              hidden: true
            },
            city: {
              value: checkField(user.address.city),
              label: "City",
              required: true,
              type: "text"
            },
            address: {
              value: checkField(user.address.address),
              label: "Address",
              required: true,
              type: "text"
            },
            zipCode: {
              value: checkField(user.address.zipCode),
              label: "Zip Code",
              required: true,
              type: "text"
            }
          };
        }

        return $.extend(fields, fieldsAddress);
      }

      function profileFormAction() {
        var profileSection = "#profile-account-section";

        function codeFieldList(bidspiritUser) {
          bidspiritQuery(
            "settings/getCountriesList",
            {
              sessionId: bidspiritSessionId,
              language: LANG
            },
            function(data) {
              var countrySelect = $("#profilecountryCode"),
                stateSelect = $("#profilestate"),
                codeSelect = $(".phoneCodeSelect"),
                codeFirstSelect = $("#detailsphoneCountryCode"),
                codeSecondSelect = $("#detailssecondPhoneCountryCode"),
                items = [],
                codeItems = [];

              if (data.response !== undefined) {
                items = $.map(data.response, function(obj) {
                  return {
                    id: obj.code,
                    phoneCode: obj.phoneCode,
                    text: obj.name
                  };
                });
                codeItems = $.map(data.response, function(obj) {
                  return {
                    id: obj.phoneCode,
                    text: obj.phoneCode + " (" + obj.name + ")"
                  };
                });
              }

              countrySelect.select2({
                theme: "default bp-custom-select",
                width: "resolve",
                data: items
              });

              if (
                bidspiritUser.address !== undefined &&
                bidspiritUser.address.countryCode !== undefined
              ) {
                countrySelect
                  .val(bidspiritUser.address.countryCode)
                  .trigger("change.select2");

                if (bidspiritUser.address.countryCode !== "US") {
                  stateSelect.val("").trigger("change.select2");
                }

                // stateList(bidspiritUser);
              }

              countrySelect.on("select2:select", function(event) {
                var data = event.params.data;
                fieldState(data.id, "");
                fieldTaxNumber();
              });
              codeSelect.select2({
                theme: "default bp-custom-select",
                width: "resolve",
                data: codeItems,
                placeholder: window.bs_lang.country_code
              });

              if (bidspiritUser.phoneCountryCode !== undefined) {
                codeFirstSelect
                  .val(bidspiritUser.phoneCountryCode)
                  .trigger("change.select2");
              }

              if (bidspiritUser.secondPhoneCountryCode !== undefined) {
                codeSecondSelect
                  .val(bidspiritUser.secondPhoneCountryCode)
                  .trigger("change.select2");
              }

              stateList(bidspiritUser);
              if (countrySelect.val() === "US") {
                stateSelect
                  .parents(".bp-form-group")
                  .removeClass(window.bs_data.hidden_class);
              }
            }
          );
        }

        function fieldState(stateCode, value) {
          var stateSelect = $("#profilestate"),
            provinceField = $("#profileprovince"),
            stateCodeUS = "US",
            stateCodeIL = "IL";

          if (stateCode === stateCodeUS) {
            provinceField
              .parents(".bp-form-group")
              .addClass(window.bs_data.hidden_class);
            provinceField.attr("name", "province");
            stateSelect
              .parents(".bp-form-group")
              .removeClass(window.bs_data.hidden_class);
            if (
              bidspiritUser.address !== undefined &&
              bidspiritUser.address.stateCode !== undefined &&
              value !== ""
            ) {
              stateSelect
                .val(bidspiritUser.address.stateCode)
                .trigger("change.select2");
            }
          } else if (stateCode === stateCodeIL) {
            stateSelect
              .parents(".bp-form-group")
              .addClass(window.bs_data.hidden_class);
            provinceField
              .parents(".bp-form-group")
              .addClass(window.bs_data.hidden_class);
            provinceField.attr({
              name: "state",
              value: ""
            });
          } else {
            provinceField
              .parents(".bp-form-group")
              .removeClass(window.bs_data.hidden_class);
            provinceField.attr({
              name: "state",
              value: value
            });
            stateSelect
              .parents(".bp-form-group")
              .addClass(window.bs_data.hidden_class);
          }
        }

        function fieldTaxNumber() {
          var taxNumberField = $("#profiletaxNumber"),
            bsOptions = window.bs_data;

          if (
            bsOptions.tax_number_required !== undefined &&
            bsOptions.tax_number_required === "on"
          ) {
            taxNumberField
              .parents(".bp-form-group")
              .removeClass(window.bs_data.hidden_class);
            taxNumberField
              .attr("required", "true")
              .attr("placeholder", taxNumberField.attr("placeholder") + " *");
          } else {
            taxNumberField
              .parents(".bp-form-group")
              .addClass(window.bs_data.hidden_class);
            taxNumberField.val("").removeAttr("required");
          }
        }

        function stateList(bidspiritUser) {
          var stateCodeUS = "US";
          bidspiritQuery(
            "settings/getCountryStates",
            {
              sessionId: bidspiritSessionId,
              countryCode: stateCodeUS
            },
            function(data) {
              var countrySelect = $("#profilecountryCode"),
                stateSelect = $("#profilestate"),
                items = [];

              if (data.response !== undefined) {
                data.response.unshift({
                  code: "",
                  name: ""
                });

                items = $.map(data.response, function(obj) {
                  return {
                    id: obj.code,
                    text: obj.name
                  };
                });
              }

              stateSelect.select2({
                theme: "default bp-custom-select",
                width: "resolve",
                data: items,
                placeholder: "State"
              });
              var stateVal = "";

              if (
                bidspiritUser.address !== undefined &&
                (bidspiritUser.address.state !== undefined ||
                  bidspiritUser.address.stateCode !== undefined)
              ) {
                stateVal = bidspiritUser.address.state;
                if (bidspiritUser.address.countryCode == "US") {
                  stateVal = bpIsset(bidspiritUser.address.stateCode)
                    ? bidspiritUser.address.stateCode
                    : bidspiritUser.address.state;
                }

                fieldState(countrySelect.val(), stateVal);
              }

              fieldTaxNumber();
            }
          );
        }

        if (!$(profileSection + " > *").length) {
          loadTemplate(
            profileSection,
            "profile-account-template",
            {
              user: bidspiritUser,
              fields: buildFields(bidspiritUser),
              stateInfo: getApprovalStateInfo(bidspiritUser)
            },
            true,
            function() {
              if (bidspiritUser.allowInvitations !== undefined) {
                $(subscribeCheckbox).prop(
                  "checked",
                  bidspiritUser.allowInvitations
                );
              }

              $(subscribeCheckbox).on("change", function(event) {
                var $this = $(this),
                  value = $this.prop("checked");
                setInvitationsEnabled(value);
              });
            }
          );
          codeFieldList(bidspiritUser);
        }

        let profileEmailEditSelector = "#profileemail + svg.icon";
        if ($(profileEmailEditSelector).length !== 0) {
          $(profileEmailEditSelector)
            .off()
            .on("click", function(event) {
              document.getElementById("profileemail").disabled = false;
            });
        }

        passwordShowAction();
      }

      if (profile.length) {
        var wishList = "#bp-wish-list",
          wishListSection = "#profile-wishlist-section",
          bidsList = "#bp-my-bids",
          bidsListSection = "#profile-bids-section",
          winningsList = "#bp-winnings",
          winningsListSection = "#profile-winnings-section",
          paymentMethods = "#bp-payment-methods",
          paymentMethodsSection = "#profile-payment-methods-section",
          subscribeCheckbox = "#invitationsEnabled input";

        if (bidspiritUser && bidspiritUser.emailConfirmed === true) {
          loadTemplate(
            "#profile-page",
            "profile-page-template",
            bidspiritUser,
            false,
            function() {
              activeTabs();

              switch (window.location.hash) {
                case wishList:
                  profileQuery("account/getFavorites", wishListSection);
                  break;

                case bidsList:
                  profileQuery("account/getAbsenteeBids", bidsListSection);
                  break;

                case winningsList:
                  profileQuery("account/getPurchases", winningsListSection);
                  break;

                case paymentMethods:
                  paymentMethodAction(
                    "users/paymentMethods/getStripeSetupSecret",
                    paymentMethodsSection,
                    bidspiritUser
                  );
                  break;

                default:
                  profileFormAction();
              }
            }
          );
        } else if (bidspiritUser && bidspiritUser.emailConfirmed === false) {
          loadTemplate(
            "#profile-page",
            "profile-page-empty-template",
            bidspiritUser
          );
        } else {
          loadTemplate(
            "#profile-page",
            "profile-page-gate-template",
            bidspiritUser
          );
          MicroModal.init(microModalInitConfig());
        }

        var updateDetailsForm = $("#updateDetailsSection"),
          logoutAction = $(".logoutLink"),
          profileLink = $("#bp-profile-link, #bp-account .bp-spoiler-trigger"),
          wishListLink = $(
            "#bp-wish-list-link, #bp-wish-list .bp-spoiler-trigger"
          ),
          bidsListLink = $(
            "#bp-bids-list-link, #bp-my-bids .bp-spoiler-trigger"
          ),
          paymentMethodsLink = $(
            "#bp-payment-methods-link, #bp-payment-methods .bp-spoiler-trigger"
          ),
          winningsListLink = $(
            "#bp-winnings-list-link, #bp-winnings .bp-spoiler-trigger"
          );

        if (updateDetailsForm.length) {
          updateDetailsForm.on("submit", function(event) {
            event.preventDefault();
            submitUpdateDetails();
          });
        }

        resendEmailAction();

        if (profileLink.length) {
          profileLink.on("click", function(event) {
            event.preventDefault();
            profileFormAction();
          });
        }

        if (wishListLink.length) {
          wishListLink.on("click", function(event) {
            event.preventDefault();

            if ($(wishListSection).is(":empty")) {
              profileQuery("account/getFavorites", wishListSection);
            }
          });
        }

        if (bidsListLink.length) {
          bidsListLink.on("click", function(event) {
            event.preventDefault();

            if ($(bidsListSection).is(":empty")) {
              profileQuery("account/getAbsenteeBids", bidsListSection);
            }
          });
        }

        if (paymentMethodsLink.length) {
          paymentMethodsLink.on("click", function(event) {
            event.preventDefault();

            if ($(paymentMethodsSection).is(":empty")) {
              paymentMethodAction(
                "users/paymentMethods/getStripeSetupSecret",
                paymentMethodsSection,
                bidspiritUser
              );
            }
          });
        }

        if (winningsListLink.length) {
          winningsListLink.on("click", function(event) {
            event.preventDefault();

            if ($(winningsListSection).is(":empty")) {
              profileQuery("account/getPurchases", winningsListSection);
            }
          });
        }

        doLogout(logoutAction);
      }
    })();

    (function() {
      var dateTimeField = $("#dateTimeField, .bp-auction-start-date");

      if (dateTimeField.length) {
        dateTimeField.each(function(index, elem) {
          printTime($(elem), $(elem).attr("data-time"));
        });
      }
    })();

    if (bidspiritUser !== null) {
      noticeUser(bidspiritUser);
    }
  }

  function doLogout(logoutAction) {
    checkPoint("bp-login", true);
    logoutAction.on("click", function(event) {
      event.preventDefault();
      bidspiritQuery(
        "users/logout",
        {
          sessionId: bidspiritSessionId
        },
        function(data) {
          if (!checkError(data)) {
            bidspiritUser = null;

            if ($("#modal-profile").length) {
              MicroModal.close("modal-profile");
              MicroModal.init(microModalInitConfig());
            }

            try {
              localStorage.removeItem("bidspiritSessionId");
              localStorage.removeItem("bidspiritAuthToken");
            } catch (e) {
              console.error("Local storage disabled");
            }
            window.location.reload();
          }
        }
      );
    });
  }

  function printTime(elem, dateTime) {
    function getLocalTime(time) {
      var str = time;
      var re = /\(.+\)/gm;
      var found = str.match(re);

      if (found !== null) {
        return found[0];
      } else {
        return "";
      }
    }

    function addZero(i) {
      if (i < 10) {
        i = "0" + i;
      }

      return i;
    }

    if (bpIsset(window.timeZoneName) && bpIsset(window.timeZoneName) !== "") {
      var getAuctionDate = new Date(dateTime),
        polylangTimeUse = window.polylang_time,
        getAuctionDateDiff = timeShift(dateTime);
      // getAuctionDateDiff = new Date(getAuctionDateDiff).toLocaleTimeString("en-US", {timeZone: window.timeZoneName});
    } else {
      var getAuctionDate = new Date(dateTime),
        // getAuctionDateDiff = timeShift(getAuctionDate);
        getAuctionDateDiff = getAuctionDate;
    }

    if (
      !(bpIsset(window.timeZoneName) && bpIsset(window.timeZoneName) !== "") &&
      window.browser_time === "off"
    ) {
      getAuctionDateDiff = new Date(getAuctionDate.getTime());
    }

    if (window.format_display_time === "2" || polylangTimeUse === "on") {
      var getAuctionDateDay = addZero(getAuctionDateDiff.getDate()),
        getAuctionMonth = addZero(getAuctionDateDiff.getMonth() + 1),
        getAuctionFullYear = getAuctionDateDiff.getFullYear(),
        getAuctionHours = addZero(getAuctionDateDiff.getHours()),
        getAuctionMinutes = addZero(getAuctionDateDiff.getMinutes()),
        nameDaysArray = [
          "Sunday",
          "Monday",
          "Tuesday",
          "Wednesday",
          "Thursday",
          "Friday",
          "Saturday"
        ][getAuctionDate.getDay()],
        nameMonthArray = [
          "January",
          "February",
          "March",
          "April",
          "May",
          "June",
          "July",
          "August",
          "September",
          "October",
          "November",
          "December"
        ][getAuctionDate.getMonth()];
    }

    var customDateForm = elem.attr("data-custom-format"),
      customDateFormTime = elem.attr("data-custom-format-time"),
      unknownExactDate = Boolean(
        parseInt(elem.attr("data-unknown-exact-date"))
      ),
      unknownDate = elem.attr("data-unknown-date"),
      localTime = getLocalTime(getAuctionDateDiff.toString()),
      polyLanguage = getCookie("pll_language");

    if (window.browser_time === "off") {
      localTime =
        window.timeZoneLabel !== "" ? "(" + window.timeZoneLabel + ")" : "";
    }

    var userLang =
      polyLanguage !== ""
        ? polyLanguage
        : navigator.language || navigator.userLanguage;
    var options = {
      timeZone: getTimeZoneFromUser(),
      formatMatcher: "basic",
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric",
      hour: "numeric",
      minute: "numeric",
      timeZoneName: "short"
    };

    if (elem.length) {
      if (unknownExactDate) {
        elem.html(unknownDate);
        return;
      }

      if (window.browser_time === "on" || customDateForm === "") {
        if (window.format_display_time === "2") {
          elem.html(
            nameMonthArray +
              " " +
              getAuctionDateDay +
              ", " +
              getAuctionFullYear +
              ", " +
              getAuctionHours +
              ":" +
              getAuctionMinutes +
              " " +
              localTime
          );
        } else if (polylangTimeUse === "on") {
          elem.html(getAuctionDateDiff.toLocaleTimeString(userLang, options));
        } else {
          elem.html(
            getAuctionDateDiff.toLocaleTimeString(getLocaleFromUser(), options)
          );
        }
      } else {
        elem.html(customDateFormTime);
      }
    }
  }

  function submitBid() {
    var singleLot = $("#single-lot"),
      notApproveStateNotice = window.bs_lang.not_approved_user,
      pendingStateNotice = window.bs_lang.pending_user_state;

    if (!bidspiritUser) {
      try {
        MicroModal.show("modal-login", microModalInitConfig());
      } catch (e) {
        console.error(e);
      }
    } else if (bidspiritUser.approvalState === "PENDING") {
      noticeSwall("error", window.bs_lang.oops, pendingStateNotice);
    } else if (bidspiritUser.approvalState === "INCOMPLETE_PROFILE") {
      noticeSwall("error", window.bs_lang.oops, notApproveStateNotice);
    } else {
      var data = getDataForm("bidFormSection"),
        modalBidForm = "#modal-bid-content",
        lotName = $(modalBidForm).attr("data-name"),
        lotLinkTerm = window.bs_data.page_terms,
        additionalNotice = false,
        additionalNoticeText = "";
      var fullPriceVat = Boolean(
          parseInt(singleLot.attr("data-full-price-vat"))
        ),
        auctionCommission = $(singleLot).attr("data-auction-commission");
      data.sessionId = bidspiritSessionId;
      data.auctionId = currentAuctionNumber;
      data.lotIndex = currentItemInfo.lotIndex;
      data.bidFormUrl = window.location.href;
      data.sendBidEmails = false;
      data.sendOverBidEmails = false;

      if (parseInt(data.price) >= currentItemInfo.buyoutPrice) {
        additionalNotice = true;
        additionalNoticeText = window.bs_lang.buyout_notice.replace(
          /#price#/,
          formattedPrice(currentItemInfo.buyoutPrice, currencySymbol)
        );
      }

      MicroModal.show("modal-bid", microModalInitConfig());
      loadTemplate(
        modalBidForm,
        "modal-bid-template",
        {
          index: data.lotIndex,
          name: lotName,
          currentCurrency: currencySymbol,
          price: data.price,
          fullPrice: getCommissionPrice(data.price),
          linkTerms: lotLinkTerm,
          additionalNotice: additionalNotice,
          additionalNoticeText: additionalNoticeText,
          auctionHouseData: auctionHouseData,
          fullPriceVat: fullPriceVat,
          auctionCommission: auctionCommission,
          user: bidspiritUser,
          itemInfo: currentItemInfo,
          settings: auctionSettingsData,
          additionalMessage: autoChargingCreditCardMessage(auctionSettingsData)
        },
        false,
        function() {
          $(modalBidForm)
            .off("click", "#agreeBid")
            .on("click", "#agreeBid", function(event) {
              event.preventDefault();
              var bsOptions = window.bs_data,
                taxNumberNotRequired =
                  bsOptions.tax_number_required !== undefined &&
                  bsOptions.tax_number_required === "off";

              function userGate(bidspiritUser) {
                if (
                  bidspiritUser.taxNumber !== undefined &&
                  bidspiritUser.taxNumber !== ""
                ) {
                  return true;
                }

                return false;
              }

              var subData = getDataForm("subBidFormSection");

              if (subData) {
                data.sendBidEmails =
                  subData.sendBidEmails !== undefined &&
                  subData.sendBidEmails === "true";
                data.sendOverBidEmails =
                  subData.sendOverBidEmails !== undefined &&
                  subData.sendOverBidEmails === "true";
                data.callUserWhenItemIsLive =
                  subData.callUserWhenItemIsLive !== undefined &&
                  subData.callUserWhenItemIsLive === "true";
                bidspiritUser.sendBidEmails = data.sendBidEmails;
                bidspiritUser.sendOverBidEmails = data.sendOverBidEmails;
              }

              if (taxNumberNotRequired || userGate(bidspiritUser)) {
                var dataAlert = {
                  sessionId: data.sessionId,
                  auctionId: data.auctionId,
                  lotIndex: data.lotIndex,
                  isOn: true
                };
                bidspiritQuery("items/placeBid", data, function(data) {
                  if (!checkError(data)) {
                    handleSubmitResponse(data.response);
                    bidspiritQuery(
                      "items/setItemAlert",
                      dataAlert,
                      function() {}
                    );
                    data.response.data = {
                      auctionId: dataAlert.auctionId,
                      lotIndex: dataAlert.lotIndex,
                      user: bidspiritUser.email
                    };
                    hangUpEvent("bp:after-items-place-bid", data.response);
                  }
                });
                MicroModal.close("modal-bid");
              } else {
                MicroModal.close("modal-bid");
                noticeSwall(
                  "error",
                  window.bs_lang.tax_number_required,
                  window.bs_lang.tax_number_required_label,
                  {},
                  function() {
                    var linkProfile = window.bs_data.link_profile;

                    if (linkProfile !== undefined && linkProfile !== "link") {
                      window.location = linkProfile;
                    }
                  }
                );
              }
            });
          $(modalBidForm)
            .off("click", "#dontAgreeBid")
            .on("click", "#dontAgreeBid", function(event) {
              event.preventDefault();
              MicroModal.close("modal-bid");
            });
        }
      );
    }
  }

  function showTermsCondModal() {
    bidspiritQuery(
      "docs/getTerms",
      {
        language: LANG
      },
      function(data) {
        let modalBody = document.getElementById(
          "modal-requestApprovalTerms-content"
        );
        if (!!modalBody) {
          modalBody.innerHTML = data;
          $("#requestApprovalTermsAction").on("click", function(event) {
            event.preventDefault();
            let $this = $(this),
              auctionInfo = bidspiritApi.getAuctionInfo(),
              data = {};
            data.sessionId = bidspiritSessionId;
            data.auctionId = auctionInfo.id;

            $this.prop("disabled", true);
            bidspiritPostQuery(
              "approvals/requestToParticipateInAuction",
              data,
              function(data) {
                if (!checkError(data)) {
                  MicroModal.close("modal-request-approval-terms");
                  approvalInfo(auctionInfo.id);
                }
              },
              function() {},
              function() {
                $this.prop("disabled", false);
              }
            );
          });

          MicroModal.show(
            "modal-request-approval-terms",
            microModalInitConfig()
          );
        }
      }
    );
  }

  function bidProcessAction(modalBidForm, params, data, dataAlert) {
    MicroModal.show("modal-bid", microModalInitConfig());
    loadTemplate(modalBidForm, "modal-bid-template", params, false, function() {
      $(modalBidForm)
        .off("click", "#agreeBid")
        .on("click", "#agreeBid", function(event) {
          event.preventDefault();

          var subData = getDataForm("subBidFormSection");

          if (subData) {
            data.sendBidEmails =
              subData.sendBidEmails !== undefined &&
              subData.sendBidEmails === "true";
            data.sendOverBidEmails =
              subData.sendOverBidEmails !== undefined &&
              subData.sendOverBidEmails === "true";
            data.callUserWhenItemIsLive =
              subData.callUserWhenItemIsLive !== undefined &&
              subData.callUserWhenItemIsLive === "true";
            bidspiritUser.sendBidEmails = data.sendBidEmails;
            bidspiritUser.sendOverBidEmails = data.sendOverBidEmails;
          }

          bidspiritQuery("items/placeBid", data, function(data) {
            if (!checkError(data)) {
              var response = data.response;
              noticeSwall(
                "info",
                getLeadingBidMessage(response.leadingBidCode)
              );
              bidspiritQuery("items/setItemAlert", dataAlert, function() {});
              updateDisplay();
              data.response.data = {
                auctionId: dataAlert.auctionId,
                lotIndex: dataAlert.lotIndex,
                user: bidspiritUser.email
              };
              hangUpEvent("bp:after-items-place-bid", data.response);
            }
            MicroModal.close("modal-bid");
          });
        });
      $(modalBidForm)
        .off("click", "#dontAgreeBid")
        .on("click", "#dontAgreeBid", function(event) {
          event.preventDefault();
          MicroModal.close("modal-bid");
        });
    });
  }

  function submitBidCatalog3(lot, minBidPrice, itemInfoData) {
    var singleLot = lot,
      notApproveStateNotice = window.bs_lang.not_approved_user,
      pendingStateNotice = window.bs_lang.pending_user_state;
    currentItemInfo =
      itemInfoData.response.itemsInfo[singleLot.attr("data-lot-index")];
    currentItemInfo.buyoutPrice = minBidPrice;
    MicroModal.init(microModalInitConfig());

    if (!bidspiritUser) {
      try {
        MicroModal.show("modal-login", microModalInitConfig());
      } catch (e) {
        console.error(e);
      }
    } else if (bidspiritUser.approvalState === "PENDING") {
      noticeSwall("error", window.bs_lang.oops, pendingStateNotice);
    } else if (bidspiritUser.approvalState === "INCOMPLETE_PROFILE") {
      noticeSwall("error", window.bs_lang.oops, notApproveStateNotice);
    } else {
      var data = getDataForm("bidFormSection"),
        modalBidForm = "#modal-bid-content",
        lotName = lot
          .find(".bp-lot__title a")
          .text()
          .replace(/Lot\s\d+\:/, ""),
        lotLinkTerm = window.bs_data.page_terms,
        additionalNotice = false,
        additionalNoticeText = "",
        auctionInfo = bidspiritApi.getAuctionInfo();
      var fullPriceVat = Boolean(
          parseInt(singleLot.attr("data-full-price-vat"))
        ),
        auctionCommission = auctionInfo.commission;
      data.sessionId = bidspiritSessionId;
      data.auctionId = currentAuctionNumber;
      data.lotIndex = currentItemInfo.lotIndex;
      data.bidFormUrl = singleLot.find("a").attr("href");
      data.sendBidEmails = false;
      data.sendOverBidEmails = false;

      if (parseInt(data.price) >= currentItemInfo.buyoutPrice) {
        additionalNotice = true;
        additionalNoticeText = window.bs_lang.buyout_notice.replace(
          /#price#/,
          formattedPrice(currentItemInfo.buyoutPrice, currencySymbol)
        );
      }

      if (data.price === undefined) {
        data.price = minBidPrice;
      }

      MicroModal.show("modal-bid", microModalInitConfig());
      var params = {
        index: data.lotIndex,
        name: lotName,
        currentCurrency: currencySymbol,
        price: data.price,
        fullPrice: getCommissionPrice(
          data.price,
          fullPriceVat,
          auctionCommission
        ),
        linkTerms: lotLinkTerm,
        additionalNotice: additionalNotice,
        additionalNoticeText: additionalNoticeText,
        auctionHouseData: auctionHouseData,
        fullPriceVat: fullPriceVat,
        auctionCommission: auctionCommission,
        user: bidspiritUser,
        itemInfo: currentItemInfo,
        settings: auctionSettingsData,
        additionalMessage: autoChargingCreditCardMessage(auctionSettingsData)
      };
      loadTemplate(
        modalBidForm,
        "modal-bid-template",
        params,
        false,
        function() {
          $(modalBidForm)
            .off("click", "#agreeBid")
            .on("click", "#agreeBid", function(event) {
              event.preventDefault();
              var bsOptions = window.bs_data,
                taxNumberNotRequired =
                  bsOptions.tax_number_required !== undefined &&
                  bsOptions.tax_number_required === "off";

              function userGate(bidspiritUser) {
                if (
                  bidspiritUser.taxNumber !== undefined &&
                  bidspiritUser.taxNumber !== ""
                ) {
                  return true;
                }

                return false;
              }

              var subData = getDataForm("subBidFormSection");

              if (subData) {
                data.sendBidEmails =
                  subData.sendBidEmails !== undefined &&
                  subData.sendBidEmails === "true";
                data.sendOverBidEmails =
                  subData.sendOverBidEmails !== undefined &&
                  subData.sendOverBidEmails === "true";
                data.callUserWhenItemIsLive =
                  subData.callUserWhenItemIsLive !== undefined &&
                  subData.callUserWhenItemIsLive === "true";
                bidspiritUser.sendBidEmails = data.sendBidEmails;
                bidspiritUser.sendOverBidEmails = data.sendOverBidEmails;
              }

              if (taxNumberNotRequired || userGate(bidspiritUser)) {
                var dataAlert = {
                  sessionId: data.sessionId,
                  auctionId: data.auctionId,
                  lotIndex: data.lotIndex,
                  isOn: true
                };
                bidspiritQuery("items/placeBid", data, function(data) {
                  var auctionApprovalState = bidspiritApi.getAuctionApprovalState();

                  if (
                    auctionApprovalState !== null &&
                    auctionApprovalState === "NOT_REQUESTED"
                  ) {
                    modalRequestApprovalShow();
                    MicroModal.init(microModalInitConfig());
                  } else {
                    if (!checkError(data)) {
                      var data = data.response;
                      noticeSwall(
                        "info",
                        getLeadingBidMessage(data.leadingBidCode)
                      );
                      bidspiritQuery(
                        "items/setItemAlert",
                        dataAlert,
                        function() {}
                      );
                      updateDisplay();
                    }
                  }
                });
                MicroModal.close("modal-bid");
              } else {
                MicroModal.close("modal-bid");
                noticeSwall(
                  "error",
                  window.bs_lang.tax_number_required,
                  window.bs_lang.tax_number_required_label,
                  {},
                  function() {
                    var linkProfile = window.bs_data.link_profile;

                    if (linkProfile !== undefined && linkProfile !== "link") {
                      window.location = linkProfile;
                    }
                  }
                );
              }
            });
          $(modalBidForm)
            .off("click", "#dontAgreeBid")
            .on("click", "#dontAgreeBid", function(event) {
              event.preventDefault();
              MicroModal.close("modal-bid");
            });
        }
      );
    }
  }

  function submitBidCatalog(lot, minBidPrice, itemInfoData) {
    var singleLot = lot,
      notApproveStateNotice = window.bs_lang.not_approved_user,
      pendingStateNotice = window.bs_lang.pending_user_state;
    currentItemInfo =
      itemInfoData.response.itemsInfo[singleLot.attr("data-lot-index")];
    currentItemInfo.buyoutPrice = minBidPrice;
    MicroModal.init(microModalInitConfig());

    if (!bidspiritUser) {
      try {
        MicroModal.show("modal-login", microModalInitConfig());
      } catch (e) {
        console.error(e);
      }
    } else if (bidspiritUser.approvalState === "PENDING") {
      noticeSwall("error", window.bs_lang.oops, pendingStateNotice);
    } else if (bidspiritUser.approvalState === "INCOMPLETE_PROFILE") {
      noticeSwall("error", window.bs_lang.oops, notApproveStateNotice);
    } else {
      var data = getDataForm("bidFormSection"),
        modalBidForm = "#modal-bid-content",
        lotName = lot
          .find(".bp-lot__title a")
          .text()
          .replace(/Lot\s\d+\:/, ""),
        lotLinkTerm = window.bs_data.page_terms,
        additionalNotice = false,
        additionalNoticeText = "",
        auctionInfo = bidspiritApi.getAuctionInfo();
      var fullPriceVat = Boolean(parseInt(lot.attr("data-full-price-vat"))),
        auctionCommission = auctionInfo.commission;
      data.sessionId = bidspiritSessionId;
      data.auctionId = currentAuctionNumber;
      data.lotIndex = currentItemInfo.lotIndex;
      data.bidFormUrl = lot.find("a").attr("href");
      data.sendBidEmails = false;
      data.sendOverBidEmails = false;

      if (parseInt(data.price) >= currentItemInfo.buyoutPrice) {
        additionalNotice = true;
        additionalNoticeText = window.bs_lang.buyout_notice.replace(
          /#price#/,
          formattedPrice(currentItemInfo.buyoutPrice, currencySymbol)
        );
      }

      if (data.price === undefined) {
        data.price = minBidPrice;
      }

      var params = {
        index: data.lotIndex,
        name: lotName,
        currentCurrency: currencySymbol,
        price: data.price,
        fullPrice: getCommissionPrice(
          data.price,
          fullPriceVat,
          auctionCommission
        ),
        linkTerms: lotLinkTerm,
        additionalNotice: additionalNotice,
        additionalNoticeText: additionalNoticeText,
        auctionHouseData: auctionHouseData,
        fullPriceVat: fullPriceVat,
        auctionCommission: auctionCommission,
        user: bidspiritUser,
        itemInfo: currentItemInfo,
        settings: auctionSettingsData,
        additionalMessage: autoChargingCreditCardMessage(auctionSettingsData)
      };

      function userGate(bidspiritUser) {
        if (
          bidspiritUser.taxNumber !== undefined &&
          bidspiritUser.taxNumber !== ""
        ) {
          return true;
        }

        return false;
      }

      var bsOptions = window.bs_data,
        taxNumberNotRequired =
          bsOptions.tax_number_required !== undefined &&
          bsOptions.tax_number_required === "off";

      if (taxNumberNotRequired || userGate(bidspiritUser)) {
        var auctionApprovalState = bidspiritApi.getAuctionApprovalState();
        var dataAlert = {
          sessionId: data.sessionId,
          auctionId: data.auctionId,
          lotIndex: data.lotIndex,
          isOn: true
        };

        var auctionInfo = bidspiritApi.getAuctionInfo();
        if (
          auctionInfo.approvalRequired !== undefined &&
          auctionInfo.approvalRequired
        ) {
          if (
            auctionInfo.paymentMethodRequired !== undefined &&
            auctionInfo.paymentMethodRequired === true
          ) {
            if (bidspiritApi.getAuctionApprovalState() === "APPROVED") {
              bidProcessAction(modalBidForm, params, data, dataAlert);
            } else if (
              bidspiritApi.getAuctionApprovalState() === "NOT_REQUESTED"
            ) {
              if (paymentMethods.length > 0) {
                modalRequestApprovalShow();
                MicroModal.init(microModalInitConfig());
              } else {
                addPaymentMethodCallback();
              }
            } else if (
              bidspiritApi.getAuctionApprovalState() === "APPROVAL_REQUESTED"
            ) {
              noticeSwall(
                "info",
                "",
                window.bs_lang.approval_info_approval_requested
              );
            } else {
              if (bidspiritApi.getAuctionApprovalState() === "PENDING") {
                noticeSwall(
                  "error",
                  window.bs_lang.oops,
                  window.bs_lang.pending_user_state
                );
              } else if (
                bidspiritApi.getAuctionApprovalState() === "INCOMPLETE_PROFILE"
              ) {
                noticeSwall(
                  "error",
                  window.bs_lang.oops,
                  window.bs_lang.not_approved_user
                );
              }
            }
          } else if (
            auctionInfo.paymentMethodRequired !== undefined &&
            auctionInfo.paymentMethodRequired === false
          ) {
            if (bidspiritApi.getAuctionApprovalState() === "APPROVED") {
              bidProcessAction(modalBidForm, params, data, dataAlert);
            } else if (
              bidspiritApi.getAuctionApprovalState() === "NOT_REQUESTED"
            ) {
              showTermsCondModal();
            } else if (
              bidspiritApi.getAuctionApprovalState() === "APPROVAL_REQUESTED"
            ) {
              noticeSwall(
                "info",
                "",
                window.bs_lang.approval_info_approval_requested
              );
            } else {
              if (bidspiritApi.getAuctionApprovalState() === "PENDING") {
                noticeSwall(
                  "error",
                  window.bs_lang.oops,
                  window.bs_lang.pending_user_state
                );
              } else if (
                bidspiritApi.getAuctionApprovalState() === "INCOMPLETE_PROFILE"
              ) {
                noticeSwall(
                  "error",
                  window.bs_lang.oops,
                  window.bs_lang.not_approved_user
                );
              }
            }
          } else {
            bidProcessAction(modalBidForm, params, data, dataAlert);
          }

          MicroModal.init(microModalInitConfig());
        } else {
          bidProcessAction(modalBidForm, params, data, dataAlert);
        }
      } else {
        MicroModal.close("modal-bid");
        noticeSwall(
          "error",
          window.bs_lang.tax_number_required,
          window.bs_lang.tax_number_required_label,
          {},
          function() {
            var linkProfile = window.bs_data.link_profile;

            if (linkProfile !== undefined && linkProfile !== "link") {
              window.location = linkProfile;
            }
          }
        );
      }
    }
  }

  function getApprovalStateInfo(user) {
    var userState = $("#profile-account-section");

    if (!user.emailConfirmed) {
      return userState.attr("data-confirm-email");
    }

    switch (user.approvalState) {
      case "INCOMPLETE_PROFILE":
        return userState.attr("data-incomplete-profile");

      case "PENDING":
        return userState.attr("data-pending");
    }

    return "";
  }

  function submitUpdateDetails() {
    function filterData(data) {
      let updatedData = { data: {}, errors: {} };

      if (data.countryCode !== undefined && data.countryCode === "US") {
        data.stateCode = data.state;
        data.state = "";
        data.province = "";
      } else {
        data.stateCode = "";
      }

      for (const [key, value] of Object.entries(data)) {
        console.log(key, value);
        if (key === "") {
          continue;
        }

        if (key === "firstName" || key === "lastName") {
          console.log(value.match(/\@/));
          if (value.match(/\@/)) {
            updatedData["errors"][
              key
            ] = window.bs_lang.profile_field_error.replace(/\%s/, key);
          }
        }
        updatedData["data"][key] = value;
      }
      return updatedData;
    }

    var data = getDataForm("updateDetailsSection"),
      formParent = $("#updateDetailsSection"),
      approvalState = bidspiritUser.approvalState,
      postConfirmationLink = formParent.attr("action");
    data.sessionId = bidspiritSessionId;
    data.postConfirmationLink = postConfirmationLink;

    let tmpData = filterData(data);
    data = tmpData["data"];

    if (Object.keys(tmpData["errors"]).length > 0) {
      let keys = Object.keys(tmpData["errors"]),
        message = window.bs_lang.profile_error;
      if (keys[0] !== undefined) {
        message = tmpData["errors"][keys[0]];
      }
      noticeSwall("error", "Error", message);
    } else {
      if (approvalState === "PENDING") {
        var info = bidspiritApi.getAuctionHouseData(),
          title = window.bs_lang.you_are_still_pending_approval.replace(
            /\%1s/,
            info.name
          ),
          message = window.bs_lang.you_are_still_pending_approval_body
            .replace(/\%1s/, info.phone)
            .replace(/\%2s/, info.email);
        noticeSwall("info", title, message);
      } else {
        bidspiritPostQuery("users/updateDetails", data, function(data) {
          console.log(data);
          if (data.response.success === false) {
            noticeSwall("error", "Error", data.response.errorMessage);
          } else {
            bidspiritApi.setBidspiritUser(data.response);
            updateDisplay();
            noticeSwall(
              "info",
              window.bs_lang.profile_changes_saved,
              window.bs_lang.profile_changes_saved_body,
              {},
              function() {
                if (approvalState !== bidspiritUser.approvalState) {
                  window.location = postConfirmationLink;
                }
              }
            );
          }
        });
      }
    }
  }

  function handleSubmitResponse(data) {
    currentItemInfo.selfAbsenteeBid = data.selfAbsenteeBid;
    currentItemInfo.leadingBid = data.leadingBid;
    displayBidFormData(currentItemInfo);
    noticeSwall("info", getLeadingBidMessage(data.leadingBidCode));
  }

  function disableLoader() {
    $("#bsLoader").addClass(window.bs_data.hidden_class);
  }

  function toggleFavorite(lot, elem, auctionNumber, delLot) {
    var lotIndex = lot.attr("data-lot-index"),
      wishListClass = "bp__wishlist-active",
      isFavorite = !$(elem).hasClass(wishListClass);

    if (!bidspiritUser) {
      try {
        MicroModal.show("modal-login", microModalInitConfig());
      } catch (e) {
        console.error(e);
      }
    } else {
      bidspiritQuery(
        "items/setFavorite",
        {
          sessionId: bidspiritSessionId,
          auctionId: auctionNumber,
          lotIndex: lotIndex,
          isFavorite: isFavorite
        },
        function(data) {
          if (!checkError(data)) {
            if (data.response.success) {
              if (isFavorite) {
                $(elem).addClass(wishListClass);
              } else {
                $(elem).removeClass(wishListClass);

                if (delLot) {
                  lot.remove();
                }
              }
            }
          }
        }
      );
    }
  }

  function getLeadingBidMessage(leadingBidCode) {
    var response = "";
    switch (leadingBidCode) {
      case "YOU_ARE_THE_HIGH_BIDDER":
        response = window.bs_lang.success_high_bidder;
        break;

      case "ANOTHER_BID_HIGHER":
        response = window.bs_lang.higher_your_bid_has_been_outbid;
        break;

      case "ANOTHER_BID_EARLIER":
        response = window.bs_lang.earlier_your_bid_has_been_outbid;
        break;

      case "SYNC_ERROR":
        response = window.bs_lang.sync_error;
        break;
    }

    return response;
  }

  function tabs() {
    $(".tools-wrapper").on("click", ".bp-tabs-link a", function(event) {
      event.preventDefault();
      var $this = $(this),
        parent = $this.parents(".bp-tabs-block"),
        idTab = parent.attr("data-tab-id"),
        href = $this.attr("href");
      window.location.href =
        window.location.origin + window.location.pathname + href;

      if ($(href).length) {
        parent.find(".nav-link").removeClass("active");
        $("#" + idTab + " > *").removeClass("active");
        $this.addClass("active");
        $(href).addClass("active");
      }
    });
  }

  function activeTabs() {
    var activeTab = $('.bp-tabs-block a[href="' + window.location.hash + '"]');

    if (activeTab.length) {
      activeTab.trigger("click");
    }
  }

  function spoiler() {
    $(document).on("click", ".bp-spoiler-trigger", function(e) {
      e.preventDefault();
      $(this).toggleClass("active");
      $(this)
        .parent()
        .toggleClass("active-spoiler")
        .find(".bp-spoiler-block")
        .first()
        .toggleClass("active");
    });
  }

  function loginLink() {
    function loadLoginLink(login) {
      loadTemplate(
        ".wrpLoginLink",
        "account-link-profile",
        {
          login: login
        },
        false,
        function() {
          MicroModal.init(microModalInitConfig());
        }
      );

      if ($(".wrpRegisterLink").length) {
        loadTemplate(
          ".wrpRegisterLink",
          "account-link-register",
          {
            login: login
          },
          false,
          function() {
            MicroModal.init(microModalInitConfig());
          }
        );
      }
    }

    var loginLink = $(".bp-login-link"),
      menu = loginLink.parents(".menu");

    if (loginLink.length && bidspiritUser) {
      loadLoginLink(true);

      if (menu !== undefined) {
        menu.addClass("user-is-authorize");
        menu.removeClass("user-is-not-authorize");
      }
    } else if (!bidspiritUser) {
      loadLoginLink(false);

      if (menu !== undefined) {
        menu.removeClass("user-is-authorize");
        menu.addClass("user-is-not-authorize");
      }
    }
  }

  function resendEmailAction() {
    var resendEmailSection = $("#resendEmailSection");

    if (resendEmailSection.length) {
      resendEmailSection.on("click", function(event) {
        event.preventDefault();
        bidspiritQuery(
          "users/resendConfirmationMail",
          {
            sessionId: bidspiritSessionId,
            postConfirmationLink: window.location.href
          },
          function(data) {
            if (!bPcheckError(data)) {
              if (data.response.success) {
                noticeSwall("success", "Email confirmation sent");
              } else {
                noticeSwall("error", "Unknown error");
              }
            }
          }
        );
      });
    }
  }

  function saveFirebaseUser() {
    try {
      var firebaseTokenFCM = localStorage.getItem("token_firebase_push_id");
    } catch (e) {
      firebaseTokenFCM = null;
    }

    if (firebaseTokenFCM !== null) {
      if (
        bidspiritUser.leadingBidAlertsEnabled !== undefined &&
        bidspiritUser.leadingBidAlertsEnabled !== true
      ) {
        bidspiritQuery(
          "users/setLeadingBidAlertsEnabled",
          {
            sessionId: bidspiritSessionId,
            isEnabled: true
          },
          function(data) {
            if (!checkError(data)) {
            }
          }
        );
      }

      restQuery(
        "user/login",
        "POST",
        {
          bidspirit_user_email: bidspiritUser.email,
          firebase_id: firebaseTokenFCM
        },
        function(response) {
          console.info(response);
        }
      );
    }
  }

  function widgetSliders() {
    new SwiperBP(".widget-lots", {
      speed: 400,
      slidesPerView: 1,
      spaceBetween: 10,
      centeredSlides: true,
      freeMode: false,
      autoplay: {
        delay: 4000
      },
      breakpoints: {
        977: {
          slidesPerView: 3,
          spaceBetween: 15
        },
        1200: {
          slidesPerView: 5,
          spaceBetween: 30,
          centeredSlides: false
        }
      }
    });
  }

  function updateLotsWidget() {
    if ($(".bt-wi-lots_wrp").length) {
      var widgets = $(".bt-wi-lots");
      widgets.each(function(index, widget) {
        var lots = $(widget).find(".bp-lot"),
          hash = $(widget).attr("data-hash"),
          auctions = {};

        if (hash === undefined) {
          hash = "";
        }

        lots.each(function(index, elem) {
          var $this = $(elem),
            auctionId = $this.attr("data-auction-id"),
            lotId = $this.attr("data-lot-index");

          if (auctions[auctionId] === undefined && auctionId !== "") {
            auctions[auctionId] = [];
          }
          if (lotId !== "") {
            auctions[auctionId].push(lotId);
          }
        });
        $.each(auctions, function(index, items) {
          if (items.length > 0 && index !== "undefined") {
            bidspiritQuery(
              "items/getItemsInfo",
              {
                sessionId: bidspiritSessionId,
                auctionId: index,
                lotIndexes: items.join(",")
              },
              function(data) {
                if (!checkError(data)) {
                  var bidsInfoData = data.response;

                  if (
                    bidsInfoData.itemsInfo !== undefined &&
                    items.length > 0
                  ) {
                    for (var i = 0; i < items.length; i++) {
                      var itemIndex = items[i],
                        itemRow = $(
                          "#single-lot-" + index + "-" + itemIndex + hash
                        );

                      if (bidsInfoData.itemsInfo[itemIndex] !== undefined) {
                        var itemInfo = bidsInfoData.itemsInfo[itemIndex];
                      }

                      var content = "";

                      try {
                        var dataContent = itemRow.attr("data-content");

                        if (dataContent !== undefined) {
                          content = JSON.parse(
                            urldecode(itemRow.attr("data-content"))
                          );
                        }
                      } catch (e) {
                        console.error("error parse content of lot");
                      }

                      loadTemplate(
                        "#single-lot-" +
                          index +
                          "-" +
                          itemIndex +
                          hash +
                          "-content",
                        "lot-content-template",
                        {
                          auctionInfo: bidsInfoData,
                          auctionData: bidspiritApi.getAuctionInfo(),
                          itemInfo: itemInfo,
                          title: itemRow.find(".bp-lot__title").html(),
                          link: itemRow.find(".img-block").attr("href"),
                          content: content,
                          currency: currencySymbol,
                          hiddenPrice: false,
                          showEstimatedPriceInItemsList: false,
                          displayStartPriceInCatalog: false,
                          postAuctionSaleOpenedUntil: false,
                          bidspiritUser: undefined,
                          bidsInCatalog: false,
                          houseInfo: bidspiritApi.getAuctionHouseData()
                        },
                        true,
                        function() {
                          if (itemInfo !== undefined) {
                            hangUpEvent(
                              "bp:after-getItemsInfo-content-item",
                              itemInfo,
                              itemRow
                            );
                          }
                        }
                      );
                    }

                    hangUpEvent("bp:after-getItemsInfo-item", bidsInfoData);
                  }
                }
              }
            );
          }
        });
      });
    }
  }

  function onPageAction() {
    function auctionAlertAction() {
      $("body").on("click", ".auction-follow-action", function(event) {
        event.preventDefault();
        var $this = $(event.target),
          auctionId = $this.attr("data-auction-id");
        bidspiritQuery(
          "auctions/setAuctionAlert",
          {
            sessionId: bidspiritSessionId,
            auctionId: auctionId,
            isOn: true
          },
          function(data) {
            if (data.response.success) {
              noticeSwall("success", "Success", "");
            } else {
              noticeSwall("error", window.bs_lang.oops);
            }
          }
        );
      });
    }

    auctionAlertAction();
  }

  document.addEventListener("DOMContentLoaded", function(event) {
    try {
      if (!bpIsset(window.localStorage)) {
        noticeSwall("error", window.bs_lang.storage_not_working);
      }
    } catch (e) {
      noticeSwall("error", window.bs_lang.storage_not_working);
    }

    initApp();
    init();
    var loginForm = $(".bp-login-api"),
      bidForm = $("#bidFormSection"),
      loginModal = $("#modal-login"),
      registerModal = $("#modal-register"),
      registerForm = $(".bp-register-api"),
      logoutAction = $("#doLogout"),
      forgottenAction = $(".doForgotten"),
      wishListButtons = $(".bp-lot .bp__wishlist"),
      errorBlockSelector = ".errors-group";

    if (loginForm.length) {
      loginForm.on("submit", function(event) {
        event.preventDefault();
        submitLogin(event);
      });
    }

    if (forgottenAction.length) {
      forgottenAction.each(function(index, elem) {
        var $this = $(elem),
          formParent = $(".bp-login-api");
        $this.on("click", function(event) {
          event.preventDefault();
          bidspiritPostQuery(
            "users/sendPasswordReset",
            {
              sessionId: bidspiritSessionId,
              email: formParent.find("[name='email']").val(),
              language: LANG,
              postResetPage: window.location.href
            },
            function(data) {
              if (!checkError(data)) {
                if (data.response.success) {
                  noticeSwall("info", window.bs_lang.profile_password_reset);
                } else {
                  noticeSwall("error", window.bs_lang.profile_email_not_found);
                }
              }
            }
          );
        });
      });
    }

    if (registerForm.length) {
      registerForm.each(function(index, elem) {
        $(elem).on("submit", function(event) {
          var $this = $(event.target),
            acceptPrivacy = $this.attr("data-accept-privacy");
          event.preventDefault();
          var errorBlock = $this.find(errorBlockSelector),
            checkboxPersonalData = $(event.target).find(
              '[name="personal-data"]'
            );

          if (errorBlock === undefined) {
            errorBlock = registerModal.find(errorBlockSelector);
          }

          errorBlock.empty();

          if (acceptPrivacy === "on") {
            if (
              checkboxPersonalData.length &&
              checkboxPersonalData.is(":checked")
            ) {
              submitRegister(event);
            } else {
              var error = window.bs_lang["notice_personal_data"];
              errorBlock
                .empty()
                .append("<p>" + error + "</p>")
                .removeClass(window.bs_data.hidden_class);
            }
          } else {
            submitRegister(event);
          }
        });
      });
    }

    if (bidForm.length) {
      bidForm.unbind("submit");
      bidForm.on("submit", function(event) {
        event.preventDefault();

        if (!bidspiritUser) {
          try {
            MicroModal.show("modal-login", microModalInitConfig());
          } catch (e) {
            console.error(e);
          }

          return;
        }

        var auctionInfo = bidspiritApi.getAuctionInfo();
        if (auctionInfo.state !== "ENDED") {
          if (
            auctionInfo.approvalRequired !== undefined &&
            auctionInfo.approvalRequired
          ) {
            if (
              auctionInfo.paymentMethodRequired !== undefined &&
              auctionInfo.paymentMethodRequired === true
            ) {
              if (bidspiritApi.getAuctionApprovalState() === "APPROVED") {
                submitBid();
              } else if (
                bidspiritApi.getAuctionApprovalState() === "NOT_REQUESTED"
              ) {
                if (paymentMethods.length > 0) {
                  modalRequestApprovalShow();
                  MicroModal.init(microModalInitConfig());
                } else {
                  addPaymentMethodCallback();
                }
              } else if (
                bidspiritApi.getAuctionApprovalState() === "APPROVAL_REQUESTED"
              ) {
                noticeSwall(
                  "info",
                  "",
                  window.bs_lang.approval_info_approval_requested
                );
              } else {
                if (bidspiritApi.getAuctionApprovalState() === "PENDING") {
                  noticeSwall(
                    "error",
                    window.bs_lang.oops,
                    window.bs_lang.pending_user_state
                  );
                } else if (
                  bidspiritApi.getAuctionApprovalState() ===
                  "INCOMPLETE_PROFILE"
                ) {
                  noticeSwall(
                    "error",
                    window.bs_lang.oops,
                    window.bs_lang.not_approved_user
                  );
                }
              }
            } else if (
              auctionInfo.paymentMethodRequired !== undefined &&
              auctionInfo.paymentMethodRequired === false
            ) {
              if (bidspiritApi.getAuctionApprovalState() === "APPROVED") {
                submitBid();
              } else if (
                bidspiritApi.getAuctionApprovalState() === "NOT_REQUESTED"
              ) {
                showTermsCondModal();
              } else if (
                bidspiritApi.getAuctionApprovalState() === "APPROVAL_REQUESTED"
              ) {
                noticeSwall(
                  "info",
                  "",
                  window.bs_lang.approval_info_approval_requested
                );
              } else {
                if (bidspiritApi.getAuctionApprovalState() === "PENDING") {
                  noticeSwall(
                    "error",
                    window.bs_lang.oops,
                    window.bs_lang.pending_user_state
                  );
                } else if (
                  bidspiritApi.getAuctionApprovalState() ===
                  "INCOMPLETE_PROFILE"
                ) {
                  noticeSwall(
                    "error",
                    window.bs_lang.oops,
                    window.bs_lang.not_approved_user
                  );
                }
              }
            } else {
              submitBid();
            }

            MicroModal.init(microModalInitConfig());
          } else {
            submitBid();
          }
        }
      });
    }

    if (logoutAction.length) {
      doLogout(logoutAction);
    }

    if (loginModal.length) {
      loginModal.on("click", "#doRegister", function(event) {
        event.preventDefault();
        MicroModal.close("modal-login");
        MicroModal.init(microModalInitConfig());
        MicroModal.show("modal-register");
      });
    }

    if (registerModal.length) {
      registerModal.on("click", "#doLogin", function(event) {
        event.preventDefault();
        MicroModal.close("modal-register");
        MicroModal.init(microModalInitConfig());
        MicroModal.show("modal-login", microModalInitConfig());
      });
    }

    $("#single-lot, #catalog-section").on("click", wishListButtons, function(
      event
    ) {
      var elem = event.target,
        lot = $(elem).parents(".bp-lot");

      if ($(elem).hasClass("bp__wishlist")) {
        event.stopPropagation();
        event.preventDefault();
        toggleFavorite(lot, elem, currentAuctionNumber);
      }
    });
    $("body").on("click", ".modal-open", function(event) {
      var $this = $(this),
        target = $this.attr("data-micromodal-trigger"),
        parentModal = $this.parents(".bp-modal");

      if (parentModal.length) {
        MicroModal.close(parentModal.attr("id"));
      }

      MicroModal.show(target, microModalInitConfig());
    });
    $("body").on("click", ".click-action", function(event) {
      var $this = $(this),
        target = $this.attr("data-trigger"),
        parentModal = $this.parents(".bp-modal");

      if (parentModal.length) {
        MicroModal.close(parentModal.attr("id"));
      }

      $("#" + target).trigger("click");
    });

    function loadMore() {
      var loadMoreButton = $(".bt-wi-lots_more .btn"),
        bgColor = $(".bt-wi-lots_wrp").attr("data-bg-color");

      if (loadMoreButton.length) {
        loadMoreButton.on("click", function(event) {
          event.preventDefault();
          var $this = $(this),
            parent = $this.parents(".bt-wi-lots_wrp"),
            count = parent.find(".bp-lots .bp-lot").length;
          $.ajax({
            type: "post",
            dataType: "json",
            url: window.wp_data.ajax_url,
            data: {
              action: "do_lot_list",
              security: window.wp_nonce,
              count: count
            }
          })
            .done(function(response) {
              loadTemplate(
                parent.find(".bp-lots"),
                "shortcode-lot",
                {
                  lots: response.data.lots,
                  currency: currencySymbol,
                  bgColor: bgColor
                },
                false,
                function() {},
                true
              );
              count = parent.find(".bp-lots .bp-lot").length;

              if (count >= response.data.total) {
                parent
                  .find(".bt-wi-lots_more")
                  .addClass(window.bs_data.hidden_class);
              }
            })
            .fail(function() {
              console.error("Fatal error");
            });
        });
      }
    }

    function printNoticeBanner() {
      var htmlTemplate = document.getElementById("oldest-browser-template")
          .innerHTML,
        data = {
          message: window.bs_lang.oldest_browser_text,
          linkMessage: window.bs_lang.oldest_browser_link_text,
          link: window.bs_data.link_on_not_supported_browsers
        };
      htmlTemplate = _.template(htmlTemplate);
      $("body").append(htmlTemplate(data));
    }

    function ie11supportDisabled() {
      if (auctionforgeDetectIE()) {
        printNoticeBanner();
      }
    }

    function incrementTable() {
      $("#incrementTable, [href='#incrementTable']").on("click", function(
        event
      ) {
        bidspiritQuery(
          "items/getIncrementsSteps",
          {
            sessionId: bidspiritSessionId
          },
          function(data) {
            MicroModal.show("modal-steps", microModalInitConfig());
            loadTemplate(
              "#modal-steps-content",
              "increment-tables-template",
              {
                data: data.response,
                currency: currencySymbol
              },
              true
            );
          }
        );
      });
    }

    galleryInitial();
    tabs();
    spoiler();
    select2ToolsInit();
    loadMore();
    updateLotsWidget();
    updateWidgetLots();
    widgetSliders();
    onPageAction();
    incrementTable();
    ie11supportDisabled();
  });
})(jQuery);

function noticeSwall(type, title, message, params, callback) {
  if (params === undefined) {
    params = {};
  }

  var conf = {
    icon: type,
    title: title,
    text: message
  };
  conf = jQuery.extend({}, conf, params);
  Swal.fire(conf).then(function(result) {
    if (result.isConfirmed && callback !== undefined) {
      callback();
    }
  });
}

function getLeftDate(eventDate) {
  var outputDays = jQuery("#auctionStartTimer .outputDays"),
    outputHours = jQuery("#auctionStartTimer .outputHours"),
    nowDate = new Date(),
    archiveDate = timeShift(new Date(eventDate)),
    result = archiveDate.getTime() - nowDate.getTime() + 1000,
    hours = Math.floor((result / 1000 / 60 / 60) % 24),
    days = Math.floor(result / 1000 / 60 / 60 / 24);

  if (result < 0) {
    jQuery("#auctionStartTimer").hide();
  } else {
    outputDays.text(days);
    outputHours.text(hours);
  }
}

function smartCut(text, limit) {
  if (text === undefined) {
    return "";
  }

  text = text.replace(/<\/?[^>]+(>|$)/g, "");
  var array = text.split(" ").slice(0, limit);
  return array.join(" ");
}

function microModalInitConfig() {
  return {
    onShow: modal => {
      console.log(modal);
    },
    onClose: modal => {
      console.log(modal);
    },
    debugMode: false
  };
}

function formattedPrice(price, currencySymbol) {
  if (currencySymbol === undefined) {
    currencySymbol = window.bidSpiritCurrency;
  }

  try {
    if (price === undefined) {
      price = 0;
    }

    price = price.toLocaleString();

    switch (window.bidSpiritLang) {
      case "ru":
        return price.replace(/(\,)/, " ") + " " + currencySymbol;

      default:
        return currencySymbol + price;
    }
  } catch (e) {
    return currencySymbol + price;
  }
}

function auctionforgeDetectIE() {
  var ua = window.navigator.userAgent;
  var msie = ua.indexOf("MSIE ");

  if (msie > 0) {
    // IE 10 or older => return version number
    return true;
  }

  var trident = ua.indexOf("Trident/");

  if (trident > 0) {
    // IE 11 => return version number
    return true;
  }

  var edge = ua.indexOf("Edge/");

  if (edge > 0) {
    // Edge (IE 12+) => return version number
    return false;
  }

  return false;
}

function bp_t(phrase) {
  var key = phrase.toLowerCase().replace(/(\s)+/gm, "_");

  if (window.bs_lang[key] !== undefined) {
    return window.bs_lang[key];
  } else {
    return phrase;
  }
}

function bpGetQueryParams(qs) {
  var searchParams = new URLSearchParams(window.location.search);
  return searchParams.get(qs);
}

function bpIsset(variable) {
  return typeof variable != "undefined" && variable !== null;
}

function bpYoutubeIDParser(url) {
  var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
  var match = url.match(regExp);
  return match && match[7].length == 11 ? match[7] : false;
}

function getTimeZoneFromUser() {
  return Intl.DateTimeFormat().resolvedOptions().timeZone;
}

function convertTZ(date, tzString) {
  return new Date(
    (typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {
      timeZone: tzString
    })
  );
}

function getLocaleFromUser() {
  return Intl.DateTimeFormat().resolvedOptions().locale;
}

function timeShift(deadline, isDTS) {
  function createDateAsUTC(date) {
    return new Date(
      Date.UTC(
        date.getFullYear(),
        date.getMonth(),
        date.getDate(),
        date.getHours(),
        date.getMinutes(),
        date.getSeconds()
      )
    );
  }

  Date.prototype.addHours = function(hours) {
    var date = new Date(this.valueOf());
    date.setHours(date.getHours() + hours);
    return date;
  };

  var baseTimeZone = parseInt(window.timeZone),
    baseTimeZoneName = window.timeZoneName;

  if (bpIsset(baseTimeZoneName) && bpIsset(window.timeZoneName) !== "") {
    deadline = createDateAsUTC(
      new Date(
        new Date(deadline).toLocaleString("en-US", {
          timeZone: "UTC"
        })
      )
    );

    return deadline;
  } else {
    var timeZone = (deadline.getTimezoneOffset() / 60) * -1 - baseTimeZone;
    return new Date(deadline.getTime()).addHours(timeZone);
  }
}

(function($) {
  function metaSlider() {
    if ($(".bt-wi-slider .swiper-container").length) {
      new SwiperBP(".bt-wi-slider .swiper-container", {
        slidesPerView: 1,
        breakpoints: {
          320: {
            slidesPerView: 2
          },
          640: {
            slidesPerView: 3,
            spaceBetween: 10
          },
          990: {
            slidesPerView: 4,
            spaceBetween: 15
          },
          1200: {
            slidesPerView: 5,
            spaceBetween: 20
          }
        },
        autoplay: {
          delay: 4000
        }
      });
    }
  }

  function inquiryLot() {
    function fillFiled(inquiryField) {
      inquiryField.each(function(index, elem) {
        var qParam = "";
        qParam = bpGetQueryParams("bp-inquiry");
        $(elem).val(qParam);
      });
    }

    var inquiryField = $(".inquiry-target-field"),
      defaultFields = $(
        ".elementor-form .elementor-field-type-textarea textarea, .wpcf7-form .wpcf7-textarea"
      );

    if (inquiryField.length) {
      fillFiled(inquiryField);
    } else if (defaultFields.length) {
      fillFiled(defaultFields);
    }
  }

  function fallbackCopyTextToClipboard(text) {
    var textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.style.top = "0";
    textArea.style.left = "0";
    textArea.style.position = "fixed";
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
      var successful = document.execCommand("copy");
      var msg = successful ? "successful" : "unsuccessful";
      console.info("Fallback: Copying text command was " + msg);
    } catch (err) {
      console.error("Fallback: Oops, unable to copy", err);
    }

    document.body.removeChild(textArea);
  }

  function copyTextToClipboard(text) {
    if (!navigator.clipboard) {
      fallbackCopyTextToClipboard(text);
      return;
    }

    navigator.clipboard.writeText(text);
  }

  function shareLink() {
    var shaleLinkBtn = $(".share-btn__link[data-id=link]");

    if (shaleLinkBtn !== undefined) {
      shaleLinkBtn.on("click", function(event) {
        event.preventDefault();
        var $this = $(this);

        if ($this.hasClass("share-btn__link-active")) {
          return;
        }

        copyTextToClipboard(window.location);
        $this.html(window.bs_lang.copied).addClass("share-btn__link-active");
        return;
      });
    }
  }

  function countDown() {
    function getTimeRemaining(endtime) {
      var t = Date.parse(endtime) - Date.parse(new Date()),
        index = t <= 0 ? 0 : 1,
        seconds = Math.floor((t / 1000) % 60) * index,
        minutes = Math.floor((t / 1000 / 60) % 60) * index,
        hours = Math.floor((t / (1000 * 60 * 60)) % 24) * index,
        days = Math.floor(t / (1000 * 60 * 60 * 24)) * index;
      return {
        total: t,
        days: days,
        hours: hours,
        minutes: minutes,
        seconds: seconds
      };
    }

    function initializeClock(clock, endtime) {
      if (clock) {
        var daysSpan = clock.querySelector(".bp-days");
        var hoursSpan = clock.querySelector(".bp-hours");
        var minutesSpan = clock.querySelector(".bp-minutes");
        var secondsSpan = clock.querySelector(".bp-seconds");

        function updateClock() {
          var t = getTimeRemaining(endtime);
          daysSpan.innerHTML = t.days;
          hoursSpan.innerHTML = ("0" + t.hours).slice(-2);
          minutesSpan.innerHTML = ("0" + t.minutes).slice(-2);
          secondsSpan.innerHTML = ("0" + t.seconds).slice(-2);

          if (t.total <= 0) {
            clearInterval(timeinterval);
          }
        }

        updateClock();
        var timeinterval = setInterval(updateClock, 1000);
      }
    }

    var countdown = $(".bp-countdown");

    if (countdown.length) {
      countdown.each(function(index, count) {
        var dateTime = $(count).attr("data-time"),
          deadline = new Date(Date.parse(dateTime));
        initializeClock(count, timeShift(deadline));
      });
    }
  }

  function getAuctionCarCallback(response) {
    if (_.template !== undefined) {
      var carInfoTemplate = document.getElementById("car-info-template");

      if (!bpIsset(carInfoTemplate)) {
        return;
      }

      var html = _.template(carInfoTemplate.innerHTML),
        additionalInfoBlock = document.getElementById("additional-info-block");
      response = response.response;

      if (response.item !== undefined && response.item.carInfo !== undefined) {
        additionalInfoBlock.innerHTML = html({
          data: response.item,
          info: response.item.carInfo
        });
      }
    }
  }

  function getAuctionApertmentCallback(response) {
    if (_.template !== undefined) {
      var apartmentTemplate = document.getElementById(
        "apartment-info-template"
      );

      if (!bpIsset(apartmentTemplate)) {
        return;
      }

      var html = _.template(apartmentTemplate.innerHTML),
        additionalInfoBlock = document.getElementById("additional-info-block");

      response = response.response;

      if (
        response.item !== undefined &&
        response.item.realEstateInfo !== undefined
      ) {
        additionalInfoBlock.innerHTML = html({
          data: response.item,
          info: response.item.realEstateInfo
        });
      }
    }
  }

  function getAuctionIndustrialCallback(response) {
    if (_.template !== undefined) {
      var apartmentTemplate = document.getElementById(
        "industrial-info-template"
      );

      if (!bpIsset(apartmentTemplate)) {
        return;
      }

      var html = _.template(apartmentTemplate.innerHTML),
        additionalInfoBlock = document.getElementById("additional-info-block");

      response = response.response;

      if (
        response.item !== undefined &&
        response.item.machineInfo !== undefined
      ) {
        additionalInfoBlock.innerHTML = html({
          data: response.item,
          info: response.item.machineInfo
        });
      }
    }
  }

  function adminBarTools() {
    function adminBarToolsCallback(response) {
      $("#wp-admin-bar-bp-single-sync a").on("click", function(event) {
        event.preventDefault();
        let data = response.response.item;
        $.ajax({
          url: "/wp-json/plugin/v1/sync-lot/",
          type: "POST",
          dataType: "json",
          data: {
            item: data,
            auctionId: data.auctionId,
            itemIndex: data.itemIndex,
            language: data.lang,
            sessionId: bidspiritApi.getBidspiritSessionId()
          }
        })
          .done(function(response) {
            noticeSwall("info", window.bs_lang.lot_sync_is_queued);
            console.log(response);
          })
          .fail(function(response) {
            noticeSwall("error", window.bs_lang.not_found);
            console.log(response);
          })
          .always(function() {});
      });
    }

    if (
      document.body.classList.contains("admin-bar") &&
      document.body.classList.contains("admin-bar")
    ) {
      $(window).on("bp:get-auction-item", adminBarToolsCallback);
    }
  }

  $(document).ready(function() {
    metaSlider();
    inquiryLot();
    shareLink();
    countDown();
    adminBarTools();

    $(window).on("bp:get-auction-item", getAuctionCarCallback);
    $(window).on("bp:get-auction-item", getAuctionApertmentCallback);
    $(window).on("bp:get-auction-item", getAuctionIndustrialCallback);
  });
})(jQuery);
