(function () {
	'use strict';

	jQuery(function ($) {
	  var body = $('body');
	  body.on('click', '.nishiki-pro-image-uploader', function (e) {
	    e.preventDefault();
	    var button = $(this),
	        customUploader = wp.media({
	      title: '画像を選択',
	      library: {
	        type: 'image'
	      },
	      button: {
	        text: 'この画像を使う'
	      },
	      multiple: false
	    }).on('select', function () {
	      var attachment = customUploader.state().get('selection').first().toJSON();
	      var removeButton = $('.nishiki-pro-remove-image');
	      var current = $('.nishiki-pro-image-current');
	      var preview = $('.nishiki-pro-image-loader-preview');
	      var val = $('#eye_catch');

	      if (!preview.length) {
	        $(button).before('<img class="nishiki-pro-image-loader-preview" src="' + attachment.url + '" style="max-width:320px;margin-bottom:1rem;display:block;" alt="" />');
	      } else {
	        preview.attr('src', attachment.url);
	      }

	      if (current.length) {
	        current.remove();
	      }

	      val.val(attachment.id);

	      if (!removeButton.length) {
	        $(button).after('<a href="#" class="nishiki-pro-remove-image button">画像を削除</a>');
	      }
	    }).open();
	  });
	  body.on('click', '.nishiki-pro-remove-image', function () {
	    var preview = $('.nishiki-pro-image-loader-preview');
	    var current = $('.nishiki-pro-image-current');
	    var val = $('#eye_catch');

	    if (preview.length) {
	      preview.remove();
	    }

	    if (current.length) {
	      current.remove();
	    }

	    $(this).remove();
	    val.val('');
	    return false;
	  });
	});

}());
