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

var ChoosetransportAssistant = Class.create({
	initialize: function(sceneToReturnTo){
		this.accountsAttributes = {
			itemTemplate : "choosetransport/accountTypeRow",		
		};
		this.accountsModel = {
			items : []
		};
		this.sceneToReturnTo = sceneToReturnTo;
	},
	
	handleAccountTypesListTap: function(event) {
		//Mojo.Log.info("handleAccountTypesListTap: %s ",event.item.domain);
		// If the account type is EAS, then we sublaunch Email to their create account scene
		if (event.item.domain == "eas") {
			var args = {
         appId: "com.palm.app.email",
         name: "wizard"
     	};
			
			var params = {
				edit: false,
				id: undefined,
				type: "calendar", 
				title: $L("Add An Account"), 
				protocol: "EAS"
			};
			
			this.controller.stageController.pushScene(args, params);
		} else {
			var sceneToReturnTo = "prefs";
			if (this.sceneToReturnTo) {
				sceneToReturnTo = this.sceneToReturnTo;
			}
			this.controller.stageController.pushScene("accountlogin", 
																							0 /*acctId*/, 
																							undefined /*acctLogin*/,
																							event.item.id, 
																							event.item.serviceIcon, 
																							event.item.name, 
																							sceneToReturnTo);
		}
		
	},
	
	setup: function(){
		getAccountsService().getAllAccountTypesForService (this.renderExistingAccountTypes.bind(this), this.controller);
		this.controller.setupWidget("ExistingAccountTypes", this.accountsAttributes, this.accountsModel);
		},
	
	activate: function(results){
		
		if (results !== undefined) {
			if (results.action == "create") {
				this.controller.stageController.popScene();
				return;
			}
		}
		
		this.accountTypesListTapHandler = this.handleAccountTypesListTap.bindAsEventListener(this);
		this.controller.get("ExistingAccountTypes").observe(Mojo.Event.listTap, this.accountTypesListTapHandler);
	},
	
	deactivate: function(){
		this.controller.get("ExistingAccountTypes").stopObserving(Mojo.Event.listTap, this.accountTypesListTapHandler);
	},
	
	renderExistingAccountTypes: function(response){
		//Mojo.Log.info("choosetransport-assistant: renderExistingAccountTypes %j",response);
		this.accountsModel.items = response.list;
		// Set up the account type icons
		this.accountsModel.items.each(function(acctType){
			// NOTE: Account names to be localized are located in javascripts/accountLocalizations.js
			acctType.name = $L(acctType.name);
			if (acctType.icons)
				acctType.serviceIcon = getCalendarsManager().parseAcctIconString(acctType.icons);
		});
		this.controller.modelChanged(this.accountsModel);
	}
})
