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

var AlarmAssistant = Class.create({
	statuses: [   
	    {label:$L('Ring Once'), value:"once"},
		{label:$L('Daily'), value:"daily" },
		{label:$L('Weekdays'), value:"weekdays"}, 
		{label:$L('Weekends'), value:"weekends"} 
	],
	initialize: function(alarm, deleteSelf) {
		this.appControl = Mojo.Controller.getAppController();
		this.appAssistant = this.appControl.assistant;
		
		this.deleteSelf = deleteSelf;
		this.alarm = this.appAssistant.alarms.findAlarmByID(alarm);
		this.alarmModel = {};
		this.updateAlarmModel();
		this.settings = this.appAssistant.settings;
		
		this.settingsChanged = this.settingsChanged.bindAsEventListener(this);
		this.onAlarmSet = this.onAlarmSet.bind(this);
		
		this.setAlarmSound = this.setAlarmSound.bindAsEventListener(this);
		this.onAlarmSoundSet = this.onAlarmSoundSet.bind(this);
	},
	
	// copies alarm properties from model to UI's model
	// we maintain the alarm properties in a separate object to handle the possibility
	// that alarm setting is unsuccessful
	updateAlarmModel: function() {
		this.appAssistant.updateAlarmDashboard();
		this.alarmModel.enabled = this.alarm.enabled;
		this.alarmModel.time = this.alarm.time;
		this.alarmModel.title = this.alarm.title;
	},
	
	setup: function() {

		////this.controller.document.body.removeClassName("clockview");
		this.timePickerAttributes = {
			minuteInterval: this.settings.timePickerIntervalGet(),
			modelProperty: "time",
			label: $L("Time")
		};
		this.controller.setupWidget('time', this.timePickerAttributes, this.alarmModel);
		this.controller.listen('time', Mojo.Event.propertyChange, this.settingsChanged);
		
		this.alarmToggleAttributes = {
			modelProperty: "enabled",
		};
		this.controller.setupWidget('alarmToggle', this.alarmToggleAttributes, this.alarmModel);
		this.controller.listen('alarmToggle', Mojo.Event.propertyChange, this.settingsChanged);
		
		var appMenuModel = {
			visible: true,
			items: [
				Mojo.Menu.editItem,
				{label: $L('Preferences'), command:'cmdThemes', disabled:true},
				{label:$L('Help'), command:Mojo.Menu.helpCmd, disabled:false}
			]
		};
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, appMenuModel);
		
		// load alarm sound title into row
		this.alarmSoundTitleSet(this.alarm.alarmSoundTitle)
		//this.controller.document.body.removeClassName("clockview");
		this.controller.get('alarmsound_set').observe(Mojo.Event.tap, this.setAlarmSound);
		
		this.nameModelAttributes = {
			hintText: $L('Enter Name...'),
			modelProperty: 'value',
			textReplacement: false,
			acceptBack: true,
			autoFocus: false,
			multiline: false,
			focusMode: Mojo.Widget.focusInsertMode
		};
		this.nameModel = {
			'value' : this.alarmModel.title,
			disabled: false
		};
		this.controller.setupWidget('alarm_name', this.nameModelAttributes, this.nameModel);
		this.controller.listen('alarm_name', Mojo.Event.propertyChange, this.changeNameHandler.bindAsEventListener(this));
		
		this.cmdMenuModel = { label: $L('Delete'), visible:true,
								items: [{},{label: $L('Delete'), icon:'delete', command:'cmdDelete'}]};
		this.controller.setupWidget(Mojo.Menu.commandMenu, undefined, this.cmdMenuModel);
		
		this.selectorsModel={currentStatus: this.alarm.occurs};
		this.controller.setupWidget('frequency', {label: $L('Occurs'), choices: this.statuses, modelProperty:'currentStatus'}, this.selectorsModel);
		this.controller.listen('frequency', Mojo.Event.propertyChange, this.selectorChanged.bindAsEventListener(this));
		
	},
	
	handleCommand: function(event) {
		if (event.type == Mojo.Event.command) {
			switch (event.command) {
				case ('cmdDelete'):
					this.deleteSelf();
					this.controller.stageController.popScene();
					break;
				case (Mojo.Menu.helpCmd):
					this.controller.serviceRequest("palm://com.palm.applicationManager", {
					  method: "open",
					  parameters: {
					      id: 'com.palm.app.help',
					      params: {
					          target: "http://help.palm.com/clock/index.html"
					      }
					  }
					});
					break;
			}
		}		
	},
	
	selectorChanged: function(e){
		this.alarm.saveOccurance(e.value);
		this.settingsChanged();
	},
	
	activate: function(){
		if (this.controller.stageController.setWindowOrientation) {
			this.controller.stageController.setWindowOrientation('free');
			//console.log('alarm set to up');
			//console.log(this.controller.stageController.getWindowOrientation());
		}
		if(!this.alarm.newAlarm){
			//dont focus the textfield
			this.controller.setInitialFocusedElement(null); 
		}
	},
	
	deactivate: function(){
		//console.log("saving alarm then deactivate");
		this.alarm.settingsCookieSave();
		if(this.alarm.newAlarm){
			this.alarm.newAlarm = false;
		}
		if (this.controller.stageController.setWindowOrientation) {
			this.controller.stageController.setWindowOrientation('free');
			//console.log('alarm set to free');
			//console.log(this.controller.stageController.getWindowOrientation());
		}
	},
	
	changeNameHandler: function(e){
		this.alarm.saveTitle(e.value);
		this.updateAlarmModel();
		this.controller.modelChanged(this.alarmModel, this);
	},
	
	// anytime something in the UI changes, attempt to change alarm settings
	// call onAlarmSet to update results
	settingsChanged: function() {
		this.alarm.alarmSet(this.alarmModel.enabled, this.alarmModel.time, this.onAlarmSet);
	},
	
	// in case setting the alarm failed, reload settings from alarms object, and update UI
	onAlarmSet: function() {
		//console.log('model updated');
		this.updateAlarmModel(); 
		this.controller.modelChanged(this.alarmModel);
	},
	
	//functions copied from settings
	
	// opens ringtone picker.  users can pick a ringtone to use as alarm sound
	// or grab a sound file from the music library
	setAlarmSound: function() {
		Mojo.FilePicker.pickFile({
			"kinds": ["ringtone"],
			"filePath":this.alarm.alarmSoundTitle,
			"onSelect":this.onAlarmSoundSet,
			"actionType":"attach",
			"actionName": $L("Done")
		}, this.controller.stageController);
	},
	
	// filepicker calls this after user selects a sond	
	onAlarmSoundSet: function(file) {
		if (file && file.fullPath) {
			// file.name is actually the name we show in the UI, not the 
			// filename
			// if we didn't get a name, fall back to the path
			if (!file.name) {
				file.name = file.fullPath;
			}
			this.alarm.alarmSoundSet(file.fullPath, file.name);
			
			this.alarmSoundTitleSet(file.name);
		}
	},
	
	alarmSoundTitleSet: function(title) {
		this.controller.get('alarmsound_title').textContent = title;
	},
	
	
});