var custom_upload_frame_obj;

( function( $ ) {

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

		$(document).on('click', 'input.wh-image-picker', function( event ){

			var $this = $(this);
			event.preventDefault();

			var artblogImageObject = wp.media.controller.Library.extend({
				defaults : _.defaults({
					id: 'custom-state-insert',
					title: $this.data( 'uploader_title' ),
					allowLocalEdits: false,
					displaySettings: true,
					displayUserSettings: false,
					multiple: false,
					library: wp.media.query( { type: 'image' } )
				}, wp.media.controller.Library.prototype.defaults )
			});

			custom_upload_frame_obj = wp.media.frames.custom_upload_frame_obj = wp.media({
				button: {
					text: $( this ).data( 'uploader_button_text' )
				},
				state : 'custom-state-insert',
				states : [
					new artblogImageObject()
				],
				multiple: false
			});

			custom_upload_frame_obj.on( 'select', function() {

				var state = custom_upload_frame_obj.state('custom-state-insert');
				var selection = state.get('selection');
				var display = state.display( selection.first() ).toJSON();
				var object_attachment = selection.first().toJSON();
				display = wp.media.string.props( display, object_attachment );

				var image_field = $this.siblings('.image-field-hidden');
				var image_url = display.src;

				image_field.val( image_url );
				image_field.trigger('change');

				var image_preview_wrap = $this.siblings('.field-image-preview');
				var image_html = '<img src="' + image_url + '" />';
				image_preview_wrap.html( image_html );

				var btn_remove_image = $this.siblings('.btn-image-remove');
				btn_remove_image.css('display','inline-block');
			});

			custom_upload_frame_obj.open();
		});

		// Callback for image remove.
		$(document).on('click', 'input.btn-image-remove', function( e ) {
			e.preventDefault();
			var $this = $(this);
			var image_field = $this.siblings('.image-field-hidden');
			image_field.val('');
			var image_preview_wrap = $this.siblings('.field-image-preview');
			image_preview_wrap.html('');
			$this.css('display','none');
			image_field.trigger('change');
		});
	});

} )( jQuery );
