var Guestcompass = Guestcompass || {};

Guestcompass.push = {}

Guestcompass.push.init = function()
{
	//dit is dus voor pushwoosh
	var pushNotification = cordova.require("com.pushwoosh.plugins.pushwoosh.PushNotification");
 
	if (device.platform == 'android' || device.platform == 'Android')
	{
		//set push notifications handler
	    document.addEventListener('push-notification', function(event) {
	        var title = event.notification.title;
	        var userData = event.notification.userdata;
	                                 
	        if(typeof(userData) != "undefined") {
	            console.warn('user data: ' + JSON.stringify(userData));
	        }
	                                     
	        Guestcompass.push.render(title);
	    });
	 
	    //initialize Pushwoosh with projectid: "GOOGLE_PROJECT_NUMBER", pw_appid : "PUSHWOOSH_APP_ID". This will trigger all pending push notifications on start.
	    pushNotification.onDeviceReady({ projectid: iGoogleProjectNr, pw_appid : pushWooshId });
	
	}else{
	    //set push notification callback before we initialize the plugin
	    document.addEventListener('push-notification', function(event) {
	        //get the notification payload
	        var notification = event.notification;

	        //display alert to the user for example
	        Guestcompass.push.render(notification.aps.alert);
	                               
	        //clear the app badge
	        pushNotification.setApplicationIconBadgeNumber(0);
	    });
	 
	    //initialize the plugin
	    pushNotification.onDeviceReady({pw_appid: pushWooshId});
	    //register for pushes
	}    
	
    //register for pushes
    pushNotification.registerDevice(
        function(status) {
            var pushToken = status;
            console.warn('push token: ' + pushToken);
        },
        function(status) {
            console.warn(JSON.stringify(['failed to register ', status]));
        }
    );

    //reset badges on app start
    pushNotification.setApplicationIconBadgeNumber(0);
	

/* DIT IS VOOR URBAN AIRSHIP 
	// Register for any urban airship events
	document.addEventListener("urbanairship.registration", function (event) {
	    if (event.error) {
	        console.log('there was an error registering for push notifications');
	    } else {
	        console.log("Registered with ID: " + event.pushID);
	    } 
	}, false)

	document.addEventListener("urbanairship.push", function (event) {
	    console.log("Incoming push: " + event.message)
	}, false)

	// Set tags on a device, that you can push to
	// https://docs.urbanairship.com/display/DOCS/Server%3A+Tag+API
	PushNotification.setTags(["loves_cats", "shops_for_games"], function () {
	    PushNotification.getTags(function (obj) {
	        obj.tags.forEach(function (tag) {
	            console.log("Tag: " + tag);
	        });
	    });
	});

	// Set an alias, this lets you tie a device to a user in your system
	// https://docs.urbanairship.com/display/DOCS/Server%3A+iOS+Push+API#ServeriOSPushAPI-Alias
	PushNotification.setAlias("awesomeuser22", function () {
	    PushNotification.getAlias(function (alias) {
	        console.log("The user formerly known as " + alias)
	    });
	});

	// Check if push is enabled
	PushNotification.isPushEnabled(function (enabled) {
	    if (enabled) {
	        console.log("Push is enabled! Fire away!");
	    }
	})
*/
	
	/*
	try 
	{ 
		pushNotification = window.plugins.pushNotification;
		if (device.platform == 'android' || device.platform == 'Android')
		{
			pushNotification.register(Guestcompass.push.successHandler, Guestcompass.push.errorHandler, {"senderID": iGoogleProjectNr,"ecb":"Guestcompass.push.onNotificationGCM"});		// required!
		}
		else
		{
			pushNotification.register(Guestcompass.push.saveIos, Guestcompass.push.errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"Guestcompass.push.onNotificationAPN"});	// required!
		}
	}
	catch(err) 
	{ 
		txt="There was an error on this page.\n\n"; 
		txt+="Error description: " + err.message + "\n\n"; 
		// alert(txt); 
	}
	*/
}

Guestcompass.push.saveIos = function(result)
{
	// zolang de locatie nog niet terug is moet hij niks doen 
	/*	


	if(Guestcompass.sCMSLocation == undefined ){
		setTimeout(function()
		{
			//alert('call save ios');
			Guestcompass.push.saveIos(result);
			
		}, 500);
	}else{

		window.localStorage.setItem("sPushDevice", result);

		$.ajax({
		url: Guestcompass.sCMSLocation + "push/save-ios/device/"+ result +'/hotel/' + iHotelID + '/lang/'+ Guestcompass.sCurrentLanguage + '/tablet/' + Guestcompass.tablet
		}).done(function( data ) {
			window.localStorage.setItem("sPushDeviceId", data);
		});
	}
	*/
}

Guestcompass.push.saveAndroid = function(e)
{	
	/*
	// zolang de locatie nog niet terug is moet hij niks doen 
	if(Guestcompass.sCMSLocation == undefined ){
		setTimeout(function()
		{
			//alert('call save android');
			Guestcompass.push.saveAndroid(e);
			
		}, 1000);
	}else{

		//alert(Guestcompass.sCMSLocation + "push/save-android/device/"+ e.regid +'/hotel/' + iHotelID +'/lang/'+ Guestcompass.sCurrentLanguage +'/tablet/' + Guestcompass.tablet);
		window.localStorage.setItem("sPushDevice", e.regid);

		$.ajax({
		url: Guestcompass.sCMSLocation + "push/save-android/device/"+ e.regid +'/hotel/' + iHotelID +'/lang/'+ Guestcompass.sCurrentLanguage +'/tablet/' + Guestcompass.tablet
		}).done(function( data ) {
			window.localStorage.setItem("sPushDeviceId", data);
		});
	}
	*/
}

Guestcompass.push.render = function(mssg)
{	

	$('body').lightbox({
		'loadData' : '\
		    		<div class="mssg-container">\
		    			<div class="mssg-header">Bericht</div>\
		    			<div class="mssg-content">\
		    				'+mssg+'\
		    			</div>\
		    		</div>\
		    		<div class="close">X</div>' 
	});

	// check of er een push id page is gezet
	// als de app open staat is de push pagina bekend zo niet dan later toch nog maar een keer kijken of we er 1 hebben
	// dit omdat bij het drukken op een push bericht gelijk getoond wordt 
/*
	if(Guestcompass.push.page == undefined ){
		setTimeout(function()
		{
			if(Guestcompass.push.page != undefined && Guestcompass.push.page != 0 ){
				setButton();
			}
		}, 1000);
	}else{
		if(Guestcompass.push.page != 0 ){
			setButton();
		}
	}
/*
	function setButton(){

		$('.lightboxMainContainer .button-container').html('<a href="#page'+Guestcompass.push.page+'" class="close button" > '+Guestcompass.aTranslations['bekijken']+' </a>');
		$('body').lightbox.redraw();

		$('.lightboxMainContainer a').click(function(e){

			var sHref = $(this).attr("href");
			$('body').lightbox.close();		

			if(sHref.substring(0, 5) == "#page"){

				e.preventDefault();
				var iClickedPage = sHref.substring(5);
				Guestcompass.loadNewPage(iClickedPage);
				return false;
			}
		});	
	}
*/	
}

// handle APNS notifications for iOS
Guestcompass.push.onNotificationAPN = function(e)
{
	/*
	// als de app in de voor grond draait moet er iets naders gebrueren 
	if (e.alert) {
		if(Guestcompass.active){
			
			Guestcompass.push.render(e.alert);	
			//append('<div>' + e.alert + ' </div>');
		}else{
			alert(e.alert);
		}
		// $("#app-status-ul")
	}
		
	if (e.sound) {
		var snd = new Media(e.sound);
		snd.play();
	}
	
	if (e.badge) {
		pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
	}
	*/
}


// handle GCM notifications for Android
Guestcompass.push.onNotificationGCM = function(e)
{	
	/*
	switch( e.event )
	{
		case 'registered':
		if ( e.regid.length > 0 )
		{
			//$("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>");
			// Your GCM push server needs to know the regID before it can push to this device
			// here is where you might want to send it the regID for later use.
			Guestcompass.push.saveAndroid(e);
		}
		break;
		
		case 'message':
			// hier zou je dingen in de app kunnen doen 
			// if this flag is set, this notification happened while we were in the foreground.
			// you might want to play a sound to get the user's attention, throw up a dialog, etc.

			if (e.foreground)
			{
				//$("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</li>');
				Guestcompass.push.render(e.payload.message);
				// if the notification contains a soundname, play it.
				//var my_media = new Media("/android_asset/www/"+e.soundname);
				//my_media.play();
			}
			else
			{	// otherwise we were launched because the user touched a notification in the notification tray.
				if (e.coldstart){
					Guestcompass.push.render(e.payload.message);
					//alert(e.payload.message+'coldstart');	
					//$("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>');
				}else{
				// als ik hier iets doe crasht de app geen idee waarom
					Guestcompass.push.render(e.payload.message);
				//	alert(e.payload.message+'not running');
				}
			}
					
			//	alert(e.payload.msgcnt);
		break;
		
		case 'error':
			//$("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>');
			//alert('Error' + e.msg);
		break;
		
		default:
			//$("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');
				//alert('Unknown, an event was received and we do not know what it is');
		break;
	}
	*/
}


/* deze wordt nu niet meer gebruikt
function tokenHandler(result)
{
	Guestcompass.push.saveIos(result);
}
*/
Guestcompass.push.successHandler = function(result)
{
	// dit moet ook maar naar de pushe class
	//alert( result + '<--success handler' );
}

Guestcompass.push.errorHandler = function(error)
{
	// dit moet ook maar naar de pushe class
	//alert( error + '<--error handler');
}
