;(function ($){
    if( ! ('serviceWorker' in navigator ) ) {
        return;
    }
    if( ! ('PushManager' in window ) ) {
        return;
    }

    var registerer;

    if( 'serviceWorker' in navigator ) {
        navigator.serviceWorker.register( academy_pro_notifications.swurl )
            .then(function (register){
                console.log(register);
                registerer = register;
        }, function (err){
            console.log(err);
        });
    }

    function enableNotification() {
        // request for notification permission if it is not granted
        Notification.requestPermission().then(function (permission) {
            // check is the permission is granted
            if (permission === 'granted') {
                sessionStorage.setItem( 'push', 'true' );
                // get the endpoint
                registerer.pushManager.subscribe({
                    userVisibleOnly: true,
                    applicationServerKey: academy_pro_notifications.publickey,
                }).then(function (subscription){
                    subscription = JSON.stringify(subscription);
                    subscription = JSON.parse( subscription );
                    var _data = {
                        action : academy_pro_notifications.action,
                        security : academy_pro_notifications.security,
                        endpoint : subscription.endpoint,
                        expirationTime : subscription.expirationTime,
                        p256dh : subscription.keys.p256dh,
                        auth : subscription.keys.auth,
                    };
                    jQuery.ajax({
                        type : "post",
                        dataType : "json",
                        url: academy_pro_notifications.ajaxurl,
                        data : _data,
                    })
                 });
            }
        });
    }

    if( Notification.permission === 'default' ) {
        enableNotification();
    }
})(jQuery);