{% load static otree %}

<script>
    $(function () {
        var loadingwindowtime = new Date(),
            unloadingwindowtime = new Date(),
            submittingformtime = new Date();

        var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
        var ws_path = ws_scheme + '://' + window.location.host + "/timetracker/{{ participant.code}}/{{page_name}}/{{page_index}}";

        function sendingEvent(event_type, timestamp, exittype=null) {
            var msg = JSON.stringify({
                'eventtype': event_type,
                'timestamp': timestamp,
                'exittype': exittype,
            });
            if (socket.readyState === WebSocket.OPEN) {
                socket.send(JSON.stringify(msg));
            }
            ;
        }

        $(window).on('beforeunload', function () {
            unloadingwindowtime = new Date().getTime();
            sendingEvent('exit', unloadingwindowtime, 1);
        });
        $('form#form').on('submit', function () {
            submittingformtime = new Date().getTime();
            sendingEvent('exit', submittingformtime, 0);


        });
        var socket = new ReconnectingWebSocket(ws_path);
        socket.onopen = function (event) {
            console.log('connected to oTree');
            loadingwindowtime = new Date().getTime();
            sendingEvent('enter', loadingwindowtime);
        };

    })
    ;
</script>

