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

var SecurityconfigAssistant = Class.create({
	initialize: function() {
		this.switchAppOnInfo = $L("Swiping the entire length of the gesture area will switch to the next or previous app.");
		this.switchAppOffInfo = $L("Any right to left swipe on the gesture area will perform the back gesture.");
		this.newSecurity = '';	
		this.dialogBox = null;
		
		this.securityPolicy = false;
		this.requiredLockMode = 'password';
		
		this.getSecurityPolicyReq = SystemService.getSecurityPolicy(this.handleSecurityPolicy.bind(this));
		this.getSystemAlertsSetting = SystemService.getShowAlertWhenLocked(this.updateAlertSettings.bind(this));				
	},
	
	onOffToggleOpt: {
        modelProperty: 'value',
        enableProp: 'enabled',        
    },
    
    switchApptoggleModel: {
        value: false,
    },
	
	alertToggleModel: {
        value: false,
    },
	
	ledThrobberToggleModel: {
		 value: false,
	},
	
	sliderattributes: {
			modelProperty: 'value',
			maxValue: 100,
			minValue: 10,
			round: false,
			updateInterval: 0.1
	},	
				
    brightnessModel: {
     	 'value' : 10
  	},
		
	setup: function(){
		
		//this.controller.get('fixedtimerrow').hide();
			
		this.controller.setupWidget('showAlerts', this.onOffToggleOpt, this.alertToggleModel);
		Mojo.Event.listen($('showAlerts'),'mojo-property-change', this.toggleShowAlerts.bindAsEventListener(this));
		
		this.controller.setupWidget('blinkAlerts', this.onOffToggleOpt, this.ledThrobberToggleModel);
		Mojo.Event.listen($('blinkAlerts'),'mojo-property-change', this.toggleLEDThrobber.bindAsEventListener(this));
		
		this.controller.setupWidget('switchApps', this.onOffToggleOpt, this.switchApptoggleModel);
		Mojo.Event.listen($('switchApps'),'mojo-property-change', this.toggleSwitchApps.bindAsEventListener(this));
		
		this.controller.get('switchAppsInfo').innerHTML = this.switchAppOffInfo;
		
		this.controller.setupWidget('lockTimer', {
			label: $L("Lock After"),
			choices: this.availableLockTimers,
			modelProperty: 'currentLockTimer',
			multiline: true
		}, this.lockTimerModel);

		Mojo.Event.listen($('lockTimer'),'mojo-property-change', this.lockTimerChanged.bindAsEventListener(this));

		this.controller.setupWidget('screenOffTimer', {
			label: $L("Turn off after"),
			choices: this.availableTimers,
			modelProperty: 'currentTimer',
			multiline: true
		}, this.timerModel);
		
		Mojo.Event.listen($('screenOffTimer'),'mojo-property-change', this.screenTimerChanged.bindAsEventListener(this));
		Mojo.Event.listen($('secureUnlock'),'mojo-property-change', this.secureLockChanged.bindAsEventListener(this));
		
		this.controller.setupWidget('secureUnlock', {
			choices: this.availableSecurity,
			modelProperty: 'currentSecurity'
		}, this.securityModel);
		
		this.controller.setupWidget('brightness', this.sliderattributes,this.brightnessModel);
		Mojo.Event.listen($('brightness'),'mojo-property-change', this.handleBrightnessChange.bindAsEventListener(this));
		
		this.spinnerLAttrs = {
			spinnerSize: 'small'
		},
		this.spinnerModel = {
			spinning: false
		},
		this.controller.setupWidget('setwallpaper-spinner', this.spinnerLAttrs, this.spinnerModel);
		Mojo.Event.listen($('setwallpaper'),'mojo-tap', this.launchFilePicker.bindAsEventListener(this));
		
		Mojo.Event.listen($('changepassword'),'mojo-tap', this.launchModifyCredential.bindAsEventListener(this));
		$('securelastrow').hide();
		
		//App Menu - Remove default items and add only Edit & Help items.
		var appMenuModel = {
	        visible: true,
	        items: [Mojo.Menu.editItem,{label:$L('Help'), command:Mojo.Menu.helpCmd}
	            ]
	        };
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems:true}, appMenuModel);		
	},
	
	handleCommand: function(event) {
		if (event.type == Mojo.Event.command) {
			if(event.command == Mojo.Menu.helpCmd) {
				new Mojo.Service.Request('palm://com.palm.applicationManager', {
					method: 'open',
					parameters: {'id': 'com.palm.app.help',params: {'target': 'http://help.palm.com/screen/index.html'}}});
			}
		}	
	},
	
	activate: function() {
				
	},

	//Model for Lock Timer Selection List
	lockTimerModel: {currentLockTimer: 0},

	//Available Lock Timer Values.
	availableLockTimers: [
		{label: $L('Screen turns off'), value:0}, 
		{label: $L('30 seconds'), value:30}, 
		{label: $L('1 minute'), value:60},
		{label: $L('2 minutes'), value:120},
		{label: $L('3 minutes'), value:180},
		{label: $L('5 minutes'), value:300},
		{label: $L('10 minutes'), value:600},
		{label: $L('30 minutes'), value:1800}
	],
		
	//Model for Timer Selection List
	timerModel: {currentTimer: 30},
	
	//Available Timer Values.
	availableTimers: [{label: $L('30 seconds'), value:30},{label: $L('1 minute'), value:60},{label: $L('2 minutes'), value:120},{label: $L('3 minutes'), value:180}],
	
	//Model for Security Selection List
	securityModel: {currentSecurity: 'none'},
	
	//Available Security Values.
	availableSecurity: [{label: $L('Off'), value: 'none'},{label: $L('Simple PIN'), value: 'pin'},{label: $L('Password'), value: 'password'}],
	
	
	handleSystemlockMode: function(payload) {
		if(!payload)
			return;
		this.currentSecurity = payload.lockMode || 'none';
		this.showModifyRow();
		this.revertChanges();
	},
	
	handleSystemlockValue: function(payload) {
		if(!payload)
			return;
		this.systemlockValue = payload.passcode;
			
	},
	
	handleSecurityPolicy: function(payload) {
		
		if(payload.returnValue && payload.policy) {
			this.parseSecurityPolicy(payload.policy);
		}
		else {
			this.securityPolicy = false;
		}
		
		this.getInitialValues();
	},
	
	parseSecurityPolicy: function(policy) {
		
		//save the policy
		this.securityPolicyObj = policy;
		
		//Find out if the Lock Timer is set.
		if(policy.inactivityInSeconds !== undefined) {
			this.securityPolicyInactivityTimer = policy.inactivityInSeconds;
		}
		else {
			this.securityPolicyInactivityTimer = 0;
		}
		
		//Find out the password policies and get the password message.
		if(policy.password && policy.password.enabled) {
			this.securityPolicy = true;
			
			if(policy.password.alphaNumeric === false && policy.password.minLength > 0) {
				this.passwordHintText = $L("Password must be at least #{minLength} characters.").interpolate(policy.password);
			} 
			else if(policy.password.alphaNumeric && policy.password.minLength > 0) 
				this.passwordHintText = $L("Password must be #{minLength} or more characters long and contain both numbers and letters.").interpolate(policy.password);
			else if(policy.password.alphaNumeric)
				this.passwordHintText = $L("Password must contain both numbers and letters.");
			else 
				this.passwordHintText = '';
			
			//Remove the 'Off' from the list option, if the policy requires PIN or Password.
			if(policy.password.alphaNumeric === false) {
				this.requiredLockMode = "PinOrPass";
				this.availableSecurity.splice(0, 1);
				this.controller.modelChanged(this.securityModel);
			}
		}
		else {
			//Password not enforced.
			this.securityPolicy = false;
		}
		
		//Save the Max tries
		this.maxRetries = policy.password.maxRetries;
		
		//Find out the Policy Status
		this.policyEnforced = policy.status.enforced;
		this.retriesLeft = policy.status.retriesLeft;
		
	},
	
	getInitialValues: function() {
		var updateUI = this.updateUI.bind(this);
		//Get the current value of Screen Time Off.
		this.controller.serviceRequest('palm://com.palm.display/control', {
			method: 'getProperty', 
			onSuccess: function(response) {
			    updateUI(response.timeout,response.maximumBrightness);
			},
			parameters:{properties:['timeout','maximumBrightness']}
	    });
		
		this.getSystemlockModeReq = SystemService.getSystemlockMode(this.handleSystemlockMode.bind(this));
		this.getSystemlockTimeoutReq = SystemService.getSystemlockTimeout(this.handleSystemlockTimeout.bind(this));
	},
	
	updateUI: function(timeout,maximumBrightness) {
		
		if(maximumBrightness != undefined) {
			this.brightnessModel.value = maximumBrightness;
			this.controller.modelChanged(this.brightnessModel, this);
		}		
		if(timeout != undefined) {
			this.timerModel.currentTimer = timeout;
			this.controller.modelChanged(this.timerModel,this);
		}
	},

	handleSystemlockTimeout: function(response) {

		if (response.lockTimeout !== undefined) {
			this.lockTimerModel.currentLockTimer = response.lockTimeout;

			if (this.securityPolicyInactivityTimer !== undefined && this.securityPolicy) {
				for (var i=0; i<this.availableLockTimers.length; i++) {
					if (this.availableLockTimers[i].value > this.securityPolicyInactivityTimer) {
						this.availableLockTimers.splice(i, this.availableLockTimers.length-i);
						break;
					}
				}
				//The last value in the list should be same as the policy inactivity timer value. If not, add it to the list.
				if(this.availableLockTimers[this.availableLockTimers.length-1].value !== this.securityPolicyInactivityTimer) {
					var obj = {};
					obj.label = $L('#{policyInactivityTimer} minutes').interpolate({policyInactivityTimer: this.securityPolicyInactivityTimer/60});
					obj.value = this.securityPolicyInactivityTimer;
					this.availableLockTimers.push(obj);
				}	
			}
			this.controller.modelChanged(this.lockTimerModel, this);
		}
		delete this.getSystemlockTimeoutReq;
	},	
	
	updateAlertSettings: function(payload){
		
		if (!payload) 
			return;
		if (payload.showAlertsWhenLocked != undefined) {
			this.alertToggleModel.value = payload.showAlertsWhenLocked;
			this.controller.modelChanged(this.alertToggleModel, this);
		}
		
		if (payload.sysUiEnableNextPrevGestures != undefined) {
			this.switchApptoggleModel.value = payload.sysUiEnableNextPrevGestures;
			this.controller.modelChanged(this.switchApptoggleModel, this);
			if(payload.sysUiEnableNextPrevGestures) {
				this.controller.get('switchAppsInfo').innerHTML = this.switchAppOnInfo;
			}	
			else {
				this.controller.get('switchAppsInfo').innerHTML = this.switchAppOffInfo;
			}
		}
		
		if (payload.BlinkNotifications != undefined) {
			this.ledThrobberToggleModel.value = payload.BlinkNotifications;
			this.controller.modelChanged(this.ledThrobberToggleModel, this);
		}
		
		//Demo Device -- Hide the PIN / Password options.
		if(payload.onDeviceDemoRunning != undefined && payload.onDeviceDemoRunning === true) {
			this.availableSecurity.splice(1,2); 
			this.controller.modelChanged(this.securityModel);
		}
	},
	
	showModifyRow: function() {
		if (this.currentSecurity == 'pin' || this.currentSecurity == 'password') {

			if (this.currentSecurity == 'pin') {
				$('changepassword').innerHTML = $L("Change PIN");
			}
			else {
				$('changepassword').innerHTML = $L("Change Password");
			}

			$('secureFirstrow').removeClassName('single');
			$('secureFirstrow').addClassName('first');

			$('securelastrow').removeClassName('first');
			$('securelastrow').show();
			$('locktimerrow').show();

			if(this.securityPolicy) {
				if(!this.policyEnforced) {
					if (this.requiredLockMode == "password") {
						this.availableSecurity.splice(0, 1);
						if(this.currentSecurity == 'pin')
							$('securelastrow').hide();
					}
				}
				else {
					if (this.securityPolicyObj.password.alphaNumeric) {
						$('secureFirstrow').hide();
						$('securelastrow').addClassName('first');
					}
				}
				this.controller.modelChanged(this.securityModel);
			}
		}
		else {
			$('secureFirstrow').removeClassName('first');
			$('secureFirstrow').addClassName('single');
			$('securelastrow').hide();
			$('locktimerrow').hide();
			if(this.securityPolicy) {
				if(this.requiredLockMode == "password") {
					this.availableSecurity.splice(1,1);
				}
				this.controller.modelChanged(this.securityModel);
			}
		}
					
	},
	
	launchModifyCredential: function(event) {
		Event.stop(event);
		if (this.currentSecurity == 'pin') {
			this.controller.stageController.pushScene({name: "pin", automaticFocusAdvance: false},"changePin",this);
		}
		else if(this.currentSecurity == 'password') {
			this.askPassword();
			this.newSecurity = "password";
		}			
	},

	lockTimerChanged: function(event) {
		if (event.value === undefined)
			return;

		Mojo.Log.info("attempting to set lock timeout to %d", event.value);
		SystemService.setSystemlockTimeout(parseInt(event.value));
	},
	
	screenTimerChanged: function(event) {
		if(!event.value)
			return;
		
		//Set the timer.
		this.controller.serviceRequest('palm://com.palm.display/control', {
			method: 'setProperty', 
			parameters:{timeout:parseInt(event.value)}	
		});
	},
	
	handleBrightnessChange: function(event) {
		if(!event)
			return;
		this.controller.serviceRequest('palm://com.palm.display/control', {
			method: 'setProperty', 
			parameters:{maximumBrightness:parseInt(event.value)}
		});
	},
	
	secureLockChanged: function(event) {
		
		if(!event.value)
			return;
		
		Event.stop(event);
		this.newSecurity = event.value;	
		
		if(this.currentSecurity === 'none') {
			this.changeSecureLock(event.value,false);
		}
		else if(this.currentSecurity === 'pin') {
			this.askPin();
		}
		else if(this.currentSecurity === 'password') {			
			this.askPassword();
		}		
		
	},
	
	askPin: function() {
		this.controller.stageController.pushScene({name: "pin", automaticFocusAdvance: false},"verifyPin",this);
	},
	
	pinVerified: function(pinCorrect) {
		if(pinCorrect)
			this.changeSecureLock(this.newSecurity,true);
		else {
			Mojo.Log.info("Pin was wrong");
			this.revertChanges();
		}
	},
	
	askPassword: function() {
		this.dialogBox = this.controller.showDialog({
			template: 'template/password-box',			
			assistant: new VerifyPasswordAssistant(this,this.systemlockValue),			
		});
	},
	
	passwordVerified: function(passwordCorrect) {
		if (passwordCorrect) {
			this.changeSecureLock(this.newSecurity,false);
		}
		else {
			Mojo.Log.info("Password was wrong");
			this.revertChanges();
			
		}
	},
	
	changeSecureLock: function(newSetting,setFocus) {
		if(newSetting == 'pin') {
			this.showPINDialogBox();				
		}
		else if (newSetting == 'password') {
			this.showPasswordDialogBox(setFocus);				
		}
		else {
			Mojo.Log.info("Security is Off");
			this.currentSecurity = 'none';
			$('lockImg').hide();
			this.setSystemlockModeReq = SystemService.setSystemlockValue('none','');
			this.showModifyRow();
		}	
	},
	
	setPinCode: function(pincode) {
		
		if(pincode === '') {
			Mojo.Log.info("PIN code is Emplty");
			this.revertChanges();
			return;
		}
		this.setSystemlockModeReq = SystemService.setSystemlockValue('pin',pincode, this.handleSetPasscodeResponse.bind(this));	
	},
	
	handleSetPasscodeResponse: function(response) {
		Mojo.Log.error("Response "+ Object.toJSON(response));
		if(response.returnValue) {
			this.currentSecurity = 'pin';
			$('lockImg').show();
			this.policyEnforced = true;
			this.showModifyRow();
		}
		else 
			this.revertChanges();
	},
	
	pinAlreadySet: function() {
		this.currentSecurity = 'pin';
		$('lockImg').show();
		this.policyEnforced = true;
		this.showModifyRow();
	},
	
	showPINDialogBox: function(prompt,showerror) {
		this.controller.stageController.pushScene({name: "pin", automaticFocusAdvance: false},"enterPin",this);	
	},
	
	setPassword: function(password) {
		Mojo.Log.info("Entered Password "+ password);
		if(password === '') {
			Mojo.Log.info("Password is Emplty");
			this.revertChanges();
			return;
		}
		this.currentSecurity = 'password';
		this.systemlockValue = password;
		$('lockImg').show();
		this.setSystemlockModeReq = SystemService.setSystemlockValue('password',password);
		this.showModifyRow();	
	},
	
	passwordAlreadySet: function(password) {
		this.currentSecurity = 'password';
		this.systemlockValue = password;
		this.policyEnforced = true;
		$('lockImg').show();
		this.showModifyRow();	
	},
	
	
	showPasswordDialogBox: function(setFocus) {		
		this.dialogBox = this.controller.showDialog({
			template: 'template/security-password-box',
			assistant: new PasswordAssistant(this,setFocus),			
		});		
	},

	revertChanges: function() {
		this.securityModel.currentSecurity = this.currentSecurity;
		this.controller.modelChanged(this.securityModel);
		if(this.currentSecurity != 'none')
			$('lockImg').show();
		else
			$('lockImg').hide();
	},
		
	toggleShowAlerts: function(event) {
		if(!event)
			return;		
		SystemService.setShowAlertWhenLocked(event.value);		
	},
	
	toggleLEDThrobber: function(event) {
		if(!event)
			return;		
		SystemService.setLEDThrobber(event.value);		
	},
	
	toggleSwitchApps: function(event) {
		if(!event)
			return;		
		SystemService.setSwitchAppSettings(event.value);
		if(event.value) {
			this.controller.get('switchAppsInfo').innerHTML = this.switchAppOnInfo;
		}	
		else {
			this.controller.get('switchAppsInfo').innerHTML = this.switchAppOffInfo;
		}
	},
	
	
	
	launchFilePicker: function(event) {
		//Is setting wallpaper in progress?
		if(this.spinnerModel.spinning)
			return;
		var params = {"kinds": ["image"],"onSelect":this.selectedImage.bind(this),"onAppMenuCommand":this.handleCommand.bind(this),actionType:"open",
						actionName: $L("Set wallpaper"),  crop: {width: 318,height:479 }};
		Mojo.FilePicker.pickFile(params,Mojo.Controller.stageController);
	},
	
	selectedImage: function(response) {	
		if(!response)
			return;
		
		if(!response.fullPath)
			return;
		
		this.spinnerModel.spinning = true;
		this.controller.modelChanged(this.spinnerModel,this);
		$('setwallpaper').innerHTML = $L("Setting wallpaper");
			
		var params = {"target": encodeURIComponent(response.fullPath)};
		
		var cropInfoWindow = response.cropInfo.window;
		
		if(cropInfoWindow) {
			if(cropInfoWindow.scale)
				params["scale"] = cropInfoWindow.scale;
			
			if(cropInfoWindow.focusX)
				params["focusX"] = cropInfoWindow.focusX;
			
			if(cropInfoWindow.focusY)
				params["focusY"] = cropInfoWindow.focusY;
		}			
		this.importWallPaper(params);		
		
	},
	
	importWallPaper: function(params) {
						
		var setWallpaper = this.setWallpaper.bind(this);
		
		this.importWallpaperReq = new Mojo.Service.Request("palm://com.palm.systemservice/wallpaper", {
			method: 'importWallpaper', 
			parameters: params,
			onSuccess: function(payload) {
           	 	if(payload.wallpaper)
					setWallpaper(payload.wallpaper);		
       		},
			onFailure: function(payload) {
				
			},
	});
	},
	
	setWallpaper: function(wallpaperInfo) {
			
		this.setWallpaperReq = new Mojo.Service.Request("palm://com.palm.systemservice/", {
		method: 'setPreferences', 
		parameters: {"wallpaper":wallpaperInfo},
		onSuccess: function(a) {
			this.spinnerModel.spinning = false;
			this.controller.modelChanged(this.spinnerModel,this);
			$('setwallpaper').innerHTML = $L("Change wallpaper");			
        }.bind(this),
	});
	},
	
	showErrorDialog: function() {
		this.spinnerModel.spinning = false;
		this.controller.modelChanged(this.spinnerModel,this);
		$('setwallpaper').innerHTML = $L("Change wallpaper");
		this.controller.showAlertDialog({
			onChoose : function(value) {},
			message: $L('Unable to set wallpaper!'),
			choices:
			[{
				label: $L('Close'),
				type: "dismiss",
				value: 'dismissed'
			}]
		});	
	},
});


var VerifyPasswordAssistant = Class.create({
	
	initialize: function(sceneAssistant) {
		this.sceneAssistant = sceneAssistant;
		this.enteredPassword = '';
		this.passwordVerified = false;		
	},
	
	setup : function(widget) {
		
		Mojo.Log.info("Pincode assistant setup ");
		this.widget = widget;
						
		this.passwordAttributes = {
		textFieldName: "password",
		hintText: $L('enter password...'),
        property: 'value',
        multi: false,        
		changeOnKeyPress: true,
        disabled: false,
		requiresEnterKey: true,		
    	},
    
    	this.passwordModel = {
        'value': ''
    	},
		
		this.sceneAssistant.controller.setupWidget('password', this.passwordAttributes, this.passwordModel);
		$('password').observe(Mojo.Event.propertyChange, this.propertyChanged.bind(this));
		$('done_pw').addEventListener(Mojo.Event.tap, this.matchPassword.bindAsEventListener(this));
		$('cancel_pw').addEventListener(Mojo.Event.tap, this.cancel.bindAsEventListener(this));
				
		if(this.sceneAssistant.securityPolicy && this.sceneAssistant.retriesLeft == 1) {
			$('passworderrortext').innerHTML = $L("Password incorrect. If you enter an incorrect password now your phone will be erased.");
			$('passworderror').show();
		}
	},
	
	matchPassword: function(event) {
		if(!event)
			return;
		event.stop();
		SystemService.matchDevicePasscode($('password').mojo.getValue(),this.verifyPasswd.bind(this));
	},
	
	propertyChanged: function(event) {
		if(!event)
			return;
		
		if (event && Mojo.Char.isEnterKey(event.originalEvent.keyCode)) {
			this.matchPassword(event);
		}
	},
	
	cancel: function(event) {
		event.stop();
		this.sceneAssistant.passwordVerified(false);
		this.widget.mojo.close();	
	},
	
	cleanup: function() {
		if(this.passwordVerified === false) {
			this.sceneAssistant.passwordVerified(false);
		}
	},
	
	
	verifyPasswd: function(payload) {
		if(!payload)
			return;
				
		if(payload.returnValue === true ) {
			if(this.sceneAssistant.securityPolicy) 
				this.sceneAssistant.retriesLeft = this.sceneAssistant.maxRetries;
			this.passwordVerified = true;		
			Mojo.Log.info("Password Matches!!!");
			this.sceneAssistant.passwordVerified(true);
			this.widget.mojo.close();			
		}
		else {
			
			this.clearFields();
			
			if(this.sceneAssistant.securityPolicy) {
				this.sceneAssistant.retriesLeft = payload.retriesLeft;
				if(payload.retriesLeft === 1) { 
					$('passworderrortext').innerHTML = $L("Password incorrect. If you enter an incorrect password now your phone will be erased.");
				}
				else {
					$('passworderrortext').innerHTML = $L("Password incorrect. ") + Mojo.Format.formatChoice(payload.retriesLeft, 
								$L("##{num} tries remaining."), 
								{num: SystemService.numberToWord(payload.retriesLeft)});
				}
			}
			else 
				$('passworderrortext').innerHTML = $L("Incorrect password.");
			$('passworderror').show();
		}
	},
	
	clearFields: function() {
		this.passwordModel.value = '';
		this.sceneAssistant.controller.modelChanged(this.passwordModel,this);	
		$('password').mojo.focus();	
	},
	
	handleCommand: function(event) {
		if(event.type == Mojo.Event.back) {			
			this.sceneAssistant.revertChanges();
			event.stop();
			this.widget.mojo.close();								
		}
	}	
	
});

var PasswordAssistant = Class.create({
	
	initialize: function(sceneAssistant,setFocus) {
		this.sceneAssistant = sceneAssistant;
		this.enteredPin = '';
		this.firstPinInput = '';
		this.setFocus = setFocus;
		this.settingPassword = false;
	},
	
	setup : function(widget) {
		
		Mojo.Log.info("Pincode assistant setup ");
		this.widget = widget;
						
		this.attributes = {
     	 textFieldName: "password",
        property: 'value',
        multi: false,        
		changeOnKeyPress: true,
        disabled: false,		      
		hintText: $L('enter password...'),
    	};
   		 this.model = {
     		 'value' : ''
   		 };
		 
		 this.attributes1 = {
     	textFieldName: "password",
        property: 'value',
        multi: false,        
		changeOnKeyPress: true,
        disabled: false,	    
		hintText: $L('confirm password...'),
		requiresEnterKey: true,
    	};
   		 this.model1 = {
     		 'value' : ''
   		 };
		 
		 this.buttonattributes = {
				disabledProperty: 'disabled'
		 },
		 
		 this.donebuttonmodel = {
			buttonLabel : $L("Done"),
			buttonClass : "affirmative",
			disabled: false
		},
		this.cancelbuttonmodel = {
			buttonLabel : $L("Cancel"),
			disabled: false
		},
		 
		this.sceneAssistant.controller.setupWidget('passwordInput', this.attributes, this.model);
		this.sceneAssistant.controller.setupWidget('password_confirm', this.attributes1, this.model1);
		$('passwordInput').observe(Mojo.Event.propertyChange, this.propertyChanged.bind(this));
		$('password_confirm').observe(Mojo.Event.propertyChange, this.confirmPasswordpropertyChanged.bind(this));
		
		this.sceneAssistant.controller.setupWidget('done', this.buttonattributes, this.donebuttonmodel);
		this.sceneAssistant.controller.setupWidget('cancel', this.buttonattributes, this.cancelbuttonmodel);		
		$('cancel').addEventListener(Mojo.Event.tap, this.cancel.bindAsEventListener(this));	
   		$('done').addEventListener(Mojo.Event.tap, this.verifyPasswd.bindAsEventListener(this));
		
		if(this.sceneAssistant.passwordHintText)
			$('passwordhint').innerHTML = this.sceneAssistant.passwordHintText;
	},
	
	activate: function() {
		if(this.setFocus)
			$('passwordInput').mojo.focus();	
	},
	
	cleanup: function() {
		if(this.settingPassword === false)	
			this.sceneAssistant.revertChanges();
	},

	verifyPasswd: function(event) {
		Event.stop(event);
		
		if($('passwordInput').mojo.getValue() == $('password_confirm').mojo.getValue()) {
			if(this.sceneAssistant.securityPolicy) {
				this.settingPassword = true;
				this.donebuttonmodel.disabled = true;
				this.cancelbuttonmodel.disabled = true;
				this.sceneAssistant.controller.modelChanged(this.donebuttonmodel);
				this.sceneAssistant.controller.modelChanged(this.cancelbuttonmodel);
				this.setSystemlockPasswordReq = SystemService.setSystemlockValue('password',$('passwordInput').mojo.getValue(), this.handleSetPasswordResponse.bind(this));
			}
			else {
				this.sceneAssistant.setPassword($('password_confirm').mojo.getValue());
				this.widget.mojo.close();	
			}		
		}
		else {
			Mojo.Log.info("Password don't Match!!!");
			this.clearFields();
			$('errortext').innerHTML = $L("Passwords do not match.");
			$('passworderror').show();
		}
	},
	
	handleSetPasswordResponse: function(payload) {
		
		this.settingPassword = false;
		this.donebuttonmodel.disabled = false;
		this.cancelbuttonmodel.disabled = false;
		this.sceneAssistant.controller.modelChanged(this.donebuttonmodel);
		this.sceneAssistant.controller.modelChanged(this.cancelbuttonmodel);
		
		if(payload.returnValue) {
			this.sceneAssistant.passwordAlreadySet($('passwordInput').mojo.getValue());
			this.widget.mojo.close();	
		}
		else {
			this.clearFields();
			$('errortext').innerHTML = $L("Password does not match security requirements.");
			$('passworderror').show();
		}
	},
	
	propertyChanged: function(event) {
		if(!event)
			return;
		if($('passworderror').visible())
			$('passworderror').hide();
	},
	
	confirmPasswordpropertyChanged: function(event) {
		if (event && Mojo.Char.isEnterKey(event.originalEvent.keyCode)) {
			this.verifyPasswd(event);
		}
	},
		
	cancel: function(event) {
		this.sceneAssistant.setPassword('');
		this.widget.mojo.close();	
	},
	
	clearFields: function() {
		this.model1.value = '';
		this.model.value = '';
		this.sceneAssistant.controller.modelChanged(this.model,this);
		this.sceneAssistant.controller.modelChanged(this.model1,this);
		$('passwordInput').mojo.focus();	
	},
	
	handleCommand: function(event) {
		if(event.type == Mojo.Event.back) {	
			event.stop();
			if(this.settingPassword == true)
				return;		
			this.sceneAssistant.revertChanges();
			this.widget.mojo.close();										
		}
	}		
	
});

