<style>

	#location-table {
		width: 30em;
	}

	.location-property-selection {
		width: 30em;
	}

	.lms-ui-popup .ui-dialog-content {
		overflow: visible;
	}

	#location-box-autosuggest {
		max-height: 30em;
		overflow-y: auto;
		z-index: 1;
	}

	#location-box-autosuggest .lms-ui-suggestion-item:not(:hover):nth-child(even):not(.selected) {
		background-color: #F4F0EC;
	}

	#location-box-autosuggest .lms-ui-suggestion-item .terc {
		font-size: 80%;
	}

	@media screen and (max-width: 800px) {
		#location-box-autosuggest .lms-ui-suggestion-list {
			overflow: initial;
		}
		#location-box-autosuggest .lms-ui-suggestion-description {
			display: none;
		}
	}

</style>

{if !empty($states)}
<div id="location-box-autosuggest" style="display: none;" class="lms-ui-popup"><ul></ul></div>

<form name="location-search" id="location-search" method="post" action="?m=chooselocation">
	<table id="searchtable" cellpadding="5">
		<tr>
			<td class="dark nobr">
				<i class="lms-ui-icon-home"></i>
				<input type="text" name="searchcity" value="" size="40"
					placeholder="{trans('Enter city name')}" id="location-name"
					class="lms-ui-quick-search-input">
			</td>
		</tr>
	</table>
</form>

<script>

	new AutoSuggest({
		form: '#location-search',
		elem: 'form[name="location-search"] [name="searchcity"]',
		uri: '?m=chooselocation&ajax=1&mode=city&what=',
		autosubmit: 0,
		suggestionContainer: '#location-box-autosuggest',
		suggestMaxLength: 0,
		autoSubmitForm: false,
		onSubmit: function(data) {
			if (data.hasOwnProperty('action')) {
				search_update(data.action.cityid, data.action.districtid, data.action.stateid);
			}
		},
		onAjax: function(uri) {
			var stateid = parseInt($('#state_sel').val());
			var districtid = parseInt($('#district_sel').val());
			return uri + (stateid ? '&stateid=' + stateid : '') + (districtid ? '&districtid=' + districtid : '');
		}
	});

</script>
{/if}

<table id="location-table" cellpadding="3"
	{if !empty($data.allow_empty_streets)} data-allow-empty-streets="true"{/if}
	{if !empty($data.allow_empty_building_numbers)} data-allow-empty-building-numbers="true"{/if}>
	<colgroup>
		<col style="width: 1%;">
		<col style="width: 99%;">
	</colgroup>
{if empty($states)}
	<tr>
		<td colspan="2" class="text-center">
			<strong>{trans("Location database is empty.")}</strong>
		</td>
	</tr>
{else}
	<tr id="state">
		<td>{trans("State")}:</td>
		<td>
			<select id="state_sel" class="location-property-selection" name="state" {tip text="Select state"}>
				{if empty($data.stateid)}
					<option value="0"></option>
				{/if}
				{foreach $states as $item}
					<option value="{$item.id}">{$item.name}</option>
				{/foreach}
			</select>
		</td>
	</tr>
	<tr id="district"{if empty($districts)} style="display:none"{/if}>
		<td>{trans("District")}:</td>
		<td>
			<select id="district_sel" class="location-property-selection" name="district" {tip text="Select district"}>
				{if empty($data.districtid)}
					<option value="0"></option>
				{/if}
				{foreach $districts as $item}
					<option value="{$item.id}">{$item.name}</option>
				{/foreach}
			</select>
		</td>
	</tr>
	<tr id="city"{if empty($cities)} style="display:none"{/if}>
		<td>{trans("City")}:</td>
		<td>
			<select id="city_sel" name="city" class="location-property-selection" {tip text="Select city"}>
				{if empty($data.cityid)}
					<option value="0"></option>
				{/if}
				{foreach $cities as $item}
					<option value="{$item.id}" data-terc="{$item.terc}" data-simc="{$item.simc}">{$item.name}</option>
				{/foreach}
			</select>
		</td>
	</tr>
	<tr id="street"{if empty($streets)} style="display:none"{/if}>
		<td>{trans("Street")}:</td>
		<td>
			<select id="street_sel" name="street" class="location-property-selection" {tip text="Select street"}>
				{if !empty($data.allow_empty_streets)}
					<option value="">{trans("<!street-name>— none —")}</option>
				{/if}
				{foreach $streets as $street}
					<option value="{$street.id}"
						data-street-type="{$street.typename}"
						data-street-name-1="{$street.name1|escape}"
						data-ulic="{$street.ulic}"
						{if $street.name2} data-street-name-2="{$street.name2|escape}"{/if}
					>{$street.name}</option>
				{/foreach}
			</select>
		</td>
	</tr>
	<tr id="house"{if empty($data.streetid) && empty($data.cityid)} style="display:none"{/if}>
		<td class="nobr">{trans("House No.")}:</td>
		<td>
			<input type="text" size="8" maxlength="8" id="house_input" name="house" value="" {tip text="Enter house number"}>
		</td>
	</tr>
	<tr id="flat"{if empty($data.streetid) && empty($data.cityid)} style="display:none"{/if}>
		<td class="nobr">{trans("Flat No.")}:</td>
		<td>
			<input type="text" size="8" maxlength="8" id="flat_input" name="flat" value="" {tip text="Enter flat number"}>
		</td>
	</tr>

	<tr>
		<td colspan="2" class="text-right nobr">
			{button icon="save" label="Save" onclick="javascript:submit_location()"}
		</td>
	</tr>
{/if}
</table>

<script>

function select_location(name, value)
{
	$.ajax({
		url: '?m=chooselocation&ajax=1&api=1',
		method: 'GET',
		dataType: 'json',
		data: {
			what: name,
			id: value
		},
		success: function(data) {
			$.each(data, function(index, value) {
				update_selection(value.type, value.data, value.selected);
			});
		}
	});
}


/*!
 * \brief Update input visibility on change value.
 */
$( "#state_sel, #district_sel, #city_sel" ).change( function() {
    var name = $(this).attr( 'name' );

    switch ( name ) {
         case 'state':
             $( '#district' ).hide();

         case 'district':
             $( '#city' ).hide();

         default:
             $( '#street, #house, #flat' ).hide();
    }

    if ( $(this).val() != 0 ) {
		select_location( name, $(this).val() );
    }
});

function update_selection(type, data, selected) {
	var elem = $('#' + type);
	var select = $('#' + type + '_sel');
	var options = '';


	if (type == 'street') {
		options += '<option value="">{trans("<!street-name>— none —")}</option>';
	} else {
		options += '<option value="0"></option>';
	}

	$.each(data, function (index, value) {
		if (type == 'street' && value.name.length) {
			options += '<option value="' + value.id + '" data-street-type="' + value.typename + '" data-street-name-1="'
					+ value.name1 + '"' + (value.name2 ? ' data-street-name-2="' + value.name2 + '"' : '') + '>' +
					value.name + '</option>';
		} else {
			options += '<option value="' + value.id + '">' + value.name + '</option>';
		}
	});

	select.html(options);
	if (data.length) {
		elem.show();
	}

	select.val(selected ? selected : 0).focus();

	if (type == 'street') {
		initAdvancedSelectsTest(select);
		$('#house,#flat').show();

		if (!data.length) {
			$('#house_input').focus().select();
		}
	}
}

function search_update(cityid, districtid, stateid) {
    $( '#state_sel' ).val( stateid );
    $( '#district,#city,#street,#house,#flat' ).hide();

    select_location('', cityid + ':' + districtid + ':' + stateid);
}

function submit_location() {
	var state  = $('#state_sel');
    var city   = $('#city_sel');
    var street = $('#street_sel');
    var house  = $('#house_input');
    var flat   = $('#flat_input' );
    var cr     = $('#city');
    var tmp, input_str;
	var locationTable = $('#location-table');
	var allowEmptyStreets = locationTable.is('[data-allow-empty-streets]');
	var allowEmptyBuildingNumbers = locationTable.is('[data-allow-empty-building-numbers]');

    if (!cr.is(':visible') || !city.val()) {
		window.parent.alertDialog($t("City has not been selected!"));
		return;
    }

    if (!allowEmptyBuildingNumbers && !house.val().length) {
		window.parent.alertDialog($t("House number is required!"));
		return;
    }

    if (house.val().length > 8) {
		window.parent.alertDialog($t("House number is too long (max. 8 characters)!"));
        return;
    }

    if (flat.val().length > 8) {
		window.parent.alertDialog($t("Flat number is too long (max. 8 characters)!"));
		return;
    }

    // SET CITY
    input_str = city.val() ? city.find('option:selected').text() : '';

	var city_option = $('option:selected', city);
    if ( input_str && /^([^(]+)/.test(input_str) )  {
        tmp = RegExp.$1.replace(/\s+$/, '');

        location_box.find( "input[data-address='city']"        ).val(tmp);
        location_box.find( "input[data-address='city-hidden']" ).val(city_option.val());
		location_box.find( "input[data-address='terc']" ).val(city_option.attr('data-terc'));
        location_box.find( "input[data-address='simc']" ).val(city_option.attr('data-simc'));
        // automatically preselect 'Poland' country when we submit territized location
        location_box.find('select[data-address="country"]').find('option[data-ccode="pl_PL"]').prop("selected", true);
    }

    // SET STREET
    var street_option = $('option:selected', street);
    if (parseInt(street_option.val())) {
		var terytStreetAddressFormat = '{ConfigHelper::getConfig('phpui.teryt_street_address_format', '%type% %street2% %street1%')}';
		var streetParts = {};

		streetParts.type = street_option.attr('data-street-type');
		streetParts.street1 = street_option.attr('data-street-name-1');
		streetParts.street2 = typeof(street_option.attr('data-street-name-2')) !== 'undefined' ? street_option.attr('data-street-name-2') : '';
		if (streetParts.type.match(/^rynek$/i) &&
			(streetParts.street1.match(/^rynek/i) || streetParts.street2.match(/^rynek/i))) {
			streetParts.type = '';
		} else if (!streetParts.street2.length && streetParts.street1.match(/^[0-9]+(\.|-go)?$/)) {
			streetParts.type = '';
		}

		{literal}
		var street = terytStreetAddressFormat.replace('%type%', streetParts.type)
			.replace('%street1%', streetParts.street1)
			.replace('%street2%', streetParts.street2)
			.replaceAll(/[ ]{2,}/g, ' ');
		{/literal}

		location_box.find( "input[data-address='street']"        ).val( street );
        location_box.find( "input[data-address='street-hidden']" ).val( street_option.val() );
		location_box.find( "input[data-address='ulic']" ).val( street_option.attr('data-ulic') );
    } else {
        location_box.find( "input[data-address='street']"        ).val( '' );
        location_box.find( "input[data-address='street-hidden']" ).val( '' );
    }

    // SET HOUSE AND FLAT NUMBER
    location_box.find( "input[data-address='house']" ).val(house.val().trim());
    location_box.find( "input[data-address='flat']"  ).val(flat.val());

    // SET LOCATION NAME
    //location_box.find( "input[data-address='location-name']" ).val( $( '#location-name' ).val() );

    // SET STATE
	var state_option = $('option:selected', state);
    location_box.find( "input[data-address='state']"        ).val(state_option.text());
    location_box.find( "input[data-address='state-hidden']" ).val(state_option.val());

    // UPDATE ADDRESS STRING
    parent.$( '#{$data.boxid}' ).find('input').first().trigger('input');

	$('#' + location_box.find('[data-dialog-id]').attr('data-dialog-id')).dialog('destroy').remove();
}

var location_box = $( "#{$data.boxid}", window.parent.document );

{if !empty($states)}
$( '#house_input' ).val( location_box.find( "input[data-address='house']" ).val() );
$( '#flat_input'  ).val( location_box.find( "input[data-address='flat']"  ).val() );

{/if}

// select city and street from selects
$( '#state_sel'     ).val( {$data.stateid} );
$( '#district_sel'  ).val( {$data.districtid} );
$( '#city_sel'      ).val( {$data.cityid} );
$( '#street_sel'    ).val( location_box.find( "input[data-address='street-hidden']" ).val() );
initAdvancedSelectsTest('#street_sel');

$('#location-search').submit(function(e) {
	e.preventDefault();
});

</script>
