( function() {
	'use strict';

	function initThumbNav() {
		var gallery = document.querySelector( '.larder-product-gallery' );
		if ( ! gallery ) {
			return;
		}
		var thumbs = gallery.querySelector( '.flex-control-thumbs' );
		if ( ! thumbs ) {
			return;
		}
		if ( thumbs.scrollWidth <= thumbs.clientWidth ) {
			return;
		}

		var prev = document.createElement( 'button' );
		prev.className = 'larder-thumb-nav larder-thumb-nav--prev';
		prev.setAttribute( 'aria-label', larderThumbNav.prev );
		prev.innerHTML = '&#8249;';

		var next = document.createElement( 'button' );
		next.className = 'larder-thumb-nav larder-thumb-nav--next';
		next.setAttribute( 'aria-label', larderThumbNav.next );
		next.innerHTML = '&#8250;';

		var wrapper = document.createElement( 'div' );
		wrapper.style.position = 'relative';
		thumbs.parentNode.insertBefore( wrapper, thumbs );
		wrapper.appendChild( thumbs );
		wrapper.appendChild( prev );
		wrapper.appendChild( next );

		function updateArrows() {
			prev.classList.toggle( 'is-visible', thumbs.scrollLeft > 0 );
			next.classList.toggle( 'is-visible', thumbs.scrollLeft + thumbs.clientWidth < thumbs.scrollWidth - 1 );
		}

		prev.addEventListener( 'click', function() {
			thumbs.scrollLeft -= 90;
		} );
		next.addEventListener( 'click', function() {
			thumbs.scrollLeft += 90;
		} );
		thumbs.addEventListener( 'scroll', updateArrows );
		updateArrows();

		wrapper.addEventListener( 'mouseenter', function() {
			wrapper.classList.add( 'is-hovered' );
		} );
		wrapper.addEventListener( 'mouseleave', function() {
			wrapper.classList.remove( 'is-hovered' );
		} );
	}

	if ( document.readyState === 'complete' ) {
		setTimeout( initThumbNav, 500 );
	} else {
		window.addEventListener( 'load', function() {
			setTimeout( initThumbNav, 500 );
		} );
	}
} )();
