{% extends "otree/BaseExperiment.html" %}
{% load staticfiles %}

{% block internal_scripts %}
    {{ block.super }}
    <!-- this is an HTML file rather than JavaScript static file because context variables need to be passed to it -->
<script type="text/javascript">
$(document).ready(function () {


    var socket;
    // TODO: add to view
    var index_in_pages = {{ view.index_in_pages }};

    initWebSocket();

    function initWebSocket() {
        var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
        var ws_path = ws_scheme + '://' + window.location.host + "{{ view.socket_url|safe }}";

        socket = new ReconnectingWebSocket(ws_path);
        socket.onmessage = function(e) {
            console.log('Received redirect message', e.data);
            var data = JSON.parse(e.data);

            if (data.error) {
                $("#error-notice").show();
                return;
            }

            if (data.new_index_in_pages > index_in_pages) {
                window.location.href = '{{ view.redirect_url|safe }}';
            }
        };
        socket.onopen = function() {
            console.log('WebSocket connected');
        };
        socket.onclose = function() {
            console.log('WebSocket disconnected');
        }
    }


    {% if use_browser_bots %}
        {# submit the form instantly #}
        $('#form').submit();
    {% endif %}

});

</script>

{% endblock %}
