$( document ).ready(function(event) {
    var ad = false;
    if(window.location.href.indexOf("?ad") != -1) {
        var ad = true; //a variable to indicate this comes from an ad.
    }

    recalcQuantity();

    if($(".shortDescProduct").height() < $(".shortDescProduct p").height()) {
        $(".read-more").addClass("inline");
    } else if($(".shortDescProduct p").html() == $("#fullTextAnchor p").html()) {
        $(".read-more").addClass("hide");
    }
    $(".productDesc .descContainer").css("visibility", "visible");

    $(document).on('click', function(event) {
        if (
            (
                !$(event.target).closest('.quantityDropDown').length &&
                !$(event.target).closest('.selectAmount').length &&
                !$(event.target).closest('.mobqualityContainer').length
            )
            ||
            (
                $(event.target).hasClass("accept"))
        ) {
            closeDropdown();
        }
    });

    $(".inputQuantity div").on('click', function(event) {
        closeDropdown();
    });

    $(".inputQuantity input").on('keydown', function(event) {
        if ((event.keyCode || event.which) == 13) {
            event.preventDefault(); // FireFox Bugfix
            closeDropdown();
        }
    });

    function closeDropdown() {
        _revert = [];
        $(".dropDownOpened").removeClass("dropDownOpened").addClass("dropDownClosed");
        $(".fa-caret-up").addClass("fa-caret-down").removeClass("fa-caret-up");
        $(".selectActive").removeClass("selectActive");
        // Disabled, browser behaviour changed and every click this function is noticeable
        //recalcQuantity();
    }

    /**
     * Edit the code underneath when div is applied
     */
    $(".cartColor").on("click", function() {
        $.post("/product/getOffset", {"id": $(this).attr('id'), "quantity": $("#CartItem_quantity").val()- $(this).val()}, function(html) {
            $(".offsetClass").html(html);
        })
    });

    $("#rightArrow").on("click", function() {
        if(next = $(".scrolling .productThumbnail").last().next()) {
            if(next.hasClass("thumbnailHidden")) {
                next.removeClass("thumbnailHidden");
                next.addClass("productThumbnail");
                $(".scrolling .productThumbnail").first().addClass("thumbnailHidden");
                $(".scrolling .productThumbnail").first().removeClass("productThumbnail");
                if(!next.next().hasClass("thumbnailHidden")) {
                    $("#rightArrow").addClass("no-more");
                } else {
                    $("#leftArrow").removeClass("no-more");
                }
            }
        }
    });

    $("#leftArrow").on("click", function() {
        if(prev = $(".scrolling .productThumbnail").first().prev()) {
            if(prev.hasClass("thumbnailHidden")) {
                prev.removeClass("thumbnailHidden");
                prev.addClass("productThumbnail");
                $(".scrolling .productThumbnail").last().addClass("thumbnailHidden");
                $(".scrolling .productThumbnail").last().removeClass("productThumbnail");
                if(!prev.prev().hasClass("thumbnailHidden")) {
                    $("#leftArrow").addClass("no-more");
                } else {
                    $("#rightArrow").removeClass("no-more");
                }
            }
        }
    });

    $(".selectAmount").on("click", function(ev) {

        // Check URL FOR Ads
        var url = window.location.href;
        var containsAd = url.includes("&ad=");

        // If Adds, then remove close button (bugged)
        if(containsAd){
            $( "div" ).find( ".btn.btn-small.btn-white.cancel" ).css("display", "none");

            // Show close button (not bugged without adds view)
        } else {
            $( "div" ).find( ".btn.btn-small.btn-white.cancel" ).css("display", "block");
        }


        var id = $(this).closest(".priceColorBox").data("stockid");
        if($(this).closest(".priceColorBox").find(".quantityDropDown").hasClass("dropDownOpened")) {
            closeDropdown();
        } else {
            closeDropdown();
            $(this).closest(".priceColorBox").find(".quantityDropDown  .quantity").each(function() {
                _revert.push({ id: $(this).data("stock"), val: $(this).val()});
            });
            $(".quantityDropDown[data-stockid='" + id + "']").removeClass("dropDownClosed").addClass("dropDownOpened");
            $(this).closest(".priceColorBox").find(".inputQuantity input").first().focus();
            $(this).find(".fa-caret-down").removeClass("fa-caret-down").addClass("fa-caret-up");
            $(this).addClass("selectActive");
            if(!$(this).hasClass("excludeOffset")) {
                $(".quantityDropDown.dropDownOpened .offset li").html("<i class=\"fas fa-sync fa-spin\"></i><span class=\"sr-only\">Loading...</span>");
                $.post("/product/getOffset", $("#productConfigFrom").serialize() + "&id=" + id + (ad == true ? "&ad" : ""), function (html) {
                    $(".quantityDropDown.dropDownOpened .offset").html(html);
                    if(html) {
                        // Html load done ..
                        checkAmountInput();
                    }
                });
            }
        }
    });


    function checkAmountInput(ev) {
        var NoAmountItem =  document.querySelector('.quantityDropDown.dropDownOpened li.quantity0.clearPulldown');
        var amountInput =   document.querySelector('.quantityDropDown.dropDownOpened .inputQuantity input[type="number"]');

        if(NoAmountItem){
            NoAmountItem.style.display = "none";
            if(amountInput.value === '0'){
                NoAmountItem = 0;
            }
        }

        if(amountInput.value  > 0 ) {
            NoAmountItem.style.display = "block";
        } else {
            amountInput.value = "";
        }
    }


    function getTopLevelDomain() {
        const hostname = window.location.hostname;
        const parts = hostname.split('.');
        return parts[parts.length - 1];
    }


    $(".priceColorBox").on("click", function() {
        var imgElement = $(this).find(".imageColor img");
        if(imgElement.length > 0) {
            var src = imgElement.attr("src");
            $("#mainpic img").attr("src", src+"&width=320&height=320");
            $("#mainpic").attr("href", src+"&width=1000&height=1000");
        }
    });

    $(".quantity, .mobquantity").on("keyup", function(ev) {
        $("[name='form[stock]["+$(this).data("stockid")+"]']:not(.sampleInput)").val($(this).val()).trigger("valHasChanged");

        if($(this).hasClass("mobquantity")) {
            if($(this).closest(".quantityDropDown").length > 0) {
                var val = 0;
                $(this).closest(".quantityDropDown").find(".mobquantity").each(function(index, quantity) {
                    if($(quantity).val() != "") {
                        val += parseInt($(quantity).val());
                    }
                });

                if(val == 0) {
                    val = "Maak uw keuze";
                }

                $(this).closest(".mobQuantityContainer").find(".mobquantity.complete").val(val);
            } else {
                if($(this).val() != "0" && $(this).val() != "") {
                    $(this).closest(".mobQuantityContainer").removeClass("empty").find(".removeEnrichment").addClass("show");
                } else {
                    $(this).closest(".mobQuantityContainer").addClass("empty").find(".removeEnrichment").removeClass("show");
                }
            }

            recalcQuantity(false, ".productCalculation", "#mobileProductConfigFrom");
        } else {
            //console.log('BBBBBBBBBBBBBBBBBBBB');
            //recalcQuantity();
        }
    });

    $(".mobQuantityContainer .removeColor").on("click", function() {
        $(this).closest(".mobQuantityContainer").find(".mobquantity").val("").trigger("keyup");
    });


    $(".mobQuantityContainer").on("click", function() {
        if($(this).find(".dropDownClosed").length > 0) {
            _revert = [];
            $(this).closest(".mobQuantityContainer").find(".quantityDropDown .inputQuantity  .mobquantity").each(function () {
                _revert[$(this).data("stock")] = $(this).val();
            });
        }
        $(".mobQuantityContainer .dropDownOpened").removeClass("dropDownOpened").addClass("dropDownClosed");
        $(this).find(".dropDownClosed").removeClass("dropDownClosed").addClass("dropDownOpened");
    });

    $(".quantity").on("valHasChanged", function() {
        var element = $(this);
        var quantityElements = $(element).closest(".quantityDropDown").find(".quantity");
        var quantity = 0;
        // var minQuantity = $(".alert.minQuantity")
        $(element).closest(".priceColorBox").find(".selectAmount").removeClass("stockWarning");



        if($(".stockWarning").length == 0) {
            $(".outOfStocks").hide();
        }

        $.each(quantityElements, function(id, element) {
            if($(element).val() != "") {
                var usesStock = $(element).data("use-stock");
                var sufficientStock = $(element).val() >= $(element).data("stock");
                if($(element).data("stock") >= 0 && ($(element).data("stock") != "" || $(element).data("stock") === 0) && $(element).val() > $(element).data("stock")) {
                    $(".outOfStocks").show();
                    $(element).closest(".priceColorBox").find(".selectAmount").addClass("stockWarning");
                }

                quantity += parseInt($(element).val());
            }
        });
        if(quantity == 0) {
            $(".priceColorBox .fa-circle").removeClass("fas fa-circle").addClass("far fa-circle");
            $(element).closest(".quantityDropDown").find(".quantityList li[data-quantity='"+quantity+"'] .far.fa-circle").removeClass("far fa-circle").addClass("fas fa-circle");
            if(getTopLevelDomain() == 'de') {
                $(element).closest(".priceColorBox").find(".quantityText").html("Anzahl");
            } else {
                $(element).closest(".priceColorBox").find(".quantityText").html("Kies aantallen");
            }
            $(element).closest(".priceColorBox").removeClass("hasValue");
        } else {
            $(element).closest(".priceColorBox").find(".quantityText").html(quantity);
            $(element).closest(".priceColorBox").addClass("hasValue");
            $(".priceColorBox .fa-circle").removeClass("fas fa-circle").addClass("far fa-circle");
            $(element).closest(".quantityDropDown").find(".quantityList li[data-quantity='"+quantity+"'] .far.fa-circle").removeClass("far fa-circle").addClass("fas fa-circle");
        }

        //console.log('aaaaaaaaaaa');
        recalcQuantity();

    });

    $(".mobquantity").on("valHasChanged", function() {
        recalcQuantity(false, ".productCalculation", "#mobileProductConfigFrom");
        if(!$(this).is(":focus") && ($(this).val() == "0" || $(this).val() == "")) {
            $(this).closest(".mobQuantityContainer").addClass("empty");
        }
    });

    $(".mobilePriceCalcInput.button").on("click", function() {
        $(this).closest(".mobilePriceCalc").find(".mobilePriceCalcInput:not('.button')").toggleClass("closed");
        if( $(this).find("i").hasClass("fa-level-down")) {
            $(this).find("i").removeClass("fa-level-down").addClass("fa-level-up");
        } else {
            $(this).find("i").removeClass("fa-level-up").addClass("fa-level-down");
        }
    });




    // Get the correct selected print options for mobile and desktop
    $("ul.printList li").on("click", function(event) {

        // Get Color value from selected item
        var selectedColorData = $(this).find('span.price')[0].dataset.color;

        // Get the relevant group, printname and print position
        var printPositionData = event.target.closest('.printList').dataset.position;
        var selectedPrintName = event.target.closest('.printPosition').dataset.printname;
        var selectedPrintGroup = event.target.closest('.printPosition').dataset.group;

        // Change the .active class to the right item
        var AllprintPositions = document.querySelectorAll('.printPosition');
        $(AllprintPositions).each(function(i, element) {

            // Check for correct group:
            if(element.dataset.printname == selectedPrintName && element.dataset.group == selectedPrintGroup){


                // Find all ul.printLists related to this group
                var printListedItems = $(element).find('ul.printList li');
                $(printListedItems).each(function(index, element) {

                    // Check for the correct Print Position
                    if(element.closest('ul').dataset.position == printPositionData) {

                        // Check color value
                        var printColors = $(printListedItems[index]).find('span.price')[0].dataset.color;
                        if(printColors == selectedColorData) {
                            $(printListedItems[index]).addClass('active');
                        } else {
                            $(printListedItems[index]).removeClass('active');
                        }

                    }

                });
            }
        });
    });



    $(".mobquantity").on("change", function() {
        $(this).trigger("valHasChanged");
        recalcQuantity();
    });

    $("ul.printList").on("click", function() {
        recalcQuantity(true, ".productCalculation", "#mobileProductConfigFrom");
    });



    $(".offset").on("click", ".quantityList li", function() {
        var quantity = $(this).data("quantity");
        $(this).closest(".quantityDropDown").find(".quantity").val(quantity);
        $(this).closest(".quantityDropDown").find(".quantity").keyup();
        $(this).closest(".offset").find(".fa-circle").removeClass("fa-circle").addClass("fa-circle-thin");
        $(this).find("priceColorBox .fa-circle-thin").removeClass("fa-circle-thin").addClass("fa-circle");
        closeDropdown();
        recalcQuantity();
    });

    var recalc;
    var enriched = false;
    function recalcQuantity(recalcEnrichment, element, form) {

        if(typeof recalcEnrichment == "undefined") {
            recalcEnrichment = true;
        }
        element = element || ".productCalculation";
        form = form || "#productConfigFrom";

        if(form == "#productConfigFrom") {
            var sample = true;
            var hasVal = false;
            $(".quantity").each(function() {
                if($(this).val() > 0) {
                    hasVal = true;
                    // alert('Aantallen aanwezig');
                }
                if($(this).val() > 1) {
                    sample = false;

                }
            });
            if(sample == true && hasVal == true) {
                $(".outOfStocks").hide();
                $(".sampleNotAllowed").show();
                // return;
            } else {
                $(".sampleNotAllowed").hide();
            }
        }

        var enrichmentInfo = enrichmentsAsString();

        if (typeof recalc !== "undefined") {
            recalc.abort();
        }
        if (typeof enrichmentRecalc !== "undefined") {
            enrichmentRecalc.abort();
        }
        //var farEastPossible = false;
        var newPrice = $("#newPrice").val();
        var data = $(form).serialize() + enrichmentInfo + (ad == true ? "&ad" : "");

        if(typeof newPrice !== "undefined") {
            data = data + "&form[newPrice]=" + newPrice
        }

        var url = window.location.href;

        $(form + " .quantity, "+ form + " .mobquantity").each(function(i, quantity) {
            if($(quantity).val() > 0) {
                url = addParam(url, "q["+$(quantity).data("stockid")+"]", $(quantity).val());
            } else {
                url = deleteParam(url, "q["+$(quantity).data("stockid")+"]");
            }
        });
        //url = addParam(url, "d",  $(form + " #deliveryDate, " + form + " #deliveryDate_mobile").val());

        var enrichments = $("li.active");
        $.each(enrichments, function(enrichment) {
            color = $(this).find(".price").data("color");
            method = $(this).closest(".printPosition").data("group");
            pos = $(this).closest(".printGroup").find(".printGroupName").data("printgroupid");
            if(color != 0) {
                url = addParam(url, "p["+pos+"]["+method+"]", color);
            } else {
                url = deleteParam(url, "p["+pos+"]["+method+"]");
            }
        });

        window.history.replaceState({ additionalInformation: 'Updated configuration' }, $(document).attr('title'), url);

        recalc = $.ajax({
            type:"POST",
            data:data,
            beforeSend: function(){
                $('.loadingPriceConfig').addClass( 'active' );

                var priceContainerHeight = document.querySelector('.productCalculation .priceContainer');
                var priceContainerHeightActive = document.querySelector('.productCalculation.active');
                var priceContainerButtons = document.querySelector('.footerButtons');

                if(priceContainerHeightActive) {
                    var loadingBoxHeigt = priceContainerHeightActive.offsetHeight - priceContainerButtons.offsetHeight - 15;
                    $('.loadingPriceConfig.active').css({ height: loadingBoxHeigt });
                    $('.loadingPriceConfig.active .loadingIcon .fas.fa-sync').css("line-height", loadingBoxHeigt + "px");

                } else if (priceContainerHeight) {
                    if(!priceContainerButtons) {priceContainerButtons = 0; }
                    var loadingBoxHeigt = priceContainerHeight.offsetHeight - priceContainerButtons.offsetHeight - 15;
                    $('.loadingPriceConfig').css({ height:  loadingBoxHeigt });
                    $('.loadingPriceConfig .loadingIcon .fas.fa-sync').css("line-height", loadingBoxHeigt + "px");

                }
            },
            success: function(data) {
                $(element).html(data);
            },
            url: "/product/configurationPricing"
        });




        if(recalcEnrichment == true) {
            $(".printList .price").addClass("loading");
            //recalcQuantity(true, ".productCalculation", "#productConfigFrom");
            $( ".borderColorCount .price" ).hide();


            enrichmentRecalc = $.ajax({
                type: "POST",
                data: data + "&firstRow=" + (!$(".printPositions .printGroup:not(.recommandPos)").is(":visible")),

                beforeSend: function(){
                    $('.loadingPriceConfig').addClass( 'active' );
                    // $('.printPositions').slideUp();
                },

                success: function (data) {
                    $(".printList .price").html("-");
                    data = $.parseJSON(data);
                    if (data == "" || data === null) {
                        $(".printList .price").html("");
                    } else {
                        $( ".borderColorCount .price" ).show();

                        $.each(data, function (methodId, positions) {
                            $.each(positions, function (position, colors) {
                                $("[data-group=\"" + methodId + "\"]").find("[data-position=\"" + position.toLowerCase() + "\"]").parent().find(".deliveryDays").html(colors.deliveryDays);
                                if(colors.colors !== undefined) {
                                    $.each(colors.colors, function (color, price) {
                                        if (price.price != false) {
                                            $("[data-group=\"" + methodId + "\"]").find("[data-position=\"" + position.toLowerCase() + "\"]").find("[data-color=\"" + color + "\"]").html("<i class=\'fal fa-plus\'></i> <span class=\'printPriceSmall\'>" + price.price + " p/s</span>");
                                        } else if (price.price == false) {
                                            $("[data-group=\"" + methodId + "\"]").find("[data-position=\"" + position.toLowerCase() + "\"]").find("[data-color=\"" + color + "\"]").html("Op aanvraag");
                                        }
                                    });
                                }
                            });
                        });
                    }

                    $(".printList .price").removeClass("loading");
                    // $('.printPositions').slideDown();
                },
                url: "/product/calculateEnrichmentPiecePrices"
            });
        }
    }

    function addParam(currentUrl,key,val) {
        var url = new URL(currentUrl);
        url.searchParams.set(key, val);
        url.search = decodeURIComponent(url.search)
        return url.href;
    }

    function deleteParam(currentUrl,key) {
        var url = new URL(currentUrl);
        url.searchParams.delete(key);
        url.search = decodeURIComponent(url.search)
        return url.href;
    }

    function enrichmentsAsString() {
        var string = "";
        var enrichments = $("li.active");
        $.each(enrichments, function(enrichment) {
            color = $(this).find(".price").data("color");
            if(color != 0) {
                method = $(this).closest(".printPosition").data("group");
                pos = $(this).closest(".printList").data("position");
                string += "&form[enrichmentPositions][" + method + "][" + pos + "]=" + color
            }
        });
        return string;
    }

    $(".mobquality, .removeEnrichment div:not('.removeColor')").on("click", function(e) {
        if($(this).closest(".mobqualityContainer").hasClass("disabled")) {
            return;
        }
        if($(this).closest(".mobqualityContainer").find(".options").hasClass("show")) {
            $(".mobqualityContainer").find(".options").removeClass("show");
        } else {
            $(".mobqualityContainer").find(".options").removeClass("show");
            $(this).closest(".mobqualityContainer").find(".options").addClass("show");
        }
    });


    $(".options li").on("click", function() {
        var position = $(this).closest(".mobqualityContainer").data("position").toLowerCase();
        var group = $(this).closest(".mobqualityContainer").data("group");
        var color =  $(this).data("color");
        $(this).closest(".mobqualityContainer").find(".fa-square").removeClass("fa-square").addClass("fa-square-o");
        $(this).find(".fa-square-o").removeClass("fa-square-o").addClass("fa-square");
        if($(this).data("color") == "0") {
            $(this).closest(".mobqualityContainer").find(".removeEnrichment .removeColor").trigger("click");
        } else {
            $(this).closest(".mobqualityContainer").find(".options").removeClass("show");
            $(this).closest(".mobqualityContainer").find(".removeEnrichment").addClass("show");
            $(this).closest(".mobqualityContainer").removeClass("empty");
            $(this).closest(".mobqualityContainer").find(".colorName").html($(this).data("colorname"));
            $(".mobqualityContainer[data-position='" + position + "']").addClass("disabled");
            $(this).closest(".mobqualityContainer").removeClass("disabled");        }

        $(".printPosition[data-group='"+group+"'] .printList[data-position='"+position+"'] li:has(.price[data-color='"+color+"'])").trigger("click");

    });

    $(".removeEnrichment .removeColor").on("click", function() {
        var position = $(this).closest(".mobqualityContainer").data("position");
        var position = $(this).closest(".mobqualityContainer").data("position");
        var group = $(this).closest(".mobqualityContainer").data("group");
        var color =  0;

        $(".mobqualityContainer[data-position='"+position+"']").removeClass("disabled");
        $(this).closest(".mobqualityContainer").find(".fa-square").removeClass("fa-square").addClass("fa-square-o");
        $(this).closest(".mobqualityContainer").find("[data-color='0'] .fa-square-o").removeClass("fa-square-o").addClass("fa-square");
        $(this).closest(".mobqualityContainer").addClass("empty");
        $(this).closest(".mobqualityContainer").find(".removeEnrichment").removeClass("show");
        $(this).closest(".mobqualityContainer").find(".options").removeClass("show");

        $(".printPosition[data-group='"+group+"'] .printList[data-position='"+position+"'] li:has(.price[data-color='"+color+"'])").trigger("click");
    });




    // // DOM CHECKER Sticky Price Summary
    // $(window).on('DOMContentLoaded load resize scroll',
    //     { passive: true },
    //     function() {
    //
    //     var rect = $(".inView")[0].getBoundingClientRect();
    //     var end = ($("#orderStart").offset().top) + ($("#orderStart").height());
    //     var floater = ($(".productCalculation").offset().top) + ($(".productCalculation").height()) ;
    //     var top = $(".productDesc ").height() - $(".productCalculation").height();
    //
    //     if( rect.top >= 64 && rect.left >= 0 && rect.right <= (window.innerWidth || document.documentElement.clientWidth)) {
    //         if($(".productCalculation").hasClass("priceboxFloat")) {
    //             $(".productCalculation").removeClass("priceboxFloat");
    //         }
    //     } else {
    //         if(!$(".productCalculation").hasClass("priceboxFloat") && Math.abs(rect.top) + 64 < top) {
    //             $(".productCalculation").addClass("priceboxFloat");
    //             $(".productCalculation").css("top", "");
    //             $(".productCalculation").removeClass("bottomReached");
    //         }
    //     }
    //
    //     if(floater > end) {
    //         if(!$(".productCalculation").hasClass("bottomReached") && window.scrollY != 0) {
    //             $(".productCalculation").addClass("bottomReached");
    //             $(".productCalculation").css("top", top + "px");
    //             $(".productCalculation").removeClass("priceboxFloat");
    //         }
    //     } else {
    //         if(!$(".productCalculation").hasClass("bottomReached")) {
    //             $(".productCalculation").removeClass("bottomReached");
    //             $(".productCalculation").css("top", "");
    //         }
    //     }
    //
    // });




    // DOM CHECKER Sticky Price Summary
    $(document).ready(function() {
        let isScrolling = false;  // Variabele om te bepalen of scrollen bezig is

        // Debounce voor de resize event
        let resizeTimer;
        $(window).on('resize', function() {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function() {
                checkStickyPosition();
            }, 500);  // Pas de tijd aan naar behoefte
        });

        // Gebruik van requestAnimationFrame voor scroll-event
        $(window).on('scroll', function() {
            if (!isScrolling) {
                window.requestAnimationFrame(function() {
                    checkStickyPosition();
                    isScrolling = false;
                });
                isScrolling = true;
            }
        });

        // Dezelfde functie aanroepen bij DOMContentLoaded en window load
        $(window).on('DOMContentLoaded load', function() {
            checkStickyPosition();
        });

        function checkStickyPosition() {
            const rect = $(".inView")[0].getBoundingClientRect();
            const end = ($("#orderStart").offset().top) + ($("#orderStart").height());
            const floater = ($(".productCalculation").offset().top) + ($(".productCalculation").height());
            const top = $(".productDesc").height() - $(".productCalculation").height();
            const $productCalculation = $(".productCalculation");

            // Controleer of het element zichtbaar is in de viewport
            if (rect.top >= 64 && rect.left >= 0 && rect.right <= (window.innerWidth || document.documentElement.clientWidth)) {
                if ($productCalculation.hasClass("priceboxFloat")) {
                    $productCalculation.removeClass("priceboxFloat");
                }
            } else {
                if (!$productCalculation.hasClass("priceboxFloat") && Math.abs(rect.top) + 64 < top) {
                    $productCalculation.addClass("priceboxFloat").css("top", "").removeClass("bottomReached");
                }
            }

            // Controleer of het floater element het einde heeft bereikt
            if (floater > end) {
                if (!$productCalculation.hasClass("bottomReached") && window.scrollY != 0) {
                    $productCalculation.addClass("bottomReached").css("top", top + "px").removeClass("priceboxFloat");
                }
            } else {
                if (!$productCalculation.hasClass("bottomReached")) {
                    $productCalculation.removeClass("bottomReached").css("top", "");
                }
            }
        }
    });




    _revert = [];
    $(".btn.cancel").on("click", function() {
        $.each(_revert, function(stock, value) {
            $(".quantity[data-stock='"+value.id+"']").val(value.val);
            $(".mobquantity[data-stock='"+value.id+"']").val(value.val);
        });

        if($(this).closest(".mobQuantityContainer ").length > 0) {
            var val = 0;
            $(this).closest(".quantityDropDown").find(".mobquantity").each(function(index, quantity) {
                if($(quantity).val() != "") {
                    val += parseInt($(quantity).val());
                }
            });
            if(val == 0) {
                val = "Maak uw keuze";
            }
            $(this).closest(".mobQuantityContainer").find(".mobquantity.complete").val(val);
        }

        $(this).closest(".priceColorBox").find(".quantity").keyup();
        closeDropdown();

        // Check for Adds parameters in URL
        var url = window.location.href;
        var containsAd = url.includes("&ad=");

        if(containsAd){
            // Do Nothing
        } else {
            recalcQuantity();
        }

        return false;
    });


    $(".printList li").on("click", function() {
        if(!$(this).closest(".printPosition").hasClass("disabled")) {
            $(this).closest(".printList").find("li").removeClass("active");
            $(this).closest(".printList").find(".fa-square").removeClass("fa-square").addClass("fa-square-o");

            $(this).addClass("active");
            $(this).addClass("active").find(".fa-square-o").removeClass("fa-square-o").addClass("fa-square");

            var pos = $(this).closest(".printList").data("position");
            var group = $(this).closest(".printPosition").data("group");

            var color = $(this).text();

            if($(this).find(".price").data("color") == 0) {
                $(".mobEnrichmentContainer[data-position='" + pos + "'][data-group='" + group + "']").addClass("empty").find(".removeEnrichment").removeClass("show");
            } else {
                $(".mobEnrichmentContainer[data-position='" + pos + "'][data-group='" + group + "']").removeClass("empty").find(".removeEnrichment").addClass("show").find(".colorName").html(color);
            }
            $(".printList[data-position='"+pos+"']").closest(".printPosition").removeClass("disabled");

            if($(this).find(".price").data("color") !== 0) {
                $(".printList[data-position='" + pos + "']").closest(".printPosition[data-group!='" + group + "']").addClass("disabled");
            }
            recalcQuantity();
        }
    });

    $(".noEnrichment").on("click", function() {
        $(".printList li").removeClass("active");
        $(".printList .fa-square").removeClass("fa-square").addClass("fa-square-o");

        $(".printList li:has(\".price[data-color='0']\")").addClass("active");
        $(".printList li:has(\".price[data-color='0']\") .fa-square-o").removeClass("fa-square-o").addClass("fa-square");

        $(".printPosition").removeClass("disabled");
        recalcQuantity();
    });

    $(".showMore").on("click", function() {
        // console.log($(".printPositions .printGroup:not(.recommandPos)").is(":visible"));
        if($(".printPositions .printGroup:not(.recommandPos)").is(":visible")) {
            $(".printPositions .printGroup:not(.recommandPos)").hide();
        } else {
            $(".printPositions .printGroup:not(.recommandPos)").show();
        }
        $(".showMore").toggle();
        recalcQuantity();
    });

    var _clicked = false;
    $(".sampleproduct").on("click", function(event, test) {
        var input = $(this).find(".sampleInput");

        if($(event.toElement).closest(".sampleInput").length == 0 && _clicked == false) {
            $(input).prop("checked", !$(input).prop("checked"));
        }

        _clicked = false;

        var enrichmentInfo = enrichmentsAsString();
        var data = $("#sampleConfigFrom").serialize() + enrichmentInfo;
        $.ajax({
            type:"POST",
            data:data,
            success: function(data) {
                $(".sampleWarning").hide();
                recalcQuantity(false, "#samplePriceCalculation", "#sampleConfigFrom");
            },
            error: function(xhr, textStatus, errorThrown){
                $(".sampleWarning .warningMessages").html(xhr.responseText);
                $(".sampleWarning").show();
            },
            url: "/product/checkSampleCount"
        });
    });

    $(".sampleInput").on("click", function(event) {
        _clicked = true;
    });

    $(".productPrice").on("click", "#placeInCart", function() {
        var enrichmentInfo = enrichmentsAsString();
        var data = $("#productConfigFrom").serialize() + enrichmentInfo;
        submit = $.ajax({
            type:"POST",
            data:data,
            success: function(data) {
                $(".inputQuantity").each(function() {
                    if($(this).find(".quantity").val() > 0) {
                        $(this).trigger("addToCart");
                    }
                });
                $("#productPage").trigger("addedToCart");
                confirm(data);
            },
            url: "/cart/update"
        });
    });

    $("#sampleConfigFrom").on('submit', function(e) {
        e.preventDefault(); // @todo OOK LOGICA UITVOEREN
    });

    $(".placeSampleCart").on("click", function() {
        var data = $("#sampleConfigFrom").serialize();
        $(".sampleWarning").removeClass("blinker");
        submit = $.ajax({
            type:"POST",
            data:data,
            success: function(data) {
                $("#sampleConfigFrom").trigger("addSampleToCart");
                dataLayer.push({
                    event: "sample_AddedToCart"
                });
                window.location = "/checkout/cart";
            },
            error: function(xhr, textStatus, errorThrown){
                $(".sampleWarning .warningMessages").html(xhr.responseText);
                $(".sampleWarning").show();
                $(".sampleWarning").addClass("blinker");
            },
            url: "/cart/update"
        });
    });

    $("#newMargin, #newPrice").on("change", function() {
        recalcQuantity();
    });

    function confirm(data) {
        $("#completedWindow .modal-body").html(data);

        if (data.toLowerCase().indexOf("op aanvraag") >= 0) {
            $("#completedWindow .btn-success").html("Aanvragen");
        } else {
            $("#completedWindow .btn-success").html("Bestellen");
        }

        $("#completedWindow").modal("show");
        var count = $("#dropdownMenu1 .badge").html();
        $("#dropdownMenu1 .badge").html(1+parseInt(count));
        $.ajax("/cart/refresh").done(function(html) {
            $(".dropdown-menu.cartView, .mobileCartContainer").html(html);
            var quantity = parseInt($(html).find(".recentAdded").length);

            if(quantity == 0) {
                $(".ordercount").addClass("empty");
            } else {
                $(".ordercount").removeClass("empty");
            }

            var quantityHTML = quantity === 1 ? "1 item in winkelwagen" : quantity + " items in winkelwagen";
            $(".ordercounter").html(quantity);
        });
    }

    $(".mainImageArrow").on("click", function() {
        var direction = $(this).data("direction");
        if(direction == "previous") {
            mainImagePrevious();
        } else if(direction == "next") {
            mainImageNext();
        }
    });

    function mainImagePrevious() {
        var splitHref = $("#mainpic").attr("href").split("/");
        var id = splitHref[3];

        var previous = $(".productThumbnail[data-imageid='"+id+"'], .thumbnailHidden[data-imageid='"+id+"']").prev();

        if(!$(previous).hasClass("productThumbnail") && !$(previous).hasClass("thumbnailHidden")) {
            previous = $("#thumbs").find("div:last").prev();
        }

        $("#mainpic").attr("href", $(previous).find("a").attr("href"));
        $("#mainpic").find("img").attr("src", $(previous).find("a").attr("href"));
    }

    function mainImageNext() {
        var splitHref = $("#mainpic").attr("href").split("/");
        var id = splitHref[3];

        var next = $(".productThumbnail[data-imageid='"+id+"'], .thumbnailHidden[data-imageid='"+id+"']").next();

        if(!$(next).hasClass("productThumbnail") && !$(next).hasClass("thumbnailHidden")) {
            next = $("#thumbnail-0");
        }

        $("#mainpic").attr("href", $(next).find("a").attr("href"));
        $("#mainpic").find("img").attr("src", $(next).find("a").attr("href"));
    }



    /** Function: Sidebar open **/
    function activateSidebar() {

        // Activate background overlay
        document.getElementById('bgOverlay').classList.toggle('disabled');

        // Activate Sidebar in screen
        document.getElementById('slideinContainer').classList.toggle('disabled');

        // Close sidebar
        document.querySelector('#slideinClose').addEventListener("click", closeSidebar);
        document.querySelector('#bgOverlay').addEventListener("click", closeSidebar);

    }

    /** Function: Sidebar close **/
    function closeSidebar() {
        document.getElementById('bgOverlay').classList.toggle('disabled');
        document.getElementById('slideinContainer').classList.toggle('disabled');
    }




    // Alt sidebar offerte
    $(".productPrice").on("click", "#onlineInvoice2",  function() {

        // fa fa-toggle-off head





        activateSidebar();

        var enrichmentInfo = enrichmentsAsString();
        var data = $("#productConfigFrom").serialize() + enrichmentInfo;
        var id=$("#addressSelection").val();
        $.ajax({
            type: "POST",
            url: "/product/offerte",
            data: data,
        }).done(function(data) {
            $("#myModalOnlinePDF2 .body").html(data);
            $("#myModalOnlinePDF2 .modal-footer").html($(data).find("#offerteButtons").html());
            $("#myModalOnlinePDF2 .modal-body").html(data);
            $("#myModalOnlinePDF2 .modal-body").find("#offerteButtons").remove();
            $("#myModalOnlinePDF2").innerHTML = data;

            // Replace html content
            var htmlContent = document.querySelector('#sidebar-list-value');
            if(htmlContent) {

                // Check BTW Toggle value
                var checkBTWtoggle = document.querySelector('.fa.fa-toggle-on.head');
                if(checkBTWtoggle) {
                    var btwValue = document.querySelector('.btwPrice-yes');
                    btwValue.classList.add('active');
                } else {
                    var btwValue = document.querySelector('.btwPrice-no');
                    btwValue.classList.add('active');
                }

                // Replace html
                document.querySelector('#sidebar-selector').innerHTML = htmlContent.innerHTML;
            }

        });
    });



    // Alt sidebar offerte submit
    $("#myModalOnlinePDF2").on("click", "#emailInvoice", function(event) {

        var dataCheck = false;
        var firstName = document.getElementById('firstName');
        var lastName = document.getElementById('lastName');
        var email = document.getElementById('email');




        if(firstName.value == ''){
            firstName.classList.add("offerte-input-error");
        } else {
            firstName.classList.remove("offerte-input-error");
        }

        if (lastName.value == '') {
            lastName.classList.add("offerte-input-error");
        } else {
            lastName.classList.remove("offerte-input-error");
        }

        if(email.value == '') {
            email.classList.add("offerte-input-error");
        } else {
            email.classList.remove("offerte-input-error");
        }

        var allForms = document.querySelectorAll('.selectBox.offerte-input-error');

        if(allForms.length == 0) {
            dataCheck = true;
        } else {
            dataCheck = false;
        }

        if(dataCheck) {

            $("#emailInvoice").hide();
            $("#emailInvoiceWait").show();
            var enrichmentInfo = enrichmentsAsString();
            var data = $("#productConfigFrom, #emailInvoice-form").serialize() + enrichmentInfo;

            $.post("/product/createInvoice", data, function(data,status,xhr) {
                if(status == "success") {

                    // GTM Values
                    document.getElementById("user_email").innerHTML = email.value;
                    document.getElementById("tel_GAds").innerHTML = quotation_phone.value;
                    document.getElementById("firstName_GAds").innerHTML = firstName.value;
                    document.getElementById("lastName_GAds").innerHTML = lastName.value;

                    // GTM Event
                    if(enrichmentInfo){
                        dataLayer.push({
                            event: "quotation_inprint"
                        });
                    } else {
                        dataLayer.push({
                            event: "quotation_noprints"
                        });
                    }
                }

                if(typeof fbq !== "undefined") {
                    fbq('track', 'Lead', {
                        content_name: "Offerte Aanvraag",
                        currency: "Offerte",
                    });
                }
                $("#contactConfirm").show();
                $("#contact-sideform").hide();
                $("#contactF").hide();


                $("#closeMenu").click(function(){
                    document.getElementById('bgOverlay').classList.toggle('disabled');
                    document.getElementById('slideinContainer').classList.toggle('disabled');
                });

            });
        }
    });




    animation = null;
    $('body').on("click", "[href^='#']:not([href='#'])", function() {
        var target = $(this).attr("href");
        target = target.length ? $(target) : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
            if(animation !== null) {
                animation.stop();
            }
            animation = $('html, body').animate({
                scrollTop: target.offset().top-55
            }, 750);
            return false;
        }
    });

    $("[data-image-tooltip]").each(function() {
        if($(this).data("image-tooltip") == "") {
            return;
        }

        $(this).tooltip({
            items: "[data-image-tooltip]",
            content: '<img style="max-width: '+ ($(this).data("image-tooltip-width") || 125) +'px; max-height: '+ ($(this).data("image-tooltip-height") || 125) +'px;" src="'+$(this).data("image-tooltip")+'" />',
            tooltipClass: "img-tooltip",
        });
    })




    // $("#myModalOnlinePDF").on("click", "#emailInvoice", function(event) {
    //
    //
    //     alert('MODAL BOX TYPE B????')
    //
    //     // Temp: Remove NEW AB Form
    //     var newInvoiceForm = document.querySelector('#sidebar-offerte');
    //     if (newInvoiceForm) {
    //         newInvoiceForm.parentNode.removeChild(newInvoiceForm);
    //     }
    //
    //     $("#emailInvoice").hide();
    //     $("#emailInvoiceWait").show();
    //     var enrichmentInfo = enrichmentsAsString();
    //     var data = $("#productConfigFrom, #emailInvoice-form").serialize() + enrichmentInfo;
    //
    //     $.post("/product/createInvoice", data, function() {
    //         // GTM Event
    //         dataLayer.push({'event': 'GoalComplete_OnlineInvoice'});
    //         if(typeof fbq !== "undefined") {
    //             fbq('track', 'Lead', {
    //                 content_name: "Offerte Aanvraag",
    //                 currency: "Offerte",
    //             });
    //         }
    //         $("#contactConfirm").show();
    //         $("#contactF").hide();
    //     });
    // });






    $('[data-toggle="tooltip"]').tooltip();

    $("[data-popup]").on("click", function() {
        // console.log("#"+$(this).data("popup"));
        $("#Modal"+$(this).data("popup")).modal("show");
    });

    function splitDate(date, format) {
        var formatS = format.split(/\/|\-|\./);

        var dd, mm, yy;
        $.each(formatS, function (key, value) {
            if(value == "dd") {
                dd = key;
            } else if(value == "mm") {
                mm = key;
            } else if(value == "yy" || value == "yyyy") {
                yy = key;
            }
        });
        var dateS = date.split(/\/|\-|\./);

        return [dateS[dd], dateS[mm], dateS[yy]];
    }

    $(".productPrice").on( "mouseenter", " #offetTooltip", function() {
        $(".offsetTooltip").slideDown("fast");
        $(".offsetTooltip").css("top", $("#offetTooltip").offset().top - $(".productCalculation").offset().top + 32);
    });

    $(".productPrice").on( "mouseout", "#offetTooltip", function() {
        $(".offsetTooltip").slideUp("fast");
    });






    // Offerte sidebar
    document.addEventListener("click", function(event) {
        var clickedElement = event.target;

        if (clickedElement.classList.contains("alt_button")) {
            var myInterval = setInterval(myTimer, 400);

            function myTimer() {

                // UI Elements
                var DOMelement = $(".sidebar-offerte-message2").html();
                var DOMelementPrint = $(".offerte-print").html();

                // UI Found No Print
                if(DOMelement) {
                    myStop();

                    // Check NL of DE
                    var browserHost = location.host;
                    if(browserHost == "allgifts.de"){
                        var submitButton = $("#emailInvoice").html("Angebot ohne druck empfangen");
                    } else {
                        var submitButton = $("#emailInvoice").html("Ontvang offerte zonder bedrukking");
                    }

                    var newHTMLCodeNew = $(".sidebar-offerte-message2").html();
                    var placeHolder = $("#selectorNoprintMessage").addClass( "noPrintMessage" );
                    var placeHolder = $("#selectorNoprintMessage").html(newHTMLCodeNew);

                    // UI Found With Print
                } else if (DOMelementPrint) {
                    myStop();
                }
            }

            function myStop() {
                clearInterval(myInterval);
            }
        }

        // Close Sidebar an Scroll to Print Element
        if(clickedElement.classList.contains("noPrintLink")){

            document.getElementById('bgOverlay').classList.toggle('disabled');
            document.getElementById('slideinContainer').classList.toggle('disabled');
            scroller();
        }

    });



    function scroller() {
        window.scroll({
            top: 2500,
            left: 0,
            behavior: 'smooth'
        });

        // Scroll certain amounts from current position
        window.scrollBy({
            top: 100, // could be negative value
            left: 0,
            behavior: 'smooth'
        });

        // Scroll to a certain element
        document.querySelector('.containerCalculating').scrollIntoView({
            behavior: 'smooth'
        });
    }
    // END Offerte sidebar


});

