(function () {
	'use strict';

	function editorId() {
		return 'subin_auto_reply_body_editor';
	}

	function insertContent(value) {
		var id = editorId();
		if (window.tinymce && window.tinymce.get(id) && !window.tinymce.get(id).isHidden()) {
			window.tinymce.get(id).execCommand('mceInsertContent', false, value);
			window.tinymce.get(id).focus();
			return;
		}

		if (window.QTags && typeof window.QTags.insertContent === 'function') {
			window.QTags.insertContent(value);
			return;
		}

		var textarea = document.getElementById(id);
		if (!textarea) {
			return;
		}

		var start = textarea.selectionStart || 0;
		var end = textarea.selectionEnd || start;
		textarea.value = textarea.value.slice(0, start) + value + textarea.value.slice(end);
		textarea.selectionStart = start + value.length;
		textarea.selectionEnd = textarea.selectionStart;
		textarea.focus();
	}

	document.addEventListener('click', function (event) {
		var button = event.target && event.target.closest ? event.target.closest('[data-subin-copy]') : null;

		if (!button) {
			return;
		}

		var value = button.getAttribute('data-subin-copy') || '';
		if (!value) {
			return;
		}

		event.preventDefault();
		insertContent(value);
		button.textContent = 'Inserted';
		window.setTimeout(function () {
			button.textContent = 'Insert';
		}, 1200);
	});
}());
