// source --> https://sandefjordevangeliske.no/wp-content/plugins/creative-sermons/js/creative-sermons.js?v= 
var player;

(function($) {
    
    $(function () {

        // Counter
        if( $('#sermons-live-player-counter').length ) {
            
			var countDownDate = new Date( $('#sermons-live-player-counter').data('start-date-utc') ).getTime();
			var stopDate = new Date( $('#sermons-live-player-counter').data('end-date-utc') ).getTime();
			
			var now = new Date();
			var utcTimeOffset = now.getTimezoneOffset();

            var x = setInterval(function() {

                var now = new Date().getTime();

				now = now + ( utcTimeOffset * 60 * 1000 );

                var distance = countDownDate - now;

                var days = Math.floor( distance / ( 1000 * 60 * 60 * 24 ) );
                var hours = Math.floor( ( ( distance % ( 1000 * 60 * 60 * 24 ) ) / ( 1000 * 60 * 60 ) ) );
                var minutes = Math.floor( ( distance % ( 1000 * 60 * 60 ) ) / ( 1000 * 60 ) );
                var seconds = Math.floor( ( distance % ( 1000 * 60 ) ) / 1000 );

                if ( distance < 0 ) {
					$( '#sermon-player-container' ).addClass( 'live' );
					if ( now < stopDate && $( '#sermons-live-player' ).is(':visible') ) {
						playLiveVideo();
					} else if ( now < stopDate ) {
						$( '#sermons-live-player-preview-message ').hide();
						$( '#sermons-live-player-video, #vimeo-player' ).show();
					}
					if ( ! $( '#sermon-player-container' ).hasClass('streaming') && $( '#sermon-player-container' ).hasClass('autoplay') ) {
						$( '#live-streaming-container' ).show();
					}
					countDownDate = countDownDate + 7 * 24 * 60 * 60 * 1000;
				}

				if ( now > stopDate ) {
					$( '#sermon-player-container' ).removeClass( 'live' );
					stopLiveVideo();
					if ( ! $( '#sermon-player-container' ).hasClass('streaming') && $( '#sermon-player-container' ).hasClass('autoplay') ) {
						$( '#sermons-live-player, #live-streaming-container' ).hide();
						$( '#sermons-player' ).show();
					}
				}

                $('#sermons-live-player-counter-days span').html( days );
                $('#sermons-live-player-counter-hours span').html( hours );
                $('#sermons-live-player-counter-minutes span').html( minutes );
                $('#sermons-live-player-counter-seconds span').html( seconds );

            }, 1000);
            
        }

        // Sermons Filter
        if ( $('#loop-wrapper').hasClass('list') && $('#loop-wrapper').hasClass('catf-content') ) {
            $(document).on('catf-get', function() {
                $('#loop-wrapper > article').not('.active').each(function (index, element) {
                    $(this).attr('style', 'animation-delay:' + ( ( $('#loop-wrapper > article').length - index ) * 50 ) + 'ms');
                });
                $('.fs-wrap').addClass('fs-disabled');
				$('#sermons-loading').addClass('visible');
				$('#sermons-content').addClass('loading');
                if( $('#loop-wrapper > article').css('opacity') == 1 )
                    $('#loop-wrapper > article').addClass('active');
                // $('#loop-wrapper > article').removeClass('slideUp').addClass('slideDown');
            });
            $(document).on('catf-done', function() {
                $('#loop-wrapper > article').not('.active').each(function (index, element) {
                    $(this).attr('style', 'animation-delay:' + ( index * 50 ) + 'ms');
                });
                $('.fs-wrap').removeClass('fs-disabled');
				$('#sermons-loading').removeClass('visible');
				$('#sermons-content').removeClass('loading');
                $('#sermons-filter').animate({ opacity: 1 }, 300);
                $('#loop-wrapper > article').removeClass('slideDown').addClass('slideUp');

                // Bible books toggle feature - show and hide children items
                $('#sermons-filter-bible-books .fs-option, #sermons-filter-bible-books .fs-option .toggle').off('click');
                var toggleContainerOpen = undefined;
                $('#sermons-filter-bible-books .fs-option').each(function (index, element) {
                    if ( $(this).hasClass('d2') && toggleContainerOpen === undefined && ! $(this).parent().hasClass('collapse') ) {
                        toggleContainerOpen = index;
                        $(this).prev().append('<span class="toggle"></span>');
                        $(this).prev().addClass('collapsed');
                    };
                    if ( ! $(this).hasClass('d2') && toggleContainerOpen >= 0 ) {
                        $('#sermons-filter-bible-books .fs-option').slice( toggleContainerOpen, index).wrapAll('<div class="collapse">');
                        toggleContainerOpen = undefined;
                    };
                });
                if ( toggleContainerOpen >= 0 ) {
                    $('#sermons-filter-bible-books .fs-option').slice( toggleContainerOpen, $('#sermons-filter-bible-books .fs-option').length ).wrapAll('<div class="collapse">');
                }

                var newDiv = 0;
                var toggleContainerOpen = undefined;
                var toggleIndex = []
                $('#sermons-filter-bible-books .fs-options > div').each(function (index, element) {
                    if ( $(this).hasClass('d1') && toggleContainerOpen === undefined && ! $(this).parent().hasClass('collapse') ) {
                        toggleContainerOpen = index;
                        $(this).prev().append('<span class="toggle"></span>');
                        $(this).prev().addClass('collapsed');
                    };
                    if ( $(this).hasClass('d0') && ( toggleContainerOpen >= 0 || toggleContainerOpen == undefined || index == 0 ) ) {
                        toggleContainerOpen = undefined;
                        toggleIndex.push( index );
                    }; 
                });

                var toggleContainerClose = $('#sermons-filter-bible-books .fs-options > div').length;
            
                for (let index = toggleIndex.length; index > 0; index--) {
                    if ( index < toggleIndex.length ) {
                        $('#sermons-filter-bible-books .fs-options > div').slice( toggleIndex[index-1]+1, toggleIndex[index] ).wrapAll('<div class="collapse">');
                    } else {
                        $('#sermons-filter-bible-books .fs-options > div').slice( toggleIndex[index-1]+1, toggleContainerClose ).wrapAll('<div class="collapse">');
                    }
                }

                 
                // Bible books click behavior
                $('#sermons-filter-bible-books .fs-option').click(function (e) { 
                    if ( $(this).hasClass('selected') ) {
                        $(this).addClass('collapsed');
                        $(this).next().removeClass('show'); 
                    }else{
                        $(this).removeClass('collapsed');
                        $(this).next().addClass('show'); 

                        $(this).next().find('.collapse').prev().addClass('collapsed');
                        $(this).next().find('.collapse').removeClass('show'); 

                        $(this).parent().prev().removeClass('selected');
                        $(this).parent().parent().prev().removeClass('selected');
                        if ( $(this).next().hasClass('collapse') ) {
                            $(this).next().find('.selected').removeClass('selected');
                        }
                    }
                });

                // Bible books toggle button
                $('#sermons-filter-bible-books .fs-option .toggle').click(function (e) { 
                    e.stopPropagation();
                    $(this).parent().toggleClass('collapsed');
                    $(this).parent().next().toggleClass('show');
                });

                // Tooltips
                tippy('[data-tippy-content]');

                // Sermons items link on all the element
                $('#sermons-content article').each(function (index, element) {
                    $(this).click(function (e) { 
                        window.location = $(this).find('.entry-image-link').attr('href');
                    });
                });
              
            });

            $(document).trigger('catf-done');

        } else if ( $('#loop-wrapper').hasClass('list') ) {
            $('#loop-wrapper > article').each(function (index, element) {
                $(this).attr('style', 'animation-delay:' + ( index * 50 ) + 'ms');
            });
            $('.fs-wrap').removeClass('fs-disabled');
            $('#sermons-loading').removeClass('visible');
            $('#sermons-filter').animate({ opacity: 1 }, 300);
            $('#loop-wrapper > article').removeClass('slideDown').addClass('slideUp');
        }

		// Filter Mobile Open & Close
		$('#sermons-filter h3').click(function (e) { 
			e.preventDefault();				
			$(this).parent().toggleClass('show');
		});

        // Sermons Filter Clear All Button
        $('#sermons-filter-clear-all').click(function (e) { 
            e.preventDefault();
            catfReset();
        });

        // Sermons items
        $('#sermons-content article').each(function (index, element) {
            $(this).click(function (e) { 
                location = $(this).find('.entry-image-link').attr('href');
            });
        });

        // Sermons Player
        if ( $('#sermons-player-options').length ) {
            $('#sermons-player-options-video').click(function (e) {
                e.preventDefault();
				$('#sermons-player-audio').hide();
				if ( cleanPlayerObj[1] !== undefined ) {
					cleanPlayerObj[1].stop();
				}
                $('#sermons-player-video').show();
                // cleanPlayerObj[0].play();
            });
            $('#sermons-player-options-audio').click(function (e) { 
                e.preventDefault();
				$('#sermons-player-video').hide();
				if ( cleanPlayerObj[0] !== undefined ) {
					cleanPlayerObj[0].stop();
				}
                $('#sermons-player-audio').show();
                // $('#cleanPlayerList ul > li:first-child').trigger('click');
            });
        }

        // Download Audio Sermon
        $('#sermons-player-options-download').click(function (e) { 
			e.preventDefault();
			document.getElementById('iframe-download').src = jsGlobalVars.ajaxUrl + '?action=csrm_download_ajax&id=' + $(this).data('id');
        });

    });

    $(window).load(function() {

        // Sermons Live Streaming
        $('#cleanPlayerList .live-streaming li').click(function (e) {
            cleanPlayerObj[0].stop();
            if ( player !== undefined )
                playLiveVideo();
            $('.yt_player_iframe').each(function(){
                this.contentWindow.postMessage('{"event":"command","func":"startVideo","args":""}', '*')
            });
            $('.chp__item--active').removeClass('chp__item--active');
            $(this).addClass('chp__item--active');
            $('#sermons-player').hide();
            $('#sermons-live-player').show();
        });

        $('#cleanPlayerList .chp__playlist li').click(function (e) {
            $('#sermons-live-player').hide();
            $('#sermons-player').show();
            if ( player !== undefined ) {
                player.stopVideo();
			}
			if ( sermonsPlayerNotes[ $( this ).index() ] !== undefined && sermonsPlayerNotes[ $( this ).index() ] != '' && sermonsPlayerOnlineNotes[ $( this ).index() ] !== undefined && sermonsPlayerOnlineNotes[ $( this ).index() ] != '' ) {
				$( '#sermons-player-footer' ).show();
			} else {
				$( '#sermons-player-footer' ).hide();
			}
			if ( sermonsPlayerNotes[ $( this ).index() ] !== undefined && sermonsPlayerNotes[ $( this ).index() ] != '' ) {
				$( '#sermons-player-footer-notes' ).show().find( 'a' ).attr( 'href', sermonsPlayerNotes[ $( this ).index() ] );
			} else {
				$( '#sermons-player-footer-notes' ).hide();
			}
			if ( sermonsPlayerOnlineNotes[ $( this ).index() ] !== undefined && sermonsPlayerOnlineNotes[ $( this ).index() ] != '' ) {
				$( '#sermons-player-footer-online-notes' ).show().find( 'a' ).attr( 'href', sermonsPlayerOnlineNotes[ $( this ).index() ] );
			} else {
				$( '#sermons-player-footer-online-notes' ).hide();
			}
		});
		
        // Tooltips
        tippy('[data-tippy-content]');

    });

})( jQuery );


// YOUTUBE PLAYER
if ( document.getElementById('youtube-player') ) {

    // Youtube Videos
    var tag = document.createElement('script');

    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var videoId = document.getElementById('youtube-player').getAttribute("data-video-id");
    function onYouTubeIframeAPIReady() {
		player = new YT.Player('youtube-player', {
			width: '768',
			height: '432',
			videoId: videoId,
			events: {
			'onReady': function(event) {
				playLiveVideo();
			}
			}
		});
    }

}

function playLiveVideo() {
    if ( document.getElementById( 'sermon-player-container' ).classList.contains( 'live' ) ) {
		document.getElementById('sermons-live-player-preview-message').style.display = 'none';
		document.getElementById('sermons-player').style.display = 'none';
		document.getElementById('sermons-live-player-video').style.display = 'block';
		document.getElementById('sermons-live-player').style.display = 'block';
		document.getElementById('vimeo-player').style.display = 'block';
		if ( player !== undefined ) {
			player.playVideo();
		}
	}
}

function stopLiveVideo() {
	document.getElementById('sermons-live-player-video').style.display = 'none';
	document.getElementById('sermons-live-player-preview-message').style.display = 'block'
	if ( player !== undefined ) {
		player.stopVideo();
	}
};