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

var ClockAssistant = Class.create({
	menuToggleModel : [ {label: $L('Alarms/Clock'), toggleCmd:'cmdClock1',items:[{}, 
									{label: $L('Clock'), iconPath:'images/menu-icon-clock.png', command:'cmdClock1'},{label: $L('Alarms'), iconPath:'images/menu-icon-alarm.png', command:'cmdAlarms1'}
								]},{}
							],
	initialize: function(sceneParams) {
		Mojo.Log.info("clock assistant initializing")
		
		this.upright = true;
		this.appAssistant = Mojo.Controller.appController.assistant;
		this.settings = this.appAssistant.settings;
		this.themes = this.appAssistant.themes;
		this.stageActive = true;
		
		this.sceneParams = sceneParams;
		/*
		this.pucked = false;
		this.musicModeActive = false;
			
		this.musicAppId = 'com.palm.app.musicplayer';
		this.musicAppParamsPlay = {play: true};
		this.musicAppParamsPause = {pause: true};

		this.onPuckEvent = this.onPuckEvent.bind(this);
		
		this.puckSubscription = this.puckStatusSubscribe(this.onPuckEvent);
		this.puckStatusQuery();
		*/
	},
	
	setup: function() {
		//console.dir(this.controller);
		var body = Element.select(this.controller.document, 'body');
		body[0].addClassName('palm-dark');
		body[0].removeClassName('palm-default');
		
		this.clockContainer = this.controller.get("clock-container");
		//get the current theme and install it
		this.currentTheme = this.themes.getCurrentTheme();
		
		//this.controller.document.body.addClassName("clockview");
		
		// add ringtone menu item
		var appMenuModel = {
			visible: true,
			items: [
				Mojo.Menu.editItem,
				{label: $L('Preferences'), command:'cmdSettings'},
				{label:$L('Help'), command:Mojo.Menu.helpCmd, disabled:false}
			]
		};
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, appMenuModel);
				
		this.cmdMenuModel = { visible: true, items: this.menuToggleModel };
								
		this.controller.setupWidget(Mojo.Menu.commandMenu, undefined, this.cmdMenuModel);
		
		this.controller.listen('clock-container', Mojo.Event.tap, this.showHide.bindAsEventListener(this));

		this.changeTheme(this.currentTheme.name);
		
		this.disableSceneScroller();
		
		//slow down the clock when deactivated
		this.firstActivation = true;
		this.controller.listen(this.controller.sceneElement, Mojo.Event.stageActivate, this.stageActivateHandler.bindAsEventListener(this));
		this.controller.listen(this.controller.sceneElement, Mojo.Event.stageDeactivate, this.stageDeactivateHandler.bindAsEventListener(this));
		
		if (this.sceneParams) {
			this.showScene(this.sceneParams);
			this.sceneParams = undefined;
		}
		
		// add class with locale identifier to body
		this.controller.document.body.addClassName(Mojo.Locale.getCurrentLocale());
	},
	
	showScene: function(params) {
		var sceneParams = { 
			settings: this.settings,
			themes: this.themes,
		}
		
		sceneParams.onThemeChange = this.changeTheme.bind(this);
		if (params && params.scene !== "list") {
			sceneParams.alarmId = params.alarmId;
		}
		
		this.controller.stageController.pushScene({name:"alarms",transition:Mojo.Transition.crossFade}, sceneParams);
	},
	
	stageActivateHandler: function(event){
		//return to normal operation
		this.stageActive = true;
		this.controller.window.clearInterval(this.updateClockTimeout);
		this.updateClock({slow:false});
		this.updateClockTimeout = this.controller.window.setInterval(this.updateClock, this.currentTheme.interval);
		
		//show the command menu after 1/2 a second to prevent the change from card view to scene view from slowing down
		this.controller.window.clearTimeout(this.stageActivationTimeout);
		this.stageActivationTimeout = this.controller.window.setTimeout(function(){
			if(this.stageActive)this.controller.setMenuVisible(Mojo.Menu.commandMenu,true);
		}.bind(this), 500);
	},
	
	stageDeactivateHandler: function(event){
		//slow down the clock
		this.stageActive = false;
		this.controller.window.clearInterval(this.updateClockTimeout);
		this.updateClock({slow:true});
		this.updateClockTimeout = this.controller.window.setInterval(this.updateClock, this.currentTheme.interval * 60);
		
		this.controller.window.clearTimeout(this.stageDeactivationTimeout);
		this.stageDeactivationTimeout = this.controller.window.setTimeout(function(){
			if(!this.stageActive)this.controller.setMenuVisible(Mojo.Menu.commandMenu,false);
		}.bind(this), 10);
	},
	
	/*
	 * Disable the scene scroller to prevent the web view from scrolling underneath whatever is being displayed on top of it
	 */
	disableSceneScroller : function() {
		this.controller.listen(this.controller.sceneElement, Mojo.Event.dragStart, this._dragStartHandler);
		this.controller.listen(this.controller.sceneElement, Mojo.Event.dragging, this._draggingHandler);
		this.controller.listen(this.controller.sceneElement, Mojo.Event.dragEnd, this._dragEndHandler);
	},
	/*
	 * Enable the scene scroller (everything back to normal)
	 */
	enableSceneScroller : function() {
		this.controller.stopListening(this.controller.sceneElement, Mojo.Event.dragStart, this._dragStartHandler);
		//this.controller.stopListening(this.controller.sceneElement, Mojo.Event.dragging, this._draggingHandler);
		this.controller.stopListening(this.controller.sceneElement, Mojo.Event.dragEnd, this._dragEndHandler);
	},
	/** @private */
	_dragStartHandler: function(event) {
		// console.log(event.timeStamp);
		// console.dir(event);
		//this.clockContainer.absolutize();
		// prevents the scene from scrolling.
		event.stop();
	},
	
	_draggingHandler: function(event) {
		//console.log(event.timeStamp);
		//console.dir(event);
		//console.log(event.distance.x + " " + event.distance.y);
		//var x = event.move.pageX;
		//console.log(x);
		//console.log(this.clockContainer.getStyle('left'));
		//this.clockContainer.setStyle({'left':x+'px'});
		//console.log(this.clockContainer.getStyle('left'));
		// prevents the scene from scrolling.
		// Mojo.Animation.animateStyle(this.clockContainer, 'left', 'linear', {
		// 			from: x,
		// 			to: event.distance.x,
		// 			duration: .25
		// 		}
		// );
		event.stop();
	},
	
	_dragEndHandler: function(event) {
		// console.log(event.timeStamp);
		// console.dir(event);
		//this.clockContainer.();
		// prevents the scene from scrolling.
		event.stop();
	},
	
	moveBackToCenter: function(){
		
	},
	
	showHide: function(event) {
		if(!this.upright){
			this.controller.toggleMenuVisible(Mojo.Menu.commandMenu);
		}
		
		// //console.log()
		// this.controller.toggleMenuVisible(Mojo.Menu.commandMenu);
		// if(this.cmdMenuModel.visible){
		// 	if(this.timeoutID){
		// 		this.controller.window.clearTimeout(this.timeoutID);
		// 		delete this.timeoutID;
		// 	}
		// 	this.timeoutID = this.controller.window.setTimeout(this.showHide.bind(this), 7000);
		// }
	},
	
	aboutToActivate: function(){
		if(this.firstActivation){
			this.firstActivation = false;
		}else{
			this.stageActivateHandler();
		}
	},
	
	activate: function(){
		// if(this.cmdMenuModel.visible){
		// 	if(this.timeoutID){
		// 		this.controller.window.clearTimeout(this.timeoutID);
		// 		delete this.timeoutID;
		// 	}
		// 	this.timeoutID = this.controller.window.setTimeout(this.showHide.bind(this), 7000);
		// }else{
		// 	this.showHide();
		// }
		if (this.controller.stageController.setWindowOrientation) {
			this.controller.stageController.setWindowOrientation('free');
			this.stageActive = true;
			//console.log('clock set to free');
			//console.log(this.controller.stageController.getWindowOrientation());
		}

	},
	
	deactivate: function(){
		//force to clock toggle
		this.cmdMenuModel.items[0].toggleCmd = 'cmdClock1';
		this.controller.modelChanged(this.cmdMenuModel);
		this.stageDeactivateHandler();
	},
	
	changeTheme: function(theme) {
		
		//temporarily stop the clock
		this.controller.window.clearInterval(this.updateClockTimeout);
		delete this.updateClock;
		//remove the old style sheet
		function match(url,link){
			if(link.href.endsWith(url)){
				//console.log("match on "+url+" = "+link.href);
				return link;
			}else{
				return false;
			}
		}
		var h = Element.select(this.controller.document, 'link');
		var theLink = h.find(match.curry(this.currentTheme.css));
		if(theLink)theLink.disabled = true;
		
		//get the new theme
		this.currentTheme = this.themes.getTheme(theme);
		//load the required css for the template
		
		//check to see if the stylesheet is already loaded before we reload it
		theLink = h.find(match.curry(this.currentTheme.css));
		if(theLink && theLink.disabled == true){
			theLink.disabled = false;
		}else{
			Mojo.loadStylesheet(this.controller.document,this.currentTheme.css);
			
		}
		
		//load the template into the clock container
		this.clockContainer.update(this.currentTheme.scene);
		//load the theme update clock function
		this.currentTheme.setup(this.controller);
		this.updateClock = this.currentTheme.updateTime.bind(this);
		this.updateClock({'setup':true});
		this.updateClockTimeout = this.controller.window.setInterval(this.updateClock, this.currentTheme.interval);
	},
	
	cleanup: function() {
		Mojo.Log.info("clock going away");
		clearTimeout(this.updateClockTimeout);
		this.updateClockTimeout = undefined;
	},
	
	handleCommand: function(event) {
		if (event.type == Mojo.Event.command) {
			switch (event.command) {
				case ('cmdSettings'):
					this.controller.stageController.pushScene("settings", this.settings,this.themes, this.changeTheme.bind(this));
					break;
				case ('cmdAlarms1'):
					this.showScene();
					break;
				case ('cmdAlarm'):
//					this.controller.stageController.pushScene("alarm", this.alarm);
					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;
			}
		}			
	},
	
	// called when device's orientation moves to a new 90-degree position
	// passes off to handlers for portrait or landscape orientation
	orientationChanged: function(orientation) {  	// only virtually possible.
		Mojo.Log.info("now swinging: " + orientation);
		this.orientation = orientation;
		
		if (orientation == "up" || orientation == "down") {
			if (!this.upright) {
				this.upright = true;
				this.handleOrientationUpright();
				//this.controller.toggleMenuVisible(Mojo.Menu.commandMenu);
				if(this.stageActive)this.controller.setMenuVisible(Mojo.Menu.commandMenu,true);
			}
		} else if (orientation == "left" || orientation == "right") {
			if (this.upright) {
				this.upright = false;
				this.handleOrientationSideways();
				this.controller.setMenuVisible(Mojo.Menu.commandMenu,false);
			}
		}
	},
	
	// called when orientation is changed to portrait.
	handleOrientationUpright: function() {
		Mojo.Log.info("handleOrientationUpright");
		var transition = this.controller.prepareTransition(Mojo.Transition.crossFade, false);
		this.controller.document.body.removeClassName("landscape");
		transition.run();
		//this.handleStatusChange();
	},
	
	// called when orientation is changed to landscape.
	handleOrientationSideways: function() {
		Mojo.Log.info("handleOrientationSideways");
		var transition = this.controller.prepareTransition(Mojo.Transition.crossFade, false);
		this.controller.document.body.addClassName("landscape");
		transition.run();
		//this.handleStatusChange();
	},
	
	updateClock: function() {
		//console.log("theme update function did not load");
		// list of divs to update
		var divs = ["h1", "h2", "m1", "m2"]; //, "s1", "s2"];
		// default content of digits for each of the divs
		var digits = ["", "", "0", ""]; // ,"0", ""];
		
		var now = new Date();
		
		var hour = now.getHours();
		if (Mojo.Format.using12HrTime()) {
			if (hour > 12) 
				hour -= 12;
			else if (hour == 0)
				hour = 12;
		}
		
		hour += "";
		if (hour.length == 1) {
			digits[1] = hour;
		} else {
			digits[0] = hour.charAt(0);
			digits[1] = hour.charAt(1);
		}
		
		var minute = now.getMinutes() + "";
		if (minute.length == 1) {			
			digits[3] = minute;
		} else {
			digits[2] = minute.charAt(0);
			digits[3] = minute.charAt(1);
		}
		
		/*
		var seconds = now.getSeconds() + "";
		if (seconds.length == 1) {
			digits[5] = seconds;
		} else {
			digits[4] = seconds.charAt(0);
			digits[5] = seconds.charAt(1);
		}
		*/
		
		
		var clock = this.controller.get('clock-container');
		/*
		// set AM/PM style  
		if (hour >= 12) {
			clock.addClassName('am');
			clock.removeClassName('pm');
		} else {
			clock.addClassName('pm');
			clock.removeClassName('am');
		}
		*/
		
		// set night style between 6PM & 6AM
		if (hour < 6 || hour > 17) {
			clock.addClassName('night');
			clock.removeClassName('day');
		} else {
			clock.addClassName('day');
			clock.removeClassName('night');
		}
		
		
		// 
		
		for (var i = 0; i < digits.length; i++) {

			this.controller.get(divs[i]).className = "digital-digit digit-" + digits[i];
		}	
		
	},
	/*
	// launches an app if pucked & landscaped
	// turns system volume off if unpucked or portraited
	handleStatusChange: function() {
		if (this.pucked && !(this.upright)) {
			
			if (!this.musicModeActive) {
				this.musicModeActive = true;
				this.musicPlay();
			}
			
		} else {
			
			if (this.musicModeActive) {
				this.musicModeActive = false;
				this.musicPause();
			}
			
		}
	},
	
	puckStatusSubscribe: function(callback){
		var request = new Mojo.Service.Request('palm://com.palm.bus/signal/', {
			method: 'addmatch',
			parameters: {"category":"/com/palm/power","method":"chargerStatus"},
			onSuccess: callback,
			onFailure: function() {
				QDLogger.log(QDLogger.INFO, "TelephonyCommands::puckStatusSubscribe", "failure");
			}
		});
		
		return request;
	},
	
	// causes a signal with puck status to be sent
	puckStatusQuery: function() {
		 var request = new Mojo.Service.Request('palm://com.palm.telephony', {
            method: 'chargeSourceQuery'
        });
	},
	
	// called when device is placed on or removed from puck
	onPuckEvent: function(response) {
		Mojo.Log.info("onPuckEvent");	
		if (response && response.type == "inductive") {
			if (response.connected !== this.pucked) {
				this.pucked = response.connected;
				Mojo.Log.info("puck connected: " + this.pucked);
				this.handleStatusChange();
			}
		}
	},
	
	musicPlay: function() {
		Mojo.Log.info("musicPlay");
		this.launchApp(this.musicAppId, this.musicAppParamsPlay);
	},
	
	musicPause: function() {
		Mojo.Log.info("musicPlay");
		this.launchApp(this.musicAppId, this.musicAppParamsPause);
	},
	
	
	launchApp: function(id, params) {
		 var request = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
            parameters: {
                "id": id,
                "params": params
            }
        });
	}
	*/
	
});

