/*
 * This class is used to edit or create server login settings 
 
Copyright 2009 Palm, Inc.  All rights reserved.

*/
var CreateAssistant = Class.create({

	initialize: function(params) {
		this.sceneResults = {};
		this.accountDetails = new EmailAccount();
		this.spinnerModel = { spinning: false };
		this.headerTitle = $L("Change login settings");
		this.isEditMode = false;
		this.isDirty = false;
		this.delayActivation = false;
		this.activationCallback = null;
		this.params = params || {};

		if (params) {
			this.type = params.type || this.type;
			CreateAssistant.logAccountDetails("----------- CreateAssistant params = ", params);
			Mojo.Log.info("----------- CreateAssistant type = " + this.type);
			if (params.edit) {
				this.isEditMode = true;
				this.delayActivation = true;
			}
			if (params.id !== undefined) {
				this.accountDetails.id = params.id;
				this.sceneResults.id = params.id;
				this.sceneResults.isEditAccount = params.edit;
			}
			
			if (params.title) {
				this.headerTitle = params.title;
			}
			if (params.password) {
				this.accountDetails.password = params.password;
			}
			if (params.email) {
				this.accountDetails.address = params.email;
			}
			
			// If inbound server settings were provided by the account wizard then prepopulate the settings now
			if (params.protocol) {
				this.accountDetails.type = params.protocol;
				this.accountDetails.login = params.username || "";
				this.accountDetails.port = params.port;
				this.accountDetails.useSsl = params.ssl;
				this.accountDetails.host = params.server || "";
			}
		}
		
		// Fix account details before rendering them
		this.fixAccountDetails("from service");
	},

	setup: function() {
		this.createForm = this.controller.get('create-form');
		
		// Setup specific controls for edit/create modes
		if (this.isEditMode) {
			// Some fields cannot be edited
			this.accountDetails.limitEdits = true;
			
			// Setup the app menu 
			this.appMenuModel = {
	        	visible: true,
	            items: [this.discardMenuItem],
	        };
			
			// Hide the email field
			this.controller.get('email-address-group').hide();	
			
			// Hide the Sign In button
			this.controller.get('create-account-button').hide();
			
			// Fetch the account details
			EmailAccount.getAccountDetails(this.controller, this.accountDetails.id, this.getAccountDetailsResult.bind(this));
		}
		else {
			// An account is being created manually
			// All fields can be edited
			this.accountDetails.limitEdits = false;
			
			// Setup the app menu 
			this.appMenuModel = {};
			
			// Set the title icon to the protocol being setup (if provided)
			if (this.params.protocol)
				this.controller.get('title-icon').addClassName(this.params.protocol.toLowerCase());
		}
		
		// Set the form title
		this.controller.get('page-title').update(this.headerTitle);

		// Setup widgets general to the whole form
		this.controller.listen(this.controller.sceneElement, Mojo.Event.propertyChange, this.fieldChanged.bindAsEventListener(this));
		this.controller.setupWidget('email-address', this.emailAddressAttributes, this.accountDetails);
		this.controller.setupWidget(Mojo.Menu.appMenu, {}, this.appMenuModel);
		this.controller.setupWidget('mail-type-selector', this.mailTypes, this.accountDetails);
		this.controller.listen('mail-type-selector', Mojo.Event.propertyChange, this.mailTypeChanged.bindAsEventListener(this));

		// Incoming Mail Server
		this.controller.setupWidget('incoming-host', this.hostAttributes, this.accountDetails);
		this.controller.setupWidget('incoming-login', this.loginAttributes, this.accountDetails);
		this.controller.setupWidget('incoming-password', this.passwordAttributes, this.accountDetails);
		this.controller.setupWidget('incoming-port', this.portNumAttributes, this.accountDetails);
		this.controller.setupWidget('eas-domain', this.easDomainAttributes, this.accountDetails);
		this.controller.setupWidget('incoming-encryption', this.encryption, this.accountDetails);
		this.controller.listen('incoming-encryption', Mojo.Event.propertyChange, this.incomingEncryptionToggle.bind(this));

		// Outgoing Mail Server
		this.controller.setupWidget('outgoing-host', this.smtpHostAttributes, this.accountDetails);
		this.controller.setupWidget('outgoing-login', this.smtpLoginAttributes, this.accountDetails);
		this.controller.setupWidget('outgoing-password', this.smtpPasswordAttributes, this.accountDetails);
		this.controller.setupWidget('outgoing-port', this.smtpPortNumAttributes, this.accountDetails);
    	this.controller.setupWidget('outgoing-auth-toggle', this.useSameCredentials, this.accountDetails);
		this.controller.setupWidget('outgoing-encryption', this.smtpEncryption, this.accountDetails);
		this.controller.listen('outgoing-auth-toggle', Mojo.Event.propertyChange, this.toggleSMTPAuth.bind(this));
		this.controller.listen('outgoing-encryption', Mojo.Event.propertyChange, this.outgoingEncryptionToggle.bind(this));
		this.controller.setupWidget('outgoing-server-auth-drawer', {unstyled:true, property:'useSmtpAuthentication'}, this.accountDetails);

		// IMAP root folder
		this.controller.setupWidget('root-folder', this.rootFolderAttributes, this.accountDetails);

		// Sign in button		
		this.controller.setupWidget('create-account-button', {type: Mojo.Widget.activityButton}, this.signInButtonModel);
		this.controller.listen('create-account-button', Mojo.Event.tap, this.createAccount.bind(this));
		this.signInButton = this.controller.get('create-account-button');
		
		// Make sure the correct fields are shown for the protocol
		this.mailTypeChanged(); 
	},

	cleanup: function() {
		if (this.isDirty && this.isEditMode && this.validAccountSetttings()) {
			// Fix the account details for the service to use
			this.fixAccountDetails("to service");
			CreateAssistant.logAccountDetails("----------- CreateAssistant deactivate saving account:", this.accountDetails);
			EmailAccount.saveAccountDetails(this.controller, this.accountDetails);
		}
	},

	aboutToActivate: function(callback) {
		// Delay activation until the data comes back from the service (if editing the account)
		if (this.delayActivation)
			this.activationCallback = callback;
		else
			callback();
	},
	
	activate: function() {
		Mojo.Log.info("----------- CreateAssistant activate...");
		if (this.type === "email") {
			// Clear the notification filters so user will get notified when any email comes in
			var notificationAssistant = Mojo.Controller.getAppController().assistant.notificationAssistant;
			if (notificationAssistant) {
				notificationAssistant.setFilter();
			}
		}
	},

	deactivate: function() {
	},

	handleCommand: function(event) {
		// Enable help menu item
		if (event.type == Mojo.Event.commandEnable) {
			if (event.command === Mojo.Menu.helpCmd)
				event.stopPropagation();
		}
		else if (event.type == Mojo.Event.command) {
			switch (event.command) {
				case 'discard':
					// Discard changes and pop this scene
					this.isDirty = false;
					this.popScene('back');
					break;

				case Mojo.Menu.helpCmd:
					MenuController.showHelp();
					break;
			}
		}
		else if (event.type == Mojo.Event.back) {
			event.stop();
			// If editing then save the account now
			Mojo.Log.info("----------- CreateAssistant handleCommand back: dirty=" + this.isDirty + " edit=" + this.isEditMode + " valid=" + this.validAccountSetttings());
			if (this.isDirty && this.isEditMode && this.validAccountSetttings())
				this.handleSaveAccount();
			else
				this.popScene('back');
		}
	},

	popScene: function(action) {
		if (action)
			this.sceneResults.action = action;
		CreateAssistant.logAccountDetails("----------- CreateAssistant popping with result:", this.sceneResults);
		this.controller.stageController.popScene(this.sceneResults);
	},

	mailTypeChanged: function() {
		Mojo.Log.info("----------- CreateAssistant mail type mailTypeChanged to ", this.accountDetails.type);
		if (!this.isEditMode) {
			this.accountDetails.setDefaultPortsForServerType(this.params.port? false: true);
			// Prepopluate the host field with "https://" is this is an EAS account
			if (!this.accountDetails.host)
				this.accountDetails.host = "";
			if (this.accountDetails.type === "EAS" && !this.accountDetails.host.startsWith("https://"))
				this.accountDetails.host = "https://" + this.accountDetails.host;
			if (this.accountDetails.type != "EAS" && this.accountDetails.host.startsWith("https://"))
				this.accountDetails.host = this.accountDetails.host.replace(/https:\/\//, "");
		}
		// Re-render the account details to reflect the new mail server type
		switch (this.accountDetails.type) {
			case "EAS":
			this.controller.get('advanced-settings').show();
			this.controller.get('simple-settings').hide();
			this.controller.get('incoming-pop-imap').hide();
			this.controller.get('outgoing-mail-server').hide();
			this.controller.get('imap-root-folder').hide();
			this.controller.get('incoming-eas').show();
			this.controller.get('incoming-last-eas-row').addClassName('last');
			break;
		case "IMAP":
		case "POP3":
			this.controller.get('advanced-settings').show();
			this.controller.get('simple-settings').hide();
			this.controller.get('incoming-eas').hide();
			if (this.accountDetails.type == "IMAP")
				this.controller.get('imap-root-folder').show();
			else
				this.controller.get('imap-root-folder').hide();
			this.controller.get('incoming-pop-imap').show();
			this.controller.get('outgoing-mail-server').show();
			this.controller.get('incoming-last-eas-row').removeClassName('last');
			break;
		case "Gmail":
		case "Yahoo":
			this.controller.get('advanced-settings').hide();
			this.controller.get('simple-settings').show();
			break;
		}
		
		// Revalidate the settings to see if the Sign In button should be enabled
		this.fieldChanged(null);
	},

	toggleSMTPAuth: function() {
		// If this is enabled and the username/password are both blank then prepopulate them using the inbound credentials
		if (this.accountDetails.useSmtpAuthentication) {
			if (this.accountDetails.smtpLogin.length == 0 && this.accountDetails.smtpPassword.length == 0) {
				this.accountDetails.smtpLogin = this.accountDetails.login;
				this.accountDetails.smtpPassword = this.accountDetails.password;
			}
		}
		// Update the model to show or hide the drawer
        this.controller.modelChanged(this.accountDetails);
		
		// Mark the data dirty so it is saved
		this.isDirty = true;
	},

	validAccountSetttings: function() {
		var emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,6}) *$/;
		var hostReg = /^([A-Za-z0-9_\-\.\/:])+(\.[A-Za-z]{2,6}|(\.[0-9]{1,3}){3}) *$/;
		var easHostReg = /^([A-Za-z0-9_\-\.\/:])+(\.[A-Za-z]{2,6}|(\.[0-9]{1,3}){3})/;
		Mojo.Log.info('---- validAccountSetttings:' + Object.toJSON(this.accountDetails));
		
		// Make sure all the server settings are valid
		if (!this.accountDetails)
			return false;
		// Validate the email address
		if (!this.isEditMode && !emailReg.test(this.accountDetails.address))
			return false;
		if (this.accountDetails.password.length < 1)
			return false;
		if (this.accountDetails.type === "Gmail" || this.accountDetails.type === "Yahoo")
			return true;
		if (this.accountDetails.login.length < 1)
			return false;
		if (this.accountDetails.type === "EAS") {
			// Validate the server settings
			if (!easHostReg.test(this.accountDetails.host))
				return false;
			// Don't validate the domain.  It can be left blank
			return true;
		}
		// Continue validating IMAP and POP3
		if (!hostReg.test(this.accountDetails.host))
			return false;
		if (this.accountDetails.port < 1 || this.accountDetails.port > 65535) 
			return false;
		if (!hostReg.test(this.accountDetails.smtpHost))
			return false;
		if (this.accountDetails.useSmtpAuthentication && (this.accountDetails.smtpLogin.length == 0 || this.accountDetails.smtpPassword.length == 0))
			return false;
		if (this.accountDetails.smtpPort < 1 || this.accountDetails.smtpPort > 65535) 
			return false;
		// IMAP root folder can be blank
		return true;
	},
	
	incomingEncryptionToggle: function(event) {
		event.model.setServerPort(false);
		this.controller.modelChanged(event.model);
		// Mark the data dirty so it is saved
		this.isDirty = true;
	},

	outgoingEncryptionToggle: function(event) {
		event.model.setSmtpPort(false);
		this.controller.modelChanged(event.model);
		// Mark the data dirty so it is saved
		this.isDirty = true;
	},

	fieldChanged: function(event) {
		// Ignore this event if we're loggin in
		if (this.loggingIn)
			return;
		Mojo.Log.info('---- fieldChanged: data valid=' + this.validAccountSetttings());
		
		// Mark the data dirty if there was an event
		if (event != null) {
			this.isDirty = true;
			Mojo.Log.info('---- fieldChanged: data is DIRTY!!!');
		}

		// A character was entered.  Enable or disable the "Sign In" button based on valid data
		Mojo.Log.info('---- fieldChanged: button was disabled? ' + this.signInButtonModel.disabled);
		if (this.signInButtonModel.disabled && this.validAccountSetttings()) {
			Mojo.Log.info('---- fieldChanged: button is now enabled');
			this.signInButtonModel.disabled = false;
			this.controller.modelChanged(this.signInButtonModel);
		} 
		else if (!this.signInButtonModel.disabled && !this.validAccountSetttings()) {
			Mojo.Log.info('---- fieldChanged: button is now disabled');
			this.signInButtonModel.disabled = true;
			this.controller.modelChanged(this.signInButtonModel);
		} 
		
		// If not edit mode and the field is the last one on the form and Enter is pressed then simulate tapping on "Sign In"
		if (!this.isEditMode && event && event.originalEvent && Mojo.Char.isEnterKey(event.originalEvent.keyCode)) {
			// Get the focused element
			var element = event.originalEvent.target;
			
			// Have all the fields been validated? (Is the "Sign In" button enabled?)
			if (!this.signInButtonModel.disabled) {
				// Get the parent mojo element of the focused element
				var parent = Mojo.View.findParentByAttribute(element, this.controller.document, "x-mojo-element", undefined)
				Mojo.Log.info('---- isEnterKey: parent id = ' + parent.id);
				
				// Get the list of focusable elements
				var list = Mojo.View.getFocusableList(this.createForm);
				if (list.length > 0) {
					// Get the last focusable element
					var lastElement = Mojo.View.findParentByAttribute(list[list.length - 1], this.controller.document, "x-mojo-element", undefined);
					// Is the last element the one where the user pressed "Enter"?
					if (lastElement && lastElement.id === parent.id) {
						this.createAccount();
						Event.stop(event);
					}
				}
			}
			
			// If not signing in then advance the focus to the next field
			if (!this.loggingIn) {
				element.focus();
				Mojo.View.advanceFocus(this.createForm);
			}
		}
	},

	setButtonState: function(loggingIn) {
		Mojo.Log.info('---- setButtonState: logging in=' + loggingIn);
		this.loggingIn = loggingIn || false;
		if (this.loggingIn) {
			// Button is always disabled when signing in
			this.signInButtonModel.buttonLabel = $L('Signing In...');
			this.signInButtonModel.disabled = true;
			this.controller.modelChanged(this.signInButtonModel);
			this.signInButton.mojo.activate();
		}
		else {
			// Button should be enabled only if user name/password are valid
			this.signInButtonModel.disabled = !this.validAccountSetttings();
			this.signInButtonModel.buttonLabel = $L('Sign In');
			this.controller.modelChanged(this.signInButtonModel);
			this.signInButton.mojo.deactivate();
		}
	},
	
	createSuccess: function() {
		Mojo.Log.info("----------- CreateAssistant createSuccess");
		this.setButtonState(false);
		this.popScene('create');
	},

	createError: function(err) {
		Mojo.Log.error("----------- CreateAssistant createError error="+$H(err).inspect());

		// Set the button state to "Sign In"
		this.setButtonState(false);
		
		if (this.accountDetails.type === "EAS" && err.errorCode == 502) {
			// EAS security policy
			var createAccount = this.handleCreateAccountAnyway.bind(this, "create");
			var cancelCreate = this.popScene.bind(this, "back");
			SecuritypolicyAssistant.handlePasswordPolicy(this.controller, this.accountDetails.address, createAccount, cancelCreate);
		}
		else if (err.setupDetails && err.setupDetails.protocol) {
			// The inbound settings validated.  Ask the user if the account should be created without outbound credentials
			this.promptCreateAccountAnyway();
		}
		else {
			// Show the error dialog
			EmailAccount.DisplayAccountSetupFailure(this.controller, err.errorCode, err.errorText, true, (this.accountDetails.type === "EAS"));
		}
	},
	
	promptCreateAccountAnyway: function() {
		this.controller.showAlertDialog({
			onChoose: function(value) { this.handleCreateAccountAnyway(value); },
			title: $L("Outgoing server setup"),
			message: $L("Unable to validate outgoing mail server settings. You will be able to receive emails, but may not be able to send emails from this account."),
			choices: [{label:$L('Edit settings'), value:'edit', type:'dismiss'},
					{label:$L('Set up anyway'), value:'create', type:'dismiss'}]
		});
	},
	
	handleCreateAccountAnyway: function(value) {
		if (value === "create") {
			// Don't validate the account; just create it
			this.accountDetails.dontValidate = true;
			this.createAccount();
		}
		else {
			// Put the focus on the outbound server field
			this.controller.get('outgoing-host').mojo.focus();
		}
	},
	
	fixAccountDetails: function(direction) {
		Mojo.Log.info('---- fixAccountDetails:' + direction);
		if (direction === "to service") {
			// Erase the SMTP credentials if SMTP authentication is disabled
			if (!this.accountDetails.useSmtpAuthentication) {
				this.accountDetails.smtpLogin = "";
				this.accountDetails.smtpPassword = "";
			}
			// Translate SSL/TLS settings for inbound server
			this.accountDetails.useSsl = false;
			this.accountDetails.useTls = false;
			switch (this.accountDetails.encryption) {
				case this.kEncryptionNone: break;
				case this.kEncryptionSSL: this.accountDetails.useSsl = true; break;
				case this.kEncryptionTLS: this.accountDetails.useTls = true; break;
			}
			// Translate SSL/TLS settings for SMTP server
			this.accountDetails.smtpSsl = false;
			this.accountDetails.smtpTls = false;
			switch (this.accountDetails.smtpEncryption) {
				case this.kEncryptionNone: break;
				case this.kEncryptionSSL: this.accountDetails.smtpSsl = true; break;
				case this.kEncryptionTLS: this.accountDetails.smtpTls = true; break;
			}
		}
		else {
			// Set smtpLogin/smtpPassword to a blank string if they're null/undefined
			if(!this.accountDetails.smtpLogin) this.accountDetails.smtpLogin = "";
			if(!this.accountDetails.smtpPassword) this.accountDetails.smtpPassword = "";
			
			// Disable SMTP authentication if no SMTP username or password is provided
			if (this.accountDetails.smtpLogin.length == 0 && this.accountDetails.smtpPassword.length == 0)
				this.accountDetails.useSmtpAuthentication = false;
			else
				this.accountDetails.useSmtpAuthentication = true;
			// For EAS accounts, split the username into domain and username
			if (this.accountDetails.type === "EAS" && this.accountDetails.login && this.accountDetails.login.indexOf('\\') > 0) {
				this.accountDetails.domain = this.accountDetails.login.gsub(/\\.*/, '');
				this.accountDetails.login = this.accountDetails.login.gsub(/.*\\/, '');
				Mojo.Log.breadcrumb("----------- username=" + this.accountDetails.login + "  domain=" + this.accountDetails.domain);
			}
			// Assume there is no encryption, then look at the SSL and TLS settings
			this.accountDetails.encryption = this.kEncryptionNone;
			if (this.accountDetails.useTls)
				this.accountDetails.encryption = this.kEncryptionTLS;
			else if (this.accountDetails.useSsl)
				this.accountDetails.encryption = this.kEncryptionSSL;
			this.accountDetails.smtpEncryption = this.kEncryptionNone;
			if (this.accountDetails.smtpTls)
				this.accountDetails.smtpEncryption = this.kEncryptionTLS;
			else if (this.accountDetails.smtpSsl)
				this.accountDetails.smtpEncryption = this.kEncryptionSSL;
		}
		Mojo.Log.info('---- fixAccountDetails end');
	},
	
	createAccount: function(event){
		// The settings have been validated already because the Sign In button has been enabled
		// Change the button to show "Signing In"
		this.setButtonState(true);
		
		// Fix the account details for the service to use
		this.fixAccountDetails("to service");

		CreateAssistant.logAccountDetails("----------- CreateAssistant createAccount:", this.accountDetails);
		this.MojoRequest = new Mojo.Service.Request(EmailAccount.identifier, {
			method: 'accountCreateManual',
			parameters: this.accountDetails,
			onSuccess: this.createSuccess.bind(this),
			onFailure: this.createError.bind(this),
		});
	},

	handleSaveAccount: function() {
		// Fix the account details for the service to use
		this.fixAccountDetails("to service");

		CreateAssistant.logAccountDetails("----------- CreateAssistant handleSaveAccount:", this.accountDetails);
		EmailAccount.saveAccountDetails(this.controller, this.accountDetails, 
		                                this.saveSuccess.bind(this), this.saveError.bind(this));
	},
	
	saveSuccess: function() {
		this.isDirty = false;
		var message = $L("Preferences updated");
		Mojo.Controller.getAppController().assistant.notificationAssistant.handleNotification({ type:"general", message:message });
		this.popScene('updated');
		// close any open notifications related to the account
		NotificationAssistant.closeAccountDashboardErrors(this.accountDetails);
	},
	
	saveError: function(response) {
		Mojo.Log.error("----------- CreateAssistant handleSaveAccount error=", $H(resp).inspect());
		this.popScene('updated');
	},
	
	getAccountDetailsResult: function(resp) {
		this.accountDetails.clone(resp);
		CreateAssistant.logAccountDetails("----------- CreateAssistant getAccountDetailsResult=", this.accountDetails);
		// Change the page title to show the name of the account without the email address
		var acctName = this.accountDetails.name;
		var ndx = acctName.indexOf('(');
		if (ndx > 0) {
			acctName = acctName.substring(0, ndx);
		}
		this.headerTitle = $L("Edit #{name}").interpolate({'name': acctName});
		this.controller.get('page-title').update(this.headerTitle);
		// Set the title icon
		this.controller.get('title-icon').addClassName(this.accountDetails.accountDomain);
		
		// Fix account details before rendering them
		this.fixAccountDetails("from service");
		
		// If this is an EAS account then prevent the user from editing the host and username
		this.accountDetails.accountIsEas = (this.accountDetails.type === "EAS");

		// Update the form with the settings that have been retrieved so far
        this.controller.modelChanged(this.accountDetails);
		
		// Show or hide the fields specific to the protocol
		this.mailTypeChanged();
		
		// If the account has a login error, mark the scene as dirty
		// so that the user can save the account without changing the password
		if(this.accountDetails.loginFailed) {
			this.isDirty = true;
		}

		// This scene can be activated now
		this.delayActivation = false;
		
		// If there is a callback to activate the scene then call it now	
		if (this.activationCallback) {
			this.activationCallback();
			this.activationCallback = null;
		}
	},
	
	//
	// Attributes for all of the Mojo widgets
	//
	emailAddressAttributes: {
		modelProperty: 'address',
		textReplacement: false,
		changeOnKeyPress: true,
		acceptBack: true
	},

	hostAttributes: {
		modelProperty: 'host',
		hintText: $L("Enter server name..."),
		textReplacement: false,
		disabledProperty: 'accountIsEas',
		changeOnKeyPress: true,
		acceptBack: true
	},

	loginAttributes: {
		modelProperty: 'login',
		maxLength: 128,
		textReplacement: false,
		disabledProperty: 'accountIsEas',
		changeOnKeyPress: true,
		acceptBack: true
	},

	passwordAttributes: {
		modelProperty: 'password',
		focusMode: Mojo.Widget.focusSelectMode,
		maxLength: 64,
		textReplacement: false,
		requiresEnterKey: true,
		changeOnKeyPress: true,
		acceptBack: true
	},

	easDomainAttributes: {
		modelProperty: 'domain',
		textReplacement: false,
		disabledProperty: 'limitEdits',
		acceptBack: true
	},

	smtpHostAttributes: {
		modelProperty: 'smtpHost',
		hintText: $L("Enter server name..."),
		textReplacement: false,
		changeOnKeyPress: true,
		acceptBack: true
	},

	smtpLoginAttributes: {
		modelProperty: 'smtpLogin',
		maxLength: 128,
		textReplacement: false,
		acceptBack: true
	},

	smtpPasswordAttributes: {
		modelProperty: 'smtpPassword',
		focusMode: Mojo.Widget.focusSelectMode,
		maxLength: 64,
		textReplacement: false,
		acceptBack: true
	},

	portNumAttributes: {
		modelProperty: 'port',
		textReplacement: false,
		modifierState: Mojo.Widget.numLock,
		charsAllow: Mojo.Widget.numericValidation,
		changeOnKeyPress: true,
		acceptBack: true
	},

	smtpPortNumAttributes: {
		modelProperty: 'smtpPort',
		textReplacement: false,
		modifierState: Mojo.Widget.numLock,
		charsAllow: Mojo.Widget.numericValidation,
		changeOnKeyPress: true,
		acceptBack: true
	},

	rootFolderAttributes: {
		modelProperty: 'rootFolder',
		textReplacement: false,
		requiresEnterKey: true,
		changeOnKeyPress: true,
		acceptBack: true
	},

	mailTypes:  {
		modelProperty: 'type',
		choices: [
			{label: $L('IMAP'), value: "IMAP"},
			{label: $L('POP'), value: "POP3"},
			{label: $L('Exchange (EAS)'), value: "EAS"},
			{label: $L('Gmail'), value: "Gmail"},
			{label: $L('Yahoo'), value: "Yahoo"}
		],
		disabledProperty: 'limitEdits',
	},
	
	useSameCredentials: {
		modelProperty: 'useSmtpAuthentication',
		trueValue: true,
		falseValue: false
	},
	
	encryption:  {
		modelProperty: 'encryption',
		label: $L("Encryption"),
		choices: [
			{label: $L('None'), value: "none"},
			{label: $L('SSL'), value: "SSL"},
			{label: $L('TLS'), value: "TLS"}
		],
	},
	
	smtpEncryption:  {
		modelProperty: 'smtpEncryption',
		label: $L("Encryption"),
		choices: [
			{label: $L('None'), value: "none"},
			{label: $L('SSL'), value: "SSL"},
			{label: $L('TLS'), value: "TLS"}
		],
	},
	
	signInButtonModel: {
		buttonClass:'primary',
		buttonLabel:$L('Sign In'),
		disabled:true
	},


	// Items for the app menu
	discardMenuItem: {
		label: $L('Discard Changes'),
		command: 'discard',
	},

	kEncryptionNone: "none",
	kEncryptionSSL: "SSL",
	kEncryptionTLS: "TLS",
});

// special logging make sure the password is not logged
CreateAssistant.logAccountDetails = function(message, details) {
	if (Mojo.Log.currentLogLevel >= Mojo.Log.LOG_LEVEL_INFO) {
		if (details) {
			var d = Object.clone(details);
			d.password = undefined;
			d.smtpPassword = undefined;
			d.proxyPassword = undefined;
			Mojo.Log.info(message + Object.toJSON(d));
		} else {
			Mojo.Log.info(message + "undefined");
		}
	}
}
