<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator="fragments/base"
      th:with="lang=${#locale.language}" th:lang="${lang}">
<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../webcontent/css/css_country.css" th:href="@{/static/css/css_country.css}"/>
    <script type="text/javascript" src="../webcontent/js/jquery-3.6.0.js"
            th:attr="src=@{/static/js/jquery-3.6.0.min.js}"></script>
    <title th:text="#{gui.residency.title}">Österreichischer Wohnsitz</title>
    <script type="text/javascript" th:inline="javascript">
        $(document).ready(function () {
            $("#textResult").hide();
            $("#tableResult").hide();
            $("#loading").hide();
            $.ajaxSetup({
                beforeSend: function () {
                    $("#loading").show();
                },
                complete: function () {
                    $("#loading").hide();
                }
            });
            $("#inputForm input[type='text']").keyup(function (event) {
                if (event.keyCode === 13) {
                    $("#buttonSearch").click();
                }
            });
        });

        function search() {
            let updatedText = /*[[#{gui.residency.updated}]]*/ 'Updated text';
            let errorText = /*[[#{gui.residency.error}]]*/ 'Error';
            let foundText = /*[[#{gui.residency.found}]]*/ 'Found {0}';
            let uniqueText = /*[[#{gui.residency.unique}]]*/ 'Unique';
            let invalidInputText = /*[[#{gui.residency.header.inputinvalid}]]*/ 'Invalid';
            if (!$("#inputForm #inputMunicipality").val().trim() && !$("#inputForm #inputPostleitzahl").val().trim() &&
                !$("#inputForm #inputVillage").val().trim()) {
                $("#textResult").show().text(invalidInputText);
                return;
            }
            $.ajax({
                type: "POST",
                url: "[(${wizardEndpoint})]",
                data: $("#inputForm").serialize()
            }).done(function (data, textStatus, jqXHR) {
                if (data["resultCount"] === 1) {
                    $("#textResult").show().text(uniqueText);
                    $("#tableResult tbody").empty();
                    $("#tableResult").hide();
                    $("#inputForm #inputPostleitzahl").val(data["results"][0]["postleitzahl"]);
                    $("#inputForm #inputMunicipality").val(data["results"][0]["municipality"]);
                    $("#inputForm #inputVillage").val(data["results"][0]["village"]);
                    $("#inputForm #inputStreet").val(data["results"][0]["street"]);
                    $("#inputForm #inputNumber").val(data["results"][0]["number"]);
                    return;
                }
                $("#textResult").show().text(foundText.replace("{0}", data["resultCount"]));
                $("#tableResult").show();
                $("#tableResult tbody").empty();
                $.each(data.results, function (i, output) {
                    $("#tableResult tbody")
                        .append($("<tr>")
                            .append($("<td>").text(output["postleitzahl"] !== null ? output["postleitzahl"] : "").css("text-align", "right"))
                            .append($("<td>").text(output["municipality"] !== null ? output["municipality"] : ""))
                            .append($("<td>").text(output["village"] !== null ? output["village"] : ""))
                            .append($("<td>").text(output["street"] !== null ? output["street"] : ""))
                            .append($("<td>").text(output["number"] !== null ? output["number"] : "").css("text-align", "right"))
                            .css("cursor", "pointer").click(function () {
                                $("#inputForm #inputPostleitzahl").val($(this).children("td:nth-child(1)").text());
                                $("#inputForm #inputMunicipality").val($(this).children("td:nth-child(2)").text());
                                $("#inputForm #inputVillage").val($(this).children("td:nth-child(3)").text());
                                $("#inputForm #inputStreet").val($(this).children("td:nth-child(4)").text());
                                $("#inputForm #inputNumber").val($(this).children("td:nth-child(5)").text());
                                $("#textResult").show().text(updatedText);
                                search();
                            })
                        );
                })
                if (data.results.length === 0) {
                    $("#tableResult").hide();
                }
            }).fail(function (jqXHR, textStatus, errorThrown) {
                $("#textResult").show().text(errorText);
            })
        }

        function clearInput() {
            $("#inputForm #inputPostleitzahl").val("");
            $("#inputForm #inputMunicipality").val("");
            $("#inputForm #inputVillage").val("");
            $("#inputForm #inputStreet").val("");
            $("#inputForm #inputNumber").val("");
            $("#textResult").hide();
            $("#tableResult").hide();
        }
    </script>
    <style>
        #residency label {
            width: 10em;
            display: inline-block;
            margin-bottom: 0.5em;
        }

        #residency input {
            width: 15em;
            display: inline-block;
            margin-bottom: 0.5em;
        }

        #result {
            margin-bottom: 4em;
        }

        button {
            padding: 0.5em;
            margin: 0.5em;
            width: 12em;
        }

        .block {
            width: 80%;
            justify-content: left;
        }

        #tableResult td, #tableResult th {
            padding: 1em 0.5em;
        }

        #tableResult a {
            text-decoration: underline;
        }

        #tableResult {
            border-collapse: collapse;
        }

        #tableResult tr {
            border-bottom: 1px solid black;
        }
    </style>
</head>

<body>
<div class="header container">
    <div class="titlebar">
        <div>
            <a href="https://www.bmi.gv.at/" target="_blank" title="Home">
                <img class="toplogo img-responsive" src="/static/BMI.png" alt="Logo BMI"
                     th:attr="alt=#{gui.countryselection.logo.bmi.alt}">
                <h1 class="hidden" th:text="#{gui.countryselection.header1}"> Bundesministerium für Inneres </h1>
            </a>
        </div>
        <ul class="nav_oben">
            <li>
                <div class="languageselection" th:include="language_selection :: selectlanguage">
                    LanguageSelectionBlock
                </div>
            </li>
            &nbsp; &nbsp;
            <li>
                <a href="https://www.bmi.gv.at/" target="_blank" th:text="#{gui.countryselection.link.bmi}">Startseite
                    BMI </a>
            </li>
        </ul>
    </div>
</div>
<div class="content">
    <div class="subtitle">
        <h1 th:text="#{gui.countryselection.header2}"> Zentraler eIDAS Knoten der Republik Österreich </h1>
        <h2 th:text="#{gui.countryselection.header3}"> Betrieben durch das Bundesministerium für Inneres </h2>
    </div>

    <div class="mainDescription">
      <h3 th:text="#{gui.residency.header.selection}">Search your Austrian Residency </h3>

      <p th:text="#{gui.residency.info.first}"> Info text for matching by address </p>
      <p th:text="#{gui.residency.info.second}"> HowTo search by address </p>
    </div>

    <div id="matchingError"
			   th:if="${advancedMatchingFailed != null} and ${advancedMatchingFailed}">
		      <p   th:if="${advancedMatchingFailedReason != null}"
			         th:text="#{${advancedMatchingFailedReason}}">Detailed
          </p>
		      <p   th:unless="${advancedMatchingFailedReason != null}"
			         th:text="#{module.eidasauth.matching.29}">Generell
          </p>
    </div>

    <div id="residency">
        <form id="inputForm" method="post" action="$contextPath$submitEndpoint"
              th:attr="action=@{${submitEndpoint}}">
            <div><p th:text="#{gui.residency.header.help}">Please enter a postcode, municipality or village first</p>
            </div>
            <div>
                <label for="inputPostleitzahl" th:text="#{gui.residency.input.postleitzahl}">Postleitzahl</label>
                <input type="text" id="inputPostleitzahl" name="postleitzahl" value=""/>
            </div>
            <div>
                <label for="inputMunicipality" th:text="#{gui.residency.input.municipality}">Municipality</label>
                <input type="text" id="inputMunicipality" name="municipality" value=""/>
            </div>
            <div>
                <label for="inputVillage" th:text="#{gui.residency.input.village}">Village</label>
                <input type="text" id="inputVillage" name="village" value=""/>
            </div>
            <div>
                <label for="inputStreet" th:text="#{gui.residency.input.street}">Street</label>
                <input type="text" id="inputStreet" name="street" value=""/>
            </div>
            <div>
                <label for="inputNumber" th:text="#{gui.residency.input.number}">Number</label>
                <input type="text" id="inputNumber" name="number" value=""/>
            </div>
            <div class="block">
                <button type="button" id="buttonSearch" onclick="search()" th:text="#{gui.residency.search}">
                    Search
                </button>
                <button type="button" id="buttonClear" onclick="clearInput()" th:text="#{gui.residency.clear}">
                    Clear
                </button>

                <form method="post" action="$contextPath$submitEndpoint" th:attr="action=@{${submitEndpoint}}">
                    <button type="submit" id="buttonProceed" value="Proceed" th:text="#{gui.residency.proceed}">Proceed</button>
                    <input type="hidden" name="pendingid" value="$pendingid" th:attr="value=${pendingid}">
                </form>
            </div>
            <input type="hidden" name="pendingid" value="$pendingid" th:attr="value=${pendingid}"/>
        </form>
    </div>


    <div id="backOrReturn" class="block">

      <p th:text="#{gui.residency.info.third}"> Alternativ infos and back </p>
      <br>
      <form class="block" method="post" action="$contextPath$submitEndpoint" th:attr="action=@{${submitEndpoint}}">
          <button type="submit" value="Back" th:text="#{gui.residency.back}">Back</button>
          <input type="hidden" name="noResidence" value="true">
          <input type="hidden" name="pendingid" value="$pendingid" th:attr="value=${pendingid}">
      </form>

      <!--form class="block" method="post" action="$contextPath$submitEndpoint" th:attr="action=@{${submitEndpoint}}">
          <button type="submit" value="Abbrechen/Cancel" th:text="#{gui.residency.cancel}">Cancel</button>
          <input type="hidden" name="stopAuthProcess" value="true">
          <input type="hidden" name="pendingid" value="$pendingid" th:attr="value=${pendingid}">
      </form-->

    </div>

    <div>
        <img id="loading" src="../webcontent/img/ajax-loader.gif"
             th:attr="src=@{/static/img/ajax-loader.gif}" style="display: none"/>
    </div>

    <div id="result">
        <div>
            <p><span id="textResult" style="display: none"></span></p>
        </div>
        <table id="tableResult" style="display: none">
            <thead>
            <tr>
                <th th:text="#{gui.residency.input.postleitzahl}" style="text-align: right">Postcode</th>
                <th th:text="#{gui.residency.input.municipality}">Municipality</th>
                <th th:text="#{gui.residency.input.village}">Village</th>
                <th th:text="#{gui.residency.input.street}">Street</th>
                <th th:text="#{gui.residency.input.number}" style="text-align: right">Number</th>
            </tr>
            </thead>
            <tbody>

            </tbody>
        </table>
    </div>

</div>
<footer>
    <div class="copyright">&copy; BUNDESMINISTERIUM FÜR INNERES</div>
    <div></div>
</footer>
</body>
</html>