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

var MslAssistant = Class.create({
	
	initialize: function(sceneAssistant) {
		this.sceneAssistant = sceneAssistant;
		this.controller = this.sceneAssistant.controller;
		
	},
	
	setup: function(parent){
		this.textAttributes = {
			enterSubmits: true,
			focus: true,
			multiline: false,       
			modifierState: Mojo.Widget.numLock,
			focusMode: Mojo.Widget.focusSelectMode,
			maxLength: 40,
			modelProperty: "mslValue",
			requiresEnterKey: true			
		};
		
		this.mslModel = {
			'mslValue':''
		},		
		this.controller.setupWidget('msl', this.textAttributes, this.mslModel);
		this.controller.get('msl').observe(Mojo.Event.propertyChange, this.mslEntered.bind(this));
		this.parent = parent;
		
		this.buttonattributes = {
				disabledProperty: 'disabled'
		},
		this.okbuttonmodel = {
			buttonLabel : "OK",
			disabled: false
		},
		this.closebuttonmodel = {
			buttonLabel : "Close",
			disabled: false
		},
		
		this.controller.setupWidget('okButton', this.buttonattributes, this.okbuttonmodel);
		this.controller.setupWidget('closeButton', this.buttonattributes, this.closebuttonmodel);
		
		Mojo.Event.listen(this.controller.get('okButton'),'mojo-tap', this.handleSave.bindAsEventListener(this));
		Mojo.Event.listen(this.controller.get('closeButton'),'mojo-tap', this.handleClose.bindAsEventListener(this));
	},
		
	handleSave: function() {
		
		this.msl = this.controller.get('msl').mojo.getValue();
		if(!this.msl)
			return;
		
		this.controller.get('message').innerHTML = "Verifying MSL";
		this.closebuttonmodel.disabled = true;
		this.okbuttonmodel.disabled = true;
		this.controller.modelChanged(this.closebuttonmodel, this);
		this.controller.modelChanged(this.okbuttonmodel, this);
		
		TelephonyCommands.enterProgramMode(this.msl, this.doProgramming.bind(this));
		
	},
	
	doProgramming: function (success, message) {
		
		if (success) {
			this.sceneAssistant.verifiedMSL(true,this.msl);
			this.controller.get('message').innerHTML = "Success";
			this.handleClose();			 
		} else {
			this.sceneAssistant.verifiedMSL(false,this.msl);
			this.controller.get('message').innerHTML = message;
            this.closebuttonmodel.disabled = false;
			this.okbuttonmodel.disabled = false;
			this.controller.modelChanged(this.closebuttonmodel, this);
			this.controller.modelChanged(this.okbuttonmodel, this);
			this.controller.get('msl').mojo.focus();
		}
	},
	
	mslEntered: function(event) {
		if (event && Mojo.Char.isEnterKey(event.originalEvent.keyCode)) {
			this.handleSave();
		}
	},
	
	handleClose: function() {
		this.parent.mojo.close();
	},
	
});