(function ($) {

	function initEcafeMarquee($scope) {

		var $marquee = $scope.find('.ecafe-marquee-wrapper');

		$marquee.each(function () {

			var $this = $(this);

			if ($this.data('initialized')) {
				return;
			}

			$this.data('initialized', true);

			var $track = $this.find('.ecafe-marquee-track');

			var speed = $this.data('speed') || 25;

			var content = $track.html();

			while ($track[0].scrollWidth < $this.outerWidth() * 2) {
				$track.append(content);
			}

			$track.append(content);

			var contentWidth = $track[0].scrollWidth / 2;

			var direction = $this.hasClass('ecafe-marquee-ltr') ? 'ltr' : 'rtl';

			var keyframeName = 'ecafe-marquee-' + $this.attr('id');

			var start = direction === 'rtl' ? 0 : -contentWidth;
			var end = direction === 'rtl' ? -contentWidth : 0;

			var style = `
				@keyframes ${keyframeName} {
					from { transform: translateX(${start}px); }
					to { transform: translateX(${end}px); }
				}
			`;

			$('head').append('<style>' + style + '</style>');

			$track.css({
				animation: keyframeName + ' ' + speed + 's linear infinite'
			});

			/* Pause on hover */
			if ($this.hasClass('ecafe-marquee-pause')) {

				$this.on('mouseenter', function () {
					$track.css('animation-play-state', 'paused');
				});

				$this.on('mouseleave', function () {
					$track.css('animation-play-state', 'running');
				});

			}

		});

	}

	$(window).on('elementor/frontend/init', function () {

		elementorFrontend.hooks.addAction(
			'frontend/element_ready/ecafe-marquee.default',
			initEcafeMarquee
		);

	});

})(jQuery);