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

var CarrierAuthDialogAssistant = Class.create({
	
	initialize: function(sceneAssistant, onSuccess) {
		this.sceneAssistant = sceneAssistant;
		this.controller = this.sceneAssistant.controller;
		this.onSuccess = onSuccess;
	},
	
	setup: function(widget) {
		this.widget = widget;
		
		Mojo.Log.info('setup')
		
		this.controller.setupWidget('code', {
			enterSubmits: true,
			focus: true,
			multiline: false,       
			modifierState: Mojo.Widget.numLock,
			focusMode: Mojo.Widget.focusSelectMode,
			maxLength: 40,
			requiresEnterKey: true			
		});
				
		this.okbuttonmodel = {
			buttonLabel : "OK",
			disabled: false
		};
		this.closebuttonmodel = {
			buttonLabel : "Close",
			disabled: false
		};
		this.controller.setupWidget('okButton', {}, this.okbuttonmodel);
		this.controller.setupWidget('closeButton', {}, this.closebuttonmodel);
		
		Mojo.Event.listen(this.controller.get('okButton'),'mojo-tap', this.handleSave.bind(this));
		Mojo.Event.listen(this.controller.get('closeButton'),'mojo-tap', this.handleClose.bind(this));
		
		this.populateSerialNumber();
	},
		
	handleSave: function() {
		this.controller.get('message').innerHTML = "Verifying Code";
		
		this.closebuttonmodel.disabled = true;
		this.okbuttonmodel.disabled = true;
		this.controller.modelChanged(this.closebuttonmodel, this);
		this.controller.modelChanged(this.okbuttonmodel, this);
		
		this.controller.serviceRequest('palm://com.palm.logctld', {
			method: 'validate',
			parameters: {
				"code": this.controller.get('code').mojo.getValue(),
				"sn": this.serialNumber
			},
			onSuccess: function(result) {
				this.handleClose();
				this.onSuccess();
			}.bind(this),
			onFailure: function(result) {
				this.controller.get('message').innerHTML = "Invalid Authorization Code entered.";
				this.closebuttonmodel.disabled = false;
				this.okbuttonmodel.disabled = false;
				this.controller.modelChanged(this.closebuttonmodel, this);
				this.controller.modelChanged(this.okbuttonmodel, this);
	            this.controller.get('code').mojo.focus();
			}.bind(this)
		});
		
	},
	
	handleClose: function() {
		this.widget.mojo.close();
	},
	
	populateSerialNumber: function() {
        this.controller.serviceRequest('palm://com.palm.preferences', {
			method: 'systemProperties/Get',
			parameters: {
          			key: 'com.palm.properties.PalmSN'
       		},
			onSuccess: function(result){
				this.serialNumber = result["com.palm.properties.PalmSN"].toUpperCase();
			}.bind(this),
			onFailure: function(result){
				Mojo.Log.error("getSerialNumber(): Failed " + result.errorText);
			}.bind(this)
    	});
	}
});