summaryrefslogtreecommitdiff
path: root/static/js/lafargue.js
blob: 645d355d1b82a0a08d82768612e4fdd6139f21da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
jQuery(function($) {
    var notificationsp = false;

    if (WebSocket) {
        var websocket_base = $('head').attr('data-websocket-base');
        var open_socket = function() {
            var socket = new WebSocket(websocket_base + '/lafargue/events');
            socket.onmessage = function(event) {
                var message = JSON.parse(event.data);
                $('.lafargue-list').prepend(message.html);
                if (window.webkitNotifications && notificationsp) {
                    var notification = window.webkitNotifications.createNotification('', 'Lafargue', 'New message by ' + message.first_name);
                    notification.show();
                    notification.onclick = function() {
                        notification.cancel();
                    };
                }
            };
            var reconnect = function() {
                window.setTimeout(function() {
                    open_socket();
                    socket.close();
                }, 2000);
            };
            socket.onclose = reconnect;
        };
        open_socket();
    }

    var updateNotificationStatus = function() {
        var status = $('#notification-status');
        if (notificationsp) {
            status.removeClass('bad');
            status.addClass('good');
            status.html('Notifications are ON.');
        } else {
            status.addClass('bad');
            status.removeClass('good');
            status.html('Notifications are OFF.');
        }
    };

    var toggleNotifications = function() {
        if (!notificationsp) {
            if (!window.webkitNotifications.checkPermission() !== 0) {
                window.webkitNotifications.requestPermission(function() {
                    updateNotificationStatus();
                });
            }
            notificationsp = true;
        } else {
            notificationsp = false;
            updateNotificationStatus();
        }
    };

    if (window.webkitNotifications) {
        var notify_button = $('.notifications').append('<a href="#" class="notify"><div id="notification-status" class="notification bad">Notifications are OFF.</div></a>');
        notify_button.click(toggleNotifications);
        if (window.webkitNotifications.checkPermission() === 0) {
            notificationsp = true;
        }
        updateNotificationStatus();
    };
});