jQuery(document).ready(function($) {
	
	var mediaUploader = [];
	jQuery('input[id^="featured_image"]').each(function(index, element) {
		var i = index + 1;
	
		$('.featured_image' + i).click(function(e) {
		  e.preventDefault();
		  
		  // If the uploader object has already been created, reopen the dialog
			if (mediaUploader[i]) {
			mediaUploader[i].open();
			return;
		  }
		  
		  // Extend the wp.media object
		  mediaUploader[i] = wp.media.frames.file_frame = wp.media({
			title: 'Choose Image',
			button: {
			text: 'Choose Image'
		  }, multiple: true });
	  
		  // When a file is selected, grab the URL and set it as the text field's value
		  mediaUploader[i].on('select', function() {
			attachment = mediaUploader[i].state().get('selection').first().toJSON();
			$('#featured_image' + i).val(attachment.url);
			$('#featured_image_id' + i).val(attachment.id);
			$('.featured_img' + i).attr("src",attachment.url).show();
			$('.featured_image' + i).hide();
			$('.remove_featured_image' + i).show();
		  });
		  
		  // Open the uploader dialog
		  mediaUploader[i].open();
		});
		
		// Remove file
		$('.remove_featured_image' + i).click( function() {
			$('#featured_image' + i).val('');
			$('.featured_img' + i).attr("src","").hide();
			$('.featured_image' + i).show();
			$(this).hide();
		});

    });
	
}); 