/* Minification failed. Returning unminified contents.
(190,36-37): run-time error JS1195: Expected expression: )
(190,39-40): run-time error JS1195: Expected expression: >
(206,31-32): run-time error JS1195: Expected expression: )
(206,34-35): run-time error JS1195: Expected expression: >
(240,7-15): run-time error JS1004: Expected ';': function
(241,26-34): run-time error JS1004: Expected ';': getAsync
(246,38-39): run-time error JS1195: Expected expression: >
(251,13-14): run-time error JS1014: Invalid character: `
(251,14-15): run-time error JS1195: Expected expression: <
(251,14-15): run-time error JS1195: Expected expression: <
(251,84-85): run-time error JS1004: Expected ';': {
(251,118-119): run-time error JS1195: Expected expression: <
(251,122-123): run-time error JS1014: Invalid character: `
(253,33-34): run-time error JS1014: Invalid character: `
(258,15-20): run-time error JS1197: Too many errors. The file might not be a JavaScript file: class
(240,7-41): run-time error JS1301: End of file encountered before function is properly closed: function homePageRecommendations()
(258,20-21): run-time error JS1195: Expected expression: =
(258,21-68): run-time error JS1197: Too many errors. The file might not be a JavaScript file: "top-product-title mt-2 fnt-xs text-capitalize"
 */
// Home page - Default.aspx


$(document).ready(function () {
    const bannerSwiper1 = new Swiper(".js-homebnr-slider1", {
        slidesPerView: 1,
        spaceBetween: 0,
        loop: true,
        effect: "fade",
        fadeEffect: {
            crossFade: true,
        },
        observer: true,
        observeParents: true,
        autoplay: {
            disableOnInteraction: false,
            delay: 12000
        }
    });

    const bannerSwiper2 = new Swiper(".js-homebnr-slider2", {
        slidesPerView: 1,
        spaceBetween: 0,
        loop: true,
        effect: "fade",
        fadeEffect: {
            crossFade: true,
        },
        observer: true,
        observeParents: true,
        autoplay: {
            disableOnInteraction: false,
            delay: 12000
        }
    });

    if (document.querySelector(".js-homebnr-arrow-slider")) {
        const bannerSwiper = new Swiper(".js-homebnr-arrow-slider", {
            slidesPerView: 1,
            spaceBetween: 0,
            loop: true,
            effect: "fade",
            fadeEffect: {
                crossFade: true,
            },
            autoplay: {
                disableOnInteraction: false,
                delay: 10000,
            },
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
                clickable: true,
            },
            observer: true,
            observeParents: true,
        });
    }

    if (document.querySelector(".js-homecard-slider")) {
        const cardSwiper = new Swiper(".js-homecard-slider", {
            slidesPerView: 1,
            spaceBetween: 0,
            speed: 500,
            touch: true,
            loop: true,
            effect: "fade",
            fadeEffect: {
                crossFade: true,
            },
            autoplay: {
                delay: 12000,
            },
            pagination: {
                el: ".swiper-pagination",
                clickable: true,
            },
            navigation: {
                nextEl: ".swiper-button-next",
                prevEl: ".swiper-button-prev",
            },
            observer: true,
            observeParents: true,
        });
    }

    if (document.querySelector(".js-homecard-slider-20sec")) {
        const cardSwiper2 = new Swiper(".js-homecard-slider-20sec", {
            slidesPerView: 1,
            spaceBetween: 0,
            speed: 500,
            touch: true,
            loop: true,
            effect: "fade",
            autoHeight: false,
            height:573,
            fadeEffect: {
                crossFade: true,
            },
            autoplay: {
                delay: 20000,
            },
            pagination: {
                el: ".swiper-pagination",
                clickable: true,
            },
            navigation: {
                nextEl: ".swiper-button-next",
                prevEl: ".swiper-button-prev",
            },
            observer: true,
            observeParents: true,
        });
    }

    if (document.querySelector(".js-homecontest-slider")) {
        const homecontestSwiper = new Swiper(".js-homecontest-slider", {
            slidesPerView: 1,
            spaceBetween: 0,
            speed: 500,
            watchOverflow: true,
            touch: true,
            loop: true,
            effect: "fade",
            fadeEffect: {
                crossFade: true,
            },
            autoplay: {
                delay: 5000,
            },
            pagination: {
                el: ".swiper-pagination",
                clickable: true,
            },
            observer: true,
            observeParents: true,
        });
    }

    if (document.querySelector(".js-homefeed-slider")) {
        const feedbackSwiper = new Swiper(".js-homefeed-slider", {
            slidesPerView: 1,
            spaceBetween: 0,
            loop: true,
            effect: "fade",
            autoplay: {
                delay: 5000,
            },
            fadeEffect: {
                crossFade: true,
            },
        });
    }

    if (document.querySelector(".brand-slider")) {
        const feedbackSwiper = new Swiper(".brand-slider", {
            slidesPerView: 1,
            spaceBetween: 0,
            speed: 500,
            touch: true,
            loop: true,
            effect: "fade",
            fadeEffect: {
                crossFade: true,
            },
            autoplay: {
                delay: 3000,
            },
            pagination: {
                el: ".swiper-pagination",
                clickable: true,
            },
            navigation: {
                nextEl: ".swiper-button-next",
                prevEl: ".swiper-button-prev",
            }
        });
    }

    if (document.querySelector(".js-fashion-slider")) {
        // breakpoint where swiper will be destroyed
        // and switches to a dual-column layout
        const breakpoint = window.matchMedia("(min-width:31.25em)");

        // keep track of swiper instances to destroy later
        let mySwiper;

        //////////////////////////////////////////////////////////////////

        const breakpointChecker = () => {
            // if larger viewport and multi-row layout needed
            if (breakpoint.matches === true) {
                // clean up old instances and inline styles when available
                if (mySwiper !== undefined) mySwiper.destroy(true, true);

                // or/and do nothing
                return;

                // else if a small viewport and single column layout needed
            } else if (breakpoint.matches === false) {
                // fire small viewport version of swiper
                return enableSwiper();
            }
        };

        const enableSwiper = () => {
            mySwiper = new Swiper(".js-fashion-slider", {
                pagination: {
                    el: ".our-team-pagination",
                    clickable: true,
                },
                // loop: true,
                spaceBetween: 15,

                slidesPerView: "1.2",
                breakpoints: {
                    320: {
                        slidesPerView: 1.2,
                        spaceBetween: 10,
                    },
                    410: {
                        slidesPerView: 1.4,
                        spaceBetween: 0,
                    },
                    // when window width is >= 640px
                },
            });
        };

        //////////////////////////////////////////////////////////////////

        // keep an eye on viewport size changes
        breakpoint.addListener(breakpointChecker);

        // kickstart
        breakpointChecker();
    }
});

async function homePageRecommendations() {
    const result = await getAsync("/baseHandler.ashx?type=gethomepagerecommendations");
    if (!result || !result.products || result.products.length < 5)
        return;

    let recommendationSlides = "";
    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>`;

        recommendationSlides += `
                <div class="swiper-slide">
                    <a href="/product/${product.productId}?source=solus_web&medium=homebanner&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>`;
    });

    const recommendationsSectionHtml = `
            <div class="container-fluid mb-5 hght100">
                <div class="row">
                    <div class="col-lg-12 card-height col-sm-6 col-sm-12">
                        <div class="customer-details p-4 mb-2 r-cards hght100">
                            <h3 class="home-cards__title px-4 mb-0">Recommended for you</h3>
                            <p class="fnt-xs px-4 mb-3">Basis your previous purchases</p>
                            <div class="swiper-container pb-2 mx-4 top-category-slider">
	                            <div class="swiper-wrapper" id="recommendationsContainer">
		                            ${recommendationSlides}
	                            </div>
                            </div>
                            <div id="top-next" class="swiper-button-next"></div>
                            <div id="top-prev" class="swiper-button-prev"></div>
                            <p class="text-right pt-1 fnt-xxs" id="recommendationFeedback">
                                <a href="javascript:void(0)" data-toggle="modal" data-target="#recommendationFeedBack" style="text-decoration: none;color: #2e333d; line-height: 1; border-bottom:1px solid #a4a4a4;">Feedback</a>
                            </p>
                        </div>
                    </div
                </div>
            </div>`;

    $(document).ready(function () {
        $("#recommendationsSection").append(recommendationsSectionHtml);
        $("#recommendationsSection").show();

        const topCategorySwiper = new Swiper('.top-category-slider', {
            slidesPerView: 1,
            spaceBetween: 15,
            loop: 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 enableFgBannerForLoggedInCustomers() {
    const userDetails = getUserDetails();

    if (
        !userDetails ||
        userDetails.isGuestUser ||
        !userDetails.fgData ||
        !userDetails.fgData.isFgSelectedCustomer ||
        !userDetails.fgData.fgOrders ||
        userDetails.fgData.fgOrders.length >= 3
    )
        return;

    $("#logged-in-fgp-banner").show();
}

function toggleSubmitButton(feedbackSubmitButton, toggle) {
    if (toggle) {
        feedbackSubmitButton.text("Submit");
        feedbackSubmitButton.fadeTo(100, 1);
    } else {
        feedbackSubmitButton.text("Submitting Feedback...");
        feedbackSubmitButton.fadeTo(100, 0.2);
    }
}

function initializeAllFeedbackPopup() {
    const feedbackQuestionMapping = {
        holidayPajamas: 31,
        vblock: 32,
        earthRiseBanner: 35
    };

    Object.keys(feedbackQuestionMapping).forEach(key => {

        $(`#${key}FeedbackForm`).submit(async function (e) {
            e.preventDefault();
            const feedbackSubmitButton = $(`#${key}FeedbackSubmitButton`);
            const txtComments = $(`#${key}txtComments`).val();
            const answer = $(`#publicPermit`).is(":checked");

            const feedbackData = {
                questionId: feedbackQuestionMapping[key],
                comments: txtComments,
                yesOrNo: answer ? "yes" : "no"
            };

            toggleSubmitButton(feedbackSubmitButton, false);

            const result = await postAsync("/handler/PageFeedback.ashx?action=savefeedback", feedbackData);

            toggleSubmitButton(feedbackSubmitButton, true);
            $(`#${key}FeedBackModal`).modal("hide");

            if (!result) {
                showDefaultErrorPopup("Error", "Unexpected error while submitting the feedback");
            }
        });
    });
}

function homeBannerFeedbackHandle() {
    $("#bannerFeedback").show();

    const hpFeedbackSubmitButton = $("#hpFeedbackSubmitButton");

    $("#hpFeedbackForm").submit(async function (e) {
        e.preventDefault();
        const txtComments = $("#hpFeedbackTxtComments").val();
        const feedbackData = {
            questionId: 27,
            comments: txtComments,
            yesOrNo: "yes"
        };

        toggleSubmitButton(hpFeedbackSubmitButton, false);

        const result = await postAsync("/handler/PageFeedback.ashx?action=savefeedback", feedbackData);

        toggleSubmitButton(hpFeedbackSubmitButton, true);
        $("#homePageBannerFeedBack").modal("hide");

        if (!result) {
            showDefaultErrorPopup("Error", "Unexpected error while submitting the feedback");
        }
    });
}

function recommendationFeedbackHandle() {
    const recommendationFeedbackSubmitButton = $("#recommendationFeedbackSubmitButton");

    $("#recommendationFeedbackForm").submit(async function (e) {
        e.preventDefault();
        const currentForm = $(this);
        currentForm.parsley().validate();
        if (!currentForm.parsley().isValid()) {
            return;
        }

        const txtComments = $("#recommendationTxtComments").val();
        const feedbackData = {
            questionId: 28,
            comments: `homeBanenr-${txtComments}`,
            yesOrNo: $("#recommendationFeedbackUsefulYes").is(":checked") ? "yes" : "no"
        };

        toggleSubmitButton(recommendationFeedbackSubmitButton, false);
        const result = await postAsync("/handler/PageFeedback.ashx?action=savefeedback", feedbackData);

        toggleSubmitButton(recommendationFeedbackSubmitButton, true);
        $("#recommendationFeedBack").modal("hide");

        if (!result) {
            showDefaultErrorPopup("Error", "Unexpected error while submitting the feedback");
        }
    });
}

function enableUsMaskPackBanner() {
    const country = $.cookie("Country").toLowerCase();
    if (country === "us" || country === "usa" || country === "united states") {
        //$("#usmask-banner").show();
        $(".banner-us-show").show();
        $(".banner-us-hide").hide();
    }
    else {
        //$("#usmask-banner").hide();
        $(".banner-us-show").hide();
        $(".banner-us-hide").show();
    }

    if (country === "canada" || country === "india") {
        $(".ViroMasks").hide();
    } else {
        $(".ViroMasks").show();
    }
}

function enableVideoBanner() {
    const usertype = $.cookie("UType").toLowerCase();

    if (usertype == "register" || usertype == "guest") {
        $("#experienceVideo").show(200);
    }

    if (usertype == "customer") {
        $("#experienceVideo").hide(200);
    }
}

function emersonVideo() {
    if (videoEventHandled) return;
    const scrollvertical = window.scrollY;
    if (scrollvertical >= 1000 && !experienceVideoClosed) {
        //enableVideoBanner();
        videoEventHandled = true;
    }
}

function handleEmersionVideo() {
    window.addEventListener("scroll", emersonVideo);

    $(".close-video").on('click', function (e) {
        $("#experienceVideo iframe").attr("src", $("#experienceVideo iframe").attr("src"));
        $("#experienceVideo").hide();
        experienceVideoClosed = true;
    });
}

function initializeFeedbackPopup() {
    const websiteFeedbackSubmitButton = $("#websiteFeedbackSubmitButton");

    $("#websiteFeedbackForm").submit(async function (e) {
        e.preventDefault();
        const txtComments = $("#txtComments").val();
        const answer = $(`input[name="public-permit"]`).is(":checked");

        const feedbackData = {
            questionId: 30,
            comments: txtComments,
            yesOrNo: answer ? "yes" : "no"
        };

        toggleSubmitButton(websiteFeedbackSubmitButton, false);

        const result = await postAsync("/handler/PageFeedback.ashx?action=savefeedback", feedbackData);

        toggleSubmitButton(websiteFeedbackSubmitButton, true);
        $("#homePageBannerFeedBack").modal("hide");

        if (!result) {
            showDefaultErrorPopup("Error", "Unexpected error while submitting the feedback");
        }
    });
}

//function moengageHome() {
//    const queryString = {};
//    const utmRequest = {
//        refUrl: document.referrer
//    };
//    const friendlyUrl = decodeURI(window.location.href.split("+").join("%20"));
//    const pairs = friendlyUrl.slice(friendlyUrl.indexOf("?") + 1).split("&");
//    pairs.forEach((pair) => {
//        const splits = pair.split("=");
//        queryString[splits[0]] = splits[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;
//        }
//    });

//    let moengageHomeSource = utmRequest.utmCamp != undefined ? utmRequest.utmCamp : 'Website';

//    moengageHomeloading(moengageHomeSource);
//}

function preLoadBannerUrls() {
    setTimeout(function () {
        let bannerUrls = Array.from($(".Homepage main .fluid-carousal a.full-link:lt(3)"))

        if (!bannerUrls)
            return;

        bannerUrls.forEach(banner => {
            let url = banner.getAttribute('href');
            fetch(url);
        });

    }, 1000);
}

function handleFacebookShare() {
    $('.facebook-share').click(function () {
        var element = $(this)
        const userDetails = getUserDetails();
        window.insertGenericTrackerData({
            trackerId: 15,
            answer: true,
            allowDuplicates: true,
            customData: userDetails.userId
        })
        let url = encodeURIComponent(element.attr('data-url'));
        let dataHashtag = encodeURIComponent(element.attr('data-hashtag'));
        window.open(`https://www.facebook.com/sharer/sharer.php?u=${url}&hashtag=${dataHashtag}&`, '_blank','width=600,height=400,resizable,scrollbars')
    });
}

$(document).ready(function () {
    enableUsMaskPackBanner();
    enableFgBannerForLoggedInCustomers();
    recommendationFeedbackHandle();
    //homeBannerFeedbackHandle();
    //initializeFeedbackPopup();
    initializeAllFeedbackPopup();
    progressiveImageLoading();
    //moengageHome();
    handleFacebookShare();
});

logSiteType();
homePageRecommendations();
;
(function () {
    $(document).ready(function () {
        if (!document.querySelector(".masonry-fashion"))
            return;

        var macyInstance1 = Macy({
            container: ".masonry-fashion",
            trueOrder: false,
            margin: 30,
            columns: 3,
            breakAt: {
                1199: {
                    margin: 30,
                },
                991: {
                    margin: 25,
                    columns: 2,
                },
                767: {
                    margin: 20,
                },
                575: {
                    margin: 15,
                },
                479: {
                    columns: 1,
                },
                399: {
                    margin: 15,
                },
            },
        });

        $(window).on("load", function () {
            macyInstance1.reInit();
        });
    });
})();;
async function initializeNewTrending() {
    if(userDetails.isRepeatCustomer)
        return;

    $("#newTrending").append(`<section class="mb-5">
    <div class="pt-0 px-0 container-fluid" id="newTrendingSection">
        <div class="container-fluid hght100">
            <div class="row">
                <div class="col-lg-12 card-height col-sm-6 col-sm-12">
                    <div class="customer-details p-4 mb-2 r-cards hght100">
                        <h3 class="home-cards__title px-4 mb-3">Trending</h3>
                        <div class="swiper-container pb-2 mx-4 trending-swiper-new">
                            <div class="swiper-wrapper" id="newTrendingSwiper">
                            </div>
                        </div>
                        <div id="trending-new-next" class="swiper-button-next home-top-next"></div>
                        <div id="trending-new-prev" class="swiper-button-prev home-top-prev"></div>
                        <p class="text-right pt-1 fnt-xxs" id="recommendationFeedbackText">
                                <a href="javascript:void(0)" data-toggle="modal"
                                    data-target="#recommendationFeedBack"
                                    style="text-decoration: none; color: #2e333d; line-height: 1; border-bottom: 1px solid #a4a4a4;">Feedback</a>
                            </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </section>`);
    
    const result = await getAsync(`/ProductListHandler.ashx?category=Bestsellers&page=1&rows=15&color=&fabric=&usage=&price=&size=&sorting=Topsellers`);

    if (!result || !result.productsJson.products || result.productsJson.products.length < 5) {
        return;
    }

    const newTrendingSwiper = $("#newTrendingSwiper");
    newTrendingSwiper.empty();

    result.productsJson.products.forEach((product, i) => {
        if(i > 15)
            return;
            
        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>`;

            newTrendingSwiper.append(`<div class="swiper-slide">
                    <a class="cursor-pointer new-trending-recommendations" x-data-productid=${product.productId}>
	    		        <img class="top-category-img" src="${product.highResImageUrls[0]}" alt="" />
			        <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>
                    </a>
		        </div>`);
    });

    $("#newTrending").show();

    const topCategorySwiper = new Swiper('.trending-swiper-new', {
        slidesPerView: 1,
        spaceBetween: 15,
        loop: true,
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
        },
        observer: true,
        observeParents: true,
        navigation: {
            nextEl: '#trending-new-next',
            prevEl: '#trending-new-prev'
        },
        breakpoints: {
            640: {
                slidesPerView: 2,
                spaceBetween: 15
            },
            768: {
                slidesPerView: 3,
                spaceBetween: 100
            },
            1024: {
                slidesPerView: 5,
                spaceBetween: 15
            }
        }
    });

    $(".new-trending-recommendations").click(function (e) {
        const productDiv = $(this);
        const productId = productDiv.attr("x-data-productid");
        const userDetails = getUserDetails();
        const recommendationId = Math.floor(Date.now() + userDetails.userId + Math.random()).toString()
        result.productsJson.products.forEach(productDetail => {
            SendEventDataToRudderstack('recommendation_product_loaded', {
                productId: productDetail.productId,
                recommendationId: recommendationId,
                pageType: "home-page",
                recommendationType: "New Trending"
            });
        });

        SendEventDataToRudderstack('recommendation_product_clicked', {
            productId: productId,
            recommendationId: recommendationId,
            pageType: "home-page",
            recommendationType: "New Trending"
        });

        const productDetail = result.productsJson.products.find(p => p.productId === productId);
        let redirectUrl = `/shop/${productDetail.styleType}/${productDetail.name.replace(/ /g, "-")}-${productDetail.productId}?utm_source=home-page&utm_medium=recommendations&view_source=recommendation&utm_campaign=new-trending`;
        let linkTarget = isMobile() ? "" : "_blank";
        window.open(redirectUrl, linkTarget);
    });
}

async function initializeNewPopular() {
    if(userDetails.isRepeatCustomer)
        return;

    $("#newPopular").append(`<section class="mb-5">
    <div class="pt-0 px-0 container-fluid" id="newPopularSection">
        <div class="container-fluid hght100">
            <div class="row">
                <div class="col-lg-12 card-height col-sm-6 col-sm-12">
                    <div class="customer-details p-4 mb-2 r-cards hght100">
                        <h3 class="home-cards__title px-4 mb-3">Most Popular</h3>
                        <div class="swiper-container pb-2 mx-4 popular-swiper-new">
                            <div class="swiper-wrapper" id="newPopularSwiper">
                            </div>
                        </div>
                        <div id="popular-new-next" class="swiper-button-next home-top-next"></div>
                        <div id="popular-new-prev" class="swiper-button-prev home-top-prev"></div>
                        <p class="text-right pt-1 fnt-xxs" id="recommendationFeedbackText">
                                <a href="javascript:void(0)" data-toggle="modal"
                                    data-target="#recommendationFeedBack"
                                    style="text-decoration: none; color: #2e333d; line-height: 1; border-bottom: 1px solid #a4a4a4;">Feedback</a>
                            </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </section>`);
    
    const result = await getAsync(`/ProductListHandler.ashx?category=Bestsellers New&page=1&rows=15&color=&fabric=&usage=&price=&size=&sorting=Topsellers`);

    if (!result || !result.productsJson.products || result.productsJson.products.length < 5) {
        return;
    }

    const newPopularSwiper = $("#newPopularSwiper");
    newPopularSwiper.empty();

    result.productsJson.products.forEach((product, i) => {
        if(i > 15)
            return;
            
        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>`;

            newPopularSwiper.append(`<div class="swiper-slide">
                    <a class="cursor-pointer new-popular-recommendations" x-data-productid=${product.productId}>
	    		        <img class="top-category-img" src="${product.highResImageUrls[0]}" alt="" />
			        <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>
                    </a>
		        </div>`);
    });

    $("#newPopular").show();

    const topCategorySwiper = new Swiper('.popular-swiper-new', {
        slidesPerView: 1,
        spaceBetween: 15,
        loop: true,
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
        },
        observer: true,
        observeParents: true,
        navigation: {
            nextEl: '#popular-new-next',
            prevEl: '#popular-new-prev'
        },
        breakpoints: {
            640: {
                slidesPerView: 2,
                spaceBetween: 15
            },
            768: {
                slidesPerView: 3,
                spaceBetween: 100
            },
            1024: {
                slidesPerView: 5,
                spaceBetween: 15
            }
        }
    });

    $(".new-popular-recommendations").click(function (e) {
        const productDiv = $(this);
        const productId = productDiv.attr("x-data-productid");
        const userDetails = getUserDetails();
        const recommendationId = Math.floor(Date.now() + userDetails.userId + Math.random()).toString()
        result.productsJson.products.forEach(productDetail => {
            SendEventDataToRudderstack('recommendation_product_loaded', {
                productId: productDetail.productId,
                recommendationId: recommendationId,
                pageType: "home-page",
                recommendationType: "New Popular"
            });
        });

        SendEventDataToRudderstack('recommendation_product_clicked', {
            productId: productId,
            recommendationId: recommendationId,
            pageType: "home-page",
            recommendationType: "New Popular"
        });

        const productDetail = result.productsJson.products.find(p => p.productId === productId);
        let redirectUrl = `/shop/${productDetail.styleType}/${productDetail.name.replace(/ /g, "-")}-${productDetail.productId}?utm_source=home-page&utm_medium=recommendations&view_source=recommendation&utm_campaign=new-Popular`;
        let linkTarget = isMobile() ? "" : "_blank";
        window.open(redirectUrl, linkTarget);
    });
}

async function initializeOldTrending() {    
    if(!userDetails.isRepeatCustomer)
        return;

    $("#oldTrending").append(`<section class="mb-5">
    <div class="pt-0 px-0 container-fluid" id="oldTrendingSection">
        <div class="container-fluid hght100">
            <div class="row">
                <div class="col-lg-12 card-height col-sm-6 col-sm-12">
                    <div class="customer-details p-4 mb-2 r-cards hght100">
                        <h3 class="home-cards__title px-4 mb-3">Trending</h3>
                        <div class="swiper-container pb-2 mx-4 trending-swiper-old">
                            <div class="swiper-wrapper" id="oldTrendingSwiper">
                            </div>
                        </div>
                        <div id="trending-old-next" class="swiper-button-next home-top-next"></div>
                        <div id="trending-old-prev" class="swiper-button-prev home-top-prev"></div>
                        <p class="text-right pt-1 fnt-xxs" id="recommendationFeedbackText">
                                <a href="javascript:void(0)" data-toggle="modal"
                                    data-target="#recommendationFeedBack"
                                    style="text-decoration: none; color: #2e333d; line-height: 1; border-bottom: 1px solid #a4a4a4;">Feedback</a>
                            </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </section>`);
    
    const result = await getAsync(`/ProductListHandler.ashx?category=Bestselling NewArrivals&page=1&rows=15&color=&fabric=&usage=&price=&size=&sorting=Topsellers`);

    if (!result || !result.productsJson.products || result.productsJson.products.length < 5) {
        return;
    }

    const oldTrendingSwiper = $("#oldTrendingSwiper");
    oldTrendingSwiper.empty();

    result.productsJson.products.forEach((product, i) => {
        if(i > 15)
            return;
            
        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>`;

            oldTrendingSwiper.append(`<div class="swiper-slide">
                    <a class="cursor-pointer old-trending-recommendations" x-data-productid=${product.productId}>
	    		        <img class="top-category-img" src="${product.highResImageUrls[0]}" alt="" />
			        <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>
                    </a>
		        </div>`);
    });

    $("#oldTrending").show();

    const topCategorySwiper = new Swiper('.trending-swiper-old', {
        slidesPerView: 1,
        spaceBetween: 15,
        loop: true,
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
        },
        observer: true,
        observeParents: true,
        navigation: {
            nextEl: '#trending-old-next',
            prevEl: '#trending-old-prev'
        },
        breakpoints: {
            640: {
                slidesPerView: 2,
                spaceBetween: 15
            },
            768: {
                slidesPerView: 3,
                spaceBetween: 100
            },
            1024: {
                slidesPerView: 5,
                spaceBetween: 15
            }
        }
    });

    $(".old-trending-recommendations").click(function (e) {
        const productDiv = $(this);
        const productId = productDiv.attr("x-data-productid");
        const userDetails = getUserDetails();
        const recommendationId = Math.floor(Date.now() + userDetails.userId + Math.random()).toString()
        result.productsJson.products.forEach(productDetail => {
            SendEventDataToRudderstack('recommendation_product_loaded', {
                productId: productDetail.productId,
                recommendationId: recommendationId,
                pageType: "home-page",
                recommendationType: "Repeat Trending"
            });
        });

        SendEventDataToRudderstack('recommendation_product_clicked', {
            productId: productId,
            recommendationId: recommendationId,
            pageType: "home-page",
            recommendationType: "Repeat Trending"
        });

        const productDetail = result.productsJson.products.find(p => p.productId === productId);
        let redirectUrl = `/shop/${productDetail.styleType}/${productDetail.name.replace(/ /g, "-")}-${productDetail.productId}?utm_source=home-page&utm_medium=recommendations&view_source=recommendation&utm_campaign=Repeat-Trending`;
        let linkTarget = isMobile() ? "" : "_blank";
        window.open(redirectUrl, linkTarget);
    });
}

async function initializeWishlistRecommendations() {
    if(!userDetails.isRepeatCustomer)
        return;

    $("#wishlistRecommendations").append(`<section class="mb-5">
    <div class="pt-0 px-0 container-fluid" id="wishlistSection" style="display: none">
        <div class="container-fluid hght100">
            <div class="row">
                <div class="col-lg-12 card-height col-sm-6 col-sm-12">
                    <div class="customer-details p-4 mb-2 r-cards hght100">
                        <h3 class="home-cards__title px-4 mb-0">Recommended for you</h3>
                        <p class="fnt-xs px-4 mb-3">Basis items in your Wishlist</p>
                        <div class="swiper-container pb-2 mx-4 top-category-slider-wishlist">
                            <div class="swiper-wrapper" id="WishlistSwiper">
                            </div>
                        </div>
                        <div id="top-next-four" class="swiper-button-next home-top-next"></div>
                        <div id="top-prev-four" class="swiper-button-prev home-top-prev"></div>
                        <p class="text-right pt-1 fnt-xxs" id="recommendationFeedbackText">
                                <a href="javascript:void(0)" data-toggle="modal"
                                    data-target="#recommendationFeedBack"
                                    style="text-decoration: none; color: #2e333d; line-height: 1; border-bottom: 1px solid #a4a4a4;">Feedback</a>
                            </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </section>`);
    
    const result = await getAsync(`/baseHandler.ashx?type=get-recommendations-cart-and-wishlist`);

    if (!result || !result.products || result.products.length < 5) {
        return;
    }

    const WishlistSwiper = $("#WishlistSwiper");
    WishlistSwiper.empty();

    result.products.forEach((product, i) => {
        if(i > 15)
            return;
            
        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>`;

            WishlistSwiper.append(`<div class="swiper-slide">
                    <a class="cursor-pointer old-wishlist-recommendations" x-data-productid=${product.productId}>
	    		        <img class="top-category-img" src="${product.highResImageUrls[0]}" alt="" />
			        <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>
                    </a>
		        </div>`);
    });

    $("#wishlistSection").show();
    $("#wishlistRecommendations").show();
    
    

    const topCategorySwiper = new Swiper('.top-category-slider-wishlist', {
        slidesPerView: 1,
        spaceBetween: 15,
        loop: true,
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
        },
        observer: true,
        observeParents: true,
        navigation: {
            nextEl: '#top-next-four',
            prevEl: '#top-prev-four'
        },
        breakpoints: {
            640: {
                slidesPerView: 2,
                spaceBetween: 15
            },
            768: {
                slidesPerView: 3,
                spaceBetween: 100
            },
            1024: {
                slidesPerView: 5,
                spaceBetween: 15
            }
        }
    });

    $(".old-wishlist-recommendations").click(function (e) {
        const productDiv = $(this);
        const productId = productDiv.attr("x-data-productid");
        const userDetails = getUserDetails();
        const recommendationId = Math.floor(Date.now() + userDetails.userId + Math.random()).toString()
        result.products.forEach(productDetail => {
            SendEventDataToRudderstack('recommendation_product_loaded', {
                productId: productDetail.productId,
                recommendationId: recommendationId,
                pageType: "home-page",
                recommendationType: "Basis Wishlist"
            });
        });

        SendEventDataToRudderstack('recommendation_product_clicked', {
            productId: productId,
            recommendationId: recommendationId,
            pageType: "home-page",
            recommendationType: "Basis Wishlist"
        });

        const productDetail = result.products.find(p => p.productId === productId);
        let redirectUrl = `/shop/${productDetail.styleType}/${productDetail.name.replace(/ /g, "-")}-${productDetail.productId}?utm_source=home-page&utm_medium=recommendations&view_source=recommendation&utm_campaign=Basis-Wishlist`;
        let linkTarget = isMobile() ? "" : "_blank";
        window.open(redirectUrl, linkTarget);
    });
}


$(document).ready(function () {
    initializeNewTrending();
    initializeNewPopular();
    initializeOldTrending();
    initializeWishlistRecommendations();
});
;
