<div id="{$operation}-template-dialog" class="lms-ui-dialog" title="{if $operation == "edit"}{trans("Edit message template")}{else}{trans("Add message template")}{/if}">
	<style>

		ol.dialog-box {
			list-style: none;
			padding-left: 0;
			width: 90%;
		}
		ol.dialog-box li {
			padding-bottom: 5px;
		}
		ol.dialog-box textarea {
			width: 98%;
			resize: vertical;
		}
		ol.dialog-box select {
			padding: 2px;
		}

		ol.dialog-box .form-option {
			display: flex;
			flex-direction: column;
			margin-top: 0.3em;
			margin-bottom: 0.3em;
		}

		ol.dialog-box .form-option > label {
			font-weight: bold;
			margin-bottom: 0.3em;
		}

		ol.dialog-box .form-option > label + * {
			width: fit-content;
		}

		ol.dialog-box .existing-template-attachments ul {
			list-style-type: none;
			margin-block-start: 0;
			margin-block-end: 0;
			padding-inline-start: 0;
			margin-top: 0.3em;
		}

	</style>

	<form action="?m={$layout.module}" method="POST" id="{$operation}-template-form" enctype="multipart/form-data">
		{if $operation == 'edit'}
			<input type="hidden" id="{$operation}-template-id" name="template[id]">
		{/if}
	</form>

	<ol class="dialog-box">
		<li class="form-option">
			<label for="{$operation}-template-type">
				{trans("Type")}
			</label>
			<select id="{$operation}-template-type" name="template[type]" class="lms-ui-dialog-input"
				form="{$operation}-template-form">
				{foreach $_MESSAGETEMPLATES as $template_type => $template}
					<option value="{$template_type}">{$template.label|escape}</option>
				{/foreach}
			</select>
		</li>
		<li class="form-option">
			<label for="{$operation}-template-name">
				{trans("Name")}
			</label>
			<input type="text" id="{$operation}-template-name" name="template[name]" size="30" maxlength="45"
				form="{$operation}-template-form"
				class="text ui-widget-content ui-corner lms-ui-dialog-input">
		</li>
		<li class="form-option">
			<label for="{$operation}-template-subject">
				{trans("Subject")}
			</label>
			<input type="text" id="{$operation}-template-subject" name="template[subject]" size="30" maxlength="255" min="0"
				form="{$operation}-template-form"
				class="text ui-widget-content ui-corner lms-ui-dialog-input">
		</Li>
		<li class="{$operation}-helpdesk-properties">
			<table>
				<tr>
					<td width="99%">
						<div class="form-option">
							<label for="{$operation}-template-helpdesk-queues">
								{trans("Queues")}
							</label>
							<select name="template[helpdesk-queues][]" class="lms-ui-multiselect lms-ui-dialog-input lms-ui-multiselect-{$operation}"
								id="{$operation}-template-helpdesk-queues"
								form="{$operation}-template-form"
								size="25" multiple>
								{foreach $queues as $queue}
									<option value="{$queue.id}">{$queue.name}</option>
								{/foreach}
							</select>
						</div>
					</td>
					<td width="1%" class="nobr">
						<div class="form-option">
							<label>
								{trans("<!message-type>Message types")}
							</label>
							<span>
								<label class="nobr">
									<input type="checkbox" name="template[helpdesk-message-types][]" value="{$smarty.const.RTMESSAGE_REGULAR}"
										form="{$operation}-template-form">
									{trans("<!message-type>message")}
								</label>
								<label class="nobr">
									<input type="checkbox" name="template[helpdesk-message-types][]" value="{$smarty.const.RTMESSAGE_NOTE}"
										form="{$operation}-template-form">
									{trans("<!message-type>note")}
								</label>
							</span>
						</div>
					</td>
				</tr>
			</table>
		</li>
		<li class="form-option" id="{$operation}-content-type">
			<label for="{$operation}-template-content-type">
				{trans("Content type")}
			</label>
			<select name="template[content-type]" id="{$operation}-template-content-type"
					form="{$operation}-template-form">
				<option value="">{trans("— based on 'visual editor' option —")}&nbsp;&nbsp;&nbsp;</option>
				<option value="html">{trans("HTML")}</option>
				<option value="text">{trans("plain text")}</option>
			</select>
		</li>
		<li class="form-option" id="{$operation}-html-message">
			<label for="{$operation}-template-html-body">
				{trans("Message")}
			</label>
			<textarea id="{$operation}-template-html-body" cols="80" rows="20" name="template[html-body]"
				form="{$operation}-template-form"
				class="lms-ui-wysiwyg-editor text ui-corner lms-ui-dialog-input"></textarea>
		</li>
		<li class="form-option" id="{$operation}-text-message">
			<label for="{$operation}-template-text-body">
				{trans("Message")}
			</label>
			<textarea id="{$operation}-template-text-body" cols="80" rows="20" name="template[text-body]"
				form="{$operation}-template-form"
				class="text ui-corner lms-ui-dialog-input"></textarea>
		</li>
		<li class="form-option" id="{$operation}-attachments">
			<label>
				{trans("Attachments")}
			</label>
			{fileupload id="{$operation}-template-attachments" fileupload=$fileupload form="{$operation}-template-form"}
		</li>
		<li class="form-option existing-template-attachments" id="{$operation}-existing-attachments" style="display: none;">
			<label>
				{trans("Existing attachments")}
			</label>
			<div id="{$operation}-existing-template-attachments" class="existing-template-attachment-list"></div>
		</li>
	</ol>

	<input type="submit" style="position:absolute; top:-1000px" form="{$operation}-template-form">
</div>

<script>

	var {$operation}_template_dialog;
	var allowedAttachmentsByTemplateTypes = [
		{$smarty.const.TMPL_MAIL},
		{$smarty.const.TMPL_USERPANEL},
		{$smarty.const.TMPL_USERPANEL_URGENT}
	];

	function open_{$operation}_dialog(template_id) {
		var editor = tinymce.get('{$operation}-template-html-body');
		var templateType;

		if (template_id) {
			var row = $('[data-template-id=' + template_id + ']');
			var contentTypeMap = {
				"text/html": 'html',
				"text/plain": 'text'
			}

			templateType = $(row).find("[data-template-type]").attr('data-template-type');

			$("#{$operation}-template-id").val(template_id);
			$("#{$operation}-template-type").val(templateType);
			$("#{$operation}-template-name").val($(row).find("[data-template-name]").attr('data-template-name'));
			$("#{$operation}-template-subject").val($(row).find("[data-template-subject]").attr('data-template-subject'));
			$.each($(row).find("[data-template-helpdesk-message-types]").attr('data-template-helpdesk-message-types').split(','),
				function(index, value) {
					$('[name="template[helpdesk-message-types][]"][value="' + value + '"]').prop('checked', true);
				});
			$('.lms-ui-multiselect-{$operation}').data('multiselect-object').updateSelection(
				$(row).find("[data-template-helpdesk-queues]").attr('data-template-helpdesk-queues').split(',')
			);
			var contentType = $(row).find('[data-template-content-type]').attr('data-template-content-type');
			$("#{$operation}-template-content-type").val(contentTypeMap.hasOwnProperty(contentType) && contentType.length ? contentTypeMap[contentType] : '');
			var body = $(row).find(".data-template-message");
			$("#{$operation}-template-html-body").html(body.html());
			if (editor) {
				editor.setContent(body.html());
			}
			$("#{$operation}-template-text-body").text(body.text());

			var templateAttachments = row.find('[data-template-attachments]').attr('data-template-attachments');
			if (templateAttachments.length) {
				templateAttachments = JSON.parse(Base64.decode(templateAttachments));
			} else {
				templateAttachments = [];
			}

			var html = '';

			$.each(templateAttachments, function(id, attachment) {
				html += '<li>' +
					'<a class="lms-ui-button delete-button">' +
					'<input type="hidden" name="template[deleted-existing-attachments][' + attachment.id + ']"' +
					' value="' + attachment.id + '"' +
					' form="{$operation}-template-form" disabled>' +
					'<i class="lms-ui-icon-delete"></i></a>';

				html += '<span class="documentview">' +
					'<div class="documentviewdialog" id="documentviewdialog-' + attachment.id + '"' +
					' title="' + attachment.filename + '"' +
					' style="display: none;"' +
					' data-url="?m=messagetemplatelist&action=attachment-view&id=' + attachment.id + '"></div>';

				html += '<a href="?m=messagetemplatelist&action=attachment-view&id=' + attachment.id + '"' +
					' data-title="' + attachment.filename + '"' +
					' data-name="' + attachment.filename + '"' +
					' data-type="' + attachment.contenttype + '"';

				if (!contentType.length) {
					html += ' class="lms-ui-button" rel="external"';
				} else {
					html += ' id="documentview-' + attachment.id + '"' +
						' data-dialog-id="documentviewdialog-' + attachment.id + '"' +
						' class="lms-ui-button"';
				}

				var size = get_size_unit(attachment.size);

				html +=  '>' + attachment.filename + ' (' + size.size + ' ' + size.unit + ')' +
					' <i class="lms-ui-icon-view preview"></i>';

				html += '</a></span></li>';
			})

			if (html.length) {
				$('#{$operation}-existing-template-attachments').html(html.length ? '<ul>' + html + '</ul>' : '');
				$('#{$operation}-existing-attachments').show();
				initDocumentViewers('#{$operation}-existing-template-attachments .documentview');
			} else {
				$('#{$operation}-existing-template-attachments').empty();
				$('#{$operation}-existing-attachments').hide();
			}
		} else if (parseInt($('#template-type').val())) {
			templateType = $('#template-type').val();
			$("#{$operation}-template-type").val(templateType);
		}

		{$operation}_template_dialog.open();
		{$operation}_template_dialog.enableButtons();

		$('#{$operation}-template-type').change();

		$('#{$operation}-html-message').toggle(templateType != {$smarty.const.TMPL_SMS});
		$('#{$operation}-text-message').toggle(templateType == {$smarty.const.TMPL_SMS});

		$('#{$operation}-template-html-body').trigger(
			'lms:visual_editor_change_required',
			{
				ifShow: contentType == 'text/html' || contentType == ''
			}
		);
	}

	$( function() {
		$('#{$operation}-template-type').change(function() {
			var type = parseInt($(this).val());
			if (type == {$smarty.const.TMPL_SMS}) {
				$('#{$operation}-content-type').hide();
				$('#{$operation}-html-message').hide();
				$('#{$operation}-text-message').show();
				$('.{$operation}-helpdesk-properties').hide();
				$('#{$operation}-attachments').hide();
				$('#{$operation}-existing-attachments').hide();
			} else {
				$('#{$operation}-content-type').show();
				$('#{$operation}-html-message').show();
				$('#{$operation}-text-message').hide();
				$('.{$operation}-helpdesk-properties').toggle(type == {$smarty.const.TMPL_HELPDESK});
				$('#{$operation}-attachments').toggle(allowedAttachmentsByTemplateTypes.indexOf(type) != -1);
				$('#{$operation}-existing-attachments').toggle(
					allowedAttachmentsByTemplateTypes.indexOf(type) != -1
						&& $('#{$operation}-existing-template-attachments').text().length > 0
				);
			}
		}).change();

		{$operation}_template_dialog = new LmsUiDialog('{$operation}-template-dialog');
		{$operation}_template_dialog.setDialogWidth('40%');
		{$operation}_template_dialog.handler.dialog('option', 'resizable', true);
		{$operation}_template_dialog.setButtons([
			{
				text: "{if $operation == "edit"}{trans("Save")}{else}{trans("Add")}{/if}",
				icon: 'lms-ui-icon-save',
				click: function() {
					$(this).find("form").submit();
				}
			},
			{
				text: "{trans("Cancel")}",
				icon: 'lms-ui-icon-cancel',
				click: function() {
					$( this ).dialog( "close" );
				}
			}
		]);

		{$operation}_template_dialog.handler.find( "form" ).on( "submit", function( event ) {

			$({$operation}_template_dialog.handler).find("*")
				.removeClass("ui-state-error")
				.removeAttr("title");

			var editor = tinymce.get('{$operation}-template-html-body');
			if (editor) {
				$('#{$operation}-template-html-body').html(editor.getContent());
			}

			$.ajax({
				method: "POST",
				url: "?m=messagetemplatelist&action={$operation}",
				data: $(this).serialize(),
				beforeSend: function() {
					{$operation}_template_dialog.disableButtons();
				}
			})
				.done(function(data) {
					var response = JSON.parse(data);

					if (response.hasOwnProperty('error')) {
						$.each(response.error, function (index, value) {
							$('#' + index).addClass("lms-ui-error").prop('title', value);
							if (index == '{$operation}-template-html-body') {
								$('#' + index).siblings('.tox-tinymce').addClass('lms-ui-error');
							}
						});
					} else {
						{$operation}_template_dialog.close();
						window.location.replace('?m=messagetemplatelist');
						return;
					}

					{$operation}_template_dialog.enableButtons();
				});

			event.preventDefault();
		});

		$({$operation}_template_dialog).on('lms:dialog:form_reset_required', function() {
			$.ajax({
				method: "POST",
				url: "?m=messagetemplatelist&action=cancel",
				data: {$operation}_template_dialog.handler.find('form').serialize(),
				beforeSend: function() {
					{$operation}_template_dialog.disableButtons();
				}
			});
			$(this.dialog_body_id).find('.fileupload-files').empty();
			$(this.dialog_body_id).find('.existing-template-attachment-list').empty();
		});

		$('#{$operation}-existing-template-attachments').on('click', '.lms-ui-button.delete-button', function() {
			var attachmentDeleteButton = $(this);
			attachmentDeleteButton.find('[type="hidden"]').prop('disabled', function() {
				return !$(this).prop('disabled');
			}).end().siblings('.documentview').find('.lms-ui-button').toggleClass('blend')
				.end().end().find('i').toggleClass(['lms-ui-icon-delete', 'lms-ui-icon-restore']);
		});
	});

</script>
