{extends file="layout.html"}
{block name=title}LMS: {$layout.pagetitle|striphtml}{/block}
{block name=module_content}
{$privacy_status_change_warning = ConfigHelper::checkConfig('timetable.privacy_status_change_warning')}
{$hide_disabled_users = ConfigHelper::checkConfig('timetable.hide_disabled_users', ConfigHelper::checkConfig('phpui.timetable_hide_disabled_users'))}
{$hide_deleted_users = ConfigHelper::checkConfig('timetable.hide_deleted_users', ConfigHelper::checkConfig('phpui.timetable_hide_deleted_users'))}
	<!--// $Id$ //-->
	{$xajax}
	{if empty($event.ticketid)}
		<H1>{$layout.pagetitle}</H1>
	{else}
		<H1>{t a=$event.ticketid}Add new event to request #$a{/t}</H1>
	{/if}
	<style>

		#event.lms-ui-box-container .lms-ui-box-contents .lms-ui-box-panel .lms-ui-box-row .lms-ui-box-row-label {
			width:12em;
		}
		#event.lms-ui-box-container .lms-ui-box-row-field.multiselect {
			flex-direction: column !important;
			align-items: flex-start !important;
		}

		#eventadd-ticket,
		#eventedit-ticket {
			display: flex;
		}

	</style>
	<P class="text-center">
	<FORM method="POST" action="?m={$layout.module}" name="event" id="event">
		<INPUT type="hidden" name="event[id]" value="{$event.id}">
		<INPUT type="hidden" name="event[overlapwarned]" value="{$event.overlapwarned}">
		<INPUT type="submit" class="hiddenbtn">

		{box_container id="event"}
			{box_header icon="timetable" label="Title:" icon_class="fa-fw"}
				<INPUT type="text" name="event[title]" id="event[title]" value="{$event.title}" required size="50" {tip text="Enter event title" trigger="title"}>
			{/box_header}

			{box_contents}
				{box_panel}
					{block name="eventmodify_left_panel"}

					{box_row icon="uptime" label="Time:" icon_class="fa-fw"}
						{if $layout.module == 'eventadd'}
							{$allow_past_date = ConfigHelper::checkConfig('timetable.allow_past_events', ConfigHelper::checkConfig('phpui.timetable_allow_past_events', true))}
						{else}
							{$allow_past_date = true}
						{/if}
						{event_time_selection field_prefix="event" begin=$event.begin end=$event.end wholedays=$event.wholedays
							allow_past_date=$allow_past_date}
					{/box_row}

					{box_row icon="description" label="Description:" icon_class="fa-fw"}
						<TEXTAREA name="event[description]" id="description" cols="50" rows="5"
								{tip text="Enter additional information (optional)" class="lms-ui-wysiwyg-editor" trigger="description"}
								{if isset($event.wysiwyg.description)} data-wysiwyg="{$event.wysiwyg.description}"{/if}>{$event.description}</TEXTAREA>
					{/box_row}

					{/block}
				{/box_panel}

				{box_panel}
					{block name="eventmodify_right_panel"}

					{box_row icon="status" label="Availability:" icon_class="fa-fw"}
						<label>
							<INPUT type="checkbox" name="event[private]" {tip text="Select event's status"}{if $event.private}CHECKED{/if}>
							{trans("private")}
						</label>
					{/box_row}

					{box_row icon="type" label="Type:" icon_class="fa-fw"}
						<select name="event[type]" size="1">
							{foreach Localisation::arraySort($_EVENTTYPES, 'label') as $idx => $eventtype}
								<option value="{$idx}"
									{if $idx == $event.type || (!$event.type && $idx == $smarty.const.EVENT_OTHER)} selected{/if}
									>{$eventtype.label}</option>
							{/foreach}
						</select>
					{/box_row}

					{box_row icon="division" label="Division" icon_class="fa-fw"}
						<select name="event[divisionid]" size="1">
							<option value="">{trans("— none —")}</option>
								{foreach $divisions as $division}
									{if !$division.status || $division.id == $event.divisionid}
										<option value="{$division.id}"{if !empty($event.divisionid) && $division.id == $event.divisionid} selected{/if}
										>{$division.label|escape}</option>
									{/if}
								{/foreach}
						</select>
					{/box_row}

					{box_row icon="customer" label="Customer:" icon_class="fa-fw"}
						{if $layout.module == 'eventedit' || (empty($event.ticketid) && empty($event.customerid))}
							{$customer_selector='[name=&quot;event[custid]&quot;]'}
							{$address_selector='[name=&quot;event[address_id]&quot;]'}
							{customerlist form="event" customers=$customerlist selected=$event.customerid version=2
								selectname="event[customerid]" inputname="event[custid]" customOnChange="change_customer('{$customer_selector}', '{$address_selector}');"}
						{else}
							{if !empty($event.customerid)}
								{$event.customername} ({$event.customerid})
								<input type="hidden" name="event[custid]" value="{$event.customerid}">
							{else}
								{trans("Request not assigned to any customer.")}
							{/if}
						{/if}
					{/box_row}

					{box_row icon="location" label="Location:" icon_class="fa-fw"}
						{if !isset($event.ticketid) || empty($event.ticket.address_id)}
							{include file="customer/customeraddresses.html" id="customer_addresses" name="event[address_id]" trigger="address_id"}
						{else}
							{t a=$event.ticket.location}$a (location cannot be changed as it is assigned to ticket){/t}
						{/if}
					{/box_row}

					{$visibility=!empty($netnodelist)}
					{box_row class="netnode-row" icon="netnode" label="Network node" visible=$visibility icon_class="fa-fw"}
						{if empty($netnodeid)}
							{network_node_selection
								id='netnodeid'
								name='event[netnodeid]'
								form='event'
								selected=$event.netnodeid
								onchange="xajax_netnode_changed($(this).val(), $('#eventnetdevid').val(), 'event', 'eventnetdevs', 'eventnetdevid')"}
						{else}
							{foreach $netnodelist as $nn}
								{if $nn.id == $netnodeid}
									{$nn.name|escape} (#{$nn.id})
									<input type="hidden" name="event[netnodeid]" value="{$netnodeid}">
								{/if}
							{/foreach}
						{/if}
					{/box_row}

					{$visibility=!empty($netdevlist)}
					{box_row icon="netdev" label="Device" field_id="eventnetdevs" icon_class="fa-fw" visible=$visibility}
						{if empty($netdevid)}
							{include file="rt/rtnetdevs.html" form="event"}
						{else}
							{$netdevlist[0].name|escape} (#{$netdevid})
							<input type="hidden" name="event[netdevid]" value="{$event.netdevid}">
						{/if}
					{/box_row}

					{$visibility=!empty($nodes)}
					{box_row class="node-row" icon="node" label="Node:" icon_class="fa-fw" visible=$visibility}
						{if !empty($event.ticketid) || !empty($nodes)}
							<select class="node-list" name="event[nodeid]" {tip text="Select node"}>
								<option value="">{trans("— none —")}</option>
								{foreach $nodes as $node}
									<option value="{$node.id}"{if $node.id == $event.nodeid || count($nodes) == 1} selected{/if}>{$node.name}: {$node.location}</option>
								{/foreach}
							</select>
						{else}
							{if !empty($event.ticket.nodeid)}
								{$event.ticket.node_name} ({$event.ticket.nodeid})
								<input type="hidden" name="event[nodeid]" value="{$event.ticket.nodeid}">
							{else}
								{trans("Request not assigned to any node.")}
							{/if}
						{/if}
					{/box_row}

					{box_row icon="user" label="Users:" field_class="multiselect" icon_class="fa-fw"}
						<select name="event[userlist][]" class="lms-ui-advanced-select-test" id="userlist" multiple
								{if ConfigHelper::checkConfig('timetable.event_user_required', ConfigHelper::checkConfig('phpui.event_user_required'))}required{/if}>
							{foreach $userlist as $user}
								{if (!is_array($event.userlist) || !in_array($user.id, $event.userlist))
									&& ($hide_disabled_users && !$user.access
										|| $hide_deleted_users && $user.deleted)}
									{continue}
								{/if}
								{if $layout.module == 'eventadd'}
									<option value="{$user.id}"
										class="{if !$user.access} lms-ui-disabled{/if}{if $user.deleted} lms-ui-crossed{/if}"
										{if is_array($event.userlist) && in_array($user.id, $event.userlist)}selected{/if}>
											{$user.rname|trunescape:40} ({$user.login})
									</option>
								{else}
									<option value="{$user.id}"
										class="{if !$user.access} lms-ui-disabled{/if}{if $user.deleted} lms-ui-crossed{/if}"
										{if is_array($event.userlist) && in_array($user.id, $event.userlist)}selected{/if}>
											{$user.rname|trunescape:40} ({$user.login})
									</option>
								{/if}
							{/foreach}
						</select>
						<br>
						<label>
							<input type="radio" name="event[usergroup]" id="usergroup_me" value="-1" onChange="xajax_getUsersForGroup(-1)"{if $event.usergroup == -1} checked{/if}>
							{trans("assign to me")}<br>
						</label>
						<label>
							<input type="radio" name="event[usergroup]" id="usergroup_0" value="0" onChange="xajax_getUsersForGroup(0)"{if empty($event.usergroup)} checked{/if}>
							{trans("None")}<br>
						</label>
						<label>
							<input type="radio" name="event[usergroup]" id="usergroup_-2" value="-2" onChange="xajax_getUsersForGroup(-2)"{if empty($event.usergroup)} checked{/if}>
							{trans("All users")}<br>
						</label>
						{foreach $usergroups as $group}
							<label>
								<input type="radio" name="event[usergroup]" id="usergroup_{$group.id}" value="{$group.id}" onClick="xajax_getUsersForGroup({$group.id})"{if $event.usergroup == $group.id} checked{/if}>
								{$group.name}<br>
							</label>
						{/foreach}
					{/box_row}

					{function event_ticket_item_content}
						{capture name="item_content_result" assign="item_content_result"}
							{hint icon="info" mode="toggle" url="?m=rtticketinfo&id={$item.id}"}
							(#{$item.id})
							<a class="lms-ui-list-item-name" href="?m=rtticketview&id={$item.id}">{$item.name}</a>
						{/capture}
					{/function}

					{if $layout.module == 'eventedit'}
						{box_row icon="note" icon_class="fa-fw" label="Note:"}
							<TEXTAREA name="event[note]" cols="50" rows="5" {tip text="Enter note (optional)"}>{$event.note}</TEXTAREA>
						{/box_row}

						{box_row icon="helpdesk" icon_class="fa-fw" label="Assign ticket"}
							<input type="hidden" name="event[ticketid]" value="0">
							{list id="eventedit-ticket" tipid="ticketid" tip="Test" items=$event.ticket
								field_name_pattern="event[ticketid]" item_content="event_ticket_item_content"}
						{/box_row}
					{/if}

{if $layout.module == 'eventadd'}
						{box_row icon="helpdesk" label="<!ticket-event>Ticket:" icon_class="fa-fw"}
							<label for="helpdesk-none">
								<input type="radio" class="helpdesk-assign-selection" id="helpdesk-none" name="event[helpdesk]" value="none"{if $event.helpdesk == 'none'} checked{/if}>
								{trans("<!ticket-event>none")}
							</label>
							<label for="helpdesk-new">
								<input type="radio" class="helpdesk-assign-selection" id="helpdesk-new" name="event[helpdesk]" value="new"{if $event.helpdesk == 'new'} checked{/if}>
								{trans("<!ticket-event>new")}
							</label>
							<label for="helpdesk-assign">
								<input type="radio" class="helpdesk-assign-selection" id="helpdesk-assign" name="event[helpdesk]" value="assign"{if $event.helpdesk == 'assign'} checked{/if}>
								{trans("<!ticket-event>assign")}
							</label>
							&nbsp;
							<input type="hidden" name="event[ticketid]" value="0">
							{if !isset($event.helpdesk) || $event.helpdesk != 'assign'}
								{$visible = false}
							{else}
								{$visible = true}
							{/if}
							{list id="eventadd-ticket" tipid="ticketid" tip="Test" items=$event.ticket
								field_name_pattern="event[ticketid]" item_content="event_ticket_item_content" visible=$visible}
						{/box_row}
{/if}

					{/block}
				{/box_panel}
			{/box_contents}

			{box_buttons}
				{if $layout.module == 'eventadd'}
					<label {tip text="Display this form again, when this event is saved"}>
						<INPUT type="checkbox" name="event[reuse]"{if $event.reuse} checked{/if}>
						{trans("Reuse")}
					</label>
				{/if}
				<label>
					<input type="checkbox" name="event[close]"{if $event.close} checked{/if} value="1">
					{trans("close event")}
				</label>
				{button type="submit" icon="save" accesskey="s" label="Submit"}
				{button icon="cancel" href="{$backurl}" label="Cancel"}
			{/box_buttons}
		{/box_container}
        <div id="row"{if $layout.module == 'eventedit' || $event.helpdesk == 'none' || $event.helpdesk == 'assign'} style="display:none;"{/if}>
			{if $layout.module == 'eventadd'}
				{include file="rt/rtticketmodify.html"}
			{/if}
        </div>
	</form>
	<script type="text/javascript" src="js/lms-ui-event-time-slider.js"></script>
	<SCRIPT>

		$(function() {
			$('[name="event[title]"]').focus();

			{if $privacy_status_change_warning}
				$('input[name="event[private]"]').change(function () {
					alertDialog($t('Warning! You have changed privacy status for this timetable event!'));
				});
			{/if}

			$('[name="event[rtqueue]"]').change(function () {
				var newticket_notify = $(this).find(':selected').attr('data-newticket-notify');
				if (newticket_notify === undefined) {
					$('#customernotify-row').hide();
					$('#customernotify').attr('checked', false);
				} else {
					$('#customernotify-row').show();
					$('#customernotify').attr('checked', true);
				}
				xajax_GetCategories($(this).val());
			});

			var newticket_notify = $('[name="event[rtqueue]"]').find(':selected').attr('data-newticket-notify');
			if (newticket_notify === undefined) {
				$('#customernotify-row').hide();
			} else {
				$('#customernotify-row').show();
			}

			function updateTicketRequirements(assign_type) {
				{if ConfigHelper::checkConfig('rt.ticket_service_required')}
					$('#ticket-service').attr('required', function() {
						return assign_type == 'new' ? '' : null;
					});
				{/if}
				{if ConfigHelper::checkConfig('rt.ticket_type_required')}
					$('#ticket-type').attr('required', function() {
						return assign_type == 'new' ? '' : null;
					});
				{/if}
			}

			$('.helpdesk-assign-selection').change(function() {
				var assign_type = $(this).val();
				$('#row').toggle(assign_type == 'new');
				updateTicketRequirements(assign_type)
				var list_container = $('#eventadd-ticket,#eventedit-ticket');
				list_container.toggle(assign_type == 'assign');
				if (assign_type == 'assign' && !list_container.find('li').length) {
					list_container.find('.lms-ui-item-suggestion-button').click();
				}
			});
			{if isset($event.helpdesk)}
				updateTicketRequirements('{$event.helpdesk}');
			{/if}

			initListQuickSearch({
				selector: '#eventadd-ticket',
				field_name_pattern: 'event[ticketid]',
				single: true,
				ajax: '?m=quicksearch&api=1&ajax=1&mode=ticket&what=',
				item_content: function(item) {
					return sprintf("#%06d", item.id) + ' <a href="?m=rtticketview&id=' + item.id + '">' +
							item.name + '</a>';
				}
			});
			initListQuickSearch({
				selector: '#eventedit-ticket',
				field_name_pattern: 'event[ticketid]',
				single: true,
				ajax: '?m=quicksearch&api=1&ajax=1&mode=ticket&what=',
				item_content: function(item) {
					return sprintf("#%06d", item.id) + ' <a href="?m=rtticketview&id=' + item.id + '">' +
							item.name + '</a>';
				}
			});

			function customerChanged(selector) {
				var disabled = !['', '0'].includes(typeof(selector) == 'string' ? $(selector).val() : $(this).val());

				$('[name="event[divisionid]"]')
					.prop('disabled', disabled)
					.closest('.lms-ui-box-row')
					.toggleClass('lms-ui-disabled', disabled);
			}

			$('[name="event[custid]"]').change(customerChanged);
			customerChanged('[name="event[custid]"]');
		});

		function update_user_selection(users) {
			var userms = $('#userlist').val();
			{if ConfigHelper::getConfig('timetable.event_usergroup_selection_type', ConfigHelper::getConfig('phpui.event_usergroup_selection_type')) == 'filter'}
				$("#userlist").val( users );
			{else}
				var users2 = jQuery.unique([].concat.apply(users, userms));
				$("#userlist").val( users2 );
			{/if}
			updateAdvancedSelectsTest(userlist);
		}

		{if intval($event.customerid)}
			{if $event.address_id}
				$('#customer_addresses').val( {$event.address_id} );
			{elseif !empty($addresses) && count($addresses) == 1}
				$('#customer_addresses').val($('#customer_addresses option:last-child').val());
			{/if}
		{/if}

		initAdvancedSelectsTest('#customer_addresses');
		$('#customer_addresses').change(function() {
			xajax_select_location($('[name="event[custid]"]').val(), $(this).val());
		}).on('lms:address_list_updated', function() {
			{if ConfigHelper::checkConfig('timetable.location_required')}
				$(this).prop('required', $('[name="event[custid]"]').val().length > 0).trigger('lms:advanced_select_update');
			{/if}
		}).on('lms:advanced_select_validate_required', function(e, data) {
			{if ConfigHelper::checkConfig('timetable.location_required')}
				var emptyCustomerId = !$('[name="event[custid]"]').val().length;
				data.advancedSelectElement.toggleClass('lms-ui-error', !emptyCustomerId && data.invalidValue);
				this.setCustomValidity(!emptyCustomerId && data.invalidValue ? $t('Location address is not selected') : '');
			{/if}
		});

		{if ConfigHelper::checkConfig('timetable.location_required')}
			$('#customer_addresses').trigger('lms:address_list_updated');
		{/if}

		{if $layout.module == 'eventedit'}
			function change_customer(customer_selector, address_selector) {
				var customerId = $(customer_selector).val();
				getCustomerAddresses(customerId, function (addresses) {
					var addressId = $('#customer_addresses').val();
					setAddressList('#customer_addresses', addresses);

					if (Object.keys(addresses).length) {
						$.each(addresses, function(index, address) {
							if (address.hasOwnProperty('default_address')) {
								$('#customer_addresses').val(address.address_id);
								updateAdvancedSelectsTest('#customer_addresses');
							}
						});
					} else {
						$('#customer_addresses').val(addressId);
					}
					updateAdvancedSelectsTest('#customer_addresses');

					xajax_select_location(customerId, $(address_selector).val());
					$('#customer_addresses').trigger('lms:address_list_updated');
				});
			}
		{/if}
		//initCustomerSelection('{$event.customerid}', '{$ticket.address_id}');

	</SCRIPT>
{/block}
