var PriceFormatter = {

    format: function(price){
        if(!price){
            return '';
        }

        price = String(price);
        price = price.padStart(3, '0');
        
        var amount = price.substr(0, price.length - 2); 
        var decimals = price.substr(price.length - 2);

        // Build price.
        var value = '';
        if(PriceFormatter.currencySignAtStart){
            value = PriceFormatter.currencySign;
        }

        if(amount.length > 3){
            amount = PriceFormatter.stringReverse(amount);
            amount = amount.replace(/(.{3})/g, "$1" + PriceFormatter.thousandsSeparator);
            amount = PriceFormatter.stringReverse(amount);
        }

        value += amount;

        if(PriceFormatter.showDecimals){
            value += PriceFormatter.decimalSeparator + decimals;
        }

        if(PriceFormatter.currencySignAtEnd){
            value += PriceFormatter.currencySign;
        }

        return value;
    },

    stringReverse: function(s) {
        var o = '';
        for (var i = s.length - 1; i >= 0; i--)
          o += s[i];
        return o;
    },

    showPrice: function(parentQuery, price, comparePrice){
        PriceFormatter.showPriceByElement($(parentQuery), price, comparePrice);
    },

    showPriceByElement: function(element, price, comparePrice){
        price = Math.trunc(price);
        comparePrice = Math.trunc(comparePrice);

        if(price == comparePrice || PriceFormatter.showComparePrice == 'no'){
            comparePrice = '';
        }

        element.find('span.price s').attr('data-compare-price', comparePrice).html(PriceFormatter.format(comparePrice));
        element.find('span.price span').attr('data-price', price).html(PriceFormatter.format(price));

        const taxRate = parseFloat(element.find('span.price_net').attr('data-tax-rate'));
        if(taxRate >= 0){
            const netPrice = PriceFormatter.calculateNetPrice(price, taxRate);
            element.find('span.price_net span').html(PriceFormatter.format(netPrice));
        }
    },

    calculateNetPrice: function(price, taxRate){
        return (price / (1 + taxRate)).toFixed(0);
    }

};

$(document).ready(function(){
    // Price pattern
    PriceFormatter.showComparePrice = $.trim(getConriseData('data-show-compare-price'));
    
    var smallPP = $.trim(getConriseData('data-small-price-pattern')).replace(/(<([^>]+)>)/gi, "");
    var pp = $.trim(getConriseData('data-price-pattern')).replace(/(<([^>]+)>)/gi, "");
    PriceFormatter.pricePattern = pp;
    PriceFormatter.currencySignAtStart = pp.indexOf('1') != 0;
    PriceFormatter.currencySignAtEnd = !PriceFormatter.currencySignAtStart;
    PriceFormatter.showDecimals = smallPP.indexOf(3) !== -1;
    
    if(PriceFormatter.currencySignAtStart){
        PriceFormatter.currencySign = pp.substr(0,pp.indexOf(1));
    }
    else if(PriceFormatter.currencySignAtEnd){
        if(PriceFormatter.showDecimals){
            PriceFormatter.currencySign = pp.substr(pp.indexOf(6) + 1).trim();
        }
        else{
            PriceFormatter.currencySign = smallPP.substr(smallPP.indexOf(22) + 2).trim();
        }
    }

    PriceFormatter.thousandsSeparator = pp.substring(pp.indexOf(1) + 1, pp.indexOf(2));
    if(PriceFormatter.showDecimals){
        PriceFormatter.decimalSeparator = pp.substring(pp.indexOf(4) + 1, pp.indexOf(5));
    }
    else{
        PriceFormatter.decimalSeparator = '';
    }

    window.cr_allowSectionHelpVideo = false;
    
    handleMenu();

    initCart();

    initUpsellSlider();

    initSearchPopup();

    // Footer
    $('.footer-column-menu h2').click(toggleFooterLinkList);

    // Product page
    if($('.template-product').length > 0 || $('.product-media').length > 0){
        handleProductPage();

        if($('.product-text-input[data-mandatory="true"]').length > 0 || $('.product-file-input[data-mandatory="true"]').length > 0){
            jQuery.fn.shake = function(intShakes, intDistance, intDuration) {
                this.each(function() {
                    $(this).css("position","relative"); 
                    for (var x=1; x<=intShakes; x++) {
                    $(this).animate({left:(intDistance*-1)}, (((intDuration/intShakes)/4)))
                .animate({left:intDistance}, ((intDuration/intShakes)/2))
                .animate({left:0}, (((intDuration/intShakes)/4)));
                }
              });
            return this;
            };
        }
    }

    // Collection page
    if($('.template-collection').length > 0 && $('.collection-product-grid').length > 0){
        // if there is no "collection-product-grid" elemetn, this function will not be called
        handleCollectionPage();
    }

    if($('.section-collection').length > 0 && $('.section-collection-card-wrapper').length > 0){
        // if there is no "template-collection" element, this function will not be called
        setupCollectionPageForm();
    }
    
    // Section handling. Sections can be placed everywhere.
    // Therefore, we do not only handle them on one specific page.
    handleSections();

    // Triggered by shopify editor. Reload stuff.
    document.addEventListener("shopify:section:load", function(event) {
        initUpsellSlider();
        if(event.detail.sectionId == "cart-drawer"){
            openCartDrawer();
        }

        if(event.detail.sectionId == "search-popup"){
            openSearchPopup();
        }

        if(event.detail.sectionId == "mobile-menu"){
            handleMenu();

            openMobileMenu();
        }

        if(event.detail.sectionId == "header-menu"){
            handleMenu();
        }

        if(event.detail.sectionId == "footer"){
            $('.footer-column-menu h2').click(toggleFooterLinkList);
        }

        // Animations.
        $('#shopify-section-' + event.detail.sectionId + ' .animated-element').each(function(){
            $(this).addClass('animated-element-show-animation');
        });

        // Sections.
        handleSections('shopify-section-' + event.detail.sectionId);
        handleProductPage('shopify-section-' + event.detail.sectionId);

        // Track edited section.
        var sectionName = event.detail.sectionId;
        if(sectionName.indexOf('__') !== -1){
            sectionName = sectionName.substring(sectionName.indexOf('__') + 2);
        }
        
        $.ajax({
            type: "POST",
            url: 'https://api.getconrise.com/v2/section-edited', 
            data : JSON.stringify({
                domain: getConriseData('data-domain'),
                section: sectionName
            }),
            contentType : 'application/json; charset=utf-8'
        });
    });

    document.addEventListener("shopify:section:select", function(event) {
        // Check if we allowed to display the help videos.
        if(!window.cr_allowSectionHelpVideo){
            return;
        }

        // Check if user has disabled the section video help.
        if(localStorage && localStorage.getItem('section-help-video-badge-disabled') == 'true'){
            return;
        }

        // Normal funcionality.
        var badge = $('#section-help-video-badge');

        // Search for identitifer and show badge...
        var identifier = $(event.target).find('.section-help-video-identifier');
        if(identifier && identifier.length > 0){
            badge.removeClass('hide-animation');
            badge.addClass('show-animation');
            badge.addClass('visible');

            var sectionData = identifier[0].dataset;
            badge.find('.section-help-video-badge-content p b').text('"' + sectionData.title + '"');
            badge.find('.btn').attr('data-video', sectionData.video);
            badge.find('.btn').attr('data-title', sectionData.title);
            badge.find('.btn').attr('data-padding-bottom', sectionData.paddingBottom);

            return;
        }

        // ... otherwise hide it.
        if(badge.hasClass('visible')){
            badge.removeClass('show-animation');
            badge.addClass('hide-animation');
            badge.removeClass('visible');
        }
    });

    document.addEventListener("shopify:section:deselect", function(event) {
        // Check if we allowed to display the help videos.
        if(!window.cr_allowSectionHelpVideo){
            return;
        }
        
        var badge = $('#section-help-video-badge');
        badge.removeClass('show-animation');
        badge.addClass('hide-animation');
        badge.removeClass('visible');
    });

    // Handle animated elements.
    if($('.animated-element:not(.animated-element-show-animation)').length > 0){
        var windowScrollTop = 0;
        var animatedElementFunction = function(){
            windowScrollTop = $(this).scrollTop() + Math.ceil(window.screen.height * 0.75);

            $('.animated-element:not(.animated-element-show-animation)').each(function(index, element){
                if(windowScrollTop >= element.offsetTop){
                    $(element).addClass('animated-element-show-animation');
                }
            });
        };
        $(window).scroll(animatedElementFunction);
        animatedElementFunction();
    }

    var downloadedThemeLanguage = 'de'; // ##
    var utm_source = 'Unknown'; // ####
    var utm_medium = ''; // ####
    var utm_campaign = ''; // ####
    var utm_content = ''; // ####

    $.ajax({
        type: "GET",
        url: 'https://api.getconrise.com/v2/store?domain=' + getConriseData('data-domain') + '&editor=' + (Shopify.designMode ? 'true' : 'false') + '&role=' + Shopify.theme.role + '&version=' + getConriseData('data-conrise-version') + '&country=' + getConriseData('data-country-of-shop') + '&theme_language=' + downloadedThemeLanguage + '&utm_source=' + utm_source + '&utm_medium=' + utm_medium + '&utm_campaign=' + utm_campaign + '&utm_content=' + utm_content,
        contentType : 'application/json; charset=utf-8',
        success: function(response){
            if(!response){
                $('#sales-view').hide();

                if(Shopify.designMode){
                    displayWhatsappSupport();
                }
                return;
            }

            // Overwrite texts.
            (response.htmlChanges || []).forEach((entry) => {
                if(entry.attr && entry.attr != ''){
                    $(entry.selector).attr(entry.attr, entry.value);
                }
                else{
                    $(entry.selector).html(entry.value);
                }
            });

            // Setup section help videos.
            window.cr_allowSectionHelpVideo = response.allowSectionHelpVideo;
            
            // Handling.
            if(!response.license){
                $('#starter-trail-expired-popup-iframe').attr('data-src', ($('#starter-trail-expired-popup-iframe').attr('data-src') + '&nolicense=true').replace('pages/purchase', 'pages/purchase-expired'));

                if(Shopify.designMode){
                    window.trialEndDateCalculated = true;
                    $('#sales-view button').click();
                }
                else{
                    if(isGermanShop()){
                        $('body').html('<div>Bitte gehe in den Theme-Editor. Du musst dort eine Handlung vornehmen.</div>');
                    }
                    else{
                        $('body').html('<div>Please go to the theme editor. You must perform an action there.</div>');
                    }
                    
                    $('body div').css({
                        position: 'absolute',
                        top: '50%',
                        left: '50%',
                        transform: 'translate(-50%, -50%)',
                        "text-align": "center"
                    });
                }
            }
            else if(response.state == 'ONBOARDING'){
                $('main').hide();
                $('#discounted-trail-welcome').show();
                $('.discounted-trail-welcome-text').html($('.discounted-trail-welcome-text').text());

                $('#discounted-trail-welcome iframe').attr('src', $('#discounted-trail-welcome iframe').attr('data-src'));

                buildOnboardingPushNotifications();
            }
            else if(response.state == 'PURCHASED'){
                $('#sales-view').hide();

                if(response.upselling && response.upselling == 'ONE_TIME' && Shopify.designMode){
                    $('#sales-view').css('display', 'flex');
                    $('#sales-view').addClass('upgrade');
                    $('#sales-view .btn').html($('#sales-view .btn').attr('data-upgrade-translation'));

                    $('#starter-trail-expired-popup-iframe').attr('data-src', ($('#starter-trail-expired-popup-iframe').attr('data-src') + '&nolicense=true&offerupgrade=true').replace('pages/purchase', 'pages/purchase-expired'));

                    window.trialEndDateCalculated = true;
                    $(document).trigger('trialEndDateCalculated');
                }
            }
            else if(response.state == 'TRAIL' && Shopify.designMode){
                if(response.showSalesView !== false){
                    $('#sales-view').css('display', 'flex');
                }

                // Set date.
                var trialDuration = 14;
                var options = { month: 'long', day: '2-digit' };
                var trailStartDate = new Date(response.trailStartedDate * 1000);
                var trailEndDate = new Date(response.trailStartedDate * 1000);
                trailEndDate.setDate(trailEndDate.getDate() + trialDuration);

                $('#sales-view .sales-view-ending-date').text(trailEndDate.toLocaleDateString($('#sales-view').attr('data-locale'), options));

                // Set title.
                var now = new Date();
                var days = 0;
                if(trailStartDate.getMonth() != now.getMonth()){
                    var lastMonthDateObject = new Date(trailStartDate);
                    lastMonthDateObject.setMonth(lastMonthDateObject.getMonth() + 1);
                    lastMonthDateObject.setDate(0);

                    var lastMonthDays = lastMonthDateObject.getDate();
                    days = lastMonthDays - trailStartDate.getDate();
                    days += now.getDate();
                }
                else{
                    days = now.getDate() - trailStartDate.getDate();
                }

                days = trialDuration - days;

                if(days < 0){
                    days = 0;
                }

                if(days == 0){
                    $('#sales-view .sales-view-header span').text($('#sales-view .sales-view-header span').attr('data-ending-today-translation'));
                }
                else if(days == 1){
                    $('#sales-view .sales-view-header span').text($('#sales-view .sales-view-header span').attr('data-ending-tomorrow-translation'));
                }
                else if(days < trialDuration - 2){
                    $('#sales-view .sales-view-header span').text($('#sales-view .sales-view-header span').attr('data-ending-translation').replace('{days}', days));
                }

                // Setup sales iframe.
                $('#starter-trail-expired-popup-iframe').attr('data-src', $('#starter-trail-expired-popup-iframe').attr('data-src') + '&trailenddate=' + trailEndDate.getTime());

                window.trialEndDateCalculated = true;
                $(document).trigger('trialEndDateCalculated');
            }
            else if(response.state == 'TRAIL_EXPIRED' && Shopify.designMode){
                $('#sales-view').css({
                    'display': 'flex',
                    'background-color': '#b71b00'
                });

                $('#sales-view .sales-view-header span').text($('#sales-view .sales-view-header span').attr('data-expired-translation'));
                $('#sales-view .sales-view-ending').html($('#sales-view .sales-view-ending').attr('data-expired-translation'));
                $('#sales-view .sales-view-info').html($('#sales-view .sales-view-info').attr('data-expired-translation'));

                // Setup sales iframe.
                $('#starter-trail-expired-popup-iframe').attr('data-src', $('#starter-trail-expired-popup-iframe').attr('data-src') + '&trailexpired=true');

                window.trialEndDateCalculated = true;
                $(document).trigger('trialEndDateCalculated');
            }

            // Remove onboarding view from html.
            if(response.state != 'ONBOARDING'){
                $('#discounted-trail-welcome').remove();
            }

            // Show help.
            if(Shopify.designMode && (response.state == 'TRAIL' || response.state == 'TRAIL_EXPIRED' || response.state == 'PURCHASED')){
                displayWhatsappSupport();
            }

            // Zoom Call.
            if(Shopify.designMode && response.zoom){
                var zoomDate = new Date(response.zoom.date);
                var zoomDateString = zoomDate.getHours().toString().padStart(2, '0') + ':' + zoomDate.getMinutes().toString().padStart(2, '0');
                var title = response.zoom.title[getConriseData('data-language')].replace('{date}', zoomDateString);

                if(zoomDate.getTime() <= Date.now()){
                    $('#zoom-call-button').addClass('on-air');
                }
                else{
                    setTimeout(function(){
                        $('#zoom-call-button').addClass('on-air');
                    }, zoomDate.getTime() - Date.now());
                }

                $('#zoom-call-button').css('display', 'flex');
                $('.zoom-call-button-title').html(title);

                $('#zoom-call-popup').attr('src', $('#zoom-call-popup').attr('data-src') + 'date=' + response.zoom.date + '&title=' + title + '&link=' + response.zoom.link);
            }
        },
        error: function(){
            $('#sales-view').hide();

            if(Shopify.designMode){
                displayWhatsappSupport();
            }
        }
    });

    $('#discounted-trail-welcome .btn').click(function(){
        showLoadingIndicator();

        var url = $(this).attr('data-url');

        // Do api call.
        $.ajax({
            type: "PUT",
            url: 'https://api.getconrise.com/v2/trail?domain=' + getConriseData('data-domain') + '&t=d',
            contentType : 'application/json; charset=utf-8',
            success: function(response){
                if(!response || !response.success){
                    if(isGermanShop()){
                        alert('Es ist ein Fehler aufgetreten: ' + response.message + '\nBitte wende dich an unseren Support: support@getconrise.com.');
                    }
                    else{
                        alert('An error has occurred: ' + response.message + '\nPlease contact our support: support@getconrise.com.');
                    }
                    
                    return;
                }

                if(!url){
                    hideLoadingIndicator();

                    $('main').show();
                    $('#discounted-trail-welcome').hide();
                }
                else{
                    window.location.href = url;
                }
            }
        });
    });

    if(!Shopify.designMode){
        return;
    }

    $('#zoom-call-button').click(function(){
        $('#zoom-call-popup').show();

        window.scrollTo(0, 0);

        $('main').hide();
    });

    $('#starter-trail-expired-popup .btn').click(function(){
        apiT(3);
    });

    // Sales view.
    $('#sales-view button').click(function(e){
        var openFunc = function(){
            hideLoadingIndicator();

            $('#starter-trail-expired-popup-iframe').show();
            $('#starter-trail-expired-popup-iframe').attr('src', $('#starter-trail-expired-popup-iframe').attr('data-src'));

            $('#starter-trail-expired-popup-overlay').show();
            
            window.scrollTo(0, 0);

            $('main').hide();

            apiT(2);
        };

        if(window.trialEndDateCalculated){
            openFunc();
        }
        else{
            showLoadingIndicator();
            $(document).on('trialEndDateCalculated', openFunc);
        }
    });

    $('#sales-view .sales-view-header img').click(function(e){
        e.preventDefault();
        e.stopPropagation();

        if($('#sales-view').hasClass('collapsed')){
            $('#sales-view').click();
            return;
        }

        $('.sales-view-ending').hide();
        $('.sales-view-info').hide();
        $('#sales-view .btn').hide();

        $('#sales-view').addClass('collapsed');

        if(localStorage){
            localStorage.setItem('sales_view_collapsed', true);
        }
    });

    $('#sales-view').click(function(e){
        e.preventDefault();
        e.stopPropagation();

        if(!$(this).hasClass('collapsed')){
            return;
        }

        $('.sales-view-ending').show();
        $('.sales-view-info').show();
        $('#sales-view .btn').show();

        $('#sales-view').removeClass('collapsed');

        if(localStorage){
            localStorage.setItem('sales_view_collapsed', false);
        }
    });

    if(localStorage && localStorage.getItem('sales_view_collapsed') == 'true'){
        $('#sales-view .sales-view-header img').click();
    }

    // Help center
    $('#help-view').click(function(){
        $('#help-dashboard').show();
        $('#help-dashboard').attr('src', $('#help-dashboard').attr('data-src'));
        $('#help-dashboard-overlay').show();

        window.scrollTo(0, 0);

        $('main').hide();
    });

    window.addEventListener('message', (evt) => {
        // Sales view.
        if(evt && evt.data === 'conrise:close-sales-view'){
            $('#starter-trail-expired-popup-iframe').hide();
            $('#starter-trail-expired-popup-iframe').removeAttr('src');
            $('#starter-trail-expired-popup-iframe').removeClass('animate');

            $('#starter-trail-expired-popup-overlay').hide();
            $('#starter-trail-expired-popup-overlay').removeClass('animate');
            
            $('main').show();
        }
        
        // Help center.
        if(evt && evt.data === 'conrise:close-help-center'){
            $('main').show();
            $('#help-dashboard').hide();
            $('#help-dashboard').removeAttr('src');
            $('#help-dashboard').removeClass('animate');
    
            $('#help-dashboard-overlay').hide();
            $('#help-dashboard-overlay').removeClass('animate');
        }
        
        if(evt && typeof evt.data === 'object' && evt.data.event_id && evt.data.event_id === 'conrise:help-center-mailto'){
            $('#conrise-mailto-link').remove();
            $('body').append('<a href="' + evt.data.data.href + '" id="conrise-mailto-link" style="display:none"></a>');
            document.getElementById('conrise-mailto-link').click();
        }

        // Zoom.
        if(evt && evt.data === 'conrise:close-zoom-view'){
            $('#zoom-call-popup').hide();
            $('main').show();
        }
    });

    // Whatsapp Support.
    $('#whatsapp-support svg').click(function(){
        $('#whatsapp-support').hide();
        $('#help-view').css('display', 'flex');

        if(localStorage){
            localStorage.setItem('hide-whatsapp-support', true);
        }
    });

    $('#whatsapp-support .whatsapp-support-content img').click(function(){
        $('#whatsapp-support').addClass('minimized');
        $('#whatsapp-support iframe').removeAttr('src');

        if(localStorage){
            localStorage.setItem('whatsapp-support-expanded', false);
        }
    });

    $('.whatsapp-support-content-collapsed').click(function(){
        $('#whatsapp-support').removeClass('minimized');
        $('#whatsapp-support iframe').attr('src', $('#whatsapp-support iframe').attr('data-src'));

        if(localStorage){
            localStorage.setItem('whatsapp-support-expanded', true);
        }
    });

    if(localStorage && localStorage.getItem('whatsapp-support-expanded') == 'true'){
        $('.whatsapp-support-content-collapsed').click();
    }

    // Section Help.
    $('#section-help-video-badge svg').click(function(){
        $('#section-help-video-badge').removeClass('show-animation');
        $('#section-help-video-badge').addClass('hide-animation');
        $('#section-help-video-badge').removeClass('visible');
    });

    $('#section-help-video-badge button').click(function(){
        var data = $('#section-help-video-badge button')[0].dataset;

        $('main').hide();

        $('#section-help-video-popup').css('display', 'flex');
        $('#section-help-video-popup h1').text(data.title);
        $('.section-help-video-popup-content div').css('padding-bottom', data.paddingBottom);
        $('.section-help-video-popup-content iframe').attr('src', 'https://www.loom.com/embed/' + data.video + '&hideEmbedTopBar=true');
    });

    $('.section-help-video-badge-bottom span').click(function(){
        $('.section-help-video-badge-bottom input').click();
    });

    $('.section-help-video-badge-bottom input').change(function(){
        if(localStorage){
            localStorage.setItem('section-help-video-badge-disabled', $(this).prop('checked'));
        }
    });

    $('#section-help-video-popup button').click(function(){
        $('main').show();

        $('.section-help-video-popup-content iframe').removeAttr('src');
        $('#section-help-video-popup').hide();
    });

    // Theme name.
    if(Shopify && Shopify.theme && Shopify.theme.name){
        Shopify.theme.name = 'conrise => https://getconrise.com';
    }
});

function getConriseData(type){
    var data = $('#conrise-data').attr(type);
    if(!data){
        return $('body').attr(type);
    }

    return data;
}

function getShopifyApiRoot(){
    if(Shopify && Shopify.routes && Shopify.routes.root){
        return Shopify.routes.root;
    }

    return '/';
}

function displayWhatsappSupport(){
    if(localStorage && localStorage.getItem('hide-whatsapp-support') == 'true'){
        $('#whatsapp-support').hide();
        $('#help-view').css('display', 'flex');
    }
    else{
        $('#whatsapp-support').show();
    }
}

function handleMenu(){
    // Header handling.
    $('main').css('padding-top', $('#header').outerHeight());
    window.addEventListener('resize',function(){
        $('main').css('padding-top', $('#header').outerHeight());
    });

    // Mobile menu
    $('.header-menu-mobile-menu').click(openMobileMenu);
    $('.mobile-menu-header-close-icon').click(closeMobileMenu);
    $('#mobile-menu-overlay').click(closeMobileMenu);

    if($('.mobile-menu-header img').length == 0){
        $('.header-menu-logo img').clone().prependTo('.mobile-menu-header');
    }
    $('.mobile-menu-header img').css('height', 'auto');

    // Sub Links Mobile.
    $('.mobile-menu-sub-link-list').prev().removeAttr('href');
    $('.mobile-menu-sub-link-list').prev().click(openSubMobileMenu);
    $('#mobile-menu-content-submenu .mobile-menu-content-submenu-header div').click(closeSubMobileMenu);

    // Sub-Sub Links Mobile.
    $('.mobile-menu-sub-sub-link-list').prev().removeAttr('href');
    $('.mobile-menu-sub-sub-link-list').prev().click(openSubSubMobileMenu);
    $('#mobile-menu-content-sub-submenu .mobile-menu-content-submenu-header div').click(closeSubSubMobileMenu);

    // Sub Links Desktop.
    $('.header-menu-sub-links:not(.header-menu-sub-sub-links)').parent().hover(showSubDesktopMenu, hideSubDesktopMenu);
    $('.header-menu-sub-links.header-menu-sub-sub-links').parent().hover(showSubSubDesktopMenu, hideSubSubDesktopMenu);

    // Cart drawer.
    $('.header-menu-cart-drawer').click(openCartDrawer);
    $('#cart-drawer-overlay').click(closeCartDrawer);

    // Search popup.
    $('.header-menu-search-popup').click(openSearchPopup);
    $('#search-popup-overlay').click(closeSearchPopup);

    $('.mobile-menu-search').click(function(){
        closeMobileMenu();
        openSearchPopup();

        $('.header-menu-search-popup input').focus();
    });
}

function buildOnboardingPushNotifications(){
    var nameList = ['Thomas', 'Lisa', 'Ben', 'Mia', 'Chris'];
    var dateList = ['Jetzt', 'Vor 46 Min.', 'Vor 1 Std.', 'Vor 29 Min.', 'Vor 2 Std.'];
    var priceList = [34.99, 29.95, 19.99, 79.95, 129.99];
    var cloneNotification = function(left, top, bottom, rotateZ){
        var push = $('.shopify-app-push-notification.temp').clone().appendTo('#discounted-trail-welcome');
        push.removeClass('temp');

        push.find('h4').text(nameList[Math.floor(Math.random() * nameList.length)]);
        push.find('span').text(dateList[Math.floor(Math.random() * dateList.length)]);
        push.find('p b').text(priceList[Math.floor(Math.random() * priceList.length)]);
        push.find('.shopify-app-push-notification-container').css({
            'width': Math.floor(Math.random() * (250 - 180 + 1) + 180) + 'px',
            'animation': 'shopify-app-push-notification-Animation 0.3s linear ' + (Math.floor(Math.random() * 1000) + 800) + 'ms forwards'
        });

        push.show();

        push.css({
            left: left,
            top: top,
            bottom: bottom,
            transform: 'rotateZ(' + rotateZ + 'deg) translate(-50%, ' + (top == 'initial' ? '' : '-') + '50%)'
        });
    };

    // Top
    cloneNotification('23%', '0px', 'initial', -1);
    cloneNotification('89%', '4px', 'initial', -5);
    cloneNotification('98%', '6px', 'initial', -4);
    cloneNotification('95%', '5px', 'initial', 0);
    cloneNotification('1%' , '2px', 'initial', 3);
    cloneNotification('55%', '7px', 'initial', -2);
    cloneNotification('23%', '6px', 'initial', -3);
    cloneNotification('47%', '8px', 'initial', 4);
    cloneNotification('81%', '0px', 'initial', 1);
    cloneNotification('78%', '5px', 'initial', -1);
    cloneNotification('17%', '9px', 'initial', -4);
    cloneNotification('64%', '1px', 'initial', -4);
    cloneNotification('25%', '5px', 'initial', -2);
    cloneNotification('37%', '7px', 'initial', 2);
    cloneNotification('38%', '2px', 'initial', 3);

    // Bottom.
    cloneNotification('100%', 'initial', '4px', 1);
    cloneNotification('16%', 'initial', '2px', -5);
    cloneNotification('73%', 'initial', '9px', -1);
    cloneNotification('19%', 'initial', '6px', -5);
    cloneNotification('55%', 'initial', '4px', -5);
    cloneNotification('85%', 'initial', '0px', 6);
    cloneNotification('14%', 'initial', '0px', 6);
    cloneNotification('2%' , 'initial', '8px', -1);
    cloneNotification('81%', 'initial', '7px', 0);
    cloneNotification('22%', 'initial', '0px', -5);
    cloneNotification('69%', 'initial', '1px', -1);
    cloneNotification('0%' , 'initial', '2px', 5);
    cloneNotification('39%', 'initial', '4px', 0);
    cloneNotification('37%', 'initial', '4px', 1);
    cloneNotification('48%', 'initial', '2px', 5);
}

function isGermanShop(){
    return getConriseData('data-language') == 'de';
}

function handleTickInit(tick){
    // Setup translations.
    var locale = {
        YEAR_PLURAL: 'Jahre',
        YEAR_SINGULAR: 'Jahr',
        MONTH_PLURAL: 'Monate',
        MONTH_SINGULAR: 'Monat',
        WEEK_PLURAL: 'Wochen',
        WEEK_SINGULAR: 'Woche',
        DAY_PLURAL: 'Tage',
        DAY_SINGULAR: 'Tag',
        HOUR_PLURAL: 'Stunden',
        HOUR_SINGULAR: 'Stunde',
        MINUTE_PLURAL: 'Minuten',
        MINUTE_SINGULAR: 'Minute',
        SECOND_PLURAL: 'Sekunden',
        SECOND_SINGULAR: 'Sekunde',
        MILLISECOND_PLURAL: 'Millisekunden',
        MILLISECOND_SINGULAR: 'Millisekunde'
    };

    for (var key in locale) {
        if (!locale.hasOwnProperty(key)) { continue; }
        tick.setConstant(key, locale[key]);
    }

    // Setup handler.
    window.countdownTicker = tick;
    $(document).trigger('TickerInit');
}

function apiT(type){
    $.ajax({
        type: "POST",
        url: 'https://api.getconrise.com/t', 
        data : JSON.stringify({
            type: type,
            d: $('body').attr('data-download-id')
        }),
        contentType : 'application/json; charset=utf-8'
    });
}

function openMobileMenu(){
    $('#mobile-menu').css('visibility', 'visible');

    $('#mobile-menu-overlay').css('opacity', '0.5');
    $('#mobile-menu-content').css('transform', 'translateX(0%)');
}

function closeMobileMenu(){
    setTimeout(function(){
        $('#mobile-menu').css('visibility', 'hidden');
    }, 200);

    $('#mobile-menu-overlay').css('opacity', '0');
    $('#mobile-menu-content').css('transform', 'translateX(-100%)');
}

function openSubMobileMenu(){
    $(this).next().attr('data-open', 'true');

    $('#mobile-menu-content-submenu').css({
        'transform': 'translateX(0%)'
    });

    // Title.
    $('#mobile-menu-content-submenu h3').text($(this).find('span').text());

    // Menu list.
    $('#mobile-menu-content-submenu .mobile-menu-content-submenu-content').empty();

    var cloned = $(this).next().clone(true, true);
    cloned.appendTo('#mobile-menu-content-submenu .mobile-menu-content-submenu-content');
    cloned.show();
}

function closeSubMobileMenu(){
    $('#mobile-menu-content-submenu').css({
        'transform': 'translateX(100%)'
    });
}

function openSubSubMobileMenu(){
    $(this).next().attr('data-open', 'true');

    $('#mobile-menu-content-sub-submenu').css({
        'transform': 'translateX(0%)'
    });

    // Title.
    $('#mobile-menu-content-sub-submenu h3').text($(this).find('span').text());

    // Menu list.
    $('#mobile-menu-content-sub-submenu .mobile-menu-content-submenu-content').empty();

    var cloned = $(this).next().clone(true, true);
    cloned.appendTo('#mobile-menu-content-sub-submenu .mobile-menu-content-submenu-content');
    cloned.show();
}

function closeSubSubMobileMenu(){
    $('#mobile-menu-content-sub-submenu').css({
        'transform': 'translateX(100%)'
    });
}

function showSubDesktopMenu(){
    $(this).find('ul:not(.header-menu-sub-sub-links)').show();
}

function hideSubDesktopMenu(){
    $(this).find('ul:not(.header-menu-sub-sub-links)').hide();
}

function showSubSubDesktopMenu(){
    $(this).find('ul.header-menu-sub-sub-links').show();
}

function hideSubSubDesktopMenu(){
    $(this).find('ul.header-menu-sub-sub-links').hide();
}

function openCartDrawer(){
    if($(document).width() < 768){
        $('#cart-drawer .cart-drawer-content').css('width', '100%');
    }
    else{
        $('#cart-drawer .cart-drawer-content').css('width', '35%');
    }

    $('#cart-drawer').css('visibility', 'visible');

    $('#cart-drawer-overlay').css('opacity', '0.5');
    $('#cart-drawer .cart-drawer-content').css('transform', 'translateX(0%)');

    // Handle scrollbar.
    if($(document).width() >= 768 || Shopify.designMode){
        $('body, #shopify-section-header-announcement-bar, #shopify-section-header-menu').css('padding-right', window.innerWidth - document.body.offsetWidth);
    }

    $('body').addClass('overflow-hidden');
}

function closeCartDrawer(){
    setTimeout(function(){
        $('#cart-drawer').css('visibility', 'hidden');
    }, 200);

    $('#cart-drawer-overlay').css('opacity', '0');
    $('#cart-drawer .cart-drawer-content').css('transform', 'translateX(100%)');

    // Handle scrollbar.
    if($(document).width() >= 768 || Shopify.designMode){
        $('body, #shopify-section-header-announcement-bar, #shopify-section-header-menu').css('padding-right', 0);
    }

    $('body').removeClass('overflow-hidden');
}

function openSearchPopup(){
    if($(document).width() < 768){
        $('#search-popup .search-popup-content').css('width', '100%');
    }
    else{
        $('#search-popup .search-popup-content').css('width', '400px');
    }

    $('#search-popup').css('visibility', 'visible');

    $('#search-popup-overlay').css('opacity', '0.5');
    $('#search-popup .search-popup-content').css('transform', 'translateX(0%)');
}

function closeSearchPopup(){
    setTimeout(function(){
        $('#search-popup').css('visibility', 'hidden');
    }, 200);

    $('#search-popup-overlay').css('opacity', '0');
    $('#search-popup .search-popup-content').css('transform', 'translateX(100%)');
}

function toggleFooterLinkList(){
    if($(document).width() >= 768){
        return;
    }

    var ul = $(this).next();

    if(ul.css('display') == 'none'){
        if($(this).parents('.footer-column-menu-show-centered').length > 0){
            $(this).find('span:last-child svg').css('transform', 'rotate(90deg)');
        }
        else{
            $(this).find('span:last-child').text('-');
        }
        
        ul.show();
    }
    else{
        if($(this).parents('.footer-column-menu-show-centered').length > 0){
            $(this).find('span:last-child svg').css('transform', 'rotate(0deg)');
        }
        else{
            $(this).find('span:last-child').text('+');
        }

        ul.hide();
    }
}

function showLoadingIndicator(){
    $('#loading-indicator').css('display', 'flex');
}

function hideLoadingIndicator(){
    $('#loading-indicator').css('display', 'none');
}

/* ======================================= */
/* =============== PRODUCT =============== */
/* ======================================= */
let countdownTimer;
function handleProductPage(containerId){
    if(containerId){
        containerId = '#' + containerId + ' ';
    }
    else{
        containerId = "";
    }

    // Swiper.
    var showThumbnails = $(containerId + '.product-media-main').attr('data-thumbnails');
    var mobileVertical = $(containerId + '.product-media-main').attr('data-mobile-vertical');
    var mobileFullWidth = $(containerId + '.product-media-main').attr('data-mobile-full-width');
    var desktopNavigation = $(containerId + '.product-media-main').attr('data-desktop-navigation');
    var mobileNavigation = $(containerId + '.product-media-main').attr('data-mobile-navigation');
    var spaceBetweenThumbnails = parseInt($(containerId + '.product-media-main').attr('data-space-between-thumbnails'));
    var mainSwiperSpaceBetween = 10;

    if(spaceBetweenThumbnails > 0){
        mainSwiperSpaceBetween = spaceBetweenThumbnails;
    }

    var mainSwiperOptions = {
        pagination: {
            el: containerId + '.product-media-main .swiper-pagination'
        },
        slidesPerView: 1,
        spaceBetween: 0,
        on: {
            slideChange: function(swiper){
                // Last slide.
                var slide = swiper.slides[swiper.previousIndex];
                var video = $(slide).find('video');

                if(video.length > 0){
                    video[0].pause();
                }

                // Current slide.
                slide = swiper.slides[swiper.activeIndex];
                video = $(slide).find('video');

                if(video.length > 0){
                    video[0].currentTime = 0;
                    video[0].play();
                }
            }
        }
    };

    if(mobileFullWidth != 'true'){
        mainSwiperOptions.spaceBetween = mainSwiperSpaceBetween;
    }
    if(showThumbnails == 'true'){
        mainSwiperOptions.thumbs = {
            swiper: new Swiper(containerId + '.product-media-thumbnail', {
                slidesPerView: 5,
                spaceBetween: spaceBetweenThumbnails,
                slideToClickedSlide: true
            })        
        };
    }
    if(mobileVertical == 'true'){
        mainSwiperOptions.direction = 'vertical';
        mainSwiperOptions.touchReleaseOnEdges = true;
        mainSwiperOptions.resistanceRatio = 0;
        mainSwiperOptions.mousewheel = {
            releaseOnEdges: true
        };
        mainSwiperOptions.breakpoints = {
            768:{
                direction: 'horizontal',
                spaceBetween: mainSwiperSpaceBetween
            }
        };

        $(containerId + '.product-media-main').height($(containerId + '.product-media-main').width());
    }
    else{
        mainSwiperOptions.breakpoints = {
            768:{
                spaceBetween: mainSwiperSpaceBetween
            }
        };
    }

    if(desktopNavigation == 'true' && mobileNavigation == 'true'){
        mainSwiperOptions.navigation = {
            nextEl: containerId + '.product-media-main .swiper-button-next',
            prevEl: containerId + '.product-media-main .swiper-button-prev'
        };
    }
    else if(desktopNavigation == 'true'){
        mainSwiperOptions.navigation = {};

        if(mainSwiperOptions.breakpoints && mainSwiperOptions.breakpoints['768']){
            mainSwiperOptions.breakpoints['768'].navigation = {
                nextEl: containerId + '.product-media-main .swiper-button-next',
                prevEl: containerId + '.product-media-main .swiper-button-prev'
            };
        }
        else{
            mainSwiperOptions.breakpoints = {
                768:{
                    navigation: {
                        nextEl: containerId + '.product-media-main .swiper-button-next',
                        prevEl: containerId + '.product-media-main .swiper-button-prev'
                    }
                }
            };
        }
    }
    else if(mobileNavigation == 'true'){
        mainSwiperOptions.navigation = {
            nextEl: containerId + '.product-media-main .swiper-button-next',
            prevEl: containerId + '.product-media-main .swiper-button-prev'
        };

        if(mainSwiperOptions.breakpoints && mainSwiperOptions.breakpoints['768']){
            mainSwiperOptions.breakpoints['768'].navigation = {};
        }
        else{
            mainSwiperOptions.breakpoints = {
                768:{
                    navigation: {}
                }
            };
        }
    }

    window.mainSwiper = new Swiper(containerId + '.product-media-main', mainSwiperOptions);

    $(containerId + '.product-media-main img').click(function(){
        window.mainSwiper.slideNext();
    });

    $('model-viewer').each(function(){
        if($(this).parents('.swiper-wrapper').length > 0){
            $(this).css('height', $(this).parents('.swiper-wrapper').height());
        }
    });

    // Quantity.
    $(containerId + '.product-information-quantity button[name="minus"]').click(function(){
        if($('#product-information-cart-button').attr('disabled')){
            return;
        }

        var input = $(containerId + '.product-information-quantity-field');
        var span = $(containerId + '.product-information-quantity-input');
        var value = Math.max(1, parseInt(input.val()) - 1);
        span.text(value);
        input.val(value);

        if(value == 1){
            $(containerId + '.product-information-quantity button[name="minus"] svg path').css('stroke', 'var(--color-border)');
        }
    });
    $(containerId + '.product-information-quantity button[name="plus"]').click(function(){
        if($('#product-information-cart-button').attr('disabled')){
            return;
        }

        var input = $(containerId + '.product-information-quantity-field');
        var span = $(containerId + '.product-information-quantity-input');
        var value = parseInt(input.val()) + 1;

        if($(this)[0].hasAttribute('data-stock')){
            value = Math.min(value, $(this).attr('data-stock'));
        }

        span.text(value);
        input.val(value);

        $(containerId + '.product-information-quantity button[name="minus"] svg path').css('stroke', 'var(--color-text)');
    });

    // Variant.
    $(containerId + '.product-variant-select').change(function(){
        setupSelectedVariant();
    });
    $(containerId + '.product-variant-radio').change(setupSelectedVariant);

    $(containerId + '.product-information-variant-picker-button-variant-option').click(function(){
        var radio = $(this).find('.product-variant-radio');
        $(containerId + '.product-variant-radio[name="' + radio.attr('name') + '"]').removeAttr('checked');
        radio.attr('checked', true);
        
        setupSelectedVariant();
    });

    $(containerId + '.product-information-variant-picker-button-box').click(function(e){
        var variants = $(this).find('.product-information-variant-picker-button-variants');
        if(variants.css('display') == 'none'){
            variants.css('display', 'flex');
            $(this).find('label svg').css('rotate', '90deg');
            return;
        }

        if(
            $(e.target).is('.product-information-variant-picker-button-variant label') || 
            $(e.target).is('.product-information-variant-picker-button-variant label *')
        ){
            variants.css('display', 'none');
            $(this).find('label svg').css('rotate', '0deg');
        }
    });

    setupSelectedVariant(true);

    // Form.
    $('#product-add-to-cart-form').submit(function(event){
        event.preventDefault();

        if($('#product-information-cart-button').attr('disabled')){
            return;
        }

        // Handle text mandatory fields.
        var allMandatoryFieldsFilled = true;
        $('.product-text-input[data-mandatory="true"] input').each(function(){
            if($(this).val() == ''){
                $(this).shake(2, 5, 300);
                allMandatoryFieldsFilled = false;

                return;
            }
        });
        $('.product-file-input[data-mandatory="true"] input').each(function(){
            if($(this).val() == ''){
                $(this).shake(2, 5, 300);
                allMandatoryFieldsFilled = false;

                return;
            }
        });

        if(!allMandatoryFieldsFilled){
            return;
        }

        // Start loading.
        var showGoodChoiceText = $('#product-information-cart-button').data().showGoodChoiceText;
        if(showGoodChoiceText){
            $('#product-information-cart-button').addClass('clicked');
        }
        else{
            showLoadingIndicator();
        }

        // Data handling.
        var data = $(this).serialize();

        if($('.product-set-discounts').length > 0){
            data = {
                'form_type': 'product'
            };

            if($('#product-add-to-cart-form input[name="product-id"]').length > 0){
                data['product-id'] = $('#product-add-to-cart-form input[name="product-id"]').val();
            }

            // Handle properties.
            var properties = {};
            $(this).serializeArray().forEach(function(entry){
                if(entry.name.indexOf('properties[') !== -1){
                    var name = entry.name.replace('properties[', '');
                    name = name.substring(0, name.length - 1);

                    properties[name] = entry.value;
                }
            });

            // Handle options.
            var selectedOptions = [];
            $('.product-set-discounts-entry.selected .product-set-discounts-entry-content-product-body-select').each(function(){
                var options = [];

                $(this).find('select').each(function(){
                    options.push({
                        key: 'option' + (cr_product.options.indexOf($(this).attr('name')) + 1),
                        value: $(this).val()
                    });
                });

                selectedOptions.push(options);
            });

            var selectedVariants = [];
            selectedOptions.forEach(function(options){
                var variant = cr_product.variants.find(function(variant) {
                    return options.every(function(values) {
                        return variant[values.key] === values.value;
                    });
                });

                selectedVariants.push({
                    id: variant.id,
                    quantity: 1,
                    properties: properties
                });
            });

            data.items = selectedVariants;
        }

        // auto add product to cart
        var autoProductUpdate = $('.add-product-automatically');
        if(autoProductUpdate.length > 0){
            var obj = Object.fromEntries(new URLSearchParams(data));
            var toBeAdded = autoProductUpdate.attr('to-be-added');
            var trigger = autoProductUpdate.attr('trigger-product');
            var cart_item_property_key = autoProductUpdate.attr('cart-item-property-key');
            var cart_item_property_value = autoProductUpdate.attr('cart-item-property-value');
            if(obj["product-id"] == trigger){
                if(data.items){
                    var item_property = {};
                    item_property[cart_item_property_key] = cart_item_property_value;
                    data.items.push({
                        id: toBeAdded,
                        quantity: 1,
                        properties: item_property
                    });
                }else{
                    data = {}
                    data.form_type = 'product';
                    var new_item_property = {};
                    new_item_property[cart_item_property_key] = cart_item_property_value;
                    data.items = [{
                        id: toBeAdded,
                        quantity: 1,
                        properties: new_item_property
                    },
                    {
                        id: obj.id,
                        quantity: obj.quantity
                    }];
                }
            }
        }

        var ajaxData = {
            type: 'POST', 
            url: getShopifyApiRoot() + 'cart/add.js',
            dataType: 'json', 
            data: data,
            success: function(){
                var cartType = $('#product-information-cart-button').data().cartType;

                // Forward to cart page.
                if(cartType == 'page'){
                    if(showGoodChoiceText){
                        $('#product-information-cart-button').removeClass('clicked');
                    }
                    else{
                        hideLoadingIndicator();
                    }
                    
                    window.location.href = "/cart";
                    return;
                }

                // Forward to checkout page.
                if(cartType == 'go_to_checkout'){
                    if(showGoodChoiceText){
                        $('#product-information-cart-button').removeClass('clicked');
                    }
                    else{
                        hideLoadingIndicator();
                    }
                    
                    window.location.href = "/checkout";
                    return;
                }

                // Forward to external page.
                if(cartType == 'go_to_external'){
                    var externalLink = $('#product-information-cart-button').data().cartExternalPageLink;
                    if(showGoodChoiceText){
                        $('#product-information-cart-button').removeClass('clicked');
                    }
                    else{
                        hideLoadingIndicator();
                    }
                    
                    window.location.href = externalLink;
                    return;
                }

                // Normal usage.
                reloadCart(function(){
                    if(cartType == 'slider'){
                        openCartDrawer();
                    }

                    if(showGoodChoiceText){
                        $('#product-information-cart-button').removeClass('clicked');
                    }
                    else{
                        hideLoadingIndicator();
                    }

                    if($('.product-information-buy-buttons').attr('data-vanga-activated') == 'true' && window.Vanga){
                        window.Vanga.open();
                        setTimeout(function(){ 
                            window.Vanga.refresh();
                            window.Vanga.refreshPromotion();
                        }, 1000);
                    }
                });
            },
            error:function(response){
                if(showGoodChoiceText){
                    $('#product-information-cart-button').removeClass('clicked');
                }
                else{
                    hideLoadingIndicator();
                }

                if(response && response.responseJSON && response.responseJSON.description){
                    alert(response.responseJSON.message + "\n\n" + response.responseJSON.description);
                }
                else{
                    if(isGermanShop()){
                        alert('Es ist ein Fehler aufgetreten. Bitte versuches es noch einmal.');
                    }
                    else{
                        alert('An error has occurred. Please try again.');
                    }
                }
            }
        };

        if($('.product-set-discounts').length == 0 && $('.product-file-input').length > 0){
            ajaxData.data = new FormData(this);
            ajaxData.processData = false;
            ajaxData.contentType = false;
        }

        $.ajax(ajaxData);
    });

    // Scroll to form button.
    $(containerId + '.product-information-scroll-to-form').click(productScrollToCartButton);

    // Sticky add to cart button.
    if($('#sticky-add-to-cart').length > 0){
        // Handle position
        if($('#sticky-add-to-cart').attr('data-position') == "top"){
            var top = 0;

            if(
                $('#shopify-section-header-menu').css('--header-position').includes('fixed') && 
                window.screen.width > 767
            ){
                top = $('#header').outerHeight();
            }

            $('#sticky-add-to-cart').css({
                bottom: 'initial',
                top: top
            });
        }

        // Handle scroll.
        setTimeout(function(){
            var scrollTopCartButton = 0;

            if($('#product-information-cart-button').length > 0){
                scrollTopCartButton = $('#product-information-cart-button').offset().top;
            }

            if($('#sticky-add-to-cart').attr('data-show-type') == "percentage"){
                scrollTopCartButton = document.documentElement.scrollHeight * (parseInt($('#sticky-add-to-cart').attr('data-show-type-percentage')) / 100);   
            }

            $(window).scroll(function(){
                if($(this).scrollTop() > scrollTopCartButton){
                    $('#sticky-add-to-cart').show();
                }
                else{
                    $('#sticky-add-to-cart').hide();
                }
            });
        }, 100);

        // Handle selection / inventory.
        $('#sticky-add-to-cart select').change(function(){
            var options = [];
            $('#sticky-add-to-cart select').each(function(){
                options.push({
                    key: 'option' + (cr_product.options.indexOf($(this).attr('name')) + 1),
                    value: $(this).val()
                });
            });

            var variant = window.cr_product.variants.find(function(variant) {
                return options.every(function(values) {
                    return variant[values.key] === values.value;
                });
            });

            if(!variant){
                return;
            }

            // Handle sold out.
            if(window.cr_variantStock.hasOwnProperty(variant.id) && window.cr_variantStock[variant.id] == 0){
                $('#sticky-add-to-cart .btn').attr('disabled', true);
            }
            else{
                $('#sticky-add-to-cart .btn').removeAttr('disabled');
            }
        });

        // Setup click
        $('#sticky-add-to-cart form').submit(function(event){
            event.preventDefault();
    
            if($('#sticky-add-to-cart .btn').attr('disabled')){
                return;
            }

            var options = [];
            $('#sticky-add-to-cart select').each(function(){
                options.push({
                    key: 'option' + (cr_product.options.indexOf($(this).attr('name')) + 1),
                    value: $(this).val()
                });
            });

            var variant = window.cr_product.variants.find(function(variant) {
                return options.every(function(values) {
                    return variant[values.key] === values.value;
                });
            });

            if(variant){
                $(this).find('input[name="id"]').val(variant.id);
            }
    
            showLoadingIndicator();
    
            $.ajax({
                type: 'POST', 
                url: getShopifyApiRoot() + 'cart/add.js',
                dataType: 'json', 
                data: $(this).serialize(),
                success: function(){
                    reloadCart(function(){
                        openCartDrawer();
                        hideLoadingIndicator();
                    });
                },
                error:function(response){
                    hideLoadingIndicator();
    
                    if(response && response.responseJSON && response.responseJSON.description){
                        alert(response.responseJSON.message + "\n\n" + response.responseJSON.description);
                    }
                    else{
                        if(isGermanShop()){
                            alert('Es ist ein Fehler aufgetreten. Bitte versuches es noch einmal.');
                        }
                        else{
                            alert('An error has occurred. Please try again.');
                        }
                    }
                }
            });
        });
    }

    // Volume discount.
    $('.product-set-discounts-entry').click(function(e){
        if($(this).hasClass('selected')){
            return;
        }

        $('.product-set-discounts-entry').removeClass('selected');
        $(this).addClass('selected');
    });
    $('.product-set-discounts-entry').eq($('.product-set-discounts').data('pre-selected-set-discounts')).click();

    // Set / volume discount.
    if($('.product-set-discounts').length > 0){
        $('.product-set-discounts-entry-content-product-body-select select').change(function(){
            var options = [];
            $(this).parent().find('select').each(function(){
                options.push({
                    key: 'option' + (cr_product.options.indexOf($(this).attr('name')) + 1),
                    value: $(this).val()
                });
            });

            var variant = cr_product.variants.find(function(variant) {
                return options.every(function(values) {
                    return variant[values.key] === values.value;
                });
            });

            if(!variant){
                return;
            }

            // Update image.
            if(variant.featured_image && variant.featured_image.src){
                $(this).parents('.product-set-discounts-entry-content-product').find('img').attr("src", variant.featured_image.src).removeAttr("data-srcset").removeAttr("srcset");
            }

            // Update price.
            var data = $(this).parents('.product-set-discounts-entry').data();
            var compareAtPrice = Math.trunc(variant.price * parseFloat(data.discount));

            if(data.discountProductPrice && data.discountProductPrice != '0'){
                compareAtPrice = data.discountProductPrice;
            }

            PriceFormatter.showPriceByElement($(this).parents('.product-set-discounts-entry-content-product-body').find('h4'), compareAtPrice, data.useComparePrice ? variant.compare_at_price : variant.price);

            // Update total.
            var total = 0;
            var totalCompare = 0;

            $(this).parents('.product-set-discounts-entry-content').find('span.price:not(.hide)').each(function(){
                totalCompare += parseInt($(this).find('span').attr('data-price'));
                total += parseInt($(this).find('s').attr('data-compare-price'));
            });

            PriceFormatter.showPriceByElement($(this).parents('.product-set-discounts-entry').find('.product-set-discounts-entry-header'), totalCompare, total);

            // Handle sold out.
            var $entryContainer = $(this).closest('.product-set-discounts-entry');
            var $contentBody = $(this).parents('.product-set-discounts-entry-content-product-body');
            var $outOfStockElement = $contentBody.find('.product-set-discounts-entry-content-product-body-out-of-stock');
            
            if(
                cr_variantStock.hasOwnProperty(variant.id) && 
                cr_variantStock[variant.id] == 0
            ){
                $outOfStockElement.css('display', 'flex');
                
                // Update soldout state
                $entryContainer.attr('data-soldout', 'true');
                
                // Disable cart button
                $('#product-information-cart-button').attr('disabled', true);
                var disabledText = $('#product-information-cart-button').attr('data-text-disabled');
                $('#product-information-cart-button').text(disabledText);
            }
            else{
                $outOfStockElement.css('display', 'none');

                var displays = [];
                $(this).parents('.product-set-discounts-entry-content').find('.product-set-discounts-entry-content-product-body-out-of-stock').each(function(){
                    displays.push($(this).css('display'));
                });

                if(!displays.includes('flex')){
                    $entryContainer.attr('data-soldout', 'false');
                    
                    // Only enable cart button if this is the currently selected discount entry
                    if ($entryContainer.hasClass('active')) {
                        $('#product-information-cart-button').removeAttr('disabled');
                        var normalText = $('#product-information-cart-button').attr('data-text-normal');
                        $('#product-information-cart-button').text(normalText);
                    }
                } else {
                    $entryContainer.attr('data-soldout', 'true');
                }
            }
        });

        $('.product-set-discounts-entry select').change();
        
        var $firstDiscountEntry = $('.product-set-discounts-entry:first');
        $firstDiscountEntry.addClass('active');
        $firstDiscountEntry.find('.product-set-discounts-entry-content-product-body-select select').trigger('change');
        setTimeout(function() {
            if ($('#product-information-cart-button').is(':disabled')) {
                $('.product-information-quantity').css('opacity', '0.4');
                $('.product-information-quantity button').addClass('disabled');
            } else {
                $('.product-information-quantity button').removeClass('disabled');
            }
        }, 0);
        
        setTimeout(function() {
            var hasSoldOut = false;
            $firstDiscountEntry.find('.product-set-discounts-entry-content-product-body-out-of-stock').each(function() {
                if ($(this).css('display') === 'flex') {
                    hasSoldOut = true;
                    return false;
                }
            });
            
            $firstDiscountEntry.attr('data-soldout', hasSoldOut ? 'true' : 'false');
            
            if (hasSoldOut) {
                $('#product-information-cart-button').attr('disabled', true);
                var disabledText = $('#product-information-cart-button').attr('data-text-disabled');
                $('#product-information-cart-button').text(disabledText);
            }
        }, 100);
        
        $('.product-set-discounts-entry').on('click', function() {
            var $discountEntry = $(this);
            
            $('.product-set-discounts-entry').removeClass('active');
            $discountEntry.addClass('active');
            
            if ($discountEntry.attr('data-soldout') === 'true') {
                $('#product-information-cart-button').attr('disabled', true);
                var disabledText = $('#product-information-cart-button').attr('data-text-disabled');
                $('#product-information-cart-button').text(disabledText);
            } else {
                $('#product-information-cart-button').removeAttr('disabled');
                var normalText = $('#product-information-cart-button').attr('data-text-normal');
                $('#product-information-cart-button').text(normalText);
            }
        });
    }

    // Select field.
    $('.product-select-options span').click(function(){
        $(this).parent().find('span').removeClass('selected');
        $(this).addClass('selected');

        $(this).parents('.product-select').find('select').val($(this).text());
        $(this).parents('.product-select').find('label span:eq(1)').text($(this).text());
    });

    $('.product-select-options span:first-child').click();

    $('.product-select.button_box label').click(function(){
        var options = $(this).parent().find('.product-select-options');

        if(options.css('display') == 'flex'){
            options.css('display', 'none');
            $(this).find('svg').css('rotate', '0deg');
        }
        else{
            options.css('display', 'flex');
            $(this).find('svg').css('rotate', '90deg');
        }        
    });

    // Desktop images scrolling.
    if($(document).width() > 768 && $('.product-media').length > 0 && $(containerId + '.product-media-main').attr('data-desktop-media-fixed') == 'true'){
        var productDataHeight = $('#product-add-to-cart-form').height();
        var productMedia = $('.product-media');
        var productMediaOffsetTop = productMedia[0].offsetTop;
        var productMediaHeight = productMedia.height();

        $(window).scroll(function(){
            var diff = Math.min($(window).scrollTop() - productMediaOffsetTop, productDataHeight - productMediaHeight);

            if(diff > 0){
                productMedia.css('margin-top', diff + 'px');
            }
            else{
                productMedia.css('margin-top', '0px');
            }
        });
    }

    // Page button.
    $('.product-page-button').click(function(){
        var url = $(this).attr('data-page-url').trim();
        if(url){
            var popup = $('.product-page-button-popup');
            popup.find('iframe').remove();
            popup.append('<iframe src="' + url + '"></iframe>');

            $('.product-page-button-overlay').show();
        }
    });

    $('.product-page-button-overlay, .product-page-button-overlay svg').click(function(){
        $('.product-page-button-overlay').hide();
    });

    // Collapsible Content.
    if($('.product-collapsible-content').attr('data-desktop') == 'true'){
        if($.trim($('.product-media-collapsible-content-desktop-container').html()) == ''){
            $('.product-collapsible-content').clone().appendTo('.product-media-collapsible-content-desktop-container');
        }

        $('.product-media-collapsible-content-desktop-container .product-collapsible-content').removeClass('product-collapsible-content-move-on-desktop');
        $('.product-media-collapsible-content-desktop-container .product-collapsible-content').removeAttr('style');
    }

    $('.product-collapsible-content-entry-header').click(function(){
        if($(this).parent().hasClass('active')){
            $(this).parent().removeClass('active');
        }
        else{
            $(this).parent().addClass('active');
        }
    });

    // Handle conrise reviews click.
    if($('.product-reviews-dummy-stars').length > 0 && $('#conrise-reviews').length > 0){
        $('.product-reviews-dummy-stars, .product-reviews-dummy span').css('cursor', 'pointer');
        $('.product-reviews-dummy-stars, .product-reviews-dummy span').click(function(){
            $('html, body').animate({
                scrollTop: $('#conrise-reviews').offset().top - 100
            }, 500);
        });
    }

    // Move blocks on mobile above media.
    $('.product-above-media').empty(); 
    $('.product-information .product-move-above-media').clone().appendTo('.product-above-media');
    $('.product-above-media .product-reviews-dummy-stars:not(.for-above-media)').remove();

    // Countdown offer.
    if ($('.product-countdown-offer-timer').length > 0) {
        clearInterval(countdownTimer);
        var targetTimestamp = parseInt($('.product-countdown-offer-timer').attr('data-target-timestamp')) * 1000;
        var endOfOffer = targetTimestamp ? new Date(targetTimestamp) : new Date();

        if(!targetTimestamp){
            endOfOffer.setHours(23);
            endOfOffer.setMinutes(59);
            endOfOffer.setSeconds(59);
        }

    
        var timerFunction = function () {
            if(targetTimestamp){
                var now = new Date();
                var remaining = endOfOffer.getTime() - now.getTime();
                if (remaining <= 0) {
                    $('.product-countdown-offer').hide();
                    clearInterval(countdownTimer);
                    return;
                }
        
                var days = Math.floor(remaining / (1000 * 60 * 60 * 24));
                var hours = Math.floor((remaining / (1000 * 60 * 60)) % 24);
                var minutes = Math.floor((remaining / (1000 * 60)) % 60);
                var seconds = Math.floor((remaining / 1000) % 60);
        
                if (days < 1) {
                    $('.product-countdown-offer-timer-days').hide();
                    $('.divider-days').hide();
                } else {
                    $('.product-countdown-offer-timer-days').show();
                    $('.product-countdown-offer-timer-days div').html(days); // Sıfır eklemeden yaz
                }
                $('.product-countdown-offer-timer-hours div').html(hours.toString().padStart(2, '0'));
                $('.product-countdown-offer-timer-minutes div').html(minutes.toString().padStart(2, '0'));
                $('.product-countdown-offer-timer-seconds div').html(seconds.toString().padStart(2, '0'));
            }else{
                var remaining = new Date();

                if(endOfOffer.getTime() < remaining.getTime()){
                    endOfOffer = new Date();
                    endOfOffer.setHours(23);
                    endOfOffer.setMinutes(59);
                    endOfOffer.setSeconds(59);
                }

                remaining.setHours(endOfOffer.getHours() - remaining.getHours());
                remaining.setMinutes(endOfOffer.getMinutes() - remaining.getMinutes());
                remaining.setSeconds(endOfOffer.getSeconds() - remaining.getSeconds());

                $('.product-countdown-offer-timer-days').hide();
                $('.divider-days').hide();
                $('.product-countdown-offer-timer-hours div').html(remaining.getHours().toString().padStart(2, '0'));
                $('.product-countdown-offer-timer-minutes div').html(remaining.getMinutes().toString().padStart(2, '0'));
                $('.product-countdown-offer-timer-seconds div').html(remaining.getSeconds().toString().padStart(2, '0'));
            }
        };
    
        countdownTimer = setInterval(timerFunction, 1000);
        timerFunction();
    }

    //Collapsible media container.
    var $container = $('.product-media-grid.desktop');
    var containerAttribute = $container.attr('collapsible');
    if($container.length > 0 && containerAttribute == 'true'){
        dropdownElement($container);
    }

    // Check if selected variants in product-set-discounts-entry are soldout when clicked
    $('.product-set-discounts-entry').click(function() {
        var $discountEntry = $(this);
        var $entryContent = $discountEntry.find('.product-set-discounts-entry-content');
        var hasSoldOutVariants = false;
        
        $entryContent.find('.product-set-discounts-entry-content-product-body-out-of-stock').each(function() {
            if ($(this).css('display') === 'flex') {
                hasSoldOutVariants = true;
                return false;
            }
        });
        
        if (hasSoldOutVariants) {
            $('#product-information-cart-button').attr('disabled', true);
            var disabledText = $('#product-information-cart-button').attr('data-text-disabled');
            $('#product-information-cart-button').text(disabledText);
        } else {
            $('#product-information-cart-button').removeAttr('disabled');
            var normalText = $('#product-information-cart-button').attr('data-text-normal');
            $('#product-information-cart-button').text(normalText);
        }
    });

}

function productScrollToCartButton(){
    var scrollTop = 0;

    if($('#product-information-cart-button').length > 0){
        scrollTop = $('#product-information-cart-button').offset().top - (window.screen.height / 2);
    }

    $('html, body').animate({
        scrollTop: scrollTop
    }, 500);
}

function setupSelectedVariant(isInitExecution){
    var options = [];
    $('.product-variant-select').each(function(){
        options.push({
            key: 'option' + (cr_product.options.indexOf($(this).attr('name')) + 1),
            value: $(this).val()
        });
    });

    $('.product-information-variant-picker-button-variant-option').removeClass('product-information-variant-picker-button-variant-option-checked');
    $('.product-variant-radio:checked').each(function(){
        $(this).parent().addClass('product-information-variant-picker-button-variant-option-checked');

        var span = $(this).parents('.product-information-variant-picker-button-variant').find('label span:eq(1)');
        if(span.attr('data-color-swatch') == "true"){
            span.html($(this).val() + '<span class="color-swatch" style="background-color: ' + $(this).next().css('background-color') + ';"></span>');
        }
        else{
            span.html($(this).val());
        }

        options.push({
            key: 'option' + (cr_product.options.indexOf($(this).attr('name')) + 1),
            value: $(this).val()
        });
    });

    var selectedVariant = cr_product.variants.find(function(variant) {
        return options.every(function(values) {
            return variant[values.key] === values.value;
        });
    });

    const url = new URL(window.location);
    if(selectedVariant){
        url.searchParams.set('variant', selectedVariant.id);
    }
    else{
        url.searchParams.delete('variant');
    }
    window.history.replaceState({}, '', url);

    if(selectedVariant){
        $(`.${cr_product.id}-product-sku`).text(selectedVariant.sku);

        if($('.product-stock-alarm').length > 0 && cr_variantStock.hasOwnProperty(selectedVariant.id)){
            var stockElement = $('.product-stock-alarm')[0];
            var text = stockElement.dataset.text;
            var minStock = parseInt(stockElement.dataset.minStock);
            var stock = parseInt(cr_variantStock[selectedVariant.id]);
            
            if(stock <= minStock){
                $('.product-stock-alarm').css('display', 'block');
                stockElement.innerHTML = text.replace('[stock]', stock);
            }
            else{
                $('.product-stock-alarm').css('display', 'none');    
            }
        }
        else{
            $('.product-stock-alarm').css('display', 'none');
        }
    }
    
    if(!selectedVariant){
        var firstValue = options.find(option => option.key == 'option1').value;
        
        for (var i = 0; i < cr_product.variants.length; i++) {
            if(cr_product.variants[i].option1 == firstValue){
                selectedVariant = cr_product.variants[i];
                break;
            }
        }

        // Trigger click on second and third option.
        var fieldOption2 = $('.product-information-variant-picker-button-variant:eq(1) .product-information-variant-picker-button-variant-option[data-option="' + selectedVariant.option2 + '"]');
        var fieldOption3 = $('.product-information-variant-picker-button-variant:eq(2) .product-information-variant-picker-button-variant-option[data-option="' + selectedVariant.option3 + '"]');
        if(fieldOption2.length > 0){
            var radio = fieldOption2.find('.product-variant-radio');
            $('.product-variant-radio[name="' + radio.attr('name') + '"]').removeAttr('checked');
            radio.attr('checked', true);
        }
        if(fieldOption3.length > 0){
            var radio = fieldOption3.find('.product-variant-radio');
            $('.product-variant-radio[name="' + radio.attr('name') + '"]').removeAttr('checked');
            radio.attr('checked', true);
        }

        $('.product-variant-select:eq(1)').val(selectedVariant.option2);
        $('.product-variant-select:eq(2)').val(selectedVariant.option3);

        if(
            fieldOption2.length > 0 || fieldOption3.length > 0 || 
            $('.product-variant-select:eq(1)').length > 0 || $('.product-variant-select:eq(2)').length > 0
        ){
            setupSelectedVariant();
        }
    }
    
    // Variant Options 2.
    var selectedVariantOptions2 = [];
    cr_product.variants.forEach(function(variant){
        if(variant.option1 == selectedVariant.option1){
            selectedVariantOptions2.push(variant.option2);
        }
    });
    
    $('.product-information-variant-picker-button-variant:eq(1) .product-information-variant-picker-button-variant-option').each(function(index, div){
        if(selectedVariantOptions2.includes($(div).attr('data-option'))){
            $(div).removeClass('hide');
        }
        else{
            $(div).addClass('hide');
        }
    });
    $('.product-variant-select:eq(1) option').each(function(index, option){
        option.hidden = !selectedVariantOptions2.includes($(option).attr('value'));
    });
    
    // Variant Options 3.
    var selectedVariantOptions3 = [];
    cr_product.variants.forEach(function(variant){
        if(variant.option1 == selectedVariant.option1){
            selectedVariantOptions3.push(variant.option3);
        }
    });
    
    $('.product-information-variant-picker-button-variant:eq(2) .product-information-variant-picker-button-variant-option').each(function(index, div){
        if(selectedVariantOptions3.includes($(div).attr('data-option'))){
            $(div).removeClass('hide');
        }
        else{
            $(div).addClass('hide');
        }
    });
    $('.product-variant-select:eq(2) option').each(function(index, option){
        option.hidden = !selectedVariantOptions3.includes($(option).attr('value'));
    });

    // Disabled atc button when variant not exists.
    if(!selectedVariant){
        $('#product-information-cart-button').attr('disabled', true);
        $('.product-information-quantity').css('opacity', '0.4');
        $('#product-information-cart-button span').text($('#product-information-cart-button').attr('data-text-disabled'));

        return;
    }

    $('#product-add-to-cart-form input[name="id"]').val(selectedVariant.id);

    // Handle inventory.
    $('#product-information-cart-button').removeAttr('disabled');
    $('.product-information-quantity').css('opacity', '1');
    $('#product-information-cart-button span').text($('#product-information-cart-button').attr('data-text-normal'));

    if(cr_variantStock.hasOwnProperty(selectedVariant.id)){
        $('.product-information-quantity button[name="plus"]').attr('data-stock', cr_variantStock[selectedVariant.id]);

        var input = $('.product-information-quantity-field');
        var value = parseInt(input.val());
        if(value > cr_variantStock[selectedVariant.id]){
            value = cr_variantStock[selectedVariant.id];
        }
        else if(value == 0 && cr_variantStock[selectedVariant.id] > 0){
            value = 1;
        }
        input.val(value);

        $('.product-information-quantity').each(function(){
            $(this).find('.product-information-quantity-input').text(value);
    
            if(value < 2){
                $(this).find('button[name="minus"] svg path').css('stroke', 'var(--color-border)');
            }
            else{
                $(this).find('button[name="minus"] svg path').css('stroke', 'var(--color-text)');
            }

            // Disable button.
            if(value == 0){
                $('#product-information-cart-button').attr('disabled', true);
                $('.product-information-quantity').css('opacity', '0.4');
                $('#product-information-cart-button span').text($('#product-information-cart-button').attr('data-text-disabled'));
            }
        });

        // Disable button.
        if($('.product-information-quantity').length == 0 && value == 0){
            $('#product-information-cart-button').attr('disabled', true);
            $('.product-information-quantity').css('opacity', '0.4');
            $('#product-information-cart-button span').text($('#product-information-cart-button').attr('data-text-disabled'));
        }
    }
    else{
        $('.product-information-quantity button[name="plus"]').removeAttr('data-stock');

        $('.product-information-quantity').each(function(){
            var input = $('.product-information-quantity-field');
            var value = parseInt(input.val());
            if(value != 0){
                return;
            }

            value = 1;
    
            $('.product-information-quantity-input').text(value);
            input.val(value);
    
            $('button[name="minus"] svg path').css('stroke', 'var(--color-border)');
        });
    }

    // Show weight.
    if($('.product-weight').length > 0 && cr_productWeight && cr_productWeight[selectedVariant.id]){
        $('.product-weight-value').html(cr_productWeight[selectedVariant.id]);
    }

    // Show price.
    PriceFormatter.showPrice('.product-information-price', selectedVariant.price, selectedVariant.compare_at_price);

    if(!isInitExecution && selectedVariant.featured_media && selectedVariant.featured_media.position && $('.variant-picker').data('selectVariantImage')){
        window.mainSwiper.slideTo(selectedVariant.featured_media.position - 1);
    }

    // Show unit price.
    if($('.product-information-unit-price').length > 0){
        if(selectedVariant.unit_price_measurement){
            $('.product-information-unit-price').show();

            PriceFormatter.showPrice('.product-information-unit-price-price', selectedVariant.unit_price);
            $('.product-information-unit-price-unit').text(selectedVariant.unit_price_measurement.reference_value + '' + selectedVariant.unit_price_measurement.reference_unit);
        }
        else{
            $('.product-information-unit-price').hide();
        }
    }

    // Handle price discount badge.
    if($('.product-information-price-saved').length == 0){
        return;
    }

    if(selectedVariant.compare_at_price > selectedVariant.price){
        $('.product-information-price-saved').show();
    }
    else{
        $('.product-information-price-saved').hide();
    }

    if($('.product-information-price-saved').attr('data-type') == 'percentage'){
        var value = (selectedVariant.compare_at_price - selectedVariant.price) * 100 / selectedVariant.compare_at_price;
        $('.product-information-price-saved span').html(Math.ceil(value) + '%');
    }
    else{
        PriceFormatter.showPrice('.product-information-price-saved span', selectedVariant.compare_at_price - selectedVariant.price);
    }
}

function dropdownElement($container){
    if ($container.children().length > 2) { 
        var firstHeight = $container.children().eq(0).outerHeight(); 
        var secondHeight = $container.children().eq(1).outerHeight(); 

        $container.css('max-height', firstHeight + secondHeight);
        $container.css('overflow', 'hidden');
    

        $('.btn.show-toggle-btn').on('click', function(){
            var $this = $(this);
            var showMoreText = $this.find("span").attr('text-show-more');
            var showLessText = $this.find("span").attr('text-show-less');

            if ($this.hasClass('toggle-active')) {
                $this.removeClass('toggle-active');
                $container.css('max-height', firstHeight + secondHeight);
                $this.find("span").text(showMoreText);
                $this.find("svg").css('transform', 'rotate(180deg)');
            } else {
                $this.addClass('toggle-active');
                $container.css('max-height', '100%');
                $this.find("span").text(showLessText);
                $this.find("svg").css('transform', 'rotate(0deg)');
            }
        });
    }
}

/* ==================================== */
/* =============== CART =============== */
/* ==================================== */

function initUpsellSlider(){
    // drawer cart upsell slider.
    var cartUpsellingSliderSize = $('.cart__upselling-slider').data('list-size');
    new Swiper(".cart__upselling-slider",{
        breakpoints: {
            100: {
                slidesPerView: 1.8,
                spaceBetween: 10
            },
            768: {
                slidesPerView: 2.3,
                spaceBetween: 10
            }
        }
    });
}

function initCart(){
    // Change line item.
    $('.cart-drawer-content').on('click', '.cart-drawer-item-quantity-minus', function(){
        var lineIndex = $(this).attr('data-line-index');
        var input = $('#cart-drawer-item-quantity-input-' + lineIndex);
        input.val(parseInt(input.val()) - 1);

        updateCartItemQuantity(lineIndex, input.val());
    });
    $('.cart-drawer-content').on('click', '.cart-drawer-item-quantity-plus', function(){
        var lineIndex = $(this).attr('data-line-index');
        var input = $('#cart-drawer-item-quantity-input-' + lineIndex);
        var value = parseInt(input.val()) + 1;

        if($(this)[0].hasAttribute('data-stock') && value > parseInt($(this).attr('data-stock'))){
            return;
        }

        input.val(value);

        updateCartItemQuantity(lineIndex, input.val());
    });
    $('.cart-drawer-content').on('click', '.cart-drawer-item-remove', function(){
        var trigger_product_on_remove = $(this).closest(".cart-drawer-item-data").attr("trigger-product-cart");
        updateCartItemQuantity($(this).attr('data-line-index'), 0, trigger_product_on_remove);
    });

    // Close cart.
    $('.cart-drawer-header-close-icon').click(closeCartDrawer);  

    // Cart auto add product reward
    if($('.cart-auto-add-product-reward').length > 0){
        var reward_element = $('.cart-auto-add-product-reward');
        var reward_product = reward_element.attr('data-reward-product-id');
        var cart_amount = Number(reward_element.attr('data-cart-amount'));
        var reward_cost = Number(reward_element.attr('data-reward-cost'));
        var cart_items = reward_element.data('cart-items');
        var remove_reward_product = reward_element.attr('data-remove-product-automatically');
        var is_reward_product_in_cart = cart_items.some(item => item.id == reward_product);
        var is_cart_amount_more_than_reward_cost = cart_amount > reward_cost;

        if(is_reward_product_in_cart && !is_cart_amount_more_than_reward_cost && remove_reward_product == 'true'){
            // remove reward product from cart with index
            var index_of_reward_product = cart_items.findIndex((item) => item.id == reward_product) + 1;            
            updateCartItemQuantity(index_of_reward_product, 0);
        } else if(!is_reward_product_in_cart && is_cart_amount_more_than_reward_cost){
            // add reward product to cart
            showLoadingIndicator();
            var data_reward_product = {
                id: reward_product,
                quantity: 1
            }
            data_reward_product.form_type = 'product';
            $.ajax({
                type: 'POST', 
                url: getShopifyApiRoot() + 'cart/add.js',
                dataType: 'json', 
                data: data_reward_product,
                success: function(){
                    reloadCart(function(){
                        $('.cart-drawer-content').addClass('no-transition');
                        openCartDrawer();
                        setTimeout(function(){
                            $('.cart-drawer-content').removeClass('no-transition');
                        }, 400);
        
                        hideLoadingIndicator();
                    });
                },
                error:function(response){
                    hideLoadingIndicator();
    
                    if(response && response.responseJSON && response.responseJSON.description){
                        alert(response.responseJSON.message + "\n\n" + response.responseJSON.description);
                    }
                    else{
                        if(isGermanShop()){
                            alert('Es ist ein Fehler aufgetreten. Bitte versuches es noch einmal.');
                        }
                        else{
                            alert('An error has occurred. Please try again.');
                        }
                    }
                }
            });
        }

        
    }

    // Cart upselling.
    $('.cart-drawer-content').on('change', '.cart-upselling-item-variants-select', cartUpsellVariantSelection);
    /* cartUpsellVariantSelection(); */

    $(".cart-upselling-form-class").submit(function(event){
        event.preventDefault();

        if($('#cart-upselling button').attr('disabled')){
            return;
        }

        showLoadingIndicator();

        $.ajax({
            type: 'POST', 
            url: getShopifyApiRoot() + 'cart/add.js',
            dataType: 'json', 
            data: $(this).serialize(),
            success: function(){
                reloadCart(function(){
                    $('.cart-drawer-content').addClass('no-transition');
                    openCartDrawer();
                    setTimeout(function(){
                        $('.cart-drawer-content').removeClass('no-transition');
                    }, 400);

                    hideLoadingIndicator();
                });
            },
            error:function(response){
                hideLoadingIndicator();

                if(response && response.responseJSON && response.responseJSON.description){
                    alert(response.responseJSON.message + "\n\n" + response.responseJSON.description);
                }
                else{
                    if(isGermanShop()){
                        alert('Es ist ein Fehler aufgetreten. Bitte versuches es noch einmal.');
                    }
                    else{
                        alert('An error has occurred. Please try again.');
                    }
                }
            }
        });
    });

    // Cart discount.
    $('.cart-drawer-footer-discount-input button').click(function(){
        var discountCode = $('.cart-drawer-footer-discount-input input').val().trim();

        if(!discountCode){
            return;
        }

        showLoadingIndicator();

        $.ajax({
            type: 'GET', 
            url: getShopifyApiRoot() + 'discount/' + discountCode,
            success: function(){
                $.ajax({
                    type: 'POST', 
                    url: getShopifyApiRoot() + 'cart/update.js',
                    dataType: 'json', 
                    data: {"updates": {}},
                    success: function(){
                        reloadCart(function(){
                            $('.cart-drawer-content').addClass('no-transition');
                            openCartDrawer();
                            setTimeout(function(){
                                $('.cart-drawer-content').removeClass('no-transition');
                            }, 400);
        
                            hideLoadingIndicator();
                        });
                    },
                    error:function(){
                        $('.cart-drawer-footer-discount-input-failure').show();
                        hideLoadingIndicator();
                    }
                });
            },
            error:function(){
                $('.cart-drawer-footer-discount-input-failure').show();
                hideLoadingIndicator();
            }
        });
    });

    // Note.
    if($('.cart-drawer-footer-note-input').length > 0){
        $('.cart-drawer-footer-note-input input').on('keyup', function(){
            $.ajax({
                type: 'POST', 
                url: getShopifyApiRoot() + 'cart/update.js',
                dataType: 'json', 
                data: {"note": $(this).val()},
                success: function(){},
                error:function(){}
            });
        });
    }

    initUpsellSlider();
}

function cartUpsellVariantSelection(){
    var mainProductId = $(this).attr('main-product-id');
    var upsellProductVariant = window.cr_upsell_product_variants[mainProductId];
    var idInputInForm = $(this).closest('form').find('input[name="id"]');
    if(window.cr_upsell_product_variants.length == 0){
        return;
    }

    var options = [];
    $(`.cart-upselling-item-variants-select[main-product-id="${mainProductId}"]`).map(function(selectItem){
        options.push($(this).val());
    });

    function getIdByOptions(option1, option2 = null, option3 = null) {
        const item = upsellProductVariant.find(d => 
            d.option1 === option1 && 
            d.option2 === option2 && 
            (d.option3 === option3 || d.option3 === null && option3 === undefined)
        );
        return item ? item.id : null;
    }

    var variantId = getIdByOptions(options[0], options[1], options[2]);
    idInputInForm.val(variantId);

    let parent = ""
    if($(this).closest(".cart-upselling-form-slider").length > 0){
        parent = $(this).closest(".cart-upselling-form-slider");
    } else {
        parent = $(this).closest(".cart-upselling-form");
    }

    var optionsUpsell = [];
    var product = window['cr_product_upsell_' + mainProductId];
    parent.find('select').each(function(){
        optionsUpsell.push({
            key: 'option' + (product.options.indexOf($(this).attr('name')) + 1),
            value: $(this).val()
        });
    });
    var selectedVariant = product.variants.find(function(variant) {
        return optionsUpsell.every(function(values) {
            return variant[values.key] === values.value;
        });
    });
    
    if(selectedVariant){
        PriceFormatter.showPriceByElement(parent, selectedVariant.price, selectedVariant.compare_at_price);
        
        // Update button text based on availability
        const button = parent.find('button[type="submit"]');
        if (button.length) {
            if (selectedVariant.available) {
                button.prop('disabled', false);
                button.text(button.attr('data-text-normal'));
            } else {
                button.prop('disabled', true);
                button.text(button.attr('data-text-disabled'));
            }
        }
        
        // change image
        var imageContainer;
        if(parent.closest('.swiper-slide').length > 0) {
            imageContainer = parent.closest('.swiper-slide').find('.cart-upselling-item-slider-image[data-product-id="' + mainProductId + '"]');
        } else {
            imageContainer = $('.cart-upselling-item-image[data-product-id="' + mainProductId + '"]');
        }
        
        if(imageContainer.length > 0) {
            var img = imageContainer.find('img');
            if(selectedVariant.featured_image && selectedVariant.featured_image.src) {
                img.attr("src", selectedVariant.featured_image.src);
                
                var dataSrc = selectedVariant.featured_image.src;
                if (dataSrc.indexOf('?') !== -1) {
                    dataSrc = dataSrc.split('?')[0];
                }
                
                if (dataSrc.indexOf('.jpg') !== -1) {
                    dataSrc = dataSrc.replace('.jpg', '_{width}x.jpg');
                } else if (dataSrc.indexOf('.jpeg') !== -1) {
                    dataSrc = dataSrc.replace('.jpeg', '_{width}x.jpeg');
                } else if (dataSrc.indexOf('.png') !== -1) {
                    dataSrc = dataSrc.replace('.png', '_{width}x.png');
                } else if (dataSrc.indexOf('.webp') !== -1) {
                    dataSrc = dataSrc.replace('.webp', '_{width}x.webp');
                } else {
                    dataSrc = dataSrc + '_{width}x';
                }
                
                img.attr("data-src", dataSrc)
                   .removeAttr("data-srcset")
                   .removeAttr("srcset");
            } else if (product.media && product.media.length > 0) {
                var firstProductImage = product.media[0];
                if (firstProductImage && firstProductImage.src) {
                    img.attr("src", firstProductImage.src);
                    
                    var productDataSrc = firstProductImage.src;
                    if (productDataSrc.indexOf('?') !== -1) {
                        productDataSrc = productDataSrc.split('?')[0];
                    }
                    
                    if (productDataSrc.indexOf('.jpg') !== -1) {
                        productDataSrc = productDataSrc.replace('.jpg', '_{width}x.jpg');
                    } else if (productDataSrc.indexOf('.jpeg') !== -1) {
                        productDataSrc = productDataSrc.replace('.jpeg', '_{width}x.jpeg');
                    } else if (productDataSrc.indexOf('.png') !== -1) {
                        productDataSrc = productDataSrc.replace('.png', '_{width}x.png');
                    } else if (productDataSrc.indexOf('.webp') !== -1) {
                        productDataSrc = productDataSrc.replace('.webp', '_{width}x.webp');
                    } else {
                        productDataSrc = productDataSrc + '_{width}x';
                    }
                    
                    img.attr("data-src", productDataSrc)
                       .removeAttr("data-srcset")
                       .removeAttr("srcset");
                }
            }
        }
    }
}

async function updateCartItemQuantity(line, quantity, trigger_on_cart = null){
    showLoadingIndicator();

    var autoProductUpdate = $('.add-product-automatically');
    if(autoProductUpdate.length > 0){
        var trigger = autoProductUpdate.attr('trigger-product');
        var delete_auto_from_cart = autoProductUpdate.attr('delete-auto');
        if(trigger_on_cart == trigger && delete_auto_from_cart == 'true'){
            var toBeAdded = autoProductUpdate.attr('to-be-added');
            var addedProductLine = $(`.cart-drawer-item-data[added-product-cart="${toBeAdded}"]`).find('.cart-drawer-item-remove').attr('data-line-index');
            if(addedProductLine){
                await $.ajax({
                    type: 'POST', 
                    url: getShopifyApiRoot() + 'cart/change',
                    dataType: 'json', 
                    data: {
                        line: addedProductLine,
                        quantity: quantity
                    }
                })
            }
        }
    }

    await $.ajax({
        type: 'POST', 
        url: getShopifyApiRoot() + 'cart/change',
        dataType: 'json', 
        data: {
            line: line,
            quantity: quantity
        },
        success: function(){
            reloadCart(function(){
                $('.cart-drawer-content').addClass('no-transition');
                openCartDrawer();
                setTimeout(function(){
                    $('.cart-drawer-content').removeClass('no-transition');
                }, 400);

                hideLoadingIndicator();
            });
        },
        error:function(){
            if(isGermanShop()){
                alert('Es ist ein Fehler aufgetreten. Bitte versuches es noch einmal.');
            }
            else{
                alert('An error has occurred. Please try again.');
            }
        }
    });
}

function reloadCart(callback){
    $.ajax({
        type: 'GET', 
        url: getShopifyApiRoot() + '?sections=cart-drawer', 
        success: function(data){
            if(data && data["cart-drawer"]){
                // Build cart.
                $('#shopify-section-cart-drawer').replaceWith(data["cart-drawer"]);

                if($('.template-cart').length > 0){
                    $('main .shopify-section').replaceWith(data["cart-drawer"]);
                }

                initCart();

                // Header.
                var totalQuantity = parseInt($('.cart-drawer-content').attr('data-item-count'));
                $('#header-cart-drawer-item-count').text(totalQuantity);
                
                if(parseInt(totalQuantity) > 0){
                    $('#header-cart-drawer-item-count').show();
                    $('#header-cart-drawer-item-count').removeClass('hide');
                }
                else{
                    $('#header-cart-drawer-item-count').hide();
                }

                // Callback.
                if(callback){
                    callback();
                }
            }
            else{
                if(isGermanShop()){
                    alert('Es ist ein Fehler aufgetreten. Bitte versuches es noch einmal.');
                }
                else{
                    alert('An error has occurred. Please try again.');
                }
            }
        },
        error:function(){
            if(isGermanShop()){
                alert('Es ist ein Fehler aufgetreten. Bitte versuches es noch einmal.');
            }
            else{
                alert('An error has occurred. Please try again.');
            }
        }
    });
}

/* ========================================== */
/* =============== COLLECTION =============== */
/* ========================================== */

function handleCollectionPage(){
    var currentPage = 1;
    var allowFetchPages = true;
    var isLoading = false;

    $(window).scroll(function(){
        if(!allowFetchPages || isLoading){
            return;
        }
        
        var scrollPosition = $(window).scrollTop() + window.screen.height * 1.3;
        var gridBottom = $('.collection-product-grid').offset().top + $('.collection-product-grid').height();

        if(scrollPosition < gridBottom){
            return;
        }

        currentPage++;
        isLoading = true;

        $('.collection-product-grid-loading').show();

        $.ajax({ 
            url: '?page=' + currentPage + '&' + window.location.search.substring(1),
            success: function(data){
                $('.collection-product-grid-loading').hide();
                isLoading = false;

                if(!data){
                    return;
                }

                var html = $(data);
                if(html.find('.collection-product-grid-cards .card-product').length > 0){
                    $('.collection-product-grid-cards').append(html.find('.collection-product-grid-cards').html());

                    setupCollectionPageForm();
                    return;
                }

                allowFetchPages = false;
            },
            error:function(){
                $('.collection-product-grid-loading').hide();
                isLoading = false;
            }
        });
    });

    setupCollectionPageForm();
    setupSelectedVariantProductCard();

    // Handle filter.
    $('.collection-product-grid-filter-header').click(function(){
        // Hide all other.
        $('.collection-product-grid-filter-content').each(function(){
            if($(this).css('display') == 'flex'){
                $(this).css('display', 'none');
                $(this).prev().find('svg').css('transform', ' rotate(90deg)');
            }
        });

        // Handle self.
        if($(this).next().css('display') == 'flex'){
            $(this).next().css('display', 'none');
            $(this).find('svg').css('transform', ' rotate(90deg)');
        }
        else{
            $(this).next().css('display', 'flex');
            $(this).find('svg').css('transform', ' rotate(270deg)');
        }
    });

    $('body').click(function(evt){
        if(!$(evt.target).is('.collection-product-grid-filter') && $(evt.target).parents('.collection-product-grid-filter').length == 0){
            $('.collection-product-grid-filter-content').each(function(){
                if($(this).css('display') == 'flex'){
                    $(this).css('display', 'none');
                    $(this).prev().find('svg').css('transform', ' rotate(90deg)');
                }
            });
        }
    });

    // Handle sort.
    $('.collection-product-grid-sort select').change(function(){
        $(this).parents('form').submit();
    });

    // Handle mobile fitler popup.
    $('.collection-product-grid-filterbar-mobile-button').click(openFilterPopup);
    $('#collection-filter-drawer-overlay, #collection-filter-drawer-content .collection-filter-drawer-header svg').click(closeFilterPopup);
}

// Collection product card
function setupSelectedVariantProductCard(){
    $('.product-card-variant-select').change(function(){
        let parent = $(this).closest(".card-product-content");
        var options = [];
        var product = window['cr_product_card_' + parent.find('input[name="productid"]').val()];
        var percentage_span = parent.find(".percentage")
        parent.find('select').each(function(){
            options.push({
                key: 'option' + (product.options.indexOf($(this).attr('name')) + 1),
                value: $(this).val()
            });
        });
        var selectedVariant = product.variants.find(function(variant) {
            return options.every(function(values) {
                return variant[values.key] === values.value;
            });
        });
        var variant_compare_at_price = selectedVariant.compare_at_price
        var variant_price = selectedVariant.price;
        var percentage_result = ((variant_compare_at_price - variant_price) * 100) / variant_compare_at_price
        var rounded_percentage = Math.round(percentage_result)
        if(selectedVariant){
            parent.find('input[name="id"]').val(selectedVariant.id);
            var priceContainer = parent.find('.card-product-price')
            PriceFormatter.showPriceByElement(priceContainer, selectedVariant.price, selectedVariant.compare_at_price);
            percentage_span.html(`${rounded_percentage}%`)
        }
    })
}
 

function setupCollectionPageForm(){
    $('.card-product-form form').off('submit');
    $('.card-product-form button[name="minus"]').off('click');
    $('.card-product-form button[name="plus"]').off('click');

    $('.card-product-form form').submit(function(event){
        event.preventDefault();

        showLoadingIndicator();

        // Handle variant.
        if($(this).find('select').length > 0){
            var options = [];
            var product = window['cr_product_' + $(this).find('input[name="productid"]').val()];
            $(this).find('select').each(function(){
                options.push({
                    key: 'option' + (product.options.indexOf($(this).attr('name')) + 1),
                    value: $(this).val()
                });
            });

            var selectedVariant = product.variants.find(function(variant) {
                return options.every(function(values) {
                    return variant[values.key] === values.value;
                });
            });

            if(selectedVariant){
                $(this).find('input[name="id"]').val(selectedVariant.id);
            }
        }

        // Do post.
        var cartType = $(this).find('button[type="submit"]').data().cartType;

        $.ajax({
            type: 'POST', 
            url: getShopifyApiRoot() + 'cart/add.js',
            dataType: 'json', 
            data: $(this).serialize(),
            success: function(){
                // Forward to cart page.
                if(cartType == 'page'){
                    hideLoadingIndicator();
                    window.location.href = "/cart";
                    return;
                }

                reloadCart(function(){
                    if(cartType == 'slider'){
                        openCartDrawer();
                    }

                    hideLoadingIndicator();
                });
            },
            error:function(response){
                hideLoadingIndicator();

                if(response && response.responseJSON && response.responseJSON.description){
                    alert(response.responseJSON.message + "\n\n" + response.responseJSON.description);
                }
                else{
                    if(isGermanShop()){
                        alert('Es ist ein Fehler aufgetreten. Bitte versuches es noch einmal.');
                    }
                    else{
                        alert('An error has occurred. Please try again.');
                    }
                }
            }
        });
    });

    $('.card-product-form button[name="minus"]').click(function(){
        var input = $(this).parents('.card-product-form').find('input[name="quantity"]');
        var span = $(this).parent().find('.product-information-quantity-input');
        var value = Math.max(1, parseInt(input.val()) - 1);
        span.text(value);
        input.val(value);

        if(value == 1){
            $(this).find('svg path').css('stroke', 'var(--color-border)');
        }
    });
    $('.card-product-form button[name="plus"]').click(function(){
        var input = $(this).parents('.card-product-form').find('input[name="quantity"]');
        var span = $(this).parent().find('.product-information-quantity-input');
        var value = parseInt(input.val()) + 1;
        span.text(value);
        input.val(value);

        $(this).parents('.card-product-form').find('button[name="minus"] svg path').css('stroke', 'var(--color-text)');
    });
}

function openFilterPopup(){
    $('#collection-filter-drawer').css('visibility', 'visible');

    $('#collection-filter-drawer-overlay').css('opacity', '0.5');
    $('#collection-filter-drawer-content').css('transform', 'translateX(0%)');
}

function closeFilterPopup(){
    setTimeout(function(){
        $('#collection-filter-drawer').css('visibility', 'hidden');
    }, 200);

    $('#collection-filter-drawer-overlay').css('opacity', '0');
    $('#collection-filter-drawer-content').css('transform', 'translateX(100%)');
}

/* ====================================== */
/* =============== SEARCH =============== */
/* ====================================== */

function initSearchPopup(){
    $('#search-popup .search-popup-header input').on('input', function(){
        if($(this).val() == ''){
            $('.search-popup-contents').empty();
            return;
        }

        showLoadingIndicator();

        $.ajax({ 
            url: getShopifyApiRoot() + 'search/suggest?q=' + $(this).val() + '&section_id=search-predictive',
            success: function(data){
                $('.search-popup-contents').empty();
                $('.search-popup-contents').html(data);

                hideLoadingIndicator();
            }
        });
    });

    $('#search-popup .search-popup-header svg:last-child').click(closeSearchPopup);
}

/* ======================================== */
/* =============== SECTIONS =============== */
/* ======================================== */

function handleSections(containerId){
    if(containerId){
        containerId = '#' + containerId + ' ';
    }
    else{
        containerId = "";
    }

    // Announcement bar.
    if($(containerId + '.header-announcement-bar').attr('data-use-slideshow') == 'true'){
        new Swiper(containerId + ".header-announcement-bar", {
            slidesPerView: 1,
            centeredSlides: true,
            autoplay:{
                delay: parseInt($(containerId + '.header-announcement-bar').attr('data-slideshow-speed')) * 1000,
                disableOnInteraction: false
            }
        });
    }

    // Collapsible Content.
    $(containerId + '.collapsible-content-row-header').click(function(){
        $(this).find('svg').css('rotate', '90deg');
        $(this).find('h3 span:last-child').text('-');
        $(this).next().toggle();

        if($(this).next().css('display') == 'none'){
            $(this).find('svg').css('rotate', '0deg');
            $(this).find('h3 span:last-child').text('+');
        }
    });

    // Collection
    $(containerId + '.section-collection-cards').each(function(){
        if($(this).attr('data-use-slider') != "true"){
            return true;
        }

        var config = {
            slidesPerView: parseFloat($(this).attr('data-product-count-mobile')),
            spaceBetween: 20,
            grabCursor: true,
            breakpoints: {
                768: {
                    slidesPerView: parseFloat($(this).attr('data-product-count-desktop'))
                }
            }
        };

        if($(this).attr('data-show-navigation') == "true" && $(this).attr('data-use-slider') == "true"){
            config.navigation = {
                nextEl: $(this).find('.swiper-button-next')[0],
                prevEl: $(this).find('.swiper-button-prev')[0]
            };
        }

        new Swiper($(this)[0], config);
    });

    // Custom reviews
    new Swiper(containerId + ".custom-reviews-cards",{
        loop: true,
        navigation: {
            nextEl: containerId + '.custom-reviews-cards .swiper-button-next',
            prevEl: containerId + '.custom-reviews-cards .swiper-button-prev',
        },
        breakpoints: {
            768: {
                slidesPerView: 3,
                spaceBetween: 20
            }
        }
    });

    // Selling point slider
    $(containerId + '.selling-point-slider').each(function(){
        new Swiper($(this)[0], {
            slidesPerView: 1,
            centeredSlides: true,
            loop: true,
            autoplay:{
                delay: parseInt($(this).attr('data-slideshow-speed')) * 1000,
                disableOnInteraction: false
            },
            breakpoints: {
                768: {
                    centeredSlides: false,
                    slidesPerView: parseInt($(this).attr('data-desktop-slides-per-view'))
                }
            }
        });
    });

    // Bundle
    $(containerId + '.bundle button').click(function(){
        var variants = bundleGetSelectedVariants(containerId);
        if(!variants || $(this).attr('disabled')){
            return;
        }

        showLoadingIndicator();

        var data = {
            'form_type': 'product',
            'items': [
                {
                    id: variants.first.id,
                    quantity: 1
                },
                {
                    id: variants.second.id,
                    quantity: 1
                }
            ]
        };

        $.ajax({
            type: 'POST', 
            url: getShopifyApiRoot() + 'cart/add.js',
            dataType: 'json', 
            data: data,
            success: function(){
                reloadCart(function(){
                    openCartDrawer();

                    hideLoadingIndicator();
                });
            },
            error:function(response){
                hideLoadingIndicator();

                if(response && response.responseJSON && response.responseJSON.description){
                    alert(response.responseJSON.message + "\n\n" + response.responseJSON.description);
                }
                else{
                    if(isGermanShop()){
                        alert('Es ist ein Fehler aufgetreten. Bitte versuches es noch einmal.');
                    }
                    else{
                        alert('An error has occurred. Please try again.');
                    }
                }
            }
        });
    });

    var updateVariants = function(){
        var variants = bundleGetSelectedVariants(containerId);
        if(!variants){
            return;
        }

        // Calculate bundle prices.
        var total = variants.first.price + variants.second.price;

        var discountType = $(containerId + '.bundle .bundle-add-to-cart').attr('data-discount-type');
        var discountValue = parseInt($(containerId + '.bundle .bundle-add-to-cart').attr('data-discount-value'));
        var bundleTotal = variants.first.price;

        if(discountType == 'percentage'){
            if(discountValue > 100){
                discountValue = 100;
            }
            
            bundleTotal += parseInt(Math.trunc(variants.second.price * ((100 - discountValue) / 100)));
        }
        else{
            bundleTotal += parseInt(Math.trunc(variants.second.price - discountValue));
        }

        // Update image.
        if(variants.first.featured_image && variants.first.featured_image.src){
            $(containerId + '.bundle .bundle-product:eq(0) .bundle-product-image img').attr("src", variants.first.featured_image.src).removeAttr("data-srcset").removeAttr("srcset");
        }
        if(variants.second.featured_image && variants.second.featured_image.src){
            $(containerId + '.bundle .bundle-product:eq(1) .bundle-product-image img').attr("src", variants.second.featured_image.src).removeAttr("data-srcset").removeAttr("srcset");
        }

        // Update price.
        PriceFormatter.showPrice(containerId + '.bundle .bundle-product:eq(0)', variants.first.price * bundleTotal/total, variants.first.price);
        PriceFormatter.showPrice(containerId + '.bundle .bundle-product:eq(1)', bundleTotal - Math.trunc(variants.first.price * bundleTotal/total), variants.second.price);

        // Handle stock.
        var anyOutOfStock = false;

        if(cr_bundle_product_1_variantStock.hasOwnProperty(variants.first.id)){
            $(containerId + '.bundle .bundle-product:eq(0) .bundle-product-available')[cr_bundle_product_1_variantStock[variants.first.id] > 0 ? 'addClass' : 'removeClass']('in-stock');
            $(containerId + '.bundle .bundle-product:eq(0) .bundle-product-available')[cr_bundle_product_1_variantStock[variants.first.id] == 0 ? 'addClass' : 'removeClass']('out-of-stock');

            anyOutOfStock = cr_bundle_product_1_variantStock[variants.first.id] == 0;
        }
        else{
            $(containerId + '.bundle .bundle-product:eq(0) .bundle-product-available').addClass('in-stock').removeClass('out-of-stock');
        }

        if(cr_bundle_product_2_variantStock.hasOwnProperty(variants.second.id)){
            $(containerId + '.bundle .bundle-product:eq(1) .bundle-product-available')[cr_bundle_product_2_variantStock[variants.second.id] > 0 ? 'addClass' : 'removeClass']('in-stock');
            $(containerId + '.bundle .bundle-product:eq(1) .bundle-product-available')[cr_bundle_product_2_variantStock[variants.second.id] == 0 ? 'addClass' : 'removeClass']('out-of-stock');

            anyOutOfStock = anyOutOfStock || cr_bundle_product_2_variantStock[variants.second.id] == 0;
        }
        else{
            $(containerId + '.bundle .bundle-product:eq(1) .bundle-product-available').addClass('in-stock').removeClass('out-of-stock');
        }

        // Handle add to cart.
        PriceFormatter.showPrice(containerId + '.bundle .bundle-add-to-cart', bundleTotal, total);

        $(containerId + '.bundle .bundle-add-to-cart .bundle-add-to-cart-price-saved span').text(Math.trunc(100 - (bundleTotal/total * 100)) + '%');

        var button = $(containerId + '.bundle .bundle-add-to-cart button');
        button[anyOutOfStock ? 'attr' : 'removeAttr']('disabled', 'disabled');
        button.text(anyOutOfStock ? button.attr('data-sold-out-text') : button.attr('data-available-text'));
    };
    $(containerId + '.bundle select').change(updateVariants);
    updateVariants();

    // UGC Videos
    $(containerId + '.ugc-videos .ugc-videos-video-main').click(function(){
        var video = $(this)[0];

        if(video.muted){
            video.pause();
            video.currentTime = 0;
            video.play();
            
            video.muted = false;
            $(this).parent().find('svg').hide();
        }
        else{
            video.muted = true;
            $(this).parent().find('svg').show();
        }
    });

    // Reviews.
    if($('.reviews-list').length > 0){
        $('.reviews-load-more-wrapper .btn').click(function(){
            $(this).parent().hide();
            $('.reviews-list-entry').show();
        });
    }

    // Newsletter popup.
    $('.product-information-show-newsletter-popup').click(function(){
        $('.newsletter-popup-overlay, .newsletter-popup-stage-signup').show();
    });

    if($('.newsletter-popup-stage-signup').length > 0){
        var newsletterPopupData = $('.newsletter-popup-stage-signup').data();
        if(newsletterPopupData.showByScroll){
            var showPoint = document.body.scrollHeight * (parseInt(newsletterPopupData.scrollPosition) / 100);
            var newsletterPopupWasOpen = false;

            $(window).scroll(function(){
                if(!newsletterPopupWasOpen && $(this).scrollTop() > showPoint){
                    $('.newsletter-popup-overlay, .newsletter-popup-stage-signup').show();
                    newsletterPopupWasOpen = true;
                }
            });
        }
    }

    $('#newsletter-popup-form').submit(function(event){
        event.preventDefault();
        event.stopPropagation();

        // Check mail address.
        $('.newsletter-popup-error').hide();

        var email = $(this).find('input[name="contact[email]"]').val();
        if(email == '' || !email.toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)){
            $('.newsletter-popup-error').css('display', 'inline-block');
            return;
        }

        // Signup.
        showLoadingIndicator();

        $.ajax({
            type: "POST",
            url: $(this).attr('action'),
            data: $(this).serialize(),
            dataType: "json",
            success: function() {
                hideLoadingIndicator();

                $('.newsletter-popup-stage-signup').hide();
                $('.newsletter-popup-stage-success').show();
            },
            error: function() {
                hideLoadingIndicator();

                $('.newsletter-popup-stage-signup').hide();
                $('.newsletter-popup-stage-success').show();
            }
        });
    });

    $('.newsletter-popup-overlay, .newsletter-popup-close').click(function(){
        $('.newsletter-popup-overlay, .newsletter-popup').hide();
    });

    // Video With Text
    $(".video-manually-play-pause-video-with-text").click(function () {
        if (this.paused) {
            $(".video-manually-play-pause-video-with-text").each(function () {
                this.pause();
            });
            this.play();
        } else {
            this.pause();
        }
    });

    // Video Banner
    $(".video-manually-play-pause").click(function () {
        if (this.paused) {
            $(".video-manually-play-pause").each(function () {
                this.pause();
            });
            this.play();
        } else {
            this.pause();
        }
    });

    var videoBannerExecuted = false;
    var startVideoBannerFunc = function(){
        videoBannerExecuted = true;

        $('.video-banner-video video').each(function(){
            var video = $(this)[0];
            if(!video.muted){
                video.play();
            }
        });

        if(videoBannerExecuted){
            return;
        }
    };

    $(window).scroll(startVideoBannerFunc);
    $(document).click(startVideoBannerFunc);


    $(containerId + ".link-list-mobile").each(function(){
        var slidesPerView = $(containerId + '.link-list-mobile').attr('data-slide-per-view');
        var config = {
            slidesPerView: slidesPerView,
            grabCursor: true,
            spaceBetween: 25,
        };
        new Swiper($(this)[0], config);
    });

    // Slide Show
    $(containerId + '.section-slideshow').each(function(){
        var config = {
            slidesPerView: 1,
            pagination: {
                el: containerId + '.section-slideshow .swiper-pagination'
            },
        };

        var desktopNavigation = $(containerId + '.section-slideshow').attr('data-slideshow-desktop-navigation');
        var mobileNavigation = $(containerId + '.section-slideshow').attr('data-slideshow-mobile-navigation');

        if(desktopNavigation == 'true' && mobileNavigation == 'true'){
            config.navigation = {
                nextEl: containerId + '.section-slideshow .swiper-button-next',
                prevEl: containerId + '.section-slideshow .swiper-button-prev'
            };
        } else if(desktopNavigation == 'true'){
            config.navigation = {};
            config.breakpoints = {
                768:{
                    navigation: {
                        nextEl: containerId + '.section-slideshow .swiper-button-next',
                        prevEl: containerId + '.section-slideshow .swiper-button-prev'
                    }
                }
            };
        }

        if($(this).attr('data-use-loop') == "true"){
            config.loop = true;
        }

        if($(this).attr('data-use-autoplay') == "true" && $(this).attr('data-autoplay-delay') > 0){
            config.autoplay= {
                delay: Number($(this).attr('data-autoplay-delay')) * 1000,
                disableOnInteraction: false
            }
        }

        new Swiper($(this)[0], config);
    });

    // Section Multi Column
    $(containerId + '.section-multi-column-slider').each(function(){
        var slidesPerView = $(containerId + '.section-multi-column-slider').attr('data-slide_per_view');
        var horizontalGap = $(containerId + '.section-multi-column-slider').attr('data-horizontal-gap');
        var config = {
            slidesPerView: slidesPerView,
            pagination: {
                el: containerId + '.section-multi-column-slider .swiper-pagination'
            },
            spaceBetween: Number(horizontalGap),
        };

        var mobileNavigation = $(containerId + '.section-multi-column-slider').attr('data-mobile-navigation');

        if(mobileNavigation == 'true'){
            config.navigation = {
                nextEl: containerId + '.section-multi-column-slider .swiper-button-next',
                prevEl: containerId + '.section-multi-column-slider .swiper-button-prev'
            };
        }

        if($(this).attr('data-use-loop') == "true"){
            config.loop = true;
        }

        if($(this).attr('data-use-autoplay') == "true" && $(this).attr('data-autoplay-delay') > 0){
            config.autoplay= {
                delay: Number($(this).attr('data-autoplay-delay')) * 1000,
                disableOnInteraction: false
            }
        }

        new Swiper($(this)[0], config);
    });
  
    // Marquee Slider
    if($(containerId + ".scrolling-image").length > 0){
        function getWidth($element) {
            var rect = $element[0].getBoundingClientRect();
            return rect.right - rect.left;
        }

        function ScrollingText($box, speed) {
            var $inner_element = $box.children().first();
            if (!$inner_element.length) throw "No child node found";

            $inner_element.css("position", "relative");

            this.position = 0;
            this.speed = speed;
            this.box_width = getWidth($box);
            this.inner_element_width = getWidth($inner_element);
            this.$box = $box;
            this.$inner_element = $inner_element.clone();
            setUpChildrens.call(this);
        }

        function refreshWidths() {
            this.box_width = getWidth(this.$box);
            this.inner_element_width = getWidth(this.$box.children().first());
        }

        function calculateNumElements() {
            return Math.ceil(this.box_width / this.inner_element_width) + 1;
        }

        function setUpChildrens() {
            var qty = calculateNumElements.call(this) > 15 ? 15 : calculateNumElements.call(this);
            var $children = this.$box.children();

            if (qty > $children.length) {
                for (var i = $children.length; i < qty; i++) {
                    this.$box.append(this.$inner_element.clone());
                }
            } else if (qty < $children.length) {
                for (var i = $children.length - 1; i >= qty; i--) {
                    $children.eq(i).remove();
                }
            }
        }

        function nextFrame(delta, direction) {
            var self = this;
            refreshWidths.call(this);
            setUpChildrens.call(this);

            this.$box.children().each(function () {
                var translateX = direction === "rtl" ? self.position : -self.position;
                $(this).css("transform", `translateX(${translateX}px)`);
            });

            this.position += (this.speed * delta) / 1000;
            if (this.position >= this.inner_element_width) {
                this.position = this.position % this.inner_element_width;
            }
        }

        ScrollingText.prototype = {
            start: function (direction) {
                this._running = true;
                var self = this;
                var last_time = null;

                function loop_func() {
                    if (!self._running) return;

                    var now = Date.now();
                    var delta = last_time === null ? 0 : now - last_time;
                    nextFrame.call(self, delta, direction);
                    last_time = now;

                    requestAnimationFrame(loop_func);
                }

                requestAnimationFrame(loop_func);
            },

            stop: function () {
                this._running = false;
            },
        };

        // Get the element with selector
        var $element = $(".scrolling-image");
        if (!$element.length) return;

        var speed = $(window).width() > 768 ? parseInt($element.data("scrolling-speed")) : parseInt($element.data("scrolling-speed")) / 1.5;
        var direction = $element.data("scrolling-direction");
        var scrolling_text = new ScrollingText($element, speed);

        if ($element.data("pause-on-hover")) {
            var windowInFocus = true;

            $(window).on("blur", function () {
                windowInFocus = false;
            });

            $(window).on("focus", function () {
                windowInFocus = true;
            });

            $element.on("mouseover", function () {
                if (windowInFocus) {
                    scrolling_text.stop();
                }
            });

            $element.on("mouseout", function () {
                if (windowInFocus) {
                    scrolling_text.start(direction);
                }
            });
        }

        // Start/stop scrolling based on visibility
        var isElementVisible = false;

        function checkVisibility() {
            var rect = $element[0].getBoundingClientRect();
            var isVisible = rect.top >= 0 && rect.bottom <= $(window).height();

            if (isVisible && !isElementVisible) {
                isElementVisible = true;
                scrolling_text.start(direction);
            } else if (!isVisible && isElementVisible) {
                isElementVisible = false;
                scrolling_text.stop();
            }
        }

        $(window).on("scroll resize", checkVisibility);
        checkVisibility();
    }
    
    // Section Image With Text
    if($('.image-with-text-image .slider-container').length > 0){
        const $sliderContainer = $('.image-with-text-image .slider-container');
        const $slider = $('.image-with-text-image .slider-container .slider');
        const $beforeWrapper = $slider.find('.before-wrapper');
        const $handle = $slider.find('.slider-handle');
        const $grip = $slider.find('.slider-grip');
        const $handleFirst = $slider.find('.slider-handle-first');
        const $handleSecond = $slider.find('.slider-handle-second');
        let isDown = false;

        function onMouseDown(e) {
            e.stopPropagation();
            isDown = true;
        }

        function onMouseUp() {
            isDown = false;
        }

        function onMouseMove(e) {
            if (isDown) {
                e.preventDefault();
                moveSlider(e);
            }
        }

        function onTouchStart(e) {
            e.stopPropagation();
            isDown = true;
        }

        function onTouchEnd() {
            isDown = false;
        }

        function onTouchMove(e) {
            if (isDown) {
                e.preventDefault();
                moveSlider(e);
            }
        }

        function moveSlider(e) {
            const rect = $slider[0].getBoundingClientRect();
            let xPos = (e.clientX || e.touches[0].clientX) - rect.left;
            let width = rect.width;
            if (xPos < 0) xPos = 0;
            if (xPos > width) xPos = width;
            let percent = (xPos / width) * 100;
            $beforeWrapper.css('clip-path', `inset(0 ${99.5 - percent}% 0 0)`);
            $handle.css('left', percent + '%');
            $grip.css('left', percent + '%');
        }

        function setupDesktop() {
            $grip.on('mousedown', onMouseDown);
            $(window).on('mouseup', onMouseUp);
            $slider.on('mousemove', onMouseMove);
        }

        function setupMobile() {
            $grip.on('touchstart', onTouchStart);
            $(window).on('touchend', onTouchEnd);
            $slider.on('touchmove', onTouchMove);
        }

        function setupSlider() {
            if ('ontouchstart' in window) {
                setupMobile();
            } else {
                setupDesktop();
            }
        }

        function updateSliderHandleSize() {
            const sliderContainerHeight = $sliderContainer.height();
            const gripHeight = $grip.height();
            const firstAndSecondHeight = (sliderContainerHeight - gripHeight) / 2;
            $handleFirst.css('height', firstAndSecondHeight + 'px'); 
            $handleSecond.css('height', firstAndSecondHeight + 'px');

            const initialPosition = 50;
            $beforeWrapper.css('clip-path', `inset(0 ${99.5 - initialPosition}% 0 0)`);
            $handle.css('left', initialPosition + '%');
            $grip.css('left', initialPosition + '%');
        }

        setupSlider();
        updateSliderHandleSize();

        

        window.addEventListener('resize',function(){
            updateSliderHandleSize();
        });
    }
}

function bundleGetSelectedVariants(containerId){
    if(!window.cr_bundle_product_1 || !window.cr_bundle_product_2){
        return null;
    }

    // Variant 1.
    var options = [];
    $(containerId + '.bundle-product').eq(0).find('select').each(function(){
        options.push({
            key: 'option' + (cr_bundle_product_1.options.indexOf($(this).attr('name')) + 1),
            value: $(this).val()
        });
    });

    var variant_1 = cr_bundle_product_1.variants.find(function(variant) {
        return options.every(function(values) {
            return variant[values.key] === values.value;
        });
    });

    // Variant 2.
    options = [];
    $(containerId + '.bundle-product').eq(1).find('select').each(function(){
        options.push({
            key: 'option' + (cr_bundle_product_2.options.indexOf($(this).attr('name')) + 1),
            value: $(this).val()
        });
    });

    var variant_2 = cr_bundle_product_2.variants.find(function(variant) {
        return options.every(function(values) {
            return variant[values.key] === values.value;
        });
    });

    if(!variant_1 || !variant_2){
        return null;
    }

    return {
        first: variant_1,
        second: variant_2
    };
}