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

// Use to select the IMAP server folder
var SelectfolderAssistant = Class.create( {
	initialize: function(params) {
		this.params = {};
		if (params)
			this.params = params;
		this.activateCallback = null;
	},

	setup: function() {
		this.folderList = this.controller.get('folder_list');
		
		// Set the page title
		this.controller.get('title').update($L("Choose #{folder} folder").interpolate({folder: this.params.folder.escapeHTML()}));
		this.controller.get('header-icon').className = ("icon select-folder #{folder}").interpolate(this.params);		
		
		this.foldersModel = {items: []};
		this.controller.setupWidget('folder_list', {itemTemplate: 'selectfolder/folder'}, this.foldersModel);

		// Request the list of server folders		
		Folder.getImapServerFolderList(this.params.id, this.renderFolderList.bind(this));
		
		Mojo.Event.listen(this.folderList, Mojo.Event.listTap, this.listTapHandler.bindAsEventListener(this), false);
	},
	
	aboutToActivate: function(callback) {
		if (this.foldersModel.items.length)
			callback();
		else
			this.activateCallback = callback;
	},

	listTapHandler: function(event) {
		Folder.setImapServerFolder(event.item.id, this.params.folder);
		this.controller.stageController.popScene();
	},

	renderFolderList: function(data) {
		this.foldersModel.items = data.list;
		// Find the current folder for this use
		for (var i=0; i<data.list.length; i++) {
			if (this.params.folder === "sent" && data.list[i].use == 1)
				data.list[i].checked = "checked";
			if (this.params.folder === "drafts" && data.list[i].use == 2)
				data.list[i].checked = "checked";
			if (this.params.folder === "trash" && data.list[i].use == 3)
				data.list[i].checked = "checked";
				
			data.list[i].folderName = data.list[i].folderName.escapeHTML(); 
		}
		this.controller.modelChanged(this.foldersModel);
		if (this.activateCallback) {
			this.activateCallback();
			this.activateCallback = null;
		}
			
	},
});