<style>
    #image_media {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.8);
        z-index: 9500;
    }

    #bricklayer_box {
        position: relative;
        padding: 0;
        margin: 0;
        margin: 70px 20px 20px 20px;
    }

    .image_media_grid {
        display: flex;
        height: auto;
        border: 5px solid transparent;
    }

    .image_media_grid:HOVER {
        border: 5px solid rgba(255,255,255,0.5);
    }

    .image_media_grid img {
        width: 100%;
        height: auto;
        display: block;
    }
</style>

<?php
require Plugin::get('PATH','imgedit').'header.php';
?>

<div id="image_media">
    <div id="bricklayer_box" class="bricklayer"></div>
</div>
<script>
    var bricklayer = new Bricklayer(document.querySelector('.bricklayer'));

    <?php
    echo '
        $.ajax({
            type: "GET",
            url: "'.Plugin::getFile("imgedit", "ajax_media").'",
            success : function(data) {
                make_media(data);
            }
        });';
    ?>
    make_media = function(data){
        var data = $.parseJSON(data);

        $.each(data.img, function(i, img) {
            i = document.createElement('img');
            var img_url = '<?php echo PA::getImageURL();?>upload/small/'+img.year+'/'+img.week+'/'+img.name+'.'+img.type
            $(i).attr('src',img_url);
            d = document.createElement('div');
            $(d).addClass('image_media_grid').data('img_url',img_url).html(i);
            bricklayer.append(d);
        });
    }


function insertAtCursor(iframename, text, replaceContents) {
      if(replaceContents==null){replaceContents=false;}
      if(!replaceContents){//collapse selection:
         var sel=document.getElementById(iframename).contentWindow.getSelection()
         sel.collapseToStart()
      }
     console.log('insert_img'); document.getElementById(iframename).contentWindow.document.execCommand('insertHTML', false, text);
    
};
    
    $('body').off( "click", ".image_media_grid").on('click','.image_media_grid',function(){
        if($('body').data('plugin_imgedit_source') == 'html_editor'){
            $("#meta_box").fadeOut();
            console.log('img_url_in_body');
            
            insertAtCursor("cleditor_iframe",'<div class="cleditor_img_box"><img src="' + $(this).data('img_url') + '" class="cleditor_img" /><div class="cleditor_img_box_edit" onClick="parent.show_imgedit_options(this)">&nbsp;</div></div>', 0); //change 0 to 1 if you want the user's selection to be replaced by the img

            

        }
    });
    
    var iframe_cont = $('#cleditor_iframe').contents();
iframe_cont.find(".cleditor_img_box_edit").click(function(){
   alert("test");
});

    
</script>
