"use strict";

jQuery(function($) {
	// Product gallery file uploads
	var product_gallery_frame;
	var $image_gallery_id = $('.gfxbucket_cover_image_url');
	var $product_images = $('.gfxbucket_cover_image');

	$('.gfxbucket_cover_image_button_remove').on( 'click', function( event ) {
		var $el = $(this);
		event.preventDefault();

		$('.gfxbucket_cover_image_button').show();
		$('.gfxbucket_cover_image_button_remove').hide();

		$product_images.html('');
		$image_gallery_id.val('');

	});

	$('.gfxbucket_cover_image').on( 'click', '.gfxbucket_cover_image_button', function( event ) {
		setImage(event);
	});

	$('.gfxbucket_cover_image_button').on( 'click', function( event ) {
		setImage(event);
	});

	function setImage(event) {
		var $el = $(this);
		var attachment_id = $image_gallery_id.val();

		event.preventDefault();

		// If the media frame already exists, reopen it.
		if ( product_gallery_frame ) {
			product_gallery_frame.open();
			return;
		}

		// Create the media frame.
		product_gallery_frame = wp.media.frames.product_gallery = wp.media({
			// Set the title of the modal.
			title: $el.data('choose'),
			button: {
				text: $el.data('update'),
			},
			states : [
				new wp.media.controller.Library({
					title: $el.data('choose'),
					filterable :	'all',
					multiple: true,
				})
			]
		});

		// When an image is selected, run a callback.
		product_gallery_frame.on( 'select', function() {

			var selection = product_gallery_frame.state().get('selection');

			selection.map( function( attachment ) {

				attachment = attachment.toJSON();

				if ( attachment.id ) {
					attachment_id   = attachment.id;
					var attachment_image = attachment.sizes.medium ? attachment.sizes.medium.url : attachment.url;

					$('.gfxbucket_cover_image_button').hide();
					$('.gfxbucket_cover_image_button_remove').show();

					$product_images.append('<a class="gfxbucket_cover_image_button" href="#"><img style="max-width: 100%; height: auto;" src="' + attachment_image + '" /></a>');
				}

			});

			$image_gallery_id.val( attachment_id );
		});

		// Finally, open the modal.
		product_gallery_frame.open();
	}
});