jQuery(document).ready(function($) {
    var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
    var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
    // setTimeout(function() {
    //     $('.count-up-inview.active').countTo({
    //         onComplete: (
    //             $(this).find('.count-up-inview.active').removeClass('active')
    //         // setTimeout(function() {
    //         //     module_parent.find('.badge_counter .circle').addClass('animated tada');
    //         // }, counter_completion)
    //         )
    //     });
    // }, 5000);
    // $('.count-up-inview.active').each(function(){
    //     var module_parent = $(this);
    //     var count_up_item = $(this);
    //     new Waypoint.Inview({
    //         element: count_up_item,
    //         entered: function(down) {
    //             setTimeout(function() {
    //                 $('.count-up-inview.active').countTo({
    //                     onComplete: (
    //                         count_up_item.removeClass('active')
    //                     )
    //                 });
    //             }, 300);
    //         }
    //     });
    // });
    // remove class from product page hero graphics to animate in
    $(window).load(function() {
        // $('#hero .hero_graphic_item').each(function(i){
        //     var hero_item = $(this);
        //     setTimeout(function() {
        //         hero_item.removeClass('not_active');
        //     }, 200*i);
        //     setTimeout(function() {
        //         hero_item.removeClass('hero_graphic_item');
        //     }, 5000);
        // });
        // show get 2 dollars back popup on page load
        // setTimeout(function() {
            // $('body, html').addClass('popup-open');
            // $('#popup-get_2_back.popup-overlay').addClass('popup-open');
        // }, 300);
    });
    // sort retailer list alphabeticallys
    // var select2_alphabetical_sorter = function(data) {
    //    return data.sort(function(a,b){
    //        a = a.text.toLowerCase();
    //        b = b.text.toLowerCase();
    //        if(a > b) {
    //            return 1;
    //        } else if (a < b) {
    //            return -1;
    //        }
    //        return 0;
    //    });
    // };
    // // initialize select dropdown search
    // $('.retailer_dropdown').select2({
    //     sorter: select2_alphabetical_sorter,
    //     placeholder: "*Enter Store Name",
    //     allowClear: true,
    //     selectOnClose: false,
    //     dropdownCssClass: "select2_retailer_dropdown",
    //     maximumSelectionLength: 1,
    // });
    // open store locator / maps search on submit
    $('form.retailer_form input[type="submit"]').click(function (e) {
        e.preventDefault();
        var link_url = $(this).closest('.retailer_form').find('.retailer_dropdown').attr('data-store-url');
        var option_value = $(this).closest('.retailer_form').find('.retailer_dropdown').find(':selected').val();
        var search_query = option_value.replace('\'', '').replace(' ', '+');
        var search_query = 'https://maps.google.com/?q='+search_query+'';
        window.open(search_query, '_blank');
        // if(link_url && link_url.length > 0) {
        //     window.open(link_url, '_blank');
        // } else {
        //     alert('This retailer does not have a website');
        // }
    });
    function YouTubeGetID(url){
      var ID = '';
      url = url.replace(/(>|<)/gi,'').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
      if(url[2] !== undefined) {
        ID = url[2].split(/[^0-9a-z_\-]/i);
        ID = ID[0];
        }
        else {
            ID = url;
        }
        return ID;
    }
       // add html for youtube videos
    $('#videos .video_youtube').each(function(){
        var youtube_id = $(this).attr('data-attr-yt-id');
        $(this).html('\
            
\
            \
        ');
    });
    // hide poster image on click for youtube video
    $('#watch_video .video_youtube .poster_thumbnail').click(function(e){
        e.preventDefault();
        $(this).hide();
        // var youtube_id = $(this).closest('.video_youtube').attr('data-youtube-id');
        var youtube_id = YouTubeGetID($(this).closest('.video_youtube').attr('data-youtube-url'));
        // $(this).closest('.video_youtube').find('iframe').attr('src', 'https://www.youtube.com/embed/'+youtube_id+'?vq=hd1080&modestbranding=1&autohide=1&showinfo=0&controls=1&autoplay=1&rel=0enablejsapi=1&html5=1')
        $(this).after('')
    });
    // // carousel before after photos
    // var carousel_before_after = $(".carousel_before_after");
    // carousel_before_after.owlCarousel({
    //     loop:true,
    //     margin:24,
    //     nav:true,
    //     dots:true,
    //     items: 2,
    //     slideBy: 1,
    //     mouseDrag: true,
    //     autoHeight: true,
    //     touchDrag: true,
    //     freeDrag: false,
    //     autoplay:true,
    //     URLhashListener:false,
    //     autoplayTimeout:4500,
    //     smartSpeed: 3000,
    //     autoplayHoverPause: false,
    //     responsiveClass:true,
    //     responsive:{
    //         0:{
    //             items:1,
    //         },
    //         520:{
    //             items:1,
    //         },
    //         768:{
    //             items:2,
    //         }
    //     }
    // });
    // carousel videos
    var carousel_videos = $(".carousel_videos");
    carousel_videos.owlCarousel({
        loop:false,
        margin:0,
        nav:true,
        dots:true,
        items: 1,
        slideBy: 1,
        mouseDrag: true,
        autoHeight: false,
        touchDrag: false,
        freeDrag: false,
        autoplay:false,
        URLhashListener:false,
        autoplayTimeout:6000,
        smartSpeed: 700,
        autoplayHoverPause: false
    });
    // carousel videos
    var carousel_reviews = $(".carousel_reviews");
    carousel_reviews.owlCarousel({
        loop:true,
        margin:5,
        nav:false,
        dots:true,
        items: 2,
        slideBy: 1,
        mouseDrag: true,
        autoHeight: false,
        touchDrag: true,
        freeDrag: false,
        responsive:{
            0:{
                items:1
            },
            768:{
                items:2
            }
        },
        autoplay:true,
        URLhashListener:false,
        autoplayTimeout:6000,
        smartSpeed: 700,
        autoplayHoverPause: false
    });
    // carousel videos
    var carousel_products = $(".carousel_products");
    carousel_products.owlCarousel({
        loop:true,
        margin:15,
        nav:true,
        dots:true,
        items: 3,
        slideBy: 1,
        mouseDrag: true,
        autoHeight: true,
        touchDrag: true,
        freeDrag: false,
        autoplay:true,
        URLhashListener:false,
        // autoplayTimeout:12000,
        autoplayTimeout:2500,
        smartSpeed: 1500,
        autoplayHoverPause: false,
        rewind: true,
        // afterMove: moved,
        responsive:{
            0:{
                items:1
            },
            768:{
                items:2
            },
            1199:{
                items:3
            }
        }
    });
    // function moved() {
    //     var owl_moved = $(".carousel_products").data('owl.carousel')
    //     if (owl_moved.currentItem + 1 === owl_moved.itemsAmount) {
    //         alert('THE END');
    //         $('.carousel_products').trigger('to.owl.carousel', [0, 100]);
    //     }
    // }
    // autoplay carousel when user scrolls to section
    // $('#products').each(function(){
    //     var this_item = $(this);
    //     var appear_item_start = $('#products .carousel_wrapper');
    //     new Waypoint.Inview({
    //         element: appear_item_start,
    //         enter: function(direction) {
    //             $('.carousel_products').data('owl.carousel').options.autoplay = true;
    //             $('.carousel_products').data('owl.carousel').options.autoplayTimeout = 10000;
    //             $('.carousel_products').trigger( 'refresh.owl.carousel' );
    //             // alert('enter carousel');
    //         },
    //         exit: function(direction) {
    //            $('.carousel_products').trigger('to.owl.carousel', [0, 100]);
    //            $('.carousel_products').data('owl.carousel').options.autoplayTimeout = 10000;
    //            $('.carousel_products').data('owl.carousel').options.autoplay = false;
    //         }
    //     });
    // });
    // owl.owlcarousel2_filter( '.blue' );
    $( '#products .filter_wrapper .filter_inner' ).on( 'click', '.btn', function(e) {
        e.preventDefault();
        var $item = $(this);
        var filter = $item.data( 'owl-filter' );
        $item.addClass( 'active' ).siblings().removeClass( 'active' );
        if (!$(this).hasClass('btn-all')) {
            $(this).closest('.carousel_wrapper').addClass('hide-clones');
            // $(this).closest('.carousel_wrapper').find('.owl-item.cloned').remove();
            // carousel_products.trigger('change.owl.carousel', {
            //   loop: false
            // });
            // carousel_products.trigger('refresh.owl.carousel');
        } else {
            $(this).closest('.carousel_wrapper').removeClass('hide-clones');
            // $(this).closest('.carousel_wrapper').find('.owl-item.cloned').remove();
            // carousel_products.trigger('change.owl.carousel', {
            //   loop: false
            // });
            // carousel_products.trigger('refresh.owl.carousel');
        }
        // setTimeout(function() {
            carousel_products.owlcarousel2_filter( filter );
        // }, 300);
    });
    // carousel product mobile
    var carousel_product_mobile = $(".carousel_product_mobile");
    carousel_product_mobile.owlCarousel({
        loop:true,
        margin:0,
        nav:true,
        dots:true,
        items: 1,
        slideBy: 1,
        mouseDrag: true,
        autoHeight: false,
        touchDrag: false,
        freeDrag: false,
        autoplay:true,
        URLhashListener:false,
        autoplayTimeout:6000,
        smartSpeed: 700,
        autoplayHoverPause: false
    });
    var howtouse_carousel = $("#how_to_use .steps_wrapper");
    if (viewportWidth <= 767) {
        start_howtouse_carousel();
    }
    $(window).on('resize', function(){
      var win = $(this); //this = window
      if (win.width() <= 767) {
        start_howtouse_carousel();
    } else {
        stop_howtouse_carousel();
    }
});
    function start_howtouse_carousel(){
        var howtouse_carousel = $("#how_to_use .steps_wrapper");
        howtouse_carousel.owlCarousel({
          loop:false,
            margin:0,
            nav:true,
            dots:true,
            items: 1,
            slideBy: 1,
            mouseDrag: true,
            autoHeight: false,
            touchDrag: true,
            freeDrag: false,
            autoplay:false,
            URLhashListener:false,
            autoplayTimeout:6000,
            smartSpeed: 700,
            autoplayHoverPause: false
      });
    }
    function stop_howtouse_carousel() {
        var howtouse_carousel = $("#how_to_use .steps_wrapper");
        howtouse_carousel.trigger('destroy.owl.carousel');
        howtouse_carousel.addClass('off');
    }
    // faq section question / answer accordion toggle
    $('.questions_wrapper ul li .question').click(function (e) {
        e.preventDefault();
        // $(this).closest('ul').find('li .answer').toggle();
        $(this).closest('li').find('> .answer').slideToggle(300);
        $(this).closest('li').toggleClass('open');
    });
    // popup overlay trigger on link click
    $('.popup_link_trigger').click(function(e) {
        e.preventDefault();
        var link_id = $(this).attr('href')
        var link_id = link_id.replace('#', '')
        $('body, html').addClass('popup-open');
        $('.popup-overlay--video#'+link_id+'').addClass('popup-open');
    });
    // close popup window
    $('.popup-overlay .close-button').click(function(e) {
        e.preventDefault();
        var target = $(e.target);
        $('body, html').removeClass('popup-open');
        $('.popup-overlay').removeClass('popup-open');
    });
    // scroll to anchor link on click
    $('a.link_scrollto[href^="#"]').click(function(e){
        e.preventDefault();
        var link_anchor = $(this).attr('href');
        // scroll to anchor link if section ID is visible and exists
        if($(''+link_anchor+':visible').length > 0) {
            $('html, body').animate({
                scrollTop: $(''+link_anchor+'').offset().top + 0
            }, 300);
        }
        // scroll to anchor link tab wrapper if hidden
        else {
            var current_tab = $(''+link_anchor+'').closest('.tab_wrapper');
            // close all other tabs
            $('.tab_wrapper').removeClass('open');
            $('.tab_wrapper .tab_content').slideUp(300);
            current_tab.addClass('open');
            current_tab.find('.tab_content').slideDown(300);
            setTimeout(function() {
                $('html, body').animate({
                    scrollTop: current_tab.offset().top - 10
                }, 300);
            }, 300);
        }
    });
    // // play video with custom icon
    // $('a.play_video').click(function(e){
    //     e.preventDefault();
    //     if ($(this).closest('.responsive_video_wrapper.hosted_self').length > 0) {
    //         $(this).hide();
    //         $(this).closest('.responsive_video_wrapper.hosted_self').find('video').get(0).play();
    //     }
    // });
    // // hide video play icon on video controls click
    // $('video').click(function() {
    //   if ($(this).get(0).paused) {
    //       // this.pause();
    //       $(this).closest('.responsive_video_wrapper').find('a.play_video').hide();
    //       // alert('video playing');
    //   }
    // });
    // waypoints scroll inview for sticky shop now button
    $('#hero .sticky_shop_now').each(function(){
        var this_item = $(this);
    
        // var appear_item_start = $('#routine');
    
    
        // // var appear_item_end = $('body.home .module-6');
    
        // new Waypoint.Inview({
        //     element: appear_item_start,
        //     enter: function(direction) {
        //         this_item.addClass('entered')
        //     },
        //     exited: function(direction) {
        //         if (direction == 'up') {
        //             this_item.removeClass('entered')
        //         }
        //     }
        // });
    
    
    
    
        var retailers_section = $('#retailers');
    
        new Waypoint.Inview({
            element: retailers_section,
            // enter: function(down) {
    
            //     this_item.removeClass('entered')
    
    
            // },
            exited: function(direction) {
                // if (direction == 'up') {
                    this_item.addClass('entered')
                // }
            }
        });
    
    
        var footer_section = $('#contact');
    
        new Waypoint.Inview({
            element: footer_section,
            entered: function(down) {
    
                this_item.removeClass('entered')
    
    
            },
            exit: function(direction) {
                if (direction == 'up') {
                    this_item.addClass('entered')
                }
            }
        });
    
    });
    // // waypoints scroll inview for sticky shop now button
    // $('#hero .sticky_shop_now').click(function(){
    //     var this_item = $(this);
    //     $('#hero .sticky_shop_now').removeClass('entered');
    // });
    // Devices without touch events
    $('html.no-touchevents .tile').hover(function() {
        $(this).addClass('hover');
    }, function() {
        $(this).removeClass('hover');
    }
    );
    $('html.no-touchevents #product_before_after .photo_column .photo_column_inner').hover(function(e) {
        e.stopPropagation();
        // e.preventDefault();
        // $(this).toggleClass('hover');
        if ($(this).hasClass('hover')) {
            $(this).removeClass('hover');
        } else {
            $(this).addClass('hover');
        }
    });
    // Devices with touch events
    $('html.touchevents #product_before_after .photo_column .photo_column_inner').click(function(e) {
        e.stopPropagation();
        // e.preventDefault();
        // $(this).toggleClass('hover');
        if ($(this).hasClass('hover')) {
            $(this).removeClass('hover');
        } else {
            $(this).addClass('hover');
        }
    });
    $(window).on('load', function(){
        var site_header_height = $('#site_header').height();
        $('#page_product').css({'padding-top':''+site_header_height+'px'});
    });
    $(window).on('resize', function(){
      var win = $(this); //this = window
      var site_header_height = $('#site_header').height();
      $('#page_product').css({'padding-top':''+site_header_height+'px'});
        // if (win.width() <= 767) {
        //   start_product_carousel();
        // } else {
        //   stop_product_carousel();
        // }
      });
    // add detailed title to each logo link
    $('.tab_headline h3').each(function(){
        var headline_copy = $(this).text();
        $(this).closest('.tab_headline').attr('data-detailed-title', 'Tab - '+headline_copy+'')
    });
    // add detailed title to each logo link
    $('.logo_column img').each(function(){
        var logo_retailer_name = $(this).attr('alt');
        $(this).closest('.logo_wrapper').attr('data-detailed-title', 'Shop - '+logo_retailer_name+'')
        $(this).wrap('');
        $(this).after(''+logo_retailer_name+'');
    });
    $('.product_wrapper a.btn').each(function(){
        var product_name = $(this).closest('.product_wrapper').find('.headline h3').text();
        $(this).prepend(''+product_name+' -  ');
    });
    // add selected retailer to search button as detailed title
    $('.retailer_dropdown').on('select2:select', function (e) {
        var retailer_value = $(this).val();
        var retailer_text = $(this).closest('.retailer_form').find('option:selected').text();
        $(this).closest('.retailer_form').find('input[type="submit"]').attr('data-detailed-title', 'Shop - '+retailer_text+'')
        // alert(retailer_text);
    });
    // mobile accordion tabs
    $('.tab_wrapper .tab_headline').click(function (e) {
        e.preventDefault();
        var current_tab = $(this).closest('.tab_wrapper');
        if ($(this).closest('.tab_wrapper').hasClass('open')) {
            $(this).closest('.tab_wrapper').removeClass('open');
            // $(this).closest('.tab_wrapper').toggleClass('open');
            $(this).closest('.tab_wrapper').find('.tab_content').slideUp(300);
        } else {
            // close all other tabs
            $('.tab_wrapper').removeClass('open');
            $('.tab_wrapper .tab_content').slideUp(300);
            $(this).closest('.tab_wrapper').addClass('open');
            // $(this).closest('.tab_wrapper').toggleClass('open');
            $(this).closest('.tab_wrapper').find('.tab_content').slideDown(300);
            setTimeout(function() {
                $('html, body').animate({
                    scrollTop: current_tab.offset().top - 10
                }, 300);
            }, 300);
        }
    });
    // $(window).on('resize', function(){
    //   var win = $(this); //this = window
    //     if (win.width() <= 767) {
    //     } else {
    //     }
    //   });
    // add classes to all shop links for tracking
    $('\
        a.logo_wrapper, \
        #site_header .col_buttons .btn, \
        .sticky_shop_now, \
        .retailer_form input[type="submit"], \
        .link_scrollto, \
        .tab_headline, \
        .cta_wrapper .btn, \
        .btn_wrapper .btn, \
        .logo_column .logo_wrapper, \
        .product_wrapper a.btn \
        ').each(function () {
            $(this).addClass('tracking_shop_link');
    });
    // trigger pricespider popup from one single button with ps-widget class and ps-sku attribute (any link/button with ps_popup_link class)
    $(function () {
        const ps_popuplinkelements = document.getElementsByClassName("cs_popup_link")
        for (let index = 0; index < ps_popuplinkelements.length; index++) {
            const ele = ps_popuplinkelements [index]
            ele.onclick = (e) => {
                e.stopImmediatePropagation(); 
                e.preventDefault(); 
                document.getElementsByClassName("cswidget")[0].click()
            }
        }
    });
    $(function () {
        const wrapperOuter  =  document.getElementById("col_graphic_inner");
        const wrapperPercent  =  document.getElementById("ingredients_col_left");
        const outer = document.getElementById("ingredients_col_left");
        // const night = document.getElementById("night");
        let width = document.body.clientWidth;
        let imageWrapperPercent;
        wrapperOuter.addEventListener('mousemove', mouseMove );
        function mouseMove(e) {
          var x = e.clientX;
          console.log(x);
          var outerTracker = outer.getBoundingClientRect();
          let mousePointerPos;
          mousePointerPos = x - outerTracker.left;
          console.log(mousePointerPos);
          //wrapperPercent.style.width = x + "px"; // wrapper width using clientX
          wrapperPercent.style.width = mousePointerPos + "px"; // wrapper width using mouse postion in the box
          // convert to a %
          //imageWrapper =  mousePointerPos/10;
          //wrapperPercent.style.width = imageWrapper + "%";
          // Night Image Show and Hide
          /*if(mousePointerPos < 0) {
            night.style.opacity = "100"
          }
          if(mousePointerPos > 0) {
            night.style.opacity = "0"
        }*/
        }
        $('#ingredients').mouseleave(function() {
          $( '#ingredients_col_left' ).css( "width", "50%" );
        });
    });
    // wait for element to exist function using MutationObserver
    // https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
    // function waitForElm(selector) {
    //     return new Promise(resolve => {
    //         if (document.querySelector(selector)) {
    //             return resolve(document.querySelector(selector));
    //         }
    //         const observer = new MutationObserver(mutations => {
    //             if (document.querySelector(selector)) {
    //                 resolve(document.querySelector(selector));
    //                 observer.disconnect();
    //             }
    //         });
    //         observer.observe(document.body, {
    //             childList: true,
    //             subtree: true
    //         });
    //     });
    // }
    // waitForElm('.ps-sku-selector').then((elm) => {
    //     // console.log('Element is ready');
    //     // console.log(elm.textContent);
    //     $('.ps-sku-selector').val('1640015').prop('selected', true).trigger('change');
    // });
    if($('#treatment .product_wrapper.hidden-xs').length > 0) {
        // Also can pass in optional settings block
        var rellax = new Rellax('#treatment .product_wrapper.hidden-xs', {
            speed: 3,
            center: true,
            wrapper: null,
            round: false,
            vertical: true,
            horizontal: false
        });
    }
    if($('#treatment .product_wrapper.visible-xs').length > 0) {
        // Also can pass in optional settings block
        var rellax = new Rellax('#treatment .product_wrapper.visible-xs', {
            speed: 1,
            // speed: 1,
            center: false,
            wrapper: null,
            round: false,
            vertical: true,
            horizontal: false
        });
    }
    // if($('#hero').length > 0) {
    //     // Also can pass in optional settings block
    //     var rellax = new Rellax('#hero', {
    //         speed: 3,
    //         center: true,
    //         wrapper: null,
    //         round: false,
    //         vertical: true,
    //         horizontal: false
    //     });
    // }
    // $('#hero').paroller({
    //   // factorXs: 0.1,
    //   // factorSm: 0.1,
    //   // factorMd: -0.4,
    //   // factorLg: -0.5,
    //   // factorXl: -0.6,
    //   factor: .25,
    //   // factor: -.4,
    //   type: 'background',
    //   direction: 'vertical',
    //   // transition: 'transform .3s ease-out'
    // });
});