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

var SecurityQuestionAssistant = Class.create({
	
	initialize: function(){
		FirstUseUtil.addDashboardSmall($('target'));
		this.securityQuestions = [{"label":$L("Select a question"), "value":-1}];
	},
	
	initQuestions: function() {
		if(RoamUtil.enableRoaming() === true) {
			RoamGuardDialog.turnOffRoamguard(
			{
				"sceneController": this.controller,
				"method": this.getAllSecurityQuestions.bind(this)
			});
			return;
		}
		this.getAllSecurityQuestions();
	},
	
	getAllSecurityQuestions: function() {
		this.questionsRequest = AppAssistant.accountService.getAllSecurityQuestions(
					Account.language+"_"+Account.country, this.readQuestions.bind(this), this.errorQuestions.bind(this));
	},
	
	readQuestions: function (response) {
		var i=0;
		var index = -1;
				
		if (response.challengeQuestions == undefined || Object.isArray(this.securityQuestions) === false 
														|| response.challengeQuestions.size() === 0) {
			Mojo.Log.error("no security questions");
			this.errorQuestions(response);
		} else {	
			var thatSecurityQuestions = this.securityQuestions;
			response.challengeQuestions.each(function(question){	
			
				if (Account.questionId != "-1") {
					if (Account.questionId == question.id) {
						index = i;
					} 
				}	
				thatSecurityQuestions.push({
					label: question.question,
					value: question.id
				});
				
			});
		}
				
		this.selectedIndex = index;
		Mojo.Log.info("Selected index = ", this.selectedIndex);
		if (this.questionsModel) {
			this.questionsModel.disabled = false;
			this.controller.modelChanged(this.questionsModel);
		}
	},
	
	errorQuestions: function (response) {
		Mojo.Log.error("Could not fetch questions");
		
		if (isConnected === false) {
			Account.action = "account-creation-connection-error";
			Mojo.Controller.stageController.pushScene('status');
			return;
		} else {
			Account.action = "account-creation-error";
			Mojo.Controller.stageController.pushScene('status');
			return;
		}
	},
	
	setup: function(){
		this.controller.listen(this.controller.get('target'), Mojo.Event.tap, FirstUseUtil.tapHandler.bindAsEventListener(this));
				
		this.questionsModel = {selectedQuestion: this.securityQuestions[0].label, choices: this.securityQuestions, disabled: true}; 
		this.controller.setupWidget('questionSelector', {modelProperty: 'selectedQuestion'}, this.questionsModel);	
		this.initQuestions();
		
		this.controller.listen(this.controller.get('questionSelector'), Mojo.Event.propertyChange, this.questionChanged.bindAsEventListener(this));
		this.controller.listen(this.controller.get('questionSelector'), Mojo.Event.hold, this.removeLabelFromQuestions.bind(this)); 
		this.controller.listen(this.controller.get('questionSelector'), Mojo.Event.tap, this.removeLabelFromQuestions.bind(this));
				
		this.answerAttributes = {
			modelProperty: 'answer',
			multiline: false,
			maxLength: 50, 
			textReplacement: false,
			changeOnKeyPress: true,
			requiresEnterKey: true
		};
		
		this.answerModel = {
			'answer' : '',
			disabled: true
		};
		
		this.controller.setupWidget('answer', this.answerAttributes, this.answerModel);
		
		this.answerFocusHandler = this.answerHandler.bind(this);
		Mojo.Event.listenForFocusChanges(this.controller.get('answer'), this.answerFocusHandler);
		
		this.controller.listen(this.controller.get('answer'), Mojo.Event.propertyChange, this.answerAdded.bind(this));
		
		this.keyPressEventHandler =  FirstUseUtil.handleKeyPressEvent.bind(this);
		//this.controller.listen(this.controller.sceneElement, Mojo.Event.keydown, this.keyPressEventHandler);
		
		this.isAnswerInFocus = false;
				
		this.buttonModel = {
			disabled: true,
			buttonLabel : $L('Next'),
			buttonClass: 'palm-button'
		};
		
		this.controller.setupWidget('submitAnswer', this.buttonAttr, this.buttonModel);
		Mojo.listen(this.controller.get('submitAnswer'), Mojo.Event.tap, this.submitAnswer.bindAsEventListener(this));
		this.toggleDisabled();
	},
	
	startListeningToKeyPress: function () {
		Mojo.Event.listen(this.controller.document, Mojo.Event.keydown, this.keyPressEventHandler, true);
	},
	
	stopListeningToKeyPress: function () {
		Mojo.Event.stopListening(this.controller.document, Mojo.Event.keydown, this.keyPressEventHandler, true);
	},
	
	activate: function () {
		this.startListeningToKeyPress();
	},
	
	deactivate: function () {
		this.stopListeningToKeyPress();
	},
	
	toggleDisabled: function() {
       if(this.answerModel.answer.length > 0) {
		  	this.buttonModel.disabled = false;
			this.controller.modelChanged(this.buttonModel);
	   } else {
	   		this.buttonModel.disabled = true;
			this.controller.modelChanged(this.buttonModel);
	   }
    },
	
	answerHandler: function (event) {
		this.isAnswerInFocus = !this.isAnswerInFocus;
		if(this.isAnswerInFocus) {
			var height = $("firstuse-main").getHeight();
			this.controller.sceneScroller.mojo.scrollTo(0, -height, true);
		}
		this.toggleListener(this.isAnswerInFocus);
	},
	
	toggleListener: function (flag) {
		if(flag === true) {
			this.stopListeningToKeyPress();
		} else {
			this.startListeningToKeyPress();
		}
	},
	
	answerAdded: function(event) {
	 	this.answerModel.answer = event.value;	
		this.toggleDisabled();
		if (event && Mojo.Char.isEnterKey(event.originalEvent.keyCode)) {
			if (this.buttonModel.disabled == false) {
				this.submitAnswer();
				Event.stop(event);
			}
		}	
	},
	
	questionChanged: function(event) {
		this.removeLabelFromQuestions();
		var newId = this.questionsModel.selectedQuestion;
		if(newId !== this.selectedQuestionId) {
			Mojo.Log.info("Question is changed");
			this.selectedQuestionId = newId;
		}
		this.answerModel.disabled = false;
		this.controller.get('answer').mojo.focus();
		this.controller.modelChanged(this.answerModel);
		
	},
	
	removeLabelFromQuestions: function() {
		if(this.isAnswerInFocus === true) {
			this.controller.get('answer').mojo.blur();
			this.startListeningToKeyPress();
		}
		if (Object.isArray(this.securityQuestions) && (this.securityQuestions.size() > 0) 
				&& (this.securityQuestions[0].value === -1)) {
			this.securityQuestions.shift();
			this.controller.modelChanged(this.questionsModel, this);
		}	
	},
	
	submitAnswer: function() {
		Account.response = this.answerModel.answer;
		Account.questionId = this.selectedQuestionId;
		if(RoamUtil.enableRoaming() === true) {
			RoamGuardDialog.turnOffRoamguard(
			{
				"sceneController": this.controller,
				"method": this.pushWaitScene.bind(this)
			});
			return;
		}
		this.pushWaitScene();
	},
	
	pushWaitScene: function() {
		Mojo.Controller.stageController.pushScene('wait', 'createAccount');
	}
});	