(function (d, w) {
    if (!("Notification" in w)) {
        alert("Warning this web brower dont support desktop notifications !");
    }

    if (w.Notification && Notification.permission !== 'granted') {
        //Request user for notification permission
        Notification.requestPermission(function (status) {
            if (Notification.permission !== status) {
                Notification.permission = status;
            }
        });
    }

    function sendNotification(title, icon, body, link) {
        if (w.Notification && Notification.permission === 'granted') {
            var options = {
                icon: icon,
                body: body
            }

            var n = new Notification(title, options);

            n.onshow = function () {
                player.play();
                setTimeout(n.close.bind(n), 5000);
            }

            n.onclick = function () {
                player.pause();
                player.currentTime = 0;
                w.open(link);
                setTimeout(n.close.bind(n), 10);
            }

            n.onclose = function () {
                player.pause();
                player.currentTime = 0;
            }
        }
    }


    var socket = io.connect('http://localhost:8080');
    var link;

    socket.on('available', function (message, ref) {
        link = 'https://www.kimsufi.com/fr/commande/kimsufi.xml?reference=' + ref;
        sendNotification('Information', 'https://cdn1.iconfinder.com/data/icons/appicns/513/appicns_Chrome.png', message, link);
        link = '';
    })

    var button = d.getElementById('submit');
    var ref = d.getElementById('ref');
    var stop = d.getElementById('stop');

    button.addEventListener('click', function () {
        socket.emit('start', ref.value);
        ref.value = '';
    })

    stop.addEventListener('click', function () {
        socket.emit('stop');
    })


})(document, window);