jQuery(function($) {

	var scosCurrentEditorId = null;
	var scosCurrentGroup = null;

	function addPlaceholderButtons() {

		$('.acf-field-wysiwyg').each(function() {
			var $field = $(this);
			var $wrap = $field.find('.wp-editor-wrap').first();
			var $buttons = $wrap.find('.wp-media-buttons').first();
			var $textarea = $wrap.find('textarea.wp-editor-area').first();

			if (!$wrap.length || !$buttons.length || !$textarea.length)
				return;

			if ($buttons.find('.scos-placeholder-button').length)
				return;

			var group = null;

			if ($field.is('[data-key="field_scos_email_template"]'))
				group = 'email';

			if (!group)
				return;

			var buttonHtml =
				'<button type="button" class="button scos-placeholder-button" data-editor="' + escAttr($textarea.attr('id')) + '" data-group="' + escAttr(group) + '">' +
					'<span class="dashicons dashicons-shortcode"></span> ' +
					escHtml(scosPlaceholdersData.button) +
				'</button>';

			$buttons.append(buttonHtml);
		});
	}

	function buildDialog(group) {

		var placeholders = (scosPlaceholdersData.groups && scosPlaceholdersData.groups[group]) ? scosPlaceholdersData.groups[group] : {};

		$('#scos-placeholder-dialog').remove();

		var html = '<div id="scos-placeholder-dialog" title="' + escHtml(scosPlaceholdersData.title) + '" style="display:none;">';
		html += '<div class="scos-placeholder-buttons">';

		for (var placeholder in placeholders) {
			html += '<button type="button" class="button scos-placeholder-btn" data-placeholder="' + escAttr(placeholder) + '">';
			html += escHtml(placeholders[placeholder]);
			html += '</button> ';
		}

		html += '</div></div>';

		$('body').append(html);
	}

	$(document).on('click', '.scos-placeholder-button', function(e) {
		e.preventDefault();

		scosCurrentEditorId = $(this).data('editor') || null;
		scosCurrentGroup = $(this).data('group') || null;

		if (!scosCurrentEditorId || !scosCurrentGroup)
			return;

		buildDialog(scosCurrentGroup);

		$('#scos-placeholder-dialog').dialog({
			modal: true,
			appendTo: $('#poststuff'),
			width: scosPlaceholdersData.width || 700,
			buttons: [{
				text: scosPlaceholdersData.cancel,
				class: 'button',
				click: function() {
					$(this).dialog('close');
				}
			}]
		});
	});

	$(document).on('click', '.scos-placeholder-btn', function(e) {
		e.preventDefault();

		var placeholder = $(this).data('placeholder');

		if (!placeholder)
			return;

		insertPlaceholder(scosCurrentEditorId, placeholder);
		$('#scos-placeholder-dialog').dialog('close');
	});

	function insertPlaceholder(editorId, placeholder) {

		if (
			editorId &&
			typeof tinymce !== 'undefined' &&
			tinymce.get(editorId) &&
			!tinymce.get(editorId).isHidden()
		) {
			tinymce.get(editorId).focus();
			tinymce.get(editorId).execCommand('mceInsertContent', false, placeholder);
			return;
		}

		var $textarea = $('#' + editorId);

		if (!$textarea.length)
			return;

		var field = $textarea.get(0);
		var value = $textarea.val();

		if (typeof field.selectionStart === 'number' && typeof field.selectionEnd === 'number') {
			var start = field.selectionStart;
			var end = field.selectionEnd;

			$textarea.val(value.substring(0, start) + placeholder + value.substring(end));
			field.selectionStart = field.selectionEnd = start + placeholder.length;
			$textarea.focus();
		} else {
			$textarea.val(value + placeholder).focus();
		}
	}

	function escHtml(string) {
		return String(string).replace(/[&<>"']/g, function(match) {
			return {
				'&': '&amp;',
				'<': '&lt;',
				'>': '&gt;',
				'"': '&quot;',
				"'": '&#039;'
			}[match];
		});
	}

	function escAttr(string) {
		return escHtml(string);
	}

	addPlaceholderButtons();

	if (typeof acf !== 'undefined') {
		acf.addAction('ready', addPlaceholderButtons);
		acf.addAction('append', addPlaceholderButtons);
		acf.addAction('show_field', addPlaceholderButtons);
	}

});