(function($) {

    $(document).on('ready', function(e){
        var widget = $('.webien-video-wrapper');

        widget.each(function(){
            let el = $(this);
            let trigger = el.data('trigger');
            let videoPlayer = el.find('video')[0];
            let selectedOffset = el.data('offset');
            let hasControls = el.hasClass('has-controls');
            videoPlayer.addEventListener('play', (event) => {
                el.find('video').addClass('started');
            });
            videoPlayer.addEventListener('loadeddata', () => {
                el.find('video').addClass('loaded');
            });

            if(trigger === 'hover'){
                el.on({
                    mouseenter: function () {
                        videoPlayer.play();
                    },
                    mouseleave: function () {
                        if(el.hasClass('pause-leave')){
                            videoPlayer.pause();
                        };
                        if(el.hasClass('reset-leave')){
                            videoPlayer.currentTime = 0;
                            videoPlayer.pause();
                        };
                    }
                });
            }

            if(trigger === 'click'){
                if(!hasControls){
                    el.on({
                        click: function () {
                            videoPlayer.play();
                        }
                    });
                }

            }

            if(trigger === 'load'){
                videoPlayer.play();
            }

            if(trigger === 'scroll'){
                let waypoint = new Waypoint({
                    element: videoPlayer,
                    handler: function(direction) {
                        videoPlayer.play();
                    },
                    offset: (100 - selectedOffset) + '%',
                });
            }
        });
    });
}(jQuery));