jQuery(document).ready(function($) {
    var frame;
    $("#upload-logo-btn").on("click", function(e) {
        e.preventDefault();
        if (frame) { frame.open(); return; }
        frame = wp.media({
            title: "Choose a logo",
            button: { text: "Use this image" },
            multiple: false,
            library: { type: "image" }
        });
        frame.on("select", function() {
            var attachment = frame.state().get("selection").first().toJSON();
            $("#company_logo_id").val(attachment.id);
            $("#logo-preview").html('<img src="' + attachment.url + '" style="max-width: 200px; max-height: 100px;">');
            if ($("#remove-logo-btn").length === 0) {
                $("#upload-logo-btn").after(' <button type="button" class="button" id="remove-logo-btn">Remove</button>');
            }
        });
        frame.open();
    });
    $(document).on("click", "#remove-logo-btn", function(e) {
        e.preventDefault();
        $("#company_logo_id").val("");
        $("#logo-preview").html("");
        $(this).remove();
    });
});