var mediaUploader;
var formField;

jQuery( document ).ready( function( $ ) {


    // Upload button click
    $('.scc-media-upload-button').click( function ( event ) {
        event.preventDefault();

        formField = $(this).parents('.scc-form-field');

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

        mediaUploader = wp.media.frames.file_frame = wp.media( {
            title: 'Choose Image',
            button: {
                text: 'Choose Image'
            }, multiple: false
        } );

        mediaUploader.on( "select", onMediaImageSelect );

        mediaUploader.open();
    } );

    // Remove button click
    $('.scc-media-uploader-remove').click( function ( e ) {
        var formField = $(this).parents('.scc-form-field');

        var buttons = formField.find('.scc-media-uploader-buttons');
        var spinner = buttons.find('span.spinner');
        spinner.addClass('is-active');

        var name = buttons.find('.scc-media-upload-field').attr('name');

        setUploadedImage( name, '', function ( response ) {
            var image = formField.find('.scc-media-uploader-image');
            image.hide();
            image.find('img').remove();
            buttons.show();
            spinner.removeClass('is-active');
        } );
    } );

} );

/**
 * Handle upload settings functionalty
 */
function setUploadedImage( name, url, callback ) {
    var data = {
        action: "scc_admin_settings_ajax",
        security: SCC_Settings.security,
        method: "save_uploaded_image",
        data: {
            name: name,
            value: url,
        }
    };

    jQuery.post( ajaxurl, data, callback );
}

/**
 * On media image select
 */
function onMediaImageSelect() {
    var attachment = mediaUploader.state().get('selection').first().toJSON();
    var field = formField.find('.scc-media-upload-field');
    var spinner = formField.find('span.spinner');
    field.val( attachment.url );
    spinner.addClass('is-active');

    setUploadedImage( field.attr('name'), attachment.url, function ( response ) {
        spinner.removeClass('is-active');
        var html = '<img src="' + response.data.url + '" />';
        var image = formField.find('div.scc-media-uploader-image');
        image.append( html );
        image.show();
        field.parent().hide();
    } );
}
