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

var THIRTY_MINUTES = $L("30 minutes");
var ONE_HOUR = $L("1 hour");
var TWO_HOURS = $L("2 hours");
var numTimedAlarm = 7;		
var PrefsAssistant = Class.create({
				 
	initialize: function() {

	},
	
	startOfDayCallback: function(event) {
		var time = event.value;
		var newStartOfDay = new Date(this.prefs.startTimeOfDay);
		newStartOfDay.setHours(time.getHours());
		newStartOfDay.setMinutes(time.getMinutes());
		// Convert the time back to utc
		newStartOfDay.addMinutes(-newStartOfDay.getTimezoneOffset());
		this.prefs.startTimeOfDay = newStartOfDay.getTime();
		this.dirty = true;
	},
	
	endOfDayCallback: function(event) {
		var time = event.value;
		var newEndOfDay = new Date(this.prefs.endTimeOfDay);
		newEndOfDay.setHours(time.getHours());
		newEndOfDay.setMinutes(time.getMinutes());
		// Convert the time back to utc
		newEndOfDay.addMinutes(-newEndOfDay.getTimezoneOffset());
		this.prefs.endTimeOfDay = newEndOfDay.getTime();
		this.dirty = true;
	},
	
	renderStartOfWeek: function() {
		var sowDate = new Date();
		sowDate.moveToDayOfWeek(this.prefs.startOfWeek-1);
		var sow = {};
		
		this.controller.get('pv_start_of_week').update(Mojo.Format.formatDate(sowDate, "EEEE"));
	},
	
	renderNewEventDuration: function() {
		var ned = {};
		
		if (this.prefs.defaultEventDuration == 30) {
			ned.duration = THIRTY_MINUTES;
		} else if (this.prefs.defaultEventDuration == 60) {
			ned.duration = ONE_HOUR;
		} else {
			ned.duration = TWO_HOURS;
		}
		
		this.controller.get('pv_new_event_duration').update(ned.duration);
	},
	chooseAlarmType:function(event){
		if(event.value!=3)/*if it is not ringtone type*/
		{
			this.controller.get('currentringtonerow').hide();
		}
		else{
			
			this.controller.get('currentringtonerow').show();
			if(!this.prefs.ringtoneName || this.prefs.ringtoneName=='')
				this.chooseNotificationRingtone();
			else
			{
				this.controller.get('currentringtone').update(this.prefs.ringtoneName);
			}
		}
		//the reason we are doing this is we are mapping mute option
		//whose value in the db is 0 to an option 4 in the drop down
		//in the alert preferences.
		
		this.prefs.alarmSoundOn =this.convertSoundPopupToDBVal(event.value);
		this.dirty=true;
		
	},
	updateEasAccountLoginDisplayNames: function() {
		//Mojo.Log.info("updateEasAccountLoginDisplayNames %s", Object.toJSON(this.acctsModel));
		this.acctsModel.items.each(function(acct){
			if (acct.domain == 'eas') {
				var calAcct = getCalendarsManager().getCalAccount(acct.accountId);
				if (calAcct && calAcct.calendars) {
					if (acct.originalLogin) {
						// Use the originalLogin set for eas accounts
						acct.loginDisplayName = acct.originalLogin;
					} else {
						// Get the only calendar from this account and copy
						// its name into the loginDisplayName
						var template = new Template($L("#{calName} (#{loginName})"));
						var templateModel = {};
						templateModel.calName = calAcct.calendars[0].name;
						templateModel.loginName = acct.login;
						
						// For EAS accounts, remove the domain name from the login
	          if (acct.login.indexOf('\\') > 0) {
	            templateModel.loginName = acct.login.gsub(/.*\\/, '');
	          }
													
						acct.loginDisplayName =  template.evaluate(templateModel);
					}
				}
			} else {
				acct.loginDisplayName = acct.login;
			}
			
			// Setup account icon here
			if (acct.accountSpecificIcons) {
				acct.serviceIcon = getCalendarsManager().parseAcctIconString(acct.accountSpecificIcons);
			}
		});
	},
	
	getCalendarAccountsCallback: function(response) {
		//Mojo.Log.info('prefs-assistant: getCalendarSyncAccountsCallback');
		
		for(i=0;i<response.list.length;i++)
		{
				// NOTE: Account names to be localized are located in javascripts/accountLocalizations.js
				response.list[i].accountDisplayName = $L(response.list[i].accountDisplayName);
		}
		
		this.acctsModel.items = response.list;
		// Inject the loginDisplayName here...since for EAS we need to display
		// the domain of the account instead of the username
		this.updateEasAccountLoginDisplayNames();
		this.controller.modelChanged(this.acctsModel);
		
		// Find all the EAS accounts if there are any
		this.easAccountIds = null;
		this.acctsModel.items.each(function(acct){
			//Mojo.Log.info("acct domain %s", acct.domain);
			if (acct.domain == 'eas') {
				// Keep track of the list of eas accounts for Sync Accounts button
				if (this.easAccountIds == null) {
					this.easAccountIds = new Array();
				}
				this.easAccountIds.push(acct.accountId);
			}
		}, this);
	},
	
	renderDefaultCalendar: function() {
		var obj = {};
		
		var defaultCalId = getPrefsManager().getDefaultCalendar();
		if (defaultCalId != 0) {
			var defaultCalName = getCalendarsManager().getCalName("id"+defaultCalId);
			if(defaultCalName == "Palm Profile")
				defaultCalName = $L("Palm Profile");
		
			if (defaultCalName == undefined) {
				// The local calendar is the default
				obj.name = $L('Palm Profile');
			} else {
				obj.domain = getCalendarsManager().getCalSyncSource("id"+defaultCalId);
				obj.name = obj.domain;
				obj.login = defaultCalName;
			}
		} else {
			obj.name = $L('Palm Profile');
		}
		obj.serviceIcon = getCalendarsManager().getCalIcon("id"+defaultCalId);
		
		var html = Mojo.View.render({object: obj, template: 'prefs/prefs-defaultcal'});
		// Update the UI to reflect the default calendar name
		this.controller.get('pv_default_cal').update(html);
	},
	
	renderDefaultEventAlarm: function(timedAlarmStr, allDayAlarmStr) {
		//Mojo.Log.info('prefs-assistant: renderDefaultEventAlarm');
		var obj = {};
		
		// Timed Alarm
		this.controller.get('pv_default_evt_alarm_value').update(timedAlarmStr);
		
		// All Day Alarm
		this.controller.get('pv_default_allday_evt_alarm_value').update(allDayAlarmStr);
	},
	
	getCurrentAlarmString: function() {
		var index = 0;
		for (index = 0; index < this.alarms.size(); index++) {
			if (this.alarms[index].command == this.prefs.defaultEventReminder)
				return this.alarms[index].label;
		}
	},
	
	getCurrentAllDayAlarmString: function() {
		var index = 0;
		for (index = 0; index < this.alarms.size(); index++) {
			if (this.allDayAlarms[index].command == this.prefs.defaultAllDayEventReminder)
				return this.allDayAlarms[index].label;
		}
	},
	
	formatAlarmStringsCallback: function(response) {
		//Mojo.Log.info('prefs-assistant: formatAlarmStringsCallback');
		var index = 0;
		var currentTimedAlarmStr = "";
		var currentAllDayAlarmStr = "";
		
		
		for (index = 0; index < this.alarms.size() + this.allDayAlarms.size() - 1; index++) {
			alarmStr = response[index];
			
			if (index < numTimedAlarm) {
		  	if (this.alarms[index].command == this.prefs.defaultEventReminder) 
		  		currentTimedAlarmStr = alarmStr;
					if (index == 0) {
						if (this.allDayAlarms[index].command == this.prefs.defaultAllDayEventReminder)
							currentAllDayAlarmStr = alarmStr;
					}
		  }
			
			if (index >= numTimedAlarm) {
				if (this.allDayAlarms[index-(numTimedAlarm-1)].command == this.prefs.defaultAllDayEventReminder)
					currentAllDayAlarmStr = alarmStr;
			}
			
			if (index == 0) {
		  	this.alarms[index].label = alarmStr;
				this.allDayAlarms[index].label = alarmStr;
		  } else if (index < numTimedAlarm) {
				this.alarms[index].label = alarmStr;
			} else {
				this.allDayAlarms[index-(numTimedAlarm-1)].label = alarmStr;
			}
		};
		
		this.renderDefaultEventAlarm(currentTimedAlarmStr, currentAllDayAlarmStr);
	},
	
	buildAlarmsMenu: function() {
		//Mojo.Log.info('prefs-assistant: buildAlarmsMenu');
		var params =[this.alarms[0].command, 
					 this.alarms[1].command, 
					 this.alarms[2].command,
					 this.alarms[3].command, 
					 this.alarms[4].command,
					 this.alarms[5].command,
					 this.alarms[6].command,
				
									
					 this.allDayAlarms[1].command,
					 this.allDayAlarms[2].command,
					 this.allDayAlarms[3].command,
					 this.allDayAlarms[4].command];
		
		/*this.request = new Mojo.Service.Request(CalendarMojoService.identifier + '/formatter', {
			method: 'formatAlarmStrings',
			parameters: params,
			onSuccess: this.formatAlarmStringsCallback.bind(this)
		});*/
		this.formatAlarmStringsCallback(getFormatterService().getAlarmStrings(params));
		
		
	},
	
	currentCalendarUpdated: function() {
		// Do Nothing,
	},
	
	calendarPrefsUpdated: function() {
		//Mojo.Log.info("prefs-assistant: calendarPrefsUpdated");
		// This only gets called while the Prefs scene is up, when the user
		// has modified the default calendar setting.
		this.renderDefaultCalendar();
	},
	
	calendarSettingsUpdated: function() {
		// Do Nothing
	},
	
	convertSoundPopupToDBVal:function(val){
		console.error("*********convert soundPopup:"+val);
		switch(val){
			case "1":
			//vibrate
			 prefsVal =3;
			break;
			
			case "2":
			//System sound
			 prefsVal = 1;
			break;
			
			case "3":
			// Ringtone
			 prefsVal=2;
			break;
			
			case "4":
			//Mute
			 prefsVal=0;
			break;
			
			default:
			//system sound
			prefsVal =1;
			break;
		}
			console.error("***************prefsval :"+prefsVal);
		return prefsVal;
	},
	convertSoundDBToPopupVal:function(val){
		switch(val){
			case 0:
			//mute
			 popupVal =4;
			break;
			
			case 1:
			//System Sound
			 popupVal = 2;
			break;
			
			case 2:
			// Ringtone
			 popupVal =3;
			break;
			
			case 3:
			 //Vibrate
			 popupVal=1;
			break;
			
			default:
			//system sound
			popupVal =2;
			break;
		}
		console.error("***************popupval :"+popupVal);
		return popupVal;
	},
	
	chooseNotificationRingtone: function() {
    	var params = {
			actionType: "attach",
            defaultKind: 'ringtone',
			kinds: ["ringtone"],
			filePath: this.prefs.ringtonePath,
			actionName: $L("Done"),
	        onSelect: this.handleRingtoneSelect.bind(this)
	    };
	    Mojo.FilePicker.pickFile(params,this.controller.stageController);
		//this.handleRingtoneSelect.bind(this, {"fullPath": "/media/internal/ringtones/Discreet.mp3", "name": "Discreet"}).delay(1);
	},

	handleRingtoneSelect: function(file) {
		this.prefs.ringtonePath= file.fullPath,
		this.prefs.ringtoneName= file.name
		this.prefs.alarmSoundOn=3;
	
		this.controller.get('currentringtone').update(file.name);
		this.dirty=true;
	},
		
	calendarListUpdated: function() {
		//Mojo.Log.info("prefs-assistant: calendarListUpdated");
		// Sanity check the default calendar setting
		this.renderDefaultCalendar();
		// Reinject the loginDisplayName here...since for EAS we need to display
		// the domain of the account (calendar name) instead of the username.
		// calendarListUpdated is called when the EAS calendar is created, and
		// at that time we will have the name of the EAS calendar.
		this.updateEasAccountLoginDisplayNames();
		this.controller.modelChanged(this.acctsModel);
	},
	handleCommand:function(event){
		if (event.command == Mojo.Menu.helpCmd) {
			getAppManagerService().launchHelp(this.controller);
		}
	},
	
	setup: function() {
		// Retrieve the prefs from the service
		this.prefs = getPrefs();
		this.requests = [];
		this.syncSources = [];
		this.dirty = false;
		
		//Mojo.Log.info("prefs-assistant: setup");
		//Mojo.Log.info("prefs :%j" ,this.prefs);
		getCalendarsManager().observeCalendars('prefs', this);
		getPrefsManager().observeCalendarPrefs('prefs', this);
		
		this.renderDefaultCalendar();
		this.renderStartOfWeek();
		
		// new Date() will create a LOCAL time, so we need to adjust the time
		// to reflect UTC time
		var startTime = new Date(this.prefs.startTimeOfDay);
		startTime.addMinutes(startTime.getTimezoneOffset());
		var utcStartTime = startTime.getTime();
		this.startTimeModel = {
			time: new Date(utcStartTime),
		};
	    this.controller.setupWidget('pv_startofday_timepicker', {label: $L("Start")}, this.startTimeModel);
	    this.controller.listen('pv_startofday_timepicker',Mojo.Event.propertyChange, this.startOfDayCallback.bindAsEventListener(this));
		
		var endTime = new Date(this.prefs.endTimeOfDay);
		endTime.addMinutes(endTime.getTimezoneOffset());
		var utcEndTime = endTime.getTime();
		this.endTimeModel = {
			time: new Date(utcEndTime),
		};
	    this.controller.setupWidget('pv_endofday_timepicker', {label: $L("End")}, this.endTimeModel);
	    this.controller.listen('pv_endofday_timepicker',Mojo.Event.propertyChange, this.endOfDayCallback.bindAsEventListener(this));
				
		var soundSelections = {
      	modelProperty: 'value',
      	label: $L("Alert"),
      	choices: [
      		{label: $L('Vibrate'), value: "1"},
      		{label: $L('System Sound'), value: "2"},
			{label: $L('Ringtone'),value:"3"},
			{label: $L('Mute'),value:"4"}
      		]
      	};
	
		
		this.notificationSoundModel = {
        	value:this.convertSoundDBToPopupVal(this.prefs.alarmSoundOn)
      	};
		this.controller.setupWidget('notificationSoundSelector', soundSelections, this.notificationSoundModel);

		if(this.prefs.alarmSoundOn!=2)/* 2 from db is ringtone*/
		{
			this.controller.get('currentringtonerow').hide();
		}
		else 
			this.controller.get('currentringtone').update(this.prefs.ringtoneName);
		
	
		this.renderNewEventDuration();
	
		this.buildAlarmsMenu();
		
		this.controller.setupWidget('pv_accounts_list', this.acctsListAttrs, this.acctsModel);
		
		this.getCalendarAccountsRequest = getAccountsService().getAllAccountsForCalendarService(
		this.getCalendarAccountsCallback.bind(this), this.controller);
		
		
		this.appMenuModel= {
			visible:true, 
			label:$L('Calendar'), 
			items: [ Mojo.Menu.editItem,
					{label:$L('Preferences & Accounts'), command:Mojo.Menu.prefsCmd, disabled: true},
					{label:$L('Help'), command:Mojo.Menu.helpCmd, disabled:false}]
		}
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems:true}, this.appMenuModel);

				
	},

	setCalendarPrefsCallback: function(response) {
		//Mojo.Log.info("prefs-assistant:setCalendarPrefsCallback");
	},
	
	savePrefs: function() {
		//Mojo.Log.info("prefs-assistant:savePrefs, %j " ,this.prefs);
		this.requests.push(getCalendarService().setCalendarPrefs(
			this.prefs, this.setCalendarPrefsCallback.bind(this), this.controller));
	},
	
	cleanup: function() {
		//Mojo.Log.info("prefs-assistant:cleanup");
		getCalendarsManager().stopObservingCalendars('prefs');
		getPrefsManager().stopObservingCalendarPrefs('prefs');
		
		if (this.dirty)
			this.savePrefs();
	},
	
	syncAllCallback: function(response) {
		//Mojo.Log.info("prefs-assistant: syncAllCallback");
		// Show the banner
		Mojo.Controller.appController.showBanner({
			messageText: $L("Syncing accounts")},
			null /*launchArguments*/,
			"calendar-sync-all");
	},
	
	handleSyncAccountsBtnTap: function(event) {
		// Retrieve the list of eas accounts if any
		getPimSyncService().syncAll(this.controller, this.easAccountIds, this.syncAllCallback.bind(this));
	},
	
	handleAddAccountBtnTap: function(event) {
		this.controller.stageController.pushScene("choosetransport");
	},
	
	activate: function() {
		//Mojo.Log.info('prefs-assistant: activate');
		getPrefsManager().validateDefaultCalPref();
		
		this.startOfWeekClickHandler = this.handleStartOfWeekClick.bindAsEventListener(this);
		this.controller.get('pv_start_of_week').observe('mojo-tap', this.startOfWeekClickHandler);
		
		this.defaultEventAlarmClickHandler = this.handleDefaultEventAlarmClick.bindAsEventListener(this);
		this.controller.get('pv_default_evt_alarm').observe('mojo-tap', this.defaultEventAlarmClickHandler);
		this.defaultAllDayEventAlarmClickHandler = this.handleDefaultAllDayEventAlarmClick.bindAsEventListener(this);
		this.controller.get('pv_default_allday_evt_alarm').observe('mojo-tap', this.defaultAllDayEventAlarmClickHandler);
				
		this.newEventDurationClickHandler = this.handleNewEventDurationClick.bindAsEventListener(this);
		this.controller.get('pv_new_event_duration').observe('mojo-tap', this.newEventDurationClickHandler);	
	
		this.acctsListSelectionHandler = this.handleAcctsListSelection.bindAsEventListener(this);
		this.controller.get('pv_accounts_list').observe(Mojo.Event.listTap, this.acctsListSelectionHandler);
		
		this.defaultCalClickHandler = this.handleDefaultCalClick.bindAsEventListener(this);
		this.controller.get('pv_default_cal').observe('mojo-tap', this.defaultCalClickHandler);
		
		this.syncAccountsBtnTapHandler = this.handleSyncAccountsBtnTap.bindAsEventListener(this);
		this.controller.get('pv_sync_accounts_btn').observe('mojo-tap', this.syncAccountsBtnTapHandler);
		
		this.addAccountBtnTapHandler = this.handleAddAccountBtnTap.bindAsEventListener(this);
		this.controller.get('pv_add_account_btn').observe('mojo-tap', this.addAccountBtnTapHandler);
		
		this.viewOptionsBtnTapHandler = this.handleViewOptionBtnTap.bindAsEventListener(this);
		this.controller.get('pv_view_option_btn').observe('mojo-tap', this.viewOptionsBtnTapHandler);
		
		this.notificationSoundChanged = this.chooseAlarmType.bindAsEventListener(this);
	 	this.controller.listen('notificationSoundSelector',Mojo.Event.propertyChange,this.notificationSoundChanged);
		
		this.chooseNotificationRingtone = this.chooseNotificationRingtone.bindAsEventListener(this);
		this.controller.listen('currentringtonerow',Mojo.Event.tap, this.chooseNotificationRingtone);		


	},
	
	handleViewOptionBtnTap :function(){
		
		this.controller.stageController.pushScene("prefs-options",this.acctsModel);
	},
	
	deactivate: function() {
		//Mojo.Log.info('prefs-assistant: deactivate');
		this.controller.get('pv_start_of_week').stopObserving('mojo-tap', this.startOfWeekClickHandler);
		
		this.controller.get('pv_default_evt_alarm').stopObserving('mojo-tap', this.defaultEventAlarmClickHandler);
		this.defaultEventAlarmClickHandler = undefined;
		this.controller.get('pv_default_allday_evt_alarm').stopObserving('mojo-tap', this.defaultAllDayEventAlarmClickHandler);
		this.defaultAllDayEventAlarmClickHandler = undefined;
		
		this.controller.get('pv_new_event_duration').stopObserving('mojo-tap', this.newEventDurationClickHandler);
		
		this.controller.get('pv_accounts_list').stopObserving(Mojo.Event.listTap, this.acctsListSelectionHandler);
		
		this.controller.get('pv_default_cal').stopObserving('mojo-tap', this.defaultCalClickHandler);
		
		this.controller.get('pv_sync_accounts_btn').stopObserving('mojo-tap', this.syncAccountsBtnTapHandler);
		
		this.controller.get('pv_add_account_btn').stopObserving('mojo-tap', this.addAccountBtnTapHandler);
		
		this.controller.get('pv_view_option_btn').stopObserving('mojo-tap', this.viewOptionsBtnTapHandler);
		
	 	this.controller.stopListening('notificationSoundSelector',Mojo.Event.propertyChange,this.notificationSoundChanged);
		
		this.controller.stopListening('currentringtonerow',Mojo.Event.tap, this.chooseNotificationRingtone);		

	},
	
	// *** EVENT HANDLERS ***
	
	handleDefaultCalClick: function(event) {
		//Mojo.Log.info("prefs-assistant: handleDefaultCalClick");
		Event.stop(event);
    var items = buildCalendarsMenu(false /*includeAll*/, false /*includeReadOnly*/, false /*includeExcludedFromAll*/);
 
    this.controller.popupSubmenu({
        onChoose: this.calendarChoose.bind(this),
    		toggleCmd: getPrefsManager().getDefaultCalendar(), 
        placeNear: event.target,
        items: items
    });
	},
	
	calendarChoose: function(value) {
		if (value != undefined && value) {
			
			this.prefs.defaultCalId = value;
			
			// save this pref now... the change takes effect immediately since
			// if the user tries to add an account, the defaultCalId must be up to date
			// in order for getDefaultCalendar to work properly.
			this.savePrefs();
			this.dirty = false;
			
			// The render is called when the prefs is successfully saved, and the
			// scene is notified that the prefs have changed
			//this.renderDefaultCalendar();
		}
	},
	
	handleAcctsListSelection: function(event) {
		var id = event.item.accountId;
		Event.stop(event);
		// Get the login and domain
		var login = "";
		var domain = "";
		var name = "";
		var folderid = "";
		var isCrudAccount = "";
		this.acctsModel.items.each(function(acct){
			if (acct.accountId == id) {
				domain = acct.domain;
				name = acct.accountDisplayName;
				login = acct.login;
				folderid = acct.id;
				serviceIcon = acct.serviceIcon;
				isCrudAccount = acct.isCrudAccount;
			}
		});
		// we dont have to show anything for 
		//PalmLocal accounts
		if(domain=="local")
			return;
		
		this.controller.stageController.pushScene("accountlogin", 
														id, 
														login,
														0 /*acctTypeId*/,
														serviceIcon /*acctIcon*/, 
														name, 
														undefined /*sceneToReturnTo*/,
														domain);
		
		//Mojo.Log.info("prefs-assistant: handleAcctsListSelection %s " , id);
		//this.controller.stageController.pushScene('prefs-acct', id, domain, name, login, folderid, serviceIcon, isCrudAccount);
	},
	
	startOfWeekChoose: function(val) {
		//Mojo.Log.info('prefs-assistant: startOfWeekChoose: %s', val);
		var value = parseInt(val);
		if (val != undefined && value != this.prefs.startOfWeek) {
			this.prefs.startOfWeek = value ;
			this.prefs.userChangedstartOfWeek =true;
			this.renderStartOfWeek();
			this.dirty = true;
		}
	},
	
	handleStartOfWeekClick: function(event) {
		//Mojo.Log.info('prefs-assistant: handleStartOfWeekClick');
		var sowDate = new Date().moveToDayOfWeek(0);
		Event.stop(event);
		this.controller.popupSubmenu({
				onChoose: this.startOfWeekChoose.bind(this),
				toggleCmd: this.prefs.startOfWeek ,
				items: [{
					label: Mojo.Format.formatDate(sowDate, 'EEEE'),
					command: 1
				}, {
					label: Mojo.Format.formatDate(sowDate.addDays(1), 'EEEE'),
					command: 2
				}, {
					label: Mojo.Format.formatDate(sowDate.addDays(1), 'EEEE'),
					command: 3
				}, {
					label: Mojo.Format.formatDate(sowDate.addDays(1), 'EEEE'),
					command: 4
				}, {
					label: Mojo.Format.formatDate(sowDate.addDays(1), 'EEEE'),
					command: 5
				}, {
					label: Mojo.Format.formatDate(sowDate.addDays(1), 'EEEE'),
					command: 6
				}, {
					label: Mojo.Format.formatDate(sowDate.addDays(1), 'EEEE'),
					command: 7
				}]
			});
	},
	
	newEventDurationChoose: function(value) {
		//Mojo.Log.info('prefs-assistant: newEventDurationChoose');
		if (value != undefined && value != this.prefs.defaultEventDuration) {
			this.prefs.defaultEventDuration = value;
			this.renderNewEventDuration();
			this.dirty = true;
		}
	},
	
	handleNewEventDurationClick: function(event) {
		//Mojo.Log.info('prefs-assistant: handleNewEventDurationClick');
		Event.stop(event);
		this.controller.popupSubmenu({
				onChoose: this.newEventDurationChoose.bind(this),
				toggleCmd: this.prefs.defaultEventDuration,
				items: [{
					label: THIRTY_MINUTES,
					command: 30
				}, {
					label: ONE_HOUR,
					command: 60
				}, {
					label: TWO_HOURS,
					command: 120
				}]
			});
	},
	
	defaultEventAlarmChoose: function(value) {
		//Mojo.Log.info('prefs-assistant: defaultEventAlarmChoose');
		if (value != undefined && value != this.prefs.defaultEventReminder) {
			this.prefs.defaultEventReminder = value;
			this.renderDefaultEventAlarm(this.getCurrentAlarmString(), this.getCurrentAllDayAlarmString());
			this.dirty = true;
		}
	},
	
	handleDefaultEventAlarmClick: function(event) {
		//Mojo.Log.info('prefs-assistant: handleDefaultEventAlarmClick');
				
		Event.stop(event);
		this.controller.popupSubmenu({
				onChoose: this.defaultEventAlarmChoose.bind(this),
				toggleCmd: this.prefs.defaultEventReminder,
				items: this.alarms
			});
	},
	
	defaultAllDayEventAlarmChoose: function(value) {
		//Mojo.Log.info('prefs-assistant: defaultAllDayEventAlarmChoose');
		if (value != undefined && value != this.prefs.defaultAllDayEventReminder) {
			this.prefs.defaultAllDayEventReminder = value;
			this.renderDefaultEventAlarm(this.getCurrentAlarmString(), this.getCurrentAllDayAlarmString());
			this.dirty = true;
		}
	},
	
	handleDefaultAllDayEventAlarmClick: function(event) {
		//Mojo.Log.info('prefs-assistant: handleAllDayDefaultEventAlarmClick');
				
		Event.stop(event);
		this.controller.popupSubmenu({
				onChoose: this.defaultAllDayEventAlarmChoose.bind(this),
				toggleCmd: this.prefs.defaultAllDayEventReminder,
				items: this.allDayAlarms
			});
	},
	
	// *** WIDGET ATTRS & MODELS

	
	acctsListAttrs : {
		itemTemplate: 'prefs/prefs-account',
		listTemplate: 'shared/group_container',
	},
	
	acctsModel : {
		listTitle: $L('Accounts'),
		items: [],
	},
	
	alarms: [
		{label: '', command: 'none'},			// Do NOT Localize
		{label: '', command: '-PT5M'},		//Do Not localize
		{label: '', command: '-PT10M'},		//Do Not localize
		{label: '', command: '-PT15M'},		// Do NOT Localize
		{label: '', command: '-PT30M'},		// Do NOT Localize
		{label: '', command: '-PT1H'},		// Do NOT Localize
		{label: '', command: '-P1D'}			// Do NOT Localize	
	],
	
	allDayAlarms: [
		{label: '', command: 'none'},			// Do NOT Localize
		{label: '', command: '-P1D'},			// Do NOT Localize
		{label: '', command: '-P2D'},			// Do NOT Localize
		{label: '', command: '-P3D'},			// Do NOT Localize
		{label: '', command: '-P1W'}			// Do NOT Localize		
	]
});