/* jshint esversion: 6 */
if ( 'function' !== typeof window.wpexPageAnimations ) {
	window.wpexPageAnimations = function() {
		const settings   = wpex_page_animations_params;
		const animatedEl = document.querySelector( '.wpex-page-animation' );
		const loader     = document.querySelector( '.wpex-page-animation__loading' );
		const hasOut     = settings.outClass || false;

		const hideLoader = () => {
			loader.classList.add( 'wpex-page-animation__loading--hidden' );
		};

		const inEvent = () => {
			hideLoader();
			animatedEl.style.animationDuration = settings.inDuration + 'ms';
			animatedEl.classList.add( 'wpex-page-animation--' + settings.inClass );
			setTimeout( () => {
				if ( 'undefined' !== typeof window.vc_rowBehaviour ) {
					vc_rowBehaviour();
				}
				document.dispatchEvent( new Event( 'wpexPageAnimationInEnd' ) );
			}, settings.inDuration );
		};

		const outEvent = () => {
			animatedEl.style.animationDuration = settings.outDuration + 'ms';
			animatedEl.classList.add( 'wpex-page-animation--' + settings.outClass );
		};

		const onPagesShow = ( event ) => {
			if ( true === event.persisted ) {
				animatedEl.className = 'wpex-page-animation wpex-page-animation--persisted';
			}
		};

		const onWindowLoad = () => {
			inEvent();
		};

		const onLinkClick = ( event ) => {
			const link = event.target.closest( 'a' );
			if ( ! link ) {
				return;
			}
			const href = link.getAttribute( 'href' );
			if ( ! href ) {
				return;
			}
			event.preventDefault();
			outEvent();
			setTimeout( () => {
				window.location = href;
			}, settings.outDuration );
		};

		/*** Add Event Listeners ****/
		if ( ! settings.devMode ) {
			window.addEventListener( 'pageshow', onPagesShow );
			window.addEventListener( 'load', onWindowLoad );
		}

		if ( hasOut ) {
			document.querySelectorAll( settings.linkElement ).forEach( ( link ) => {
				link.addEventListener( 'click', onLinkClick );
			} );
		}
	};
}

if ( document.readyState === 'interactive' || document.readyState === 'complete' ) {
	setTimeout( wpexPageAnimations, 0 );
} else {
	document.addEventListener( 'DOMContentLoaded', wpexPageAnimations, false );
}