jQuery(document).ready(function($){
    var t4p_megamenu_media_frame;

    $(document).on('click', '.t4p-megamenu-upload-thumbnail', function(e) {
        e.preventDefault();

        var button = $(this);

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

        t4p_megamenu_media_frame = wp.media.frames.t4p_megamenu_media_frame = wp.media({

            className: 'media-frame t4p-megamenu-media-frame',
            frame: 'select',
            multiple: false,
            //title: tgm_nmp_media.title,
            library: {
                type: 'image'
            }
            /*button: {
                text:  tgm_nmp_media.button
            }*/
        });

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

            $(button).closest('.menu-item-settings').find('.edit-menu-item-megamenu-thumbnail').val(media_attachment.url);

            $(button).closest('.menu-item-settings').find('.t4p-megamenu-thumbnail-image').attr('src', media_attachment.url).show();

            $(button).closest('.menu-item-settings').find('.remove-t4p-megamenu-thumbnail').show();
        });

        t4p_megamenu_media_frame.open();
    });
    
    $(document).on('click', '.remove-t4p-megamenu-thumbnail', function(e) {
        e.preventDefault();

        $(this).hide();

        $(this).closest('label').find('input').val('');
        $(this).closest('label').find('img').attr('src', '').hide()
    });
});