jQuery(document).ready(function($){

  var image_frame;

  $(".avatar_uploader").click(function(e){
    e.preventDefault();
      console.log("click");

    if(image_frame){
      image_frame.open();
      return;
    }

   image_frame = wp.media.frames.file_frame = wp.media({
     title: 'Bild auswählen',
     button: {
     text: 'Bild auswählen'
   }, multiple: false });
    image_frame.on('close',function () {
        console.log('close')
    })

   image_frame.on('select', function() {
     var attachment = image_frame.state().get('selection').first().toJSON();

     var data = {
       'action' : 'avatar_action',
       'url'    : attachment.url
     }
     $.post(ajax_object.ajax_url, data, function(response){
         console.log(response);
         $(".avatar").attr('src',attachment.url);
         $(".avatar").removeAttr("srcset");
     });
   });
   // Open the uploader dialog
   image_frame.open();


  });
});
