<?php
function drk_add_mirror_links_meta_boxes()
{
    add_meta_box(
        "post_metadata_mirror_links_id",
        "Mirror links",
        "drk_meta_box_mirror_links",
        array("markets","venders",'tlg_channels','other_services','top_forums'),
        "normal",
        'default'
    );
}

add_action('add_meta_boxes', "drk_add_mirror_links_meta_boxes");

function drk_meta_box_mirror_links()
{
    global $post;
    wp_enqueue_script("jquery");
    $links = get_post_meta($post->ID, '_mirror_links', true);
    ?>
    <div class="DrkEntriesContainerLinks" data-count="<?php echo count($links); ?>" id="linksList">
        <?php
        $cnt = 0;
        if (is_array($links)) {
            foreach ($links as $link) {
                ++$cnt;
                ?>
                <div id="_mirror_links[<?php echo $cnt; ?>]" class="newItem">
                    <input name="_mirror_links[<?php echo $cnt; ?>]" type="text" value="<?php echo $link ?>"/>
                    <button data-element="_mirror_links[<?php echo $cnt; ?>]" class="btn btn-sm drk_delete"
                            onclick="drk_remove('_mirror_links[<?php echo $cnt; ?>]')">Remove
                    </button>
                </div>
                <?php
            }
        }
        ?>
    </div>
    <input type="button" value="Add new Link" class="button" id="addNewLink"/>
    <script>
        function drk_remove(elId) {
            document.getElementById(elId).remove();
        }

        jQuery(document).ready(
            function ($) {
                var ttlItems = parseInt(jQuery('#linksList').attr('data-count'));
                jQuery('#addNewLink').on(
                    'click.darkey',
                    function (e) {
                        e.preventDefault();
                        ttlItems++;
                        var $newItem = '<div id="_mirror_links[' + ttlItems + ']" class="newItem">' +
                            '<input name="_mirror_links[' + ttlItems + ']" type="text" />' +
                            '<button data-element="_mirror_links[' + ttlItems + ']" class="btn btn-sm drk_delete" ' +
                            'onclick=document.getElementById("_mirror_links[' + ttlItems + ']").remove();>Remove</button>' +
                            '<br/><br/></div>';

                        jQuery('#linksList').append($newItem);
                    }
                );
            }
        );
    </script>
    <?php
}

function drk_save_mirror_links_meta_boxes()
{
    global $post;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    update_post_meta($post->ID, "_mirror_links", $_POST["_mirror_links"]);

}

add_action("save_post", "drk_save_mirror_links_meta_boxes");