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

var LocationAutoEnableAssistant = Class.create({
	
	initialize: function(){
		FirstUseUtil.addDashboardSmall($('target'));
		saveCurrentState("location-auto-enable");
	},
	
	setup: function(){
		$('target').addEventListener(Mojo.Event.tap, FirstUseUtil.tapHandler.bindAsEventListener(this));
		// Listen to ## key presses
		this.controller.listen(this.controller.sceneElement, Mojo.Event.keydown, FirstUseUtil.handleKeyPressEvent.bind(this));
				
		this.buttonAttr = {
			disabledProperty: 'disabled'
		};
		
		this.buttonModel = {
			disabled: false,
			buttonLabel : $L('Enable auto locate'),
			buttonClass: 'palm-button'
		};
		
		this.controller.setupWidget('enable', this.buttonAttr, this.buttonModel);
		Mojo.listen(this.controller.get('enable'), Mojo.Event.tap, this.setPreferences.bindAsEventListener(this));
		
		this.rejectButtonAttr = {
			disabledProperty: 'disabled'
		};
		
		this.rejectButtonModel = {
			disabled: false,
			buttonLabel : $L("Ask each time"),
			buttonClass: 'palm-button'
		};
		
		this.controller.setupWidget('disable', this.rejectButtonAttr, this.rejectButtonModel);
		Mojo.listen(this.controller.get('disable'), Mojo.Event.tap, this.rejectAutoLocate.bindAsEventListener(this));
	},
	
	handleCommand: function(event) {
		if (event.type == Mojo.Event.back) {
			event.preventDefault();
			event.stopPropagation();
		}	
	},
	
	setPreferences: function (event) {
		this.buttonModel.disabled = true;
		this.controller.modelChanged(this.buttonModel);
		AppAssistant.locationService.setAutoLocatePrefs(true, this.controller);
		this.getMachineName();
	},
	
	getMachineName: function () {
		this.machineNameRequest = AppAssistant.accountService.getMachineName(
										this.readMachineName.bind(this),
										this.errorMachineName.bind(this));
	},
	
	readMachineName: function (response) {
		response = $H(response);
		if(response.values()) {
			var machineName = response.values().first();
			//TODO Revisit this to fix the flow for different types of devices
			Mojo.Controller.stageController.pushScene(tutorialScript);
		}
	},
	
	errorMachineName: function (response) {
		Mojo.Log.error("---------- Error in reading machine name -----------%j", response);
		Mojo.Controller.stageController.pushScene(tutorialScript);
	},
	
	rejectAutoLocate: function (event) {
		this.rejectButtonModel.disabled = true;
		this.controller.modelChanged(this.rejectButtonModel);
		this.getMachineName();
	}
		
}); 

