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

var Class0AlertAssistant = Class.create({
	initialize: function(alertData) {
		this.appController = Mojo.Controller.getAppController();
		this.alertData = alertData;
		this.currentAlert = alertData.list[alertData.list.length-1];
		this.handleDismiss = this.handleDismiss.bindAsEventListener(this);
		this.handleCopy = this.handleCopy.bindAsEventListener(this);

	},

	setup: function() {
		var kButtonHeightCorrection = 100; // one button and the title text
		this.controller.get("class0Alert-scroller").style.height = (this.controller.window.innerHeight - kButtonHeightCorrection) + "px";
		
		this.controller.setupWidget('class0Alert-scroller', {mode: 'vertical'});	
	},

	ready: function() {
		this.dismissButton = this.controller.get('class0Alert-dismiss-button');
		this.dismissButton.addEventListener(Mojo.Event.tap, this.handleDismiss);

		this.copyButton = this.controller.get('class0Alert-copy-button');
		this.copyButton.addEventListener(Mojo.Event.tap, this.handleCopy);		
		
		var carrierName = this.currentAlert.carrierName;
		Mojo.Log.info("carrierName " + carrierName);
		var title;
		if( (carrierName) && (carrierName.length > 0) ) {
			title = $L("Message from #{carrierName}").interpolate({
				carrierName: carrierName.escapeHTML()
			});		
		} else {
			title = $L("Message from carrier");
		}
		
		var message = this.currentAlert.messageText;
		if(message) {
			message = PalmSystem.runTextIndexer(message);
		}
		this.controller.get('class0Alert-title').update(title);
		this.controller.get('class0Alert-message').update(message);
	},
  
	cleanup: function() {
		this.dismissButton.removeEventListener(Mojo.Event.tap, this.handleDismiss);
		this.copyButton.removeEventListener(Mojo.Event.tap, this.handleCopy);
		this.appController.notificationAssistant.updateClass0Dashboard();
	},

	handleDismiss: function(event) {
		this.alertData.list.pop();
		if(this.alertData.list.length > 0) {
			// this will swap the current scene with the previous alert
			this.appController.notificationAssistant.renderClass0PopupAlert();
		} else {
			this.controller.window.close();	
		}
	},
	
	handleCopy: function(event) {
		
		Mojo.Log.logProperties(this.currentAlert, "this.currentAlert", false);
		var params = {
     		messageText: this.currentAlert.messageText,
      		ntwkMsgID: this.currentAlert.ntwkMsgID,
			messageTimeStamp: this.currentAlert.messageTimeStamp
		};
		
		if(this.currentAlert.carrierName) {
			params.carrierName = this.currentAlert.carrierName;
		} else {
			params.carrierName = $L("Message from carrier");
		}

		
		MessagingMojoService.saveClass0Message(this.controller, params);
		
		this.alertData.list.pop();
		if(this.alertData.list.length > 0) {
			// this will swap the current scene with the previous alert
			this.appController.notificationAssistant.renderClass0PopupAlert();
		} else {
			this.controller.window.close();	
		}		
	}
	
});
