jQuery(function($) {
	wpt_cf7_divi.addButtons();

	// row
	jQuery('span#tag-generator-list button[data-shortcode$="wpt_row"').on("click", function(e){
		e.preventDefault();
		wpt_cf7_divi.insertShortcode("wpcf7_row");
	});

	// one
	jQuery('span#tag-generator-list button[data-shortcode$="wpt_one"').on("click", function(e){
		e.preventDefault();
		wpt_cf7_divi.insertShortcode("wpcf7_one");
	});

	// one_half
	jQuery('span#tag-generator-list button[data-shortcode$="wpt_one_half"').on("click", function(e){
		e.preventDefault();
		wpt_cf7_divi.insertShortcode("wpcf7_one_half");
	});

	// one_third
	jQuery('span#tag-generator-list button[data-shortcode$="wpt_one_third"').on("click", function(e){
		e.preventDefault();
		wpt_cf7_divi.insertShortcode("wpcf7_one_third");
	});

	// one_fourth
	jQuery('span#tag-generator-list button[data-shortcode$="wpt_one_fourth"').on("click", function(e){
		e.preventDefault();
		wpt_cf7_divi.insertShortcode("wpcf7_one_fourth");
	});


	// two_third
	jQuery('span#tag-generator-list button[data-shortcode$="wpt_two_third"').on("click", function(e){
		e.preventDefault();
		wpt_cf7_divi.insertShortcode("wpcf7_two_third");
	});

	// three_fourth
	jQuery('span#tag-generator-list button[data-shortcode$="wpt_three_fourth"').on("click", function(e){
		e.preventDefault();
		wpt_cf7_divi.insertShortcode("wpcf7_three_fourth");
	});

});

var wpt_cf7_divi = {
	getButtonHtml: function(name, shortcodeName){
		let html = `<button type="button" data-shortcode="${shortcodeName}" class="wpt-cf7-tag" title="Form-tag Generator: ${name}">${name}</button>`
		return html
	},
	addButtons: function(){
		const self = this
		const btnContainer = jQuery('#tag-generator-list')
		
		btnContainer.prepend(self.getButtonHtml('3/4-col', 'wpt_three_fourth'))
		btnContainer.prepend(self.getButtonHtml('2/3-col', 'wpt_two_third'))
		btnContainer.prepend(self.getButtonHtml('1/4-col', 'wpt_one_fourth'))
		btnContainer.prepend(self.getButtonHtml('1/3-col', 'wpt_one_third'))
		btnContainer.prepend(self.getButtonHtml('1/2-col', 'wpt_one_half'))
		btnContainer.prepend(self.getButtonHtml('1-col', 'wpt_one'))
		btnContainer.prepend(self.getButtonHtml('row', 'wpt_row'))
	},
	insertShortcode: function(name) {
		var selected = this.getSelection();
		var shortcode_start = "[" + name + "]";
		this.insertAt(selected.start, shortcode_start );
		var shortcode_end = "[/" + name + "]";
		this.insertAt((selected.finish + shortcode_end.length - 1), shortcode_end);
	},
	insertAt : function(index, text){
		var value = jQuery('#wpcf7-form').val();
		var updated_value = [value.slice(0, index), text, value.slice(index)].join('')
		jQuery('#wpcf7-form').val(updated_value);
	},
	getSelection: function(){
		var txtarea = document.getElementById("wpcf7-form");
    	var start = txtarea.selectionStart;
    	var finish = txtarea.selectionEnd;
    	return {start: start, finish: finish}
	}
}

