;(function($) {


    //-----------------------------------------------------------------//
    // TOUCH DETECT
    //-----------------------------------------------------------------//
    window.is_touch_device = function () {
        try {
            document.createEvent("TouchEvent");
            return true;
        } catch (e) {
            return false;
        }
    }

    if (is_touch_device()) {
        document.documentElement.classList.add('touch');
    } else {
        document.documentElement.classList.add('no-touch');
    }

    //-----------------------------------------------------------------//
    // Global detect if mouse down to handle some conflicts with focus
    //-----------------------------------------------------------------//
    var mouseDown = 0;
    document.body.onmousedown = function() {
        ++mouseDown;
    }
    document.body.onmouseup = function() {
        --mouseDown;
    }

    //-----------------------------------------------------------------//
    // Tabindex fix on popups
    //-----------------------------------------------------------------//
    $(document).on('DOMNodeInserted', function(e) {
        if ( $(e.target).hasClass('dialog-widget') ) {
            $(e.target).find('.dialog-message').attr('tabindex',0);
        }

    });
    var overlayFocused = false;
    $(document).keydown(function(e) {
        var key = (event.keyCode ? event.keyCode : event.which);
        if (key === 27) { // Escape key removes focus
            $(document.activeElement).blur();
        }
        if (key === 9) { // Tab key
            if(
                $('.elementor-popup-modal').length &&
                $('.elementor-popup-modal').attr('style') !== 'display: none;')
            {
                setTimeout(function(){
                    if($(':focus').parents('.elementor-popup-modal').length > 0) {
                    } else {
                        $('.elementor-popup-modal').find('.dialog-message').focus();
                    }
                }, 10);
                if(!overlayFocused) {
                    $('.elementor-popup-modal').find('.dialog-message').focus();
                    overlayFocused = true;
                }
            } else {
                overlayFocused = false;
            }
        }
    });


    //-----------------------------------------------------------------//
    // Jump to content section from tab
    //-----------------------------------------------------------------//
    $('.jump-to-content-button a').on('click', function(e) {
        var link = $(this).attr('href');
        if(!$(link).length) link = 'main';

        $("html, body").animate({ scrollTop: $(link).offset().top });
        $(link).attr('tabindex','0');
        $(link).focus();

        return false;
    });


    //-----------------------------------------------------------------//
    // Open Elementor nav menu on tabindex
    //-----------------------------------------------------------------//
    $(document).on('focusin', '.elementor-widget-nav-menu', function(){
        if(mouseDown) return;

        var el = $(this);

        if(!el.find('.elementor-menu-toggle').hasClass('elementor-active')){
            el.find('.elementor-menu-toggle').addClass('elementor-active');
        }
    });

    $(document).on('focusout', '.elementor-widget-nav-menu', function(){
        if(mouseDown) return;

        var el = $(this);

        if(el.find('.elementor-menu-toggle').hasClass('elementor-active')){
            el.find('.elementor-menu-toggle').removeClass('elementor-active');
        }
    });


    //-----------------------------------------------------------------//
    // Tab index on Jet menus
    //-----------------------------------------------------------------//
    $(document).on('focusin', '.jet-menu-item-has-children', function(){
        var el = $(this);
        el.addClass('jet-menu-hover');
    });

    $(document).on('focusout', '.jet-menu-item-has-children', function(){
        var el = $(this);
        el.removeClass('jet-menu-hover');
    });

    // Add tab index to mega menus
    $('.elementor-widget-jet-mega-menu').each(function(){
        var el = $(this);
        el.find('.jet-menu-item.jet-menu-item-has-children').attr('tabindex',0);
    });

    //-----------------------------------------------------------------//
    // Tab index on Jet Filters
    //-----------------------------------------------------------------//
    // Checkboxes
    $('.jet-checkboxes-list').each(function(){
        $(this).find('label.jet-checkboxes-list__item').each(function(){
            var label = $(this);
            label.attr('tabindex',0);



            label.on('keypress', function (event) {
                if (event.keyCode == 13) {
                    label.trigger('click');
                }
            });
        });
    });
    // Select
    $('.jet-select').each(function(){
        var select = $(this).find('select');
        select.attr('tabindex',0);

        // Expand select only on tab, not on click
        $(document).keyup(function(e) {
            var key = (event.keyCode ? event.keyCode : event.which);
            if (key === 9) { // Tab key
                if(select.is(":focus")){
                    select.attr('size', select.find('option').length);
                } else {
                    select.on('focusout',function(){
                        select.attr('size', 1);
                    });
                }
            }
        });
    });



    //-----------------------------------------------------------------//
    // When working with Elementor Tabs, the container padding CSS cant be inside the tab wrapper.
    //-----------------------------------------------------------------//

    jQuery('.e-n-tabs-content').each(function(){
        let el = jQuery(this);
        let styleTags = el.find('style');
        // Move out of the tab wrapper
        if(styleTags.length > 0){
            styleTags.each(function(){
                let styleTag = jQuery(this);
                styleTag.insertAfter(el);
            });
        }
    });






    // -----------------------------------------------------------------//
    // Add video attribute to video playlist as specified in our Elementor Videos Extension PHP class
    //-----------------------------------------------------------------//

    $(window).load(function(){
        $('.elementor-widget-video-playlist video').each(function(){
            $(this).attr('controlsList','nodownload noplaybackrate');
        });
    });



    //-----------------------------------------------------------------//
    // Handle video autoplay for Elementor.
    // Detect if video can autoplay or not. When in battery save mode autoplay won't play. Handle that.
    // https://developer.chrome.com/blog/play-request-was-interrupted
    //-----------------------------------------------------------------//

    function handleVideoAutoPlay(state, save){

        // Add a class to body for outer knowledge
        if(state === 0){
            document.body.classList.add('no-autoplay');
        } else if(state === 1){
            document.body.classList.add('can-autoplay');
        }

        if(save){
            let object = {canPlay: state, lastCheck: new Date().getTime()}
            localStorage.setItem("webienAutoplayVideoState", JSON.stringify(object));
        }
    }

    // On window load (Safari needs it)
    $(window).load(function() {
        // First check if we have a saved video state in local storage so that we don't need to do this check on each page load
        let videoAutoplayState = localStorage.getItem('webienAutoplayVideoState');
        if (videoAutoplayState !== null) {
            let object = JSON.parse(localStorage.getItem("webienAutoplayVideoState"));
            if (object.lastCheck > (new Date().getTime() - (1000 * 60 * 5))) {
                // If the last check was less than 5 min ago, use the saved state, else check again
                //console.log('Using saved video state: ' + object.canPlay);
                videoAutoplayState = object.canPlay;
                handleVideoAutoPlay(videoAutoplayState, false);
            } else {
                // If the last check was more than 1 hour ago, check again
                //console.log('Time for new video check');
                videoAutoplayState = null;
            }
        }
        if (videoAutoplayState === null) {
            let videos = document.querySelectorAll('video.elementor-background-video-hosted, video.elementor-video');
            if (videos.length > 0) {
                let i = 0;
                let videoCleared = false;
                while (i < videos.length) {
                    if (videos[i].hasAttribute('autoplay') && !videoCleared) {
                        // Check if the video can autoplay
                        let promise = videos[i].play();

                        if (promise !== undefined) {
                            promise.then(function () {
                                // Autoplay started successfully
                                //console.log('Autoplay started');
                                videoAutoplayState = 1;
                                handleVideoAutoPlay(videoAutoplayState, true);

                            }).catch(function (error) {
                                // Autoplay was prevented
                                console.log('Autoplay prevented:', error);
                                videoAutoplayState = 0;
                                handleVideoAutoPlay(videoAutoplayState, true);
                            });
                        }
                        videoCleared = true;
                    }
                    i++;
                }
            }
        }
    });


})(jQuery);
