<!--// $Id$ //-->

<style>

    .tab-beautify td { padding: 3px; }
    .tab-beautify tr td:nth-child(2) {
        font-weight: bold;
        white-space: nowrap;
    }

	#network-connection > * {
		margin-top: 0.2em;
		margin-bottom: 0.2em;
	}

	.cell-flex {
		display: flex;
		flex-wrap: wrap;
	}

	@media screen and (max-width: 420px) {
		.tab-beautify tr td:nth-child(2) {
			white-space: normal;
		}

		.cell-flex > div .chosen-container {
			min-width: 243px;
		}

		.cell-flex > span {
            white-space: normal;
        }

		.cell-flex > div select {
			max-width: 185px;
			white-space: normal;
		}

        .lms-ui-wysiwyg-editor textarea{
            max-width: 200px;
        }
    }

</style>

{include file="google-maps.html"}

<form name="nodeadd" id="nodeadd" method="POST" action="?m=nodeadd{if $customerinfo.id}&ownerid={$customerinfo.id}{/if}">
	<input type="submit" class="hiddenbtn">
<table class="lmsbox">
	<colgroup>
		<col style="width: 1%;">
		<col style="width: 99%;">
	</colgroup>
	<thead>
		<tr>
			<td>
				{icon name="node"}
			</td>
			<td>
				<input type="text" name="nodedata[name]" value="{$nodedata.name}" maxlength="32" size="30"
					required placeholder="{trans("Node name")}" {tip trigger="name" bold=1}>
			</td>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td colspan="2" class="container">
				<table style="width: 100%;" cellpadding="0">
					{block name="nodeaddbox-tablebody"}
					<tr>
						<td class="lmsbox-panels">
							<div class="lmsbox-panel">
								<table>
									<colgroup>
										<col style="width: 1%;">
										<col style="width: 99%;">
									</colgroup>
									{block name="nodeaddbox-leftcolumn"}
									<tr>
										<td>
											{icon name="network"}
										</td>
										<td class="cell-flex">
											<div>
												<select size="1" name="nodedata[netid]" id="netid"
														{tip class="lms-ui-advanced-select-test" trigger="netid"}>
													<option value="0">{trans("— automatic selection —")}</option>
													{foreach $networks as $net}
														<option value="{$net.id}" data-pubnetid="{$net.pubnetid}"
																{if $net.id == $nodedata.netid} selected{/if}
																{if $net.disabled == 1} class="lms-ui-alert"{/if}>{$net.name|truncate:20:"":true}: {$net.address}/{$net.prefix}</option>
													{/foreach}
												</select>
												{if ConfigHelper::checkConfig('phpui.show_assigned_networks_only') && ConfigHelper::checkConfig('nodes.public_ip', ConfigHelper::checkConfig('phpui.public_ip', true))}
													<script>

														$('#netid').change(function() {
															var pubnetid = parseInt($('option:selected', this).attr('data-pubnetid'));
															if (pubnetid) {
																$('[name="nodedata[pubnetid]"]').val(0);
															}
														});

													</script>
												{/if}
												<label>
													<input type="checkbox" name="nodedata[wholenetwork]" value="1"
														id="wholenetwork"
														{if $nodedata.wholenetwork} checked{/if}>
													{trans("the whole network")}
												</label>
											</div>
										</td>
									</tr>
									<tr>
										<td>
											{icon name="routed"}
										</td>
										<td class="cell-flex">
											<div>
												<input type="text" name="nodedata[ipaddr]" id="ipaddr" value="{$nodedata.ipaddr}" required
													placeholder="{trans("IP address")}"
													data-manually-changed="0"
													{tip trigger="ipaddr"}>
												{button type="link" onClick="return ipchoosewin({
														ipelem: document.nodeadd['nodedata[ipaddr]'],
														ip: document.nodeadd['nodedata[ipaddr]'].value,
														netelem: document.nodeadd['nodedata[netid]'],
														netid: document.nodeadd['nodedata[netid]'].value
														});" tip="Click to select IP from the list"
													icon="next"}
											</div>
											{button type="link" id="get-first-free-address" icon="download"
												label="Select first free address"}
										</td>
									</tr>

									{if ConfigHelper::checkConfig('nodes.public_ip', ConfigHelper::checkConfig('phpui.public_ip', true))}
										<tr>
											<td>
												{icon name="routed"}
											</td>
											<td>
												<input type="hidden" name="nodedata[pubnetid]"
													value="{if $nodedata.pubnetid}{$nodedata.pubnetid}{else}0{/if}">
												<input type="text" name="nodedata[ipaddr_pub]"
													placeholder="{trans("Pub. IP address")}"
													value="{$nodedata.ipaddr_pub}" {tip trigger="ipaddr_pub"}>
												{button type="link" onClick="return ipchoosewin({
														ipelem: document.nodeadd['nodedata[ipaddr_pub]'],
														ip: document.nodeadd['nodedata[ipaddr_pub]'].value,
														netelem: document.nodeadd['nodedata[pubnetid]'],
														netid: document.nodeadd['nodedata[pubnetid]'].value,
														privnetid: document.nodeadd['nodedata[netid]'].value
													});" tip="Click to select IP from the list"
														icon="next"}
											</td>
										</tr>
									{/if}

									<tr>
										<td>
											{icon name="mac"}
										</td>
										<td class="lms-ui-mac-address-selection" colspan="2">
											{mac_address_selection form="nodedata" macs=$nodedata.macs node_empty_mac=$node_empty_mac}
										</td>
									</tr>

									<tr>
										<td>
											{icon name="login"}
										</td>
										<td>
											<input type="text" name="nodedata[login]" value="{$nodedata.login|default:""|escape}"
												placeholder="{trans("<!node>Login")}"
												{tip trigger="login"}>
										</td>
									</tr>

									<tr>
										<td>
											{icon name="password"}
										</td>
										<td>
											<input type="text" name="nodedata[passwd]" value="{$nodedata.passwd|default:""|escape}"
												placeholder="{trans("Password")}"
												{tip trigger="passwd"}>
											{button type="link" id="genpasswd" icon="next"
												tip="Click to generate random password"}
										</td>
									</tr>

									{if $netdevices}
										<tr>
											<td>
												{icon name="netdev"}
											</td>
											<td class="cell-flex">
												<div id="network-connection">
													{button type="link" icon="search" tip="Search device"
														onclick="return netDevChooseWin(document.nodeadd.elements['nodedata[netdev]']);"}
													<select size="1" name="nodedata[netdev]" id="netdev" {tip trigger="netdev" class="lms-ui-advanced-select-test"}
															{if ConfigHelper::checkConfig('nodes.network_device_connection_required', ConfigHelper::checkConfig('phpui.node_to_network_device_connection_required'))} required{/if}>
														<option value="0"{if !$nodedata.netdev} selected{/if}>— {trans("no device")} —</option>
														{foreach $netdevices as $netdev}
															<option value="{$netdev.id}"
																	{if $nodedata.netdev == $netdev.id} selected{/if}
															>{$netdev.name}{if $netdev.producer} / {$netdev.producer}{/if}{if $netdev.location} ({$netdev.location}){/if}</option>
														{/foreach}
													</select>

													{button type="link" icon="map"
														onClick="return netdevfrommapchoosewin(document.nodeadd.elements['nodedata[netdev]']);"
														tip="Click to select network device from map"}

													<input type="text" name="nodedata[port]"
														value="{if $nodedata.port}{$nodedata.port}{/if}" size="2"
														{tip text="Enter port number in device (optional)" trigger="port"}>
													<br>

													<select name="nodedata[linktype]" id="linktype"
															{tip trigger="linktype" text="Select link type"}>
														{foreach $_LINKTECHNOLOGIES as $linktype => $linktech}
															<option value="{$linktype}"{if $linktype == $nodedata.linktype} selected{/if}>{$_LINKTYPES[$linktype]}</option>
														{/foreach}
													</select>

													<select name="nodedata[radiosector]" id="radiosector"
															{tip trigger="radiosector" text="Select radio sector"}
															{if $nodedata.linktype != $smarty.const.LINKTYPE_WIRELESS} style="display: none;"{/if}>
														<option value="0">{trans("— none —")}</option>
														{foreach $nodedata.radiosectors as $radiosector}
															<option value="{$radiosector.id}"
																	{if $radiosector.id == $nodedata.linkradiosector} selected{/if}
															>{$radiosector.name}</option>
														{/foreach}
													</select>

													<select name="nodedata[linktechnology]" id="linktechnology"
															{tip trigger="linktechnology" text="Select link technology"}
														<option value="0">{trans("— unknown —")}</option>
														{foreach $_LINKTECHNOLOGIES[$nodedata.linktype] as $linktechnologyidx => $linktechnology}
															<option value="{$linktechnologyidx}"
																{if $linktechnologyidx == $nodedata.linktechnology} selected{/if}
															>{$linktechnology}</option>
														{/foreach}
													</select>

													<select name="nodedata[linkspeed]" id="linkspeed"
															{tip trigger="linkspeed" text="Select link speed"}>
														{foreach $_LINKSPEEDS as $key => $item}
															<option value="{$key}"
																{if $key == $nodedata.linkspeed} selected{/if}
															>{$item}</option>
														{/foreach}
													</select>
												</div>
											</td>
										</tr>
									{/if}

									<tr>
										<td>
											{icon name="invproject"}
										</td>
										<td>
											<select name="nodedata[invprojectid]" id="project" value="{$nodedata.invprojectid}">
												<option value="-2" {if $nodedata.invprojectid == '-2'} selected{/if}
													>{trans("— none —")}</option>
												<option value="-1" {if $nodedata.invprojectid == '-1'} selected{/if}
													>{trans("New project")}</option>
												<option value="1" {if $nodedata.invprojectid == '1'} selected{/if}
													>{trans("From root device")}</option>
												{foreach $NNprojects as $project}
													<option value="{$project.id}"
														{if $nodedata.invprojectid == $project.id} selected{/if}
													>{$project.name|escape}</option>
												{/foreach}
											</select>
											<input type="text" name="nodedata[projectname]" value="{$nodedata.projectname|default:""|escape}"
												placeholder="{trans("Investment project")}"
												{tip trigger="projectname" } id="projectname"
												{if !isset($nodedata.invprojectid) || empty($nodedata.invprojectid)} style="display: none;"{/if}>
										</td>
									</tr>

									<tr>
										<td>
											{icon name="customer"}
										</td>
										<td>
											{customerlist
												form       = "nodeadd"
												customers  = $customers
												selected   = $nodedata.ownerid
												selectname = "nodedata[customerid]"
												select_id  = "customerid_select"
												inputname  = "nodedata[ownerid]"
												input_id   = "customerid_input"
												selecttip  = "Assign node to customer"
												required   = true
												customOnChange = "customer_change();"
												version = 2
											}
										</td>
									</tr>

									<tr>
										<td>
											{icon name="home"}
										</td>
										<td colspan="2">
											{if $nodedata.address_id && $nodedata.ownerid}
												{$selected_address_id = $nodedata.address_id}
											{else}
												{$selected_address_id = null}
											{/if}
											{include file="customer/customeraddresses.html" id="customer_addresses" name="nodedata[address_id]"
												trigger="nodedata[address_id]" selected_address_id=$selected_address_id}
										</td>
									</tr>

									<tr>
										<td>
											{icon name="options"}
										</td>
										<td>
											<label>
												<input type="checkbox" name="nodedata[chkmac]" value="1" id="chkmac"
													{tip text="Enable/disable MAC address checking" trigger="chkmac"}
													{if $nodedata.chkmac} checked{/if}>
												{trans("MAC checking")}
											</label>
											<label>
												<input type="checkbox" name="nodedata[halfduplex]" value="1" id="halfduplex"
													{tip text="Select transmission mode"}
													{if $nodedata.halfduplex} checked{/if}>
												{trans("Half duplex")}
											</label>
										</td>
									</tr>

									<tr>
										<td>
											{icon name="netdev"}
										</td>
										<td>
											{foreach $_SESSIONTYPES as $idx => $sessiontype}
											<label {tip text="`$sessiontype.tip`"}>
												<input type="checkbox" name="nodedata[authtype][{$idx}]" value="{$idx}"
													id="authtype{$idx}" {tip trigger="authtype`$idx`"}
													{if ($nodedata.authtype & $idx) == $idx} checked{/if}>
												{$sessiontype.label}
											</label><br>
											{/foreach}
										</td>
									</tr>
									{/block}
								</table>
							</div>
							<div class="lmsbox-panel">
								<table>
									<colgroup>
										<col style="width: 1%;">
										<col style="width: 1%;">
										<col style="width: 98%;">
									</colgroup>
									{block name="nodeaddbox-rightcolumn"}
									<tr>
										<td>
											{icon name="network"}
										</td>
										<td colspan="2">
											<span class="lms-ui-button" id="set_gps">
												{trans("Determine GPS coordinates automatically")}
											</span>
											&nbsp;
											{reset_to_defaults target="#longitude,#latitude"}
										</td>
									</tr>

									<tr>
										<td>
											{icon name="location"}
										</td>
										<td class="nobr">
											<strong>{trans("GPS longitude")}</strong>
										</td>
										<td>
											<input type="text" id="longitude" name="nodedata[longitude]"
												value="{if $nodedata.longitude}{$nodedata.longitude}{else}{/if}"
												{tip trigger="longitude"}>
											{button type="link" icon="map" tip="Click to select GPS coordinates from map"
												onClick="return gpscoordschoosewin(document.nodeadd.elements['nodedata[longitude]'], document.nodeadd.elements['nodedata[latitude]']);"}
										</td>
									</tr>

									<tr>
										<td>
											{icon name="location"}
										</td>
										<td class="nobr">
											<strong>{trans("GPS latitude")}</strong>
										</td>
										<td>
											<input type="text" id="latitude" name="nodedata[latitude]"
												value="{if $nodedata.latitude}{$nodedata.latitude}{else}{/if}"
												{tip trigger="latitude"}>
											{button type="link" icon="map" tip="Click to select GPS coordinates from map"
												onClick="return gpscoordschoosewin(document.nodeadd.elements['nodedata[longitude]'], document.nodeadd.elements['nodedata[latitude]']);"}
										</td>
									</tr>

									<tr>
										<td>
											{icon name="info"}
										</td>
										<td colspan="2">
											<textarea name="nodedata[info]" class="lms-ui-wysiwyg-editor"
												cols="50" rows="5"
												{tip text="Enter additional information (optional)"}
												{if isset($nodedata.wysiwyg.info)} data-wysiwyg="{$nodedata.wysiwyg.info}"{/if}
												>{$nodedata.info}</textarea>
										</td>
									</tr>

									<tr>
										<td>
											{if $nodedata.access}
												{$icon = "connected"}
											{else}
												{$icon = "disconnected"}
											{/if}
											{icon name=$icon id="statusico"}
										</td>
										<td colspan="2">
											<select size="1" name="nodedata[access]" id="status"
												{tip text="Select node status" trigger="access"}>
												<option value="1"{if $nodedata.access} selected{/if}
													>{trans("connected<!singular>")}</option>
												<option value="0"{if !$nodedata.access} selected{/if}
													>{trans("disconnected<!singular>")}</option>
											</select>
										</td>
									</tr>

									<tr>
										<td>
											{if $nodedata.warning}
												{$icon = "warnon"}
											{else}
												{$icon = "warnoff"}
											{/if}
											{icon name=$icon id="noticesico"}
										</td>
										<td colspan="2">
											<select size="1" name="nodedata[warning]" id="notices"
												{tip text="Set notice for node"}>
												<option value="1"{if $nodedata.warning} selected{/if}
													>{trans("enabled<!node>")}</option>
												<option value="0"{if !$nodedata.warning} selected{/if}
													>{trans("disabled<!node>")}</option>
											</select>
										</td>
									</tr>
									{/block}
								</table>
							</div>
						</td>
					</tr>
				{/block}
				</table>
			</td>
		</tr>
		<te>
			<td colspan="2" class="lms-ui-box-buttons">
				{block name="nodeaddbox-options"}
				{button type="submit" id="save-button" icon="save" label="Submit"}
				{button icon="search" label="Scan"
					href="?m=nodescan{if $customerinfo.id}&ownerid={$customerinfo.id}{/if}"}
				{button icon="cancel" label="Cancel"
					href="?m={if $customerinfo.id}customerinfo&id={$customerinfo.id}{else}nodelist{/if}"}
				<br>
				<label>
					<input type="checkbox" name="nodedata[reuse]" id="reuse" value="ON"
						{if $nodedata.reuse} checked{/if}>
					{trans("Display this form again, when this node is saved")}
				</label>
				{/block}
			</td>
		</te>
	</tbody>
</table>
</form>

<script>

	function first_free_address_received(ip) {
		var ipAddrElem = $('#ipaddr');
		if (typeof(ip) === 'string') {
			ipAddrElem.val(ip)
				.removeClass('lms-ui-warning')
				.removeAttr('data-tooltip')
				.attr({
					'data-manually-changed': '0',
					'title': null
				});
		} else {
			ipAddrElem.addClass('lms-ui-warning')
				.removeAttr('data-tooltip')
				.attr('title', $t("No free addresses in selected network!"));
		}
	}

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

		$('#get-first-free-address').click(function() {
			var netid = parseInt($('#netid').val());
			if (!netid) {
				return;
			}
			xajax_getFirstFreeAddress(netid);
		});

		{if ConfigHelper::checkConfig('nodes.auto_get_first_free_address')}
			$('#ipaddr').on('change keyup', function() {
				$(this).attr('data-manually-changed', '1');
			});

			$('#netid').change(function() {
				var netid = parseInt($(this).val());
				if ($('#ipaddr').attr('data-manually-changed') === '0') {
					xajax_getFirstFreeAddress(netid);
				}
			});
		{/if}

		$('#project').change(function() {
			$('#projectname').toggle(parseInt($(this).val()) == -1);
		});

		$('#notices').change(function() {
			var notices = parseInt($(this).val());
			$('#noticesico').toggleClass('lms-ui-icon-warnon', notices).toggleClass('lms-ui-icon-warnoff', !notices);
		});

		$('#status').change(function() {
			var status = parseInt($(this).val());
			$('#statusico').toggleClass('lms-ui-icon-connected', status).toggleClass('lms-ui-icon-disconnected', !status);
		});

		$('#genpasswd').click(function() {
			var length = {ConfigHelper::getConfig('nodes.password_length', ConfigHelper::getConfig('phpui.node_password_length', ConfigHelper::getConfig('phpui.nodepassword_length', '16')))};
			if (length > 32) {
				length = 32;
			}

			$('[name="nodedata[passwd]"]').val(
				generate_random_string(length, "{ConfigHelper::getConfig('nodes.password_allowed_characters', ConfigHelper::getConfig('phpui.node_password_allowed_characters', ConfigHelper::getConfig('phpui.nodepassword_allowed_characters', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')))|replace:'"':'\"'}")
			);
		});

		$('#set_gps').click(function() {
			if ($('#customer_addresses').val()) {
				xajax_get_gps_coordinates({
					address_id: $('#customer_addresses').val()
				}, '#latitude', '#longitude');
			}
		});

		$('#netdev').change(function() {
			if (parseInt($('#linktype').val()) == {$smarty.const.LINKTYPE_WIRELESS}) {
				$('#linktype,#radiosector,#linktechnology,#linkspeed').prop('disabled', true);
				xajax_getRadioSectors($(this).val(), $('#linktechnology').val());
			}
		});

		$('#linktype').change(function() {
			linktype = parseInt($(this).val());
			var select = $('#linktechnology');
			var selected = parseInt($('#netdev').val());
			var html = '<option value="0">{trans("— unknown —")}</option>';
			switch (linktype) {
				case 0:
				{foreach $_LINKTECHNOLOGIES[$smarty.const.LINKTYPE_WIRE] as $linktechnologyidx => $linktechnology}
					html += '<option value="{$linktechnologyidx}">{$linktechnology}</option>';
				{/foreach}
					break;
				case 1:
				{foreach $_LINKTECHNOLOGIES[$smarty.const.LINKTYPE_WIRELESS] as $linktechnologyidx => $linktechnology}
					html += '<option value="{$linktechnologyidx}">{$linktechnology}</option>';
				{/foreach}
					break;
				case 2:
				{foreach $_LINKTECHNOLOGIES[$smarty.const.LINKTYPE_FIBER] as $linktechnologyidx => $linktechnology}
					html += '<option value="{$linktechnologyidx}">{$linktechnology}</option>';
				{/foreach}
					break;
			}
			select.html(html);
			$('#radiosector').toggle(linktype == {$smarty.const.LINKTYPE_WIRELESS});

			if (linktype == {$smarty.const.LINKTYPE_WIRELESS} && selected) {
				$('#radiosector').prop('disabled', true);
				xajax_getRadioSectors(selected);
			}
		});

		$('#linktechnology').change(function() {
			technology = parseInt($(this).val());
			var linktype = $('#linktype').val();
			if (linktype != {$smarty.const.LINKTYPE_WIRELESS}) {
				return;
			}
			var netdev = $('#netdev').val();
			if (netdev !== undefined) {
				$('#radiosector').prop('disabled', true);
				xajax_getRadioSectors(netdev, technology);
			}
		});

		$('#wholenetwork').change(function() {
			var wholenetwork = $(this).prop('checked');
			$('[name="nodedata[ipaddr]"],[name="nodedata[ipaddr_pub]"]').closest('tr').toggle(!wholenetwork);
			$('[name="nodedata[ipaddr]"]').prop('required', !wholenetwork);
		}).change();
	});

	function radio_sectors_received(radiosectors) {
		var select = $('#radiosector');
		var oldValue = select.val();
		var html = '<option value="0">{trans("— none —")}</option>';
		if (radiosectors !== null) {
			$.each(radiosectors, function(index, elem) {
				html += '<option value="' + elem.id + '"' + (elem.id == oldValue ? ' selected' : '') + '>' + elem.name + '</option>';
			});
		}
		select.html(html);
		$('#linktype,#radiosector,#linktechnology,#linkspeed').prop('disabled', false);
	}

    /*!
     * \brief Update addresses list on customer input change.
     */
    function customer_change() {
        getCustomerAddresses($("#customerid_input").val(), function(addresses) {
            setAddressList('#customer_addresses', addresses);
        });
    }

	initAdvancedSelectsTest('#customer_addresses');

</script>
