<?php
// Copyright 1999-2024. WebPros International GmbH. All rights reserved.
?>
<script type="text/javascript">
    //<![CDATA[
    Jsw.onReady(function () {
        var getServerId = function () {
            return parseInt(serverElement.value);
        };

        var serverElement = document.getElementById('<?= $this->serverControl->getId() ?>');
        var serverId = getServerId();

        var updateControlsState = function () {
            var newServerId = getServerId();
            if (newServerId === serverId) {
                return false;
            }
            Jsw.api.get(Jsw.prepareUrl('/database/get-user-prefix/dbServerId/' + newServerId))
                .then(function (result) {
                    if (result.redirect) {
                        Jsw.redirect(result.redirect);
                        return;
                    }
                    serverId = newServerId;
                    if (result.loginPrefix) {
                        var prefixElement = document.getElementById('<?= $this->element->getId() ?>').parentNode.querySelector('.field-prefix');
                        if (prefixElement) {
                            prefixElement.innerHTML = result.loginPrefix;
                        }
                    }
                });
        };

        Jsw.Observer.appendAndCall(updateControlsState, 'dbServer');
        // Temporary workaround for custom prototype's event '<?= $this->element->getId() ?>:update'
        document.getElementById('<?= $this->element->getId() ?>').addEventListener('dataavailable', updateControlsState);
    });
    //]]>
</script>
