/* globals waitForFinalEvent: false */
'use strict';

jQuery( document ).ready(function( $ ) {
	// Setup sections & background heights (+borders, padding etc)
	if ($.fn.shrk_set_sections) {
		$( 'section.section' ).shrk_set_sections();

		if ( typeof(waitForFinalEvent) === 'function' )  {
			$(window).resize(function() { 
				waitForFinalEvent(function() { 
					$( 'section.section' ).shrk_set_sections(); 
				}, 200, 'resetSections'); 
			});
		} else {
			$(window).resize(function() { 
				$( 'section.section' ).shrk_set_sections(); 
			});
		}
	}

	// Take care of video backgrounds in swiper-slides
	$(window).on('shrk_swipers_init', function () {
		// Pause video bg on not-active slide
		$('.swiper-slide:not(.swiper-slide-active) .section-background.video.autostart video').each( function () {
			$(this)[0].pause();

			// Control play pause based on active slide or not
			var sw_index = shrk.swipers.getIndex( $(this).closest('.shrk-swiper-container') );
			shrk.swipers.instances[sw_index].on( 'onSlideChangeEnd', function(s) { 
				$(s.container).find('.swiper-slide.swiper-slide-active .section-background.video.autostart video').each( function() {
					$(this)[0].play();
				});

				$(s.container).find('.swiper-slide:not(.swiper-slide-active) .section-background.video.autostart video').each( function () {
					$(this)[0].pause();
				});
			});
		});
	});

	if ( $('.section-background.video.autostart').length > 0 && typeof jQuery.fn.isOnScreen === 'function' ) {
		// Bind onScroll events
		$(window).scroll( function () {
			handle_autostart_video( $('.section-background.video.autostart') );
		});

		$(window).on('shrk_init_page', function () {
			handle_autostart_video( $('.section-background.video.autostart') );
		});
	}

	function handle_autostart_video( $elements ) {
		$elements.each( function () {
			// Exclude if in swiper
			if ( $(this).closest('.shrk-swiper-container').length > 0 ) {
				return true; // continue .each loop
			} 

			if ( $(this).isOnScreen(function(deltas){
				return deltas.top >= -100 && deltas.bottom >= -100;
			}) ) {
				if ( $(this).hasClass('playing') ) {
					return true; // continue .each loop
				}
				$(this).find('video')[0].play();
				$(this).addClass('playing').removeClass('paused');
			} else {
				if ( $(this).hasClass('paused') ) {
					return true; // continue .each loop
				}
				$(this).find('video')[0].pause();
				$(this).addClass('paused').removeClass('playing');
			}
		});		
	}
});
