( function ( $ ) {
    $( window ).on( "elementor/frontend/init", function () {
        var WPMOZOSplitImage = elementorModules.frontend.handlers.Base.extend( {
            bindEvents: function () {
                this.change();
            },
            change: function () {
                const $this = this.$element.find(".wpmozo_split_image");
                    if ( $this.length > 0 ) {
                        $this.each( function() {
                            wpmozo_init_split_image( $( this ) );
                        } );
                    }
                
                // Init split image.
                function wpmozo_init_split_image( thisObj ) {
                    const $w = thisObj.find( '.wpmozo_split_image_wrapper' ),
                        cols = parseInt( $w.data('columns') ) || 3,
                        image = $w.data('image'),
                        rows = parseInt( $w.data('rows') ) || 3;
                
                    $w.css( {
                        'display':'grid',
                        'grid-template-columns': `repeat(${cols},1fr)`,
                        'grid-template-rows': `repeat(${rows},1fr)`
                    } );
                
                    const bgSize = `${cols * 100}% ${rows * 100}%`;
                
                    $w.find('.wpmozo_split_image_portion').css({
                        'background-size': bgSize,
                        'background-image': `url(${image})`,
                        'background-repeat': 'no-repeat'
                    }).each(function(index) {
                        const x = index % cols;
                        const y = Math.floor(index / cols);
                    
                        // correct calculation
                        const posX = (x * 100) / (cols - 1 || 1);
                        const posY = (y * 100) / (rows - 1 || 1);
                    
                        $(this).css('background-position', `${posX}% ${posY}%`);
                    });
                    
                }                             
            },
        } );
        elementorFrontend.elementsHandler.attachHandler( "wpmozo_ae_split_image", WPMOZOSplitImage );
    } );
} )( jQuery );
