{extends file="layout.html"}
{block name=title}LMS: {$layout.pagetitle|striphtml}{/block}
{block name=module_content}
<!--// $Id$ //-->

<style>

	#customer-filter {
		border: 0;
	}

	.customer-contact-wrapper {
		margin-left: 1em;
		display: flex;
	}

	.customer-contact-wrapper label {
		margin-left: 0.3em;
	}

	.customers {
		padding-bottom: 1em !important;
	}

	.customer-list-summary {
		padding-top: 0.3em;
		font-weight: bold;
		cursor: pointer;
	}

	.customer-list {
		background-color: #EBE4D6;
		column-width: 20vh;
		column-gap: 2em;
		column-rule: 1px dotted black;
		margin-top: 0.7em;
		margin-right: 1em;
		padding: 0.4em;
		border: 1px dotted black;
	}

	.customer-list-item {
		display: flex;
		flex-direction: column;
		break-inside: avoid;
	}

	.customer-list-item label {
		white-space: normal;
	}

	.customer-list-item:hover {
		background-color: #CCFFCC;
	}

	.customer-list-summary-container {
		display: block;
	}

	.lms-ui-tooltip-toggle:not(.ui-tooltip) {
		margin-left: 0.5em;
	}

	.additional-email-address.hidden {
		display: none;
	}

	#template-attachment-list ul {
		list-style-type: none;
		margin-block-start: 0;
		margin-block-end: 0;
		padding-inline-start: 0;
	}

	#attachment > td:not(:last-child) {
		padding-top: 0.8em;
	}

	#file-list {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}

	#container-file-list {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		border-top: 1px dotted grey;
		margin-top: 0.5em;
		padding-top: 0.5em;
	}

	#container-file-list ul {
		margin-block-start: 0.5em;
		margin-block-end: 0.5em;
		padding-inline-start: 0;
		list-style-type: none;
	}

	#container-file-list ul li.deleted .documentview .lms-ui-button {
		text-decoration-line: line-through;
		text-decoration-thickness: 1px;
		text-decoration-color: rgba(0, 0, 0, 0.5);
	}

</style>

{$xajax}

<h1>{$layout.pagetitle}</h1>

<form name="message" id="message" method="post" action="?m=messageadd" enctype="multipart/form-data">

<input type="submit" class="hiddenbtn">

{if !empty($message.customers)}
	<input type="hidden" name="message[customermode]" value="1">
{/if}

<script>

	var viewContentTypes = {
		'image/jpeg': 'image',
		'image/png': 'image',
		'image/gif': 'image',
		'audio/mp3': 'audio',
		'audio/ogg': 'audio',
		'audio/oga': 'audio',
		'audio/wav': 'audio',
		'video/mp4': 'video',
		'video/ogg': 'video',
		'video/webm': 'video',
		'application/pdf': 'pdf',
	};

	function checkaddr(email)
	{
		{literal}
		var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
		{/literal}
		if (filter.test(email))
			return 1
		else
			return 0;
	}

	function messageTemplatesReceived(templates) {
		var options = '<OPTION value="0">' + $t("— none —") + '</OPTION>';
		$.each(templates, function(index, template) {
			options += '<option value="' + template.id + '">' + template.name + '</option>';
		});
		$('#msgtmplid').html(options).prop('disabled', false);
		updateAdvancedSelectsTest('#msgtmplid');
	}

	function countChars(elem)
	{
		$('#charscounttext').html(elem.value.length);
	}

	function messageTemplateReceived(data) {
		var type = $('[name="message[type]"]:checked').val();

		$('#' + data.subjectElem).val(data.subject);

		var editor = tinyMCE.get(0);
		if (editor) {
			editor.setContent(data.message);
		}

		var messageElem = $('textarea[name="message[' + data.messageElem + ']"]');
		messageElem.html(data.message);

		var templateAttachmentList = $('#template-attachment-list');
		if (data.attachments.length) {
			var html = '';
			$.each(data.attachments, function(id, attachment) {
				html += '<li>';

				html += '<a class="lms-ui-button">' +
					'<input type="hidden" name="message[template-attachments][' + attachment.id + ']"' +
					' value="' + attachment.id + '">' +
					'<i class="lms-ui-icon-delete"></i></a>';

				var contentType = '';
				if (viewContentTypes.hasOwnProperty(attachment.contenttype)) {
					contentType = viewContentTypes[attachment.contenttype];
				}

				html += '<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 + '"';
				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 documentview documentview-' + contentType + '"';
				}

				var size = get_size_unit(attachment.size);

				html +=  '>' + attachment.filename + ' (' + size.size + ' ' + size.unit + ')' +
					' <i class="lms-ui-icon-view' +
					(attachment.contenttype.match(/pdf/)
						? ' pdf'
						: (attachment.contenttype.match(/csv|excel|spreadsheet/)
							? ' xls'
							: ''
						)
					) + '"></i>' +
					'</a>';

				html += '</li>';
			});
			templateAttachmentList.html('<ul>' + html + '</ul>');
			initDocumentViewers(templateAttachmentList.find('.documentview'))
		} else {
			templateAttachmentList.empty();
		}
		$('#template-attachments').toggle(data.attachments.length > 0);

		if (type < {$smarty.const.MSG_SMS} || type > {$smarty.const.MSG_ANYSMS}) {
			data.messageElem.trigger(
				'lms:visual_editor_change_required',
				{
					ifShow: data.contentType == 'text/html' || data.contentType == ''
				}
			);
		}
	}

</script>
<table class="lmsbox">
	<colgroup>
		<col style="width: 1%;">
		<col style="width: 1%;">
		<col style="width: 98%;">
	</colgroup>
    <thead>
		<tr>
			<td>
				{icon name="filter"}
			</td>
			<td class="nobr">
				<strong>{trans("Type")}</strong>
			</td>
			<TD>
				{if $message.emailcount || empty($message.customers)}
					<label>
						<input type="radio" name="message[type]" id="typemail" value="{$smarty.const.MSG_MAIL}"
								{if $message.type < $smarty.const.MSG_SMS || $message.type > $smarty.const.MSG_ANYSMS} checked{/if}
								{tip trigger="type" text="Select message type"}>
						<strong>{trans("email")}</strong>
					</label>
				{/if}
				{if $message.phonecount || empty($message.customers)}
					<label>
						<input type="radio" name="message[type]" id="typesms" value="{$smarty.const.MSG_SMS}"
								{if $message.type == $smarty.const.MSG_SMS} checked{/if}
								{tip trigger="type" text="Select message type"}>
						<strong>{trans("sms")}</strong>
					</label>
				{/if}
				<label>
					<input type="radio" name="message[type]" id="typeanysms" value="{$smarty.const.MSG_ANYSMS}"
							{if $message.type == $smarty.const.MSG_ANYSMS} checked{/if}
							{tip trigger="type" text="Select message type"}>
					<strong>{trans("any sms")}</strong>
				</label>
				<label>
					<input type="radio" name="message[type]" id="typewww" value="{$smarty.const.MSG_WWW}"
						{if $message.type == $smarty.const.MSG_WWW} checked{/if}
						{tip trigger="type" text="Select message type"}>
					<strong>{trans("www")}</strong>
				</label>
				<label>
					<input type="radio" name="message[type]" id="typeuserpanel" value="{$smarty.const.MSG_USERPANEL}"
						{if $message.type == $smarty.const.MSG_USERPANEL} checked{/if}
						{tip trigger="type" text="Select message type"}>
					<strong>{trans("userpanel")}</strong>
				</label>
				<label>
					<input type="radio" name="message[type]" id="typeuserpanelurgent" value="{$smarty.const.MSG_USERPANEL_URGENT}"
						{if $message.type == $smarty.const.MSG_USERPANEL_URGENT} checked{/if}
						{tip trigger="type" text="Select message type"}>
					<strong>{trans("userpanel urgent")}</strong>
				</label>
			</TD>
		</tr>
		{if !empty($message.customers)}
			{if count($message.customers) == 1}
				{$customer = reset($message.customers)}
				<tr id="customer-filter">
					<td class="valign-top">
						{icon name="customer"}
					</td>
					<td class="valign-top bold nobr">
						<span id="customer-recipient"{if $message.type == $smarty.const.MSG_ANYSMS} style="display: none;"{/if}>{trans("Recipient:")}</span>
						<span id="customer-data"{if $message.type != $smarty.const.MSG_ANYSMS} style="display: none;"{/if}>{trans("Customer data:")}</span>
					</td>
					<td class="bold">
						{$customer.name} ({$customer.customerid|string_format:"%04d"})
						<br>
						{if empty($nodes)}
							<input type="hidden" name="message[nodeid]" value="">
						{else}
							{trans("Node:")}
							<select name="message[nodeid]">
								<option value="">{trans("— none —")}</option>
								{foreach $nodes as $node}
									<option value="{$node.id}"{if $node.id == $message.nodeid} selected{/if}>{$node.name}: {$node.location}</option>
								{/foreach}
							</select>
						{/if}
					</td>
				</tr>
			{/if}
		{else}
			<tr id="customer-filter"{if $message.type == $smarty.const.MSG_ANYSMS} style="display: none;"{/if}>
				<td>
					{icon name="customergroup"}
				</td>
				<td class="nobr">
					<strong>{trans("Recipients")}</strong>
				</td>
				<td>
					<table width="100%">
						<colgroup>
							<col style="width: 1%;">
							<col style="width: 1%;">
							<col style="width: 1%;">
							<col style="width: 1%;">
							<col style="width: 1%;">
							<col style="width: 1%;">
							<col style="width: 1%;">
							<col style="width: 93%;">
						</colgroup>
						<tr>
							<td class="nobr">{trans("Status")}</td>
							<td>
								<select name="message[state]" {tip trigger="state"}>
									<option value="0"{if !$message.state} selected{/if}>{trans("— all customers —")}</option>
									<optgroup label="Status">
										{foreach $_CSTATUSES as $statusidx => $status}
											<option value="{$statusidx}"{if $message.state == $statusidx} selected{/if}>{$status.plurallabel}</option>
										{/foreach}
									</optgroup>
									<optgroup label="{trans("Customers")}">
										<option value="50"{if $message.state == "50"} selected{/if}>{trans("deleted<!plural>")}</option>
									</optgroup>
									<optgroup label="{trans("Nodes")}">
										<option value="51"{if $message.state == "51"} selected{/if}>{trans("with disconnected nodes")}</option>
									</optgroup>
									<optgroup label="{trans("Finances")}">
										{if !ConfigHelper::checkPrivilege('hide_finances')}
											<option value="52"{if $message.state == "52"} selected{/if}>{trans("in debt")}</option>
											<option value="161"{if $message.state == "161"} selected{/if}>{trans("in debt (expired)")}</option>
											<option value="164"{if $message.state == "64"} selected{/if}>{trans("in debt (expired by more than 30 days)")}</option>
											<option value="165"{if $message.state == "65"} selected{/if}>{trans("in debt (expired by more than 60 days)")}</option>
											<option value="57"{if $message.state == "57"} selected{/if}>{trans("in debt above 100%")}</option>
											<option value="162"{if $message.state == "162"} selected{/if}>{trans("in debt above 100% (expired)")}</option>
											<option value="58"{if $message.state == "58"} selected{/if}>{trans("in debt above 200%")}</option>
											<option value="163"{if $message.state == "163"} selected{/if}>{trans("in debt above 200% (expired)")}</option>
											<option value="153"{if $message.state == "153"} selected{/if}>{trans("not in debt")}</option>
											<option value="160"{if $message.state == "160"} selected{/if}>{trans("not in debt (expired)")}</option>
										{/if}
									</optgroup>
									<optgroup label="{trans("Documents")}">
										<option value="159"{if $message.state == "159"} selected{/if}>{trans("unapproved documents")}</option>
										<option value="59"{if $filter.state == 59} selected{/if}>{trans("without contracts")}</option>
										<option value="76"{if $filter.state == 76} selected{/if}>{trans("without active contracts")}</option>
										<option value="60"{if $filter.state == 60} selected{/if}>{trans("with expired contracts")}</option>
										<option value="77"{if $filter.state == 77} selected{/if}>{trans("with expired, active contracts")}</option>
										<option value="61"{if $filter.state == 61} selected{/if}>{trans("with expiring contracts")}</option>
										<option value="78"{if $filter.state == 78} selected{/if}>{trans("with expiring, active contracts")}</option>
									</optgroup>
								</select>
							</td>
							<td class="nobr">{trans("Group")}</td>
							<td class="multiselect">
								<select name="message[customergroup][]" multiple class="lms-ui-multiselect"
									{tip trigger="customergroup" text="Select customers group"} data-default-value="{trans("— all groups —")}">
									{foreach $customergroups as $customergroup}
										<option value="{$customergroup.id}"{if isset($message.customergroup) && in_array($customergroup.id, $message.customergroup)} selected{/if}
											>{$customergroup.name|trunescape:30}</option>
									{/foreach}
								</select>
							</td>
							<td class="nobr">{trans("Network")}</td>
							<td>
								<select name="message[network][]" multiple class="lms-ui-multiselect"
									data-default-value="{trans("— all networks —")}"
									{tip trigger="network" text="Select IP network"}>
									{foreach $networks as $network}
										<option value="{$network.id}"{if $message.network == $network.id} selected{/if}
											>{$network.name|trunescape:30}</option>
									{/foreach}
								</select>
							</td>
							<td class="nobr">{trans("Tariff type")}</td>
							<td>
								<select name="message[tarifftype]" {tip trigger="network"}>
									<option value="0">{trans("— all —")}</option>
									{foreach $_SERVICETYPES as $key => $type}
										<option value="{$key}"{if $message.tarifftype == $key} selected{/if}>{$type}</option>
									{/foreach}
								</select>
							</td>
						</tr>
						<tr>
							<td class="nobr valign-top" rowspan="1">
								{trans("Division")}
							</td>
							<td class="valign-top" rowspan="1">
								<select name="message[division]">
									<option value="">- {trans("all")} -</option>
									{foreach $divisions as $division}
										<option value="{$division.id}"{if $message.division == $division.id} selected{/if}
											>{$division.label|escape}</option>
									{/foreach}
								</select>
							</td>
							<td class="nobr">{trans("Node Group<!short>")}</td>
							<td class="multiselect">
								<select size="1" name="message[nodegroup][]" multiple class="lms-ui-multiselect"
									{tip trigger="nodegroup"} data-default-value="{trans("— all groups —")}">
									{foreach $nodegroups as $nodegroup}
										<option value="{$nodegroup.id}"{if isset($message.nodegroup) && in_array($nodegroup.id, $message.nodegroup)} selected{/if}
											>{$nodegroup.name|trunescape:30}</option>
									{/foreach}
								</select>
							</td>
							<td class="nobr">{trans("Link type")}</td>
							<td colspan="3">
								<select size="1" name="message[linktype]" {tip trigger="linktype"}>
									<option value="">{trans("— all —")}</option>
									{foreach $_LINKTECHNOLOGIES as $linktype => $linktech}
										<option value="{$linktype}">{$_LINKTYPES[$linktype]}</option>
									{/foreach}
								</select>
							</td>
						</tr>
						<tr>
							<td class="nobr" colspan="1">
								<label>
									<input type="checkbox" name="message[consent]" value="1"
											{tip text="Check if customer consent to messages delivery via e-mail or sms is required" trigger="consent"}
											{if $message.consent} checked{/if}>
									{trans("consent required")}
								</label>
							</td>
							<td class="nobr" colspan="7">
								<label data-contact-type="typemail"
									{if !empty($message.type) && $message.type != $smarty.const.MSG_MAIL} class="lms-ui-disabled"{/if}>
									{trans("E-mail contact options")}
									<select name="message[email-options]"
										{if !empty($message.type) && $message.type != $smarty.const.MSG_MAIL} disabled{/if}>
										<option value="">{trans("— any —")}</option>
										{foreach $_CUSTOMERCONTACTTYPES.email.ui.flags as $flagval => $flag}
											{if $flagval != $smarty.const.CONTACT_DISABLED}
												<option value="{$flagval}"{if $message['email-options'] == $flagval} selected{/if}>{$flag.label}</option>
											{/if}
										{/foreach}
									</select>
								</label>
								<label data-contact-type="typesms"
									{if $message.type != $smarty.const.MSG_SMS} class="lms-ui-disabled"{/if}>
									{trans("Phone contact options")}
									<select name="message[phone-options]"
										{if $message.type != $smarty.const.MSG_SMS} disabled{/if}>
										<option value="">{trans("— any —")}</option>
										{foreach $_CUSTOMERCONTACTTYPES.phone.ui.flags as $flagval => $flag}
											{if $flagval != $smarty.const.CONTACT_DISABLED}
												<option value="{$flagval}"{if $message['phone-options'] == $flagval} selected{/if}>{$flag.label}</option>
											{/if}
										{/foreach}
									</select>
								</label>
							</td>
						</tr>
						<tr>
							<td class="nobr">
								<label for="netdev">
									{trans("Network device")}
								</label>
							</td>
							<td colspan="7" class="nobr">
								<select name="message[netdev]" id="netdev" {tip class="lms-ui-advanced-select-test" trigger="netdev" text="Select network device"}>
									<option value="">{trans("— none —")}</option>
									{foreach $netdevices as $netdev}
										<option value="{$netdev.id}"{if isset($message.netdev) && $netdev.id == $message.netdev} selected{/if}>{$netdev.name}</option>
									{/foreach}
								</select>
								<label>
									<input type="checkbox" name="message[wholesubtree]" value="1"{if isset($message.wholesubtree)} checked{/if}>
									{trans("whole subtree")}
								</label>
							</td>
						</tr>
					</table>
				</td>
			</tr>
		{/if}
	</thead>
	<tbody>
		{if $message.emailcount}
			<tr id="customermails"{if $message.type != $smarty.const.MSG_MAIL} style="display: none;"{/if}>
				<td class="valign-top">
					{icon name="mail"}
				</td>
				<td class="nobr valign-top">
					<strong>{trans("E-mail")}</strong>
				</td>
				<td class="customers">
					<div class="customer-list-summary-container">
						<span class="customer-list-summary"></span>
						{button icon="more" class="more-button" tip="show customer list"}
						{button icon="less" class="less-button" tip="hide customer list" visible=false}
					</div>
					<div class="customer-list" style="display: none;">
						{$selected_contacts = 0}
						{$total_customers = 0}
						{foreach $message.customers as $customerid => $customer}
							{if !empty($customer.emails)}
								<div class="customer-list-item">
									<a href="?m=customerinfo&id={$customerid}">(#{$customerid|string_format:"%04d"}) {$customer.name|truncate:50:"&hellip;"}</a>
									{foreach $customer.emails as $email}
										{if !empty($email.checked)}{$selected_contacts = $selected_contacts + 1}{/if}
										<div class="customer-contact-wrapper">
											<input type="hidden" name="message[customers][{$customerid}][emails][{$email.id}]" value="0">
											<input type="checkbox" name="message[customers][{$customerid}][emails][{$email.id}]"
												value="{$email.contact}" id="customer-contact-{$email.id}" class="customer-contact"
												{if !empty($email.checked)}checked{/if}>
											<label for="customer-contact-{$email.id}">
												{$email.contact|escape}{if $email.name} ({$email.name|escape}){/if}
											</label>
										</div>
									{/foreach}
								</div>
								{$total_customers = $total_customers + 1}
							{/if}
						{/foreach}
					</div>
					<script>

						var customers = $(document.currentScript).closest('.customers');
						customers.find('.customer-list-summary')
							.text($t('$a selected contacts of $b customers', {$selected_contacts}, {$total_customers}))
							.parent().toggle({if $total_customers > 5}true{else}false{/if});
						{if $total_customers <= 5}
							customers.find('.customer-list').show();
						{/if}

					</script>
				</td>
			</tr>
		{/if}
		{if $message.phonecount}
			<tr id="customerphones"{if $message.type != $smarty.const.MSG_SMS} style="display: none;"{/if}>
				<td class="valign-top">
					{icon name="sms"}
				</td>
				<td class="nobr valign-top">
					<strong>{trans("Phone:")}</strong>
				</td>
				<td class="customers">
					<div class="customer-list-summary-container">
						<span class="customer-list-summary"></span>
						{button icon="more" class="more-button" tip="show customer list"}
						{button icon="less" class="less-button" tip="hide customer list" visible=false}
					</div>
					<div class="customer-list" style="display: none;">
						{$selected_contacts = 0}
						{$total_customers = 0}
						{foreach $message.customers as $customerid => $customer}
							{if !empty($customer.phones)}
								<div class="customer-list-item">
									<a href="?m=customerinfo&id={$customerid}">(#{$customerid|string_format:"%04d"}) {$customer.name|truncate:50:"&hellip;"}</a>
									{foreach $customer.phones as $phone}
										{if !empty($phone.checked)}{$selected_contacts = $selected_contacts + 1}{/if}
										<div class="customer-contact-wrapper">
											<input type="hidden" name="message[customers][{$customerid}][phones][{$phone.id}]" value="0">
											<input type="checkbox" name="message[customers][{$customerid}][phones][{$phone.id}]"
												value="{$phone.contact}" id="customer-contact-{$phone.id}" class="customer-contact"
												{if !empty($phone.checked)}checked{/if}>
											<label for="customer-contact-{$phone.id}">
												{$phone.contact|escape}{if $phone.name} ({$phone.name|escape}){/if}
											</label>
										</div>
									{/foreach}
								</div>
								{$total_customers = $total_customers + 1}
							{/if}
						{/foreach}
					</div>
					<script>

						var customers = $(document.currentScript).closest('.customers');
						customers.find('.customer-list-summary')
								.text($t('$a selected contacts of $b customers', {$selected_contacts}, {$total_customers}))
								.parent().toggle({if $total_customers > 5}true{else}false{/if});
						{if $total_customers <= 5}
							customers.find('.customer-list').show();
						{/if}

					</script>
				</td>
			</tr>
		{/if}
		<tr id="startdate-row" class="scheduled-message"{if $message.type != $smarty.const.MSG_MAIL && $message.type != $smarty.const.MSG_SMS && !$message.type != $smarty.const.MSG_ANYSMS} style="display: none;"{/if}>
			<td>
				{icon name="calendar"}
			</td>
			<td class="nobr">
				<strong>
					<label for="startdate">
						{trans("Start date")}
					</label>
				</strong>
			</td>
			<td>
				<input type="text" name="message[startdate]" id="startdate"
					value="{if $message.startdate}{$message.startdate|date_format:"Y/m/d H:i"}{/if}"
					size="20" maxlength="20"
					{tip trigger="startdate" class="lms-ui-datetime"}>
			</td>
		</tr>
		<tr id="attemtps-row" class="scheduled-message"{if $message.type != $smarty.const.MSG_MAIL && $message.type != $smarty.const.MSG_SMS && !$message.type != $smarty.const.MSG_ANYSMS} style="display: none;"{/if}>
			<td>
				{icon name="reload" class="attempts-field"}
			</td>
			<td class="nobr">
				<strong>
					<label for="attempts" class="attempts-field">
						{trans("Attempts")}
					</label>
				</strong>
			</td>
			<td>
				<input type="number" name="message[attempts]" id="attempts"
					value="{if isset($message.attempts)}{$message.attempts}{else}{$default_send_attempts}{/if}"
					size="10" maxlength="5" min="1" max="10">
			</td>
		</tr>
		<tr id="mailsender"{if $message.type > $smarty.const.MSG_MAIL} style="display: none;"{/if}>
			<td>
				{icon name="mail"}
			</td>
			<td class="nobr">
				<strong>{trans("Sender E-mail")}</strong>
			</td>
			<td>
				<input type="email" name="message[sender]" size="40"
					value="{if $message.sender}{$message.sender}{/if}"
					{tip trigger="sender"}
					{if $division_count > 1}style="display: none;"{/if}>
				<label {tip trigger="copytosender" text="Check if you want do send message copy to sender"}>
					<input type="checkbox" name="message[copytosender]"
						{if ConfigHelper::checkConfig('messages.send_to_sender_checkbox', ConfigHelper::checkConfig('phpui.send_message_to_sender_checkbox'))} checked{/if}>
					{trans("send copy to sender")}
				</label>
			</td>
		</tr>
		<tr id="mailfrom"{if $message.type > $smarty.const.MSG_MAIL} style="display: none;"{/if}>
			<td>
				{icon name="user"}
			</td>
			<td>
				<strong>{trans("Sender")}</strong>
			</td>
			<td>
				<input type="text" name="message[from]" size="40"  value="{if $message.from}{$message.from}{else}{$sender_name}{/if}"
					{tip trigger="from" text="Enter sender name"}>
			</td>
		</tr>
		<tr class="additional-email-addresses"{if $message.type > $smarty.const.MSG_MAIL} style="display: none;"{/if}>
			<td></td>
			<td></td>
			<td>
				{if empty($message['cc-email']) && empty($message['bcc-email']) && empty($message['reply-email'])}
					{$icon = "next"}
					{$label = "More e-mail addresses"}
				{else}
					{$icon = "previous"}
					{$label = "Less e-mail addresses"}
				{/if}
				{button type="link" icon=$icon label=$label id="additional-email-addresses-button"}
			</td>
		</tr>
		<tr class="additional-email-address{if empty($message['cc-email']) && empty($message['bcc-email']) && empty($message['reply-email'])} hidden{/if}"{if $message.type > $smarty.const.MSG_MAIL} style="display: none;"{/if}>
			<td>
				{icon name="mail"}
			</td>
			<td class="nobr">
				<strong>{trans("Reply to")}</strong>
			</td>
			<td>
				<input type="email" name="message[reply-email]" size="40"  value="{if !empty($message['reply-email'])}{$message['reply-email']}{/if}">
			</td>
		</tr>
		<tr class="additional-email-address{if empty($message['cc-email']) && empty($message['bcc-email']) && empty($message['reply-email'])} hidden{/if}"{if $message.type > $smarty.const.MSG_MAIL} style="display: none;"{/if}>
			<td>
				{icon name="mail"}
			</td>
			<td class="nobr">
				<strong>{trans("Carbon copy")}</strong>
			</td>
			<td>
				<input type="email" multiple name="message[cc-email]" size="40"  value="{if !empty($message['cc-email'])}{$message['cc-email']}{/if}">
			</td>
		</tr>
		<tr class="additional-email-address{if empty($message['cc-email']) && empty($message['bcc-email']) && empty($message['reply-email'])} hidden{/if}"{if $message.type > $smarty.const.MSG_MAIL} style="display: none;"{/if}>
			<td>
				{icon name="mail"}
			</td>
			<td class="nobr">
				<strong>{trans("Blind carbon copy")}</strong>
			</td>
			<td>
				<input type="email" multiple name="message[bcc-email]" size="40"  value="{if !empty($message['bcc-email'])}{$message['bcc-email']}{/if}">
			</td>
		</tr>
		{if $users}
		<tr id="users"{if $message.type != $smarty.const.MSG_ANYSMS} style="display: none;"{/if}>
			<td>
				{icon name="user"}
			</td>
			<td>
				<strong>{trans("Users")}</strong>
			</td>
			<td>
				<select size="4" name="message[users][]" id="user-selection" multiple class="lms-ui-multiselect"
						data-default-value="{trans("— none —")}" data-shorten-to-default-value="false">
					{foreach $users as $user}
						<option value="{$user.id}"{if isset($message.users) && in_array($user.id, $message.users)} selected{/if}>{$user.name|trunescape:30}</option>
					{/foreach}
				</select>
				<strong>{trans("user group")}</strong>
				<select name="message[usergroup]" id="usergroup-selection">
					<option value="" data-users="[{implode(',', array_keys($users))}]">{trans("— all —")}</option>
					{foreach $usergroups as $usergroup}
						<option value="{$usergroup.id}" data-users="[{$usergroup.users}]"
							{if $message.usergroup == $usergroup.id} selected{/if}>{$usergroup.name}</option>
					{/foreach}
				</select>
			</td>
		</tr>
		{/if}
		<tr id="phonenumber"{if $message.type != $smarty.const.MSG_ANYSMS} style="display: none;"{/if}>
			<td>
				{icon name="sms"}
			</td>
			<td>
				<strong>{trans("Phone number")}</strong>
			</td>
			<td>
				<input type="tel" name="message[phonenumber]" size="60" value="{$message.phonenumber}"
					{tip trigger="phonenumber" text="Enter phone numbers separated by commas"}>
			</td>
		</tr>
		{capture assign="content_hint"}{strip}
			Supported substitutions/variables:<br>
			<strong>%customer</strong> - customer first name and last name or name,<br>
			<strong>%balance</strong>, <strong>%totalsaldo</strong>, <strong>%totalB</strong> - customer total balance,<br>
			<strong>%commented_balance</strong> - customer total balance as absolute value with text comment explaining customer billing status,<br>
			<strong>%b</strong> - customer expired liability balance amount to pay,<br>
			<strong>%totalb</strong> - customer total balance amount to pay,<br>
			<strong>%B</strong>, <strong>%saldo</strong> - customer expired liability balance,<br>
			<strong>%cid</strong> - customer identifier,<br>
			<strong>%pin</strong> - customer pin,<br>
			<strong>%bankaccount</strong> - bank account for payments,<br>
			<strong>%services</strong> - customer service summary,<br>
			<strong>%last_N_in_a_table</strong> - last N operation in customer financial history (N means number),<br>
			<strong>%date-y</strong> - current year<br>
			<strong>%date-m</strong> - current month,<br>
			<strong>%date-d</strong> - current day.<br>
			<br>
			Substitution/variables supported while customer node is selected:<br>
			<strong>%node_name</strong> - customer node name,<br>
			<strong>%node_login</strong> - customer node login (node name is used when login is empty),<br>
			<strong>%node_password</strong> - customer node password,<br>
			<strong>%node_ip</strong> - customer node ip address,<br>
			<strong>%node_ip_pub</strong> - customer node public ip address,<br>
			<strong>%node_mac</strong> - customer node mac addresses.<br>
		{/strip}{/capture}
		<tr>
			<td>
				{icon name="message"}
			</td>
			<td>
				<strong>{trans("Subject")}</strong>
			</td>
			<td>
				<input type="text" name="message[subject]" id="subject" size="60" value="{$message.subject}"
					{tip trigger="subject"}>
				{hint text=trans("Enter message subject.")|cat:"<br><br>"|cat:trans($content_hint)}
			</td>
		</tr>
		<tr>
			<td>
				{icon name="document"}
			</td>
			<td class="nobr">
				<strong>{trans("Message template")}</strong>
			</td>
			<td>
				<select name="message[tmplid]" id="msgtmplid" {tip class="lms-ui-advanced-select-test" trigger="msgtmplid" text="Select message template"}>
					<option value="0">{trans("— none —")}</option>
					{foreach $messagetemplates as $msgtmpl}
						<option value="{$msgtmpl.id}"{if $message.tmplid == $msgtmpl.id} selected{/if}>{$msgtmpl.name}</option>
					{/foreach}
				</select>
			</td>
		</tr>
		<tr id="mailbody"{if $message.type > $smarty.const.MSG_MAIL && $message.type < $smarty.const.MSG_WWW} style="display: none"{/if}>
			<td>
				{icon name="edit"}
			</td>
			<td class="nobr">
				<strong>{trans("Message body")}</strong>
			</td>
			<td>
				<div class="valign-middle">
					<textarea name="message[mailbody]" id="mailtext" cols="80" rows="20"
						{tip class="lms-ui-wysiwyg-editor" trigger="mailbody"}
						{if isset($message.wysiwyg.mailbody)} data-wysiwyg="{$message.wysiwyg.mailbody}"{/if}>{$message.body}</textarea>
					<div class="lms-ui-util-buttons">
						{hint text=trans("Enter message body.")|cat:"<br><br>"|cat:trans($content_hint)}
						{speech_recognition target="#mailtext"}
					</div>
				</div>
			</td>
		</tr>
		<tr id="smsbody"{if $message.type < $smarty.const.MSG_SMS || $message.type > $smarty.const.MSG_ANYSMS} style="display: none"{/if}>
			<td>
				{icon name="edit"}
			</td>
			<td class="nobr">
				<strong>{trans("Message body")}</strong>
			</td>
			<td>
				<div class="valign-middle">
					<textarea name="message[smsbody]" id="smstext" cols="60" rows="5" onkeydown="countChars(this)"
						onkeyup="countChars(this)" {tip trigger="smsbody"}
						>{$message.body}</textarea>
					<div class="lms-ui-util-buttons">
						{hint text=trans("Enter message body.")|cat:"<br><br>"|cat:trans($content_hint)}
						{speech_recognition target="#smstext"}
					</div>
				</div>
			</td>
		</tr>
		<tr>
			<td>
				&nbsp;
			</td>
			<td>
				&nbsp;
			</td>
			<td>
				<label>
					<input type="radio" name="message[tmploper]" value="1" checked>
					{trans("no operation on message template")}
				</label>
				<br>
				<label>
					<input type="radio" name="message[tmploper]" value="2">
					{trans("message template update")}
				</label>
				<br>
				<label>
					<input type="radio" name="message[tmploper]" value="3">
					{trans("message template creation")}
				</label>
				<input type="text" size="40" name="message[tmplname]" id="msgtmplname" maxlength="45" style="display: none;"
					{tip trigger="tmplname" text="Enter name of the new message template"}>
			</td>
		</tr>
		<tr id="charscount"{if $message.type < $smarty.const.MSG_SMS || $message.type > $smarty.const.MSG_ANYSMS} style="display: none"{/if}>
			<td></td>
			<td class="nobr">
				<strong>{trans("Characters")}</strong>
			</td>
			<td id="charscounttext">0</td>
		</tr>
		<tr id="attachment"{if $message.type > $smarty.const.MSG_MAIL} style="display: none"{/if}>
			<td class="valign-top">
				{icon name="attachment"}
			</td>
			<td class="nobr valign-top">
				<strong>{trans("Attachments")}</strong>
			</td>
			<td id="file-list">
				{fileupload id="files" fileupload=$fileupload form="message"}
				{if !empty($message['file-container'])}
					<input type="hidden" name="message[file-container][id]" value="{$message['file-container'].id}">
					<div id="container-file-list">
						<span>
							<strong>{trans("from earlier sent message")}</strong>
						</span>
						<ul>
							{foreach $message['file-container'].files as $file}
								<li{if !empty($file.deleted)} class="deleted"{/if}>
									<input type="hidden" class="deleted-file" name="message[file-container][files][{$file.id}][deleted]" value="{if $file.deleted}1{else}0{/if}">
									<input type="hidden" name="message[file-container][files][{$file.id}][id]" value="{$file.id}">
									{$deleted = !empty($file.deleted)}
									{button type="link" icon="trash" class="file-delete" style="{if $deleted} display: none;{/if}"}
									{button type="link" icon="restore" class="file-restore" visible="false" style="{if !$deleted} display: none;{/if}"}
									{capture assign="filename"}
										{$file.filename|escape} ({$file.sizestr})
									{/capture}
									{documentview
										id="file-{$file.id}"
										type=$file.contenttype
										name=$filename
										url="?m=attachments&attachmentaction=viewfile&type=messageid&id={$message['file-container'].id}&fileid={$file.id}"
									}
								</li>
							{/foreach}
						</ul>
					</div>
				{/if}
			</td>
		</tr>
		<tr id="template-attachments" style="display: none;">
			<td class="valign-top">
				{icon name="attachment"}
			</td>
			<td class="valign-top nobr">
				<strong>{trans("Template attachments")}</strong>
			</td>
			<td id="template-attachment-list">
			</td>
		</tr>
		<tr>
			<td colspan="3" class="lms-ui-box-buttons">
				{button icon="quick-send" id="submit-button" label="Send"}
			</td>
		</tr>
    </tbody>
</table>
</form>

<script>

	$(function() {
		$('form[name="message"] [name="message[sender]"]').focus();

		$('[name="message[type]"]').change(function() {
			$('#customer-filter').toggle(parseInt($(this).val()) != {$smarty.const.MSG_ANYSMS}{if !empty($message.customers)} || true{/if});

			var elem = $(this).attr('id');

			$('[data-contact-type]').each(function() {
				var disabled = elem != $(this).attr('data-contact-type');
				$(this).toggleClass('lms-ui-disabled', disabled).find('select').prop('disabled', disabled);
			});

			if (elem == 'typesms' || elem == 'typeanysms' || elem == 'typewww' || elem == 'typeuserpanel' || elem == 'typeuserpanelurgent') {
				$('#mailfrom,#mailsender,.additional-email-addresses,.additional-email-address').hide();

				$('.scheduled-message').toggle(elem != 'typewww' && elem != 'typeuserpanel' && elem != 'typeuserpanelurgent');

				$('#attachment').toggle(elem != 'typesms' && elem != 'typeanysms' && elem != 'typewww');

				{if $message.emailcount}
					$('#customermails').hide();
				{/if}

				$('#users,#phonenumber,#customer-data').toggle(elem == 'typeanysms');
				$('#customer-recipient').toggle(elem != 'typeanysms');

				$('#mailbody').toggle(elem == 'typewww' || elem == 'typeuserpanel' || elem == 'typeuserpanelurgent');
				$('#smsbody,#charscount').toggle(elem != 'typewww' && elem != 'typeuserpanel' && elem != 'typeuserpanelurgent');
				if (elem == 'typewww') {
					{if $message.phonecount}
						$('#customerphones').hide();
					{/if}

					xajax_getMessageTemplates({$smarty.const.TMPL_WWW});
				} else if (elem == 'typeuserpanel') {
					{if $message.phonecount}
						$('#customerphones').hide();
					{/if}

					xajax_getMessageTemplates({$smarty.const.TMPL_USERPANEL});
				} else if (elem == 'typeuserpanelurgent') {
					{if $message.phonecount}
						$('#customerphones').hide();
					{/if}

					xajax_getMessageTemplates({$smarty.const.TMPL_USERPANEL_URGENT});
				} else {
					{if $message.phonecount}
						$('#customerphones').toggle(elem != 'typeanysms');
					{/if}

					xajax_getMessageTemplates({$smarty.const.TMPL_SMS});
				}
			} else {
				$('#mailbody,#mailfrom,#mailsender,.additional-email-addresses,scheduled-message,#attachment').show();
				$('.additional-email-address').css('display', '');
				$('.additional-email-address').toggleClass('hidden', !$('[name="message[cc-email]"]').val().length && !$('[name="message[bcc-email]"]').val().length && !$('[name="message[reply-email]"]').val().length);

				{if $message.emailcount}
					$('#customermails').show();
				{/if}

				{if $message.phonecount}
					$('#customerphones').hide();
				{/if}

				if ($('#phonenumber').length) {
					$('#phonenumber').hide();
				}
				$('#smsbody,#charscount').hide();
				xajax_getMessageTemplates({$smarty.const.TMPL_MAIL});
			}
			$('#msgtmplid').prop('disabled', true);
		});

		$('#additional-email-addresses-button').click(function() {
			$('.additional-email-address').toggleClass('hidden');
			$(this).find('i').toggleClass('lms-ui-icon-next lms-ui-icon-previous');
			$(this).find('.lms-ui-label').text($(this).find('i').is('.lms-ui-icon-next') ?
				'{trans("More e-mail addresses")}' :
				'{trans("Less e-mail addresses")}'
			);
		});

		$('#startdate').change(function() {
			var disabled = !$(this).val().length;
			$('#attempts').prop('disabled', disabled).prop('required', !disabled);
			$('.attempts-field').toggleClass('lms-ui-disabled', disabled);
		}).change();

		$('#usergroup-selection').change(function() {
			var userms = $('#user-selection').data('multiselect-object');
			var users = JSON.parse($(this).find('option:selected').attr('data-users'));
			$.each(users, function(index, value) {
				users[index] = String(value);
			});
			userms.filterSelection(users);
		}).change();

		{if isset($autoload_template) && $message.tmplid}
			$('#msgtmplid').change();
		{/if}

		$('.customer-contact :checkbox').click(function() {
			var customers = $(this).closest('.customers');
			customers.find('.customer-list-summary')
				.text($t(
					'$a selected contacts of $b customers',
					customers.find(':checkbox:checked').length,
					customers.find('.customer-list-item').length
				));
		});

		$('.customer-list-summary-container .lms-ui-button').click(function() {
			$(this).closest('.customers').find('.customer-list').toggle();
			$(this).toggle().siblings('.lms-ui-button').not(this).toggle();
		});

		$('.customer-list-summary').click(function() {
			$(this).closest('.customers').find('.customer-list').toggle();
			$(this).siblings('.lms-ui-button').not(this).toggle();
		});

		$('[name="message[tmploper]"]').change(function() {
			$('#msgtmplname').toggle(parseInt($(this).val()) == 3);
		});

		$('#smstext').mouseout(function() {
			countChars(this);
			pophide();
		}).mouseout();

		$('#submit-button').click(function() {
			var progressDeferred = progressDialog($t("Preparing recipient list. Please wait."));

			var that = this;
			tinyMCE.triggerSave();

			$(that).prop('disabled', true);

			var ajaxRequest = $.ajax(
				'?m=messageadd&validate=1',
				{
					method: "POST",
					dataType: "json",
					data: $('#message').serialize()
				}
			).done(function (data) {
				function sendFormData() {
					var modalDialog = $('#lms-ui-modal-dialog');
					var status = modalDialog.find('.status');
					var progressBar = modalDialog.find('.progress-bar');
					var logMessages = modalDialog.find('.log-messages');
					var messageId = null;
					var lastLen = 0;

					var form = $('#message').get(0);
					var formData = new FormData(form);

					var progressDeferred = progressDialog(
						$t("Preparing messages..."),
						null,
						{
							showProgressBar: true,
							showLogMessages: true
						}
					);

					var ajaxRequest = $.ajax({
						url: this.action,
						method: 'POST',
						data: formData,
						processData: false,
						contentType: false,
						xhr: function() {
							var xhr = new window.XMLHttpRequest();
							var total = 0;
							var item = 0;
							var unhandledLine = '';

							xhr.onprogress = function() {
								var responseText = xhr.responseText || '';
								var chunk = responseText.substring(lastLen);
								lastLen = responseText.length;

								if (chunk) {
									$.each(chunk.split(/\r?\n/), function(index, line) {
										var icon, token;

										try {
											if (unhandledLine.length) {
												line = unhandledLine + line;
												unhandledLine = '';
											}
											token = JSON.parse(line);
										} catch (e) {
											unhandledLine = line;
											return;
										}

										if (token.hasOwnProperty('message')) {
											status.html(token.message);
										} else if (token.hasOwnProperty('logmessage')) {
											logMessages.append(token.logmessage + '<br>');
										} else if (token.hasOwnProperty('item')) {
											if (!total && token.hasOwnProperty('total')) {
												status.html($t("Sending messages"));
												total = parseInt(token.total);
												progressBar.progressbar('option', 'max', total);
											}
											item = parseInt(token.item);
											progressBar.progressbar('value', item);
											icon = token.hasOwnProperty('icon') ? token.icon : '';
											recipient = token.hasOwnProperty('recipient') ? token.recipient : '';
											logMessages.append('<i class="' + icon + '"></i> (' + item + ' / ' + total + ') ' + recipient + ':');
										} else if (token.hasOwnProperty('status')) {
											logMessages.append(' ' + token.status + '<br>');
										} else if (token.hasOwnProperty('messageid')) {
											messageId = parseInt(token.messageid);
										}
									});

									logMessages.scrollTop(logMessages[0].scrollHeight);
								}
							};

							return xhr;
						},
						success: function(data) {
							status.html($t("Finished"));

							var buttons = modalDialog.dialog('option', 'buttons');

							// zmień pierwszy przycisk
							buttons[0].text = $t('Info');
							buttons[0].icon = 'ui-icon-info';
							buttons[0].click = function () {
								location.href = '?m=messageinfo&id=' + messageId;
							};

							modalDialog.dialog('option', 'buttons', buttons);
						}
					});

					progressDeferred.fail(function() {
						ajaxRequest.abort();
						$(that).prop('disabled', false);
					});
				}

				progressDeferred.reject();

				if (data.hasOwnProperty('error')) {
					var error = data.error;

					if (error.hasOwnProperty('recipients')) {
						alertDialog(error.recipients);
					}

					$.each(error, function (property, message) {
						var elem = $('[name="message[' + property + ']"]');
						if (!elem.length) {
							elem = $('#' + property);
						}
						if (elem.length) {
							if (!elem.is(':visible')) {
								if (elem.is('.lms-ui-wysiwyg-editor')) {
									elem = elem.siblings('.tox-tinymce')
								}
							}
							elem.addClass('lms-ui-error').attr('title', message);
						}
					});

					return;
				} else {
					$('#message').find('.lms-ui-error').removeClass('lms-ui-error');
				}

				var confirmThreshold = {intval(ConfigHelper::getConfig('messages.send_confirm_threshold', ConfigHelper::getConfig('phpui.send_message_confirm_threshold', 50)))};

				if (data.recipients <= confirmThreshold) {
					sendFormData();
				} else {
					var violationType = '{ConfigHelper::getConfig('messages.send_limit_violation_type', ConfigHelper::getConfig('phpui.send_message_limit_violation_type', 'warning'))}';
					switch (violationType) {
						case 'error':
							alertDialog(
								$t(
									"You violate recipient limit ($a) trying to send messages to $b customer(s)!",
									confirmThreshold,
									data.recipients
								)
							).done(function() {
								$(that).prop('disabled', false);
							});
							break;
						case 'warning':
							confirmDialog(
								$t(
									"Are you sure you want to send messages to $a customer(s)?",
									data.recipients
								)
							).done(function() {
								sendFormData();
							}).fail(function() {
								$(that).prop('disabled', false);
							});
							break;
						default:
							sendFormData();
							break;
					}
				}
			});

			progressDeferred.fail(function() {
				ajaxRequest.abort();
				$(that).prop('disabled', false);
			});
		});

		$('#msgtmplid').change(function() {
			var templateId = parseInt($(this).val());
			if (templateId) {
				xajax_getMessageTemplate(templateId, 'subject', {if $message.emailcount || empty($message.customers)}$('#typemail').prop('checked') || {/if}
				$('#typewww').prop('checked') || $('#typeuserpanel').prop('checked') || $('#typeuserpanelurgent').prop('checked') ? 'mailbody' : 'smsbody');
			} else {
				$('#template-attachments').hide();
				$('#template-attachment-list').empty();
			}
		});

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

		$('#container-file-list li').find('.file-delete,.file-restore').click(function() {
			var deleted = $(this).is('.file-delete');
			$(this).toggle();
			$(this).siblings('.lms-ui-button').show();
			$(this).closest('li').toggleClass('deleted', deleted)
				.find('.deleted-file').val(deleted ? 1 : 0);
		});
	});

</script>
{/block}
