/* Minification failed. Returning unminified contents.
(179,49-50): run-time error JS1195: Expected expression: >
(181,14-15): run-time error JS1195: Expected expression: )
(183,6-7): run-time error JS1195: Expected expression: )
(185,78-79): run-time error JS1195: Expected expression: )
(185,80-81): run-time error JS1004: Expected ';': {
(187,49-50): run-time error JS1195: Expected expression: >
(189,14-15): run-time error JS1195: Expected expression: )
(190,10-11): run-time error JS1195: Expected expression: ,
(192,54-55): run-time error JS1195: Expected expression: )
(192,56-57): run-time error JS1004: Expected ';': {
(194,49-50): run-time error JS1195: Expected expression: >
(196,14-15): run-time error JS1195: Expected expression: )
(197,10-11): run-time error JS1195: Expected expression: ,
(200,36-37): run-time error JS1195: Expected expression: )
(200,38-39): run-time error JS1004: Expected ';': {
(205,6-7): run-time error JS1195: Expected expression: )
(207,6-7): run-time error JS1197: Too many errors. The file might not be a JavaScript file: (
 */
const asShown = "As Shown";
const queryString = {};
let productId = null;
let rawProductDetail = {};
let isCustomPreviewGlobal = true;
let rawUserSizeProfile = {};
let selectedStyle = {
    otherOptions: {},
};
let swipers = {};
let selectedSavedStyleId = 0;
let defaultSavedStyleRadio = null;
//let selectedMatchingMask = null;
let selectedMatchingMask = [];

const sizeProfileLocalStorageKey = "sizeProfiles";
let hasCompleteSizeProfile = false;
let hasCustomSize = false;
const standardSizeText = "standard";
const customSizeText = "custom";
var size = standardSizeText;
const selectedSize = {
    standardSize: null
};

const asShownMapping = {
    "Neckline": "Necklines",
    "Sleeve-Type": "SleeveTypes",
    "Length": "TunicLengths",
    "Pant-Length": "PantLength"
};

const mapping = {
    neckline: "Neckline",
    sleeveType: "Sleeve Type",
    length: "Length",
    pantLength: "Pant Length",
};
const reverseMapping = {
    Neckline: "neckline",
    "Sleeve Type": "sleeveType",
    Length: "length",
    "Pant Length": "pantLength",
};
const customStyleImageParameterMapping = {
    Neckline: "n",
    "Sleeve Type": "s",
    Length: "l",
    "Pant Length": "pl",
};

function executeYotpo() {
    const e = document.createElement("script");
    e.type = "text/javascript";
    e.async = true;
    e.src =
        "//staticw2.yotpo.com/OWLKzFts5bkXXwMY6sKzXBrNgCs9Atv1ERLYKejB/widget.js";
    const t = document.getElementsByTagName("script")[0];
    t.parentNode.insertBefore(e, t);
}

function stickyAddCartBtn() {
    let bottomHeight = $(".pdfeedback-link")[0].offsetTop;
    bottomHeight = bottomHeight + 90;
    $(".btn-wrp").addClass("sticky-btn");
    $(window).scroll(function () {
        let windowHeight = $(window)[0].innerHeight;
        let heightELem = $(".pdfeedback-link")[0].clientHeight;
        let totalOffset = bottomHeight + heightELem;
        let scrollSpacePoint = windowHeight - totalOffset;
        let scrollPoint = totalOffset + scrollSpacePoint;
        if ($(window).scrollTop() <= totalOffset) {
            $(".btn-wrp").addClass("sticky-btn");
        } else {
            $(".btn-wrp").removeClass("sticky-btn");
        }
    });
}

function initializeMainPageSliders() {
    try {
        const galleryThumbs = new Swiper(".gallery-thumbs", {
            spaceBetween: 10,
            slidesPerView: 3.5,
            // loop: true,
            freeMode: true,
            // loopedSlides: 5, //looped slides should be the same
            watchSlidesVisibility: true,
            watchSlidesProgress: true,
            // Navigation arrows
            navigation: {
                nextEl: ".left-arrow",
                prevEl: ".right-arrow",
            },

            grabCursor: true,
            breakpoints: {
                360: {
                    slidesPerView: 2.5,
                },
                768: {
                    slidesPerView: 3.5,
                },
            },
        });

        const galleryTop = new Swiper(".gallery-top", {
            spaceBetween: 10,
            effect: "fade",
            loop: true,
            loopedSlides: 5, //looped slides should be the same
            pagination: {
                el: ".swiper-pagination-bullets",
                clickable: true,
            },
            thumbs: {
                swiper: galleryThumbs,
            },
            observer: true,
            observeParents: true
        });
    } catch (e) {

    }
}

function initializeRecentlyViewedSlider() {
    if (document.querySelector(".js-recently-viewed")) {
        let mySwiper = new Swiper(".js-recently-viewed", {
            loop: false,
            preventClicks: true,
            grabCursor: true,
            simulateTouch: false,
            observer: true,
            observeParents: true,
            grabCursor: false,
            watchOverflow: true,
            pagination: {
                el: ".our-team-pagination",
                clickable: true,
            },
            navigation: {
                nextEl: ".left-arrow-img",
                prevEl: ".right-arrow-img",
            },
            // loop: true,
            spaceBetween: 15,
            slidesPerView: 1,
            // Responsive breakpoints
            breakpoints: {
                // when window width is >= 320px
                320: {
                    slidesPerView: 1.3,
                },
                // when window width is >= 480px
                480: {
                    slidesPerView: 1.3,
                },
                // when window width is >= 640px
                640: {
                    slidesPerView: 1.9,
                },
                // when window width is >= 992px
                992: {
                    slidesPerView: 2.7,
                },
                // when window width is >= 1200px
                1200: {
                    slidesPerView: 6.5,
                },
            },
        });
    }
}

function initializeLollypopControls() {
    $(".custom-stye-br").click(function () {
        setTimeout(function () {
            Object.keys(swipers).forEach((key) => {
                swipers[key].update();
            });
        }, 300);
    });

    $(document).on("click", ".product-modal .nav-link.style-head", function () {
        setTimeout(function () {
            Object.keys(swipers).forEach((key) => {
                swipers[key].update();
            });
        }, 300);
    });
    $(document).on("click", ".style-head", function () {
        setTimeout(function () {
            Object.keys(swipers).forEach((key) => {
                swipers[key].update();
            });
        }, 300);
    });

    $(".size-lbl").click(function () {
        $(".size-number").removeClass("size-active");
        if ($(this).siblings("input").is(":checked")) {
            $(this).parent(".size-number").addClass("size-active");
        }
    });

    $(".js-size-model").click(function () {
        $(".js-size-modal-wrp").modal("show");
    });

    $(document).on("click", ".web-tooltip", function (e) {
        e.stopPropagation();
    });

    $(document).on("click", ".img-wrp", function (e) {
        ////console.log("inside style type");
        const styletype = $(this).attr('x-data-style-type');
        ////console.log(styletype);
        $('.nav.d-flex.d-md-none a[href="#' + styletype + '"]').tab('show');
    });

    //Save style popup
    stickyAddCartBtn();

    //Save style model
    var CreateMoreStyles = document.querySelector(".create-more-styles");
    CreateMoreStyles.addEventListener("click", function (event) {
        setTimeout(function () {
            $(".bd-example-modal-lg").modal("show");
        }, 650);
    });

    $(".js-size-model").click(function () {
        $(".js-size-modal-wrp").modal("show");
    });

    let productScroll = OverlayScrollbars(document.querySelector(".model-wrp"), {
        overflowBehavior: {
            x: "never",
        },
    });

    let stickyInnerContainer = OverlayScrollbars(
        document.querySelector(".sticky-inner-container"),
        {
            overflowBehavior: {
                x: "never",
            },
        }
    );

    let addressScroll = OverlayScrollbars(
        document.querySelector(".js-address-wrp"),
        {
            overflowBehavior: {
                x: "never",
            },
        }
    );

    let custompopupScroll = OverlayScrollbars(
        document.querySelector(".js-custom-scroll"),
        {
            overflowBehavior: {
                x: "never",
            },
        }
    );

    let measureScroll = OverlayScrollbars(
        document.querySelector(".js-measure-content"),
        {
            overflowBehavior: {
                x: "never",
            },
        }
    );

    let productDetails = OverlayScrollbars(
        document.querySelector(".product-details-list"),
        {
            overflowBehavior: {
                x: "never",
            },
        }
    );

    document.addEventListener("DOMContentLoaded", function () {
        //The first argument are the elements to which the plugin shall be initialized
        //The second argument has to be at least a empty object or a object with your desired options
    });
    $("#myModal").on("show.bs.modal", function (e) {
        // overscroll.update();
        productScroll.update();
        // do something...
    });
    $(".js-save-style-item").on("click", function () {
        custompopupScroll.update();
    });
}

$(document).ready(function () {
    $(".pd-strip-banner").hide();
    const addToCartButton = $(".btn-addCart");

    var savedStyleSlider = new Swiper(".js-style-slider", {
        slidesPerView: "auto",
        paginationClickable: true,
        spaceBetween: 20,
        navigation: {
            nextEl: ".left-arrow",
            prevEl: ".right-arrow",
        },
        breakpoints: {
            480: {
                spaceBetween: 10,
                slidesPerView: 1,
            },

            768: {
                slidesPerView: "auto",
                spaceBetween: 20,
            },
            992: {
                slidesPerView: "auto",
                spaceBetween: 20,
            },
            1200: {
                spaceBetween: 30,
            },
        },
        pagination: {
            el: ".swiper-pagination",
            clickable: true,
        },
        observer: true,
        observeParents: true
    });

    savedStyleSlider.update();

    function getQueryString() {
        const friendlyUrl = decodeURI(window.location.href.split("+").join("%20"));
        const fxView = "fx";
        const customTracker = {
            viewSource: null
        };
        const utmRequest = {
            refUrl: document.referrer
        };

        if (!friendlyUrl.toLowerCase().includes("productdetail.aspx?")) {
            if (friendlyUrl.toLowerCase().includes("/shop")) {
                let splits = friendlyUrl.split("/");
                const lastSection = splits[splits.length - 1];
                splits = lastSection.split("?");
                splits = splits[0].split("-");
                productId = splits[splits.length - 1];
            }
            if (friendlyUrl.toLowerCase().includes("/product/")) {
                const startIndex = friendlyUrl.toLowerCase().indexOf("/product/");
                const requiredString = friendlyUrl.substr(startIndex);
                let splits = requiredString.split("/");
                const productIdWithParams = splits[2];
                splits = productIdWithParams.split("?");
                productId = splits[0];
            }
        }

        const pairs = friendlyUrl.slice(friendlyUrl.indexOf("?") + 1).split("&");
        pairs.forEach((pair) => {
            const splits = pair.split("=");
            queryString[splits[0]] = splits[1];
            if (splits[0].toLowerCase() === "productid") {
                productId = splits[1];
                const productIdSplit = productId.split("-");
                productId = productIdSplit[productIdSplit.length - 1];
            }

            switch (splits[0].toLowerCase()) {
                case "utm_source":
                case "source":
                    utmRequest.utmSource = splits[1];
                    break;
                case "utm_medium":
                case "medium":
                    utmRequest.utmMedium = splits[1];
                    break;
                case "utm_campaign":
                case "campaign":
                    utmRequest.utmCamp = splits[1];
                    break;
                case "view_source":
                    customTracker.viewSource = splits[1].toLowerCase();
                    break;
                default:
                    break;
            }
        });

        utmRequest.productId = productId;
        //solusTracking(utmRequest);
        if (customTracker.viewSource && customTracker.viewSource.length > 0) {
            window.insertGenericTrackerData({
                trackerId: 3,
                answer: customTracker.viewSource === fxView,
                customData: customTracker.viewSource
            });
        }
    }

    //function solusTracking(utmRequest) {
    //    if (!utmRequest || !utmRequest.utmSource)
    //        return;

    //    const onSuccess = function (result) {
    //        if (!result) {
    //            logError("Could not save solus tracking details");
    //            sendErrorEmail("Solus tracking error", "Could not save tracking details for the user");
    //            return;
    //        }
    //    };

    //    const onError = function (response, status, error) {
    //        logError(`Could not save solus tracking details. Error = ${response.responseText}`);
    //        sendErrorEmail("Solus tracking error", `Could not save tracking details for the user. Error = ${response.responseText}`);
    //    };

    //    ////console.log(utmRequest);
    //    sendAjaxPostRequestWithToken("/baseHandler.ashx?type=SolusTracking", utmRequest, onSuccess, onError);
    //}

    function refreshRecentItems() {
        const recentlyViewedCookie = $.cookie("_rec_view_");
        if (!recentlyViewedCookie) return;

        const today = new Date();
        let recentlyViewedItems = JSON.parse(recentlyViewedCookie);
        recentlyViewedItems = recentlyViewedItems.filter((item) => {
            const itemAddedDate = new Date(item.dateAdded);
            var differenceInTime = today.getTime() - itemAddedDate.getTime();
            var differenceInDays = differenceInTime / (1000 * 3600 * 24);

            return differenceInDays <= 2;
        });
        $.cookie("_rec_view_", JSON.stringify(recentlyViewedItems), {
            expires: 7300,
            path: "/"
        });
    }

    function removeBreakingProduct() {
        const recentlyViewedCookie = $.cookie("_rec_view_");
        if (!recentlyViewedCookie) return;

        let recentlyViewedItems = JSON.parse(recentlyViewedCookie);
        const index = recentlyViewedItems.findIndex(item => item.productId === deleteId);
        if (index < 0)
            return;

        recentlyViewedItems.splice(index, 1);
        $.cookie("_rec_view_", JSON.stringify(recentlyViewedItems), {
            expires: 7300,
            path: "/"
        });
    }

    function loadRecentlyViewed() {
        try {
            const recentlyViewedListContainer = $(".recently-viewed-list");
            if (!recentlyViewedListContainer) return;

            recentlyViewedListContainer.empty();

            const recentlyViewedCookie = $.cookie("_rec_view_");
            if (!recentlyViewedCookie) return;

            const recentlyViewedItems = JSON.parse(recentlyViewedCookie);
            const breakingItems = [];
            let itemsRetrieved = 0;
            const customLazyLoad = function () {
                itemsRetrieved++;

                if (itemsRetrieved === recentlyViewedItems.length)
                    eShaktiLazyLoading(".eshakti-lazy-load-recently-viewed");
            };

            var products = "";
            let items = 0;
            recentlyViewedItems.forEach((item) => {
                if (!item.productId && item.productId.length === 0) {
                    customLazyLoad();
                    return;
                }
                items++;
                if (items === recentlyViewedItems.length) {
                    products += item.productId;
                }
                else {
                    products += item.productId + "-";
                }
            });

            const onSuccess = function (results) {
                results.forEach((result) => {
                    try {
                        let productStyleType = result.styleType;
                        if (styleTypeUrlMapping && styleTypeUrlMapping[productStyleType]) {
                            productStyleType = styleTypeUrlMapping[productStyleType];
                        }
                        const productUrl = `/shop/${productStyleType}/${result.name.replace(/ /g, "-")}-${result.productId}`;
                        const listItem = `
                        <li class="swiper-slide">
                            <a class="product-card__view" href="${productUrl}" target="_blank">
                                ${result.stickerFlag && result.stickerFlag.toLowerCase() === "fx" ? `<div class="card-tag">Fx</div>` : ""}
                                <picture>
                                    <img class="js-loading-card__img img-fluid img-scale eshakti-lazy-load-recently-viewed" data-lazy-src="${result.lowResImageUrls[0]}"/>
                                </picture>
                            </a>
                            <div class="product-card__body">
                                <div class="product-info">
                                    <span class="product-name">${result.brand}</span>
                                    <span class="product-type">${result.name}</span>
                                    <span style="color: #2c2a2a;" class="product-cost">${result.currencySymbol}${result.listPrice.toFixed(2)}</span>
                                </div>
                                <div class="product-conatct d-flex">
                                    <div class="favourite ${result.wishlistFlag ? "active" : ""}" id="rec-viwd-${result.productId}" x-data="${result.productId}">
                                    <i class="icon-wishlist"></i>
                                    <div class="wishlistProductCount">${(result.wishListCount <= 0 ? "" : result.wishListCount.toString())}</div>
                                </div>
                                </div>
                            </div>
                        </li>`;
                        recentlyViewedListContainer.append(listItem);
                        addFavouriteHandleEvent(
                            document.querySelector(`#rec-viwd-${result.productId}`)
                        );
                        customLazyLoad();
                    }
                    catch (ex) {
                        console.log(ex);
                        customLazyLoad();
                        breakingItems.push(result);
                    }
                });

                breakingItems.forEach(item => removeBreakingProduct(item.productId));
                $(".recent-viewed-section").show();
            };

            const onError = function (_, status, error) {
                customLazyLoad();
                console.error(status, error);
            };
            sendAjaxGetRequestWithToken(
                `/baseHandler.ashx?type=getrecentlyviewed&productId=${products}`,
                onSuccess,
                onError
            );
        } catch (e) {

        }
    }

    function updateRecentlyViewed() {
        const product = {
            productId: productId,
            dateAdded: new Date(),
        };
        const recentlyViewedCookie = $.cookie("_rec_view_");
        if (!recentlyViewedCookie) {
            $.cookie("_rec_view_", JSON.stringify([product]), {
                expires: 7300,
                path: "/"
            });
            return;
        }

        const recentlyViewedItems = JSON.parse(recentlyViewedCookie);
        const index = recentlyViewedItems.findIndex(
            (item) => item.productId === productId
        );
        if (index === -1) recentlyViewedItems.push(product);
        else recentlyViewedItems[index].dateAdded = new Date();

        $.cookie("_rec_view_", JSON.stringify(recentlyViewedItems), {
            expires: 7300,
            path: "/"
        });
    }

    function setDefaultStyle() {
        rawProductDetail.styles.forEach((style) => {
            const styleType = style.type.replace(/ /g, "-");
            if (
                selectedStyle[style.type] &&
                selectedStyle[style.type].length > 0 &&
                selectedStyle[style.type] !== asShown
            ) {
                const styleOption = style.styleOptions.find(
                    (option) => option.name.toLowerCase() === selectedStyle[style.type].toLowerCase()
                );
                const friendlyOptionName = styleOption.name.replace(/ /g, "-");
                $(`#${styleType}Check00${friendlyOptionName}`).trigger("click");
                return;
            }

            $(`#${styleType}Check000`).trigger("click");
        });
    }

    function setLargeModal() {
        const largeImagesContainer = $(".largeImagesContainer");
        largeImagesContainer.empty();
        let index = 0;
        rawProductDetail.highResImageUrls.forEach((image) => {
            largeImagesContainer.append(`<img class="lg-image-index-${index++}" src="${image}" alt=""/>`);
        });

        $(".model-img-tab-container").css(
            "background-image",
            "url(" + rawProductDetail.highResImageUrls[0] + ")"
        );
    }

    function handleLargerImageModelEvents() {
        // on main slider click
        $(document).on("click", ".main-slider", function (e) {
            e.stopPropagation();
            const mainSlider = e.currentTarget;
            const targetIndex = mainSlider.getAttribute("x-data-target-index");
            const targetImage = mainSlider.getAttribute("x-data-target-image");
            $(".tab-img img").css({ border: "none" });
            $(`.lg-image-index-${targetIndex}`).css({ border: "1px solid #464748" });
            $(".model-img-tab-container").css("background-image", `url(${targetImage})`);
        });

        // on hover change img
        $(".tab-img img").hover(function () {
            $(".tab-img img").css({ border: "none" });
            $(this).css({ border: "1px solid #464748" });
            let src = $(this).attr("src");
            $(this)
                .parent(".tab-img")
                .siblings(".model-img-tab-container")
                .css("background-image", "url(" + src + ")");
        });

        $(".model-img-tab-container").on("mousemove", function (e) {
            var zoomer = e.currentTarget;
            // e.offsetX ? offsetX = e.offsetX : offsetX = e.touches[0].pageX
            e.offsetY ? (e.offsetY = e.offsetY) : (e.offsetX = e.touches[0].pageX);
            // x = offsetX/zoomer.offsetWidth*100
            let y = (e.offsetY / zoomer.offsetHeight) * 100;

            $(this).css({
                "background-position-x": 100 + "%",
                "background-position-y": y + "%",
            });
        });
    }

    function returnSelectOptions(sizeOption) {
        let selectOptions = `<option disabled="disabled" selected="selected">select</option>`;
        let selectedOptionValue = null;
        if (rawUserSizeProfile && rawUserSizeProfile.length > 0) {
            const sizeProfile = rawUserSizeProfile.find(
                (measurement) => measurement.name.replace("*","").toLowerCase().trim() === sizeOption.name.replace("*","").toLowerCase().trim()
            );
            if (
                sizeProfile &&
                sizeProfile.value &&
                sizeProfile.value.length > 0
            ) {
                selectedOptionValue = sizeProfile.value.replace("'", ".").replace(/'/g, "").replace(/"/g, "");
                selectOptions = `<option disabled="disabled">select</option>`;
            }
        }

        let foundSelectedValue = false;
        if (sizeOption.optionValues && sizeOption.optionValues.length > 0) {
            sizeOption.optionValues.forEach((optionValue) => {
                let changedValue  = optionValue.replace(".", "'");
                changedValue  = changedValue + '"';
                if (selectedOptionValue === optionValue.toString()) {
                    foundSelectedValue = true;
                    selectedSize[sizeOption.name] = optionValue;
                }

                selectOptions += `<option value="${optionValue}" ${selectedOptionValue === optionValue ? `selected="selected"` : ""
                    }>${changedValue}</option>`;
            });
        }
        else if (
            sizeOption.min &&
            !isNaN(sizeOption.min) &&
            sizeOption.max &&
            !isNaN(sizeOption.max) &&
            sizeOption.step &&
            !isNaN(sizeOption.step)
        ) {
            const min = parseInt(sizeOption.min);
            const max = parseInt(sizeOption.max);
            const step = parseInt(sizeOption.step);
            if (selectedOptionValue && !isNaN(selectedOptionValue) && (min > parseInt(selectedOptionValue) || max < parseInt(selectedOptionValue))) {
                selectOptions = `<option disabled="disabled" selected="selected">select</option>`;
            }
            for (let optionValue = min; optionValue <= max; optionValue += step) {
                let changedValue = optionValue + '"';
                if (selectedOptionValue === optionValue.toString()) {
                    foundSelectedValue = true;
                    selectedSize[sizeOption.name] = optionValue.toString();
                }

                selectOptions += `<option value="${optionValue}" ${selectedOptionValue === optionValue.toString()
                    ? `selected="selected"`
                    : ""
                    }>${changedValue}</option>`;
            }
        }

        if (hasCompleteSizeProfile && !foundSelectedValue && !sizeOption.optional) {
            logError(`Value in size profile does not match the product size ${productId}. SizeProfile = ${JSON.stringify(rawUserSizeProfile)}`);
            hasCompleteSizeProfile = false;
        }

        return selectOptions;
    }

    function returnSizeOption(sizeOption) {
        const selectOptions = returnSelectOptions(sizeOption);

        $("#measureContainer").append(`
<div class="col-12 measure-card">
    <p class="head-text">How to Measure?</p>
    <div class="size-info-wrp d-flex flex-column flex-md-row mt-3">
        <div class="img-wrp">
            <img class="img-fluid" src="" modal-lazy-load="${sizeOption.imageUrl}" alt="${sizeOption.name}" />
        </div>
        <div class="info-wrp pl-md-4 ml-md-2 pt-4 pt-md-0">
            <h5>${sizeOption.name.replace("*", "")}</h5>
            <p class="sub-text">${sizeOption.imageText}</p>
        </div>
    </div>
</div>`);

        return `
<div class="drop-container mb-2 mb-md-3">
    <div class="drop-title">
        <span class="selection-label">${sizeOption.name.replace("*", "")}</span>
        <i class="js-size-model icon-info pl-1 measurement-icon" data-toggle="modal" data-target=".js-size-modal-wrp" x-data-name="${sizeOption.name.replace("*", "")
            }" x-data-imageUrl="${sizeOption.imageUrl}" x-data-imageText="${sizeOption.imageText}"></i>
        <div class="select-style">
            <select class="txt-gry-12 select_box" x-data-name="${sizeOption.name
            }" x-data-optional="${sizeOption.optional}">
                ${selectOptions}
            </select>
        </div>
    </div>
</div>`;
    }

    function returnHeightSelect(sizeOption) {
        const selectOptions = returnSelectOptions(sizeOption);

        if (selectedSize[sizeOption.name] && sizeOption.name !== "height") {
            selectedSize.height = selectedSize[sizeOption.name];
            delete selectedSize[sizeOption.name];
        }

        return `
<select class="txt-gry-12 select_box" x-data-name="height">
    ${selectOptions}
</select>`;
    }

    function getStyleContent(style, styleOptions, styleIndex) {
        const styleType = style.type.replace(/ /g, "-");
        const arrows = `
                    <div class="swiper-arrow">
                        <div class="arrow right-arrow-${styleType}Slider"><span></span></div>
                        <div class="arrow left-arrow-${styleType}Slider"><span></span></div>
                    </div>`;

        let asShownStyle = asShownMapping[styleType];
        let asShownText = "";
        rawProductDetail.asShownStyles.forEach((shownStyle) => {
            if (shownStyle.styleName == asShownStyle) {
                asShownText = shownStyle.styleValue;
            }
        });

        return `
<div class="tab-pane fade ${styleIndex === 0 ? "show active" : ""
            } style-model-content" id="${styleType}">
    <div class="style-head pb-md-1 d-none d-md-block">${style.type}</div>
    <div class="style-contain d-flex">
        <label class="img-container" for="${styleType}Check000">
            <p class="img-txt pb-2">As Shown</p>
            <input
                class="d-none style-check"
                id="${styleType}Check000"
                type="radio"
                name="${styleType}"
                value="${asShown}"
            />
            <div class="img-wrp d-flex justify-content-center align-item-center">
                <span class="style-img text-center pt-3 m-auto img-txt__inner-txt">Default</span>
            </div>
            <p class="img-txt pt-2">${asShownText}</p>
        </label>
        <div class="styleThumbSlider">
            <div class="change-style-title justify-content-start pt-0 pb-1">Click to change ${style.type}</div>
            <div class="swiper-container pt-1 js-${styleType}Slider">
                <div class="swiper-wrapper">
                    ${styleOptions}
                </div>
            </div>
            ${style.styleOptions.length > 1 ? arrows : ""}
        </div>
    </div>
</div>`;
    }

    function getMainPageStyle(style, styleType) {
        const selected = style.styleOptions.find(
            (option) => option.name.toLowerCase() === asShown.toLowerCase()
        );

        let asShownStyle = asShownMapping[styleType];
        let asShownText = "";
        rawProductDetail.asShownStyles.forEach((shownStyle) => {
            if (shownStyle.styleName == asShownStyle) {
                asShownText = shownStyle.styleValue;
            }
        });
        return `
            <div class="img-card-wrp">
                <p class="prod-label pb-1">${style.type}</p>
                <div class="img-wrp d-flex cursor-pointer fx-click-track" x-data-style-type="${styleType}" data-toggle="modal" data-target=".bd-example-modal-lg" style="flex-direction: column; align-items: center;">
                    <img id="${styleType}Image" class="img50x50" src="${selected.imageUrl}" alt=""  />
                    <span id="${styleType}Text" class="neck-type">${asShownText}</span>
                    <a href="javascript:void(0)" id="${styleType}ChangeStyleText" class="learn-link fnt-xxs neck-type">Change style</a>
                </div>
            </div>`;
    }

    function loadCustomStyles() {
        if (
            !rawProductDetail ||
            !rawProductDetail.styles ||
            rawProductDetail.styles.length === 0
        )
            showDefaultErrorPopup("Unexpected error", "Styles Empty");

        const myTab = $("#myTab");
        const myTabContent = $("#myTabContent");
        const mainPageStyles = $("#mainPageStyles");
        const fxImageHolder = $("#fxImageHolder");
        const otherOptionsList = [];
        const otherOptionsEvents = [];
        let maxWidth = 0;
        let maxHeight = 0;

        fxImageHolder.empty();
        myTab.empty();
        myTabContent.empty();
        mainPageStyles.empty();

        if (!rawProductDetail.isCustomPreview) {
            fxImageHolder.append(`
                <div class="fxImageDiv" id="non-fx-img">
                    <img class="img img-fluid" src="${rawProductDetail.highResImageUrls[0]}" alt="" />
                </div>`);
        }

        let styleIndex = -1;
        rawProductDetail.styles.forEach((style) => {
            if (!style || !style.styleOptions) return;

            styleIndex++;
            const styleType = style.type.replace(/ /g, "-");
            const isOtherOption = style.styleOptions.find(
                (styleOption) => !styleOption.imageUrl
            );

            if (isOtherOption) {
                if (queryString[style.type] && queryString[style.type] !== asShown)
                    selectedStyle.otherOptions[style.type] = queryString[style.type];

                style.styleOptions.forEach((option) => {
                    if (!option || option.name === asShown) return;

                    let isSelected = false;
                    if (
                        queryString[style.type] &&
                        queryString[style.type] === option.value
                    ) {
                        isSelected = true;
                    }

                    const friendlyOptionName = option.name.replace(/ /g, "-");
                    const otherOptionDisplayText = (option.displayText && option.displayText.length > 0) ? option.displayText : option.name;
                    const otherOptionValue = (option.value && option.value.length > 0) ? option.value : option.name;

                    otherOptionsList.push(`
                        <label class="label-container label-container--check">
                            ${otherOptionDisplayText}
                            <input type="checkbox" name="${styleType}" id="${styleType}Check00${friendlyOptionName}" value="${otherOptionValue}" ${isSelected ? `checked="checked"` : ""} />
                            <span class="checkmark"></span>
                        </label>`);
                });

                otherOptionsEvents.push(function () {
                    $(`input[name="${styleType}"]`).change(function () {
                        if ($(this).is(":checked")) {
                            const selectedOption = $(this).val();
                            selectedStyle.otherOptions[style.type] = selectedOption;
                        }
                        else {
                            delete selectedStyle.otherOptions[style.type];
                        }
                    });
                });
            } else {
                let styleOptions = "";
                let numberOfImages = 0;
                let styleMaxWidth = 0;
                let styleMaxHeight = 0;

                if (queryString[style.type] && queryString[style.type] !== asShown)
                    selectedStyle[style.type] = queryString[style.type];

                mainPageStyles.append(getMainPageStyle(style, styleType));
                myTab.append(`
                    <li class="nav-item mt-2">
                        <a 
                            class="nav-link style-head ${styleIndex === 0 ? "active" : ""}"
                            id="${styleType}-tab"
                            data-toggle="tab"
                            href="#${styleType}"
                            role="tab"
                            aria-controls="home"
                            aria-selected="${styleIndex === 0 ? "true" : "false"}">
                            ${style.type}
                        </a>
                    </li>`);

                style.styleOptions.forEach((styleOption) => {
                    if (styleOption.styleImageInfo) {
                        numberOfImages = styleOption.styleImageInfo.length;
                        isCustomPreviewGlobal = true;
                    }
                    else
                        isCustomPreviewGlobal = false;

                    if (styleOption.name === asShown) return;

                    if (styleOption.styleImageInfo) {
                        styleOption.styleImageInfo.forEach((imageInfo) => {
                            const width = parseInt(imageInfo.width) + parseInt(imageInfo.x);
                            const height = parseInt(imageInfo.height) + parseInt(imageInfo.y);
                            styleMaxWidth = styleMaxWidth > width ? styleMaxWidth : width;
                            styleMaxHeight =
                                styleMaxHeight > height ? styleMaxHeight : height;
                            preLoadFxImage(imageInfo.styleImageUrl);
                        });
                    }

                    const friendlyOptionName = styleOption.name.replace(/ /g, "-");

                    styleOptions += `
                        <label class="swiper-slide img-container mr-sm-2 mr-4" for="${styleType}Check00${friendlyOptionName}">
                            <input
                                class="d-none style-check"
                                id="${styleType}Check00${friendlyOptionName}"
                                type="radio"
                                name="${styleType}"
                                value="${styleOption.name}"
                            />
                            <div class="img-wrp"><img class="style-img" src="${styleOption.imageUrl}" alt=""/></div>
                            <p class="img-txt pt-2">${styleOption.name}</p>
                          </label>`;
                });

                myTabContent.append(getStyleContent(style, styleOptions, styleIndex));

                if (style.styleOptions.length > 1) {
                    swipers[style.type] = new Swiper(`.js-${styleType}Slider`, {
                        spaceBetween: 10,
                        watchOverflow: true,
                        slidesPerView: "auto",
                        observer: true,
                        observeParents: true,
                        navigation: {
                            nextEl: `.left-arrow-${styleType}Slider`,
                            prevEl: `.right-arrow-${styleType}Slider`,
                        },
                    });
                } else {
                    swipers[style.type] = new Swiper(`.js-${styleType}Slider`, {
                        spaceBetween: 10,
                        watchOverflow: true,
                        slidesPerView: "auto",
                        observer: true,
                        observeParents: true,
                    });
                }

                if (rawProductDetail.isCustomPreview) {
                    isCustomPreviewGlobal = isCustomPreviewGlobal && rawProductDetail.isCustomPreview;
                    if (numberOfImages > 1) {
                        for (let n = 0; n < numberOfImages; n++) {
                            fxImageHolder.append(`
                        <div class="fxImageDiv" id="${styleType}-img-${n}">
                            <img class="img img-fluid img-bg" src="" alt="" />
                            <img class="img img-fluid img-fg" src="" alt="" />
                        </div>`);
                        }
                    } else {
                        fxImageHolder.append(`
                        <div class="fxImageDiv" id="${styleType}-img">
                            <img class="img img-fluid img-bg" src="" alt="" />
                            <img class="img img-fluid img-fg" src="" alt="" />
                        </div>`);
                    }
                } else {
                    isCustomPreviewGlobal = isCustomPreviewGlobal && rawProductDetail.isCustomPreview;
                }

                maxWidth = styleMaxWidth > maxWidth ? styleMaxWidth : maxWidth;
                maxHeight = styleMaxHeight > maxHeight ? styleMaxHeight : maxHeight;

                $(`input[name="${styleType}"]`).change(function () {
                    if ($(this).is(":checked")) {
                        const selectedOption = $(this).val();
                        selectedStyle[style.type] = selectedOption;
                        applyStyle(style, selectedOption);
                        findAndSelectSavedStyle();
                        //setTimeout(function () {
                        //    window.solusProductStyleSelection && window.solusProductStyleSelection(rawProductDetail, selectedStyle);
                        //});
                    }
                });
            }
        });

        if (otherOptionsList.length > 0) {
            let optionsHtml = "";

            otherOptionsList.forEach((option) => {
                optionsHtml += option;
            });

            myTab.append(`
                <li class="nav-item mt-2">
                    <a 
                        class="nav-link style-head"
                        id="otherOptions-tab"
                        data-toggle="tab"
                        href="#otherOptions"
                        role="tab"
                        aria-controls="home"
                        aria-selected="false">
                        Other Options (Free)
                    </a>
                </li>`);

            myTabContent.append(`
            <div class="tab-pane fade style-model-content" id="otherOptions">
                <div class="style-head pb-md-3 d-none d-md-block">Other Options (Free)</div>
                <div id="otherOptionsList">
                    ${optionsHtml}
                </div>
            </div>`);

            otherOptionsEvents.forEach((optionEvent) => {
                if (optionEvent) optionEvent();
            });
        }

        const fxImageContainer = $(".model-img");
        if (rawProductDetail.isCustomPreview) {
            fxImageContainer.width(applyScaling(maxWidth));
            fxImageContainer.height(applyScaling(maxHeight));
        } else {
            fxImageContainer.width(applyScaling(470));
        }
    }

    function applyStyle(style, selectedOption) {
        const styleType = style.type.replace(/ /g, "-");
        const styleOption = style.styleOptions.find(
            (option) => option.name === selectedOption
        );
        if (!styleOption)
            return showDefaultErrorPopup(
                "Unexpected error",
                "Selected neck style not found"
            );

        if (rawProductDetail.isCustomPreview) {
            if (styleOption.styleImageInfo && styleOption.styleImageInfo.length > 1) {
                let index = 0;
                styleOption.styleImageInfo.forEach((imageInfo) => {
                    const styleImageContainer = $(`#${styleType}-img-${index}`);
                    const styleImageForeground = styleImageContainer.children(".img-fg");
                    const styleImageBackground = styleImageContainer.children(".img-bg");
                    styleImageForeground.hide().fadeIn("slow");
                    applyDimensions(styleImageContainer, styleImageForeground, imageInfo);
                    styleImageForeground.show().fadeIn("slow");
                    setTimeout(function () {
                        applyDimensions(
                            styleImageContainer,
                            styleImageBackground,
                            imageInfo
                        );
                    }, 700);
                    index++;
                });
            } else {
                const styleImageContainer = $(`#${styleType}-img`);
                const styleImageForeground = styleImageContainer.children(".img-fg");
                const styleImageBackground = styleImageContainer.children(".img-bg");
                styleImageForeground.hide().fadeIn("slow");
                applyDimensions(
                    styleImageContainer,
                    styleImageForeground,
                    styleOption.styleImageInfo[0]
                );
                styleImageForeground.show().fadeIn("slow");
                setTimeout(function () {
                    applyDimensions(
                        styleImageContainer,
                        styleImageBackground,
                        styleOption.styleImageInfo[0]
                    );
                }, 700);
            }
        }
    }

    function applyDimensions(styleImageContainer, styleImageTag, styleImageInfo) {
        styleImageTag.attr("src", styleImageInfo.styleImageUrl);
        styleImageContainer.width(applyScaling(styleImageInfo.width));
        styleImageContainer.height(applyScaling(styleImageInfo.height));

        let yInt = parseInt(styleImageInfo.y);
        yInt = yInt > 0 ? (yInt - 1) : yInt;
        styleImageContainer.css({
            left: applyScaling(styleImageInfo.x),
            top: applyScaling(yInt.toString())
        });
    }

    function setTrackingElements() {
        $(".fx-click-track").attr("x-data-product-id", productId);
    }

    function getCookie(cname) {
        var name = cname + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }

    function getProductDetails() {
        if (!productId) return;

        const onSuccess = function (result) {
            rawProductDetail = result;
            //ovontsProductViewed(rawProductDetail);

            if (!rawProductDetail) location.href = "/";

            if (rawProductDetail.isOverStock) {
                location.replace(`/overstock.aspx?productid=${productId}`);
                return;
            }

            if (rawProductDetail.isFaceMask) {
                location.replace(`/faceMasks.aspx?productid=${productId}`);
                return;
            }

            //$("#overlay").fadeOut(300);

            setProductInformation();
            initializeFeedbackPopup();
            initializeMainPageSliders();
            // fetchMatchingMask();
            if(rawProductDetail.isFabricCustomizable)
                handleFdc(rawProductDetail);

            setTimeout(function () {
                loadCustomStyles();
                fxPopupText();
                appendSavedStyles(rawProductDetail.savedStyles);
                setDefaultStyle();
                applyOtherOptions();
                onSelectedStyleApply();
                setTrackingElements();
            });

            setTimeout(function () {
                setLargeModal();
                handleLargerImageModelEvents();
                loadSizeProfile();

                setTimeout(function () {
                    refreshRecentItems();
                    updateRecentlyViewed();
                    // loadRecentlyViewed();
                    initializeRecentlyViewedSlider();
                    executeYotpo();
                    initializeShareButtons();
                    initializeFxShareButtons();
                    initializeLollypopControls();
                });
            });

            //setTimeout(function () {
            //    //initializeFbPixelViewContent();
            //    window.solusProductDetail && window.solusProductDetail(rawProductDetail)
            //    var userid = getCookie("UID3");
            //    //var Criteo_Tracking = "<script type='text/javascript' src='//static.criteo.net/js/ld/ld.js' async='true'></script>"
            //    //    + " <script type='text/javascript'>"
            //    //    + " window.criteo_q = window.criteo_q || [];"
            //    //    + " window.criteo_q.push("
            //    //    + "     { event: 'setAccount', account: [12194, 13306] },"
            //    //    + "     { event: 'setCustomerId', id: '" + userid + "' },"
            //    //    + "     { event: 'setSiteType', type: '" + window.criteoSiteType + "' },"
            //    //    + "     { event: 'viewItem', product: '" + productId + "' }"
            //    //    + " );"
            //    //    + " </script>";
            //    //$('#divCriteo').html(Criteo_Tracking);

            //    //zaius.event("product",
            //    //    {
            //    //        action: "detail",
            //    //        color: rawProductDetail.colors[0],
            //    //        price: rawProductDetail.listPrice,
            //    //        product_id: productId,
            //    //        name: rawProductDetail.name
            //    //    }
            //    //);


            //    ga('create', getGoogleAnalyticsId());
            //    ga('require', 'ec');

            //    ga('ec:ec:addProduct', {
            //        'id': productId,
            //        'name': rawProductDetail.name,
            //        'brand': rawProductDetail.brand,
            //        'variant': rawProductDetail.colors[0]
            //    });

            //    ga('ec:setAction', 'detail');
            //    ga('send', 'pageview');

            //    //const config = getConfig();
            //    //if (!config.isZapelle) {
            //    //    window.blue_q = window.blue_q || [];
            //    //    window.blue_q.push(
            //    //        { event: "setCampaignId", value: "06551B10-07C4-AECD-8A220C3562319D0C" },
            //    //        { event: "setProductId", value: rawProductDetail.productId },
            //    //        { event: "setPageType", value: "product" }
            //    //    );
            //    //}
            //});
        };

        const onFailure = function (_, status, error) {
            console.error(status, error);
            //$("#overlay").fadeOut(300);
        };

        //$("#overlay").fadeIn(300);

        const productDetailJsonString = $(".hiddenProductDetailJson").val();
        let productDetails = null;
        if (productDetailJsonString)
            productDetails = JSON.parse(productDetailJsonString);

        if (productDetails)
            onSuccess(productDetails);
        else
            sendAjaxGetRequestWithToken(
                `/ProductDetailHandler.ashx?productId=${productId}`,
                onSuccess,
                onFailure
            );
    }

    const matchingMaskContainer = $("#matchingMaskContainer");

    function setMatchingMaskPopup(maskDetailId) {
        if (!maskDetailId)
            return;

        //$("#maskImage").attr("src", maskDetail.lowResImageUrls[0]);
        const onSuccess = function (maskDetail) {
            $("#maskImage").attr("src", `https://img1.eshakti.com/clothimages/${maskDetail.productId}MP.jpg`);
            const maskDetailsContainer = $("#maskDetails");
            maskDetailsContainer.empty();
            maskDetailsContainer.append(
                `<li class="head-txt">${maskDetail.name}</li>`
            );

            const descriptionAllParts = maskDetail.description.split("\n\n");
            descriptionAllParts.splice(0, 2);

            if (descriptionAllParts.length > 0) {
                const descriptionPart = [];
                const productDescription = [];

                descriptionAllParts.forEach((part) => {
                    part.split("|").forEach((split) => {
                        if (split && split.length > 0)
                            descriptionPart.push(split);
                    });
                });

                descriptionPart.forEach((part) => {
                    part.split("<li>").forEach((split) => {
                        if (split && split.length > 0)
                            productDescription.push(split);
                    });
                });

                if (productDescription.length > 0) {
                    productDescription.forEach((part) => {
                        maskDetailsContainer.append(`<li class="product-sub">${part}</li>`);
                    });
                }
            }
            $(".js-Matching-Mask-Model").modal("show");
        }

        const onFailure = function (_, status, error) {
            console.error(status, error);
        };
        sendAjaxGetRequestWithToken(
            `/ProductDetailHandler.ashx?productId=${maskDetailId}`,
            onSuccess,
            onFailure
        );
    }

    function compare(a, b) {
        if (a.last_nom < b.last_nom) {
            return -1;
        }
        if (a.last_nom > b.last_nom) {
            return 1;
        }
        return 0;
    }

    function matchingMaskSort(matchingMaskConfig) {
        const wrapper = $("#matching-masks-swiper-wrapper");
        wrapper.empty();

        const freeIndicator = `<span class="fnt-xxs pop-link matching-mask-details-link" style="text-decoration:none;">FREE</span>`;
        //const freeIndicator = "";
        let matchingMaskSlides = "";
        let firstFreeMask = matchingMaskConfig.freeFirstMask;
        let freeShown = false;
        rawProductDetail.matchingMasks.forEach((maskDetail, index) => {
            const maskSelected = selectedMatchingMask.indexOf(maskDetail.productId) !== -1;
            if (!maskSelected)
                return;

            if (firstFreeMask && !freeShown) {
                matchingMaskSlides += `
                <div class="swiper-slide">
                    <div class="mask-slider-content">
                        <img class="mask-slide-options-img" src="https://img1.eshakti.com/clothimages/${maskDetail.productId}MP.jpg" alt="" />
                        <label class="m-0 label-container label-container--check d-flex flex-column">
                            <span style="color: #f25c50; text-decoration: line-through;">$${maskDetail.discountPrice ? maskDetail.discountPrice.toFixed(2) : maskDetail.listPrice.toFixed(2)}</span>
                            <input type="checkbox" name="matching-mask-multi-checkbox" value="${maskDetail.productId}" checked /><span class="checkmark"></span>
                        </label>
                            ${firstFreeMask === true ? freeIndicator : ""}
                            <span class="fnt-xxs pop-link description-link" href="#" data-toggle="modal" data-target=".js-Matching-Mask-Model" x-data-matching-mask-product-id="${maskDetail.productId}">Details</span>
                    </div>
                </div>`;

                freeShown = true;
                return;
            }

            matchingMaskSlides += `
                <div class="swiper-slide">
                    <div class="mask-slider-content">
                        <img class="mask-slide-options-img" src="https://img1.eshakti.com/clothimages/${maskDetail.productId}MP.jpg" alt="" />
                        <label class="m-0 label-container label-container--check d-flex flex-column">
                            <span style="color: #f25c50">$${maskDetail.listPrice.toFixed(2)}</span>
                            ${maskDetail.discountPrice ? `<span style="color: #2c2a2a; text-decoration: line-through;" class="product-strike">$${maskDetail.discountPrice.toFixed(2)}</span>` : ""}
                            <input type="checkbox" name="matching-mask-multi-checkbox" value="${maskDetail.productId}" checked /><span class="checkmark"></span>
                        </label>
                            <span class="fnt-xxs pop-link description-link" href="#" data-toggle="modal" data-target=".js-Matching-Mask-Model" x-data-matching-mask-product-id="${maskDetail.productId}">Details</span>
                    </div>
                </div>`;
        });

        rawProductDetail.matchingMasks.forEach(maskDetail => {
            const maskSelected = selectedMatchingMask.indexOf(maskDetail.productId) !== -1;
            if (maskSelected)
                return;

            matchingMaskSlides += `
                <div class="swiper-slide">
                    <div class="mask-slider-content">
                        <img class="mask-slide-options-img" src="https://img1.eshakti.com/clothimages/${maskDetail.productId}MP.jpg" alt="" />
                        <label class="m-0 label-container label-container--check d-flex flex-column">
                            <span style="color: #f25c50">$${maskDetail.listPrice.toFixed(2)}</span>
                            ${maskDetail.discountPrice ? `<span style="color: #2c2a2a; text-decoration: line-through;" class="product-strike">$${maskDetail.discountPrice.toFixed(2)}</span>` : ""}
                            <input type="checkbox" name="matching-mask-multi-checkbox" value="${maskDetail.productId}" /><span class="checkmark"></span>
                        </label>
                            <span class="fnt-xxs pop-link description-link" href="#" data-toggle="modal" data-target=".js-Matching-Mask-Model" x-data-matching-mask-product-id="${maskDetail.productId}">Details</span>
                    </div>
                </div>`;
        });

        wrapper.append(matchingMaskSlides);
        initializeMatchingMaskSwiper(matchingMaskConfig);
    }

    function initializeMatchingMaskSwiper(matchingMaskConfig) {
        $(`input[name="matching-mask-multi-checkbox"]`).change(function () {
            const selectedOption = $(this).val();
            if ($(this).is(":checked")) {
                if (selectedMatchingMask.indexOf(selectedOption) == -1) {
                    selectedMatchingMask.push(selectedOption);
                }

            } else {
                if (selectedMatchingMask.length > matchingMaskConfig.minimumMasksToBeSelected) {
                    if (selectedMatchingMask.indexOf(selectedOption) > -1)
                        selectedMatchingMask.splice(selectedMatchingMask.indexOf(selectedOption), 1);
                }
                else {
                    $(this).prop('checked', true);
                    alert('Atleast One Matching Mask should be selected');
                }
            }
            $("#freeMask").text(selectedMatchingMask.length - 1);
            matchingMaskSort(matchingMaskConfig);
        });

        const matchingMaskSwiper = new Swiper('.matchingmask-swiper', {
            slidesPerView: 2.5,
            spaceBetween: 10,
            loop: false,
            observer: true,
            observerParent: true,
            keyboard: {
                enabled: true,
            },
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
        });
    }

    function fetchMatchingMask() {
        matchingMaskContainer.empty();
        $(".pdp-size-container").removeClass("matching-mask-added");

        if (!rawProductDetail.matchingMasks || rawProductDetail.matchingMasks.length === 0) {
            //rawProductDetail.addDefaultMatchingMask && fetchDefaultMatchingMask();
            return;
        }

        $(".pdp-size-container").addClass("matching-mask-added");

        const matchingMaskConfig = JSON.parse($(".hiddenMatchingMaskConfigJson").val());

        const freeIndicator = `<span class="fnt-xxs pop-link matching-mask-details-link" style="text-decoration:none;">FREE</span>`;
        //const freeIndicator = "";
        let matchingMaskSlides = "";
        const selectFirstMask = matchingMaskConfig.selectFirstMask;
        const freeFirstMask = matchingMaskConfig.freeFirstMask;

        rawProductDetail.matchingMasks.forEach((maskDetail, index) => {
            if (index == 0 && selectFirstMask === true)
                selectedMatchingMask.push(maskDetail.productId);

            if (index == 0 && freeFirstMask) {
                matchingMaskSlides += `
                <div class="swiper-slide">
                    <div class="mask-slider-content">
                        <img class="mask-slide-options-img" id="matching-mask-img-slide-${index}" src="https://img1.eshakti.com/clothimages/${maskDetail.productId}MP.jpg" alt="" />
                        <label class="m-0 label-container label-container--check d-flex flex-column">
                            <span style="color: #f25c50; text-decoration: line-through;" id="matching-mask-price-slide-${index}">$${maskDetail.discountPrice ? maskDetail.discountPrice.toFixed(2) : maskDetail.listPrice.toFixed(2)}</span>
                            <input type="checkbox" name="matching-mask-multi-checkbox" value="${maskDetail.productId}" ${index === 0 && selectFirstMask === true ? "checked" : ""} /><span class="checkmark"></span>
                        </label>
                            ${freeIndicator}
                            <span class="fnt-xxs pop-link description-link" href="#" data-toggle="modal" data-target=".js-Matching-Mask-Model" x-data-matching-mask-product-id="${maskDetail.productId}">Details</span>
                    </div>
                </div>`;

                return;
            }

            matchingMaskSlides += `
                <div class="swiper-slide">
                    <div class="mask-slider-content">
                        <img class="mask-slide-options-img" id="matching-mask-img-slide-${index}" src="https://img1.eshakti.com/clothimages/${maskDetail.productId}MP.jpg" alt="" />
                        <label class="m-0 label-container label-container--check d-flex flex-column">
                            <span style="color: #f25c50" id="matching-mask-price-slide-${index}">$${maskDetail.listPrice.toFixed(2)}</span>
                            ${maskDetail.discountPrice ? `<span style="color: #2c2a2a; text-decoration: line-through;" class="product-strike">$${maskDetail.discountPrice.toFixed(2)}</span>` : ""}
                            <input type="checkbox" name="matching-mask-multi-checkbox" value="${maskDetail.productId}" ${index === 0 && selectFirstMask === true ? "checked" : ""} /><span class="checkmark"></span>
                        </label>
                        <span class="fnt-xxs pop-link description-link" href="#" data-toggle="modal" data-target=".js-Matching-Mask-Model" x-data-matching-mask-product-id="${maskDetail.productId}">Details</span>
                    </div>
                </div>`;
        });

        // With free matching mask text
        freeFirstMask && matchingMaskContainer.append(`
                <div class="select-Matching-Mask flex-column">
                    <div class="free-mask-slider">
                        <p class="fnt-700">Free Matching Mask</p>
                        <span class="fnt-10" ${rawProductDetail.matchingMasks.length > 1 ? "" : `style="display:none"`}>${matchingMaskConfig.freeMatchingMaskText}</span>
                        <div class="swiper-arrow-container">
                            <div class="swiper-container matchingmask-swiper">
                                <div class="swiper-wrapper" id="matching-masks-swiper-wrapper">
                                    ${matchingMaskSlides}
                                </div>
                            </div>
                            <div class="swiper-button-next"></div>
                            <div class="swiper-button-prev"></div>
                        </div>
                    </div>
                    <div class="maskselection form-template"></div>
                    <div class="justify-content-start mt-3" style="display:${rawProductDetail.matchingMasks.length > 1 ? "flex" : "none"}">
                        <p style="display:none;">Selected Mask(s): Free - 1, 50% off - <span id="freeMask">0</span></p>
                    </div>
                </div>`);

        !freeFirstMask && matchingMaskContainer.append(`
                <div class="select-Matching-Mask flex-column">
                    <div class="free-mask-slider">
                        <p class="fnt-700 mb-2">Matching Mask</p>
                        <div class="swiper-arrow-container">
                            <div class="swiper-container matchingmask-swiper">
                                <div class="swiper-wrapper" id="matching-masks-swiper-wrapper">
                                    ${matchingMaskSlides}
                                </div>
                            </div>
                            <div class="swiper-button-next"></div>
                            <div class="swiper-button-prev"></div>
                        </div>
                    </div>
                    <div class="maskselection form-template"></div>
                </div>`);

        matchingMaskContainer.show();

        $(document).on('click', ".matching-mask-details-link", function () {
            const matchingMaskProductId = $(this).attr("x-data-matching-mask-product-id");
            const matchingMask = rawProductDetail.matchingMasks.find(m => m.productId === matchingMaskProductId);
            setMatchingMaskPopup(matchingMaskProductId);
        });

        $(document).on('click', ".description-link", function () {
            const matchingMaskProductId = $(this).attr("x-data-matching-mask-product-id");
            setMatchingMaskPopup(matchingMaskProductId);
        });

        initializeMatchingMaskSwiper(matchingMaskConfig);

        var popSwiper = new Swiper('.mask-detail-popup-desc', {
            slidesPerView: 1,
            spaceBetween: 10,
            loop: true,
            observer: true,
            observerParent: true,
            keyboard: {
                enabled: true,
            },
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
        });
    }

    function setProductInformation() {
        //$("#BrandName").text(rawProductDetail.brand);
        //$("#ProductName").text(rawProductDetail.name);
        //$("#StyleNumber").text(`STYLE # ${productId}`);
        $(".yotpo.bottomLine").attr("data-product-id", productId);
        $(".yotpo-main-widget").attr("data-product-id", productId);

        //$("#ListingPrice").text(
        //    `${rawProductDetail.currencySymbol}${rawProductDetail.listPrice.toFixed(
        //        2
        //    )}`
        //);
        //if (rawProductDetail.listPrice !== rawProductDetail.originalPrice) {
        //    $("#OriginalPrice").text(
        //        `${
        //        rawProductDetail.currencySymbol
        //        }${rawProductDetail.originalPrice.toFixed(2)}`
        //    );
        //    $("#OriginalPrice").show();
        //} else $("#OriginalPrice").hide();
        if(rawProductDetail.categories.includes("essentials")) {
            $(".btn-addCart").html("Add To Cart<br><small class='specialOrderTxt'>(Delivery in 21-28 days)</small>"); 
        }
        if (rawProductDetail.isSpecialOrder) {
            $(".btn-addCart").html("Place Special Order<br><small class='specialOrderTxt'>(Delivery in 21-28 days)</small>");
            $(".btn-addCart").removeClass("px-5");
            $(".btn-addCart").addClass("px-4");
            $("#MainContentPlaceHolder_ProductName").append("<span style='font-size: 16px;vertical-align: middle;' class='web-tooltip ml-2'><i class='icon-info' wz_dt_ref='true'></i><span class='web-tooltip__content p-1 px-2'><span>Special orders take 21-28 days to be delivered</span></span></span>");
        }
            
        if (rawProductDetail.isOutOfStock) {
            $(".btn-addCart").text("Out of Stock");
            $(".btn-addCart").prop("disabled", true);

            $("#remindMeSection").show();
            const remindMeSubmitButton = $("#remindMeSubmitButton");

            $("#remindMeForm").submit(function (e) {
                e.preventDefault();
                const remindEmailId = $("#txtnotifEmail").val();
                if (!remindEmailId || remindEmailId.trim().length === 0) {
                    remindMeSubmitButton.text("Submit");
                    remindMeSubmitButton.fadeTo(100, 1);
                    alert("Please enter a valid email id");
                    return;
                }

                const onReminderSuccess = function (result) {
                    remindMeSubmitButton.text("Submit");
                    remindMeSubmitButton.fadeTo(100, 1);
                    alert("You will be notified when the product goes online. Thanks!");
                    $("#remindModal").modal("hide");
                };

                const onReminderError = function (_, status, error) {
                    console.error(status, error);
                    alert("Error! Please try again later");
                };

                remindMeSubmitButton.text("Setting Reminder...");
                remindMeSubmitButton.fadeTo(100, 0.2);
                sendAjaxGetRequestWithToken(`/Handler/ReminderHandler.ashx?productId=${rawProductDetail.productId}&remindEmailId=${remindEmailId}`, onReminderSuccess, onReminderError);
            });
        }

        $("#WishListButton").attr("x-data", productId);
        if (rawProductDetail.wishlistFlag) $("#WishListButton").addClass("active");

        const highResImagesRepeater = $("#HighResImagesRepeater");
        const lowResImagesRepeater = $("#LowResImagesRepeater");
        const colorsRepeater = $("#ColorsRepeater");

        //highResImagesRepeater.empty();
        //lowResImagesRepeater.empty();
        colorsRepeater.empty();

        //let highResImageIndex = 0;
        //rawProductDetail.highResImageUrls.forEach((imageUrl) => {
        //    highResImagesRepeater.append(`
        //        <div class="swiper-slide main-slider" data-toggle="modal" data-target=".img-modal-lg" x-data-target-index="${highResImageIndex++}" x-data-target-image="${imageUrl}">
        //            <img class="img-fluid" src="${imageUrl}" alt="" />
        //        </div>`);
        //});
        //let index = 0;
        //rawProductDetail.lowResImageUrls.forEach((imageUrl) => {
        //    lowResImagesRepeater.append(`
        //        <div
        //            class="swiper-slide thumb-slide"
        //            x-index="${index++}"
        //            style="background-image: url(${imageUrl})">
        //        </div>`);
        //});

        //$('#colorName').append(`Color : ${rawProductDetail.colors.join(", ")}`);

        if (rawProductDetail.otherColors && rawProductDetail.otherColors.length > 0) {
            rawProductDetail.otherColors.forEach(color => {
                colorsRepeater.append(`
                    <label class="label-container color-list-item mb-0" x-data-productId="${color.productId}">
                        <input type="radio" name="color-select" />
                        <span class="checkmark checkmark--circle" style="background:url(${color.imageUrl}) no-repeat scroll center center">
                        <div class="checkborder"></div>
                        </span>
                    </label>`);
            });
            colorsRepeater.append(`
                 <label class="label-container color-list-item mb-0" x-data-productId="${rawProductDetail.productId}">
                     <input type="radio" name="color-select" />
                     <span class="checkmark checkmark--circle" style="background:url(${rawProductDetail.lowResImageUrls[0]}) no-repeat scroll center center">
                     <div class="checkborder"></div>
                     </span>
                 </label>`);
        }

        $(document).on("click", ".color-list-item", function (e) {
            const productId = $(this).attr('x-data-productId');
            const existingProductId = rawProductDetail.productId;
            let existingUrl = window.location.href;
            existingUrl = existingUrl.replace(existingProductId, productId);
            window.location.href = existingUrl;

        });


        //colorsRepeater.empty();
        //colorsRepeater.append(`Color : ${rawProductDetail.colors.join(", ")}`);

        //const descriptionRepeater = $("#DescriptionRepeater");
        //const descriptionAllParts = rawProductDetail.description.split("\n\n");
        //descriptionAllParts.splice(0, 2);

        //if (descriptionAllParts.length > 0) {
        //    const descriptionPart = [];
        //    const productDescription = [];

        //    descriptionAllParts.forEach((part) => {
        //        part.split("|").forEach((split) => {
        //            if (split && split.length > 0) descriptionPart.push(split);
        //        });
        //    });

        //    descriptionPart.forEach((part) => {
        //        part.split("<li>").forEach((split) => {
        //            if (split && split.length > 0) productDescription.push(split);
        //        });
        //    });

        //    if (productDescription.length > 0) {
        //        //$("#ProductDescriptionShort").append(`<li class="product-short-sub">${productDescription[0]}</li>`);
        //        productDescription.splice(0, 1);
        //        //$("#ProductDescriptionShort").append(`<li class="product-short-sub">${productDescription[productDescription.length - 1]}</li>`);
        //        //productDescription.splice(productDescription.length - 1, 1);

        //        productDescription.forEach((part) => {
        //            descriptionRepeater.append(`<li class="product-sub">${part}</li>`);
        //        });
        //    }
        //}
        //$("#ProductDescriptionShort").append(`<li class="product-short-sub">${rawProductDetail.shippingInfo}</li>`);
        //descriptionRepeater.append(`<li class="product-sub">${rawProductDetail.shippingInfo}</li>`);
        //$("#shippingInfoText").html(rawProductDetail.shippingInfo);
    }

    const fxImagePreLoadContainer = $("#fxImagePreLoadContainer");
    function preLoadFxImage(styleImageUrl) {
        fxImagePreLoadContainer.append(`<img modal-lazy-load="${styleImageUrl}"/>`);
    }

    function applyOtherOptions() {
        //rawProductDetail.styles.forEach(style => {
        //    const isOtherOption = style.styleOptions.find(styleOption => !styleOption.imageUrl);
        //    if (!isOtherOption)
        //        return;
        //    const styleType = style.type.replace(/ /g, '-');
        //    const otherOption = style.styleOptions.find(option => option.name === queryString[style.type]);
        //    const friendlyOptionName = otherOption.name.replace(/ /g, '-');
        //    $(`#${styleType}Check00${friendlyOptionName}`).trigger("click");
        //});
    }

    function applyScaling(value) {
        if (window.innerWidth < 768) return parseInt(value) * 0.5;
        else return parseInt(value) * 0.8;
    }

    function onSelectedStyleApply() {
        Object.keys(selectedStyle).forEach((key) => {
            if (
                key !== "otherOptions" &&
                selectedStyle[key] &&
                selectedStyle[key].length > 0
            ) {
                const styleType = key.replace(/ /g, "-");
                const style = rawProductDetail.styles.find(
                    (style) => style.type === key
                );
                const styleOption = style.styleOptions.find(
                    (option) => option.name.toLowerCase() === selectedStyle[key].toLowerCase()
                );
                if (selectedStyle[key] === asShown) {
                    $(`#${styleType}ChangeStyleText`).show();
                    $(`#${styleType}Text`).hide();
                }
                else {
                    $(`#${styleType}ChangeStyleText`).hide();
                    $(`#${styleType}Text`).show();
                    $(`#${styleType}Text`).text(selectedStyle[key]);
                }
                $(`#${styleType}Image`).attr("src", styleOption.imageUrl);
            }
        });

        let titleText = "";
        let index = 0;
        Object.keys(reverseMapping).forEach((key) => {
            if (key !== "otherOptions") {
                if (selectedStyle[key] && selectedStyle[key].length > 0) {
                    if (index++ !== 0)
                        titleText += ", ";

                    titleText += `${selectedStyle[key]}`;
                }
            }
        });

        $(".custom-fx-card-title-text").text(`Selected style options - ${titleText}`);

        if (!rawProductDetail.isCustomPreview || isSelectedStyleAllAsShown()) {
            $("#customizeButton").show();
            $("#resetStyleButton").hide();
            $("#styleByYouDiv").hide();
            $(".preve-img-text").hide();
            $("#Saved-styles").removeClass("show");
            $("#Saved-styles").removeClass("active");
            $("#Saved-styles-tab").removeClass("active");
            $("#mainTabSwitch").hide();
            $("#as-shown-styles").addClass("show");
            $("#as-shown-styles").addClass("active");
            $("#as-shown-styles-tab").addClass("active");
            $("#mainSlidePagination").show();
            $("#pdstyledata").text("");
        } else {
            const imageSource = encodeURI(
                `${customImageHandler}?p=${productId}&n=${selectedStyle.Neckline}&s=${selectedStyle["Sleeve Type"]}&l=${selectedStyle.Length}&pl=${selectedStyle["Pant Length"]}&pst=${rawProductDetail.styleType}`
            );
            $("#styleByYouImage").css("background-image", `url("${imageSource}")`);
            $("#styleByYouImageLarge").attr("src", imageSource);

            $("#customizeButton").hide();
            $("#resetStyleButton").show();
            $("#styleByYouDiv").show();
            $(".preve-img-text").show();
            $("#Saved-styles").addClass("show");
            $("#Saved-styles").addClass("active");
            $("#Saved-styles-tab").addClass("active");
            $("#mainTabSwitch").show();
            $("#as-shown-styles").removeClass("show");
            $("#as-shown-styles").removeClass("active");
            $("#as-shown-styles-tab").removeClass("active");
            $("#mainSlidePagination").hide();
            $("#pdstyledata").text(`Selected style options - ${titleText}`);
        }
    }

    function isSelectedStyleAllAsShown() {
        let isCustomStyle = false;
        Object.keys(selectedStyle).forEach((key) => {
            if (key !== "otherOptions") {
                if (
                    selectedStyle[key] &&
                    selectedStyle[key].length > 0 &&
                    selectedStyle[key] !== asShown
                )
                    isCustomStyle = true;
            }
        });

        return !isCustomStyle;
    }

    $("#resetStyleButton").click(function (e) {
        Object.keys(selectedStyle).forEach((key) => {
            if (
                key !== "otherOptions" &&
                selectedStyle[key] &&
                selectedStyle[key].length > 0
            )
                selectedStyle[key] = asShown;
        });

        selectedStyle.otherOptions &&
            Object.keys(selectedStyle.otherOptions).forEach((key) => {
                selectedStyle.otherOptions[key] = asShown;
            });

        setDefaultStyle();
        findAndSelectSavedStyle();
        onSelectedStyleApply();
    });

    function findAndSelectSavedStyle() {
        let titleText = "";
        let index = 0;
        Object.keys(reverseMapping).forEach((key) => {
            if (key !== "otherOptions") {
                if (selectedStyle[key] && selectedStyle[key].length > 0) {
                    if (index++ !== 0)
                        titleText += ", ";

                    titleText += `${selectedStyle[key]}`;
                }
            }
        });

        $(".custom-fx-card-title-text").text(`Selected style options - ${titleText}`);

        if (!rawProductDetail.isCustomPreview) return;

        let isDefaultStyle = isSelectedStyleAllAsShown();

        if (isDefaultStyle) {
            //$(".js-btn-save").hide();
            $(".js-btn-save").prop("disabled", true);
            $(".js-btn-save").addClass("btn-disable");
            $(`#savedStyle0`).trigger("click");
            return;
        }

        const savedStyle = rawProductDetail.savedStyles.find((style) => {
            let matched = true;
            Object.keys(selectedStyle).forEach((key) => {
                if (key !== "otherOptions") {
                    if (selectedStyle[key] !== style[reverseMapping[key]])
                        matched = false;
                }
            });
            return matched;
        });

        if (savedStyle) {
            //$(".js-btn-save").hide();
            $(".js-btn-save").prop("disabled", true);
            $(".js-btn-save").addClass("btn-disable");
            $(`#savedStyle${savedStyle.id}`).trigger("click");
        } else {
            //$(".js-btn-save").show();
            $(".js-btn-save").prop("disabled", false);
            $(".js-btn-save").removeClass("btn-disable");
        }
    }

    function handleSavedStyleDelete() {
        const closeCards = Array.from(document.querySelectorAll(".close-card"));

        Array.from(closeCards).forEach((node) => {
            node.addEventListener("click", (event) => {
                const savedStyleId = parseInt(
                    node.getAttribute("x-data-saved-style-id")
                );
                if (savedStyleId === selectedSavedStyleId) {
                    defaultSavedStyleRadio.trigger("click");
                }

                const url = `/DeleteSavedCustomStyleHandler.ashx?productId=${productId}&savedStyleId=${savedStyleId}`;

                const onSuccess = function (result) {
                    const index = rawProductDetail.savedStyles.findIndex(
                        (savedStyle) => savedStyle.id === savedStyleId
                    );
                    rawProductDetail.savedStyles.splice(index, 1);
                    appendSavedStyles(rawProductDetail.savedStyles);
                    $("#savedStyle0").trigger("click");
                };

                const onError = function (_, status, error) {
                    console.error(status, error);
                    showDefaultErrorPopup(
                        "Unexpected error",
                        "Deleting the style failed"
                    );
                };

                sendAjaxGetRequestWithToken(url, onSuccess, onError);
            });
        });
    }

    function handleSavedStyleSelect() {
        $('input[name="img-check"]').change(function () {
            if ($(this).is(":checked")) {
                //$(".js-btn-save").hide();
                $(".js-btn-save").prop("disabled", true);
                $(".js-btn-save").addClass("btn-disable");
                $(".js-btn-save").addClass("btn-disable");
                const savedStyleId = $(this).val();
                selectedSavedStyleId = savedStyleId;

                $(".scroll-container .os-viewport").animate(
                    {
                        scrollTop: 0
                    },
                    1500
                );

                if (savedStyleId === "default") {
                    setDefaultStyle();

                    rawProductDetail.styles.forEach((style) => {
                        $(`#${style.type.replace(/ /g, "-")}Check000`).trigger("click");
                    });

                    return;
                }

                const savedStyle = rawProductDetail.savedStyles.find(
                    (style) => style.id === parseInt(savedStyleId)
                );

                Object.keys(savedStyle).forEach((key) => {
                    if (mapping[key]) selectedStyle[mapping[key]] = savedStyle[key];
                });

                rawProductDetail.styles.forEach((style) => {
                    const styleOption = style.styleOptions.find(
                        (option) => option.name === selectedStyle[style.type]
                    );
                    if (!styleOption || !styleOption.name) return;

                    const friendlyOptionName = styleOption.name.replace(/ /g, "-");
                    $(
                        `#${style.type.replace(/ /g, "-")}Check00${friendlyOptionName}`
                    ).trigger("click");
                });
            }
        });
    }

    function returnAsShownStyle(imageSource) {
        const savedStyleId = "default";
        const cardTitle = asShown;

        imageSource = `${customImageHandler}?p=${productId}`;

        rawProductDetail.styles.forEach((style) => {
            if (!customStyleImageParameterMapping[style.type])
                return;

            imageSource += `&${customStyleImageParameterMapping[style.type]}=${asShown}`;
        });

        imageSource += `&pst=${rawProductDetail.styleType}`;

        return `
<li class="slide-item swiper-slide" x-data-saved-style-id="${savedStyleId}">
    <div class="card-wrp">
        <input id="savedStyle0" type="radio" name="img-check" class="d-none img-check" value="${savedStyleId}"/>
        <div class="check-circle"><span></span></div>
        <label for="savedStyle0" class="style-card"><img class="saved-img" src="${imageSource}" alt="style image" /></label>
    </div>
    <div class="d-flex pt-2 align-items-center  " >
        <p class="fnt-11 w-100 pr-2">${cardTitle}</p>
    </div>
</li>`;
    }

    function returnSavedStyle(savedStyle) {
        if (!savedStyle) {
            console.error("Invalid saved style");
            return "";
        }

        const cardTitle = `${savedStyle.neckline}, ${savedStyle.sleeveType}, ${savedStyle.length ? savedStyle.length : savedStyle.pantLength
            }`;
        const imageSource = `${customImageHandler}?p=${productId}&n=${savedStyle.neckline}&s=${savedStyle.sleeveType}&l=${savedStyle.length}&pl=${savedStyle.pantLength}&pst=${rawProductDetail.styleType}`;

        return `
<li class="slide-item swiper-slide" x-data-saved-style-id="${savedStyle.id}">
    <div class="card-wrp">
        <div class="close-card" slide-id="${savedStyle.id}" x-data-saved-style-id="${savedStyle.id}"><span></span><span></span></div>
        <input id="savedStyle${savedStyle.id}" type="radio" name="img-check" class="d-none img-check" value="${savedStyle.id}"/>
        <div class="check-circle"><span></span></div>
        <label for="savedStyle${savedStyle.id}" class="style-card"><img class="saved-img" src="${imageSource}" alt="style image" /></label>
    </div>
    <div class="d-flex pt-2 align-items-center  " >
        <p class="fnt-11 w-100 pr-2">${cardTitle}</p>
        <div class="share">
            <i class="icon-share"></i>
            <div class="tooltip-share">
                <div class="tooltip-share__item pinterest d-flex saved-style-share" x-data="${savedStyle.id}">
                    <i class="icon-pinterest tip-icon"></i>
                    <p class="prd-sub-txt">Pinterest</p>
                </div>
                <div class="tooltip-share__item facebook d-flex saved-style-share" x-data="${savedStyle.id}">
                    <i class="icon-facebook tip-icon"></i>
                    <p class="prd-sub-txt">Facebook</p>
                </div>
                <div class="tooltip-share__item twitter d-flex saved-style-share" x-data="${savedStyle.id}">
                    <i class="icon-twitter tip-icon"></i>
                    <p class="prd-sub-txt">Twitter</p>
                </div>
            </div>
        </div>
    </div>
</li>`;
    }

    function appendSavedStyles(savedStyles) {
        const defaultSavedStyleContainer = $(".defaultSavedStyleContainer");
        const savedStylesCountArea = $(".saved-styles-count-area");
        const savedStyleSliderContainer = $("#savedStyleSlider");

        defaultSavedStyleContainer.empty();
        savedStyleSliderContainer.empty();
        defaultSavedStyleContainer.append(returnAsShownStyle());

        if (savedStyles && savedStyles.length > 0) {
            $(".saveditem-container").css({ display: "block" });
            savedStylesCountArea.text(
                `(${savedStyles.length} item${savedStyles.length > 1 ? "s" : ""})`
            );

            let lastSaved = "";
            savedStyles.forEach((savedStyle) => {
                lastSaved = `#savedStyle${savedStyle.id}`;
                savedStyleSliderContainer.append(returnSavedStyle(savedStyle));
            });

            savedStyleSlider.update();
            handleSavedStyleDelete();
            handleSavedStyleSelect();
            findAndSelectSavedStyle();
            initializeSavedStyleShare();
        } else {
            $(".saveditem-container").css({ display: "none" });

            savedStylesCountArea.text(`(0 items)`);
            savedStyleSlider.update();
            handleSavedStyleDelete();
            handleSavedStyleSelect();

            if (isSelectedStyleAllAsShown()) {
                //$(".js-btn-save").hide();
                $(".js-btn-save").prop("disabled", true);
                $(".js-btn-save").addClass("btn-disable");
                defaultSavedStyleRadio = $("#savedStyle0");
                defaultSavedStyleRadio.trigger("click");
            }
        }
    }

    function handleDenimText() {
        const denimCategories = [
            "jeans",
            "denim dress",
            "denim skirt",
            "denim jacket",
            "denim shirts"
        ];
        const removeMeasurement = [
            "skirt",
            "denim skirt",
            "pant",
            "jeans"
        ]
        const freeRmkCategories = [
            "jeans",
            "pant"
        ];
        const userDetails = getUserDetails();
        if(denimCategories.includes(rawProductDetail.styleType.toLowerCase())) {
            //$(".pd-strip-banner").show();
            //// if(userDetails.privilegeType.toUpperCase() == "PALLADIUM") {
            ////     $(".pd-strip-banner .pipe-line-2").show();
            //// }
            //$(".primary-txt").show();
            //$(".customization-txt").empty();
            //if (userDetails.privilegeType)
            //    $(".pd-strip-banner .pipe-line-1").show();
            const { fgData } = userDetails;
            if (fgData && fgData.isFgSelectedCustomer && fgData.fgOrders && fgData.fgOrders.length < 3) {
                $(".customization-txt").text("Customization fees is 1) $14.95 for Denim Dresses and Jackets 2)$8.95 for Denim Jeans, Shorts, and Skirts 3) $6.95 for Denim Shirts. Customization fees is waived for first 3 orders.");
            } else {
                $(".customization-txt").text("(For custom size and/or custom style, a fee of 1) $6.95 for Denim Shirts, 2) $8.95 for Denim Jeans, Shorts, and Skirts, 3) $14.95 for Denim Dresses & Jackets per item will apply)");
            }
            
        }
        if(freeRmkCategories.includes(rawProductDetail.styleType.toLowerCase())) {
            $(".fgRemake_text").hide();
            $(".freeRemake_text").show();
        }
        if(removeMeasurement.includes(rawProductDetail.styleType.toLowerCase())) {
            $(".bustSize-chart").hide();
        }
    }

    //function handleFreeRmkText() {
    //    const freeRmkCategories = [
    //        "jeans",
    //        "pant"
    //    ];
    //    const userDetails = getUserDetails();
    //    if(freeRmkCategories.includes(rawProductDetail.styleType.toLowerCase())) {
    //        $(".pd-strip-banner").show();
    //        // if(userDetails.privilegeType.toUpperCase() == "PALLADIUM") {
    //        //     $(".secondary-txt").append("<span class='pipe-line'></span> Perfect Fit or Free Remake.");
    //        // }
    //        // else {
    //        //     $(".secondary-txt").text("Perfect Fit or Free Remake.");
    //        //     $(".pd-strip-banner .pipe-line-2").show();
    //        // }
    //        $(".secondary-txt").text("Perfect Fit or Free Remake.");
    //        if(userDetails.privilegeType)
    //            $(".pd-strip-banner .pipe-line-2").show();

    //        $(".secondary-txt").show();
           
    //    }
    //}

    function handleOfferText() {
        const userDetails = getUserDetails();
        if(userDetails.privilegeType) {
            let naturalFabrics = ['cotton poplin','100% cotton','cotton','rayon cotton','cotton jersey knit','cotton linen','100% linen','rayon','chambray']
            let naturalFabricCategories = ['hand block prints','khaddar collection','gingham']
            if(naturalFabrics.includes(rawProductDetail.fabric.toLowerCase()) || rawProductDetail.categories.some(c => naturalFabricCategories.includes(c.toLowerCase()))){
                $("#OfferTxt").show();
            }
        }
    }

    async function handlePrivilegeBenifitText() {
        const userDetails = getUserDetails();
        if(!userDetails) 
            return;

        // switch(userDetails.privilegeType.toUpperCase()) {
        //     case "GOLD":
        //         $(".tier-name").text("Gold");
        //         $(".tier-percent").text("10%");
        //         $(".tier-price").text("100");
        //         break;

        //     case "PLATINUM":
        //         $(".tier-name").text("Platinum");
        //         $(".tier-percent").text("10%");
        //         $(".tier-price").text("100");
        //         break;

        //     case "PALLADIUM":
        //         $(".tier-name").text("Palladium");
        //         $(".tier-percent").text("15%");
        //         $(".tier-price").text("150");
        //         break;
        // }
        $(".note-txt").show();
        //$(".middle-txt").show();
        //$(".pd-strip-banner").show();
        //// if(!rawProductDetail.categories.includes("tops") && userDetails.privilegeType.toUpperCase() == "PALLADIUM") {
        ////     $(".secondary-txt").show();
        //// }
        //if(rawProductDetail.categories.includes("tops")) {
        //    $(".secondary-txt").text("New Tops Program: Lower Prices, Lower Customization & Shipping Fees");
        //    $(".secondary-txt").show();
        //    $(".middle-txt").hide();
        //    $(".pd-strip-banner .pipe-line-2").show();
        //}
        const stripBanner = $("#strip-banner");
        const stripBannerTexts = await getAsync(`/BaseHandler.ashx?type=get-strip-banner-text&pageType=productdetail&productcategory=${rawProductDetail.styleType}`);
        if (!stripBannerTexts || stripBannerTexts.length == 0) {
            stripBanner.hide();
            return;
        }

        let stripBannerTextHtml = '';
        stripBannerTexts.forEach((text, index) => {
            stripBannerTextHtml = stripBannerTextHtml + `<p class="px-2 text-center">${text}</p>`
            if (index < stripBannerTexts.length - 1)
                stripBannerTextHtml = stripBannerTextHtml + `<span class="pipe-line"></span>`
        });

        stripBanner.append(stripBannerTextHtml);
        stripBanner.show();
    }

    getQueryString();
    getProductDetails();
    handleDenimText();
    handlePrivilegeBenifitText(); 
    // handleOfferText();
    //handleFreeRmkText();

    $("#styleByYouDiv").on("click", function (e) {
        $("#Saved-styles").addClass("show");
        $("#Saved-styles").addClass("active");
        $("#as-shown-styles").removeClass("show");
        $("#as-shown-styles").removeClass("active");
    });
    $("#Saved-styles-tab").click(function (e) {
        $("#mainSlidePagination").hide();
    });
    $("#as-shown-styles-tab").click(function (e) {
        $("#mainSlidePagination").show();
    });

    $(".gallery-thumbs").on("click", function (e) {
        $("#Saved-styles").removeClass("show");
        $("#Saved-styles").removeClass("active");
        $("#as-shown-styles").addClass("show");
        $("#as-shown-styles").addClass("active");
        $("#mainSlidePagination").show();
    });

    $(".js-proceed").on("click", function (e) {
        onSelectedStyleApply();
    });

    $(".js-btn-save").click(function (e) {
        if (isSelectedStyleAllAsShown()) return;

        const requestData = {
            styleType: rawProductDetail.styleType,
            sortOrder: 0,
        };
        Object.keys(selectedStyle).forEach((key) => {
            if (key !== "otherOptions") {
                requestData[key.replace(" ", "")] = selectedStyle[key];
            }
        });

        const onSuccess = function (result) {
            setTimeout(function () {
                var topValue = $(".saveditem-container").position().top + 35;

                $(".scroll-container .os-viewport").animate(
                    {
                        scrollTop: topValue,
                    },
                    1500
                );
            });

            $(".saveditem-container").css({ display: "block" });
            rawProductDetail.savedStyles.push(result);
            appendSavedStyles(rawProductDetail.savedStyles);
        };

        sendAjaxPostRequestWithToken(
            `/SaveCustomStyleHandler.ashx?productId=${productId}`,
            requestData,
            onSuccess,
            function (_, status, error) {
                console.error(status, error);
                showDefaultErrorPopup("Unexpected error", "Saving the style failed");
            }
        );
    });

    function isCompleteSizeProfile(sizeOptionsToCompare) {
        if (!rawProductDetail.sizeOptions || !sizeOptionsToCompare)
            return false;

        let isComplete = true;
        rawProductDetail.sizeOptions.forEach(measurement => {
            if (!measurement.optional) {
                const sizeOption = sizeOptionsToCompare.find(option => option.name.replace("*","").toLowerCase().trim() === measurement.name.replace("*","").toLowerCase().trim());
                if (sizeOption && sizeOption.value && sizeOption.value.toString().length > 0) {
                    hasCustomSize = true;
                    isComplete = isComplete && true;
                }
                else
                    isComplete = false;
            }
        });
        return isComplete;
    }

    function loadSizeProfile() {
        loadCustomSizeOptions();
        return;
    }

    function getSizeProfileForCurrentUserFromCache() {
        const sizeProfileJson = localStorage.getItem(sizeProfileLocalStorageKey);
        const sizeProfile = JSON.parse(sizeProfileJson);
        if (!sizeProfile)
            return null;

        const userSizeProfile = sizeProfile.find(profile => profile.userId === $.cookie("UID3"));
        return userSizeProfile;
    }

    function createNewSizeProfile() {
        const newProfile = {
            userId: $.cookie("UID3"),
            measurements: []
        };

        rawProductDetail.sizeOptions.forEach(measurement => {
            newProfile.measurements.push({
                name: measurement.name,
                value: getSelectedSizeForOption(measurement.name)
            });
        });

        return newProfile;
    }

    function getSelectedSizeForOption(optionName) {
        for (const key of Object.keys(selectedSize)) {
            if (key.toLowerCase() === optionName.toLowerCase())
                return selectedSize[key];
        }

        return null;
    }

    function setSizeProfileIntoCache() {
        if (!rawProductDetail.sizeOptions || !selectedSize)
            return;

        const sizeProfileJson = localStorage.getItem(sizeProfileLocalStorageKey);
        if (!sizeProfileJson) {
            logInfo("local storage is empty");
            localStorage.setItem(sizeProfileLocalStorageKey, JSON.stringify([createNewSizeProfile()]));
            return;
        }

        const sizeProfile = JSON.parse(sizeProfileJson);
        const userSizeProfileIndex = sizeProfile.findIndex(profile => profile.userId === $.cookie("UID3"));
        if (userSizeProfileIndex < 0) {
            logInfo("size profile not present for the current user");
            sizeProfile.push(createNewSizeProfile());
            localStorage.setItem(sizeProfileLocalStorageKey, JSON.stringify(sizeProfile));
            return;
        }

        if (!sizeProfile[userSizeProfileIndex] || !sizeProfile[userSizeProfileIndex].measurements) {
            logInfo("invalid size profile for the current user");
            sizeProfile[userSizeProfileIndex] = createNewSizeProfile();
            localStorage.setItem(sizeProfileLocalStorageKey, JSON.stringify(sizeProfile));
            return;
        }

        rawProductDetail.sizeOptions.forEach(measurement => {
            const sizeOptionIndex = sizeProfile[userSizeProfileIndex].measurements.findIndex(option => option.name.toLowerCase() === measurement.name.toLowerCase());
            const newSizeOption = {
                name: measurement.name,
                value: getSelectedSizeForOption(measurement.name)
            };

            if (sizeOptionIndex < 0) {
                sizeProfile[userSizeProfileIndex].measurements.push(newSizeOption);
                return;
            }

            sizeProfile[userSizeProfileIndex].measurements[sizeOptionIndex] = newSizeOption;
        });

        logInfo(`updated user size profile. ${JSON.stringify(sizeProfile[userSizeProfileIndex])}`);
        localStorage.setItem(sizeProfileLocalStorageKey, JSON.stringify(sizeProfile));
        return;
    }

    async function loadCustomSizeOptions() {
        let optionalPresent = false;
        const mandatorySizeOptions = $("#mandatorySizeOptions");
        const optionalSizeOptions = $("#optionalSizeOptions");
        const heightSelectContainer = $(".heightSelectContainer");

        mandatorySizeOptions.empty();
        optionalSizeOptions.empty();
        heightSelectContainer.empty();
        $("#measureContainer").empty();

        rawUserSizeProfile = rawProductDetail.sizeOptions;
        
        hasCompleteSizeProfile = false;

        let userSizeProfile = getSizeProfileForCurrentUserFromCache();
        if (!userSizeProfile) {
            userSizeProfile = await getAsync("/UserHandler.ashx?action=getsizeprofile");
            if (userSizeProfile && userSizeProfile.measurements) {
                rawUserSizeProfile = userSizeProfile.measurements;
            }
        }
        else if (userSizeProfile && userSizeProfile.measurements) {
            rawUserSizeProfile = userSizeProfile.measurements;
        }
        else {
            //console.log("user has no complete size profile");
        }

        if (userSizeProfile && userSizeProfile.measurements && isCompleteSizeProfile(userSizeProfile.measurements)) {
            hasCompleteSizeProfile = true;
        }

        rawProductDetail.sizeOptions.forEach((sizeOption) => {
            if (sizeOption.name.toLowerCase() === "height")
                return heightSelectContainer.append(returnHeightSelect(sizeOption));

            if (!sizeOption.optional)
                mandatorySizeOptions.append(returnSizeOption(sizeOption));
            else {
                optionalPresent = true;
                optionalSizeOptions.append(returnSizeOption(sizeOption));
            }
        });

        if (optionalPresent) $(".optionalArea").show();
        else $(".optionalArea").hide();

        if (hasCustomSize) {
            $("#pills-home-tab").removeClass("active");
            $("#pills-profile-tab").addClass("active");
            $("#pills-home").removeClass("show");
            $("#pills-home").removeClass("active");
            $("#pills-profile").addClass("show");
            $("#pills-profile").addClass("active");

            size = customSizeText;
        }

        if (hasCompleteSizeProfile && !rawProductDetail.isOutOfStock) {
            $(".pdp-size-container").hide();
            $(".btn-editsize").show();
        } else {
            $(".btn-editsize").hide();
        }

        selectit(".select_box");
        handleIconClick();
        handleMeasurementChange();
        $(".custom-failure-popup").on("hidden.bs.modal", function () {
            document.querySelector(".pdp-size-container").scrollIntoView();
        });
    }

    $(".btn-editsize").on("click", function () {
        $(".pdp-size-container").slideToggle(500, stickyAddCartBtn);
        $(".btn-editsize").hide();
    });

    $("#pills-home-tab").click(function (e) {
        size = standardSizeText;
    });

    $("#pills-profile-tab").click(function (e) {
        size = customSizeText;
    });

    $('input[name="size"]').change(function () {
        if ($(this).is(":checked")) {
            selectedSize.standardSize = $(this).val();
        }
    });

    function handleIconClick() {
        $(".measurement-icon").click(function (e) {
            $("#measureImage").attr("src", $(this).attr("x-data-imageUrl"));
            $("#measureText").text($(this).attr("x-data-imageText"));
            $("#measureName").text($(this).attr("x-data-name"));
        });
    }

    function handleMeasurementChange() {
        $("select.select_box").change(function () {
            selectedSize[$(this).attr("x-data-name")] = $(this)
                .children("option:selected")
                .val();
        });
    }

    handleMeasurementChange();

    addToCartButton.click(function (e) {
        if (!validateInputs()) return;

        addToCartButton.text("Adding to cart");
        addToCartButton.prop("disabled", true);

        const onError = function (_, status, error) {
            console.error(status, error);
            addToCartButton.text("Add to cart");
            addToCartButton.prop("disabled", false);
            showDefaultErrorPopup(
                "Add to cart failed",
                "Unexpected error while adding the item to cart"
            );
        };

        const onSuccess = function (result) {
            if (!result || result.error) {
                addToCartButton.text("Add to cart");
                addToCartButton.prop("disabled", false);
                showDefaultErrorPopup(
                    "Add to cart failed",
                    "Unexpected error while adding the item to cart"
                );
                return;
            }

            addToCartButton.text("Added to cart");

            //zaius.event("product",
            //    {
            //        action: "add_to_cart",
            //        product_id: productId,
            //    }
            //);
            window.FMApi = window.FMApi || [];
            window.FMApi.push('zg_trackEvent', 'Add to Cart');


            ga('create', getGoogleAnalyticsId());
            ga('require', 'ec');

            ga('ec:addProduct', {
                'id': rawProductDetail.productId,
                'name': rawProductDetail.name,
                'brand': rawProductDetail.brand,
                'variant': rawProductDetail.colors[0],
                'price': rawProductDetail.listPrice,
            });
            ga('ec:setAction', 'add');
            ga('send', 'event', 'UX', 'click', 'add to cart');

            ga('create', getGoogleAnalyticsId());
            ga('require', 'ec');

            ga('ec:addProduct', {
                'id': rawProductDetail.productId,
                'name': rawProductDetail.name,
                'brand': rawProductDetail.brand,
                'variant': rawProductDetail.colors[0],
                'price': rawProductDetail.listPrice,
            });
            ga('ec:setAction', 'checkout', {
                'step': 1,
            });
            ga('send', 'event');
            //ovontsProductAddedToCart(rawProductDetail,result);
            //fbAddToCartPixel();
            window.location.href = "/ShoppingCart.aspx";
        };

        const onProductAddedToCart = function (result) {
            if (!result || result.error) {
                showDefaultErrorPopup(
                    "Add to cart failed",
                    "Unexpected error while adding the item to cart"
                );
                return;
            }

            if (selectedMatchingMask && selectedMatchingMask.length > 0) {
                const maskData = {
                    productId: selectedMatchingMask,
                    quantity: 1,
                    parentItemId: result
                };
                //console.log(maskData);
                sendAjaxPostRequestWithToken(
                    "/AddToCartHandler.ashx",
                    maskData,
                    onSuccess,
                    onError
                );
            } else onSuccess(result);
        };

        const data = prepareAddToCartData();
        data.originUrl = location.href;

        sendAjaxPostRequestWithToken(
            "/AddToCartHandler.ashx",
            data,
            onSuccess,
            onError
        );
    });

    function initializeFbPixelViewContent() {
        fbq('track', 'ViewContent', {
            content_name: rawProductDetail.name,
            content_category: rawProductDetail.styleType,
            content_ids: [rawProductDetail.productId],
            content_type: 'product',
            value: rawProductDetail.listPrice,
            currency: "USD"
        });
    }

    function fbAddToCartPixel() {
        // Facebook Addto Cart pixel as well
        if (typeof window._fbq != 'undefined') {
            window._fbq = window._fbq || [];
            window._fbq.push(['track', '6025335509790', { 'value': rawProductDetail.listPrice, 'currency': "USD" }]);
            //Facebook custom audience pixel for Add to cart
            fbq('track', 'AddToCart', {
                content_name: rawProductDetail.name,
                content_category: rawProductDetail.styleType,
                content_ids: [rawProductDetail.productId],
                content_type: 'product',
                value: rawProductDetail.listPrice,
                currency: "USD"
            });
        }
    }

    function prepareAddToCartData() {
        const data = {
            productId: rawProductDetail.productId,
            quantity: 1,
            heightInfo: selectedSize.height,
            styleInfo: [],
            sizeInfo: {
                measurements: [],
            },
            selectedAddOns: [...selectedMatchingMask]
        };

        Object.keys(selectedStyle).forEach((key) => {
            if (
                key !== "otherOptions" &&
                selectedStyle[key] &&
                selectedStyle[key].length > 0
            ) {
                data.styleInfo.push({
                    type: key,
                    styleOption: selectedStyle[key],
                });
            }
        });

        Object.keys(selectedStyle.otherOptions).forEach((key) => {
            data.styleInfo.push({
                type: key,
                styleOption: selectedStyle.otherOptions[key],
            });
        });

        if (size === standardSizeText) {
            data.sizeInfo.type = 0;
            data.sizeInfo.measurements.push({
                name: "Size",
                value: selectedSize.standardSize,
            });
        } else {
            data.sizeInfo.type = 1;
            rawProductDetail.sizeOptions.forEach((sizeOption) => {
                if (sizeOption.name.toLowerCase() !== "height")
                    if (
                        selectedSize[sizeOption.name] &&
                        selectedSize[sizeOption.name] !== "select"
                    )
                        data.sizeInfo.measurements.push({
                            name: sizeOption.name,
                            value: selectedSize[sizeOption.name]
                        });
            });

            setSizeProfileIntoCache();
        }

        return data;
    }

    function validateInputs() {
        //console.log(selectedSize);
        $(`input[name="size"]`).each(function () {
            if ($(this).is(":checked")) {
                const value = $(this).val();
                if (value && value !== "select") selectedSize.standardSize = value;
            }
        });
        $("select.select_box").each(function () {
            const value = $(this).children("option:selected").val();
            if (value && value !== "select")
                selectedSize[$(this).attr("x-data-name")] = value;
        });

        if (size === standardSizeText) {
            if (
                !selectedSize ||
                !selectedSize.standardSize ||
                selectedSize.standardSize.length === 0
            ) {
                showDefaultErrorPopup(
                    "Select Your Size",
                    "Please choose either standard size or custom size measurement."
                );
                return false;
            }

            if (!selectedSize.height || selectedSize.height === "select") {
                showDefaultErrorPopup(
                    "Select Your Height",
                    "Please select a measurement for height"
                );
                return false;
            }
        } else {
            let result = true;
            rawProductDetail.sizeOptions.forEach((sizeOption) => {
                if (sizeOption.name.toLowerCase() !== "height") {
                    if (
                        !sizeOption.optional &&
                        (!selectedSize[sizeOption.name] ||
                            selectedSize[sizeOption.name].length === 0 ||
                            selectedSize[sizeOption.name].toLowerCase() === "select")
                    ) {
                        showDefaultErrorPopup(
                            "Select Your Size",
                            "Please provide all the custom size measurements."
                        );
                        result = false;
                    }
                }
            });

            if (result) {
                if (!selectedSize.height || selectedSize.height === "select") {
                    showDefaultErrorPopup(
                        "Validation error",
                        "Please select a measurement for height"
                    );
                    return false;
                }
            }

            return result;
        }

        return true;
    }

    function initializeShareButtons() {
        $(document).on("click", ".tooltip-share__item.facebook.product-share", function (e) {
            e.preventDefault();
            e.stopPropagation();
            FB.ui(
                {
                    method: "share",
                    hashtag: "#eShakti",
                    href: encodeURI(`${getShareProductUrl()}${isSelectedStyleAllAsShown(selectedStyle) ? "?" : "&"}utm_medium=pdshare&utm_source=facebook`),
                },
                function (response) { }
            );
        });

        $(document).on("click", ".tooltip-share__item.twitter.product-share", function (e) {
            e.preventDefault();
            e.stopPropagation();
            const twitterUrl = encodeURI(
                `${getShareProductUrl()}?utm_medium=pdshare&utm_source=twitter`
            );

            const onSuccess = function (shortUrl) {
                const twitterText = encodeURI(
                    `I <3 this ${rawProductDetail.name} from eShakti! Check it out now ${shortUrl}&hashtags=eShakti`
                );
                const shareUrl = `https://twitter.com/intent/tweet?text=${twitterText}`;
                window.open(shareUrl, "sharer", "width=626,height=436");
            };

            const onError = function (_, status, error) {
                console.error(status, error);
            };

            sendAjaxPostRequestWithToken(
                `/handler/URLShorten.ashx`,
                {
                    pageUrl: twitterUrl,
                },
                onSuccess,
                onError
            );
        });

        $(document).on("click", ".tooltip-share__item.pinterest.product-share", function (e) {
            e.preventDefault();
            e.stopPropagation();
            const productUrl = encodeURIComponent(`${getShareProductUrl()}&utm_medium=pdshare&utm_source=pinterest`);
            const imageUrl = encodeURIComponent(getProductImage());
            const pinterestText = `I <3 this ${rawProductDetail.name} from eShakti! Check it out now`;

            const shareUrl = `http://www.pinterest.com/pin/create/button/?url=${productUrl}&media=${imageUrl}&description=${pinterestText}`;
            window.open(shareUrl, "sharer", "width=626,height=436");
        });
    }

    function getShareProductUrl(savedStyle) {
        let productStyleType = rawProductDetail.styleType;
        if (styleTypeUrlMapping && styleTypeUrlMapping[productStyleType]) {
            productStyleType = styleTypeUrlMapping[productStyleType];
        }
        let productUrl = `${baseUrl}/shop/${productStyleType}/${rawProductDetail.name.replace(/ /g, "-")}-${productId}`;
        if (savedStyle) {
            let index = 0;
            Object.keys(savedStyle).forEach((key) => {
                if (key.toLowerCase() === "productid" || key.toLowerCase() === "id") return;

                if (savedStyle[key] && savedStyle[key].length > 0) {
                    productUrl += index++ === 0 ? "?" : "&";
                    productUrl += `${mapping[key]}=${savedStyle[key]}`;
                }
            });
            return productUrl;
        }
        else {
            if (isSelectedStyleAllAsShown(selectedStyle))
                return productUrl;

            let index = 0;
            Object.keys(selectedStyle).forEach((key) => {
                if (key.toLowerCase() === "otheroptions") return;

                if (selectedStyle[key] && selectedStyle[key].length > 0) {
                    productUrl += index++ === 0 ? "?" : "&";
                    productUrl += `${key}=${selectedStyle[key]}`;
                }
            });
            Object.keys(selectedStyle.otherOptions).forEach((key) => {
                if (
                    selectedStyle.otherOptions[key] &&
                    selectedStyle.otherOptions[key].length > 0
                ) {
                    productUrl += index++ === 0 ? "?" : "&";
                    productUrl += `${key}=${selectedStyle.otherOptions[key]}`;
                }
            });
        }

        return productUrl;
    }

    function getProductImage(savedStyle) {
        if (savedStyle) {
            return `${location.origin}/${customImageHandler}?p=${productId}&n=${savedStyle.neckline}&s=${savedStyle.sleeveType}&l=${savedStyle.length}&pl=${savedStyle.pantLength}&pst=${rawProductDetail.styleType}`;
        }

        if (isSelectedStyleAllAsShown(selectedStyle))
            return rawProductDetail.lowResImageUrls[0];

        return `${location.origin}/${customImageHandler}?p=${productId}&n=${selectedStyle.Neckline}&s=${selectedStyle["Sleeve Type"]}&l=${selectedStyle.Length}&pl=${selectedStyle["Pant Length"]}&pst=${rawProductDetail.styleType}`;
    }

    function initializeSavedStyleShare() {
        $(".tooltip-share__item.facebook.saved-style-share").click(function (e) {
            e.preventDefault();
            const savedStyleId = $(this).attr("x-data");
            const savedStyle = rawProductDetail.savedStyles.find(ss => ss.id == savedStyleId);
            const productUrl = getShareProductUrl(savedStyle);
            FB.ui(
                {
                    method: "share",
                    hashtag: "#eShakti",
                    href: encodeURI(`${productUrl}${isSelectedStyleAllAsShown(selectedStyle) ? "?" : "&"}utm_medium=pdshare&utm_source=facebook`),
                },
                function (response) { }
            );
        });

        $(".tooltip-share__item.twitter.saved-style-share").click(function (e) {
            e.preventDefault();
            const savedStyleId = $(this).attr("x-data");
            const savedStyle = rawProductDetail.savedStyles.find(ss => ss.id == savedStyleId);
            const productUrl = getShareProductUrl(savedStyle);
            const twitterUrl = encodeURI(
                `${productUrl}&utm_medium=pdshare&utm_source=twitter`
            );

            const onSuccess = function (shortUrl) {
                const twitterText = encodeURI(
                    `eShakti - ${rawProductDetail.name} as styled by me! Check it out now&url=${shortUrl}&hashtags=eShakti`
                );
                const shareUrl = `https://twitter.com/intent/tweet?text=${twitterText}`;
                window.open(shareUrl, "sharer", "width=626,height=436");
            };

            const onError = function (_, status, error) {
                console.error(status, error);
            };

            sendAjaxPostRequestWithToken(
                `/handler/URLShorten.ashx`,
                {
                    pageUrl: twitterUrl,
                },
                onSuccess,
                onError
            );
        });

        $(".tooltip-share__item.pinterest.saved-style-share").click(function (e) {
            e.preventDefault();
            const savedStyleId = $(this).attr("x-data");
            const savedStyle = rawProductDetail.savedStyles.find(ss => ss.id == savedStyleId);
            const productUrl = encodeURIComponent(`${getShareProductUrl(savedStyle)}&utm_medium=pdshare&utm_source=pinterest`);
            const imageUrl = encodeURIComponent(getProductImage(savedStyle));
            const pinterestText = `eShakti - ${rawProductDetail.name} as styled by me! Check it out now`;

            const shareUrl = `http://www.pinterest.com/pin/create/button/?url=${productUrl}&media=${imageUrl}&description=${pinterestText}`;
            window.open(shareUrl, "sharer", "width=626,height=436");
        });
    }

    function initializeFxShareButtons() {
        $(".tooltip-share__item.facebook.fx-share").click(function (e) {
            e.preventDefault();
            const productUrl = getShareProductUrl();
            FB.ui(
                {
                    method: "share",
                    hashtag: "#eShakti",
                    href: encodeURI(`${productUrl}${isSelectedStyleAllAsShown(selectedStyle) ? "?" : "&"}utm_medium=pdshare&utm_source=facebook`),
                },
                function (response) { }
            );
        });

        $(".tooltip-share__item.twitter.fx-share").click(function (e) {
            e.preventDefault();
            const productUrl = getShareProductUrl();
            const twitterUrl = encodeURI(
                `${productUrl}&utm_medium=pdshare&utm_source=twitter`
            );

            const onSuccess = function (shortUrl) {
                const twitterText = encodeURI(
                    `eShakti - ${rawProductDetail.name} as styled by me! Check it out now&url=${shortUrl}&hashtags=eShakti`
                );
                const shareUrl = `https://twitter.com/intent/tweet?text=${twitterText}`;
                window.open(shareUrl, "sharer", "width=626,height=436");
            };

            const onError = function (_, status, error) {
                console.error(status, error);
            };

            sendAjaxPostRequestWithToken(
                `/handler/URLShorten.ashx`,
                {
                    pageUrl: twitterUrl,
                },
                onSuccess,
                onError
            );
        });

        $(".tooltip-share__item.pinterest.fx-share").click(function (e) {
            e.preventDefault();
            const productUrl = encodeURIComponent(`${getShareProductUrl()}&utm_medium=pdshare&utm_source=pinterest`);
            const imageUrl = encodeURIComponent(getProductImage());
            const pinterestText = `eShakti - ${rawProductDetail.name} as styled by me! Check it out now`;

            const shareUrl = `http://www.pinterest.com/pin/create/button/?url=${productUrl}&media=${imageUrl}&description=${pinterestText}`;
            window.open(shareUrl, "sharer", "width=626,height=436");
        });
    }

    const websiteFeedbackSubmitButton = $("#websiteFeedbackSubmitButton");
    const toggleSubmitButton = function (toggle) {
        if (toggle) {
            websiteFeedbackSubmitButton.text("Submit");
            websiteFeedbackSubmitButton.fadeTo(100, 1);
        } else {
            websiteFeedbackSubmitButton.text("Submitting Feedback...");
            websiteFeedbackSubmitButton.fadeTo(100, 0.2);
        }
    }

    function initializeFeedbackPopup() {
        $("#websiteFeedbackForm").submit(function (e) {
            e.preventDefault();
            const txtComments = $("#txtComments").val();
            const answer = $(`input[name="public-permit"]`).is(":checked");

            const feedbackData = {
                questionId: 26,
                comments: `${productId}-${txtComments}`,
                yesOrNo: answer ? "yes" : "no"
            };

            const onFeedbackUpdate = function (result) {
                toggleSubmitButton(true);
                $("#websiteFeedbackPopup").modal("hide");
                if (!result) {
                    showDefaultErrorPopup("Error", "Unexpected error while submitting the feedback");
                }
            };

            const onError = function (_, status, error) {
                console.error(status, error);
                toggleSubmitButton(true);
                $("#websiteFeedbackPopup").modal("hide");
                showDefaultErrorPopup("Error", "Unexpected error while submitting the feedback");
            }

            toggleSubmitButton(false);
            sendAjaxPostRequestWithToken("/handler/PageFeedback.ashx?action=savefeedback", feedbackData, onFeedbackUpdate, onError);
        });
    }


    // Test for mobile height
    let vh = window.innerHeight * 0.01;
    document.documentElement.style.setProperty("--vh", `${vh}px`);
    window.addEventListener("resize", () => {
        let vh = window.innerHeight * 0.01;
        document.documentElement.style.setProperty("--vh", `${vh}px`);
        fxPopupText();
    });


    const mobileTitleFx = "eShakti FX";
    const mobileTitleNonFx = "Customize your style";
    const mobileDescriptionFx = "Click on any box and see the style change!";
    const mobileDescriptionNonFx = "This product is currently not enabled for FX.";
    const desktopTitleFx = "Customize your style with eShakti FX";
    const desktopTitleNonFx = "Customize your style";
    const desktopDescriptionFx = "Click on any box and see the style change!";
    const desktopDescriptionNonFx = "This product is currently not enabled for FX.";

    function fxPopupText() {
        // Customize popup text change for mobile view
        if (!rawProductDetail)
            return;

        if ($(window).width() < 767) {
            $(".model-22").text(isCustomPreviewGlobal ? mobileTitleFx : mobileTitleNonFx);
            $("#customizeText2").text(isCustomPreviewGlobal ? mobileDescriptionFx : mobileDescriptionNonFx);
        } else {
            $(".model-22").text(isCustomPreviewGlobal ? desktopTitleFx : desktopTitleNonFx);
            $("#customizeText2").text(isCustomPreviewGlobal ? desktopDescriptionFx : desktopDescriptionNonFx);
        }
    }
});

function selectFabricClick() {
    if (!fabImgProp) {
        alert("Please select the fabric for Fabric Customization.");
    }
    else {
        var url = window.location.origin + '/fabricDesignCustomPD.aspx?productid=' + rawProductDetail.productId;
        Object.keys(selectedStyle).forEach((key) => {
            if (key === "otherOptions") return;

            if (selectedStyle[key] && selectedStyle[key].length > 0) {
                url += `&${key}=${selectedStyle[key]}`;
            }
        });
        Object.keys(selectedStyle.otherOptions).forEach((key) => {
            if (
                selectedStyle.otherOptions[key] &&
                selectedStyle.otherOptions[key].length > 0
            ) {
                url += `&${key}=${selectedStyle.otherOptions[key]}`;
            }
        });
        url = url + `&FabProductId=${fabImgProp.ProductId}`
        window.location.href = url;
    }
}

$(function () {
    $('.model-img-tab-container').click(function () {
        $('.modal').modal('hide');
    });
    // $(".bd-fabric-modal-lg").modal("show");
});;
let fdcPageStartIndex = 0;
let fdcPageEndIndex = 29;
let product_Detail;

function handleFdc(productDetail) {
    product_Detail = productDetail;
    $(".fabCus").slideToggle();
    $("div.fcminimize").fadeToggle("slow");
    $(".bd-fabric-modal-lg .disimglt").children('img').attr('src', productDetail.highResImageUrls[0]);
    $(".catbytextbox, .mobcatarrow").click(function () {
        $(".cat-option-content").slideToggle(500);
        $(".mobcatarrow").toggleClass("arrowActive");
    });
    $('.bd-fabric-modal-lg .modal-content').on('scroll', function() {
        if($(this)[0].scrollHeight - $(this)[0].scrollTop - $(this)[0].clientHeight < 1) {
            fdcPageStartIndex = fdcPageStartIndex + 30;
            fdcPageEndIndex = fdcPageEndIndex + 30;
            FilterFdcProducts(productDetail.fabricType, $(".catbytextbox").attr("value"), fdcPageStartIndex, fdcPageEndIndex, $(".sortbytextbox").attr("value"));
        }
    })
    $(document).on("click", ".cat-option-content span", function (e) {
        e.preventDefault();
        var name = $(this).text();
        var value = $(this).attr("data-value");
        $(".catbytextbox").text(name);
        $(".catbytextbox").attr("value", value);
        $('.cat-option-content').fadeToggle(200);
        fdcPageStartIndex = 0;
        fdcPageEndIndex = 29;
        FilterFdcProducts(productDetail.fabricType, value, fdcPageStartIndex, fdcPageEndIndex, $(".sortbytextbox").attr("value"));
    });
    $(".fabbytextbox, .fabsortarrow").click(function () {
        $(".fab-option-content").slideToggle(500);
        $(".mobfabarrow").toggleClass("arrowActive");
    });
    $(document).on("click", ".fab-option-content span", function (e) {
        e.preventDefault();
        var name = $(this).text();
        $(".fabbytextbox").text(name);
        $('.fab-option-content').fadeToggle(200);
    });
    $(".sortbytextbox, .mobsortarrow").click(function () {
        $(".sortby-option-content").slideToggle(500);
        $(".mobsortarrow").toggleClass("arrowActive");
    });
    $(document).on("click", ".sortby-option-content span", function (e) {
        e.preventDefault();
        var name = $(this).text();
        var value = $(this).attr("data-value");
        $(".sortbytextbox").text(name);
        $(".sortbytextbox").attr("value", value);
        $('.sortby-option-content').fadeToggle(200);
        fdcPageStartIndex = 0;
        fdcPageEndIndex = 29;
        FilterFdcProducts(productDetail.fabricType, $(".catbytextbox").attr("value"), fdcPageStartIndex, fdcPageEndIndex, value);
    });
    $(".fcminimize").click(function () {
        $(".fabCus").slideToggle();
        $("div.fcminimize").fadeToggle("slow");
    });
    
    FilterFdcProducts(productDetail.fabricType, "dress", fdcPageStartIndex, fdcPageEndIndex, "Topsellers");
}   

async function FilterFdcProducts(fabtype, category, startIndex, endIndex, sort) {
    const fdcProducts = await getAsync(`/FDCHandler.ashx?type=get-fabric-products&fabricType=${fabtype}&category=${category}&startIndex=${startIndex}&endIndex=${endIndex}&sorting=${sort}`);
    if(!fdcProducts || !fdcProducts.products) {
        return;
    }
    
    $(".catbytextbox").text(fdcProducts.filters.styleTypeFilters.defaultOption.name);
    $(".catbytextbox").attr("value", fdcProducts.filters.styleTypeFilters.defaultOption.value);
    $(".sortbytextbox").text(fdcProducts.filters.sortOptions.defaultOption.name);
    $(".sortbytextbox").attr("value", fdcProducts.filters.sortOptions.defaultOption.value);
    $("#customizeFabricButton").show();
    $(".customizefab-note").show();
    $(".cat-option-content").empty();
    $(".sortby-option-content").empty();
   
    fdcProducts.filters.styleTypeFilters.options.forEach(el => {
        $(".cat-option-content").append(`<li><span data-value="${el.value}">${el.name}</span></li>`)
    });
    fdcProducts.filters.sortOptions.options.forEach(el => {
        $(".sortby-option-content").append(`<li><span data-value="${el.value}">${el.name}</span></li>`)
    });
    
    let productItems = ``;
    fdcProducts.products.forEach(product => {
            if(product_Detail.productId == product.productId)
                return;

            let productItem = `<li class="prod-list">
            <div class="products">
            <span class="imgfab">
            <img id="${product.productId}" src="${product.highResImageUrls[0]}" title="${product.productId}" class="imgswitch">
            </span>
            
                <div class="fcbtn"> <input value="Select This Fabric" onclick="fabimgClick('${product.productId}','${product.highResImageUrls[0]}','${product.fabricType}','${product.styleType}');" class="fabbtn fabimg" type="button"></div>
                        <span class="product-type">${product.name}</span>
            </div>
            </li>`
            productItems = productItems + productItem;
    });

    if(startIndex == 0) {
        $("#ulProductList").empty();
        if(productItems == ``)
            productItems="<p class='p-3'><b>No Products</b></p>"
            
        $(".product-list").animate({ scrollTop: 0 }, "slow");
        $("#ulProductList").html(productItems);
    }
    else
        $("#ulProductList").append(productItems);

};
async function productDetailsPageRecommendations() {
    const productId = $(".hiddenProduct").val();
    const result = await getAsync(`/baseHandler.ashx?type=get-product-details-page-recommendations&productId=${productId}`);

    if (!result || !result.products || result.products.length < 5) {
        return;
    }

    const recommendationsSwiper = $("#recommendationsSwiper");
    recommendationsSwiper.empty();

    result.products.forEach(product => {
        if (!product.highResImageUrls || product.highResImageUrls.length === 0)
            return;

        const originalPriceTag =
            `<p class="top-product-original ml-2 fnt-xs">${product.currencySymbol}${product.originalPrice.toFixed(2)}</p>`;

        recommendationsSwiper.append(`<div class="swiper-slide">
                    <a href="/product/${product.productId}?source=solus_web&medium=pd&campaign=myeshakti" target="_blank">
	    		        <img class="top-category-img" src="${product.highResImageUrls[0]}" alt="" />
                    </a>
			        <p class="top-product-title mt-2 fnt-xs text-capitalize">${product.name.toLowerCase()}</p>
                    <div class="d-flex justify-content-start mt-1">
		                <p class="top-product-price fnt-xs">${product.currencySymbol}${product.listPrice.toFixed(2)}</p>
                        ${product.listPrice !== product.originalPrice ? originalPriceTag : ""}
                    </div>
		        </div>`);
    });

    $("#recommendationsSection").show();

    const topCategorySwiper = new Swiper('.top-category-slider', {
        slidesPerView: 1,
        spaceBetween: 15,
        loop: true,
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
        },
        observer: true,
        observeParents: true,
        navigation: {
            nextEl: '#top-next',
            prevEl: '#top-prev'
        },
        breakpoints: {
            640: {
                slidesPerView: 2,
                spaceBetween: 15
            },
            768: {
                slidesPerView: 3,
                spaceBetween: 100
            },
            1024: {
                slidesPerView: 5,
                spaceBetween: 15
            }
        }
    });
}

function initializeSimilarItemsSlider() {
    if (document.querySelector(".js-similiar-items")) {
        let mySwiper = new Swiper(".js-similiar-items", {
            loop: false,
            preventClicks: true,
            grabCursor: true,
            simulateTouch: false,
            observer: true,
            observeParents: true,
            grabCursor: false,
            watchOverflow: true,
            pagination: {
                el: ".our-team-pagination",
                clickable: true,
            },
            navigation: {
                nextEl: ".similar-left-arrow",
                prevEl: ".similar-right-arrow",
            },
            // loop: true,
            spaceBetween: 15,
            slidesPerView: 1,
            // Responsive breakpoints
            breakpoints: {
                // when window width is >= 320px
                320: {
                    slidesPerView: 1.3,
                },
                // when window width is >= 480px
                480: {
                    slidesPerView: 1.3,
                },
                // when window width is >= 640px
                640: {
                    slidesPerView: 1.9,
                },
                // when window width is >= 992px
                992: {
                    slidesPerView: 2.7,
                },
                // when window width is >= 1200px
                1200: {
                    slidesPerView: 6.5,
                },
            },
        });
    }
}

async function loadSimilarRecommendations() {
    const productId = $(".hiddenProduct").val();
    const similarItemsListContainer = $("#similarItemsContainer");
    similarItemsListContainer.empty();
    if (window.innerWidth < 991) {
        $(".mobile-detail-section").append(similarItemsListContainer);
        stickyAddCartBtn();
    }
    
    const result = await getAsync(`/baseHandler.ashx?type=get-similar-recommendations&productId=${productId}`);
    if (!result || !result.length) {
        return;
    }

    let recommendedProductSlides = "";
    result.forEach((detail, index) => {
        let redirectUrl = `/shop/${detail.styleType}/${detail.name.replace(/ /g, "-")}-${detail.productId}?utm_source=pd-page&utm_medium=recommendations&utm_campaign=you-may-also-like-recommendation`;
        let linkTarget = isMobile() ? "" : `target="_blank"`;
        const originalPrice = detail.listPrice === detail.originalPrice ? "" : `<span class="product-strike">${detail.currencySymbol}${detail.originalPrice.toFixed(2)}</span>`;
        recommendedProductSlides += `
            <div class="swiper-slide">
                <div class="mask-slider-content">
                    <a href="${redirectUrl}" ${linkTarget}>
                        <img class="mask-slide-options-img" id="recommended-bottom-img-slide-${index}" src="https://img1.eshakti.com/clothimages/${detail.productId}MP.jpg" alt="" />
                        <label class="m-0 pl-0 label-container label-container--check d-flex flex-column">
                            <span style="line-height: 16px;" class="mt-2">${detail.name}</span>
                            <span class="product-cost d-flex">
                                <span style="color: #2c2a2a;" id="recommended-bottom-price-slide-${index}">${detail.currencySymbol}${detail.listPrice.toFixed(2)}</span>
                                ${originalPrice}
                            </span>
                        </label>
                    </a>
                </div>
            </div>`;
        });
        similarItemsListContainer.append(`
            <div class="select-Matching-Mask border-none pb-3 flex-column">
                <div class="free-mask-slider">
                    <p style="text-transform: uppercase;" class="fnt-700 text-center mb-2">You may also like</p>
                    <div class="swiper-arrow-container px-0">
                        <div class="swiper-container recommended-products-listswiper recommended-similar-swiper">
                            <div class="swiper-wrapper recommended-pd-wrapper" id="recommended-similar-swiper">
                                ${recommendedProductSlides}
                            </div>
                        </div>
                        <div class="swiper-arrow">
                            <div style="top: 38%;left: 0;" class="arrow right-arrow swiper-button-disabled" tabindex="0" role="button" aria-label="Previous slide" aria-disabled="true"><span></span></div>
                            <div style="top: 38%;left: 100%;" class="arrow left-arrow" tabindex="0" role="button" aria-label="Next slide" aria-disabled="false"><span></span></div>
                        </div>
                    </div>
                </div>
            </div>`);
            similarItemsListContainer.show();

            const recommendedSwiper = new Swiper('.recommended-similar-swiper', {
                slidesPerView: 2,
                spaceBetween: 10,
                loop: false,
                observer: true,
                observerParent: true,
                keyboard: {
                    enabled: true,
                },
                navigation: {
                    nextEl: '#similarItemsContainer .left-arrow',
                    prevEl: '#similarItemsContainer .right-arrow',
                },
                breakpoints: {
                    768: {
                      slidesPerView: 4,
                   
                    },
                  }
            });
            
            // unifyHeights();
}

async function fetchPidBasedProducts() {
        const recommendedPIdBasedContainer = $("#recommendedPIdBasedContainer");
        recommendedPIdBasedContainer.empty();
        if (window.innerWidth < 991) {
            $(".mobile-detail-section").append(recommendedPIdBasedContainer);
            stickyAddCartBtn();
        }
        if (!(rawProductDetail.categories.includes("tops") || rawProductDetail.categories.includes("bottoms"))) {
            const result = await getAsync(`/baseHandler.ashx?type=get-pidbased-recommendations&productId=${productId}`);
            if (!result || !result.length) {
                return;
            }

            let recommendedBottomSlides = "";
            result.forEach((detail, index) => {
                let redirectUrl = `/shop/${detail.styleType}/${detail.name.replace(/ /g, "-")}-${detail.productId}?utm_source=pd-page&utm_medium=recommendations&utm_campaign=customers-bought-this-also-bought`;
                let linkTarget = isMobile() ? "" : `target="_blank"`;
                const originalPrice = detail.listPrice === detail.originalPrice ? "" : `<span class="product-strike">${detail.currencySymbol}${detail.originalPrice.toFixed(2)}</span>`;
                recommendedBottomSlides += `
                    <div class="swiper-slide">
                        <div class="mask-slider-content">
                            <a href="${redirectUrl}" ${linkTarget}>
                                <img class="mask-slide-options-img" id="recommended-bottom-img-slide-${index}" src="https://img1.eshakti.com/clothimages/${detail.productId}MP.jpg" alt="" />
                                <label class="m-0 pl-0 label-container label-container--check d-flex flex-column">
                                    <span style="line-height: 16px;" class="mt-2">${detail.name}</span>
                                    <span class="product-cost d-flex">
                                        <span style="color: #2c2a2a;" id="recommended-bottom-price-slide-${index}">${detail.currencySymbol}${detail.listPrice.toFixed(2)}</span>
                                        ${originalPrice}
                                    </span>
                                </label>
                            </a>
                        </div>
                    </div>`;
            });
            recommendedPIdBasedContainer.append(`
                <div class="select-Matching-Mask border-none pb-3 flex-column">
                    <div class="free-mask-slider">
                        <p style="text-transform: uppercase;" class="fnt-700 text-center mb-2">Customers who bought this also bought</p>
                        <div class="swiper-arrow-container px-0">
                            <div class="swiper-container recommended-products-listswiper recommended-pidbased-swiper">
                                <div class="swiper-wrapper recommended-pd-wrapper" id="recommended-pidbased-swiper">
                                    ${recommendedBottomSlides}
                                </div>
                            </div>
                            <div class="swiper-arrow">
                                <div style="top: 38%;left: 0;" class="arrow right-arrow swiper-button-disabled" tabindex="0" role="button" aria-label="Previous slide" aria-disabled="true"><span></span></div>
                                <div style="top: 38%;left: 100%;" class="arrow left-arrow" tabindex="0" role="button" aria-label="Next slide" aria-disabled="false"><span></span></div>
                            </div>
                        </div>
                    </div>
                </div>`);
                recommendedPIdBasedContainer.show();

                const recommendedSwiperTwo = new Swiper('.recommended-pidbased-swiper', {
                    slidesPerView: 2,
                    spaceBetween: 10,
                    loop: false,
                    observer: true,
                    observerParent: true,
                    keyboard: {
                        enabled: true,
                    },
                    navigation: {
                        nextEl: '#recommendedPIdBasedContainer .left-arrow',
                        prevEl: '#recommendedPIdBasedContainer .right-arrow',
                    },
                    breakpoints: {
                        768: {
                          slidesPerView: 4,
                       
                        },
                      }
                });
                
                // unifyHeights();
        }
}

async function fetchRecommendedProducts() {
        const recommendedProductsContainer = $("#recommendedProductsContainer");
        const userDetails = getUserDetails();
        recommendedProductsContainer.empty();
        if (window.innerWidth < 991) {
            $(".mobile-detail-section").append(recommendedProductsContainer);
            stickyAddCartBtn();
        }

    if (rawProductDetail.categories.includes("tops") || rawProductDetail.categories.includes("bottoms") || (rawProductDetail.categories.includes("dresses") && userDetails.isIndianUser)) {
            const result = await getAsync(`/baseHandler.ashx?type=get-bottoms-recommendations&productId=${productId}`);
            if (!result || !result.length) {
                return;
            }

            let recommendedBottomSlides = "";
            result.forEach((detail, index) => {
                let redirectUrl = `/shop/${detail.styleType}/${detail.name.replace(/ /g, "-")}-${detail.productId}?utm_source=pd-page&utm_medium=recommendations&utm_campaign=top-bottom-recommendations`;
                let linkTarget = isMobile() ? "" : `target="_blank"`;
                const originalPrice = detail.listPrice === detail.originalPrice ? "" : `<span class="product-strike">${detail.currencySymbol}${detail.originalPrice.toFixed(2)}</span>`;
                recommendedBottomSlides += `
                    <div class="swiper-slide">
                        <div class="mask-slider-content">
                            <a href="${redirectUrl}" ${linkTarget}>
                                <img class="mask-slide-options-img" id="recommended-bottom-img-slide-${index}" src="https://img1.eshakti.com/clothimages/${detail.productId}MP.jpg" alt="" />
                                <label class="m-0 pl-0 label-container label-container--check d-flex flex-column">
                                    <span style="line-height: 16px;" class="mt-2">${detail.name}</span>
                                    <span class="product-cost d-flex">
                                        <span style="color: #2c2a2a;" id="recommended-bottom-price-slide-${index}">${detail.currencySymbol}${detail.listPrice.toFixed(2)}</span>
                                        ${originalPrice}
                                    </span>
                                </label>
                            </a>
                        </div>
                    </div>`;
            });
            recommendedProductsContainer.append(`
                <div class="select-Matching-Mask border-none pb-3 flex-column">
                    <div class="free-mask-slider">
                        <p style="text-transform: uppercase;" class="fnt-700 text-center mb-2">Complete this look</p>
                        <div class="swiper-arrow-container px-0">
                            <div class="swiper-container recommended-products-listswiper recommended-bottom-swiper">
                                <div class="swiper-wrapper recommended-pd-wrapper" id="recommended-bottom-swiper">
                                    ${recommendedBottomSlides}
                                </div>
                            </div>
                            <div class="swiper-arrow">
                                <div style="top: 38%;left: 0;" class="arrow right-arrow swiper-button-disabled" tabindex="0" role="button" aria-label="Previous slide" aria-disabled="true"><span></span></div>
                                <div style="top: 38%;left: 100%;" class="arrow left-arrow" tabindex="0" role="button" aria-label="Next slide" aria-disabled="false"><span></span></div>
                            </div>
                        </div>
                    </div>
                </div>`);
                recommendedProductsContainer.show();

                const recommendedSwiperOne = new Swiper('.recommended-bottom-swiper', {
                    slidesPerView: 2,
                    spaceBetween: 10,
                    loop: false,
                    observer: true,
                    observerParent: true,
                    keyboard: {
                        enabled: true,
                    },
                    navigation: {
                        nextEl: '#recommendedProductsContainer .left-arrow',
                        prevEl: '#recommendedProductsContainer .right-arrow',
                    },
                    breakpoints: {
                        768: {
                          slidesPerView: 4,
                       
                        },
                      }
                });
                
                // unifyHeights();
        }    
}

function unifyHeights() {
    setTimeout(() => {
        if($('#recommended-bottom-swiper')) {
            var maxHeight = 0;
            $('#recommended-bottom-swiper').children().each(function() {
                var height = $(this).height();
                // alert(height);
                if ( height > maxHeight ) {
                    maxHeight = height;
                }
            });
            maxHeight = maxHeight + 0;
            $('#recommended-bottom-swiper').children().each(function() {
                $(this).css('height', maxHeight);
            });
        }
         
        if($('#recommended-similar-swiper')) {
            var maxHeight = 0;
            $('#recommended-similar-swiper').children().each(function() {
                var height = $(this).height();
                // alert(height);
                if ( height > maxHeight ) {
                    maxHeight = height;
                }
            });
            maxHeight = maxHeight + 0;
            $('#recommended-similar-swiper').children().each(function() {
                $(this).css('height', maxHeight);
            }); 
        }
        if($('#recommended-pidbased-swiper')) {
            var maxHeight = 0;
            $('#recommended-pidbased-swiper').children().each(function() {
                var height = $(this).height();
                // alert(height);
                if ( height > maxHeight ) {
                    maxHeight = height;
                }
            });
            maxHeight = maxHeight + 0;
            $('#recommended-pidbased-swiper').children().each(function() {
                $(this).css('height', maxHeight);
            }); 
        }     
    }, 300);
}

   

$(document).ready(function () {
    productDetailsPageRecommendations();
    fetchRecommendedProducts();
    fetchPidBasedProducts();
    loadSimilarRecommendations();
});;
