function userTitleCommand() {
	//Aggiorno tutto l'header
	jQuery.ajax({
		  type: 'POST',
		  url: "/wazzamba-web/portal/userTitle",
		  success: function(data) {
		 		
		 		var tot = data.getElementsByTagName('MILES_TRESHOLD')[0].childNodes[0].nodeValue;
				var act = data.getElementsByTagName('CURRENT_MILES')[0].childNodes[0].nodeValue;
	
				document.getElementById("userTitle").innerHTML = data.getElementsByTagName('CURRENT_TITLE')[0].childNodes[0].nodeValue;
				document.getElementById("upTo").innerHTML = (tot - act) + ' Miles to level up';
				jQuery("#userTitle").change(); //trigger the event
				if (act!=0){				
					myJsProgressBarHandler.setPercentage('progressBar', calcPercentageProgressBar(act, tot));
				}
				
				var usrMiles = data.getElementsByTagName('MILES')[0].childNodes[0].nodeValue;
				var usrCoins = data.getElementsByTagName('COINS')[0].childNodes[0].nodeValue;
				
				updateHeaderMiles(usrMiles);
				updateHeaderCoins(usrCoins);
				
		  },
		  error: function(data) {
				alert("It seems we have problem upgrading your title, please wait and retry.")
		  }
	});
}

function changeDataCommand(cmdName, params) {
	if (cmdName == "removeFBAccount") {
		jQuery.ajax({
		  type: 'POST',
		  url: "/wazzamba-web/apispring/changeData",
		  data: {cmd: cmdName},
		  success: function(data) {
		  		window.location.href=window.location.href;
		  },
		  error: function(data) {}
		});	
	} else {
		if (cmdName == "changeMail") {
			jQuery.ajax({
                        type: 'POST',
                        url: "/wazzamba-web/apispring/changeData",
                        data: {
                            cmd: cmdName,
                            newMail: params.newMail,
                            receiveUpdate: params.receiveUpdate
                        },
                        success: function(data){
                  			alert("Your email settings have been successfully changed.\n\nRemember when you change your email address you'll receive a message to your new address, and you can use it to login.");
                  			//openModalDialog("/docroot/pages/changeEmailOK.html")
                        },
                        error: function(data){
                            alert("There are some problems with your new mail, maybe it's not valid or duplicate, please try with another one.");
                            //openModalDialog("/docroot/pages/changeEmailKO.html")
                        }
                    });
		} else {
			if (cmdName=="verifyMail") {
				jQuery.ajax({
                        type: 'POST',
                        url: "/wazzamba-web/apispring/changeData",
                        data: {
                            cmd: cmdName
                        },
                        success: function(data){
                        	alert("A verification email has been sent to you.\nPlease follow the instructions in this email to activate your email address.\n\nIf the email does not turn up in your inbox, please make sure it was not flagged as spam.");
                            //openModalDialog('/docroot/pages/resendVerificationEmailOK.html');
                        },
                        error: function(data){
                        	alert("It seems we have problem sending you the verification mail, please wait and retry.");
                            //openModalDialog('/docroot/pages/resendVerificationEmailKO.html')
                        }
                    });
			} else {
				if (cmdName=="changePwd") {
					jQuery.ajax({
                        type: 'POST',
                        url: "/wazzamba-web/apispring/changeData",
                        data: {
                            cmd: cmdName,
                            newPwd: params.newPassword
                        },
                        success: function(data){
                        	alert("From now on you can use your new password to enter Wazzamba.");
                            //openModalDialog('/docroot/pages/passwordChangeOK.html');
                        },
                        error: function(data){
                        	alert("It seems we have problem changing your password, please wait and retry.");
                            //openModalDialog('/docroot/pages/passwordChangeKO.html');
                        }
                    });
				} else {
					if (cmdName=="changeNick") {
						jQuery.ajax({
	                        type: 'POST',
	                        url: "/wazzamba-web/apispring/changeData",
	                        data: {
	                            cmd: cmdName,
	                            newNick: params.newNick
	                        },
	                        success: function(data){
	                        	var result= data.getElementsByTagName('nickChanged')[0].getAttribute('result');
	                        	
	                        	if (result == 'true') {
	                        		alert("From now your new username is " + params.newNick + ".");
	                        		document.getElementById("nickname").innerHTML = "<span>" + params.newNick + "</span>";
	                        	} else {
	                        		alert(params.newNick + " is already in use by another user, so please choose another one.");
	                        	}
	                        },
	                        error: function(data){
	                        	alert("It seems we have problem changing your username, please wait and retry.");
	                        }
	                    });
					}
				}
			}
		}
	}	
}

function loadAuctionCommand() {
	jQuery.ajax({
		type: 'POST',
		url: "/wazzamba-web/apispring/loadAuction?auctionId=",
		success: function(data) {
			auctionId=data.auctionId;
			fillFields(data, false);        			 		
			
			return auctionId;								
		},
		error: function(data) {
			alert("It seems we have problem loading the grid, please wait and retry.")
		}
	});
}
function bidAuctionCommand(id, fee) {
	jQuery.ajax({
		type: 'POST',
		url: "/wazzamba-web/apispring/bidAuction?auctionId="+id+"&amount="+fee,
		success: function(data) {
			fillFields(data, true);
					 		
			//EFFETTO GRAFICO						
		},
		error: function(data) {
			alert("It seems we have problem doing the bid, please wait and retry.")
		}
	});
}
function powHintCommand(id) {
	jQuery.ajax({
		type: 'POST',
		url: "/wazzamba-web/apispring/powAuction?auctionId="+id,
		success: function(data) {
			fillFields(data, false); 
								 		
			//EFFETTO GRAFICO
											
		},
		error: function(data) {
			alert("It seems we have problem using powerup, please wait and retry.")
		}
	});
}

function gemCollectionsRedeemCommand(type, name) {
	jQuery.ajax({
		  type: 'POST',
		  url: "/wazzamba-web/portal/gemCollectionsRedeem?option="+type+"&collection="+name,
		  success: function(data) {
		 		if (name != "DIAMOND")
		 			var t=setTimeout("window.location.href=window.location.href;",500);
		 		else
		 			parent.document.location.href=parent.document.location.href;
		  },
		  error: function(data) {
				alert("It seems we have problem upgrading/redeeming your collection, please wait and retry.")
		  }
	});
}

function cancelSubscriptionCommand() {
	jQuery.ajax({
		  type: 'POST',
		  url: "/wazzamba-web/spring/cancelSubscriptionService",
		  success: function(data) {
		  		alert("Your subscription renewal has been cancelled.");
		  		window.location.href=window.location.href;
			  },
		  error: function(data) {
				alert("It seems we have problem cancelling your subscription, please wait and retry.")
			  }
	});
}

function buyBoostersSilentCommand() {
	jQuery.ajax({
            	type: 'POST',
                url: "/wazzamba-web/spring/buyBoostersSilent",
                data: {
                	productCode: "MILES_FIVE_30"
                },
                success: function(data) {

                     var balance=document.getElementById("headerCoins").innerHTML;
                     if(balance!=null && balance!="") {
                	 	document.getElementById("headerCoins").innerHTML = balance-10;
                	 }else{
                      //alert('balance nulla');
                    	 }
                
                     document.getElementById("activateButton").className = 'btn big disabled';
                     document.getElementById("activateButton").onclick = null;
                     document.getElementById("titleButton").innerHTML = 'Booster activated';
                     document.getElementById("subtitleButton").className = 'booster-countdown-long';
                     
                     sendGAEvent( "purchase", "sold", "Booster5")
					 jQuery(data).find("VALIDITY_END_REMAINING_MILLIS").each(function() {
						 
							var remainingTime= parseInt(jQuery(this).text());
							var currentMillis=new Date().getTime();
							var endMillis=currentMillis+remainingTime;
							var austDay=new Date(endMillis);
							
							
							jQuery('.booster-countdown-long').countdown({until: austDay, onExpiry: liftOff, layout: '<span class="left">Remaining Time:</span><ul><li>{mnn}.</li><li>{snn}</li></ul>'});	
					 		jQuery('.booster-countdown').countdown({until: austDay, onExpiry: liftOffHeader, layout: '<span><ul><li>{mnn}.</li><li>{snn}</li></ul></span><span style="color: #000;">mins</span>'});  
					 		jQuery('#booster').get(0).style.display = 'inline';
					 		
					 		jQuery('#activated-booster').get(0).style.display = 'inline';
					 		jQuery('#deactivated-booster').get(0).style.display = 'none';
					 		jQuery('#earned-gem').get(0).style.display = 'none';
					 		
					 		if (removeOverlay != null)
					 			removeOverlay();
					 });
                },
                error: function(data){
                	alert("error getting Booster");
                }
            }); 
}

// NOTIFICHE
function waitForMsgGlobal(notificationWindow, oldAppContextPath){   
    jQuery.ajax({
        type: "GET",
        url: "/wazzamba-web/spring/events?action=LIST",

        async: !notificationWindow, /* If set to non-async, browser shows page as "Loading.."*/
        cache: false,
        timeout:50000, /* Timeout in ms */

        success: function(data){ /* called when request to barge.php completes */
                        
            if (notificationWindow == true) {
	            jQuery.each(data, function(i, item) {
		        	if (item.type=="UNIQUE_INVALIDATED" || item.type=="WINNING_INVALIDATAED" || item.type=="NOW_WINNING") {
		        		var date = new Date(item.time);
		            	var stringDate = getDayInWeekShortLabel(date.getDay())+" "+getHoursAMPM(date.getHours(), date.getMinutes());
		        		
		        		jQuery('#sentence').append('<div><div style="background-color: #4da9d2;width: 25px;height: 25px;float:left;margin-top:1px;"><img src="'+oldAppContextPath+'/spring/avatarThumbService?cdSize=75_75&amp;userId='+item.userId+'" width="25" height="25" alt=""/></div><div style="float:left; padding-left: 5px; padding-top: 3px;"> '+item.nick+" - "+item.type+'</div><div style="float:right; padding-top: 3px;">'+stringDate+'</div>  <div style="clear:both;"><!-- non rimuovere --></div>  </div><div class="clear"><!-- COMMENT --></div></div>');
		        		
		        		deleteNotificationCommand(item.id);
		        	}
		        });
		    } else {
		    	var cont=0;
		    	var new_bids = new Array();
		    	
		    	jQuery.each(data, function(i, item) {
		        	if (item.type=="UNIQUE_INVALIDATED" || item.type=="WINNING_INVALIDATAED" || item.type=="NOW_WINNING")
		        		cont++;
		        	else
		        	 	if (item.type=="NEW_BID")
		        			new_bids.push(item);
		        });
		        
		        if (cont!=0)
	            	showNotifications(cont);
	            else
	            	hideNotifications();
	            
	            //GESTIONE DELLA LISTA NEL CASO DI NEW_BID DALLA PAGINA DELLE AUCTION
	            if (document.location.href.search("portal/auction") != -1  && new_bids.length!=0) {	
		            var new_bids_last = new Array();
		            var new_bids_cleaned = new Array();
		            var j= 0;
		            for (var i=0; i<new_bids.length; i++) {
		            	if (new_bids_last.length<4) {
			            	if (new_bids_last[new_bids[i].nick]==null) {
			            		new_bids_last[new_bids[i].nick] = new_bids[i];
			            		new_bids_cleaned[j]=new_bids[i];
			            		j++;
			            	} else 
			            		deleteNotificationCommand(new_bids[i].id);
			            } else
			            	deleteNotificationCommand(new_bids[i].id);
		            }
		            
		            var count=1;
		            jQuery.each(new_bids_cleaned, function(i, item) {
		            	if (jQuery('#bidder_'+count+' .nickname').html() != "---" && count!=3 && jQuery('#nick_bidder_'+count).html() != item.nick) {
		            		var oldEl = jQuery('#bidder_'+count).html();
		            		jQuery('#bidder_'+(count+1)).html(oldEl);
		            	}
		            	var date = new Date(item.time);
		            	var stringDate = getDayInWeekShortLabel(date.getDay())+" "+getHoursAMPM(date.getHours(), date.getMinutes());
		            	
		            	jQuery('#bidder_'+count).html('<div class="leaderboard-entry ('+count+' % 2==0?\'alternate-color\':\'\')" style="padding-top: 5px;"><div class="nickname" style="margin: 0px 10px; width:93%"> 	<div style="background-color: #4da9d2;width: 25px;height: 25px;float:left;margin-top:1px;"><img src="'+oldAppContextPath+'/spring/avatarThumbService?cdSize=75_75&amp;userId='+item.userId+'" width="25" height="25" alt=""/></div>  <div style="float:left; padding-left: 5px; padding-top: 7px;"><b><span id="nick_bidder_'+count+'">'+item.nick+'</span> made a new bid</b></div><div style="float:right; padding-top: 7px;">'+stringDate+'</div>  <div style="clear:both;"><!-- non rimuovere --></div>  </div><div class="clear"><!-- COMMENT --></div>  </div>');
		            	deleteNotificationCommand(item.id);
		            	
		            	count++;
		            });
		        }
	            	
	            setTimeout(
	                'waitForMsgGlobal(false, \''+oldAppContextPath+'\')', /* Request next message */
	                10000 /* ..after 10 seconds */
	            );
	        }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            console.log("error", textStatus + " (" + errorThrown + ")");
            setTimeout(
                'waitForMsgGlobal('+no_show_new_bids+', \''+oldAppContextPath+'\')', /* Try again after.. */
                15000); /* milliseconds (15seconds) */
        }
    });
}
function showNotifications(num) {
	document.getElementById("notificationButton").className = 'notification highlight';
	document.getElementById("notificationButton").title = num+' new notification'+((num>1)?'s':'');
    document.getElementById("notificationButton").onclick = function() { openDialogGlobalNotifications() };
    
    jQuery("#notificationsCountValue").html(num);
    document.getElementById("notificationsCountValue").style.visibility = 'visible';
}
function hideNotifications() {
	document.getElementById("notificationButton").className = 'notification';
	document.getElementById("notificationButton").title = 'You haven\'t new notifications';
    document.getElementById("notificationButton").onclick = null;
    
    jQuery("#notificationsCountValue").html(0);
    document.getElementById("notificationsCountValue").style.visibility = 'hidden';
}
function openDialogGlobalNotifications() {
	openModalDialog("/spring/forward?forwardTo=new_style/modals/getGlobalNotifications");
}

function deleteNotificationCommand(idToDelete){
        jQuery.ajax({
            type: "GET",
            url: "/wazzamba-web/spring/events?action=POP&id="+idToDelete,

            async: false, /* If set to non-async, browser shows page as "Loading.."*/
            cache: false,
            timeout:50000, /* Timeout in ms */

            success: function(data){ /* called when request to barge.php completes */
           		console.log(data);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                console.log("error", textStatus + " (" + errorThrown + ")");
            }
        });
    }
    
function buyCoinsRedeemCoupon()
{

  var code = jQuery('#couponCode').val();
  if( code == null || code == '' )
  {
    alert( 'Insert a valid coupon code.' );
    return;
  }
  
  jQuery.ajax({
    
    type: "GET",
    data: { "couponCode": "MR_" + code },
    url: "/wazzamba-web/apispring/redeemCoupon",
    dataType: "XML",

    success: function( data )
    {
       
       var response = $(data).find("VALUE").text();
       if( response == 'true' )
       {
         parent.jQuery.nyroModalRemove();
       }
       else
       {
         jQuery(".errorReedemCoins").show();
       }
      
    },
      
    error: function(XMLHttpRequest, textStatus, errorThrown)
    {
      alert( "It seems we have problem connecting to the server, please wait and retry." );
    }
      
  });
  
}
