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

var MovetoAssistant = Class.create( {
	initialize: function(emailInfo) {
		// this gives us the following properties emailId, folder, account, login, protocol: EAS|IMAP|POP3}
		this.emailInfo = emailInfo;
		this.requests = [];
	},

	setup: function() {
		this.accountsListElement = this.controller.get('moveto_list');
		
		if (this.emailInfo.account === undefined) {
			Mojo.Log.error("MovetoAssistant->subscribeAccountFolderList account id is undefined", $H(this.emailInfo).inspect());
		}
		this.requests.push(Folder.subscribeAccountFolderList(this.emailInfo.account, undefined, this.renderFolderList.bind(this)));

		this.accountsListElement.observe(Mojo.Event.tap, this.handleSelection.bind(this));
	},

	cleanup: function() {
		this.requests.each(function (r) { r.cancel();});
	},

	renderFolderList: function(data) {
		if (this.rendered) {
			// prevent check(mark) bounce on exit
			return;
		}
		if (data.list) {
			var sourceFolder = this.emailInfo.folder;
			data.list.each(function(folder) {
				if (folder.id == sourceFolder) {
					folder.sourceFolder = "source-folder";
				}

				// this allows for the standard folder names (Inbox, Drafts, Outbox, etc.) to be displayed localized
				// if the mail server doesn't send them in the appropriate language.
				if (folder.name) {
					folder.name = $L(folder.name.escapeHTML());
				}
			});

			var contentFolders = Mojo.View.render({collection: data.list, template: 'moveto/folder_entry'});
			this.accountsListElement.update(contentFolders);
		}
		this.rendered = true;
	},

	handleSelection: function(event) {
		var targetRow = this.controller.get(event.target);
		if (!targetRow.hasClassName('selection_target')) {
			targetRow = targetRow.up('div.selection_target');
		}
		
		var sourceId = 'moveto_'+this.emailInfo.folder;
		var targetId = targetRow.id;
		if (targetRow && sourceId != targetId) {
			var controller = this.controller;
			controller.get(targetId).addClassName('source-folder');
			controller.get(sourceId).removeClassName('source-folder');

			targetId = targetId.substring(targetId.lastIndexOf('_')+1);
			Mojo.Log.info("Move email id="+this.emailInfo.emailId+" to folder "+targetId);
			Message.moveMessage(controller, this.emailInfo.emailId, targetId);
			// Add a slight visual delay so user can see the result before leaving this scene 
			setTimeout(function() { controller.stageController.popScenesTo('list'); }, 500);
		}
	}

});