'use strict';

(function($) {
  $(function() {
    $('.DejavoVS_color').wpColorPicker();
    // Only show the "remove image" button when needed
    if ('' === $('#DejavoVS_image').val()) {
      $('#DejavoVS_remove_image').hide();
    }
  });

  $(document).on('click touch', '#DejavoVS_upload_image', function(e) {
    // Uploading files
    var DejavoVS_media;

    e.preventDefault();
    // If the media frame already exists, reopen it.
    if (DejavoVS_media) {
      DejavoVS_media.open();
      return;
    }
    // Create the media frame.
    DejavoVS_media = wp.media.frames.downloadable_file = wp.media({
      title: 'Choose an image',
      button: {
        text: 'Use image',
      },
      multiple: false,
    });
    // When an image is selected, run a callback.
    DejavoVS_media.on('select', function() {
      var attachment = DejavoVS_media.state().
      get('selection').
      first().
      toJSON();
      $('#DejavoVS_image').val(attachment.id);
      $('#DejavoVS_image_thumbnail').
      find('img').
      attr('src', attachment.sizes.thumbnail.url);
      $('#DejavoVS_remove_image').show();
    });
    // Finally, open the modal.
    DejavoVS_media.open();
  });

  $(document).on('click touch', '#DejavoVS_remove_image', function() {
    $('#DejavoVS_image_thumbnail').
    find('img').
    attr('src', DejavoVS_vars.placeholder_img);
    $('#DejavoVS_image').val('');
    $('#DejavoVS_remove_image').hide();
    return false;
  });
})(jQuery);