/**
 * Included when ftm_block_id fields are rendered for editing by publishers.
 */
 ( function( $ ) {

	var block_ids = [];

	function initialize_field( $field ) {
		/**
		 * $field is a jQuery object wrapping field elements in the editor.
		 */

		console.log( 'ftm_block_id field initialized' );

		if(block_ids.includes(jQuery($field).find("input").val())){
			jQuery($field).find("input").val("Paste new block id here!");
			alert('Please notice every time you duplicate a block you will need to generate a new block id using the "Generate new block id" button');
		}else{
			block_ids.push(jQuery($field).find("input").val());
		}
		
	}

	if( typeof acf.add_action !== 'undefined' ) {
		/**
		 * Run initialize_field when existing fields of this type load,
		 * or when new fields are appended via repeaters or similar.
		 */
		//acf.add_action( 'ready_field/type=ftm_block_id', initialize_field );
		acf.add_action( 'append_field/type=ftm_block_id', initialize_field );
	}

} )( jQuery );

function generate_block_id(el, id) {

	fetch(ftm_block_id.ajax_url, {
	method: "POST"
	})
	.then(function(response) {
		return response.text();
	})
	.then(function(data) {
		window.prompt("Please copy the new block id code below and paste it in the FTM Block ID input field", data);

		var inputElement = el.previousElementSibling;
		while (inputElement && inputElement.tagName !== "INPUT") {
			inputElement = inputElement.previousElementSibling;
		}
		inputElement.select();
		inputElement.focus();

	})
	.catch(function(error) {
		console.error("Request failed: " + error);
	});
	
}