keyuser = localStorage.getItem('keyuser');

function registerntf(succes){
	if(!navigator.push){
		var notificationsrefresh = setInterval(function () {
           notifications();
       }, 4000);
	}
	var req = navigator.push.register()

	req.onsuccess = function(){
		var endpoint = req.result;
		localStorage.setItem('endpoint', endpoint);
		$.post('http://m2s.es/app/api/newfxosdevice.php', { url: endpoint, key: keyuser}, function(){
			console.log(endpoint);
			if(succes == 'login'){
				document.location.href='index.html';
			};
		})
	}

	req.onerror = function(){
		alert('Error getting a new endpoint');
	}
}

function unregisterntf(){
	var endpoint = localStorage.getItem('endpoint');
	navigator.push.unregister(endpoint);
	$.post('http://m2s.es/app/api/rmfxosdevice.php', {key: keyuser}, function(){
	   localStorage.clear();
	   document.location.href= 'index.html';
    })
}

navigator.mozSetMessageHandler('push', function(){
	var notificationsd = navigator.mozNotification;
    var n = notificationsd.createNotification('M2S', 'You have new notifications', 'http://m2s.es/app/img/icon-114.png');
    n.onclick = function() {
        var request = window.navigator.mozApps.getSelf();
		request.onsuccess = function(){
			if(request.result){
				request.result.launch();
				document.location.href= 'notifications.html';
			}else{
				document.location.href= 'notifications.html';
			}
		}
    }
    n.show();
    
    var request = window.navigator.mozApps.getSelf();
    request.onsuccess = function(){
	    if(request.result){}else{
			notifications();
		}
	}
})

navigator.mozSetMessageHandler('push-register', function(e) {
	var req = navigator.push.register();
    req.onsuccess = function(e) {
      var endpoint = req.result;
      localStorage.setItem('endpoint', endpoint);
      $.post('http://m2s.es/app/api/newfxosdevice.php', { url: endpoint, key: keyuser}, function(){
			console.log(endpoint);
	  })
    }
})