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

var AlarmsAssistant = Class.create({
	menuToggleModel : [ {label: $L('Add'),icon:'new', command:'cmdAdd'},{label: $L('Alarms/Clock'), toggleCmd:'cmdAlarms',items:[{}, 
									{label: $L('Clock'), iconPath:'images/menu-icon-clock.png', command:'cmdClock'},{label: $L('Alarms'), iconPath:'images/menu-icon-alarm.png', command:'cmdAlarms'}
								]},{},{label: $L('Add'),icon:'new', command:'cmdAdd', template:'alarms/nothing'}
							],
	initialize: function(params) {
		this.appControl = Mojo.Controller.getAppController();
		this.appAssistant = this.appControl.assistant;
		
		this.refreshAlarms();
		
		this.poppedToID = false;
		
		if (params) {
			this.launchAlarmId = params.alarmId;
			this.settings = params.settings;
			this.themes = params.themes;
			this.onThemeChange = params.onThemeChange;
		}
		
		//console.log(alarms.transition);
		
		
	},
	
	refreshAlarms: function() {
		this.alarmsModelManager = this.appAssistant.alarms;
		this.alarms = this.alarmsModelManager.alarms;
		
		if (this.alarmsModel) {
			this.alarmsModel.items = this.alarms;
			this.controller.modelChanged(this.alarmsModel, this);
		}
	},

	setup: function() {
		//this.controller.document.body.removeClassName("clockview");
		this.alarmsModel = {listTitle:$L('Alarms'), items:this.alarms};
		this.alarmsListAttrs = {
				listTemplate:'alarms/list-container', 
				itemTemplate:'alarms/list-item',
				//addItemLabel:$L("Add..."),
				swipeToDelete:true,
				autoconfirmDelete:false,
				deletedProperty: 'swiped',
				formatters: { "occurs" : this.occursLocalizer.bind(this)}
				
			};
		this.controller.setupWidget('alarmsList', this.alarmsListAttrs, this.alarmsModel);
		this.controller.listen('alarmsList', Mojo.Event.listTap, this.listTapHandler.bindAsEventListener(this));
		//this.controller.listen('alarmsList', Mojo.Event.listAdd, this.listAddHandler.bindAsEventListener(this));
		this.controller.listen('alarmsList', Mojo.Event.listDelete, this.listDeleteHandler.bindAsEventListener(this));
		var appMenuModel = {
			visible: true,
			items: [
				//{label: $L('Preferences'), command:'cmdSettings'},
				Mojo.Menu.editItem,
				{label: $L('Preferences'), command:'cmdSettings', disabled:false},
				{label:$L('Help'), command:Mojo.Menu.helpCmd, disabled:false}
			]
		};
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, appMenuModel);
		
		this.cmdMenuModel = { label: $L('Add'), visible:true,
								items: this.menuToggleModel};
		this.controller.setupWidget(Mojo.Menu.commandMenu, undefined, this.cmdMenuModel);
		
		this.controller.setupWidget('alarmToggle', {'modelProperty':'enabled'} );
		this.controller.listen('alarmsList', Mojo.Event.propertyChanged, this.toggleAlarm.bindAsEventListener(this));
		
		if (this.launchAlarmId !== undefined) {
			this.openAlarm(this.launchAlarmId);
			this.launchAlarmId = undefined;
		}
	},
	
	openAlarm: function(id) {
		this.poppedToID = id;
		this.controller.stageController.pushScene("alarm", id, this.deleteSentAlarm.curry(id).bind(this));
	},
	
	occursLocalizer: function(occurs, model) {
		model.formattedOccurs = Alarms.localizedOccurs[occurs] || occurs
	},
	
	handleCommand: function(event) {
		if (event.type == Mojo.Event.command) {
			switch (event.command) {
				case ('cmdSettings'):
					this.controller.stageController.pushScene("settings", this.settings,this.themes, this.onThemeChange.bind(this));
					break;
				case ('cmdAdd'):
					this.listAddHandler();
					break;
				case ('cmdClock'):
				    //this.timeoutID = this.controller.window.setTimeout(this.gotaClock.bind(this), 1000);
					this.controller.stageController.popScene(null,{transition:Mojo.Transition.crossFade});
					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;
			}
		// ignore back
		} else if (event.type == Mojo.Event.back) {
			event.stopPropagation();
			// Event.stop(event);
		}		
	},
	
	toggleAlarm: function(event){
		event.model.alarmSet(event.model.enabled, event.model.time, this.onAlarmSet.bind(this) );
	},
	
	onAlarmSet: function() {
		//console.log('model updated');
		this.controller.modelChanged(this.alarmsModel, this);
		this.appAssistant.updateAlarmDashboard();
	},
	
	cleanup: function() {
		//this.controller.document.body.addClassName("clockview");
	},
	
	listDeleteHandler: function(event) {
		//console.log("this is "+ event.item.id);
		this.alarmsModelManager.deleteAlarm(event.item);
		if(event.forwardedFromTapHandler){
			this.controller.modelChanged(this.alarmsModel, this);
		}
		//this.controller.modelChanged(this.alarmsModel, this);
		//Remove the item from the model's list.
		//event.model.items.splice(event.model.items.indexOf(event.item), 1);
		this.appAssistant.updateAlarmDashboard();
		
	},
	
	deleteSentAlarm: function(id){
		var alarm = this.alarmsModelManager.findAlarmByID(id);
		this.alarmsModelManager.deleteAlarm(alarm);
		this.controller.modelChanged(this.alarmsModel, this);
		this.appAssistant.updateAlarmDashboard();
	},
	
	listTapHandler: function(event) {
		if(Element.hasClassName(event.originalEvent.target, 'list-item-remove-button')) {
			event.forwardedFromTapHandler = true;
			this.listDeleteHandler(event);
			
		}else{
			var alarm = event.item;
			this.openAlarm(alarm.id);
		}
		
	},
	
	gotaClock: function(){
		this.controller.stageController.popScene(null,{transition:Mojo.Transition.crossFade});
	},
	
	activate: function(){
		if (this.controller.stageController.setWindowOrientation) {
			
			this.controller.stageController.setWindowOrientation('free');
			//console.log('alarms set to free');
			//console.log(this.controller.stageController.getWindowOrientation());
		}
		if(this.poppedToID !== false){		
			//console.log('reactivated with id '+ this.poppedToID);
			this.controller.modelChanged(this.alarmsModel, this);
		}
	},
	
	deactivate: function(){
		//force to alarm toggle
		this.cmdMenuModel.items[1].toggleCmd = 'cmdAlarms';
		this.controller.modelChanged(this.cmdMenuModel);
		this.alarmsModelManager.saveAlarms();
	},
	
	listAddHandler: function(event) {
		var newAlarm = this.alarmsModelManager.addAlarm(this.alarmsModelManager.alarms.length);
		this.controller.modelChanged(this.alarmsModel, this);
		this.openAlarm(newAlarm.id);
	}

});