/*global cambayImageUploadText */
( function( $ ){
	var file_frame,
		$document = $( document );

	$document.on( 'click', '.cambay-widget-img-uploader', function( event ){
		var _this = $(this);
		event.preventDefault();

		// Create the media frame.
		file_frame = wp.media.frames.file_frame = wp.media({
			title: cambayImageUploadText.uploader_title,
			button: {
				text: cambayImageUploadText.uploader_button_text,
			},
			multiple: false  // Set to true to allow multiple files to be selected
		});

		// When an image is selected, run a callback.
		file_frame.on( 'select', function() {
			// We set multiple to false so only get one image from the uploader
			var attachment  = file_frame.state().get('selection').first().toJSON(),
				imgUrl      = attachment.url,
				imgId       = attachment.id,
				featuredImg = document.createElement("img");
			
			featuredImg.src       = imgUrl;
			featuredImg.className = 'custom-widget-thumbnail';
			_this.html( featuredImg );
			_this.addClass( 'has-image' );
			_this.nextAll( '.cambay-widget-img-id' ).val( imgId ).trigger('change');
			_this.nextAll( '.cambay-widget-img-instruct, .cambay-widget-img-remover' ).removeClass( 'cambay-hidden' );
		});

		// Finally, open the modal
		file_frame.open();
	});

	$document.on( 'click', '.cambay-widget-img-remover', function( event ){
		console.log('hello');
		event.preventDefault();
		$( this ).prevAll('.cambay-widget-img-uploader').html(cambayImageUploadText.set_featured_img).removeClass( 'has-image' );
		$( this ).prev( '.cambay-widget-img-instruct' ).addClass( 'cambay-hidden' );
		$( this ).next( '.cambay-widget-img-id' ).val( '' ).trigger('change');
		$( this ).addClass( 'cambay-hidden' );
	});
} ) ( jQuery );
