jQuery(function($) {

	"use strict";
	
	$('.custom_pswp').on( 'click', '.woocommerce-product-gallery__image a', function ( e ) {
		e.preventDefault();

		var items = getGalleryItems(),
			$target = $( e.target ),
			options = {
				index              : $target.closest( '.woocommerce-product-gallery__image' ).index(),
				history            : false,
				bgOpacity          : 0.85,
				showHideOpacity    : true,
				captionEl          : true,
				fullscreenEl       : false,
				shareEl            : false,
				tapToClose         : true,
				tapToToggleControls: false
			};

		var lightBox = new PhotoSwipe( $( '.pswp' ).get(0), window.PhotoSwipeUI_Default, items, options );
		lightBox.init();
	} );
	/**
	 * Private function to get gallery items
	 * @returns {Array}
	 */
	function getGalleryItems() {
		var items = [];
		var $slides = $('.custom_pswp .woocommerce-product-gallery__image');

		if ( $slides.length > 0 ) {
			$slides.each( function( i, el ) {
				var img = $( el ).find( 'img' ),
					large_image_src = img.attr( 'data-large_image' ),
					large_image_w   = img.attr( 'data-large_image_width' ),
					large_image_h   = img.attr( 'data-large_image_height' ),
					item            = {
						src  : large_image_src,
						w    : large_image_w,
						h    : large_image_h,
						title: img.attr( 'data-caption' ) ? img.attr( 'data-caption' ) : ''
					};
				items.push( item );
			} );
		}

		return items;
	}
})
