var FlipCarousel = function($scope, $) {
    var $this = $(".eael-flip-carousel", $scope);

    var style = $this.data("style"),
        start = $this.data("start"),
        fadeIn = $this.data("fadein"),
        loop = $this.data("loop"),
        autoplay = $this.data("autoplay"),
        pauseOnHover = $this.data("pauseonhover"),
        spacing = $this.data("spacing"),
        click = $this.data("click"),
        scrollwheel = $this.data("scrollwheel"),
        touch = $this.data("touch"),
        buttons = $this.data("buttons"),
        buttonPrev = ($this.data("buttonprev")),
        buttonNext = ($this.data("buttonnext")),
        options = {
            itemContainer: '.eael-flip-container',
            itemSelector: '.eael-flip-item',
            style: style,
            start: start,
            fadeIn: fadeIn,
            loop: loop,
            autoplay: autoplay,
            pauseOnHover: pauseOnHover,
            spacing: spacing,
            click: click,
            scrollwheel: scrollwheel,
            tocuh: touch,
            buttons: buttons,
            buttonPrev: '',
            buttonNext: ''
        };

    options.buttonPrev = '<span class="flip-custom-nav">' + buttonPrev + '</span>';
    options.buttonNext = '<span class="flip-custom-nav">' + buttonNext + '</span>';

    function syncCarouselHeight() {
        var $flipsterContainer = $this.find('.flipster__container');
        var maxItemHeight = 0;

        $this.find('.flipster__item__content').each(function() {
            var itemHeight = $(this).outerHeight(true);
            if (itemHeight > maxItemHeight) {
                maxItemHeight = itemHeight;
            }
        });

        if (maxItemHeight > 0) {
            $flipsterContainer.css('height', maxItemHeight + 'px');
            $this.css('min-height', maxItemHeight + 'px');
        }
    }

    options.onItemSwitch = function() {
        setTimeout(syncCarouselHeight, 20);
    };
    $this.flipster(options);

    var checkActive = setInterval(function() {
        if (typeof $this !== 'undefined' && $this.hasClass('flipster--active')) {
            syncCarouselHeight();
            clearInterval(checkActive);
        }
    }, 100);

    $this.find('img').on('load', syncCarouselHeight);
    $(window).on('resize', function() {
        syncCarouselHeight();
    });
};

jQuery(window).on("elementor/frontend/init", function() {

    if (eael.elementStatusCheck('eaelFlipLoad')) {
        return false;
    }

    elementorFrontend.hooks.addAction(
        "frontend/element_ready/eael-flip-carousel.default",
        FlipCarousel
    );
});
