(function () {
	'use strict';

	var ANIM_DURATIONS = {
		shrink: 300,
		zoom: 350
	};

	function onReady( fn ) {
		if ( document.readyState !== 'loading' ) {
			fn();
		} else {
			document.addEventListener( 'DOMContentLoaded', fn );
		}
	}

	function playAnimation( item, anim ) {
		var iconWrap = item.querySelector( '.udock-nav-icon-wrap' );
		if ( ! iconWrap || ! anim || 'none' === anim ) {
			return;
		}
		var playClass = 'udock-play-' + anim;
		iconWrap.classList.remove( playClass );
		void iconWrap.offsetWidth; // force reflow so it can replay if clicked again quickly
		iconWrap.classList.add( playClass );
	}

	function bindClickAnimations() {
		var items = document.querySelectorAll( '.udock-nav-item[data-udock-anim]' );

		items.forEach( function ( item ) {
			var anim = item.getAttribute( 'data-udock-anim' );
			if ( ! anim || 'none' === anim ) {
				return;
			}

			var isLink       = item.tagName === 'A';
			var href         = isLink ? item.getAttribute( 'href' ) : null;
			var navigatesAway = isLink && href && href !== '#' && href.indexOf( '#' ) !== 0;

			item.addEventListener( 'click', function ( e ) {
				if ( navigatesAway ) {
					// Delay the actual navigation just long enough for the
					// animation to be visible before the page unloads.
					e.preventDefault();
					playAnimation( item, anim );
					var target = href;
					setTimeout( function () {
						window.location.href = target;
					}, ANIM_DURATIONS[ anim ] || 300 );
				} else {
					playAnimation( item, anim );
				}
			} );
		} );
	}

	function bindSearchOverlay() {
		var overlay = document.getElementById( 'udock-search-overlay' );
		if ( ! overlay ) {
			return;
		}
		var closeBtn = overlay.querySelector( '.udock-search-close' );
		var triggers = document.querySelectorAll( '[data-udock-search-trigger]' );

		triggers.forEach( function ( trigger ) {
			trigger.addEventListener( 'click', function () {
				overlay.classList.add( 'udock-open' );
			} );
		} );

		if ( closeBtn ) {
			closeBtn.addEventListener( 'click', function () {
				overlay.classList.remove( 'udock-open' );
			} );
		}

		document.addEventListener( 'keydown', function ( e ) {
			if ( e.key === 'Escape' ) {
				overlay.classList.remove( 'udock-open' );
			}
		} );
	}

	function bindVibration() {
		if ( typeof UNODOCK_FRONT === 'undefined' || ! UNODOCK_FRONT.vibrateEnabled ) {
			return;
		}
		if ( ! ( 'vibrate' in navigator ) ) {
			return;
		}

		var items = document.querySelectorAll( '.udock-nav-item' );
		items.forEach( function ( item ) {
			item.addEventListener( 'click', function () {
				navigator.vibrate( 15 );
			} );
		} );
	}

	onReady( function () {
		bindClickAnimations();
		bindSearchOverlay();
		bindVibration();
	} );

})();
