'use strict';

jQuery(function ($) {
	var mediaFrame = null,
		$currentImageSelector = null;

	//The "Select Image" button.
	$('.ame-select-image').on('click', function (event) {
		event.preventDefault();
		$currentImageSelector = $(this).closest('.ame-image-selector');

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

		//Initialise the media frame.
		mediaFrame = wp.media({
			title: 'Select Image',
			button: {
				text: 'Select Image'
			},
			library: {
				type: 'image'
			},
			multiple: false  //Only select one image.
		});

		//Save the choice the user clicks the select button.
		mediaFrame.on('select', function () {

			//Get media attachment details from the frame.
			var attachment = mediaFrame.state().get('selection').first().toJSON();

			//Store the attachment ID.
			$currentImageSelector.find('input.ame-image-attachment-id').val(attachment.id);

			//Display the image.
			var $preview = $currentImageSelector.find('.ame-image-preview');
			$preview.find('.ame-image-preview-placeholder').hide();
			$preview.find('img').remove();
			$preview.append($('<img  src="">').attr('src', attachment.url));

			//Show the "remove image" link.
			$currentImageSelector.find('.ame-remove-image-link').show();

			$currentImageSelector.trigger('admin-menu-editor:media-image-selected');
		});

		//Open the modal.
		mediaFrame.open();
	});

	//The "Remove Image" link.
	$('.ame-remove-image-link').on('click', function (event) {
		event.preventDefault();
		$currentImageSelector = $(this).closest('.ame-image-selector');

		//Remove the preview and show a placeholder instead.
		var $preview = $currentImageSelector.find('.ame-image-preview');
		$preview.find('img').remove();
		$preview.find('.ame-image-preview-placeholder').show();

		//Clear attachment data.
		$currentImageSelector.find('input.ame-image-attachment-id').val(0);

		//Hide the "remove image" link.
		$(this).hide();

		$currentImageSelector.trigger('admin-menu-editor:media-image-removed');
	});
});
