var owlabkbs_file_frame;
jQuery(function($){
	

  //Open the WP media library on click  
  $('.owlabkbs-media-library').live('click', function( event ){

    event.preventDefault();


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

    // Create the media frame.
    owlabkbs_file_frame = wp.media.frames.file_frame = wp.media({
      title: owl_uploader_obj.title,
      button: {
        text: owl_uploader_obj.button_text
      },
      multiple: true  // Set to true to allow multiple files to be selected
    });

    //on open
    owlabkbs_file_frame.on( 'open', function() {

      var selection = owlabkbs_file_frame.state().get('selection');
      
      //get IDs of already selected images
      var IDs=[];
      $.each($("#owlabkbs-output > li.owlabkbs-slide"),function(){
        IDs.push($(this).data('owlabkbs-slide'));
      });

      //add these to the selection list
      IDs.forEach(function(id) {
        attachment = wp.media.attachment(id);
        selection.add( attachment ? [ attachment ] : [] );
      });

    });



    // When an image is selected, run a callback.
    owlabkbs_file_frame.on( 'select', function() {

        var data  = {
            action: 'owlabkbs_insert_slides',
            nonce:   owlabkbs_metabox.insert_nonce,
            post_id: owlabkbs_metabox.id,
            images:  {},
            videos:  {},
            html:    {}
        }

        var selection = owlabkbs_file_frame.state().get('selection');

        selection.map( function( attachment ,i) {
     
          attachment = attachment.toJSON();

          data.images[i]=attachment.id;
        });

        //Add new images
        owlabbulkg_media_make_ajax_call(data,function(){
            //Update the current images UI
            var data = {
                action:  'owlabkbs_refresh',
                post_id: owlabkbs_metabox.id,
                nonce:   owlabkbs_metabox.refresh_nonce
             };
            owlabbulkg_media_make_ajax_call(data,function(res){
                if ( res && res.success ) {
                    $('#owlabkbs-output').html(res.success);
                    
                }
            });
        });
     
    });


    function owlabbulkg_media_make_ajax_call(data,callback){
        
        $.post(
            owlabkbs_metabox.ajax,
            data,
            function(response){
                callback(response);
            },
            'json'
        );
      
    }

    // Finally, open the modal
    owlabkbs_file_frame.open();
  });

});