/**
 * Init and resize sliders
 *
 * @package ThemeREX Addons
 * @since v1.1
 */

/* global jQuery:false */
/* global TRX_ADDONS_STORAGE:false */

(function() {

    "use strict";

    var init_attempts = 0;

    // Init previously hidden sliders
    jQuery(document).on( 'action.init_hidden_elements', function(e, container) {
        // Init sliders in this container
        trx_addons_init_sliders(e, container);
        // Resize sliders
        trx_addons_resize_sliders(e, container);
    } );

    // Init sliders with engine=swiper
    function trx_addons_init_sliders(e, container) {

        // Create Swiper Controllers
        if (window.Swiper && container.find('.sc_slider_controller:not(.inited)').length > 0) {
            container.find('.sc_slider_controller:not(.inited)')
                .each(function () {
                    var controller = jQuery(this).addClass('inited');
                    if ( controller.find('.slider_style_controller').length > 0 ) return;
                    var slider_id = controller.data('slider-id');
                    if (!slider_id) return;

                    var controller_id = controller.attr('id');
                    if (controller_id == undefined) {
                        controller_id = 'sc_slider_controller_'+Math.random();
                        controller_id = controller_id.replace('.', '');
                        controller.attr('id', controller_id);
                    }

                    jQuery('#'+slider_id+' .slider_container').attr('data-controller', controller_id);

                    var controller_style = controller.data('style');
                    var controller_effect = controller.data('effect');
                    var controller_direction = controller.data('direction');
                    var controller_interval = controller.data('interval');
                    var controller_height = controller.data('height');
                    var controller_per_view = controller.data('slides-per-view');
                    var controller_space = controller.data('slides-space');
                    var controller_controls = controller.data('controls');

                    var controller_html = '';
                    jQuery('#'+slider_id+' .swiper-slide')
                        .each(function (idx) {
                            var slide = jQuery(this);
                            var image = controller_style.indexOf('thumbs') == -1
                                ? ''
                                : ( slide.data('image')
                                        ? slide.data('image')
                                        : (slide.find('img').length > 0
                                                ? slide.find('img').eq(0).attr('src')
                                                : (slide.css('background-image')!=''
                                                    ? slide.css('background-image').replace('url(', '').replace(')', '').replace(';', '')
                                                    : '')
                                        )
                                );
                            var title = controller_style.indexOf('titles') == -1
                                ? ''
                                : ( slide.data('title')
                                        ? slide.data('title')
                                        : slide.find('[class*="_item_title"]').text()
                                );
                            var cats = slide.data('cats');
                            var date = slide.data('date');
                            controller_html += '<div class="slider-slide swiper-slide"'
                                + ' style="'
                                + (image !== undefined && image!=='' ? 'background-image: url('+image+');' : '')
                                + '"'
                                + '>'
                                + '<div class="sc_slider_controller_info">'
                                + '<span class="sc_slider_controller_info_number">'+(idx < 9 ? '0' : '')+(idx+1)+'</span>'
                                + '<span class="sc_slider_controller_info_title">'+(title ? title : 'Slide '+(idx+1))+'</span>'
                                + '</div>'
                                + '</div>';
                        });
                    controller.html('<div id="'+controller_id+'_outer"'
                        + ' class="slider_outer slider_swiper_outer slider_style_controller'
                        + ' slider_outer_' + (controller_controls == 1 ? 'controls slider_outer_controls_side' : 'nocontrols')
                        + ' slider_outer_nopagination'
                        + ' slider_outer_' + (controller_per_view==1 ? 'one' : 'multi')
                        + ' slider_outer_direction_' + (controller_direction=='vertical' ? 'vertical' : 'horizontal')
                        + '"'
                        + '>'
                        + '<div id="'+controller_id+'_swiper"'
                        +' class="slider_container slider_swiper swiper-slider-container'
                        + ' slider_' + (controller_controls == 1 ? 'controls slider_controls_side' : 'nocontrols')
                        + ' slider_nopagination'
                        + ' slider_notitles'
                        + ' slider_noresize'
                        + ' slider_' + (controller_per_view==1 ? 'one' : 'multi')
                        + ' slider_direction_' + (controller_direction=='vertical' ? 'vertical' : 'horizontal')
                        + '"'
                        + ' data-slides-min-width="100"'
                        + ' data-controlled-slider="'+slider_id+'"'
                        + ' data-direction="' + (controller_direction=='vertical' ? 'vertical' : 'horizontal') + '"'
                        + (controller_effect !== undefined ? ' data-effect="' + controller_effect + '"' : '')
                        + (controller_interval !== undefined ? ' data-interval="' + controller_interval + '"' : '')
                        + (controller_per_view !== undefined ? ' data-slides-per-view="' + controller_per_view + '"' : '')
                        + (controller_space !== undefined ? ' data-slides-space="' + controller_space + '"' : '')
                        + (controller_height !== undefined ? ' style="height:'+controller_height+'"' : '')
                        + '>'
                        + '<div class="slider-wrapper swiper-wrapper">'
                        + controller_html
                        + '</div>'
                        + '</div>'
                        + (controller_controls == 1
                                ? '<div class="slider_controls_wrap"><a class="slider_prev swiper-button-prev" href="#"></a><a class="slider_next swiper-button-next" href="#"></a></div>'
                                : ''
                        )
                        + '</div>'
                    );
                });
        }


        // Create Swiper Controls
        if (window.Swiper && container.find('.sc_slider_controls:not(.inited)').length > 0) {
            container.find('.sc_slider_controls:not(.inited)')
                .each(function () {
                    var controls = jQuery(this).addClass('inited'),
                        slider_id = controls.data('slider-id'),
                        pagination_style = controls.data('pagination-style');
                    if (!slider_id) return;
                    slider_id = jQuery('#'+slider_id+' .slider_swiper').attr('id');
                    if (!slider_id) return;
                    controls.on('click', 'a', function(e) {
                        var s = TRX_ADDONS_STORAGE['swipers'][slider_id];
                        if (jQuery(this).hasClass('slider_next'))
                            s.slideNext();
                        else
                            s.slidePrev();
                        e.preventDefault();
                        return false;
                    });
                    // Add pagination
                    var s = typeof TRX_ADDONS_STORAGE['swipers'] != 'undefined' && typeof TRX_ADDONS_STORAGE['swipers'][slider_id] != 'undefined' ? TRX_ADDONS_STORAGE['swipers'][slider_id] : false,
                        slides = jQuery('#'+slider_id+' .swiper-slide'),
                        spv = s
                            ? ( s.params.loop
                                    ? s.loopedSlides
                                    : 0
                            )
                            : 0;
                    var total = s
                        ? ( s.params.loop
                                ? Math.ceil((s.slides.length - s.loopedSlides * 2) / s.params.slidesPerGroup)
                                : s.snapGrid.length
                        )
                        : slides.length;
                    if (pagination_style == 'thumbs') {
                        var html = '';
                        slides.each(function(idx){
                            if ( idx < spv || idx >= slides.length - spv ) return;
                            var slide = jQuery(this);
                            var image = slide.data('image');
                            html += '<span class="slider_pagination_button_wrap swiper-pagination-button-wrap" style="width: ' + Math.round(100/total, 2) + '%;">'
                                + '<span class="slider_pagination_button swiper-pagination-button"'
                                + (image !== undefined ? ' style="background-image: url('+image+');"' : '')
                                + '></span>'
                                + '</span>';
                        });
                        controls.find('.slider_pagination_wrap').html(html);
                    } else if (pagination_style == 'fraction') {
                        controls.find('.slider_pagination_wrap').html('<span class="slider_pagination_current swiper-pagination-current">1</span>'
                            + '/'
                            + '<span class="slider_pagination_total swiper-pagination-total">'+total+'</span>');
                    } else if (pagination_style == 'bullets') {
                        var html = '';
                        slides.each(function(idx){
                            if ( idx < spv || idx >= slides.length - spv ) return;
                            html += '<span class="slider_pagination_bullet swiper-pagination-bullet" data-slide-number="'+(s ? jQuery(this).data('slide-number') : idx)+'"></span>';
                        });
                        controls.find('.slider_pagination_wrap').html(html);
                    }
                    if (pagination_style != 'none') {
                        if (controls.find('.slider_progress_bar').length > 0) {
                            var bar = controls.find('.slider_progress_bar');
                            bar.parent().on('click', function(e) {
                                var s = TRX_ADDONS_STORAGE['swipers'][slider_id];
                                var total = s.params.loop ? Math.ceil((s.slides.length - s.loopedSlides * 2) / s.params.slidesPerGroup) : s.snapGrid.length;
                                var slide_number = Math.max(0, Math.min(total-1, Math.floor(total * e.offsetX / jQuery(this).width())));
                                var slide_idx = jQuery('#'+slider_id).find('[data-slide-number="'+slide_number+'"]:not(.swiper-slide-duplicate)').index();
                                s.slideTo(slide_idx);
                                e.preventDefault();
                                return false;
                            });
                        } else {
                            controls.find('.slider_pagination_button_wrap,.slider_pagination_bullet').on('click', function(e) {
                                var s = TRX_ADDONS_STORAGE['swipers'][slider_id];
                                var slide_idx = jQuery('#'+slider_id).find('[data-slide-number="'+jQuery(this).index()+'"]:not(.swiper-slide-duplicate)').index();
                                s.slideTo(slide_idx);
                                e.preventDefault();
                                return false;
                            });
                        }

                        jQuery('#'+slider_id).on('slider_init slide_change_start', function(e) {
                            if (TRX_ADDONS_STORAGE['swipers'][slider_id]) {
                                var s = TRX_ADDONS_STORAGE['swipers'][slider_id];
                                var current = jQuery(s.slides[s.activeIndex]).data('slide-number') + 1,
                                    total = s.params.loop ? Math.ceil((s.slides.length - s.loopedSlides * 2) / s.params.slidesPerGroup) : s.snapGrid.length;
                                if (total > 0) {
                                    if (pagination_style == 'progressbar') {
                                        bar.width(Math.ceil(current/total*100)+'%');
                                    } else if (pagination_style == 'thumbs') {
                                        controls.find('.slider_pagination_button')
                                            .removeClass('slider_pagination_button_active')
                                            .eq(current-1)
                                            .addClass('slider_pagination_button_active');
                                    } else if (pagination_style == 'bullets') {
                                        controls.find('.slider_pagination_bullet')
                                            .removeClass('slider_pagination_bullet_active swiper-pagination-bullet-active')
                                            .eq(current-1)
                                            .addClass('slider_pagination_bullet_active swiper-pagination-bullet-active');
                                    } else if (pagination_style == 'fraction') {
                                        controls.find('.slider_pagination_current').text(current);
                                    }
                                }
                            }
                        });
                    }
                });
        }


        // Swiper Slider
        if (window.Swiper && container.find('.slider_swiper:not(.inited)').length > 0) {
            container.find('.slider_swiper:not(.inited)')
                .each(function () {

                    // If slider inside the invisible block - exit
                    if (jQuery(this).parents('div:hidden,article:hidden').length > 0) {
                        return;
                    }

                    // Wait for all inner images are loaded
                    var loaded = true;
                    jQuery(this).find('img').each(function() {
                        if (!jQuery(this).get(0).complete) loaded = false;
                    });
                    if (!loaded && init_attempts++ < 20) {
                        setTimeout(function() {
                            trx_addons_init_sliders(e, container);
                        }, 100);
                        return;
                    }

                    // Check attr id for slider. If not exists - generate it
                    var slider = jQuery(this);
                    var id = slider.attr('id');
                    if (id == undefined) {
                        id = 'swiper_'+Math.random();
                        id = id.replace('.', '');
                        slider.attr('id', id);
                    }
                    var cont = slider.parent().hasClass('slider_swiper_outer') ? slider.parent().attr('id', id+'_outer') : slider;
                    var cont_id = cont.attr('id');

                    // If this slider is controller for the other slider
                    var is_controller = slider.parents('.sc_slider_controller').length > 0;
                    // If this slider is controlled by other slider
                    var controller_id = slider.data('controller');

                    // Enum all slides
                    slider.find('.swiper-slide').each(function(idx) {
                        jQuery(this).attr('data-slide-number', idx);
                    });

                    // Show slider, but make it invisible
                    slider.css({
                        'display': 'block',
                        'opacity': 0
                    })
                        .addClass(id)
                        .addClass('inited')
                        .data('settings', {mode: 'horizontal'});		// VC hook

                    // Free mode
                    var free_mode = slider.data('free-mode');

                    // Direction of slides change
                    var direction = slider.data('direction');
                    if (direction != 'vertical') direction = 'horizontal';

                    // Min width of the slides in swiper (used for validate slides_per_view on small screen)
                    var smw = slider.data('slides-min-width');
                    if (smw === undefined) {
                        smw = 150;
                        slider.attr('data-slides-min-width', smw);
                    }

                    // Validate Slides per view on small screen
                    var spv = slider.data('slides-per-view');

                    if (spv == undefined || slider.parents('.widget_nav_menu').length > 0) {
                        spv = 1;
                        slider.attr('data-slides-per-view', spv);
                    }

                    var width = slider.width();
                    if (width == 0) {
                        width = slider.parent().width();
                    }
                    if (direction == 'horizontal') {
                        if (width / spv < smw) {
                            spv = Math.max(1, Math.floor(width / smw));
                        }
                    }

                    // Space between slides
                    var space = slider.data('slides-space');
                    if (space == undefined) space = 0;

                    // Correct slider height if slider vertical with no resize
                    if (direction == 'vertical' && slider.hasClass('slider_height_auto') && slider.hasClass('slider_noresize')) {
                        var height = 0;
                        slider.find('.swiper-slide').each(function(idx) {
                            if (idx >= spv) return;
                            height += jQuery(this).height()+(idx > 0 ? space : 0);
                        });
                        if (height > 0) slider.height(height);
                    }

                    // Autoplay interval
                    var interval = slider.data('interval');
                    if (interval === undefined) interval = Math.round(5000 * (1 + Math.random()));
                    if (isNaN(interval)) interval = 0;

                    // Allow swipe guestures
                    var noswipe = slider.hasClass('slider_noswipe') || slider.parents('.slider_noswipe,.elementor-edit-mode').length > 0;

                    // Slider in grid - fix width
                    if (slider.parents('[class*="_grid_wrap"]').length > 0) {
                        slider.css( {
                            'max-width': width+'px'
                        } );
                    }

                    if (TRX_ADDONS_STORAGE['swipers'] === undefined) {
                        TRX_ADDONS_STORAGE['swipers'] = {};
                    }
                    TRX_ADDONS_STORAGE['swipers'][id] = new Swiper('.'+id, {
                        freeMode: free_mode > 0,
                        direction: direction,
                        initialSlide: 0,
                        speed: 600,
                        loop: slider.data('slides-overflow') != 1,				//!is_controller
                        loopedSlides: spv,
                        slidesPerView: spv,
                        spaceBetween: space,
                        centeredSlides: slider.data('slides-centered') == 1,	//is_controller,
                        mousewheel: slider.data('mouse-wheel') == 1,
                        grabCursor: !is_controller && !noswipe,
                        slideToClickedSlide: is_controller,
                        touchRatio: is_controller ? 0.2 : 1,
                        autoHeight: false,		//!slider.hasClass('slider_height_fixed'),
                        lazy: false,
                        preloadImages: true,
                        updateOnImagesReady: true,
                        roundLengths: TRX_ADDONS_STORAGE['slider_round_lengths'] && !is_controller,	// To prevent blurry texts in Chrome (Firefox rendering texts fine with any value)
                        // Disable roundLengths for controller to prevent incorrect calcs when slidesPerView > 1
                        effect: slider.data('effect') ? slider.data('effect') : 'slide',
                        swipeHandler: noswipe ? '.slider_controls_wrap,.slider_pagination_wrap' : null,
                        //---Pagination (old way):
                        //pagination: slider.hasClass('slider_pagination') ? '#'+cont_id+' .slider_pagination_wrap' : false,
                        //paginationClickable: slider.hasClass('slider_pagination') ? '#'+cont_id+' .slider_pagination_wrap' : false,
                        //paginationType: slider.hasClass('slider_pagination') && slider.data('pagination') ? slider.data('pagination') : 'bullets',
                        //---Pagination (new way):
                        pagination: {
                            el: slider.hasClass('slider_pagination') ? '#'+cont_id+'>.slider_pagination_wrap,#'+cont_id+' > .slider_swiper > .slider_pagination_wrap' : null,
                            clickable: slider.hasClass('slider_pagination') ? '#'+cont_id+' .slider_pagination_wrap' : false,
                            type: slider.hasClass('slider_pagination') && slider.data('pagination') ? slider.data('pagination') : 'bullets',
                            progressbarOpposite: slider.data('pagination') == 'progressbar'
                                && (
                                    ( slider.data('direction')=='vertical' && ( slider.hasClass('slider_pagination_pos_bottom') || slider.hasClass('slider_pagination_pos_bottom_outside') ) )
                                    ||
                                    ( slider.data('direction')=='horizontal' && ( slider.hasClass('slider_pagination_pos_left') || slider.hasClass('slider_pagination_pos_right') ) )
                                ),
                            progressbarFillClass: 'swiper-pagination-progressbar-fill',
                            progressbarOppositeClass: 'swiper-pagination-progressbar-opposite',
                        },
                        //---Navigation (old way):
                        //nextButton: slider.hasClass('slider_controls') ? '#'+cont_id+' .slider_next' : false,
                        //prevButton: slider.hasClass('slider_controls') ? '#'+cont_id+' .slider_prev' : false,
                        //---Navigation (new way):
                        navigation: {
                            nextEl: slider.hasClass('slider_controls') ? '#'+id+'>.slider_controls_wrap>.slider_next,#'+id+'~.slider_controls_wrap>.slider_next' : null,
                            prevEl: slider.hasClass('slider_controls') ? '#'+id+'>.slider_controls_wrap>.slider_prev,#'+id+'~.slider_controls_wrap>.slider_prev' : null
                        },
                        //---Autoplay (old way):
                        //autoplay: slider.hasClass('slider_noautoplay') || interval==0 ? false : parseInt(interval, 10),
                        //autoplayDisableOnInteraction: true,
                        //---Autoplay (new way):
                        autoplay: slider.hasClass('slider_noautoplay')
                        || (typeof slider.data('autoplay')!=='undefined' && slider.data('autoplay') == 0)
                        || interval == 0
                            ? false
                            : {
                                delay: parseInt(interval, 10),
                                disableOnInteraction: true
                            },
                        //---Events (new way):
                        on: {
                            slideChangeTransitionStart: function () {
                                var swiper = this,
                                    slide  = jQuery(swiper.slides[swiper.activeIndex]),
                                    slide_number = slide.data('slide-number');

                                // Mark active custom pagination bullet
                                cont.find('.swiper-pagination-custom > span')
                                    .removeClass('swiper-pagination-button-active')
                                    .eq(slide_number)
                                    .addClass('swiper-pagination-button-active');
                                // Change outside title
                                cont.find('.slider_titles_outside_wrap .active').removeClass('active').fadeOut();
                                // Update controller or controlled slider
                                var slaves = is_controller
                                    ? jQuery('#'+slider.data('controlled-slider'))
                                    : jQuery('[data-slider-id="'+id.replace('_sc_', '_')+'"]');
                                if ( slaves.length === 0 && ! is_controller ) {
                                    slaves = jQuery('[data-slider-id="'+id.replace('_sc_', '_').replace('_swiper', '')+'"]');
                                }
                                if ( slaves.length > 0 ) {
                                    slaves.each( function() {
                                        var controlled_slider = jQuery(this).hasClass('slider_swiper') ? jQuery(this) : jQuery(this).find( '.slider_swiper' ).eq(0);
                                        var controlled_id = controlled_slider.attr('id');
                                        if ( TRX_ADDONS_STORAGE['swipers'][controlled_id] && jQuery('#'+controlled_id).attr('data-busy') != 1 ) {
                                            slider.attr('data-busy', 1);
                                            setTimeout( function() {
                                                slider.attr('data-busy', 0);
                                            }, 300 );
                                            var slide_number = jQuery(swiper.slides[swiper.activeIndex]).data('slide-number');
                                            var slide_idx = controlled_slider.find('[data-slide-number="'+slide_number+'"]:not(.swiper-slide-duplicate)').index();
                                            TRX_ADDONS_STORAGE['swipers'][controlled_id].slideTo(slide_idx);
                                        }
                                    });
                                }
                                slider.trigger('slide_change_start', [slider]);
                            },
                            slideChangeTransitionEnd: function () {
                                var swiper = this,
                                    slide  = jQuery(swiper.slides[swiper.activeIndex]),
                                    slide_prev   = jQuery(swiper.slides[swiper.lastOpenedIndex !== undefined ? swiper.lastOpenedIndex : swiper.previousIndex]),
                                    slide_number = slide.data('slide-number');
                                swiper.lastOpenedIndex = swiper.activeIndex;
                                // Change outside title
                                var titles = cont.find('.slider_titles_outside_wrap .slide_info');
                                if (titles.length > 0) {
                                    //titles.eq((swiper.activeIndex-1)%titles.length).addClass('active').fadeIn();
                                    titles.eq(slide_number).addClass('active').fadeIn(300);
                                }
                                // Remove video
                                var video = slide_prev.find('.trx_addons_video_player');
                                if ( video.length > 0 ) {
                                    if ( video.hasClass('with_cover') ) {
                                        if ( video.hasClass('video_play') ) {
                                            video.removeClass('video_play').find('.video_embed').empty();
                                        }
                                    } else {
                                        var embed = video.find('.video_embed'),
                                            html  = embed.html();
                                        embed.empty().html( html );
                                    }
                                }
                                // Unlock slider/controller
                                slider.attr('data-busy', 0);
                                slider.trigger('slide_change_end', [slider]);
                            }
                        }
                    });
                    slider.trigger('slider_init', [slider]);

                    // Custom pagination
                    cont.find('.swiper-pagination-custom').on('click', '>span', function(e) {
                        jQuery(this).siblings().removeClass('swiper-pagination-button-active');
                        var t = jQuery(this).addClass('swiper-pagination-button-active').index()
                            * TRX_ADDONS_STORAGE['swipers'][id].params.slidesPerGroup;
                        TRX_ADDONS_STORAGE['swipers'][id].params.loop && (t += TRX_ADDONS_STORAGE['swipers'][id].loopedSlides),
                            TRX_ADDONS_STORAGE['swipers'][id].slideTo(t);
                        e.preventDefault();
                        return false;
                    });

                    slider.attr('data-busy', 1).animate({'opacity':1}, 'fast', function() {
                        slider.attr('data-busy', 0);
                        trx_addons_set_controller_height(is_controller ? slider.parents('[data-slider-id]').eq(0).attr('id') : controller_id,
                            is_controller ? jQuery('#'+slider.parents('[data-slider-id]').eq(0).data('slider-id')) : slider);
                        slider.trigger('slider_inited', [slider]);
                        jQuery(document).trigger('action.slider_inited', [slider, id]);
                    });

                    // Generate 'scroll' event after the slider is showed
                    jQuery(window).trigger('scroll');

                    // Generate 'action.resize_trx_addons' event after the slider is showed
                    jQuery(document).trigger('action.resize_trx_addons');
                });
        }


        // ElastiStack Slider
        if (window.ElastiStack && container.find('.slider_elastistack:not(.inited)').length > 0) {
            container.find('.slider_elastistack:not(.inited)')
                .each(function () {

                    // If slider inside the invisible block - exit
                    if (jQuery(this).parents('div:hidden,article:hidden').length > 0 || typeof window.ElastiStack == 'undefined')
                        return;

                    // Check attr id for slider. If not exists - generate it
                    var slider = jQuery(this);
                    var id = slider.attr('id');
                    if (id == undefined) {
                        id = 'elastistack_'+Math.random();
                        id = id.replace('.', '');
                        slider.attr('id', id);
                    }
                    var cont = slider.parent().hasClass('slider_outer') ? slider.parent().attr('id', id+'_outer') : slider;
                    var cont_id = cont.attr('id');
                    var images = slider.find('ul.stack__images').attr('id', id+'_images');
                    var images_id = images.attr('id');

                    slider.css({
                        'display': 'block',
                        'opacity': 0
                    })
                        .addClass(id)
                        .addClass('inited')
                        .data('settings', {mode: 'horizontal'});		// VC hook

                    // Set height for images container before init to make stack
                    trx_addons_resize_sliders(e, cont);

                    var stack = new ElastiStack( images.get(0), {
                        onUpdateStack : function(idx) {
                            // Change outside title
                            var titles = cont.find('.slider_titles_outside_wrap');
                            if (titles.length > 0) {
                                titles.find('.active').removeClass('active').hide();
                                titles.find('.slide_info').eq(idx).addClass('active').fadeIn(300);
                            }
                            // Remove video
                            cont.find('.trx_addons_video_player.with_cover.video_play').removeClass('video_play').find('.video_embed').empty();
                            slider.trigger('slide_change_end', [slider]);
                        }
                    });

                    // Next button
                    cont.find('.slider_next').on('click', function(e) {
                        stack.nextItem( { transform : 'translate3d(0, -60px, 400px)' } );
                        e.preventDefault();
                        return false;
                    });

                    // Activate first title
                    cont.find('.slider_titles_outside_wrap .slide_info').eq(0).addClass('active').fadeIn(300);

                    // Show slider
                    slider.animate({'opacity':1}, 'fast', function() {
                        stack._setStackStyle();
                    });
                });
        }
    }

    // Sliders: Resize
    jQuery(document).on('action.resize_trx_addons', trx_addons_resize_sliders);
    function trx_addons_resize_sliders(e, container) {
        if (container === undefined) {
            container = jQuery('body');
        }
        container.find('.slider_container.inited').each(function() {
            var slider = jQuery(this);
            if (slider.parents('div:hidden,article:hidden').length > 0) return;
            var id = slider.attr('id');
            var direction = slider.data('direction');
            if (direction != 'vertical') direction = 'horizontal';
            var on_resize = false;	// Need to call onResize handlers
            //var max_width = jQuery('.content').length = 1 ? jQuery('.content').width() : jQuery('body').width();
            var max_width = slider.closest('.post_featured,.elementor-widget-wrap,.vc_column-inner,.content,.page_wrap,body').width();	//jQuery('body').width();
            var slider_width = slider.width();
            if (slider_width > max_width) {
                slider_width = Math.min( slider_width, max_width );
                on_resize = true;
            }
            var last_width = slider.data('last-width');
            if (isNaN(last_width)) last_width = 0;
            if (last_width === 0 || last_width != slider_width) {
                if (direction != 'vertical') slider.data('last-width', slider_width);
                // Detect space between slides
                var space = slider.data('slides-space');
                if (space == undefined) {
                    space = 0;
                }
                if (slider.hasClass('slider_swiper') && typeof TRX_ADDONS_STORAGE['swipers'][id].params == 'object' && typeof TRX_ADDONS_STORAGE['swipers'][id].params.spaceBetween != 'undefined') {
                    var gap = space;
                    // Detect grid space on the small screen
                    if ( jQuery(window).width() < 1440 ) {
                        var grid_element = jQuery(
                            '.elementor-column-gap-extended > .elementor-row > .elementor-column > .elementor-element-populated,'	// Elm 2.9-
                            + '.elementor-column-gap-extended > .elementor-column > .elementor-element-populated'					// Elm 3.0+
                            ).eq(0),
                            grid_gap = grid_element.length ? parseInt( grid_element.css( 'padding-left' ), 10 ) : 0;
                        if ( grid_gap >= 10 ) {
                            gap = grid_gap * 2;
                        }
                    }
                    if ( gap > 0 && TRX_ADDONS_STORAGE['swipers'][id].params.spaceBetween > gap ) {
                        TRX_ADDONS_STORAGE['swipers'][id].params.spaceBetween = gap;
                        space = gap;
                    }
                }
                // Change slides_per_view
                var spv = slider.data('slides-per-view');
                if (spv == undefined || slider.parents('.widget_nav_menu').length > 0) {
                    spv = 1;
                }
                if (slider.hasClass('slider_swiper') && typeof TRX_ADDONS_STORAGE['swipers'][id].params == 'object' && typeof TRX_ADDONS_STORAGE['swipers'][id].params.slidesPerView != 'undefined') {
                    if (TRX_ADDONS_STORAGE['swipers'][id].params.slidesPerView != 'auto') {
                        if (direction=='horizontal') {
                            var smw = slider.data('slides-min-width');
                            if (slider_width / spv < smw) {
                                spv = Math.max(1, Math.floor(slider_width / smw));
                            }
                            if (TRX_ADDONS_STORAGE['swipers'][id].params.slidesPerView != spv) {
                                TRX_ADDONS_STORAGE['swipers'][id].params.slidesPerView = spv;
                                TRX_ADDONS_STORAGE['swipers'][id].params.loopedSlides = spv;
                                //TRX_ADDONS_STORAGE['swipers'][id].reInit();
                            }
                        }
                        on_resize = true;
                    }
                }
                // Change slider height
                if ( !slider.hasClass('slider_noresize') || slider.height()===0 ) {
                    var slide = slider.find('.slider-slide').eq(0);
                    var slide_width = slide.width();
                    var slide_height = slide.height();
                    var ratio = slider.data('ratio');
                    if (ratio===undefined || (''+ratio).indexOf(':')<1) {
                        ratio = slide_height > 0 ? slide_width+':'+slide_height : "16:9";
                        slider.attr('data-ratio', ratio);
                    }
                    ratio = ratio.split(':');
                    var ratio_x = !isNaN(ratio[0]) ? Number(ratio[0]) : 16;
                    var ratio_y = !isNaN(ratio[1]) ? Number(ratio[1]) : 9;
                    var height = Math.floor((spv==1 ? slider_width : slide_width)/ratio_x*ratio_y);
                    slider.height(direction == 'vertical' ? height * spv + (spv-1) * space : height);
                    on_resize = true;
                    if (slider.hasClass('slider_elastistack')) {
                        slider.find('.slider-wrapper,.stack__images,.slider-slide').height(height);
                    }
                    // Change controller height
                    trx_addons_set_controller_height(slider.data('controller'), slider, e);
                }
                // Call onResize handlers
                if (on_resize && (slider.hasClass('slider_swiper') || slider.hasClass('slider_swiper_outer'))) {
                    if (typeof TRX_ADDONS_STORAGE['swipers'][id] == 'object' && typeof TRX_ADDONS_STORAGE['swipers'][id].resize == 'object' && typeof TRX_ADDONS_STORAGE['swipers'][id].resize.resizeHandler == 'function') {
                        TRX_ADDONS_STORAGE['swipers'][id].resize.resizeHandler(e);
                    }
                }
            }
        });
    }

    // Set controller height
    function trx_addons_set_controller_height(controller_id, slider, e) {
        if ( !controller_id && typeof TRX_ADDONS_STORAGE['pagebuilder_preview_mode'] != 'undefined' && TRX_ADDONS_STORAGE['pagebuilder_preview_mode'] ) {
            var slider_id = slider.attr('id').replace('_sc_slider', '');
            if (slider_id) {
                controller_id = jQuery('[data-slider-id="' + slider_id + '"]').eq(0).attr('id');
            }
        }
        if ( !controller_id ) return;
        var controller = jQuery('#'+controller_id);
        if (controller.length > 0
            && controller.hasClass('sc_slider_controller_vertical')
            && controller.hasClass('sc_slider_controller_height_auto')
        ) {
            var controller_slider = controller.hasClass('slider_container') ? controller : controller.find('.slider_container'),
                controller_slider_id = controller_slider.attr('id');
            if (jQuery(window).width() >= 768) {
                var paddings = parseFloat(controller.css('paddingTop'));
                if (isNaN(paddings)) paddings = 0;
                controller_slider.height(slider.height() - 2*paddings);
            } else {
                var controller_spv = controller.data('slides-per-view');
                if (isNaN(controller_spv)) controller_spv = 1;
                controller_slider.height(controller_spv*100);
            }
            // Call onResize handlers
            if ((controller_slider.hasClass('slider_swiper') || controller_slider.hasClass('slider_swiper_outer'))) {
                if (typeof TRX_ADDONS_STORAGE['swipers'][controller_slider_id] == 'object' && typeof TRX_ADDONS_STORAGE['swipers'][controller_slider_id].resize == 'object' && typeof TRX_ADDONS_STORAGE['swipers'][controller_slider_id].resize.resizeHandler == 'function') {
                    TRX_ADDONS_STORAGE['swipers'][controller_slider_id].resize.resizeHandler(e);
                }
            }
        }
    }

})();
