/* Copyright 2009 Palm, Inc.  All rights reserved. */

var noImage = "--";
var suspendImage="action-icon";

var spinner_backup = "spinner_backup palm-activity-indicator";
var spinner_optout = "spinner_optout palm-activity-indicator";


var timeoutval = 30000;
var prepareNotificationCount =0;


var progress = undefined;
var backupInProgress=false;
var backupController;

var progressbarCoordinates = "400px";
var showNotification = false;
var resetTimer = null;
var failureDuration=0;
var suspendIntiated = false;

var schedulebackupInProgress = false;
var optOutInProgress = false;

var lastbackupTime;
var suspendEventCallback;

	var BackupAssistant = Class.create({
	    initialize: function(params){
				
	    $('timeValue').innerHTML = "";       
		$('divbkuptime').hide();	
		$('backupmessageOptOut_ON_OFF').innerHTML = ProfileUtil.label_backup_message_optOut_ON;  
	    this.onOffToggleOpt= {
	        modelProperty: 'toggleOpt',
			trueValue: "ON",
	        falseValue: "OFF"		
	    }; 
	    this.toggleModel= {
	        toggleOpt: "ON",
			disabled : true
	    };
		var content = Mojo.View.render({template: 'progresspill/entry'});
		this.progresspillattr = {	content: content,modelProperty: 'progress'};
		this.progresspillmodel = {  icon: "action-icon",progress: undefined,title: ProfileUtil.label_backup_now};
		
		if(params != undefined){
			if(params.notify==true) {
				showNotification = true;
				failureDuration = params.duration;
			} else if (params.passwordRequired) {
				this.getPassword(true);
			}
		}
		
	},

	notify :function(){
		var message =  $L("Your device has not been backed up in #{day} days. Try selecting Back up Now.").interpolate({
			day: failureDuration
		});
		this.controller.showDialog({
			template: 'dialogs/notification_dialog',
			assistant: new NotificationAssistant(this),
			failureNotification: message,
			supportInfo : $L("If you continue to have problems, visit palm.com/support."),
			preventCancel:false
		});
	},
	
	
	lbtime: function(){
	    var request = new Mojo.Service.Request(serviceName, {
	        method: 'getLastBackupTime',
	        parameters: {},
	        onSuccess: this.lbtimesuccess.bind(this),
	        onFailure: this.lbtimefailure.bind(this)
	    });    
	},
	
	lbtimefailure : function(response){
		$('divbkuptime').hide();
	},

	lbtimesuccess :function(response){
		  if(response.lastbackupTime =='.'){
		  	$('divbkuptime').hide();
			Mojo.log("OPTIN RESPONSE ="+response.OptIn);
			if(response.OptIn=="no") {
				this.toggleModel.toggleOpt="OFF";
				this.controller.modelChanged(this.toggleModel);
				this.optOutSuccess();
				$('backupmessageOptOut_ON_OFF').innerHTML = ProfileUtil.label_backup_message_optOut_OFF;

			}	
			else {
				Mojo.log("Set to opt IN");
				this.toggleModel.toggleOpt="ON";
				this.controller.modelChanged(this.toggleModel);
			}
		  }
		  else {
		  	Mojo.log("Showing the last backup time " +response.lastbackupTime );
		  	this.formatTime(response.lastbackupTime);
		  }
		  
	},
	
	formatTime :function(lastbackuptime){
		Mojo.log("Calling format time" + lastbackupTime);
		$('divbkuptime').show();
		var value = Number(lastbackuptime);
		Mojo.log("Calling format time - format" + value);
		var dateTime = new Date(value);
		var v1 = Mojo.Format.formatDate(dateTime, {date:'short', time:'short'}); 
		Mojo.log("Date and time is " + v1);
		$('timeValue').innerHTML =v1;
	},
		
	//-----------------------
	 
    setup: function(){
		backupController=this.controller;
		this.progresspillmodel.icon=noImage;
		this.controller.setupWidget('progressPill',this.progresspillattr, this.progresspillmodel);
 		this.controller.setupWidget('onOffToggle', this.onOffToggleOpt, this.toggleModel);	
		this.controller.setupWidget('activity-spinner', this.spinnerLAttrs, this.spinnerModel);
		Mojo.log("Backup -Setup Over");
		
		this.appMenuModel = {
			label: $L('Palm Services'), 
			items: [
				Mojo.Menu.editItem,
                {label: $L('Palm Profile'), command: 'editAccount'},
                {label: $L('Help'), command: 'help'}
			],
		};
		
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.appMenuModel);
		setTimeout(this.configure.bind(this), 50);
		
	},
	
	handleCommand: function(event) {
		if ((event.type == Mojo.Event.command) && (event.command == 'editAccount')) {
			Mojo.Log.info("------------------ Edit Account ------------------------- Setting backupInProgress to false");
			backupInProgress = false;
			this.getPassword(false);
		}
		else if (event.type == Mojo.Event.command && event.command == 'help') {
			Mojo.Log.info("------------------ Launch Help -------------------------Setting backupInProgress to false");
			backupInProgress = false;
			this.launchHelp();
		}
	},
	
	scheduleReset : function(timeout){
		Mojo.Log.info("------------------ scheduleReset -------------------------Setting backupInProgress to false---------" + timeout+"-------"+backupInProgress);
		if (timeout == 0) {
			backupInProgress = false;
		}
		if (!resetTimer) {
			resetTimer = this.controller.window.setTimeout(this.resetBackup.bind(this), timeout);
		}
	},
	
	configure :function(){
		
		this.scheduleReset(0);
		$('onOffToggle').observe('mojo-property-change', this.selectorChangedHandler.bind(this));
		$('progressPill').observe('click', this.backup.bindAsEventListener(this));
//		this.controller.listen('progressPill', Mojo.Event.progressIconTap, this.cancelled.bind(this));
		this.controller.listen('progressPill', Mojo.Event.progressComplete,this.complete.bind(this));
		this.lbtime(); 
		this.registerForServer();
	   Mojo.Controller.getAppController().backupassitant=this;
	   //Auto closing when back out or hit the home button.
	   this.progresspillmodel.icon=noImage;
	   this.controller.modelChanged(this.progresspillmodel);
	   if(showNotification){
	   	 this.notify();
		 showNotification = false;
	   }

	},
	
    selectorChangedHandler: function(e){
		Mojo.log("Call to change backup status" + e.value);
	    var displayMessage = ProfileUtil.label_display_message;
        var displayTitle = ProfileUtil.label_opt_out;
       	if(e.value=="OFF") {
		    this.controller.showAlertDialog({
		    onChoose: function(value){
	    	if (value == "optOutIn_Yes") {
		        this.optOutFromBackup();
				$('backupmessageOptOut_ON_OFF').innerHTML = ProfileUtil.label_backup_message_optOut_OFF;
	    	}
	   		else {
				this.toggleModel.toggleOpt="ON";
				this.controller.modelChanged(this.toggleModel);
	    	}
	    	},
		        title: displayTitle,
		        message: displayMessage,
		        choices: [{
		           	label: $L("Turn Off and Erase Backup"),
		           	value: 'optOutIn_Yes',
					type:'negative'
		        	}, {
		        	label: $L("Keep Backup On"),
		           	value: "optOutIn_No",
		           	type: 'alert'
		        }]
		       });
		}
		else {
			$('backupmessageOptOut_ON_OFF').innerHTML = ProfileUtil.label_backup_message_optOut_ON;
			this.scheduleJob();
		}
    },
	showNoConnectionAvailableForOptout: function(e){
	    var displayMessage = ProfileUtil.label_noDataConnectionForOutout;
        var displayTitle = ProfileUtil.label_noDataConnectionTitle;
	    this.controller.showAlertDialog({
		    onChoose: function(value){
	    	if (value == "ConnectionFailureHelp") {
//				Show help
				this.launchHelp();
	    	}
	   		else {
			
	    	}
	    },
        title: displayTitle,
        message: displayMessage,
        choices: [{
           	label: $L("Help"),
           	value: 'ConnectionFailureHelp',
			type:'dismiss',
			buttonClass:'secondary'
        	}, {
        	label: $L("OK"),
           	value: "OK",
           	type: 'alert',
			buttonClass:'primary'
        }]
       });
    },
	
	takeDownSuspendIcon: function() {
		this.progresspillmodel.icon=noImage;

		if (suspendEventCallback != null) {
			// De-Activate the suspend Icon this time.
			this.controller.stopListening('progressPill', Mojo.Event.progressIconTap, suspendEventCallback);
			suspendEventCallback = null;
		}
	},
	
	showNoConnectionAvailable: function(e){
	    var displayMessage = ProfileUtil.label_noDataConnection;
        var displayTitle = ProfileUtil.label_noDataConnectionTitle;
	    this.controller.showAlertDialog({
		    onChoose: function(value){
	    	if (value == "ConnectionFailureHelp") {
//				Show help
				this.launchHelp();
	    	}
	   		else {
			
	    	}
	    },
        title: displayTitle,
        message: displayMessage,
        choices: [{
           	label: $L("Help"),
           	value: 'ConnectionFailureHelp',
			type:'dismiss',
			buttonClass:'secondary'
        	}, {
        	label: $L("OK"),
           	value: "OK",
           	type: 'alert',
			buttonClass:'primary'
        }]
       });
    },
	
	showNoServerAvailable: function(e){
	    var displayMessage = ProfileUtil.label_noServerAvailable;
        var displayTitle = ProfileUtil.label_noServerAvailableTitle;
	    this.controller.showAlertDialog({
		    onChoose: function(value){
//	    	Nothing to be done.
	
	    },
        title: displayTitle,
        message: displayMessage,
        choices: [{
        	label: $L("OK"),
           	value: "optOutIn_No",
           	type: 'alert'
        }]
       });
    },
	
	
  

	
	prepareBackup: function(){
		backupInProgress=true;
		this.changeLabel(ProfileUtil.label_preparing);
		this.toggleModel.toggleOpt="ON";
		this.cancelAbort();
		this.controller.modelChanged(this.toggleModel);
		this.prepareNotificationCount =0;
		Mojo.log("Preparing for backup over");
    },
	
	completeBackup : function(){
		progress=0;
		this.progresspillmodel.progress= undefined;
		this.takeDownSuspendIcon();

		this.changeLabel(ProfileUtil.label_backupcomplete);		
		this.controller.window.setTimeout(this.finished.bind(this),20);
		this.scheduleReset(timeoutval);
	},
	
	finished : function(){
		this.controller.modelChanged(this.progresspillmodel);
	},
	
	
	
	failedBackup: function(){; 
		this.takeDownSuspendIcon();
		this.changeLabel(ProfileUtil.label_backup_now);
		Mojo.log("Failed to backup, changing the label");
		this.scheduleReset(0);
	},
	
	backupSuccess : function(response){
	},

	scheduleJob : function(event) {
		this.spinOn();
		schedulebackupInProgress=true;
		AppAssistant.backupService.ScheduleBackup(this.controller,this.OptIn.bind(this),this.scheduleError.bind(this));
	},
	
	scheduleError : function(response){
		Mojo.log("Error scheduling a backup Job" + $H(response).inspect());
		this.spinOff();
		this.toggleModel.toggleOpt="OFF";
		this.controller.modelChanged(this.toggleModel);
		this.showNoConnectionAvailable();
		schedulebackupInProgress=false;		
	},
	
	registerForServer : function(event) {
		this.serverListener = AppAssistant.backupService.RegisterForServerStatus(this.controller,this.registerForServerChanges.bind(this),this.registerError.bind(this));
	},
	
	registerError : function(event){
		Mojo.log("Error in registering to backup Service" + $H(event).inspect());
	},

	
	getLastBackupTime : function(event){
		AppAssistant.backupService.LastBackupTime(this.controller,this.lasttime.bind(this),this.errorlasttime.bind(this));
	},
	
	prepareSuspend : function(){},	
	
    cleanup: function(){ 
	 	AppAssistant.backupService.UnregisterEngineChanges(this.controller, this.unRegisterResponse.bind(this));
	},
    activate: function(){},
    deactivate: function(){},
	
	
	errorlasttime : function(response){
		$('divbkuptime').hide();
	},

	lasttime : function(response){
		  Mojo.log("Response received is " + $H(response).inspect());
		  if(response.lastbackupTime =='.'){
		  	$('divbkuptime').hide();
			if(response.OptIn=="no") {
				Mojo.log("Error adding invalid toggle status");
				this.toggleModel.toggleOpt="ON";
			}	
		  }
		  else {
		  	this.formatTime(response.lastbackupTime);
		  }
	},


	suspend : function(event){
		AppAssistant.backupService.Suspend(this.controller,this.suspendSuccess.bind(this),this.suspendFailure.bind(this));
		Mojo.log("Backup Suspended from UI")
		this.changeLabel(ProfileUtil.label_backupsuspended);
		suspendIntiated = true;
	},

	backup : function(event){
		Mojo.log("Backup Initiated from UI")		
		if(backupInProgress ||suspendIntiated==true){
			return;
		}
        this.prepareBackup();

		AppAssistant.backupService.Backup(this.controller,this.backupSuccess,this.backupFailure);
	},

	suspendSuccess : function(response){
		this.prepareSuspend();
	},

	suspendFailure : function(response){
		Mojo.log("Error in suspending ");
	},
	

	resume : function(event){
		this.prepareBackup();
		AppAssistant.backupService.Resume(this.controller,this.onResumeSuccess,this.onResumeFailure);
	},

	onResumeSuccess : function(response){
		if (response.STATUS == 'Complete') {
	        this.completeBackup();
			this.getLastBackupTime();
	    }
		else if (response.STATUS == 'Suspend') {
			this.prepareSuspend();
		}
		if (response.STATUS == 'Failed') {
			this.resetBackup();
		}
	},
	
	onResumeFailure : function(event){
		this.resetBackup();
	},


//	
	optOutFromBackup : function(event){
		this.changeLabel(ProfileUtil.label_optingout);
		this.spinOn();
		backupInProgress=true;
		optOutInProgress=true;
		AppAssistant.backupService.OptOutofBackup(this.controller,this.optOutSuccess.bind(this),this.optOutFailure.bind(this));
	},
	
	optOutFailure : function(event){
		Mojo.log("Failed to opt out of backup"+ $H(event).inspect());
		this.spinOff();
		this.getLastBackupTime();
		this.progresspillmodel.progress = undefined;
	    this.changeLabel(ProfileUtil.label_backup_now); 
		this.toggleModel.toggleOpt="ON";
		this.controller.modelChanged(this.toggleModel);
		this.controller.get('progressPill').show();
		this.showNoConnectionAvailableForOptout();
		backupInProgress=false;
		optOutInProgress=false;
	},

	optOutSuccess : function(event){
		Mojo.log("Successfully opted out of backup");
		this.spinOff();
		$('divbkuptime').hide();
		this.controller.get('progressPill').hide();
		backupInProgress=false;
		optOutInProgress=false;
	},

	OptIn : function(event){   
	   this.progresspillmodel.progress = undefined;
	   this.spinOff();
	   this.changeLabel(ProfileUtil.label_backup_now); 
	   this.controller.get('progressPill').show()
       this.getLastBackupTime(); 
	   backupInProgress=false;
	   schedulebackupInProgress=false;
	},
	
	successCallback : function(response){
	  Mojo.log("Callback received " + $H(response).inspect());
	  if (response.STATUS == undefined) {
	  	if (backupInProgress == false) {
			this.changeLabel(ProfileUtil.label_backup_now);
		}
	  }
	  else if (response.STATUS == 'Complete') {
	  		this.getLastBackupTime();
			this.completeBackup();
	  }
	  else if (response.STATUS == 'Failed') {
  			this.failedBackup();
			if (response.displayError){
				Mojo.log("Display the UI error message");
				var type = response.errorType;
				if(type=="DATA_CONNECTION"){
					this.showNoConnectionAvailable();
					if(schedulebackupInProgress){
						this.scheduleError();
					}
					else if(optOutInProgress){
						this.optOutFailure();
					}
				}
				else if(type=="SERVER"){
					this.showNoServerAvailable();
				}
				console.info("callback disconnect -setting backupInprogress to false");
				backupInProgress=false;
				this.resetBackup();
			}
			backupInProgress=false;
			this.spinOff();
	 }
	 else if (response.STATUS == 'ReadyToTransfer') {
	  			//this.changeLabel(label_backing_now);
	 }
	 else if (response.STATUS == 'Preparing') {
	 	    this.cancelAbort();
			this.changeLabel(ProfileUtil.label_preparing);
			if (response.serialzied != undefined) {
				prepareNotificationCount++
				var m = prepareNotificationCount % 3;
				switch (m) {
					case 0:
						this.changeLabel(ProfileUtil.label_preparing);
						break;
					case 1:
						this.changeLabel(ProfileUtil.label_preparing + ".");
						break;
					case 2:
						this.changeLabel(ProfileUtil.label_preparing + "..");
						break;
					default:
						this.changeLabel(ProfileUtil.label_preparing);
				}
			}
	  }
	  else if (response.STATUS == "InProgress") {
	  	this.cancelAbort();
		if (response.percent == undefined) {
			return;
		}
		if(suspendIntiated==true){
			return;
		}
		if( suspendEventCallback == null) {
			// Activate the suspend Icon this time. Since this is the first progress we are getting back after the Backup call being sent ot the server.
			suspendEventCallback = this.cancelled.bind(this);
			this.controller.listen('progressPill', Mojo.Event.progressIconTap, suspendEventCallback);
		}
		this.progresspillmodel.icon = suspendImage;
		progress = response.percent / 100.0;
		this.changeLabel(ProfileUtil.label_backing_now);
		this.updateProgress();
	  }
	  else if (response.STATUS == 'Abort') {
			this.abort();
	  }
	  else if (response.STATUS == 'Suspend') {
			this.abort();
	  }
  },
	
	failureCallback : function(event){
	  Mojo.log("Receieved failure callback");
	  backupInProgress=false;
	  this.resetBackup();
	},
	
	complete : function() {
		Mojo.log("Complete...");
	},
	
	cancelled : function() {
		this.progresspillmodel.icon=noImage;
		this.changeLabel(ProfileUtil.label_backupsuspended);
		this.suspend();
		this.scheduleReset(timeoutval);
	},
	cancelAbort : function() {
		if (resetTimer) {
			this.controller.window.clearTimeout(resetTimer);
			resetTimer=null;
		}
	},
	
	abort : function() {
		this.takeDownSuspendIcon();
		this.changeLabel(ProfileUtil.label_backupsuspended);
		this.scheduleReset(timeoutval);
	},
	
	updateProgress : function(){
		this.progresspillmodel.progress = progress;
		this.controller.modelChanged(this.progresspillmodel);
	},
	resetBackup : function(){
		progress=0;
		this.progresspillmodel.progress = undefined;
		this.progresspillmodel.icon=noImage;
		this.changeLabel(ProfileUtil.label_backup_now);
		this.toggleModel.disabled=false;
		this.controller.modelChanged(this.toggleModel);
		resetTimer = null;
		suspendIntiated = false;
		backupInProgress=false;
	},
	
	changeLabel : function(label){
		this.progresspillmodel.title = label;
		this.controller.modelChanged(this.progresspillmodel);
	},

//	 backupAppHasLostFocus : function() {
//	 	AppAssistant.backupService.UnregisterEngineChanges(this.controller, this.unRegisterResponse.bind(this));
//    },
	
	unRegisterResponse : function() {
		if(this.backupRequest != undefined){
			this.backupRequest.cancel();
			this.backupRequest=undefined;
		}
		if(this.serverListener != undefined){
			this.serverListener.cancel();
		}
		window.close();
	},
	
	spinOn: function() {
			$('div_optoutspinner').show();	
			this.spinnerModel.spinningP = true;
			this.controller.modelChanged(this.spinnerModel);
			
	},

	spinOff: function() {
			$('div_optoutspinner').hide();	
			if (this.spinnerModel.spinningP == true) {
				this.spinnerModel.spinningP = false;
				this.controller.modelChanged(this.spinnerModel);
			}
	},		
		
	spinnerLAttrs: {
	    spinnerSize: 'large',
		property: 'spinningP',
	},

	spinnerModel: {
		spinningP: false
	},
	
	getPassword: function(isTokenNeeded) {
		if (isConnectionAvailable === false) {
			ProfileUtil.showConnectionError(this.controller);
		}
		else {
			this.controller.showDialog({
				template: 'account/password-dialog',
				assistant: new PasswordAssistant(this, isTokenNeeded),
				preventCancel: true
			});
		}	
	},
	
	registerForServerChanges: function(e){ 
		
	    if(this.backupRequest != undefined){
			this.backupRequest.cancel();
		}
		this.backupRequest = AppAssistant.backupService.registerEngineChanges(this.controller,
							                                                  this.successCallback.bind(this),
																			  this.failureCallback.bind(this));
    },
	
	launchHelp: function(){
		this.controller.serviceRequest("palm://com.palm.applicationManager", {
 								 method: "open",
  							 parameters: { 		id: 'com.palm.app.help',
      								   		params: { target: "http://help.palm.com/backup/index.html" }
 										 }
									  });
	}
   });

var NotificationAssistant = Class.create({
	
	initialize: function(sceneAssistant) {
		this.sceneAssistant = sceneAssistant;
		this.controller = sceneAssistant.controller;
	},
	
	setup : function(widget) {
		this.widget = widget;
		this.controller.get('ok_button').addEventListener(Mojo.Event.tap, this.accept.bindAsEventListener(this));
	},
	
	accept: function() {
		this.widget.mojo.close();
	}
	
	
});

	
var content = Mojo.View.render({template: 'progresspill/entry'}); 