(function ($, window, document, undefined) {
    'use strict';

    var initFluidVideos = function () {
            $('iframe[src*=\'youtube.com\'], iframe[src*=\'vimeo.com\']').each(function () {
                $(this).wrap('<div class="video-container"></div>');
                $(this).parent('.video-container').addClass('active');
            });
        },
        initRandomFunctionality = function () {
            $(document).foundation();
        },
        getHeaderHeight = function () {
            var $header = $('.header');
            var $wpAdminBar = $('#wpadminbar');
            var wpAdminBarHeight = ($wpAdminBar.length > 0) ? $wpAdminBar.outerHeight() : 0;
            var headerHeight = $header.outerHeight();

            return (headerHeight + wpAdminBarHeight);
        },
        initBlockArrowScrollToNextSection = function () {
            var $arrow = $('.block__arrow');
            $arrow.on('click', function () {
                var $block = $(this).closest('.block, .hero');
                var $blockNext = $block.next();
                $('html, body').animate({scrollTop: $blockNext.offset().top - getHeaderHeight()}, 1000);
            });
        },
        formatPrice = function (price) {
            var formattedPrice = customData.priceDisplay.currencySymbol + ' ';
            price = parseFloat(price);

            price = price.toFixed(customData.priceDisplay.decimals);
            formattedPrice = formattedPrice + price.toString().replace('.', customData.priceDisplay.separator);

            return formattedPrice;
        },
        messageAddedToCart = function (productId) {
            var topOffset = getHeaderHeight() + 15;

            $.ajax({
                url: customData.ajaxURL,
                type: 'POST',
                dataType: 'JSON',
                data: {
                    action: 'vo_added_to_cart_message',
                    security: customData.ajaxSecurity,
                    productId: productId,
                },
                success: function (response) {
                    var output = (typeof response.output !== 'undefined') ? response.output : '';
                    if (output) {
                        $('.vo-woocommerce-message').remove();
                        $('.header').after(output);
                        $('.vo-woocommerce-message').css({
                            'top': topOffset,
                            'opacity': 0
                        });
                        $('.vo-woocommerce-message').animate({opacity: 1}, 300);

                        // Close on click
                        $('.vo-woocommerce-message .woocommerce-message__close').on('click', function () {
                            $('.vo-woocommerce-message').animate({opacity: 0}, 300, function () {
                                $('.vo-woocommerce-message').remove();
                            });
                        });

                        // Close after 10s
                        setTimeout(
                            function () {
                                $('.vo-woocommerce-message').animate({opacity: 0}, 300, function () {
                                    $('.vo-woocommerce-message').remove();
                                });
                            },
                            10000
                        );
                    }
                }
            });
        },
        initHeaderScroll = function () {
            var $header = $('.header');
            var scrollingClass = 'header--scrolling';
            var $cart = $('.vo-cart');

            if (!$header.length) {
                return;
            }

            // Check top offset on load
            if ($(window).scrollTop() !== 0) {
                $header.addClass(scrollingClass);
            } else {
                $header.removeClass(scrollingClass);
            }

            // Check top offset on scroll
            $(document).scroll(function () {
                if ($(window).scrollTop() !== 0) {
                    $header.addClass(scrollingClass);
                } else {
                    $header.removeClass(scrollingClass);
                }
            });

            // Handle scroll for fixed cart div
            if ($cart.length) {
                $cart.on('scroll', function () {
                    if ($cart.scrollTop() !== 0) {
                        $header.addClass(scrollingClass);
                    } else {
                        $header.removeClass(scrollingClass);
                    }
                });
            }
        },
        initAnimations = function () {
            var io = new IntersectionObserver(function (items) {
                for (var i = 0; i < items.length; i++) {
                    if (items[i].intersectionRatio > 0) {
                        items[i].target.setAttribute('data-animated-visible', '');
                        io.unobserve(items[i].target);
                    }
                }
            }, {threshold: [0.3]});

            // Elements to be observed
            var animatedElements = document.querySelectorAll('[data-animated]');
            for (var i = 0; i < animatedElements.length; i++) {
                io.observe(animatedElements[i]);
            }
        },
        initAgeVerification = function ($container) {
            if (!$container) {
                return;
            }

            var form = $container.find('form');

            if (!form) {
                return;
            }

            form.submit(function (e) {
                e.preventDefault();

                var limit = form.data('age-limit');
                var month = form.find('input[name="month"]').val();
                var year = form.find('input[name="year"]').val();
                var $error = $('.age-verification__error');
                var remember = form.find('input[name="remember"]').is(':checked');

                if (!limit || !month || !year) {
                    return false;
                }

                var currentTime = new Date().getTime();
                var minimumTime = new Date((parseInt(year, 10) + parseInt(limit, 10)), parseInt(month - 1, 10), 1);
                var oldEnough = currentTime > minimumTime;

                if (oldEnough) {
                    $container.fadeOut(200);

                    initAnimations();

                    if (remember) {
                        localStorage.setItem('vo-age-verified', oldEnough);
                    }
                } else {
                    $error.removeAttr('hidden');
                }
            });
        },
        initHeroThumbLazyLoad = function ($thumb) {
            if (!$thumb) {
                return;
            }

            // Get the URL of the full image.
            var fullImageSrc = $thumb.data('vo-full-image');

            if (fullImageSrc) {
                // Create a dummy image to trigger the image loading.
                var dummyImage = new Image();

                // Hide dummy image.
                dummyImage.style.display = 'none';
                // Set dummy img source to full image.
                dummyImage.src = fullImageSrc;
                // If dummy image is loaded, fade in the full hero image.
                dummyImage.onload = function () {
                    // Remove thumb and dummy image.
                    $thumb.fadeOut();
                    dummyImage.remove();
                };
            }
        },
        initSlider = function ($slider) {
            if (!$slider) {
                return;
            }

            var $items = $slider.find('.slider__item');
            var activeClass = 'slider__item--active';

            if (!$items.length) {
                return;
            }

            function setBackgroundColor(color) {
                if (!color) {
                    return;
                }

                // Remove old background color
                $slider.removeClass(function (index, className) {
                    return (className.match(/(^|\s)slider--background-color-\S+/g) || []).join(' ');
                });

                $slider.addClass('slider--background-color-' + color);
            }

            setBackgroundColor($($items[0]).data('background-color'));

            function setActiveSliderItem($target, scroll) {
                $target = $target || $($items[0]);

                if ($target.hasClass(activeClass)) {
                    return;
                }

                // Set background color
                var bg = $target.data('background-color');

                // Add new background color if it's available.
                if (bg) {
                    setBackgroundColor(bg);
                }

                // Set active class
                $items.removeClass(activeClass);
                $target.addClass(activeClass);

                if (scroll) {
                    var offset = $target.offset().top - getHeaderHeight();

                    $('html').animate({scrollTop: offset}, 300);
                }
            }

            setActiveSliderItem();

            $items.click(function () {
                setActiveSliderItem($(this), false);
            });
        },
        initQuantityButtons = function (wrapper) {
            var $quantityButtons = $(wrapper).find('.quantity__change');
            var $input = $(wrapper).find('.quantity__input');
            var $updateCartButton = $('.vo-cart__update');

            if (!$quantityButtons.length || !$input.length) {
                return;
            }

            var min = $input.attr('min') || 1;

            $quantityButtons.click(function (event) {
                event.preventDefault();

                var val = $input.val();

                if ($(this).hasClass('quantity__change--plus')) {
                    $input.val(parseFloat(val, 10) + 1);
                } else {
                    var newValue = parseFloat(val, 10) - 1;
                    newValue = newValue < min ? min : newValue;

                    $input.val(newValue);
                }

                if ($updateCartButton.length) {
                    $updateCartButton.prop('disabled', false);
                    $updateCartButton.trigger('click');
                }
            });
        },
        updateCartCount = function (count) {
            var $cartCounter = $('.header__cart-content-count .counter');
            var $cartAnchor = $('.header__cart-content-count .counter .header__link');
            var $cartAnchorElementCounter = $('.header__cart-content-count .counter .header__link.header__link--counter');
            var cartCount = $cartCounter.data('cart-count');
            var cartCountTotal = parseInt(cartCount) + parseInt(count);
            var headerLinkCounterClass = 'header__link--counter';
            var isUpdated = 'is-updated';
            $cartCounter.data('cart-count', cartCountTotal);

            if (cartCountTotal > 0) {
                $cartAnchor.addClass(headerLinkCounterClass);
                $cartAnchor.html(cartCountTotal);
                $cartAnchorElementCounter.addClass(isUpdated);
                setTimeout(function () {
                    $cartAnchorElementCounter.removeClass(isUpdated);
                }, 500);
            } else {
                $cartAnchor.removeClass(headerLinkCounterClass);
            }
        },
        initAddToCart = function (wrapper) {
            var $button = $(wrapper).find('.vo-add-to-cart__button');
            var $productPrice = $(wrapper).find('.products__price-amount');
            var $productWholesalePrice = $(wrapper).find('.products__wholesale-price-amount');
            var $buttonPrice = $button.find('.products__button-price');
            var $buttonText = $button.find('.products__button-text');
            var initialButtonText = $buttonText.html();
            var $quantity = $(wrapper).find('.quantity__input');

            // Add to Cart button
            $button.click(function (event) {
                event.preventDefault();

                var quantity = $quantity.val();
                var $button = $(this);
                var input = $(wrapper).find('input:checked');
                var productId = $(this).data('product-id');
                var variationId = $(input).data('variation-id');
                var attribute = $(input).data('attribute-name');
                var attributeValue = $(input).val();

                // product can also be a simple product, so do not check on variationId
                if($(this).closest('.products-list__item').hasClass('products-list__item--single')) {
                    if (!quantity || !productId || !input ) {
                        $button.html('Something went wrong!');
                    }
                } else {
                    if (!quantity || !productId || !input || !attribute || !attributeValue) {
                        $button.html('Something went wrong!');
                    }
                }

                $.ajax({
                    url: customData.ajaxURL,
                    type: 'POST',
                    dataType: 'JSON',
                    data: {
                        action: 'vo_add_to_cart',
                        security: customData.ajaxSecurity,
                        quantity: quantity,
                        id: productId,
                        variationId: variationId,
                        attribute: attribute,
                        attributeValue: attributeValue
                    },
                    success: function (response) {
                        if (response.success) {
                            $buttonText.html('Added to your cart!');
                            $button.prop('disabled', true);

                            updateCartCount(quantity);
                            messageAddedToCart(productId);
                        }
                    }
                });
            });

            // Quantity change
            $(wrapper).on('click', 'input[type="radio"], .quantity__change', function () {
                var wr = $(wrapper);
                var input = wr.find('input:checked');
                var price = $(input).data('variation-price');
                var wholesalePrice = $(input).data('variation-wholesale-price');
                var msrpPrice = null;
                var quantity = $quantity.val();

                // Check if it is a product from the product list, which has another way of changing prices
                if(wr.hasClass('products-list__item--single')) {
                    wholesalePrice = formatPrice(wr.data('price-wholesale') * quantity);
                    msrpPrice = formatPrice(wr.data('price-msrp') * quantity);

                    wr.find('.products__price-amount').html(msrpPrice);
                    wr.find('.products__wholesale-price-amount').html(wholesalePrice);
                } else {
                    price = formatPrice(price * quantity);
                    wholesalePrice = formatPrice(wholesalePrice * quantity);

                    $buttonText.html(initialButtonText);
                    $buttonPrice.html(price);
                    $productPrice.html(price);
                    $productWholesalePrice.html(wholesalePrice);
                    $button.prop('disabled', false);
                }
            });

            // Handle product variation in figcaption
            $(document).on('click', '.product__information .products__attribute-label', function (event) {
                event.stopImmediatePropagation();
                var labelOptionId = $(this).data('option-id');
                var $captionSpan = $('.product__images .product__image-caption span');
                var $captionSpanActive = $('.product__images .product__image-caption span[data-option-id="' + labelOptionId + '"]');

                $captionSpan.removeClass('is-active');
                $captionSpanActive.addClass('is-active');
            });
        },
        initShowProductInfo = function (wrapper) {
            $(wrapper).click(function () {
                var wrap = $(this);
                var ajaxBox = wrap.closest('.products-list__item').find('.products-list__item--ajax');

                // Loop over all product list items
                wrap.closest('.products-list').find('.products-list__item').each(function () {
                    var listItem = $(this).closest('.products-list__item');

                    if (wrap.closest('.products-list__item').data('productid') === listItem.data('productid')) {
                        listItem.toggleClass('active');
                    } else {
                        listItem.removeClass('active');
                    }
                });

                if (!ajaxBox.hasClass('loaded')) {
                    $.ajax({
                        url: customData.ajaxURL,
                        type: 'POST',
                        dataType: 'JSON',
                        data: {
                            action: 'vo_product_show_more_info',
                            security: customData.ajaxSecurity,
                            id: wrap.closest('.products-list__item').data('productid')
                        },
                        success: function (response) {
                            console.log(response);
                            if (response.success) {
                                ajaxBox.addClass('loaded').html(response.data);
                            }
                        }
                    });
                }

            });
        },
        initMobileNav = function () {
            var mobileNavTrigger = $('.header__navigation-mobile-trigger');
            var mobileNavContainer = $('.header__navigation-mobile');
            $(mobileNavTrigger).on('click', function () {
                $(this).toggleClass('open');
                $(mobileNavContainer).slideToggle(250);
            });
        },
        initSingleProductSwitchSliderWithProduct = function () {
            var $blockProduct = $('.single-product .block--product');
            var $blockSlider = $('.single-product .block--slider');
            var orderHasChanged = false;
            var smallIndex = 0;
            var largeIndex = 0;

            if ($blockProduct.length && $blockSlider.length) {
                $(window).on('resize load', function () {
                    if (window.Foundation.MediaQuery.is('small only')) {
                        if (smallIndex === 0) {
                            $blockSlider.insertBefore($blockProduct);
                            orderHasChanged = true;
                        }
                        largeIndex = 0;
                        smallIndex++;
                    } else {
                        if (largeIndex === 0 && orderHasChanged) {
                            $blockSlider.insertAfter($blockProduct);
                        }
                        smallIndex = 0;
                        largeIndex++;
                    }
                });
            }
        },
        initTabs = function () {
            var $tabLinks = $('.product-block__tab-link');
            var $tabs = $('.product-block__tab-content');

            $tabLinks.on('click', function (e) {
                e.preventDefault();

                if ($(this).attr('aria-selected') === 'true') {
                    return;
                }

                var $target = $($(this).attr('href'));

                $tabs.attr('aria-hidden', 'true');
                $target.attr('aria-hidden', 'false');

                $tabLinks.attr('aria-selected', 'false');
                $(this).attr('aria-selected', 'true');
            });
        };

    // On document ready
    $(function () {
        initRandomFunctionality();
        initFluidVideos();
        initMobileNav();

        initBlockArrowScrollToNextSection();
        initSingleProductSwitchSliderWithProduct();
        /**
         * Initialize header scroll.
         */
        initHeaderScroll();

        /**
         * Initialize age verification
         */
        var $ageVerification = $('.age-verification');

        if ($ageVerification.length) {
            initAgeVerification($ageVerification);
        }

        // Show animations if the age modal is hidden
        if (localStorage.getItem('vo-age-verified') === 'true') {
            initAnimations();
        }

        /**
         * Fade in full hero image over blurry image
         */
        var $heroThumb = $('.hero__thumb');

        if ($heroThumb.length) {
            initHeroThumbLazyLoad($heroThumb);
        }

        /**
         * Slider
         */
        var $slider = $('.slider');

        if ($slider.length) {
            initSlider($slider);
        }

        /**
         * Quantity buttons
         */
        var $quantityButtons = $('.quantity');

        if ($quantityButtons.length) {
            $quantityButtons.each(function () {
                initQuantityButtons(this);
            });
        }

        /**
         * Custom Add To Cart button
         */
        var $addToCart = $('.vo-add-to-cart, .products-list__item');

        if ($addToCart.length) {
            $addToCart.each(function () {
                initAddToCart(this);
            });
        }

        /**
         * Show product info in wholesale list
         */
        var showProductInfo = $('.products-list__title, .products-list__price');

        showProductInfo.each(function () {
            initShowProductInfo(this);
        });

        /**
         * Initialize tabs.
         */
        initTabs();

    });
})(jQuery, window, document);
