/* Minification failed. Returning unminified contents.
(18,33-34): run-time error JS1195: Expected expression: >
(23,6-7): run-time error JS1195: Expected expression: )
(24,34-35): run-time error JS1195: Expected expression: )
(24,37-38): run-time error JS1195: Expected expression: >
(27,5-6): run-time error JS1002: Syntax error: }
(28,33-34): run-time error JS1004: Expected ';': {
(33,29-30): run-time error JS1195: Expected expression: >
(34,44-45): run-time error JS1195: Expected expression: )
(34,47-48): run-time error JS1195: Expected expression: >
(36,51-52): run-time error JS1195: Expected expression: >
(38,18-19): run-time error JS1195: Expected expression: )
(43,18-19): run-time error JS1195: Expected expression: )
(47,33-34): run-time error JS1197: Too many errors. The file might not be a JavaScript file: .
 */
$(document).ready(function () {
    const $textBlockele = $(".block-do-what-you-love .text-block");
    const swiperHover = new Swiper(".swiper-container", {
        effect: "creative",
        creativeEffect: {
            prev: {
                shadow: true,
                translate: ["-20%", 0, -1],
            },
            next: {
                translate: ["100%", 0, 0],
            },
        },
        slideToClickedSlide: true,
        speed: 1000,
        initialSlide: 0,
    });
    $(".sider-link").hover((e) => {
        var $ele = $(e.target);
        var index = $ele.data("index");
        $textBlockele.addClass("hovered");
        swiperHover.slideTo(index, 1000, true);
    });
    $(".sider-link").mouseleave(() => {
        $textBlockele.removeClass("hovered");
        swiperHover.slideTo(0, 1000, true);
    });
    function initImageTextTab() {
        const tabs = document.querySelectorAll(
            ".image-text-tab-component [data-tab-target]"
        );
        const tabContents = document.querySelectorAll("[data-tab-content]");
        tabs.forEach((tab) => {
            tab.addEventListener("click", () => {
                const target = document.querySelector(tab.dataset.tabTarget);
                tabContents.forEach((tabContent) => {
                    tabContent.classList.remove("active", "show");
                });
                tabs.forEach((tab) => {
                    tab.classList.remove("active");
                    tab.setAttribute("aria-expanded", false);
                    tab.setAttribute("aria-selected", false);
                });
                tab.classList.add("active");
                tab.setAttribute("aria-expanded", true);
                tab.setAttribute("aria-selected", true);
                target.classList.add("active", "show");
            });
        });
    }
    initImageTextTab();
    // Function to show the extra description for the ambassador
    $(".view-profile button.tertiary-btn").click(toggleExtraDesc);
    function toggleExtraDesc(event) {
        event.stopPropagation();
        const ele = $(event.target);
        const eleParent = $(ele).parent();
        const target = $(ele.data("target-desc"))[0];
        if (!$(eleParent).hasClass("expanded")) {
            $(eleParent).addClass("expanded");
            $(target).addClass("show");
        } else {
            $(eleParent).removeClass("expanded");
            $(target).removeClass("show");
        }
    }

    function handleAmbassadorCategoryClick(targetEle) {
        const currentTargetParent = targetEle.parent()[0],
            filterValue = $(currentTargetParent).data("category-target"),
            categoryListItems = $(".js-ambassador-list"),
            $viewProfileBtn = $(".ambassador-card .view-profile"),
            $profileDesc = $(".ambassador-card .ambassador-card__profile-desc");
        $viewProfileBtn.removeClass("expanded");
        $profileDesc.removeClass("show");
        $(currentTargetParent).addClass("active").siblings().removeClass("active");
        $(currentTargetParent)
            .attr("aria-selected", "true")
            .siblings()
            .attr("aria-selected", "false");
        if (filterValue === "all") {
            $(".js-ambassador-list").addClass("active");
        } else {
            for (let index = 0; index < categoryListItems.length; index++) {
                const linkedCategory = $(categoryListItems[index])
                    .data("category-content")
                    .split(" ");
                if (linkedCategory.indexOf(filterValue) > -1) {
                    $(categoryListItems[index]).addClass("active");
                } else {
                    $(categoryListItems[index]).removeClass("active");
                }
            }
        }
    }

    function removeBorderForAmbassador() {
        const activeChild = $(
            ".categories-content__wrapper .categories-content__item.active"
        ),
            activeChildLength = activeChild.length;
        activeChild.each(function (i) {
            $(this).css("borderBottom", "1px solid rgba(255, 255, 255, 0.3)");
            if (i === activeChildLength - 1) {
                $(this).css("borderBottom", "0");
            }
        });
        //activeChild.css("borderBottom", "0");
    }

    $(".js-ambassador-category>span").click(function (e) {
        e.stopPropagation();
        handleAmbassadorCategoryClick($(e.target));
        if (window.innerWidth < 767) {
            removeBorderForAmbassador();
        }
    });
    /*
        Function to initialize all the multiitems projects carousel if used on the same page
        */
    function onLoadCheckActiveAmbassadorCategory() {
        const $parentEle = $(".categories-list");
        if ($parentEle) {
            const $activeCategoryEle = $parentEle.find(
                ".js-ambassador-category.active span"
            );
            handleAmbassadorCategoryClick($activeCategoryEle);
            if (window.innerWidth < 767) {
                removeBorderForAmbassador();
            }
        }
    }
    onLoadCheckActiveAmbassadorCategory();
    /*
        Function to initialize all the multiitems projects carousel if used on the same page
        */
    function initProjectCarousels() {
        const $carouselElements = $(".cards-carousel");
        $carouselElements.each((index, carouselEle) => {
            // Only need the first occurence
            const slidesNumber = $(carouselEle).data("slide-number"),
                slideNumberOnMobile = $(carouselEle).data("slide-number-mobile")
                    ? $(carouselEle).data("slide-number-mobile")
                    : 1,
                swiper = $(carouselEle).find(".swiperSlides")[0],
                swiperWrapper = $(carouselEle).find(".swiper-wrapper")[0],
                nextEl = $(carouselEle).find(".swiper-button-next")[0],
                prevEl = $(carouselEle).find(".swiper-button-prev")[0],
                scrollbar = $(carouselEle).find(".swiper-scrollbar")[0],
                isCarouselOnMobile = $(carouselEle).hasClass(
                    "cards-carousel--on-mobile"
                );
            var spaceBetween = slidesNumber === 4 ? 22 : 30;

            function initiateCarousel() {
                const swipeslides = new Swiper(swiper, {
                    slidesPerView: slideNumberOnMobile,
                    spaceBetween: 16,
                    centerInsufficientSlides: true,
                    slidesPerGroup: 1,
                    // Navigation arrows
                    navigation: {
                        nextEl: nextEl,
                        prevEl: prevEl,
                    },

                    // And if we need scrollbar
                    scrollbar: {
                        el: scrollbar,
                        draggable: true,
                    },
                    breakpoints: {
                        640: {
                            slidesPerView: 2,
                            spaceBetween: spaceBetween,
                            slidesPerGroup: 2,
                        },
                        768: {
                            slidesPerView: slidesNumber - 1,
                            slidesPerGroup: slidesNumber - 1,
                            spaceBetween: spaceBetween,
                        },
                        1024: {
                            slidesPerView: slidesNumber - 1,
                            slidesPerGroup: slidesNumber - 1,
                            spaceBetween: spaceBetween,
                        },
                        1200: {
                            slidesPerView: slidesNumber,
                            slidesPerGroup: slidesNumber,
                            spaceBetween: spaceBetween,
                        },
                    },
                });
            }

            if (isCarouselOnMobile) {
                if (window.innerWidth < 648) {
                    initiateCarousel();
                } else {
                    $(swiper).removeClass("swiper");
                    $(swiperWrapper).removeClass("swiper-wrapper");
                    return null;
                }
            } else {
                initiateCarousel();
            }
        });
    }
    // Null check for the project carousels
    $(".cards-carousel").length > 0 ? initProjectCarousels() : "";
    // Needle Fabric Types - Start //
    const TABLET_MIN_WIDTH = 768;
    const needleTypesCarouselItems = $("#needle-types-data").children();
    const needleTypesLength = needleTypesCarouselItems.length;
    const needleTypesCarouselItemsCopy = [...needleTypesCarouselItems];
    const needleTypesContainer = $(".needle-types");
    const needleTypesScrollContainer = $(
        ".needle-types .swiper-scrollbar-container"
    );
    const needleTypesControlElem = $(".needle-types .swiper-controls-container");
    const needleTypesCarouselContainer = $(
        ".needle-fabric-types-carousel .swiper-wrapper"
    );
    const maxNeedleTypesPerSlide = getMaxNeedleTypesPerSlide();
    const needleTypesTotalSlides = Math.ceil(
        needleTypesCarouselItems.length / maxNeedleTypesPerSlide
    );
    function showHideNeedleTypesControls() {
        if (needleTypesLength <= getMaxNeedleTypesPerSlide()) {
            needleTypesScrollContainer.hide();
            needleTypesControlElem.hide();
        }
    }
    showHideNeedleTypesControls();
    function getMaxNeedleTypesPerSlide() {
        if (window.innerWidth < TABLET_MIN_WIDTH) {
            return parseInt(needleTypesContainer.data("mobileItems"));
        }
        return parseInt(needleTypesContainer.data("desktopItems"));
    }
    for (let i = 0; i < needleTypesTotalSlides; ++i) {
        const swiperSlideElem = document.createElement("ul");
        const swiperSlideElemContainer = document.createElement("div");
        swiperSlideElemContainer.classList.add("swiper-slide");
        swiperSlideElem.classList.add("needle-types__slide-container");
        for (let i = 0; i < maxNeedleTypesPerSlide; ++i) {
            if (needleTypesCarouselItemsCopy.length) {
                swiperSlideElem.append(needleTypesCarouselItemsCopy.shift());
            }
        }
        swiperSlideElemContainer.append(swiperSlideElem);
        needleTypesCarouselContainer.append(swiperSlideElemContainer);
    }
    const fabricTypesSwiper = new Swiper(".needle-fabric-types-carousel", {
        slidesPerGroup: 1,
        slidesPerView: 1,
        grabCursor: true,
        keyboard: {
            enabled: true,
        },
        scrollbar: {
            el: ".needle-types__scrollbar",
            draggable: true,
        },
        navigation: {
            nextEl: ".needle-types__btn-next",
            prevEl: ".needle-types__btn-prev",
        },
    });

    // Needle Fabric Types - End //
    // FAQ section carousel - Start //
    const FAQ_SEARCH_TERM_MIN_LENGTH = 3;
    let faqSearchResponse = [];
    let faqViewAllSearchResponse = [];
    const cachedFaqResponseSearch = {};
    let reqFaq;
    let reqViewAllFaq;
    const faqSearchUrl = "/PFAFFFAQBlock/SearchFAQ";
    const faqSearchAllResultsEndpoint = "/PFAFFFAQBlock/GetFAQ";
    const $searchFormElem = $("#faq-search-form");
    const faqBlockId = $searchFormElem.data()
        ? $searchFormElem.data().faqBlockId
        : "";
    const $faqResultsTitleElem = $("#faq-results-title");
    const faqResultsTitleElemText = $faqResultsTitleElem.text();
    const $faqNoResultsTitleElem = $("#faq-no-results-title");
    const faqNoResultsTitleElemText = $faqNoResultsTitleElem.text();
    const $faqSearchResultsContainer = $(".faq-head__search-results-container");
    const $faqNoResultsContent = $(".faq-no-results-content")[0]
        ? $(".faq-no-results-content")[0].innerHTML
        : "";
    const viewAllFaqText = $faqSearchResultsContainer.length
        ? $faqSearchResultsContainer.data().viewAllText
        : "";
    const $faqSearchId = $("#faq-search-box");
    let delayTimer;
    let faqSearchText = "";
    function showPfaffLoader() {
        $("#pfaff-loader").show();
        $("body").addClass("no-scroll");
    }

    function hidePfaffLoader() {
        $("#pfaff-loader").hide();
        $("body").removeClass("no-scroll");
    }

    function getFaqResults(searchText) {
        /**
         * Display cached data if search is already done
         */
        if (cachedFaqResponseSearch[searchText]) {
            faqSearchResponse = cachedFaqResponseSearch[searchText];
            displayFaqFlydown();
            return;
        }

        if (reqFaq) {
            reqFaq.abort();
        }

        $.when(
            showPfaffLoader(),
            (reqFaq = $.post(
                faqSearchUrl,
                { currentBlockref: faqBlockId, search: faqSearchText },
                function (res) {
                    faqSearchResponse = res;
                    cachedFaqResponseSearch[searchText] = res;
                }
            ))
        )
            .then(function () {
                hidePfaffLoader();
                displayFaqFlydown();
            })
            .catch(function (err) {
                hidePfaffLoader();
                console.error(err);
            });
    }

    function displayFaqFlydown() {
        $faqSearchResultsContainer.empty();
        const searchResultsWrapper = document.createElement("ul");
        searchResultsWrapper.classList.add("faq-head__search-results");
        if (faqSearchResponse.length >= 1) {
            faqSearchResponse.forEach((responseItem) => {
                searchResultsWrapper.insertAdjacentHTML(
                    "beforeend",
                    `
          <h4 class="faq-head__cat-title">${responseItem.category}</h4>
          <ul class="faq-head__result-links-container">
            ${responseItem.faqs
                        .map(
                            (faqItem) =>
                                `<li><a href="#" class="faq-head__results-link">${faqItem.Question.Fragments[0].InternalFormat}</a><div class="display-none">${faqItem.Answer.Fragments[0].InternalFormat}</div></li>`
                        )
                        .join("")}
          </ul>
        `
                );
            });
            $faqSearchResultsContainer[0].insertAdjacentElement(
                "beforeend",
                searchResultsWrapper
            );
            $faqSearchResultsContainer[0].insertAdjacentHTML(
                "beforeend",
                `
      <a href="#" class="faq-head__search-results-footer-link secondary-link--chevron">
        <span>${viewAllFaqText}</span>
        <i class="fa fa-chevron-right faq-head__chevron-right" aria-hidden="true"></i>
      </a>
      `
            );
        } else {
            searchResultsWrapper.insertAdjacentHTML(
                "beforeend",
                `
        <h4 class="faq-head__cat-title no-results">${$faqNoResultsContent}</h4>
      `
            );
            $faqSearchResultsContainer[0].insertAdjacentElement(
                "beforeend",
                searchResultsWrapper
            );
        }
        $faqSearchResultsContainer.show();
    }

    // submit listener for faq search form / on pressing enter
    $searchFormElem.on("submit", function (e) {
        e.preventDefault();
        const faqSearchTerm = $faqSearchId.val();
        faqSearchText = faqSearchTerm;
        if (!faqSearchText) {
            $faqSearchId.focus();
        } else if (
            faqSearchTerm &&
            faqSearchTerm.trim() &&
            faqSearchTerm.trim().length >= FAQ_SEARCH_TERM_MIN_LENGTH
        ) {
            faqSearchText = faqSearchTerm;
            handleViewAllFaq();
        }
    });

    // input listener to faq search field
    $faqSearchId.on("input", function () {
        /**
         * Wait for user to finish typing before making ajax call
         */
        if (delayTimer) {
            clearTimeout(delayTimer);
        }

        delayTimer = setTimeout(() => {
            const faqSearchTerm = $(this).val();
            if (
                faqSearchTerm &&
                faqSearchTerm.trim() &&
                faqSearchTerm.trim().length >= FAQ_SEARCH_TERM_MIN_LENGTH
            ) {
                faqSearchText = faqSearchTerm;
                getFaqResults(faqSearchTerm);
            } else {
                $faqSearchResultsContainer.hide();
            }
        }, 500);
    });

    const faqSwiper = new Swiper(".faq-body__carousel-items", {
        slidesPerView: 3,
        spaceBetween: 30,
        slidesPerGroup: 1,
        loop: true,
    });
    function scrollToSmoothly(elem = null, time = 500, elemOffsetY = 0) {
        var currentPos = window.pageYOffset;
        var start = null;
        var pos = elem.offset().top;
        pos = +pos - elemOffsetY;
        window.requestAnimationFrame(function step(currentTime) {
            start = !start ? currentTime : start;
            var progress = currentTime - start;
            if (currentPos < pos) {
                window.scrollTo(0, ((pos - currentPos) * progress) / time + currentPos);
            } else {
                window.scrollTo(0, currentPos - ((currentPos - pos) * progress) / time);
            }
            if (progress < time) {
                window.requestAnimationFrame(step);
            } else {
                window.scrollTo(0, pos);
            }
        });
    }
    const setActiveLink = (elem, activeIndex = "loadAllFAQ") => {
        const index = elem.dataset["catIndex"] || activeIndex;
        const categoriesParentElemArr = [
            ...elem.closest(".faq-body__links").children,
        ];
        categoriesParentElemArr.forEach((item) => {
            if (item.dataset["catIndex"] === index) {
                item.classList?.remove("faq-body__link--not-selected");
                item.classList?.add("faq-body__link--selected");
            } else {
                item.classList?.add("faq-body__link--not-selected");
                item.classList?.remove("faq-body__link--selected");
            }
        });
    };
    const resetFaqLinks = (elem) => {
        const categoriesParentElemArr = [
            ...elem.closest(".faq-body__links")?.children,
        ];
        categoriesParentElemArr.forEach((item) => {
            item.classList?.remove("faq-body__link--not-selected");
            item.classList?.remove("faq-body__link--selected");
        });
    };
    const showFaqContent = (e) => {
        const clickedCategory = e.target?.closest(".faq-body__link-item");
        const clickedCarouselItem = e.target?.closest(".swiper-slide");
        if (clickedCategory || clickedCarouselItem) {
            const categoryIndex =
                clickedCategory?.dataset["catIndex"] ||
                clickedCarouselItem?.dataset["catIndex"];
            if ((clickedCategory || clickedCarouselItem) && categoryIndex) {
                const elem = clickedCategory || clickedCarouselItem;
                const doScroll =
                    window.innerWidth < TABLET_MIN_WIDTH && clickedCategory;
                setActiveLink(elem);
                setActiveFaqCatCarousel(categoryIndex, doScroll);
                setActiveFaqCatContent(categoryIndex);
            }
        }
    };
    const expandCollapseItem = (e) => {
        const clickedItem = e.target?.closest(".faq-body__content-title-container");
        if (clickedItem) {
            const contentItemElem = clickedItem.closest(
                ".faq-body__content-body-item"
            );
            if (contentItemElem?.classList.contains("plus-icon")) {
                contentItemElem.classList.remove("plus-icon");
                contentItemElem.setAttribute("aria-expanded", true);
            } else {
                contentItemElem?.classList.add("plus-icon");
                contentItemElem?.setAttribute("aria-expanded", false);
            }
            if (!contentItemElem?.classList.contains("active")) {
                contentItemElem?.classList.add("active");
            } else {
                contentItemElem?.classList.remove("active");
            }
        }
    };
    const contentItemsElemArr = [...$(".faq-body__content").children()];
    const setActiveFaqCatContent = (index) => {
        contentItemsElemArr.forEach((item) => {
            if (index === "loadAllFAQ") {
                item
                    ?.querySelector(".faq-body__content-item-title")
                    ?.classList.add("display-none");
                if (item?.classList.contains("not-all-faq")) {
                    item?.classList.add("display-none");
                } else {
                    item?.classList.remove("display-none");
                }
            } else {
                item?.classList.add("display-none");
                if (item?.dataset["catIndex"] === index) {
                    item
                        ?.querySelector(".faq-body__content-item-title")
                        ?.classList?.remove("display-none");
                    item?.classList.remove("display-none");
                }
            }
        });
    };
    const slideFaqCatCarousel = (index) => {
        if ($(".faq-body__carousel-items .faq-body__links").length) {
            const slideIndex = parseInt(
                $(`.swiper-slide[data-cat-index=${index}]`).attr("data-slide-index")
            );
            faqSwiper.update();
            faqSwiper.slideTo(slideIndex + 1);
            faqSwiper.update();
        }
    };
    const setActiveFaqCatCarousel = (index, doScroll = false) => {
        if (index) {
            $(".swiper-wrapper")
                ?.find(`[data-cat-index=${index}]`)
                ?.attr("aria-selected", true);
            if (doScroll) {
                setActiveLink($(".swiper-wrapper")[0], index);
                scrollToSmoothly($(".swiper"));
            }
            slideFaqCatCarousel(index);
        }
    };
    const updateAriaSelectedCarousel = (elem) => {
        const carouselItemsArr = [...elem.children()];
        carouselItemsArr.forEach((item) => {
            item.setAttribute("aria-selected", false);
        });
    };
    if (window.innerWidth < TABLET_MIN_WIDTH) {
        setActiveFaqCatCarousel("loadAllFAQ");
        setActiveFaqCatContent("loadAllFAQ");
    }
    $("#faq-category-links").on("click", showFaqContent);
    $("#faq-category-links").on("keydown", (e) => {
        // when enter is clicked
        if (e.originalEvent.keyCode === 13) {
            showFaqContent(e);
        }
    });
    $("#faq-carousel-links").on("click", showFaqContent);
    $(".faq-body__content").on("click", expandCollapseItem);
    $(".faq-body__content").on("keydown", (e) => {
        // when enter is clicked
        if (e.originalEvent.keyCode === 13) {
            expandCollapseItem(e);
        }
    });
    $("#faq-body__content-only-mobile").on("click", expandCollapseItem);
    $(".need-help").on("click", expandCollapseItem);
    $(".machine-manuals").on("click", expandCollapseItem);
    $(".faq-head__search-container").on("submit", (e) => e.preventDefault());
    const mobFaqSwiperItems = [
        ...$(".swiper-wrapper.faq-body__links")?.children(),
    ];
    const faqCategoryItemsArr = [...$("#faq-category-links")?.children()];
    const faqCategoryItems = faqCategoryItemsArr?.length;
    mobFaqSwiperItems.forEach((swiperItem) => {
        swiperItem.setAttribute("aria-setsize", faqCategoryItems);
        swiperItem.setAttribute("aria-selected", false);
    });
    $("body").on("click", (e) => {
        const clickedItem = e.target.closest(".faq-head__search-group");
        if (!clickedItem) {
            $faqSearchResultsContainer.hide();
        }
    });
    $faqSearchResultsContainer.on("click", (e) => {
        const contactUsLink = e.target.closest(".no-results");
        if (!contactUsLink) {
            e.preventDefault();
            const clickedLink = e.target.closest(".faq-head__results-link");
            const clickedViewAll = e.target.closest(
                ".faq-head__search-results-footer-link"
            );
            if (clickedLink || clickedViewAll) {
                $faqSearchResultsContainer.hide();
                if (clickedLink) {
                    const exactResultContainer = document.querySelector(
                        '.faq-body__content-item[data-cat-index="99"]'
                    );
                    exactResultContainer.innerHTML = "";
                    const questionsWrapper = document.createElement("ul");
                    questionsWrapper.classList.add("faq-body__content-body");
                    questionsWrapper.insertAdjacentHTML(
                        "beforeend",
                        `
            <li class="faq-body__content-body-item plus-icon" aria-expanded="false">
              <div class="faq-body__content-title-container">
                  <span class="faq-body__acc-icon"></span>
                  <h3 class="faq-body__content-title">${clickedLink.innerText}</h3>
              </div>
              <div class="faq-body__content-description">
                  <p>${clickedLink?.nextSibling?.innerHTML}</p>
              </div>
            </li>
          `
                    );
                    exactResultContainer.insertAdjacentElement(
                        "beforeend",
                        questionsWrapper
                    );
                    setActiveFaqCatContent("99");
                } else {
                    handleViewAllFaq();
                }
                const faqLinksElems = [...$(".faq-body__links")];
                faqLinksElems.forEach((linksElem) => resetFaqLinks(linksElem));
                slideFaqCatCarousel("loadAllFAQ");
                if (window.innerWidth < TABLET_MIN_WIDTH) {
                    updateAriaSelectedCarousel($(".swiper-wrapper"));
                    scrollToSmoothly($(".swiper"));
                }
            }
        }
    });

    const handleViewAllFaq = function () {
        if (reqViewAllFaq) {
            reqViewAllFaq.abort();
        }

        $.when(
            showPfaffLoader(),
            (reqViewAllFaq = $.post(
                faqSearchAllResultsEndpoint,
                { currentBlockref: faqBlockId, search: faqSearchText },
                function (res) {
                    faqViewAllSearchResponse = res;
                }
            ))
        )
            .then(function () {
                hidePfaffLoader();
                const exactResultContainer = document
                    .querySelector('.faq-body__content-item[data-cat-index="100"]')
                    .querySelector(".faq-body__content-body");
                exactResultContainer.innerHTML = "";
                const searchRegEx = /"[A-Za-z0-9]*"+/;
                const faqs = faqViewAllSearchResponse;
                let resultsTitle = "";
                if (faqs && faqs.length > 0) {
                    const titleSearchTerm = faqResultsTitleElemText.match(searchRegEx);
                    resultsTitle = faqResultsTitleElemText.replace(
                        titleSearchTerm[0],
                        `"${faqSearchText}"`
                    );
                    faqs.forEach((faqItem) => {
                        exactResultContainer.insertAdjacentHTML(
                            "beforeend",
                            `
            <li class="faq-body__content-body-item plus-icon" aria-expanded="false">
              <div class="faq-body__content-title-container">
                  <span class="faq-body__acc-icon"></span>
                  <h3 class="faq-body__content-title">${faqItem.Question}</h3>
              </div>
              <div class="faq-body__content-description">
                  <p>${faqItem.Answer}</p>
              </div>
            </li>
          `
                        );
                    });
                } else {
                    const titleSearchTerm = faqNoResultsTitleElemText.match(searchRegEx);
                    resultsTitle = faqNoResultsTitleElemText.replace(
                        titleSearchTerm[0],
                        `"${faqSearchText}"`
                    );
                    exactResultContainer.insertAdjacentHTML(
                        "beforeend",
                        `
          <li class="faq-body__content-body-item plus-icon" aria-expanded="false">
            <div class="faq-body__content-title-container">
                <h3 class="faq-body__content-title no-results-body">${$faqNoResultsContent}</h3>
            </div>
          </li>
          `
                    );
                }
                $("#faq-view-all-results-title").text(resultsTitle);
                $faqSearchResultsContainer.hide();
                setActiveFaqCatContent("100");
            })
            .catch(function (err) {
                hidePfaffLoader();
                console.error(err);
            });
    };

    // returns query params string as object
    const getQueryStringParams = (query) => {
        return query
            ? (/^[?#]/.test(query) ? query.slice(1) : query)
                .split("&")
                .reduce((params, param) => {
                    let [key, value] = param.split("=");
                    params[key] = value
                        ? decodeURIComponent(value.replace(/\+/g, " "))
                        : "";
                    return params;
                }, {})
            : {};
    };
    // storing query params
    const queryParams = getQueryStringParams(
        window.location.href.split("?")?.splice(1)?.join("")
    );
    // checking if category param is present in the URL
    if (queryParams?.category === "allFaq") {
        const allFaqLinkElem = document.querySelector(
            '.faq-body__link-item[data-cat-index="loadAllFAQ"]'
        );
        if (allFaqLinkElem) {
            setActiveLink(allFaqLinkElem);
            const doScroll = window.innerWidth < TABLET_MIN_WIDTH;
            setActiveFaqCatCarousel("loadAllFAQ", doScroll);
            setActiveFaqCatContent("loadAllFAQ");
        }
    }
    // FAQ Section - End //
    // Function to pause the video in the video modal
    function pauseVideo() {
        const $parent = $(this).parent(".modal-body");
        const $iFrame = $parent.find("iframe");
        const videoSrc = $iFrame.attr("src");
        $iFrame.attr("src", videoSrc);
    }
    $(document).on("click", ".video-modal button.close", pauseVideo);
    // Funtion for the view more and hide features
    function toggleViewHide() {
        const MAXLIMIT = 6; // Can be configured
        const $parentWrapper = document.querySelectorAll(".withViewAll");
        // For each parent with withViewAll Class
        $parentWrapper.forEach((ele) => {
            const $itemListWrapper = $(ele).find(
                ".testimonial-section__list-wrapper"
            );
            const $listItems = $itemListWrapper.find(
                ".testimonial-section__list-item"
            );
            const listItemsLength = $listItems.length;
            const $ctaWrapper = $(ele).find(".testimonial-section__cta-wrapper");
            const $loadMoreBtn = ($viewMoreCta = $(ele).find(".viewMore"));
            const $hideBtn = $(ele).find(".hide");
            $listItems.slice(0, MAXLIMIT).show();
            // Check if on initial load we have less than max limit
            if (listItemsLength <= MAXLIMIT) {
                $listItems.slice(0, listItemsLength).show();
                $ctaWrapper.hide();
            } else {
                $ctaWrapper.show();
                $loadMoreBtn.show();
                $hideBtn.hide();
            }
            // To show the remaining list items
            $loadMoreBtn.on("click", function () {
                $itemListWrapper
                    .find(".testimonial-section__list-item:hidden")
                    .slice(0, listItemsLength)
                    .show();
                if (
                    $itemListWrapper.find(".testimonial-section__list-item:hidden")
                        .length == 0
                ) {
                    $loadMoreBtn.hide();
                    $hideBtn.show();
                }
            });
            // To hide the extra loaded items
            $hideBtn.on("click", function () {
                $listItems.hide(); // Hide All - Default
                $listItems.slice(0, MAXLIMIT).show(); //Show only as per the max limit
                $loadMoreBtn.show();
                $hideBtn.hide();
                scrollToSmoothly($(ele));
            });
        });
    }
    toggleViewHide();
    /*
        Function to get the visible height of the component
        @param $ele: parent element of the block
        */
    function getVisible($ele) {
        var $el = $ele,
            scrollTop = $(this).scrollTop(),
            scrollBot = scrollTop + $(this).height(),
            elTop = $el.offset().top,
            elBottom = elTop + $el.outerHeight(),
            visibleTop = elTop < scrollTop ? scrollTop : elTop,
            visibleBottom = elBottom > scrollBot ? scrollBot : elBottom;
        return visibleBottom - visibleTop;
    }
    // Function to scroll to the next block when clicked on scroll icon
    function scrollToNextBlock(e) {
        const $ele = $(this).parents(".js-scroll-to-next"),
            visibleHeight = getVisible($ele);
        $("html, body").animate({ scrollTop: "+=" + visibleHeight }, 800);
    }
    $(document).on("click", ".scroll-icon", scrollToNextBlock);
    // Article Page Badges
    function loadMoreCategoryBadge() {
        const DEFAULTVISIBLELIMIT = 5;
        const $parentList = $(
            ".article-intro-block .article-categories-badges__list"
        );
        const $badgeItems = $parentList.find(
            ".article-categories-badges__list-item"
        );
        // used -1 because the load more is also using the same classes
        const badgeItemsLength = $badgeItems.length - 1;
        const $loadMoreBtn = $parentList.find(".load-more");
        $badgeItems.slice(0, DEFAULTVISIBLELIMIT).show();
        // To hide the load more btn if we have less badges
        badgeItemsLength >= 6 ? $loadMoreBtn.show() : $loadMoreBtn.hide();
        // To show the remaining badges
        $loadMoreBtn.on("click", function () {
            $parentList
                .find(".article-categories-badges__list-item:hidden")
                .slice(0, badgeItemsLength)
                .show();
            if (
                $parentList.find(".article-categories-badges__list-item:hidden")
                    .length == 0
            ) {
                $loadMoreBtn.hide();
            }
        });
    }
    // loadMoreCategoryBadge();
    // Only for the Intro Block is present
    document.querySelectorAll(".article-intro-block").length > 0
        ? loadMoreCategoryBadge()
        : "";
    // hide the previous and next icon for the promo bar
    function hidePerviousNextIcon() {
        let promotionalBannerPrevBtn = $(".carousel-control-prev");
        let promotionalBannerNextBtn = $(".carousel-control-next");
        let promotionalBannerRowItems = $(
            ".promotional-banner .carousel-inner .item"
        );
        if (promotionalBannerRowItems && promotionalBannerRowItems.length === 1) {
            promotionalBannerNextBtn.hide();
            promotionalBannerPrevBtn.hide();
        }
    }
    // null check
    document.querySelectorAll(".promotional-banner").length > 0
        ? hidePerviousNextIcon()
        : "";
    // Video modal code Start
    // event listener for video modal trigger
    $(document).on("click", (e) => {
        const modalTriggerElem = e.target.closest(".video-modal-trigger");

        if (modalTriggerElem) {
            const videoType = modalTriggerElem.dataset.videoType;
            var videoId = "",
                title = "",
                url = "",
                staticVideoFormat = "";
            title = modalTriggerElem.dataset.title;
            if (videoType === "vimeo") {
                videoId = modalTriggerElem.dataset.vmId;
                url = videoId + "?autoplay=1&autopause=0&muted=1";
            } else if (videoType === "youtube") {
                videoId = modalTriggerElem.dataset.ytId;
                url = `https://www.youtube.com/embed/${videoId}?autoplay=1&mute=1&start=0&rel=0`;
            } else {
                url = modalTriggerElem.dataset.staticId;
                staticVideoFormat = url.split(".").pop();
            }
            if (videoType === "vimeo" || videoType === "youtube") {
                $(".video-modal").find("iframe").attr("src", url);
            } else {
                $(".video-modal").addClass("static-video");
                var exiVideoEle = $(".video-modal #video")
                exiVideoEle.remove();
                var videoEle = $(".video-modal .modal-body")
                var video = $('<video />', {
                    id: 'video',
                    src: url,
                    type: "video/" + staticVideoFormat,
                    controls: true,
                    autoplay :true
                });
                video.appendTo($(videoEle));

                //var videoEle = $(".video-modal #video");
                //var source = document.createElement("source");
                //source.setAttribute("src", url);
                //source.setAttribute("type", "video/" + staticVideoFormat);
                //$(videoEle).append(source);
                //$(videoEle).trigger("load");
            }

            if (title) {
                $(".video-modal").find("iframe").attr("title", title);
            }
            $(".video-modal").modal("show");
        }
    });
    // removes src from iframe on closing video modal
    $(".video-modal").on("hidden.bs.modal", function () {
        if ($(this).find("iframe")) {
            $(this).find("iframe").attr("src", "");
        }
        if ($(this).find("#video")) {
            $(".video-modal").removeClass("static-video");
            $(this).find("#video").trigger("pause");
            $(this).find("#video > source").remove();
        }
    });

    // Video modal code End
    /*
    Function to show the next "x" numbers of articles
    */
    function viewMoreArticles() {
        var $sectionWrapper = $(".all-articles-block"),
            $items = $sectionWrapper.find(".card-wrapper"),
            itemsLength = $sectionWrapper.find(".card-wrapper").length,
            hiddenItems = ".card-wrapper:hidden",
            hiddenItemsLength,
            LIMIT = $sectionWrapper.data("card-limit"),
            $viewMore = $sectionWrapper.find(".view-more-cta"),
            $visualScrollHighlight = $(".visual-scroll--highlight"),
            $visibleEle = $("#visible");
        // To hide the load more btn if we have less items
        itemsLength >= LIMIT ? $viewMore.show() : $viewMore.hide();
        $items.slice(0, LIMIT).show();
        hiddenItemsLength = $sectionWrapper.find(hiddenItems).length;
        udateVisualScroll();
        $viewMore.on("click", () => {
            $sectionWrapper.find(hiddenItems).slice(0, LIMIT).show();
            if ($sectionWrapper.find(hiddenItems).length == 0) {
                $viewMore.hide();
            }
            udateVisualScroll();
        });
        // Function to update the visual scroll highlighter width
        function udateVisualScroll() {
            var latestHidden = $sectionWrapper.find(hiddenItems).length,
                visibleItemLength = itemsLength - latestHidden;
            $visibleEle.text(visibleItemLength);
            const widthPercentage = Math.round(
                (visibleItemLength / itemsLength) * 100
            );
            $visualScrollHighlight.css("width", widthPercentage + "%");
        }
    }
    // Null check
    $(".all-articles-block").length > 0
        ? viewMoreArticles(".all-articles-block")
        : "";

    // Null check for sorting
    $("#articles-sort-by").length > 0 ? articlesSorting() : "";

    function articlesSorting() {
        const $onSortEle = $("#articles-sort-by .js-sort-by-option");
        $onSortEle.on("click", function (e) {
            e.preventDefault();
            const sortOrder = $(e.target).data("sortOrder"),
                sortText = $(e.target).text();
            $sortByEle = $("#sortbyMenuButton");
            $sortByEle.text(sortText);
            // show loader
            $("#pfaff-loader").show();
            $.ajax({
                url: "/AllArticlesBlock/GetSortedArticles",
                type: "POST",
                data: {
                    pageId: $("#pageId").val(),
                    sortingOrder: sortOrder,
                    articlectaText: $('[name="articlectaText"]')[0]?.innerText,
                    isLatestArticles: $("#isLatestArticles").val(),
                },
                success: function (response) {
                    /* spinner  end*/
                    $("#articles").empty();
                    response?.articleDetails?.forEach((articleItem) => {
                        $("#articles").append(`
                              <div class="card-wrapper">
                                  <a href="${articleItem.href}" target="_blank">
                                      ${articleItem.image
                                ? `<div class="img-wrapper">
                                          <img src="${articleItem.image}" alt="${articleItem.altText}" class="img-fluid" />
                                      </div>`
                                : ""
                            }
                                      ${articleItem.category
                                ? `<div class="product-badge" aria-hidden="true"><p aria-hidden="true">${articleItem.category}</p></div>`
                                : ""
                            }
                                      ${articleItem.title
                                ? `<div class="card-heading text-black font-size-32">
                                          ${articleItem.title}
                                      </div>`
                                : ""
                            }
                                      ${articleItem.description
                                ? `<div class="description text-black">
                                          ${articleItem.description}
                                      </div>`
                                : ""
                            }
                                  </a>
                                  <div class="card-cta-wrapper">
                                      ${articleItem?.href && response?.ctaText
                                ? `<a href="${articleItem.href}" target="_blank" class="secondary-btn pfaff-primary-btn pfaff-primary-btn--extended" name="articlectaText">
                                          ${response.ctaText}
                                      </a>`
                                : ""
                            }
                                  </div>
                              </div>
                              `);
                    });
                    viewMoreArticles(".all-articles-block");
                    // hides loader
                    $("#pfaff-loader").hide();
                },
                error: function (err) {
                    // hides loader
                    console.log(err);
                    $("#pfaff-loader").hide();
                },
            });
            // Most Popular Needles - Start //
            const popularNeedlesCarousel = new Swiper(".popular-needle__carousel", {
                slidesPerView: 1,
                spaceBetween: 25,
                slidesPerGroup: 1,
                loopFillGroupWithBlank: true,
                breakpoints: {
                    1024: {
                        slidesPerView: 2,
                        slidesPerGroup: 1,
                        spaceBetween: 25,
                    },
                    1260: {
                        slidesPerView: 3,
                        slidesPerGroup: 1,
                        spaceBetween: 25,
                    },
                },
                scrollbar: {
                    el: ".popular-needle__scrollbar",
                },
                navigation: {
                    nextEl: ".popular-needle__btn-next",
                    prevEl: ".popular-needle__btn-prev",
                },
            });
            // Most Popular Needles - End //
        });
    }

    // Support page - start
    const faqElem =
        $(".section.need-help .section__faq") &&
        $(".section.need-help .section__faq")[0];
    const faqElemClone = faqElem?.cloneNode(true);
    const leftSupportContainer =
        $(".section.need-help .section__body-left") &&
        $(".section.need-help .section__body-left")[0];
    leftSupportContainer?.children[0]?.insertAdjacentElement(
        "afterend",
        faqElemClone
    );
    // Support page - end

    // Needle Anatomy Swipers - Start
    const needleAnatomyTypeCarousel = new Swiper(
        "#needle-anatomy-type-carousel",
        {
            slidesPerGroup: 1,
            slidesPerView: 1,
            grabCursor: true,
            spaceBetween: 10,
            keyboard: {
                enabled: true,
            },
            navigation: {
                nextEl: "#needle-anatomy-type-btn-next",
                prevEl: "#needle-anatomy-type-btn-prev",
            },
        }
    );
    const needleAnatomySizeCarousel = new Swiper(
        "#needle-anatomy-size-carousel",
        {
            slidesPerGroup: 1,
            slidesPerView: 1,
            grabCursor: true,
            spaceBetween: 10,
            keyboard: {
                enabled: true,
            },
            navigation: {
                nextEl: "#needle-anatomy-size-btn-next",
                prevEl: "#needle-anatomy-size-btn-prev",
            },
        }
    );
    // Needle Anatomy Swipers - End //

    // Function to view all sub-categories on click
    function viewAllSubCategories() {
        const DEFAULTVISIBLELIMIT = 5,
            $parentList = $(".subCategory-listing-block .subCategories__wrapper"),
            $badgeItems = $parentList.find(".subCategories__item"),
            badgeItemsLength = $badgeItems.length - 1,
            $loadMoreBtn = $parentList.find(".view-all"),
            isCarouselOnMobile = $parentList.parents(
                ".subCategory-listing-block--mobile-carousel"
            ),
            $categoryPage = $(".category-page"),
            $hideSubCategory = $categoryPage.find(".hide-sub-category");
        if (isCarouselOnMobile.length > 0 && window.innerWidth < 767) {
            $badgeItems.slice(0, badgeItemsLength).show();
            return;
        }
        $badgeItems.slice(0, DEFAULTVISIBLELIMIT).show();
        // To hide the load more btn if we have less badges
        badgeItemsLength >= 6 ? $loadMoreBtn.show() : $loadMoreBtn.hide();

        // To show the remaining badges
        $loadMoreBtn.on("click", function () {
            $categoryPage.addClass("show-all-sub-categories");
            $parentList
                .find(".subCategories__item:hidden")
                .slice(0, badgeItemsLength)
                .show();
            if ($parentList.find(".subCategories__item:hidden").length == 0) {
                $loadMoreBtn.hide();
            }
        });

        $hideSubCategory.on("click", function () {
            location.reload();
        });
    }
    viewAllSubCategories();

    $(".sub-category-article-block").length > 0
        ? viewMoreArticles(".sub-category-article-block")
        : "";

    $("#articles-sort-by-sub-category").length > 0 ? sortSubCat() : "";

    function sortSubCat() {
        const $onSortEle = $("#articles-sort-by-sub-category .js-sort-by-option");
        $onSortEle.on("click", function (e) {
            e.preventDefault();
            const sortOrder = $(e.target).data("sortOrder"),
                sortText = $(e.target).text();
            $sortByEle = $("#sortbyMenuButton");
            $sortByEle.text(sortText);
            $("#pfaff-loader").show();
            $.ajax({
                type: "POST",
                url: "/PFAFFSubCategoryPage/GetSortedArticles",
                data: {
                    pageId: $("#category-id").data("id"),
                    sortingOrder: sortOrder,
                    subCategory: $("#category-id").text(),
                    ctaText: $('[name="articlectaText"]')[0]?.innerText,
                },

                success: function (response) {
                    /* spinner  end*/
                    $("#subCategory-articles").empty();
                    response?.articlePages?.forEach((articleItem) => {
                        $("#subCategory-articles").append(`
                            <div class="card-wrapper">
                                <a href="${articleItem.href}" target="_blank">
                                    ${articleItem.image
                                ? `<div class="img-wrapper">
                                        <img src="${articleItem.image}" alt="${articleItem.altText}" class="img-fluid" />
                                    </div>`
                                : ""
                            }
                                    ${articleItem.categoryType
                                ? `<div class="product-badge" aria-hidden="true"><p aria-hidden="true">${articleItem.categoryType}</p></div>`
                                : ""
                            }
                                    ${articleItem.title
                                ? `<div class="card-heading text-black font-size-32">
                                        ${articleItem.title}
                                    </div>`
                                : ""
                            }
                           
                                </a>
                                <div class="card-cta-wrapper">
                                    ${articleItem?.href && response?.ctaText
                                ? `<a href="${articleItem.href}" name="articlectaText" target="_blank" class="pfaff-primary-btn pfaff-primary-btn--extended">
                                        ${response.ctaText}
                                    </a>`
                                : ""
                            }
                                </div>
                            </div>
                            `);
                    });
                    viewMoreArticles(".sub-category-article-block");
                    // hides loader
                    $("#pfaff-loader").hide();
                },
                error: function (err) {
                    console.error(err);
                    // hides loader
                    $("#pfaff-loader").hide();
                },
            });
        });
    }

    // Machine manuals page scroll functionality to dropdown - Start
    const $flydownElem = $(
        ".section.machine-manuals .machine-manuals__dropdown .dropdown-menu"
    );
    const $flydownDropdown = $(
        ".section.machine-manuals .machine-manuals__dropdown .secondary-btn.dropdown-toggle"
    );
    const flydownHeight = $flydownDropdown?.innerHeight();
    const $connectScrollTrigger = $(".scroll-to-flydown")[0];
    $flydownElem?.css("padding-top", flydownHeight);
    $connectScrollTrigger?.addEventListener("click", (e) => {
        const clickedElem = e.target.closest(".section__connect-footer-txt");
        if (clickedElem) {
            e.preventDefault();
            const $machineManualsDropdown = $(".machine-manuals__dropdown");
            if ($machineManualsDropdown[0]) {
                scrollToSmoothly($(".machine-manuals__dropdown"), undefined, 100);
            }
        }
    });
    // Machine manuals page scroll functionality to dropdown - End

    //Lazy Load Images Start
    const observer = lozad(".lozad", {
        rootMargin: "30px 0px", // syntax similar to that of CSS Margin
        threshold: 0.8, // ratio of element convergence
    });
    observer.observe();

    /*
     Function to adjust the top value of the carousel nav buttons
     */

    var _adjustTopValue = function () {
        let carouselEle = $(".cards-carousel.other-machine-carousel-wrapper");
        if (carouselEle.length > 0) {
            carouselEle.each(function (index) {
                let ele = $(this).find(".swiper-slide:first-child .main-content .img-wrapper img:first-child"),
                    navBtn = $(this).find(".carousel-nav-btn"),
                    topValue = Math.round($(ele).innerHeight() / 2);
                if (topValue > 0) {
                    navBtn.css("top", topValue);
                }
            });
        }

    }

    setTimeout(_adjustTopValue, 500);
    $(window).resize(function () {
        _adjustTopValue();
    });


});
;
$(document).ready(function () {
  var delayTimer;
  var requestSearchProduct;
  var requestFlydownData;
  var responseData = {};
  var cachedResponseSearch = {};
  var $loader = $("#pfaff-loader");
  var globalSearchFlyDown = $("#global-search");
  var productListElem = $("#searchProlist");
  var articleListElem = $("#searchArtlist");
  var suggestionListElem = $("#searchSuggestionList");
  var globalSearchFlyDownData = globalSearchFlyDown.data();
  var cachedResponseFlydown = {};
  var productsWrapper = $(".products-wrapper"),
    articlesWrapper = $(".articles-wrapper");
  var urlConfig = {
    shopDomain:
      globalSearchFlyDownData == null
        ? void 0
        : globalSearchFlyDownData.shopDomain,
    searchProductUrl:
      globalSearchFlyDownData == null
        ? void 0
        : globalSearchFlyDownData.searchProductUrl,
    pfaffDoman:
      globalSearchFlyDownData == null
        ? void 0
        : globalSearchFlyDownData.pfaffDomain,
    flydownDataurl:
      globalSearchFlyDownData == null
        ? void 0
        : globalSearchFlyDownData.flydownDataUrl,
    getSearchUrl: function () {
      return this.shopDomain + this.searchProductUrl;
    },
    getFlydowndataUrl: function () {
      return this.pfaffDoman + this.flydownDataurl;
    },
  };
  function onFormSubmit() {
    $("#gloSechFrm").on("submit", function (evt) {
      evt.preventDefault();
      const $inputEle = $(evt.target).find("#searchIn"),
        value = $inputEle.val();
      $inputEle.focus();

      if (value.trim() && value.length >= 3) {
        let searchURL =
          urlConfig.shopDomain +
          "/" +
          globalSearchFlyDownData.language.toLowerCase() +
          "/search?title=" +
          value;
        window.location.href = searchURL;
      }
    });
  }
  function onKeypressForSearch() {
    $("#searchIn").on("input focus", function (event) {
      /**
       * Wait for user to finish typing before making ajax call
       */
      var inputValue = $(this).val();
      if (
        inputValue &&
        inputValue.trim() &&
        inputValue.trim().length >= 1 &&
        window.innerWidth < 768
      ) {
        $(".clear-search-icon").removeClass("d-none");
      } else {
        $(".clear-search-icon").addClass("d-none");
      }

      if (delayTimer) {
        clearTimeout(delayTimer);
      }
      delayTimer = setTimeout(() => {
        var value = $(this).val();
        if (value && value.trim() && value.trim().length >= 3) {
          getSearchData(value);
          $(".global-search-wrapper").css(
            "top",
            $(".fixed-ribbon").outerHeight(true)
          );
        } else {
          globalSearchFlyDown.hide();
        }
      }, 500);
    });
  }
  function getSearchData(searchText) {
    /**
     * Display cached data if search is already done
     */
    if (cachedResponseSearch[searchText] && cachedResponseFlydown[searchText]) {
      productListElem.html("");
      responseData.searchProjectData = cachedResponseSearch[searchText];
      responseData.flydownData = cachedResponseFlydown[searchText];
      displaySearchData();
      return;
    }
    if (requestSearchProduct) {
      requestSearchProduct.abort();
    }
    if (requestFlydownData) {
      requestFlydownData.abort();
    }
    $.when(
      $loader.show(),
      (requestSearchProduct = $.get(
        urlConfig.getSearchUrl() + searchText,
        function (res) {
          responseData.searchProjectData = res;
          cachedResponseSearch[searchText] = res;
        }
      )),
      (requestFlydownData = $.post(
        urlConfig.getFlydowndataUrl(),
        {
          language: globalSearchFlyDownData.language.toLowerCase(),
          serachtext: searchText,
        },
        function (res) {
          responseData.flydownData = res;
          cachedResponseFlydown[searchText] = res;
        }
      ))
    )
      .then(function () {
        $loader.hide();
        productListElem.html("");
        displaySearchData();
      })
      .catch(function (err) {
        $loader.hide();
        console.error(err);
      });
  }
  function displaySearchData() {
    /**
     * Adding flydown data (Article and Did you mean)
     */
    globalSearchFlyDown.show();
    var searchData = "",
      flydownData = "",
      searchSuggestionsData = "",
      tempSuggestionValuesObj = {};
    let productMachineDataArr = [],
      productAccessoryDataArr = [];
    if (
      responseData.searchProjectData &&
      responseData.searchProjectData.length
    ) {      
      let productMachineDataArrLength = 0;
      let productAccessoryDataArrLength = 0;
      responseData.searchProjectData.map((x) => {
        if (x.field_product_type.toLowerCase() === "accessories") {
          productAccessoryDataArr.push(x);
        } else if (x.field_product_type.toLowerCase() === "machines") {
          productMachineDataArr.push(x);
        }
      });
      productMachineDataArrLength = productMachineDataArr.length;
      productAccessoryDataArrLength = productAccessoryDataArr.length;
      let finalProductMachineCount = 0;
      let finalProductAccessoryCount = 0;

      if (productMachineDataArrLength >= 2) {
        if (productAccessoryDataArrLength >= 1) {
          finalProductMachineCount = 2;
          finalProductAccessoryCount = 1;
        } else if (productAccessoryDataArrLength === 0) {
          finalProductMachineCount = 3;
          finalProductAccessoryCount = 0;
        }
      } else if (productMachineDataArrLength === 1) {
        if (productAccessoryDataArrLength >= 2) {
          finalProductMachineCount = 1;
          finalProductAccessoryCount = 2;
        } else if (productAccessoryDataArrLength === 1) {
          finalProductMachineCount = 1;

          finalProductAccessoryCount = 1;
        } else if (productAccessoryDataArrLength === 0) {
          finalProductMachineCount = 1;

          finalProductAccessoryCount = 0;
        }
      } else if (productMachineDataArrLength === 0) {
        finalProductMachineCount = 0;

        if (productAccessoryDataArrLength >= 3) {
          finalProductAccessoryCount = 3;
        } else {
          finalProductAccessoryCount = productAccessoryDataArrLength;
        }
      }
      if (productMachineDataArr.length) {
        productMachineDataArr.map((x, index) => {
          if (index < finalProductMachineCount) {
            productListElem.append(
                `<li class='search-list-item'>
                <a href='${x.url}'>
                <img src='${x.field_banner_image_url}' class='img-fluid' alt='product name' />
                <div class='search-item-content'>
                <p> ${x.title} </p>
                <div class='price'>
                ${Number(x.field_product_sale_purchase_pric.replace(/,/g, '').split(' ')[1]) > 0 ? `<span class='current'> ${x.field_product_sale_purchase_pric} </span>
                <span class='before'> ${x.field_product_list_price} </span>` : `<span class='current'> ${x.field_product_list_price} </span>`}</div>
                </div></a></li>`
            );
          }
        });
      }
      if (productAccessoryDataArr.length) {
        productAccessoryDataArr.map((x, index) => {
          if (index < finalProductAccessoryCount) {
            productListElem.append(
                `<li class='search-list-item'>
                <a href='${x.url}'>
                <img src='${x.field_banner_image_url}' class='img-fluid' alt='product name' />
                <div class='search-item-content'>
                <p> ${x.title} </p>
                <div class='price'>
                ${Number(x.field_product_sale_purchase_pric.replace(/,/g, '').split(' ')[1]) > 0 ? `<span class='current'> ${x.field_product_sale_purchase_pric} </span>
                <span class='before'> ${x.field_product_list_price} </span>` : `<span class='current'> ${x.field_product_list_price} </span>`}</div>
                </div></a></li>`
            );
          }
        });
      }

      responseData.searchProjectData.forEach(function (x, index) {       
        //remove duplicate link with respect to product type
        if (x.field_product_category && x.field_product_type) {
          var temp = String(x.field_product_category).split(",");
          temp.map((y) => {
            if (tempSuggestionValuesObj[x.field_product_type]) {
              if (
                !tempSuggestionValuesObj[x.field_product_type].includes(
                  y.trim()
                )
              ) {
                tempSuggestionValuesObj[x.field_product_type].push(y.trim());
              }
            } else {
              tempSuggestionValuesObj[x.field_product_type] = [];
              tempSuggestionValuesObj[x.field_product_type].push(y.trim());
            }
          });
        }
      });      
      productsWrapper.show();
    } else {      
      productsWrapper.hide();
    }
    if (
      responseData.flydownData.articles &&
      responseData.flydownData.articles.length
    ) {
      var articles = responseData.flydownData.articles;
      articles.forEach(function (x) {
        flydownData += `<li class="search-list-item">
             <a href="${x.url}">
                 <img src="${x.article_image}" class="img-fluid" alt="${x.title}">
                 <div class="search-item-content">
                     <p class="blog-title">${x.category}</p>
                     <p class="blog-heading">${x.title}</p>
                 </div>
             </a>
         </li>`;
      });
      articleListElem.html(flydownData);
      articlesWrapper.show();
    } else {    
      articlesWrapper.hide();
    }
    if (Object.keys(tempSuggestionValuesObj).length) {
      let productLimit = 0;
      let accessoryLimit = 0;
      let tempcat = tempSuggestionValuesObj;
      // console.log("here", Object.entries(tempcat));
      Object.keys(tempcat).length &&
        Object.entries(tempcat).map((x) => {
          if (x[0].toLowerCase() === "accessories") {
            accessoryLimit = x[1].length;
          } else if (x[0].toLowerCase() === "machines") {
            productLimit = x[1].length;
          }
        });
      // console.log('productLimit', productLimit);
      // console.log('accessorylimit', accessoryLimit);
      let finalMachineCount = 0;
      let finalAccessoryCount = 0;
      if (productLimit >= 2) {
        if (accessoryLimit >= 1) {
          // console.log('show two machines and one accessory');
          finalMachineCount = 2;
          finalAccessoryCount = 1;
        } else if (accessoryLimit === 0) {
          // console.log('show three machines');
          finalMachineCount = 3;
          finalAccessoryCount = 0;
        }
      } else if (productLimit === 1) {
        if (accessoryLimit >= 2) {
          // console.log('show one machine and two accessory');
          finalMachineCount = 1;
          finalAccessoryCount = 2;
        } else if (accessoryLimit === 1) {
          // console.log('show one machines and one accessory');
          finalMachineCount = 1;
          finalAccessoryCount = 1;
        } else if (accessoryLimit === 0) {
          // console.log('show one machines and no accessory');
          finalMachineCount = 1;
          finalAccessoryCount = 0;
        }
      } else if (productLimit === 0) {
        finalMachineCount = 0;
        if (accessoryLimit >= 3) {
          finalAccessoryCount = 3;
          // console.log('show three accessory');
        } else {
          finalAccessoryCount = accessoryLimit;
        }
      }     
      Object.keys(tempcat).length &&
        Object.entries(tempcat).map((x) => {
          if (x[0].toLowerCase() === "accessories" && x[1].length) {
            x[1].map((y, index) => {
              if (index < finalAccessoryCount) {
                searchSuggestionsData +=
                  "<li class='search-suggestion-list-item'>" +
                  String(y)
                    .trim()
                    .split("</a>")
                    .join(" " + x[0] + "</a>") +
                  "</li>";                
              }
            });
          }
          if (x[0].toLowerCase() === "machines" && x[1].length) {
            x[1].map((y, index) => {
              if (index < finalMachineCount) {
                searchSuggestionsData +=
                  "<li class='search-suggestion-list-item'>" +
                  String(y)
                    .trim()
                    .split("</a>")
                    .join(" " + x[0] + "</a>") +
                  "</li>";               
              }
            });
          }
        });

    }
    if (responseData.flydownData && responseData.flydownData["do-you-mean"]) {
      var searchSuggestion = responseData.flydownData["do-you-mean"];
      searchSuggestion.forEach(function (x, index) {
        if (index < 3) {
          searchSuggestionsData += `<li class="search-suggestion-list-item">
          <a href="${x.url}">${x["sub-category"]}</a></li>`;
        }
      });
    }
    if (searchSuggestionsData) {
      let searchResultLabel = $("#global-search").data("see-result-label");
      searchSuggestionsData +=
        "<li class='search-suggestion-list-item'><a href='" +
        urlConfig.shopDomain +
        "/" +
        globalSearchFlyDownData.language.toLowerCase() +
        "/search?title=" +
        $("#searchIn").val().trim() +
        "'> " +
        searchResultLabel +
        "</a></li>";
    }
    suggestionListElem.html(
      searchSuggestionsData ||
        `<li class='search-list-item'>${
          suggestionListElem == null
            ? ""
            : suggestionListElem.data().noResultsText
        }</li>`
    );
  }

  const _hideSearchFlydown = function () {
    $(".navbar-nav").hover(() => {
      $("#global-search").hide();
    });
    $(document).on("click keydown", function (e) {
      if (
        (!$(e.target).parents(".global-search-wrapper").length &&
          !$(e.target).hasClass("global-search-wrapper")) ||
        e.key == "Escape"
      ) {
        globalSearchFlyDown.hide();
      }
    });   
  };

  const _handleClearClick = function () {
    $(".clear-search-icon").on("click", function () {
      $("#searchIn").val("");
      $(".clear-search-icon").addClass("d-none");
    });
  };

  var onInit = function () {
    onKeypressForSearch();
    onFormSubmit();
    _hideSearchFlydown();
    _handleClearClick();
  };
  onInit();
});
;
/**
 * @file
 */
jQuery(document).ready(function ($) {
    'use strict';
    adjustBannerMargin();
    // Open menu.
    $('.menu-bar-toggle').click(function () {
        $('.navbar-brand-list').addClass('resp-menu');
        $(".pfaffIpadOverlay").addClass("showPfaffIpadOverlay");
    });

    // Close menu.
    $('.hide-menu').click(function () {
        $('.navbar-brand-list').removeClass('resp-menu');
        $(".pfaffIpadOverlay").removeClass("showPfaffIpadOverlay");
        backToMegaMenu();
    });


    const pfaffUserName = $('.pfaff-user');
    const pfaffFindAstore = $('.find-a-store');
    // onhover of mini cart decrease opacity for user and find a store
    $('.header-ribbon-cart').on('mouseover', function () {
        pfaffUserName.addClass('changeNavOpacity');
        pfaffFindAstore.addClass('changeNavOpacity');
    })
    // onhover of mini cart increase opacity for user and find a store
    $('.header-ribbon-cart').on('mouseout', function () {
        pfaffUserName.removeClass('changeNavOpacity');
        pfaffFindAstore.removeClass('changeNavOpacity');
    })

    function readCookies(name) {
        return (
            (name = new RegExp(
                '(?:^|;\\s*)' +
                ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +
                '=([^;]*)'
            ).exec(document.cookie)) && name[1]
        );
    }
    $(document).on('click', '#backLink', function () {
        document.cookie =
            'accessoriesFinder=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        document.cookie = 'machineFinder=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        window.history.back();
    });
    function goBack() {
        document.cookie =
            'accessoriesFinder=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        document.cookie = 'machineFinder=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        window.history.back();
    }
    // Add breadcrum to plp page.
    var breadcrumElem = $('.header-fixed > .breadcrumb-list');
    var readaccessoriesFinderCookie = readCookies('accessoriesFinder');
    var readmachinesFinderCookie = readCookies('machineFinder');
    if (breadcrumElem.length) {
        var searchReferer = window.location.search.split('?')[1];
        var breadcrumbLink = '';
        if (
            searchReferer == 'search_referer=global_search' ||
            readaccessoriesFinderCookie ||
            readmachinesFinderCookie
        ) {
            breadcrumbLink =
                '<li><a id="backLink"> <i class="fas fa-arrow-left"></i>' +
                Drupal.t('Back to results') +
                '</a></li>';
            $(breadcrumElem).html(breadcrumbLink);
        } else {
            $(breadcrumElem).html($('.breadcrumb').html());
        }
        $('.breadcrumb').html('');
        if (!breadcrumElem.html().length) {
            breadcrumElem.remove();
        }
    }

    // Function to hide search autocomplete.
    $(window).scroll(function () {
        $('.search-api-autocomplete-search').hide();
    });

    // Close menu.
    $('.closeNav').click(function () {
        $('.navbar-brand-list').removeClass('resp-menu');
        // $(".navbar-brand-list").css({'width':'0px','right':'-999px'});
    });

    /*** Responsive filter.***/
    $(document).on('click', '#openNavFilter', function () {
        $('.desktop-filters').css({ width: '80%', left: '0%' });
    });
    $(document).on('click', '#closeNavFilter', function () {
        $('.desktop-filters').css({ width: '0%', left: '-100%' });
    });

    $(document).on('click', '#openNavSortBy', function () {
        $('.sortBy-mobile').find('.relevance-properties').animate({ right: '0%' });
    });
    $(document).on('click', '#closeNavSortBy', function () {
        $('.sortBy-mobile')
            .find('.relevance-properties')
            .animate({ right: '-100%' });
    });

    // Function to show search.
    var $myNavbarElem = $('#myNavbar');
    $('.nav-search-symbol').click(function () {
        $myNavbarElem.slideDown(300);
        var $navInput = $myNavbarElem.find('input.ui-autocomplete-input');
        $navInput.focus();
        if ($navInput[0]) {
            $navInput[0].selectionStart = $navInput[0].selectionEnd =
                $navInput.val().length;
        }
    });

    // //function to hide search
    $('.myNavbar-close').click(function () {
        $myNavbarElem.slideUp(300);
    });

    // Show count of filter results in plp,blog,category pages.
    if (
        $('.filter-results').find('.results').length &&
        $('.view-header').length
    ) {
        $('.filter-results').find('.results').text($('.view-header').text());
    }

    // Sort for projects page.
    var getSortingTypeProjects = getQueryStringValue('sort_bef_combine');
    if (
        getSortingTypeProjects === 'field_blog_date+ASC' ||
        getSortingTypeProjects === 'field_blog_date ASC' ||
        getSortingTypeProjects === 'title+ASC' ||
        getSortingTypeProjects === 'title ASC' ||
        getSortingTypeProjects === 'title+DESC' ||
        getSortingTypeProjects === 'title DESC' ||
        getSortingTypeProjects === 'field_blog_date+DESC' ||
        getSortingTypeProjects === 'field_blog_date DESC' ||
        getSortingTypeProjects === 'field_blog_date_DESC' ||
        getSortingTypeProjects === 'field_blog_date_ASC' ||
        getSortingTypeProjects === 'title_DESC' ||
        getSortingTypeProjects === 'title_ASC'
    ) {
        if (
            getSortingTypeProjects === 'field_blog_date+ASC' ||
            getSortingTypeProjects === 'field_blog_date ASC' ||
            getSortingTypeProjects === 'field_blog_date_ASC'
        ) {
            $('#project-blog-sort').val('field_blog_date_ASC');
        } else if (
            getSortingTypeProjects === 'title+ASC' ||
            getSortingTypeProjects === 'title ASC' ||
            getSortingTypeProjects === 'title_ASC'
        ) {
            $('#project-blog-sort').val('title_ASC');
        } else if (
            getSortingTypeProjects === 'title+DESC' ||
            getSortingTypeProjects === 'title DESC' ||
            getSortingTypeProjects === 'title_DESC'
        ) {
            $('#project-blog-sort').val('title_DESC');
        } else if (
            getSortingTypeProjects === 'field_blog_date+DESC' ||
            getSortingTypeProjects === 'field_blog_date DESC' ||
            getSortingTypeProjects === 'field_blog_date_DESC'
        ) {
            $('#project-blog-sort').val('field_blog_date_DESC');
        }
    }

    var getSortingBy = getQueryStringValue('sort_by'),
        getSortingByOrder = getQueryStringValue('sort_order'),
        $sortId = $('#search-sort');
    if (getSortingBy === 'title' || getSortingBy === 'field_blog_date') {
        if (getSortingBy === 'field_blog_date' && getSortingByOrder == 'ASC') {
            $sortId.val('field_blog_date ASC');
        } else if (
            getSortingBy === 'field_blog_date' &&
            getSortingByOrder == 'DESC'
        ) {
            $sortId.val('field_blog_date DESC');
        } else if (getSortingBy === 'title' && getSortingByOrder == 'DESC') {
            $sortId.val('title DESC');
        } else if (getSortingBy === 'title' && getSortingByOrder == 'ASC') {
            $sortId.val('title ASC');
        } else {
            $sortId.val('field_blog_date ASC');
        }
    }

    // Function to make filters open on page load based on selected facets in plp,blog,category pages.
    $('.common-props').each(function (index, element) {
        if (index == 0 && window.matchMedia('(min-width: 1024px)').matches) {
            $(this).find('.collapse').collapse('show');
        }
        $(element)
            .find('ul')
            .find('li')
            .each(function (ind, val) {
                var check = 0;
                if ($(val).find('input').is(':checked')) {
                    check++;
                    if (check > 0) {
                        $(this).closest('.common-props').find('.collapse').collapse('show');
                        $(this)
                            .closest('.common-props')
                            .find('.facets-soft-limit-link')
                            .click();
                    }
                    return false;
                }
            });
    });

    // Function to clear selected facets in plp,blog,category pages.
    $('.clear-btn').click(function () {
        window.location.href = window.location.href.split('?')[0];
    });

    $('.search-clear-btn').click(function () {
        window.location.href = window.location.href.split('&')[0];
    });
    $('.btn-cancel-order').on('click', function () {
        var orderNumber = '';
        if (drupalSettings.logged_in) {
            orderNumber = $(this).attr('data-order-number');
        }
        $('#cancel-order-return-request')
            .on('show.bs.modal', function () {
                $('.error-order-cancel').empty();
                $('#cancel_order_number,#cancel-order-comment,#cancel_reason').val('');
                $('.request-order-comment').hide();
                $('#cancel_order_number').val(orderNumber);
            })
            .modal('show');
    });
    $('#reason,#cancel_reason').change(function () {
        var sortValue = $(this).val();
        if (sortValue == 'Other') {
            $('.request-order-comment').show();
        } else {
            $('.request-order-comment').hide();
        }
    });

    $('.return-request').on('click', function (e) {
        e.preventDefault();
        $('#return-request')
            .on('show.bs.modal', function () {
                $('.error-order-cancel').empty();
                $('#first_name,#last_name,#order_number,#comment,#email,#reason').val(
                    ''
                );
                $('.request-order-comment').hide();
                $('#order_number').attr('data-order-number', '');
            })
            .modal('show');
    });

    $('.return-request-submit').on('click', function (e) {
        var submit = true;
        $(
            '.firstname-error,.lastname-error,.order-number-error,.comment-error,.email-error,.reason-error,.verify-email-error,.product-description-error'
        ).remove();
        var firstname = $('#first_name').val();
        var lastname = $('#last_name').val();
        var orderNumber = $('#order_number').val();
        var reason = $('#reason option:selected').val();
        var email = $('#email').val();
        var others = '';
        if (reason == 'Other') {
            others = $('#comment').val();
            var textLength = others.length;
            if (others.length > 0) {
                if (others.length > 256) {
                    $('#comment').after(
                        '<span class="error comment-error">' +
                        Drupal.t('Text should be less that 256 characters') +
                        '</span>'
                    );
                    submit = false;
                }
            } else {
                submit = false;
                $('#comment').after(
                    '<span class="error comment-error">' +
                    Drupal.t('Please provide your comment.') +
                    '</span>'
                );
            }
        }
        var product_description = $('#product_description').val();
        if (product_description.length > 0) {
            if (product_description.length > 256) {
                submit = false;
                $('#product_description').after(
                    '<span class="error product-description-error">' +
                    Drupal.t('Text should be less that 256 characters') +
                    '</span>'
                );
            }
        } else {
            submit = false;
            $('#product_description').after(
                '<span class="error product-description-error">' +
                Drupal.t('Please provide your Product Description.') +
                '</span>'
            );
        }
        var regex = /^[a-zA-Z\s]+$/;
        var orderNumberRegex = /^[0-9]+$/;
        var emailRegex =
            /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (!regex.test(firstname)) {
            $('#first_name').after(
                '<span class="error firstname-error">' +
                Drupal.t('This field can only contain alphabets') +
                '</span>'
            );
            submit = false;
        }
        if (!regex.test(lastname)) {
            $('#last_name').after(
                '<span class="error lastname-error">' +
                Drupal.t('This field can only contain alphabets') +
                '</span>'
            );
            submit = false;
        }
        if (!emailRegex.test(email)) {
            $('#email').after(
                '<span class="error email-error">' +
                Drupal.t('Invalid Email Address') +
                '</span>'
            );
            submit = false;
        }
        if (!orderNumberRegex.test(orderNumber)) {
            $('#order_number').after(
                '<span class="error order-number-error">' +
                Drupal.t('This field can only contain numbers') +
                '</span>'
            );
            submit = false;
        }
        if (reason.length == 0) {
            $('#reason').after(
                '<span class="error reason-error">' +
                Drupal.t('Please select the reason') +
                '</span>'
            );
            submit = false;
        }

        if (!submit) {
            e.preventDefault();
        } else {
            $.ajax({
                url: Drupal.url('get/return-request'),
                type: 'POST',
                data: {
                    first_name: firstname ? Drupal.checkPlain(firstname) : '',
                    last_name: lastname ? Drupal.checkPlain(lastname) : '',
                    order_number: orderNumber,
                    email: email ? Drupal.checkPlain(email) : '',
                    reason: reason,
                    others: Drupal.checkPlain(others),
                    product_description: Drupal.checkPlain(product_description),
                },
                dataType: 'json',
                beforeSend: function () {
                    document.getElementById('svp-loader').style.display = 'block';
                },
                complete: function () {
                    document.getElementById('svp-loader').style.display = 'none';
                },
                success: function (result) {
                    $('.error-order-cancel').empty();
                    if (result.response) {
                        $('.error-order-cancel').html(
                            Drupal.t(
                                'Success! Your Return Request has just been submitted. Look for an email from us with a Return Authorization and a UPS Shipping label which you will use to return your item. Please check your Spam or Junk folders if you do not receive our email within 30 minutes. Thank you for shopping Singer.com.'
                            )
                        );
                    } else {
                        $('.error-order-cancel').html(
                            Drupal.t(
                                'There is a problem in sending data. Please try again later.'
                            )
                        );
                    }
                },
            });
        }
    });

    $('.cancel-return-request-submit').on('click', function (e) {
        var submit = true;
        $('.cancel-comment-error,.reason-error').remove();

        var orderNumber = $('#cancel_order_number').val();
        var reason = $('#cancel_reason option:selected').val();
        var others = '';
        if (reason == 'Other') {
            others = $('#cancel-order-comment').val();
            var textLength = others.length;
            if (others.length > 0) {
                if (others.length > 1000) {
                    $('#comment').after(
                        '<span class="error cancel-comment-error">' +
                        Drupal.t('Text Length should be less that 1000 characters') +
                        '</span>'
                    );
                    submit = false;
                }
            } else {
                submit = false;
                $('#comment').after(
                    '<span class="error cancel-comment-error">' +
                    Drupal.t('Please provide your comment.') +
                    '</span>'
                );
            }
        }
        if (reason.length == 0) {
            $('#cancel_reason').after(
                '<span class="error reason-error">' +
                Drupal.t('Please select the reason') +
                '</span>'
            );
            submit = false;
        }
        if (!submit) {
            e.preventDefault();
        } else {
            $.ajax({
                url: Drupal.url('get/return-request'),
                type: 'POST',
                data: {
                    order_number: orderNumber,
                    reason: reason,
                    others: Drupal.checkPlain(others),
                },
                dataType: 'json',
                beforeSend: function () {
                    document.getElementById('svp-loader').style.display = 'block';
                },
                complete: function () {
                    document.getElementById('svp-loader').style.display = 'none';
                },
                success: function (result) {
                    $('.error-order-cancel').empty();
                    if (result.response) {
                        $('.error-order-cancel').html(
                            Drupal.t(
                                'Thank you for your feedback. Your order has been cancelled. Please check your email inbox for confirmation'
                            )
                        );
                        window.location.href = Drupal.url(
                            'user/order-cancel/' + result.response
                        );
                    } else {
                        $('.error-order-cancel').html(
                            Drupal.t(
                                'There is a problem in sending data. Please try again later.'
                            )
                        );
                    }
                },
            });
        }
    });

    var $thumbnailSlides = $(
        '.simpleLens-thumbnails-container-links .simpleLens-thumbnail-wrapper'
    );

    if ($thumbnailSlides.length) {
        var slide_index = 5;

        function nextSlide(n) {
            displaySlides((slide_index += n));
        }
        // Function currentSlide(n) {
        //     displaySlides(slide_index = n);
        // }.
        function displaySlides(n) {
            var i;
            if (n > $thumbnailSlides.length) {
                slide_index = 1;
            }
            if (n < 1) {
                slide_index = $thumbnailSlides.length;
            }
            for (i = 0; i < $thumbnailSlides.length; i++) {
                if (i < slide_index && slide_index - 5 <= i) {
                    $thumbnailSlides.eq(i).show();
                } else {
                    if ($(window).width() > 767) {
                        $thumbnailSlides.eq(i).hide();
                    }
                }
            }
            try {
                $thumbnailSlides.eq(0).is(':visible')
                    ? $('.product-top').addClass('visibility-hidden')
                    : $('.product-top').removeClass('visibility-hidden');
                $thumbnailSlides.eq([$thumbnailSlides.length - 1]).is(':visible')
                    ? $('.product-bottom').addClass('visibility-hidden')
                    : $('.product-bottom').removeClass('visibility-hidden');
            } catch (e) {
                // Swallow.
            }
        }

        $('.product-top').on('click', function () {
            nextSlide(-1);
        });

        $('.product-bottom').on('click', function () {
            nextSlide(1);
        });

        $(window).resize(function () {
            if ($(window).width() < 768) {
                $thumbnailSlides.show();
            }
        });
    }

    // Funtion to stop banner carousel on hover.
    $('#banner').carousel({
        pause: 'hover',
    });

    // Function to get offset position.
    if ($(window).width() >= 1024) {
        $('.header-list>li').hover(function () {
            $('.header-list>li').removeClass('right');
            var windowWidth = $(window).width();
            var offsetX = $(this).offset().left;
            if (windowWidth - offsetX < 400) {
                $(this).addClass('right');
            }
        });
    }
    var $searchResults = $('.view-global-search .view-header');
    if ($searchResults.length) {
        var $searchFilter = $('.search-results-filter').find('a.active');
        if ($searchFilter.length) {
            $searchFilter.text(
                $searchFilter
                    .text()
                    .replace('()', '(' + $searchResults.text().trim().split(' ')[0] + ')')
            );
        }
    }

    // Function to password-hide-show.
    $('.password-toggle').click(function () {
        if ($(this).text() == 'Show') {
            $(this).text('Hide');
            $(this)
                .closest('.input-group')
                .find('.form-control')
                .attr('type', 'text');
        } else {
            $(this).text('Show');
            $(this)
                .closest('.input-group')
                .find('.form-control')
                .attr('type', 'password');
        }
    });

    // Function for search click event.
    $('.support__search-form').on('submit', function (e) {
        e.preventDefault();
        var $supportSearch = $('.support__search'),
            inputValue = $('.support__model').val();
        $supportSearch.find('.alert').remove();
        if (!inputValue) {
            $supportSearch.prepend(
                '<div class="alert alert-danger">Please fill out the field.</div>'
            );
            setTimeout(function () {
                $supportSearch.find('.alert').remove();
            }, 3000);
            return false;
        }
        window.location.href = $(this).attr('action') + inputValue;
    });

    /*let skucode = 'EM200';
      //let skus = {"codes":["9960.BR","230106912","230051112","230098112","230130112","230115112","7258.CL","230125112","230011112","230134112","230003112","230061112","8763","230079112","230220112"]};
      let skus = {"codes":["9960.BR","230106912","230051112"]};
      let single = 1;
  
      getdata(skus);
  
      function getdata(skucodes) {
          console.log(skucodes);
          $.ajax({
              url: Drupal.url('get-product-images'),
              type: 'POST',
              data: {
                  "skucodes": skucodes
              },
              dataType: 'json',
              async: false,
              success: function (result) {
                  console.log(result);
              }
          });
      }*/

    // Function to redirect cart page on phones.
    $(document).on('click', '.cart-redirect', function () {
        var cartUrl = $(this).attr('data-url');
        window.location.href = cartUrl;
    });

    // Show orders in my-orders page.
    $(document).on('click', '.order-details', function () {
        $(this)
            .closest('.white-container')
            .find('.collapsed-order-details')
            .slideUp(100);
        $(this)
            .closest('.white-container')
            .find('.expanded-order-details')
            .slideDown(100);
    });

    // Close orders in my-orders page.
    $(document).on('click', '.close-order-details', function () {
        $(this)
            .closest('.white-container')
            .find('.expanded-order-details')
            .slideUp(100);
        $(this)
            .closest('.white-container')
            .find('.collapsed-order-details')
            .slideDown(100);
    });

    // Function to show sub-menu links.
    $(document).on('click touchend', '.navitem-arrow', function (e) {
        $('.navitem-arrow').not(this).closest('li').removeClass('submenu-active');
        if ($(this).closest('li').hasClass('submenu-active')) {
            $(this).closest('li').removeClass('submenu-active');
        } else {
            $(this).closest('li').addClass('submenu-active');
        }
        e.preventDefault();
    });

    $('.view-solr-search-products .pager__item a').on('click', function () {
        $('#svp-loader').show();
    });

    // Var getProductImagesCount = $('.simpleLens-thumbnails-container').find('a.simpleLens-thumbnail-wrapper').length();
    // if(getProductImagesCount > 5){
    //     $('.product-top,.product-bottom').show();
    // }
    // $('.fixed-ribbon .user-click, .user-click').on('click', function (e) {
    //     e.preventDefault();
    //     var $this = $(this),
    //         $fixedRibbon = $this.closest('.fixed-ribbon'),
    //         $closestList = $this.closest('li');
    //     $this.toggleClass('active');
    //     if ($this.hasClass('active')) {
    //         if ($(window).width() < 1025) {
    //             $fixedRibbon.addClass('show-user-dropdown');
    //         }
    //         $closestList.find('.global-tooltip').show();
    //     } else {
    //         $closestList.find('.global-tooltip').hide();
    //         $fixedRibbon.removeClass('show-user-dropdown');
    //     }
    // });
    // $(document).on('click', function (e) {
    //     if (
    //         $(e.target).closest('.user .global-tooltip').length === 0 &&
    //         !$(e.target).hasClass('user-click') &&
    //         !$(e.target).closest('user-click').length &&
    //         !$(e.target).hasClass('ribbon-caret')
    //     ) {
    //         $('.fixed-ribbon .user-click, .user-click').removeClass('active');
    //         $('.ribbon-items .global-tooltip').hide();
    //         $('.fixed-ribbon').removeClass('show-user-dropdown');
    //     }
    // });

    // // Hide function for search.
    // function checkWidth() {
    //     var windowWidth = $(window).width();
    //     if (windowWidth < 1025) {
    //         $('.search-desktop').remove();
    //     } else {
    //         $('.search-mobile').remove();
    //     }
    // }
    // checkWidth();
    // $(window).resize(checkWidth);

    // Function to sort blog project & learn.
    $('#search-sort').change(function () {
        var sortValue = $(this).val();
        if (sortValue) {
            sortBlogProjectLearn(sortValue);
        } else {
            window.location.href = window.location.href.split('?')[0];
        }
    });

    function sortBlogProjectLearn(sort_value) {
        var response = sort_value.split(' ');
        var uri = window.location.href;
        var key = 'sort_by';
        var value = response[0];
        uri = updateQueryStringParameter(uri, key, value);
        key = 'sort_order';
        value = response[1];
        uri = updateQueryStringParameter(uri, key, value);
        window.location.href = uri;
    }

    // Function to shop and search result projects.
    $('#project-blog-sort').change(function () {
        var sortValue = $(this).val();
        switch (sortValue) {
            case 'field_blog_date_ASC':
                sortbyDate('ASC');
                break;

            case 'title_ASC':
                sortbyTitleASC('ASC');
                break;

            case 'title_DESC':
                sortbyTitleDESC('DESC');
                break;

            case 'field_blog_date_DESC':
                sortbyDate('DESC');
                break;
        }
    });

    function sortbyDate(order) {
        var uri = window.location.href;
        var key = 'sort_bef_combine';
        var value = 'field_blog_date_' + order;
        uri = updateQueryStringParameter(uri, key, value);
        window.location.href = uri;
    }
    function sortbyTitleASC(order) {
        var uri = window.location.href;
        var key = 'sort_bef_combine';
        var value = 'title_' + order;
        uri = updateQueryStringParameter(uri, key, value);
        window.location.href = uri;
    }
    function sortbyTitleDESC(order) {
        var uri = window.location.href;
        var key = 'sort_bef_combine';
        var value = 'title_' + order;
        uri = updateQueryStringParameter(uri, key, value);
        window.location.href = uri;
    }

    // Get query params.
    function getQueryStringValue(key) {
        return decodeURIComponent(
            window.location.search.replace(
                new RegExp(
                    '^(?:.*[&\\?]' +
                    encodeURIComponent(key).replace(/[\.\+\*]/g, '\\$&') +
                    '(?:\\=([^&]*))?)?.*$',
                    'i'
                ),
                '$1'
            )
        );
    }

    // Update querystring.
    function updateQueryStringParameter(uri, key, value) {
        var re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i');
        var separator = uri.indexOf('?') !== -1 ? '&' : '?';
        if (uri.match(re)) {
            return uri.replace(re, '$1' + key + '=' + value + '$2');
        } else {
            return uri + separator + key + '=' + value;
        }
    }
    $(
        '#views-exposed-form-solr-search-products-page-1 input.form-autocomplete'
    ).keyup(function () {
        if ($(this).val().length >= 2) {
            $('.global-search-bar').removeAttr('disabled');
        } else {
            $('.global-search-bar').attr('disabled', 'disabled');
        }
    });

    //adjust banner margin
    function adjustBannerMargin() {
        let promotionalBannerPrevBtn = $('.carousel-control-prev');
        let promotionalBannerNextBtn = $('.carousel-control-next');
        let promotionalBannerRowItems = $(
            '.promotional-banner .carousel-inner .item'
        );
        const pfaffSearchFlydown = $('.global-search-wrapper');
        const headerMarginLeft = parseInt(
            $('.navbar-section-container').css('marginLeft')
          );
        if (promotionalBannerRowItems && promotionalBannerRowItems.length === 1) {
            promotionalBannerNextBtn.hide();
            promotionalBannerPrevBtn.hide();
        }
        // if (window.innerWidth >= 920) {
        //   const headerMarginLeft = parseInt(
        //     $('.navbar-section-container').css('marginLeft')
        //   );
        //   $('.banner-content').css('marginLeft', headerMarginLeft + 'px');
        //   promotionalBannerNextBtn.css('right', headerMarginLeft + 'px');
        //   promotionalBannerPrevBtn.css('left', headerMarginLeft + 'px');
        // } else {
        //   $('.banner-content').css('marginLeft', 0 + 'px');
        //   promotionalBannerNextBtn.css('right', 0 + 'px');
        //   promotionalBannerPrevBtn.css('left', 0 + 'px');
        // }
        if(window.innerWidth >= 920) {
            pfaffSearchFlydown.css('padding-left', headerMarginLeft + 15 + 'px');
            pfaffSearchFlydown.css('padding-right', headerMarginLeft + 15 + 'px');
        }
    }

    // adding no-scroll class when megamenu is open
    let bodyElem = $('body');
    let mainNavList = $('.navbar-brand-list');
    let navItemElemArr = $('.navbar-nav .main-nav-list-item');
    let navbarToggleElem = $('.navbar-toggle');
    let hideMenuElem = $('.hide-menu');

    navbarToggleElem.on('click', function () {
        bodyElem.addClass('no-scroll');
        mainNavList.addClass('show-main-navbar');
    });
    hideMenuElem.on('click', function () {
        bodyElem.removeClass('no-scroll');
        mainNavList.removeClass('show-main-navbar');
    });

        navItemElemArr.on('mouseover', function () {
            const headerMarginLeft =
                parseInt($('.navbar-section-container').css('marginLeft')) + 11;
                // $(this).children('ul').css('paddingRight', 'calc(' + headerMarginLeft + 'px' + ' - 2%)');
            if (window.innerWidth > 1200) {
                // $(this)
                //     .children('ul')
                //     .css('paddingLeft', headerMarginLeft + 'px');
                // $(this)
                //     .children('ul')
                //     .css('paddingRight', headerMarginLeft + 'px');
                    $(this).children('ul').css('paddingRight', 'calc(' + headerMarginLeft + 'px' + ' - 2%)');
                    $(this).children('ul').css('paddingLeft', 'calc(' + headerMarginLeft + 'px' + ' - 2%)');
            } else {
                $(this)
                    .children('ul')
                    .css('paddingLeft', 0 + 'px');
                $(this)
                    .children('ul')
                    .css('paddingRight', 0 + 'px');
            }
        });
        navItemElemArr.on('mouseout', function () {
            navItemElemArr.find('ul');
        });

    function backToMegaMenu() {
        $('.back-close-active-submenu').remove();
        $('.back-to-mega-menu').hide();
        $('.pfaff-mobile-links').removeClass('hideMobileLinks');
        $("#smLanguageSelector").removeClass("hideMobileLinks");
        navItemElemArr.each(function (index, element) {
            $(element).removeClass('pfaff-mobile-menu');
            $(element).addClass('hide-pfaff-mobile-menu');
            $(element).removeClass('submenu-active');
            $(element).show();
        });
    }

    $('.back-close-active-submenu').on('click', function (e) {
        e.stopPropagation();
        backToMegaMenu();
    });
    $('.back-to-mega-menu').on('click', function () {
        backToMegaMenu();
    });

    $('.navbar-nav .main-nav-list-item')
        .children('.nav-link')
        .on('click touchstart', function (e) {
            let windowWidth = $(window).width(),
                mainBackToMenu = $('.back-to-mega-menu'),
                flydownMenu = $(this).siblings('ul'),
                smLanguageSelector = $("#smLanguageSelector"),
                pfaffMobileLinks = $('.pfaff-mobile-links');

            if (windowWidth < 1201) {
                e.preventDefault();
                $(this).closest('.main-nav-list-item').removeClass('hide-pfaff-mobile-menu');
        $(this).closest('.main-nav-list-item').addClass('pfaff-mobile-menu');
                mainBackToMenu.show();
                smLanguageSelector.addClass('hideMobileLinks');
                pfaffMobileLinks.addClass('hideMobileLinks');
                $(this).parent().addClass('submenu-active');
                if ($('.back-close-active-submenu').length) {
                    // do nothing
                } else {
                    $(
                        `<a class='back-close-active-submenu'><span>&#10094;</span><span>Back</span></a>`
                    )
                        .appendTo(flydownMenu)
                        .on('click', function (e) {
                            e.stopPropagation();
                            backToMegaMenu();
                        });
                }
                navItemElemArr.each(function (index, element) {
                    if (!$(element).hasClass('submenu-active')) {
                        $(element).hide();
                    }
                });
            }
        });


    // Appending Checkout modal to Body
    $('.proceed-checkout-modal').appendTo('body');
    $('.pdp-convenient-modal').appendTo('body');
});

!(function (window) {
    var $q = function (q, res) {
        if (document.querySelectorAll) {
            res = document.querySelectorAll(q);
        } else {
            var d = document,
                a = d.styleSheets[0] || d.createStyleSheet();
            a.addRule(q, 'f:b');
            for (var l = d.all, b = 0, c = [], f = l.length; b < f; b++) {
                l[b].currentStyle.f && c.push(l[b]);
            }

            a.removeRule(0);
            res = c;
        }
        return res;
    },
        addEventListener = function (evt, fn) {
            window.addEventListener
                ? this.addEventListener(evt, fn, false)
                : window.attachEvent
                    ? this.attachEvent('on' + evt, fn)
                    : (this['on' + evt] = fn);
        },
        _has = function (obj, key) {
            return Object.prototype.hasOwnProperty.call(obj, key);
        };

    function loadImage(el, fn) {
        var img = new Image(),
            src = el.hasAttribute('data-imgSrc')
                ? el.getAttribute('data-imgSrc')
                : '';

        img.onload = function () {
            if (!!el.parent) {
                el.parent.replaceChild(img, el);
            } else {
                el.src = src;
                el.removeAttribute('data-imgSrc');
            }

            fn ? fn() : null;
        };
        img.src = src;
    }

    function elementInViewport(el) {
        var rect = el.getBoundingClientRect();

        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.top <= (window.innerHeight || document.documentElement.clientHeight)
        );
    }

    var images = new Array(),
        query = $q('img.images-lazyload'),
        processScroll = function () {
            for (var i = 0; i < images.length; i++) {
                if (elementInViewport(images[i])) {
                    loadImage(images[i], function () {
                        images.splice(i, i);
                    });
                }
            }
        };
    // Array.prototype.slice.call is not callable under our lovely IE8.
    for (var i = 0; i < query.length; i++) {
        images.push(query[i]);
    }

    processScroll();
    addEventListener('scroll', processScroll);
})(this);
;
$(document).ready(function () {
  const $loader = $('#pfaff-loader'),
    $body = $('body'),
    $loginModal = $('.wishlist-anonymous-popup'),
    $wishListModal = $('.wishlist-container');
  // LOOKUP_API =
  //   'https://dev01-cortex-gw.ep-dev.ep-singer.com/cortex/items/pfaffus/lookups/form?followlocation&zoom=addtowishlistform',
  // GET_ALL_WISHLIST_ITEMS =
  //   'https://dev01-cortex-gw.ep-dev.ep-singer.com/cortex/wishlists/pfaffus/default?zoom=lineitems:element,lineitems:element:item:code';

  var $wishListModalImg = $wishListModal.find('.product-img'),
    $wishListModalName = $wishListModal.find('.product-name'),
    $wishListModalIcon = $wishListModal.find('.wishlist-icon'),
    $wishListModalText = $wishListModal.find('.cart-header'),
    isLoggedIn = false,
    AUTH_TOKEN = '',
    LOOKUP_API = '',
    GET_ALL_WISHLIST_ITEMS = '';

  function showLoader() {
    $loader.show();
    $body.addClass('no-scroll');
  }

  function hideLoader() {
    $loader.hide();
    $body.removeClass('no-scroll');
  }

  function toggleLoginModal(val) {
    if (val) {
      $body.addClass('no-scroll');
      $loginModal.removeClass('in-active').addClass('active');
    } else {
      $body.removeClass('no-scroll');
      $loginModal.removeClass('active').addClass('in-active');
    }
  }

  function toggleWishListModal(val, $targetEle) {
    const imgSrc = $targetEle.attr('product-img-src'),
      productName = $targetEle.attr('data-product-name');

    $wishListModalImg.attr('src', imgSrc);
    $wishListModalName.text(productName);

    if (val) {
      $wishListModalIcon.attr('src', $wishListModal.data('added-icon'));
      $wishListModalText.text($wishListModal.data('added-text'));
    } else {
      $wishListModalIcon.attr('src', $wishListModal.data('removed-icon'));
      $wishListModalText.text($wishListModal.data('remove-text'));
    }
    $body.addClass('no-scroll');
    $wishListModal.removeClass('in-active').addClass('active');
  }

  function addToWishlist(wishlistAPI) {
    return new Promise((resolve, reject) => {
      $.ajax({
        url: wishlistAPI,
        dataType: 'json',
        contentType: 'application/json',
        type: 'POST',
        async: true,
        headers: { Authorization: AUTH_TOKEN },
        success: (resp) => {
          resolve(resp);
        },
        error: (err) => {
          reject(err);
        },
      });
    });
  }

  function getAddToWishListLink(apiEndPoint, skuCode) {
    return new Promise((resolve, reject) => {
      $.ajax({
        url: apiEndPoint,
        dataType: 'json',
        contentType: 'application/json',
        type: 'POST',
        async: true,
        headers: { Authorization: AUTH_TOKEN },
        data: JSON.stringify({ code: skuCode }),
        success: (resp) => {
          var Wishlistlink = '';
          resp.links.filter((link) => {
            if (link.rel === 'addtowishlistform') {
              Wishlistlink = link.href + '?followlocation';
            }
          });
          resolve(Wishlistlink);
        },
        error: (err) => {
          reject(err);
        },
      });
    });
  }

  function getRemoveProductWishlistLink(apiEndPoint, skuCode) {
    return new Promise((resolve, reject) => {
      $.ajax({
        url: apiEndPoint,
        dataType: 'json',
        contentType: 'application/json',
        type: 'GET',
        async: true,
        headers: { Authorization: AUTH_TOKEN },
        success: (resp) => {
          var removeItemLink = '',
            allItems = resp._lineitems[0]._element;
          allItems.forEach((item, index) => {
            if (parseInt(item._item[0]._code[0].code) === skuCode) {
              removeItemLink = allItems[index].self.href;
            }
          });
          resolve(removeItemLink);
        },
        error: (err) => {
          reject(err);
        },
      });
    });
  }

  function deleteProductWishlist(deleteAPI) {
    return new Promise((resolve, reject) => {
      $.ajax({
        url: deleteAPI,
        dataType: 'json',
        contentType: 'application/json',
        type: 'DELETE',
        async: true,
        headers: { Authorization: AUTH_TOKEN },
        success: (resp) => {
          resolve(true);
        },
        error: (jqXhr, textStatus, errorMessage) => {
          reject(errorMessage);
        },
      });
    });
  }

  function getSkuCode(event) {
    return $(event.target).data('ep-reference');
  }

  function getCookieValue(name) {
    return (
      document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() ||
      ''
    );
  }

  function addEventListener() {
    isLoggedIn = getCookieValue('drupal_ep_mail') !== '' ? true : false;

    isLoggedIn
      ? (AUTH_TOKEN = 'bearer ' + getCookieValue('drupal_ep_token'))
      : (AUTH_TOKEN = '');

    LOOKUP_API = $('.cards-carousel').data('wishlist-lookup');
    GET_ALL_WISHLIST_ITEMS = $('.cards-carousel').data('all-wishlist-item');

    $(document).on('click', '.js-wishlist-icon', (event) => {
      const skuCode = getSkuCode(event),
        $targetEle = $(event.target),
        $cardParent = $(event.target).parent(),
        method = $(event.target).data('method'),
        skuCodeObj = {};
        skuCodeObj[skuCode] = skuCode;
        var commerceUrl = $("#global-search").data("shop-domain");
        if(!commerceUrl) {
          commerceUrl = $(event.target).parents('.content').find('.main-content>a').attr('href');
          commerceUrl = commerceUrl.split('/');
          commerceUrl = commerceUrl[0]+'//'+commerceUrl[2];  
        }
        
      if (AUTH_TOKEN != null && AUTH_TOKEN != '') {
        showLoader();
        //   Add to wishList
        if (method === 'add') {
          getAddToWishListLink(LOOKUP_API, skuCode)
            .then((Wishlistlink) => {
              addToWishlist(Wishlistlink)
                .then((resp) => {
                  $cardParent.addClass('isFav');
                  hideLoader();
                  toggleLoginModal(false);
                  toggleWishListModal(true, $targetEle);
                  $.ajax({
                    url: commerceUrl+'/api/products-info',
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'POST',
                    headers: { Authorization: AUTH_TOKEN },
                    data: JSON.stringify({"skus" : skuCodeObj}),
                    success: (resp) => {
                      dataLayer.push({ ecommerce: null });
                      dataLayer.push({
                        event: "add_to_wishlist",
                        ecommerce: getProductData(resp[0])
                      })
                    },
                  })
                  
                })
                .catch((err) => {
                  window.alert('Not defined');
                  hideLoader();
                });
            })
            .catch((err) => {
              window.alert(err);
              hideLoader();
            });
        } else if (method === 'remove') {
          getRemoveProductWishlistLink(GET_ALL_WISHLIST_ITEMS, skuCode)
            .then((removeProductLink) => {
              deleteProductWishlist(removeProductLink)
                .then((resp) => {
                  $cardParent.removeClass('isFav');
                  hideLoader();
                  toggleLoginModal(false);
                  toggleWishListModal(false, $targetEle);
                })
                .catch((errMessage) => {
                  hideLoader();
                  window.alert(errMessage);
                });
            })
            .catch((err) => {
              window.alert('Get Remove API error');
              hideLoader();
            });
        } else {
          console.log('No method defined');
        }
      } else {
        //   Else show modal for login
        $wishListModal.removeClass('active').addClass('in-active');
        toggleLoginModal(true);
      }
    });

    $(document).on('click', '.wishlist-modal .remove', (event) => {
      event.stopPropagation();
      $(event.target)
        .parents('.wishlist-modal')
        .removeClass('active')
        .addClass('in-active');

      $body.removeClass('no-scroll');
    });
  }
  addEventListener();


  function getProductData(data) {
    var item = {
      currency: data.currency,
      value: data.list_price,
      item_id: data.sku,
      item_name: data.title,
      affiliation: "PFAFF Store",
      coupon: data.coupon || "",
      discount: data.sale_price ? data.list_price - data.sale_price : 0,
      index: 0,
      item_brand: "PFAFF",
      item_category: data.category,
      price: data.sale_price || data.list_price,
      quantity: 1
    };
    var categories = data.sub_category.split(',');
    categories.forEach((el, index) => {
      var count = index+2
      item['item_category'+count] = el.trim();
    })
    return {
      items: [
        item
      ],

    }

    
  }
});
;
$(document).ready(function () {
    var regionContHeight = 0;
    var mobileScreenSize = 1060;

    function onLanguageSelectorToggle(selector, optionSelector, captureHeight) {
        $("." + selector).on("click keydown", function (event) {
            event.stopPropagation();
            $(".el-hover").removeClass("el-hover");
            if (
                event.type !== "keydown" ||
                (event.type === "keydown" && event.keyCode === 13)
            ) {
                $("." + optionSelector).toggleClass("d-none");
                if (captureHeight && regionContHeight <= 0) {
                    regionContHeight = $(".language-options").height();
                }
                if (window.innerWidth < mobileScreenSize) {
                    $(".arrow-btn").toggleClass("dropdown-opened");
                }
            }
        });
    }

    /**
     * For Desktop
     */
    var _setContainerHeight = function () {
        $(".country-column li").on({
            click: function (event) {
                $(this).siblings().removeClass("el-hover");
                if (window.innerWidth >= mobileScreenSize) {
                    $(".language-options").height("unset");
                    event.stopImmediatePropagation();
                    var languageContHeight = $(this).find(".language-column").height();
                    if (regionContHeight < languageContHeight) {
                        $(".language-options").height(languageContHeight);
                    }
                    $(this).addClass("el-hover");
                }
            },
        });

        $(".region-options>li").on({
            click: function (event) {
                $(this).siblings().removeClass("el-hover");
                if (window.innerWidth >= mobileScreenSize) {
                    $(".language-options").height("unset");
                    event.stopImmediatePropagation();
                    $(".country-options li.el-hover").removeClass("el-hover");
                    event.stopImmediatePropagation();
                    var countryContHeight = $(this).find(".country-column").height();
                    if (regionContHeight < countryContHeight) {
                        $(".language-options").height(countryContHeight);
                    }
                    $(this).addClass("el-hover");
                }
            },
        });
    };

    var _closeOnOutsideClick = function () {
        $(document).on("click", function (evt) {
            if (window.innerWidth >= mobileScreenSize) {
                if (
                    !$(".language-options").hasClass("d-none") &&
                    !$(evt.target).parents(".language-options").length
                ) {
                    $(".language-options").addClass("d-none");
                }
            }
        });
    };

    /**
     * ends here
     */

    var _onSelection = function () {
        $(".menu-list>li").on("click", function (event) {
            if (window.innerWidth < mobileScreenSize) {
                var selectedValue = $(this).children("a").text();
                var clickedElementParent = $(this).parent(".menu-list");
                $(this)
                    .parent(".menu-list")
                    .siblings(".title")
                    .children(".selected-language-value")
                    .text(selectedValue)
                    .css("color", "#222");
                $(this)
                    .parent(".menu-list")
                    .siblings(".title")
                    .children(".selected-language-value")
                    .text(selectedValue);
                $(this)
                    .parent(".menu-list")
                    .siblings(".title")
                    .children(".selected-language-value")
                    .text(selectedValue);
                if (clickedElementParent.hasClass("region-options")) {
                    console.log("Region clicked");
                    $(".region-options>li").addClass("d-none");
                    $(".country-column").addClass("d-block");
                    $(".country-options>li").removeClass("d-none");
                    $(".region-options").addClass("no-box-shadow");
                    $(".country-options").removeClass("no-box-shadow");
                } else if (clickedElementParent.hasClass("country-options")) {
                    $(".country-options>li").addClass("d-none");
                    $(".language-column").addClass("d-block");
                    $(".lang-options>li").removeClass("d-none");
                    $(".country-options").addClass("no-box-shadow");
                } else if (clickedElementParent.hasClass("lang-options")) {
                    $(".lang-options>li").addClass("d-none");
                }

                $(this).removeClass("d-none").addClass("selected-option");
                event.stopPropagation();
            }
        });
    };

    var _onSelectedOptionClick = function () {
        $(".title").on("click", function () {
            if (window.innerWidth < mobileScreenSize) {
                var siblingEl = $(this).siblings(".menu-list");
                // siblingEl.removeClass("no-box-shadow");
                if (siblingEl.hasClass("region-options")) {
                    $(".country-column").removeClass("d-block");
                    $(".language-column").removeClass("d-block");
                    $(".region-options>li").removeClass("d-none selected-option");
                    $(".region-options").removeClass("no-box-shadow");
                } else if (siblingEl.hasClass("country-options")) {
                    $(".language-column").removeClass("d-block");
                    $(".country-options>li").removeClass("d-none selected-option");
                    $(".country-options").removeClass("no-box-shadow");
                } else if (siblingEl.hasClass("lang-options")) {
                    $(".lang-options>li").removeClass("d-none selected-option");
                }

                // $("li").removeClass('selected-option');
            }
        });
    };

    var _showlanguageSelector = function () {
        if (window.innerWidth < 1060) {
            // $("#lgLanguageSelector").remove();
            $("#lgLanguageSelector").css('display', 'none');
            $("#smLanguageSelector").css('display', 'block');
        } else {
            // $("#smLanguageSelector").remove();
            $("#lgLanguageSelector").css('display', 'block');
            $("#smLanguageSelector").css('display', 'none');
        }
    };

    // Add a listener for when the window resizes
    window.addEventListener('resize', _showlanguageSelector);



    var _init = function () {
        _showlanguageSelector();
        _setContainerHeight();
        onLanguageSelectorToggle("language-dropdown-selector", "language-options", true);
        _closeOnOutsideClick();
        /**
         * for Mobile devices
         */
        _onSelection();
        _onSelectedOptionClick();
    };

    _init();

    /**
     * Reset language selector properties on window resize
     */

    $(window).resize(function () {
        var width = window.innerWidth;
        if (width < mobileScreenSize) {
            $(".language-options").height("auto");
        } else {
            $(".menu-list li").removeClass("d-none selected-option");
            $(".region-column, .country-column, .language-column").removeClass(
                "d-block"
            );
            $(".arrow-btn").removeClass("dropdown-opened");
            $(".language-options").addClass("d-none");
        }
    });

    /**
     * For keyboard accessibility
     */

    $(".menu-list li a").on("keydown", function (evt) {
        if (evt.keyCode === 13) {
            $(".menu-list li").attr("aria-expanded", false);
            $(this).parent("li").addClass("el-hover").attr("aria-expanded", true);
        } else if (evt.keyCode === 27) {
            $(".language-options").addClass("d-none");
            $(".menu-list li").attr("aria-expanded", false);
        }
    });
    function getCookieValue(name) {
        return (
            document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() ||
            ''
        );
    }
    $(".handleLanguageClick").on("click", function (e) {
        e.preventDefault();
        const langFormData = {
            lang: $(e.target).data("languageId"),
            country: $(e.target).data("countryId"),
            pageLink: $(e.target).data("currentPageId"),
        };
        var epslang = getCookieValue('country');
        var userLoggedIn = getCookieValue('drupal_ep_mail');
        if ($(e.target).data("countryId") != epslang && userLoggedIn != null && userLoggedIn != "") {
            $.ajax({
                type: "POST",
                url: "/PFAFFHeaderBlock/LogOut",
                success: function (response) {
                    $.ajax({
                        type: "POST",
                        url: "/PFAFFHeaderBlock/ChangeLanguage",
                        data: langFormData,
                        success: function (response) {
                            window.location = response;
                        },
                        error: function (err) {
                            console.error(err);
                            // hides loader
                            $("#pfaff-loader").hide();
                        },
                    });
                },
                error: function (err) {
                    console.error(err);
                    // hides loader
                    $("#pfaff-loader").hide();
                },
            });
        }
        else {
            if ($(e.target).data("countryId") != epslang) {
                $.cookie("drupal_ep_token", null, { path: '/' });
                $.removeCookie("drupal_ep_token", { path: '/' });
                $.removeCookie("drupal_ep_token", { path: '/', domain: 'pfaff.com' });
            }
            $.ajax({
                type: "POST",
                url: "/PFAFFHeaderBlock/ChangeLanguage",
                data: langFormData,
                success: function (response) {
                    window.location = response;

                },
                error: function (err) {
                    console.error(err);
                    // hides loader
                    $("#pfaff-loader").hide();
                },
            });
        }
    });
});
;
class FormValidator {
  config;
  formValues = {};
  constructor(config) {
    this.config = config;
    if (config.validateOnInput) {
      for (const identifier in this.config.validationRules) {
        $(`#${identifier}`).on("input", () => {
          $(`#${this.config.formIdentifier} #${identifier}`)
            .siblings(this.config.errMsgClass)
            .addClass("d-none");
          const validator = {};
          validator[identifier] = this.config.validationRules[identifier];
          this.validate(validator);
        });
      }
    }
  }
  validate(validationRules) {
    let hasError = false;
    for (const identifier in validationRules) {
      if (validationRules.hasOwnProperty(identifier)) {
        let element = $(`#${identifier}`);
        this.formValues[identifier] = element.val() ? element.val().trim() : "";
        for (let i = 0; i < validationRules[identifier].length; i++) {
          let err = this.getFormValidations()[
            validationRules[identifier][i]["validator"]
          ](element, validationRules[identifier][i]);
          if (err) {
            hasError = err;
            break;
          }
        }
      }
    }
    return { hasError: hasError, formValues: this.formValues };
  }
  getFormValidations() {
    return {
      required: function (element, validation) {
        const value = element.val();
        if (!(value && value.trim())) {
          this.showErrorMessage(element);
          return true;
        } else {
          this.hideErorMsg(element);
        }
      },
      number: function (element, validation) {
        const value = element.val();
        const regEx = /^\d+$/;
        if (!regEx.test(value)) {
          this.showErrorMessage(element);
          return true;
        } else {
          this.hideErorMsg(element);
        }
      },
      minlength: function (element, validation) {
        const value = element.val();
        if (value.trim().length < validation.minlength) {
          this.showErrorMessage(element);
          return true;
        } else {
          this.hideErorMsg(element);
        }
      },
      maxlength: function (element, validation) {
        const value = element.val();
        if (value.trim().length > validation.maxlength) {
          this.showErrorMessage(element);
          return true;
        } else {
          this.hideErorMsg(element);
        }
      },
      pattern: function (element, validation) {
        const value = element.val();
        if (!validation.pattern.test(value.trim())) {
          this.showErrorMessage(element);
          return true;
        } else {
          this.hideErorMsg(element);
        }
      },
      showErrorMessage: function (element) {
        element.addClass("has-error");
        element.siblings("span").removeClass("d-none");
      },
      hideErorMsg: function (element) {
        element.removeClass("has-error");
        element.siblings("span").addClass("d-none");
      },
    };
  }
}
/*
 * Launch landing page js
 */
$(document).ready(function () {
  const mysewnetUrl = $(".pfaff-form").data("mysewnetUrl"),
    countryListURL = mysewnetUrl + "Country/GetIsoCountryList",
    getCitiesURL = "Machines/GetCities?countryCode=",
    getDialCodesURL = $(".pfaff-form").data("dial-code-api");

  function showLoader() {
    $("#pfaff-loader").show();
    $("body").addClass("no-scroll");
  }

  function hideLoder() {
    $("#pfaff-loader").hide();
    $("body").removeClass("no-scroll");
  }

  function handleCountrySearch() {
    let debounceTimer;
    $("#countrySearch").keydown(function (e) {
      var targetEle = $(e.target);
      clearTimeout(debounceTimer);
      debounceTimer = setTimeout(function () {
        showLoader();
        var countryList = $("#countryListWrapper li.countries-list-item"),
          searchedText = targetEle.val().toLowerCase();
        if (countryList.length > 0 && searchedText) {
          countryList.each(function () {
            var countryName = $(this).data("countryName").toLowerCase();
            if (countryName.indexOf(searchedText) > -1) {
              $(this).css("display", "block");
            } else {
              $(this).css("display", "none");
            }
            hideLoder();
          });
        } else {
          countryList.css("display", "block");
          hideLoder();
        }
      }, 400);
    });
  }

  $("#productCountry").on("show.bs.dropdown", function () {
    const $ele = $("#countrySearch"),
      countryList = $("#countryListWrapper li.countries-list-item"),
      $showSearchField = $(".country-search-input-wrapper");
    if ($ele.length && $showSearchField.length) {
      $ele.val("");
      countryList.css("display", "block");
    }
  });

  function getCountries(showSearchField = false) {
    var countryOptions = "",
      $countryList = $("#countryListWrapper"),
      countrylabel = $("#countryMenuBtn").data("countryLabel");
    showLoader();
    if (showSearchField) {
      countryOptions +=
        "<li class='country-search-input-wrapper'><input type='text' value='' id='countrySearch' class='country-search-input' placeholder=" +
        countrylabel +
        " /></li>";
    }
    $.ajax({
      url: countryListURL,
      dataType: "json",
      contentType: "application/json",
      type: "GET",
      async: true,
      success: (res) => {
        if (res && res.length) {
          res.forEach((element) => {
            countryOptions += `<li class='countries-list-item' data-country-name="${element.countryName}"><a href="#" data-selected-value = "${element.alpha2Code}" class="dropdown-item pfaff-custom-dropdown__item">${element.countryName}</a></li>`;
          });
          $countryList.html(countryOptions);
          if (showSearchField) {
            handleCountrySearch();
          }
          hideLoder();
        }
      },
      error: (err) => {
        console.log(err);
        hideLoder();
      },
    });
  }
  /**
   * Get city dropdown value on country selection
   */
  function onCountrySelection() {
    $("#country").on("change", function () {
      var value = $(this).val() || "IN",
        cityOptions = "",
        $cityList = $("#cityListWrapper");

      if (value == null || value == "") return;
      showLoader();
      $.ajax({
        url:
          "/PFAFFDealerLocatorPage/CallMysewnetApi?url=" + getCitiesURL + value,
        dataType: "json",
        contentType: "application/json",
        type: "GET",
        async: true,
        success: (res) => {
          if (res && res.length) {
            var city = "";
            res.forEach((element) => {
              if (element.u_city != city) {
                city = element.u_city;
                cityOptions += `<li> <a href="#" data-selected-value = "${element.u_city}" class="dropdown-item pfaff-custom-dropdown__item">${element.u_city}</a></li>`;
              }
            });
            $cityList.html(cityOptions);
            hideLoder();
          }
        },
        error: (err) => {
          console.log(err);
          hideLoder();
        },
      });
    });
  }
  /**
   * Get preferred dealer dropdown value on city selection
   */
  function onCitySelection() {
    $("#city").on("click", function () {
      var country = $("#country").val(),
        city = $(this).val(),
        dealerOptions = "",
        $dealerList = $("#dealerListWrapper");
      if (city == null || city == "") return;
      showLoader();
      let urldealer =
        "/PFAFFDealerLocatorPage/CallMysewnetApi?url=Machines/GetShopsWithEmail?countryCode=" +
        country +
        "%26city=" +
        city;
      $.ajax({
        url: urldealer,
        dataType: "json",
        contentType: "application/json",
        type: "GET",
        async: true,
        success: (res) => {
          if (res && res.length) {
            res.forEach((element) => {
              dealerOptions += `<li><a href="#" data-selected-value = "${element.u_shop_name}" data-selected-dealer-email= "${element.eMailaddress}" class="dropdown-item pfaff-custom-dropdown__item">${element.u_shop_name}</a></li>`;
            });
            $dealerList.html(dealerOptions);
            hideLoder();
          }
        },
        error: (err) => {
          console.log(err);
          hideLoder();
        },
      });
    });
  }
  /**
   * Form Validation
   */
  let productLaunchForm, contactForm, contactFormNA;
  const emailRegex = /^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+[.][a-zA-Z]{2,6}$/;
  const productLaunchFormConfig = {
      formIdentifier: "launchLandingPage",
      validateOnInput: true,
      errMsgClass: ".error-msg",
      validationRules: {
        firstName: [
          {
            validator: "required",
          },
        ],
        lastName: [
          {
            validator: "required",
          },
        ],
        email: [
          {
            validator: "required",
          },
          {
            validator: "pattern",
            pattern: emailRegex,
          },
        ],
        // phoneNumber: [
        //   {
        //     validator: "required",
        //   },
        //   {
        //     validator: "number",
        //   },
        // ],
        country: [
          {
            validator: "required",
          },
        ],
        city: [
          {
            validator: "required",
          },
        ],
        preferredDealer: [
          {
            validator: "required",
          },
        ],
        preferredDealerEmail: [
          {
            validator: "required",
          },
        ],
        // toemailaddress: [
        //   {
        //     validator: "required",
        //   },
        // ],
        // fromemailaddress: [
        //   {
        //     validator: "required",
        //   },
        // ],
        // senderemailpassword: [
        //   {
        //     validator: "required",
        //   },
        // ],
      },
    },
    contactFormConfig = {
      formIdentifier: "contactUsForm",
      validateOnInput: false,
      errMsgClass: ".error-msg",
      validationRules: {
        fullName: [
          {
            validator: "required",
          },
        ],
        email: [
          {
            validator: "required",
          },
          {
            validator: "pattern",
            pattern: emailRegex,
          },
        ],
        country: [
          {
            validator: "required",
          },
        ],
        countryEmail: [
          {
            validator: "required",
          },
        ],
        description: [
          {
            validator: "required",
          },
        ],
      },
    },
    contactUsFormNAConfig = {
      formIdentifier: "contactUsFormNA",
      validateOnInput: false,
      errMsgClass: ".error-msg",
      validationRules: {
        subject: [
          {
            validator: "required",
          },
        ],
        description: [
          {
            validator: "required",
          },
        ],
        email: [
          {
            validator: "required",
          },
          {
            validator: "pattern",
            pattern: /^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+[.][a-zA-Z]{2,6}$/,
          },
        ],

        "00N4W00000SC7ef": [
          {
            validator: "required",
          },
        ],
        //phone: [
        //  {
        //    validator: "required",
        //  },
        //  {
        //    validator: "number",
        //  },
        //],
        "00N4W00000SC7ei": [
          {
            validator: "required",
          },
        ],
        orgid: [
          {
            validator: "required",
          },
        ],
        recordType: [
          {
            validator: "required",
          },
        ],
        retURL: [
          {
            validator: "required",
          },
        ],
      },
    };

  //OnSubmit Handler for the prefered dealer form.
  $("#launchLandingPage .form-submit-btn").on("click", function (e) {
    e.preventDefault();
    const { hasError, formValues } = productLaunchForm.validate(
      productLaunchFormConfig.validationRules
    );
    var prefValue = $("input[name='preferredContact']:checked").val(),
      values = { ...formValues, preferredContact: prefValue },
      successfulUrl = $("#launchLandingPage").data("thanks-url");
    /* If phone is not mandatory */
    let phoneVal = $("#launchLandingPage #phone").val(),
      keyName = $("#launchLandingPage #phone").attr("name"),
      phoneCountryCode = $(
        ".intl-tel-input .flag-dropdown-btn .selected-country-code"
      ).text();
    if (phoneVal != "") {
      phoneVal = phoneCountryCode + phoneVal;
      values[keyName] = phoneVal;
    }
    if (hasError) return;
    showLoader();
    $.ajax({
      url: "/PreferredDealerFormBlock/Submit",
      dataType: "json",
      contentType: "application/json",
      type: "POST",
      async: true,
      data: JSON.stringify(values),
      success: (resp) => {
        window.dataLayer.push({
          event: "formSubmission",
          formType: "Preferred Dealer",
          formID: "launchLandingPage",
        });
        if (resp.successMessage === "success") {
          window.location.href = successfulUrl;
        } else {
          console.log("Unable to pre-order your product");
        }
        hideLoder();
      },
      error: (err) => {
        //  Do nothing
        hideLoder();
      },
    });

    return !hasError;
  });

  //OnSubmit Handler for the Contact Us form.
  $(".contact-us-form .cta-wrapper button").on("click", function (e) {
    e.preventDefault();
    const nonEcomUrl = "/ContactUsFormBlock/Submit",
      forEcom = $("#contactUsFormNA").hasClass("for-na"),
      contactUsSuccessfulUrl = $("#contactUsForm").data("thanks-url"),
      submitBtn = $(e.target);
    var postUrl = "",
      formHasError = false,
      contactFormValues;
    if (forEcom) {
      const { hasError, formValues } = contactFormNA.validate(
        contactUsFormNAConfig.validationRules
      );
      formHasError = hasError;
      /* If phone is not mandatory */
      let phoneVal = $("#contactUsFormNA #phone").val(),
        keyName = $("#contactUsFormNA #phone").attr("name"),
        phoneCountryCode = $(
          ".intl-tel-input .flag-dropdown-btn .selected-country-code"
        ).text();
      if (phoneVal != "") {
        phoneVal = phoneCountryCode + phoneVal;
        formValues[keyName] = phoneVal;
      }

      contactFormValues = formValues;
    } else {
      postUrl = nonEcomUrl;
      const { hasError, formValues } = contactForm.validate(
        contactFormConfig.validationRules
      );
      formHasError = hasError;
      contactFormValues = formValues;
    }
    if (formHasError) return;
    showLoader();
    if (forEcom) {
      window.dataLayer.push({
        event: "formSubmission",
        formType: "Contact",
        formID: "contactUsFormNA",
      });
      submitBtn.attr("disabled", true);
      $("#contactUsFormNA").submit();
    } else {
      submitBtn.attr("disabled", true);
      $.ajax({
        url: postUrl,
        dataType: "json",
        contentType: "application/json",
        type: "POST",
        async: true,
        data: JSON.stringify(contactFormValues),
        success: (resp) => {
          window.dataLayer.push({
            event: "formSubmission",
            formType: "Contact",
            formID: "contactUsForm",
          });
          if (resp.successMessage === "success" && contactUsSuccessfulUrl) {
            window.location.href = contactUsSuccessfulUrl;
          } else {
            console.log("Unable to proceed");
            submitBtn.attr("disabled", false);
          }
          hideLoder();
        },
        error: (err) => {
          //  Do nothing
          hideLoder();
          submitBtn.attr("disabled", false);
        },
      });
    }
  });

  // Function for the common phone Field Flag dropdown Handler
  const _onPhoneFlagSelection = function (e) {
    let flagBtnEle = $(".flag-dropdown-btn"),
      phoneCountryListwrapper = $(".phone-country-list"),
      counrtyCodeListItem = $(".phone-country-list--item"),
      newSelectedCountry = {},
      currentActiveItem = phoneCountryListwrapper.find(
        ".phone-country-list--item.active"
      ),
      phoneFieldWrapper = $(".intl-tel-input");

    // Function to update the button text based on the new country selection
    function updatePhoneField() {
      showLoader();
      let phoneBtnFlagIconEle = flagBtnEle.find(".selected-flag.flag"),
        phoneBtnCode = flagBtnEle.find(".selected-country-code"),
        currentSelectedWrapper = phoneCountryListwrapper.find(
          ".phone-country-list--item.current-selected"
        );

      // Hide the dropdown
      phoneCountryListwrapper.addClass("d-none");
      phoneFieldWrapper.removeClass("active");

      // Update the display button Flag
      phoneBtnFlagIconEle
        ? phoneBtnFlagIconEle.attr(
            "src",
            newSelectedCountry.selectedCountryFlag
          )
        : "";

      // Update the display country Code
      phoneBtnCode ? phoneBtnCode.text(newSelectedCountry.selectedCode) : "";

      // update the current selected country details in dropdown
      if (currentSelectedWrapper) {
        let currentSelFlag = currentSelectedWrapper.find(
            ".flag-wrapper > .flag"
          ),
          currentCountrylabel = currentSelectedWrapper.find(".country-name");

        currentSelFlag.attr("src", newSelectedCountry.selectedCountryFlag);
        currentCountrylabel.text(
          newSelectedCountry.selectedCountryName.replace(/_/g, " ") +
            " " +
            newSelectedCountry.selectedCode
        );
        currentSelectedWrapper.attr(
          "data-country-code",
          newSelectedCountry.selectedCountryCode
        );
        currentSelectedWrapper.attr(
          "data-country-name",
          newSelectedCountry.selectedCountryName
        );
        currentSelectedWrapper.attr(
          "data-dial-code",
          newSelectedCountry.selectedCode
        );
      }

      // Update the active class based on the selection
      if (currentActiveItem) {
        currentActiveItem.removeClass("active");
        let currentActiveArray = [],
          newActiveEle;
        currentActiveArray = phoneCountryListwrapper.find(
          "[data-country-code='" + newSelectedCountry.selectedCountryCode + "']"
        );
        // Second ele doesn't have the currentActive class
        newActiveEle = currentActiveArray[1];
        $(newActiveEle).addClass("active");
      }

      setTimeout(() => {
        hideLoder();
      }, 200);
    }

    // Function to show hide the country list dropdown
    flagBtnEle.on("click", function (e) {
      e.stopPropagation();
      phoneCountryListwrapper.length
        ? phoneCountryListwrapper.toggleClass("d-none")
        : "";
      phoneFieldWrapper.length ? phoneFieldWrapper.toggleClass("active") : "";
    });

    // Function to handle the country list item selection
    counrtyCodeListItem.on("click", function (e) {
      e.stopPropagation();
      let clickedEle = $(e.target),
        parentListItem = clickedEle.parents(".phone-country-list--item");
      currentActiveItem = phoneCountryListwrapper.find(
        ".phone-country-list--item.active"
      );

      if (parentListItem) {
        newSelectedCountry.selectedCode = parentListItem.data("dial-code");
        newSelectedCountry.selectedCountryCode =
          parentListItem.data("country-code");
        newSelectedCountry.selectedCountryFlag = parentListItem
          .find(".flag-wrapper > img")
          .attr("src");
        newSelectedCountry.selectedCountryName =
          parentListItem.data("country-name");
        // Function to update the values based on the selection
        updatePhoneField();
      }
    });
  };

  /**
   * Form Fetching the dial codes drop down
   * @param $ele: international phone field wrapper
   */
  const _getDialCodes = function ($ele) {
    showLoader();
    const $listWrapper = $ele.find(".phone-country-list-wrapper");
    let allDialCodeList = "",
      currentActiveDialCode = {},
      clasNamePerIndex = "",
      activeClassName = "",
      phoneBtnFlagIconEle = $(".flag-dropdown-btn").find(".selected-flag.flag"),
      phoneBtnCode = $(".flag-dropdown-btn").find(".selected-country-code");

    if (getDialCodesURL) {
      $.ajax({
        url: getDialCodesURL,
        dataType: "json",
        contentType: "application/json",
        type: "GET",
        async: true,
        success: (res) => {
          try {
            if (res && res.length) {
              currentActiveDialCode = res[0];
              // Update the display button Flag
              phoneBtnFlagIconEle
                ? phoneBtnFlagIconEle.attr(
                    "src",
                    currentActiveDialCode.flagIcon
                  )
                : "";

              // Update the display country Code
              phoneBtnCode
                ? phoneBtnCode.text(currentActiveDialCode.dial_code)
                : "";
              res.forEach((element, index) => {
                clasNamePerIndex = index == 0 ? "current-selected" : "";
                activeClassName =
                  element.code.toLowerCase() ===
                  currentActiveDialCode.code.toLowerCase()
                    ? index > 0
                      ? " active"
                      : ""
                    : "";

                allDialCodeList +=
                  "<li class='phone-country-list--item " +
                  clasNamePerIndex +
                  activeClassName +
                  "' data-dial-code=" +
                  element.dial_code +
                  " data-country-code=" +
                  element.code.toLowerCase() +
                  " data-country-name=" +
                  element.name.replace(/ /g, "_") +
                  "><div class='flag-wrapper'><img src=" +
                  element.flagIcon +
                  " alt='flag' class='flag " +
                  element.name +
                  " ' /></div><span class='country-name'>" +
                  element.name +
                  " " +
                  element.dial_code +
                  "</span></li>";
              });
              $listWrapper.html(allDialCodeList);
              _onPhoneFlagSelection();
              hideLoder();
            }
          } catch (err) {
            hideLoder();
          }
        },
        error: (err) => {
          // console.log(err);
          hideLoder();
        },
      });
    }
  };

  var onInit = function () {
    if ($("#launchLandingPage").length > 0) {
      getCountries(true);
      productLaunchForm = new FormValidator(productLaunchFormConfig);
    }
    if ($("#contactUsForm").length > 0) {
      getCountries();
      contactForm = new FormValidator(contactFormConfig);
    }
    if ($("#contactUsFormNA").length > 0) {
      // getCountries();
      contactFormNA = new FormValidator(contactUsFormNAConfig);
    }

    // If phone field present
    const phoneFieldEle = $(".intl-tel-input");
    if (phoneFieldEle.length) {
      _getDialCodes(phoneFieldEle);
    }
    onCountrySelection();
    onCitySelection();

    // Function to close the country phone list when clicked outside
    $(document).click(function () {
      if ($(".phone-country-list")) {
        $(".phone-country-list").addClass("d-none");
        $(".intl-tel-input").removeClass("active");
      }
    });
  };
  // Null check
  $(".pfaff-form").length > 0 ? onInit() : "";

  //Return/Refund Form Start
  const _handleReasonsClick = function (showFormControl) {
    const $otherReasonEle = $("#othersReason"),
      $textarea = $otherReasonEle.find("#comment");
    var showNewField = showFormControl;
    $("#makeItRightFormControl")
      .addClass("d-none")
      .find("#makeItRight")
      .removeAttr("required");
    $otherReasonEle.addClass("d-none");
    $textarea.prop("required", false);
    if (showNewField === "makeItRight") {
      $("#makeItRightFormControl")
        .removeClass("d-none")
        .find("#makeItRight")
        .attr("required", "required");
    } else if (showNewField === "comment") {
      $otherReasonEle.removeClass("d-none");
      $textarea.prop("required", true);
    }
  };

  function isReturnFormValid(formEle) {
    var isValid = false;
    if (formEle.checkValidity() === false) {
      isValid = false;
    } else {
      isValid = true;
    }
    formEle.classList.add("was-validated");
    return isValid;
  }

  function getReturnFormData(formEle) {
    var formWrapper = $("#returnRefundForm"),
      formInput = formWrapper.find("input"),
      resonSelect = formWrapper.find("#reasons"),
      comment = formWrapper.find("#comment"),
      makeItRight = formWrapper.find("#makeItRightFormControl"),
      additionalDetails = formWrapper.find("textarea#additionalDetails"),
      values = {};
    formInput.each((index, input) => {
      var key = $(input).attr("name");
      values[key] = $(input).val();
    });

    if (resonSelect.val() === "other") {
      values["comment"] = comment.val();
    }

    if (!makeItRight.hasClass("d-none")) {
      values["makeItRight"] = $("#makeItRight").val();
    } else {
      values["makeItRight"] = null;
    }
    // values["reasons"] = resonSelect.val();
    values["additionalDetails"] = additionalDetails.val();
    // values["contactStore"] = $("#contactStore").val();

    return values;
  }

  $("#returnRefundFormModal").on("hidden.bs.modal", function (e) {
    const selectText = $("#returnRefundForm").data("select-text"),
      $btnEle = $("#returnRefundForm").find(".pfaff-custom-dropdown--btn");
    selectText.length ? $btnEle.text(selectText) : "";
    $("#returnRefundForm")[0].reset();
    $("#returnRefundForm").removeClass("was-validated");
  });

  $("#returnRefundForm").submit((e) => {
    e.preventDefault();
    var $formELe = $(".returnRefundForm")[0],
      isFormValid = isReturnFormValid($formELe);
    if (isFormValid) {
      showLoader();
      var formData = getReturnFormData("#returnRefundForm");
      $.ajax({
        url: "/ReturnsAndRefundsBlock/Submit",
        dataType: "json",
        contentType: "application/json",
        type: "POST",
        async: true,
        data: JSON.stringify(formData),
        success: (resp) => {
          window.dataLayer.push({
            event: "formSubmission",
            formType: "Return and Refund",
            formID: "returnRefundForm",
          });
          if (resp.successMessage === "success") {
            $(".form-success-msg").removeClass("d-none");
            $("#returnRefundFormModal").modal("show");
          } else {
            console.log("Unable to submit return form");
          }
          hideLoder();
        },
        error: (err) => {
          //  Do nothing
          console.log(err);
          hideLoder();
        },
      });
    }
  });

  // Form Common Dropdown js
  function handleMenuClick() {
    const $pfaffCustomDropdownEle = $(".pfaff-custom-dropdown"),
      isProductLaunchPage = $(".productlaunchForm").length > 0,
      isReturnRefundForm = $("#returnRefundForm").length > 0,
      dealerText = $("#dealerMenuBtn").text().trim(),
      cityText = $("#cityMenuBtn").text().trim();
    $pfaffCustomDropdownEle.each(function (index, ele) {
      const $parentEle = $(ele),
        $btnEle = $parentEle.find("#subjectMenuBtn"),
        $countryBtnEle = $parentEle.find("#countryMenuBtn"),
        $cityBtnEle = $parentEle.find("#cityMenuBtn"),
        $dealerBtnEle = $parentEle.find("#dealerMenuBtn"),
        $inputEle = $("#subject"),
        $countryInputEle = $("#country"),
        $countryEmailEle = $("#countryEmail"),
        $cityInputEle = $("#city"),
        $dealerInput = $("#preferredDealer"),
        $recordType = $("#recordType"),
        $dealerEmailInput = $("#preferredDealerEmail");
      $parentEle.on("click", "a.pfaff-custom-dropdown__item", function (e) {
        e.preventDefault();
        // e.stopImmediatePropagation();

        const selectedValue = $(e.target).data("selectedValue"),
          countryEmail = $(e.target).data("selectedEmail"),
          displayText = $(e.target).text(),
          selectedHeight = $(e.target).innerHeight();
        if (isProductLaunchPage) {
          if ($(e.target).parents("#productCountry").length > 0) {
            $countryBtnEle ? $countryBtnEle.text(displayText) : "";
            $countryInputEle ? $countryInputEle.val(selectedValue) : "";
            $("#cityMenuBtn") ? $("#cityMenuBtn").text(cityText) : "";
            $("#dealerMenuBtn") ? $("#dealerMenuBtn").text(dealerText) : "";
            $countryInputEle.trigger("change");
          }
          if ($(e.target).parents("#cityListWrapper").length > 0) {
            $cityBtnEle ? $cityBtnEle.text(displayText) : "";
            $cityInputEle ? $cityInputEle.val(selectedValue) : "";
            $("#dealerMenuBtn") ? $("#dealerMenuBtn").text(dealerText) : "";
            $cityInputEle.trigger("click");
          }
          if ($(e.target).parents("#dealerListWrapper").length > 0) {
            $dealerBtnEle ? $dealerBtnEle.text(displayText) : "";
            $dealerInput ? $dealerInput.val(selectedValue) : "";
            $dealerEmailInput
              ? $dealerEmailInput.val($(e.target).data("selectedDealerEmail"))
              : "";
          }
        } else if (isReturnRefundForm) {
          if ($(e.target).parents("#returnContactStore").length > 0) {
            $("#contactStoreMenuBtn").text(displayText);
            $("#contactStore").val(selectedValue);
          }
          if ($(e.target).parents("#returnReasons").length > 0) {
            var showFormControl = $(e.target).data("showformcontrol");
            $("#returnReasonsMenuBtn").text(displayText);
            $("#reasons").val(selectedValue);
            _handleReasonsClick(showFormControl);
          }
          if ($(e.target).parents("#returnMakeItRight").length > 0) {
            $("#returnMakeItRightMenuBtn").text(displayText);
            $("#makeItRight").val(selectedValue);
          }
        } else {
          console.log("Else");
          $btnEle ? $btnEle.text(displayText) : "";
          $inputEle ? $inputEle.val(displayText) : "";
          $recordType ? $recordType.val(selectedValue) : "";
          $countryEmailEle ? $countryEmailEle.val(countryEmail) : "";
          $countryBtnEle ? $countryBtnEle.text(displayText) : "";
          $countryInputEle ? $countryInputEle.val(selectedValue) : "";
          $btnEle.parent().css("padding-top", selectedHeight + 20);
          $btnEle
            .siblings(".pfaff-custom-dropdown__menu")
            .css("padding-top", selectedHeight + 20);
        }
      });
    });
  }
  $(".pfaff-custom-dropdown").length > 0 ? handleMenuClick() : "";
});
;
/*! lozad.js - v1.16.0 - 2020-09-06
* https://github.com/ApoorvSaxena/lozad.js
* Copyright (c) 2020 Apoorv Saxena; Licensed MIT */
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.lozad=e()}(this,function(){"use strict";
/**
   * Detect IE browser
   * @const {boolean}
   * @private
   */var g="undefined"!=typeof document&&document.documentMode,f={rootMargin:"0px",threshold:0,load:function(t){if("picture"===t.nodeName.toLowerCase()){var e=t.querySelector("img"),r=!1;null===e&&(e=document.createElement("img"),r=!0),g&&t.getAttribute("data-iesrc")&&(e.src=t.getAttribute("data-iesrc")),t.getAttribute("data-alt")&&(e.alt=t.getAttribute("data-alt")),r&&t.append(e)}if("video"===t.nodeName.toLowerCase()&&!t.getAttribute("data-src")&&t.children){for(var a=t.children,o=void 0,i=0;i<=a.length-1;i++)(o=a[i].getAttribute("data-src"))&&(a[i].src=o);t.load()}t.getAttribute("data-poster")&&(t.poster=t.getAttribute("data-poster")),t.getAttribute("data-src")&&(t.src=t.getAttribute("data-src")),t.getAttribute("data-srcset")&&t.setAttribute("srcset",t.getAttribute("data-srcset"));var n=",";if(t.getAttribute("data-background-delimiter")&&(n=t.getAttribute("data-background-delimiter")),t.getAttribute("data-background-image"))t.style.backgroundImage="url('"+t.getAttribute("data-background-image").split(n).join("'),url('")+"')";else if(t.getAttribute("data-background-image-set")){var d=t.getAttribute("data-background-image-set").split(n),u=d[0].substr(0,d[0].indexOf(" "))||d[0];// Substring before ... 1x
u=-1===u.indexOf("url(")?"url("+u+")":u,1===d.length?t.style.backgroundImage=u:t.setAttribute("style",(t.getAttribute("style")||"")+"background-image: "+u+"; background-image: -webkit-image-set("+d+"); background-image: image-set("+d+")")}t.getAttribute("data-toggle-class")&&t.classList.toggle(t.getAttribute("data-toggle-class"))},loaded:function(){}};function A(t){t.setAttribute("data-loaded",!0)}var m=function(t){return"true"===t.getAttribute("data-loaded")},v=function(t){var e=1<arguments.length&&void 0!==arguments[1]?arguments[1]:document;return t instanceof Element?[t]:t instanceof NodeList?t:e.querySelectorAll(t)};return function(){var r,a,o=0<arguments.length&&void 0!==arguments[0]?arguments[0]:".lozad",t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},e=Object.assign({},f,t),i=e.root,n=e.rootMargin,d=e.threshold,u=e.load,g=e.loaded,s=void 0;"undefined"!=typeof window&&window.IntersectionObserver&&(s=new IntersectionObserver((r=u,a=g,function(t,e){t.forEach(function(t){(0<t.intersectionRatio||t.isIntersecting)&&(e.unobserve(t.target),m(t.target)||(r(t.target),A(t.target),a(t.target)))})}),{root:i,rootMargin:n,threshold:d}));for(var c,l=v(o,i),b=0;b<l.length;b++)(c=l[b]).getAttribute("data-placeholder-background")&&(c.style.background=c.getAttribute("data-placeholder-background"));return{observe:function(){for(var t=v(o,i),e=0;e<t.length;e++)m(t[e])||(s?s.observe(t[e]):(u(t[e]),A(t[e]),g(t[e])))},triggerLoad:function(t){m(t)||(u(t),A(t),g(t))},observer:s}}});
;
