/**
 * Created by imyuvii on 13/11/16.
 */
var media_uploader = null;

function open_media_uploader_multiple_images()
{
    var idsContainer = jQuery("[name='webtangl_ejg_options[gallery-ids]']");

    media_uploader = wp.media({
        title: 'Select or Upload Media Of Your Chosen Persuasion',
        frame:    "post",
        state:    "gallery",
        multiple: true
    });

    media_uploader.on("update", function(){
        var library = media_uploader.state().get( 'library'), image_urls = [], image_ids = [], images = [];

        library.map( function( image ) {
            image = image.toJSON();
            image_urls.push( image.url );
            image_ids.push( image.id );
            images.push({
                "id" : image.id,
                "url" : {
                    "thumbnail" : image.sizes.thumbnail.url,
                    "medium" : image.sizes.medium.url,
                    "full": image.sizes.full.url
                },
                "caption" : image.caption
            });
        });
        idsContainer.text( JSON.stringify(images) );
    });

    media_uploader.on("open", function() {
        var selection = media_uploader.state().get('selection'), images = idsContainer.val();
        try {
            images = jQuery.parseJSON(images);
            if(images.length()>0) {
                images.forEach(function(image) {
                    var attachment = wp.media.attachment(image.id);
                    attachment.fetch();
                    selection.add( attachment ? [ attachment ] : [] );
                });
            }
        } catch(e) {
            console.info("No images selected");
        }

    });

    media_uploader.open();
}