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

var DateandtimeconfigAssistant = Class.create({
	
	initialize: function(params) {
		
		this.params = null;
		
		if (params) {
			this.params = params;
			if(this.params && (this.params.launchType == "showTimezones" || this.params.launchType == "showDateTimeTimezonePicker"))
				this.pushTimezonelist = true;
		}
		
		this.NETWORKTIMEWAITMSG = $L("Waiting for network time. Turn Airplane Mode on and then off again to update immediately.");
							
		this.systemtimechanged = false;
		this.systemtimezonechanged = false;
		
		this.receiveNetworkTimeQueryDone = false;
		this.receiveNetworkTimezoneQueryDone = false;
		
		this.getSystemTimeReq = SystemService.getSystemTime(this.systemTimeHandler.bind(this));
		this.getWaitingForNetworkTimeUpdate = SystemService.getWaitForNetworkUpdate("receiveNetworkTimeUpdate", this.getWaitingForNetworkTimeUpdateDone.bind(this));
		this.getWaitingForNetworkTimezoneUpdate = SystemService.getWaitForNetworkUpdate("receiveNetworkTimezoneUpdate",this.getWaitingForNetworkTimezoneUpdateDone.bind(this));
		this.getTimeFormatReq = SystemService.getTimeFormat(this.timeFormatHandler.bind(this));		
		this.getUseNetworkTimeZoneReq = SystemService.getUseNetworkTimeZone(this.useNetworkTimezoneHandler.bind(this));
		this.currTimeZone = null;						
	},
	
	ToggleOpt: {
        modelProperty: 'value',
        enableProp: 'enabled',        
    },
    
    networkTimeModel: {
        value: true,
    },
	
	 networkTimezoneModel: {
        value: true,
    },
	
	setup: function() {
						
		this.controller.setupWidget('timeformat', {
			choices: this.availableTimeFormat,
			modelProperty: 'currentFormat'
		}, this.timeFormat);
		
		this.controller.setupWidget('useNWTime', this.ToggleOpt, this.networkTimeModel);
		this.controller.setupWidget('useNwTimeZone', this.ToggleOpt, this.networkTimezoneModel);
		
		this.dateTimeModel = {
			time:new Date(),
		}, 
		
		this.spinnerLAttrs = {
			spinnerSize: 'small'
		},
		this.spinnerModel = {
			spinning: false
		},
		
		this.handleDateChange = this.handleDateChange.bind(this);
		this.handleTimeChange = this.handleTimeChange.bind(this);
		
		this.controller.setupWidget('settimezone-spinner', this.spinnerLAttrs, this.spinnerModel);	
		this.DateAndTimePickerDivs = this.controller.get('manualsettings').innerHTML;				
		this.controller.setupWidget('dateDiv', {modelProperty:'time', minYear:1970, maxYear:2037}, this.dateTimeModel);
		this.controller.setupWidget('timeDiv', {modelProperty:'time',minuteInterval:1}, this.dateTimeModel);
		
		this.controller.get('dateDiv').observe('mojo-property-change', this.handleDateChange);
		this.controller.get('timeDiv').observe('mojo-property-change', this.handleTimeChange);
		
		this.updateClock();
		setInterval(this.updateClock.bind(this),1000);
		
		//App Menu - Remove default items and add only Edit & Help items.
		var appMenuModel = {
	        visible: true,
	        items: [Mojo.Menu.editItem,{label:$L('Help'), command:Mojo.Menu.helpCmd}
	            ]
	        };
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems:true}, appMenuModel);	
		$('timeformat').observe('mojo-property-change', this.timeFormatChanged.bindAsEventListener(this));
		$('useNWTime').observe('mojo-property-change', this.handleTimeSettings.bindAsEventListener(this));
		$('useNwTimeZone').observe('mojo-property-change', this.handleTimeZoneSettings.bindAsEventListener(this));
		$('showcitylist').observe(Mojo.Event.tap, this.showTimezonelist.bindAsEventListener(this));		
		
		if(this.params && this.params.launchType == "showTimezones") {
			this.showTimezonelist.bind(this).delay(1);
		}							
	},
	
	activate: function() {
		
	},
	
	//Model for Timer Selection List
	timeFormat: {currentFormat: ''},
	
	//Available Timer Values.
	availableTimeFormat: [{label: $L('12 hour'), value:'HH12'},{label: $L('24 hour'), value:'HH24'}],
	
	handleCommand: function(event) {
		if (event.type == Mojo.Event.command) {
			if(event.command == Mojo.Menu.helpCmd) {				
				new Mojo.Service.Request('palm://com.palm.applicationManager', {
					method: 'open',
					parameters: {'id': 'com.palm.app.help',params: {'target': 'http://help.palm.com/date_time/index.html'}}});
			}
		}
	},
	
	timeFormatHandler: function(payload) {
		
		if(payload && payload.timeFormat) {
			this.timeFormat.currentFormat = payload.timeFormat;			
		}
		else {
			this.timeFormat.currentFormat = 'HH12';
		}
		
		this.controller.modelChanged(this.timeFormat,this);
		
	},
	
	timeFormatChanged: function(event) {
		
		if(!event.value)
			return;		
		SystemService.setTimeFormat(event.value,null);
		this.recreateDateandTimePicker.bind(this).delay(1);		
	},
	
	systemTimeHandler: function(payload) {	
			
		if(!payload) {
			return;
		}
		
		if(this.currTimeZone && this.currTimeZone != payload.TZ) {
			var msg = $('cityName').innerHTML;
			msg = msg.sub($L(this.currTimeZone), $L(payload.TZ));
			$('cityName').innerHTML = msg;
			//$('currenttimezone').innerHTML = msg;
		}	
		 		
		if(payload.TZ) {
			this.currTimeZone = payload.TZ;
		}		
	},
	
	currentTimeZoneHandler: function(payload) {
		
		if(!payload.timeZone)
			return;
		this.selectedTimeZone(payload.timeZone,false);
	},
	

	updateClock: function(newFormat) {
		var date = new Date();	
		
		if (!this.systemtimechanged) {			
			return;
		}
		
		$('currentdatetime').innerHTML = Mojo.Format.formatDate(date, {date: 'long',time: 'short'});
		
	},
	
	useNetworkTimeHandler: function(payload) {
		
		if(payload && payload.useNetworkTime === true) {
			this.networkTimeModel.value = true;
			this.controller.modelChanged(this.networkTimeModel, this);
			if (!this.systemtimechanged) {
				$('currentdatetime').innerHTML = this.NETWORKTIMEWAITMSG;
				this.showDateAndTimePicker(true);
				$('currentdatetime').show();
			}	
			else {
				this.showDateAndTimePicker(false);
			}			
		}
		else {
			this.networkTimeModel.value = false;
			this.controller.modelChanged(this.networkTimeModel, this);
			this.showDateAndTimePicker(true);		
		}
	},
	
	useNetworkTimezoneHandler: function(payload) {
		
		if(payload && payload.useNetworkTimeZone === true) {
			this.networkTimezoneModel.value = true;
			this.controller.modelChanged(this.networkTimezoneModel, this);
			//$('currenttimezone').show();
			$('manualTimezoneSettings').hide();	
		}
		else {
			this.networkTimezoneModel.value = false;
			this.controller.modelChanged(this.networkTimezoneModel, this);
			//$('currenttimezone').hide();
			$('manualTimezoneSettings').show();
		}
			
	},
	handleTimeSettings: function(event) {
		
		if(event.value) {			
			this.setUseNetworkTimeReq = SystemService.setUseNetworkTime(true,null);
			if (!this.systemtimechanged) {
				$('currentdatetime').innerHTML = this.NETWORKTIMEWAITMSG;
				this.showDateAndTimePicker(true);
				$('currentdatetime').show();
			}	
			else {
				this.showDateAndTimePicker(false);
			}			
		}
		else {
			this.setUseNetworkTimeReq = SystemService.setUseNetworkTime(false,null);			
			this.showDateAndTimePicker(true);			
		}
	},
	
	showDateAndTimePicker: function(show) {
		if(show) {
			this.dateTimeModel.time = new Date();
			this.controller.modelChanged(this.dateTimeModel, this);
			$('manualsettings').show();
			$('currentdatetime').hide();
			this.controller.showWidgetContainer(this.controller.get('manualsettings'));	
		}
		else {
			$('manualsettings').hide();
			$('currentdatetime').show();
			this.controller.hideWidgetContainer(this.controller.get('manualsettings'));
		}
	},
	
	showDateTimePicker: function(launchType) {
		if(launchType == "showDateTimeTimezonePicker") {
			this.params = {launchType : "showDateTimeTimezonePicker"};
			this.pushTimezonelist = true;
			this.receiveNetworkTimeQueryDone = false;
			this.receiveNetworkTimezoneQueryDone = false;
			this.getWaitingForNetworkTimezoneUpdateDone();
			this.getWaitingForNetworkTimeUpdateDone();
		}
		else if(launchType == "showTimezones") {
			this.pushTimezonelist = true;
			this.params = {launchType : "showTimezones"};
			this.receiveNetworkTimezoneQueryDone = false;
			this.getWaitingForNetworkTimezoneUpdateDone();
		}
		else {
			this.params = {launchType : "showDateTimePicker"};
			this.receiveNetworkTimeQueryDone = false;
			this.getWaitingForNetworkTimeUpdateDone();
		}
	},
	
	recreateDateandTimePicker: function() {
		this.dateTimeModel.time = new Date();
	
		this.controller.get('manualsettings').update();
		this.controller.get('manualsettings').innerHTML = this.DateAndTimePickerDivs;
		
		this.controller.setupWidget('dateDiv', {modelProperty:'time', minYear:1970, maxYear:2037}, this.dateTimeModel);
		this.controller.setupWidget('timeDiv', {modelProperty:'time',minuteInterval:1}, this.dateTimeModel);
		this.controller.instantiateChildWidgets(this.controller.get('manualsettings'));
		
		this.controller.get('dateDiv').observe('mojo-property-change', this.handleDateChange);
		this.controller.get('timeDiv').observe('mojo-property-change', this.handleTimeChange);
		
	},
	
	handleTimeZoneSettings: function(event) {
				
		if(event.value) {
			this.setUseNetworkTimeZoneReq = SystemService.setUseNetworkTimeZone(true,null);
			this.systemtimezonechanged = false;
			SystemService.setWaitForNetworkUpdate('receiveNetworkTimezoneUpdate',false);		
			//$('manualTimezoneSettings').show();
			$('waitMsg').show();
			//$('currenttimezone').hide();	
		}
		else {			
			this.setUseNetworkTimeZoneReq = SystemService.setUseNetworkTimeZone(false,null);			
			//$('currenttimezone').hide();
			$('manualTimezoneSettings').show();
			$('waitMsg').hide();			
		}
	},
	
	showTimezonelist: function(event) {
		this.controller.stageController.pushScene('timezone',this);
	},
	
	handleDateChange: function(event) {
		if(!event.value)
			return;
			
		var dateObj = event.value;
		var obj = new Object();
		obj.utc = dateObj.getTime()/1000;
		
		this.setSystemDateReq = SystemService.setSystemTime(obj,null);
		$('currentdatetime').innerHTML = this.NETWORKTIMEWAITMSG;
		SystemService.setWaitForNetworkUpdate('receiveNetworkTimeUpdate',false);
		this.systemtimechanged = false;		
	},
	
	handleTimeChange: function(event) {
		
		if(!event.value)
			return;
		
		var dateObj = event.value;
		var obj = new Object();
		obj.utc = dateObj.getTime()/1000;
		
		this.setSystemTimeReq = SystemService.setSystemTime(obj,null);
		$('currentdatetime').innerHTML = this.NETWORKTIMEWAITMSG;
		SystemService.setWaitForNetworkUpdate('receiveNetworkTimeUpdate',false);
		this.systemtimechanged = false;			
	},
	
	delayedSelectedTimeZone: function(selectedZone) {
		$('cityName').innerHTML = $L("Setting Timezone");
		this.spinnerModel.spinning = true;
		this.controller.modelChanged(this.spinnerModel,this);
		this.selectedTimeZone.bind(this).delay(2,selectedZone,true);
	},
	
	selectedTimeZone: function(selectedZone,setTimezone) {
		if(!selectedZone)
			return;
		
		this.spinnerModel.spinning = false;
		this.controller.modelChanged(this.spinnerModel,this);
		
		if(this.currTimeZone != null) {
			if(selectedZone.City != '') {
				$('cityName').innerHTML = $L(selectedZone.City) + ", " + $L(selectedZone.Country) + " ("+ $L(this.currTimeZone) +")";
				//$('currenttimezone').innerHTML = $L(selectedZone.City) + ", " + $L(selectedZone.Country) + " ("+ $L(this.currTimeZone) +")";
			}			
			else {
				$('cityName').innerHTML = $L(selectedZone.Country) + " (" + $L(this.currTimeZone) +")";
				//$('currenttimezone').innerHTML = $L(selectedZone.Country) + " ("+ $L(this.currTimeZone) +")";
			}
			this.recreateDateandTimePicker();
		}
		else {
			if(selectedZone.City != '') {
				$('cityName').innerHTML = $L(selectedZone.City) + ", " + $L(selectedZone.Country) ;
				//$('currenttimezone').innerHTML = $L(selectedZone.City) + ", " + $L(selectedZone.Country) ;
			}			
			else {
				$('cityName').innerHTML = $L(selectedZone.Country) ;
				//$('currenttimezone').innerHTML = $L(selectedZone.Country);
			}
			this.recreateDateandTimePicker();
		}		
		
		if(!this.systemtimezonechanged) {
			//$('currenttimezone').hide();
			if (this.networkTimezoneModel.value) {
				$('waitMsg').show();
				if(this.pushTimezonelist) 
					$('manualTimezoneSettings').show();
				else
					$('manualTimezoneSettings').hide();
			}
			else {
				$('manualTimezoneSettings').show();
				$('waitMsg').hide();
			}
				
			return;
		}
		else {
			if(this.networkTimezoneModel.value ) {
				//$('currenttimezone').show();
				$('manualTimezoneSettings').hide();	
				$('waitMsg').hide();
			}
		}
		
		if(setTimezone) {
			this.systemtimezonechanged = false;
			SystemService.setWaitForNetworkUpdate('receiveNetworkTimezoneUpdate',false);
		}
			
	},
	
	getWaitingForNetworkTimeUpdateDone: function(payload) {
		
		this.getUseNetworkTimeReq = SystemService.getUseNetworkTime(this.useNetworkTimeHandler.bind(this));
		
		if(!this.receiveNetworkTimeQueryDone && this.params && (this.params.launchType == "showDateTimePicker" || this.params.launchType == "showDateTimeTimezonePicker")){
			this.systemtimechanged = false;
			this.receiveNetworkTimeQueryDone = true;
			return;
		}
		
		if(payload.receiveNetworkTimeUpdate === undefined)
			return;
		
		if(payload.receiveNetworkTimeUpdate === true)
			this.systemtimechanged = true;
		else {
			this.systemtimechanged = false;
			$('currentdatetime').innerHTML = this.NETWORKTIMEWAITMSG;
		}
	},
	
	getWaitingForNetworkTimezoneUpdateDone: function(payload) {
		
		this.getCurrentTimeZoneReq = SystemService.getCurrentTimeZone(this.currentTimeZoneHandler.bind(this));
		
		if(!this.receiveNetworkTimezoneQueryDone && this.params && (this.params.launchType == "showTimezones" || this.params.launchType == "showDateTimeTimezonePicker")){
			this.systemtimezonechanged = false;
			this.receiveNetworkTimezoneQueryDone = true;
			return;
		}
		
		if(payload.receiveNetworkTimezoneUpdate === undefined)
			return;
		
		if(payload.receiveNetworkTimezoneUpdate === true)
			this.systemtimezonechanged = true;
		else {
			this.systemtimezonechanged = false;
		}
				
	},
		
});

