var AccountsLoginPasswordAssistant = Class.create({
	
	initialize: function(account, lastAccount) {
		this.account = account;
		this.lastAccount = lastAccount;
		FirstUseUtil.addDashboardSmall($('target'));
	},

	setup: function() {
		this.buttonAttr = {
			disabledProperty: 'disabled',
			type: Mojo.Widget.activityButton
		};
		this.buttonModel = {
			disabled: true,
			buttonLabel : $L('Sign in'),
			buttonClass: 'palm-button'
		};
		this.controller.setupWidget('button_skip', this.buttonAttr, this.buttonModel);
		Mojo.listen(this.controller.get('button_skip'), Mojo.Event.tap, this.loginUser.bindAsEventListener(this));
		this.loginBtn = this.controller.get("button_skip");
		
		var t = $L("Enter the password for your #{accountName} account").interpolate({
			accountName: this.account.accountName
		});
		this.controller.get("passwordMessage").update(t);
		this.controller.get("accountIcon").addClassName(this.account.accountIconClass);
			
		this.controller.get('emailAddress').update(this.account.username);
		
		this.passwordAttr = {
			modelProperty: 'password',
			focus: false,
			className: ' ',
			focusMode: Mojo.Widget.focusSelectMode,
			changeOnKeyPress: true,
			requiresEnterKey: true
		};
		
		this.passwordModel = {
			'password' : ''
		};
		
		this.controller.setupWidget('password', this.passwordAttr, this.passwordModel);
		this.controller.listen('password', Mojo.Event.propertyChange, this.passwordChanged.bind(this));
		
		this.isPasswordInFocus = false;
		this.passwordFocusHandler = this.passwordHandler.bind(this);
		Mojo.Event.listenForFocusChanges(this.controller.get('password'), this.passwordFocusHandler);
		
		this.controller.listen(this.controller.get('target'), Mojo.Event.tap, FirstUseUtil.tapHandler.bindAsEventListener(this));
		
		// Listen to ## key presses
		this.keyPressEventHandler =  FirstUseUtil.handleKeyPressEvent.bind(this);
		this.controller.listen(this.controller.sceneElement, Mojo.Event.keydown, this.keyPressEventHandler);
	},
	
	showSpinner: function() {
		// Disable the Sign In button
		this.buttonModel.disabled = true;
		this.buttonModel.buttonLabel = $L("Signing in...");
		this.controller.modelChanged(this.buttonModel);
		this.loginBtn.mojo.activate();
	},
	
	hideSpinner: function() {
		this.buttonModel.disabled = false;
		this.buttonModel.buttonLabel = $L("Sign in");
		this.controller.modelChanged(this.buttonModel);
		this.loginBtn.mojo.deactivate();
	},
	
	passwordChanged: function(event) {
	 	this.passwordModel.original = event.value;
		this.toggleDisabled();
		if (event && Mojo.Char.isEnterKey(event.originalEvent.keyCode)) {
			if (this.buttonModel.disabled == false) {
				this.loginUser();
				Event.stop(event);
			}
			else
			{
				this.controller.get('password').mojo.focus.delay(0);
			}
		}
	},
	
	passwordHandler: function (event) {
		this.isPasswordInFocus = !this.isPasswordInFocus;
		this.toggleListener(this.isPasswordInFocus);
	},
	
	toggleListener: function (flag) {
		if(flag == true) {
			this.controller.stopListening(this.controller.sceneElement, Mojo.Event.keydown, this.keyPressEventHandler);
		} else {
			this.controller.listen(this.controller.sceneElement, Mojo.Event.keydown, this.keyPressEventHandler);
		}
	},
	
	toggleDisabled: function () {
		this.controller.get('passwordError').style.display = 'none';
		this.setButtonMode();
	},
	
	setButtonMode: function () {
		if(this.passwordModel.password.length > 0) {
			this.buttonModel.disabled = false;
			this.controller.modelChanged(this.buttonModel);		
		} else {
			this.buttonModel.disabled = true;
			this.controller.modelChanged(this.buttonModel);
		}
	},
	
	loginUser: function() {
		this.showSpinner();
		// Check if device is roaming
		if(RoamUtil.enableRoaming() === true) {
			RoamGuardDialog.turnOffRoamguard(
			{
				"sceneController": this.controller,
				"method": this.authenticate.bind(this)
			});
			return;
		}
		this.authenticate();
	},
	
	authenticate: function () {
		// Pass password as smtpPassword
		this.accountsRequest = AppAssistant.accountsLoginService.authenticate(this.account.credentialsId, this.account.accountId, 
										this.account.username, 
										this.passwordModel.password,
										this.passwordModel.password,
										this.readLoginStatus.bind(this), this.loginError.bind(this), this.controller);
	},
	
	doNextAction: function () {
		if(this.lastAccount === true) {
			Mojo.Controller.stageController.popScenesTo();
			Mojo.Controller.stageController.swapScene("restorecomplete");
			return;
		}
		Mojo.Controller.stageController.popScene(this.account);
	},
	
	readLoginStatus: function(response) {
		Mojo.Log.info("--------------- login status ------------------%j", response);
		if((response.returnValue === true) || (response.incoming.status === "successful") || (response.outgoing.status === "successful")) {
			this.doNextAction();
			return;
		}
		this.hideSpinner();
		if (response.incoming) {
			if ((response.incoming.errorCode) && (response.incoming.errorCode === "AcctMgr_Bad_Authentication")) {
				this.controller.get('password').mojo.focus();
				this.controller.get('passwordError').style.display = 'block';
				return;
			} else {
				// Show error message for other errors
			}
		}
		
		if(response.outgoing && response.outgoing.errorCode) {
			if (response.outgoing.errorCode === "AcctMgr_Bad_Authentication") {
				this.showOutgoingAccountError();
				return;
			} else {
				// Show error message for other errors
			}	
		}
		if (isConnected === false) {
			this.showConnectionError();
			return;
		}	
	},
	
	loginError: function (response) {
		this.hideSpinner();
		
		// Check if device is roaming
		if(RoamUtil.enableRoaming() === true) {
			RoamGuardDialog.turnOffRoamguard(
			{
				"sceneController": this.controller,
				"method": this.loginUser.bind(this)
			});
			return;
		}
		if (isConnected === false) {
			this.showConnectionError();
			return;
		}
		
		// If java crashes, resend the request after 30 seconds
		if(response.errorCode == "-1") {
			this.resumeRequest = setTimeout(this.loginUser.bind(this), 30000);
		}	
	},
	
	activate: function() {
		
	},
	
	showConnectionError: function () {
		var dialog = this.controller.showAlertDialog({
			title: $L("No internet connection"),
		    message: $L("You need an internet connection to sign in to an account"),
		    choices:[
		        {label:$L("OK"), value:"allow", type: 'dismiss'}
		    ]
		  });
		dialog.observe(Mojo.Event.keydown, FirstUseUtil.handleKeyPressEvent.bind(this));
	},
	
	showOutgoingAccountError: function () {
		var that = this;
		var dialog = this.sceneController.showAlertDialog({
			 onChoose: function(value) {
				if(value === "allow") {
					that.doNextAction();
				}
			},
			title: $L("Outgoing server password"),
		    message: $L("The password entered is correct for the incoming server but incorrect for the outgoing server. Enter the correct password in the Email Preferences and Accounts view after your device has restarted."),
		    choices:[
		        {label:$L("OK"), value:"allow", type: 'dismiss'}
		    ]
		  });
		dialog.observe(Mojo.Event.keydown, FirstUseUtil.handleKeyPressEvent.bind(this));
	}
	
});
