(function($){
  function syncVisibility(){
    var type = $('#nikan_story_media_type').val() || 'image';
    $('.nikan-only-image').toggle(type === 'image');
    $('.nikan-only-video').toggle(type === 'video');
  }

  $(document).on('change', '#nikan_story_media_type', syncVisibility);

  $(document).on('click', '.nikan-pick-image', function(e){
    e.preventDefault();
    var frame = wp.media({
      title: 'انتخاب تصویر',
      library: { type: 'image' },
      button: { text: 'انتخاب' },
      multiple: false
    });

    frame.on('select', function(){
      var attachment = frame.state().get('selection').first().toJSON();
      $('#nikan_story_image_id').val(attachment.id);
      $('.nikan-image-preview img').attr('src', attachment.sizes && attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url);
      $('.nikan-image-preview').show();
      $('.nikan-remove-image').show();
    });

    frame.open();
  });

  // Cover picker
  $(document).on('click', '.nikan-pick-cover', function(e){
    e.preventDefault();
    var frame = wp.media({
      title: 'انتخاب کاور',
      library: { type: 'image' },
      button: { text: 'انتخاب' },
      multiple: false
    });

    frame.on('select', function(){
      var attachment = frame.state().get('selection').first().toJSON();
      $('#nikan_story_cover_id').val(attachment.id);
      $('.nikan-cover-preview img').attr('src', attachment.sizes && attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url);
      $('.nikan-cover-preview').show();
      $('.nikan-remove-cover').show();
    });

    frame.open();
  });

  $(document).on('click', '.nikan-remove-cover', function(e){
    e.preventDefault();
    $('#nikan_story_cover_id').val('');
    $('.nikan-cover-preview').hide();
    $('.nikan-remove-cover').hide();
  });

  $(document).on('click', '.nikan-remove-image', function(e){
    e.preventDefault();
    $('#nikan_story_image_id').val('');
    $('.nikan-image-preview').hide();
    $('.nikan-remove-image').hide();
  });

  $(function(){
    syncVisibility();
  });
})(jQuery);
