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

var PoundGPSAssistant = Class.create({
	
	initialize: function(sceneAssistant) {
		
	},
	
	setup:function() {		
		this.controller.document.body.addClassName("no-wallpaper");	
		
		this.controller.get('gpsinfo').hide();
		this.attributes = {
			disabledProperty: 'disabled',
			type: Mojo.Widget.activityButton
		};
		this.model = {
			buttonLabel : "Get Fix",
			buttonClass: ''
		};
		this.controller.setupWidget('getfix', this.attributes, this.model);				
		this.controller.get('getfix').observe(Mojo.Event.tap,this.getGPSInfo.bind(this));		
	},
	
	getGPSInfo:function() {
		this.controller.get('getfix').mojo.activate();
		// don't display fixes that are old
		var reqTime = Date.now();
		this.gpsservicereq = new Mojo.Service.Request("palm://com.palm.location", {
		method: 'getCurrentPosition', 
		onSuccess: function(response) {	
			this.controller.get('getfix').mojo.deactivate();		
			if (response.errorCode == 0) {
				if (response.horizAccuracy < 100 && reqTime < response.timestamp) {
					this.controller.get('lat').innerHTML = response.latitude;
					this.controller.get('long').innerHTML = response.longitude;
					this.controller.get('velocity').innerHTML = response.velocity;
					this.controller.get('altitude').innerHTML = response.altitude;
					this.controller.get('heading').innerHTML = response.heading;
					this.controller.get('haccuracy').innerHTML = response.horizAccuracy;
					this.controller.get('vaccuracy').innerHTML = response.vertAccuracy;
					this.controller.get('gpsinfo').show();
				} else {
					this.showError($L("Position Unavailable."));
				}				
			}
			else {
				if(response.errorCode == 1)
					this.showError($L("Timeout."));
				else if(response.errorCode == 2)
					this.showError($L("Position Unavailable."));
				else 
					this.showError($L("Unknown Error."));
			}
		}.bind(this),
		onFailure: function(response) {
			this.controller.get('getfix').mojo.deactivate();
		   this.showError(response.errorText || $L("Error occurred."));
		}.bind(this),
		onComplete: function(response) {
			this.controller.get('getfix').mojo.deactivate();
			Mojo.Log.info("PhoneApp: - GPS response- Complete %j", response);
			if(response.errorText)
				this.showError(response.errorText);
		}.bind(this),
		parameters: {appId:"com.palm.app.phone",accuracy:1,maximumAge:0,responseTime:3 },
	    });	
	},
	
	showError: function(msg) {
		this.controller.showAlertDialog({
		    onChoose: function(value) {},
		    title: $L("GPS Error"),
		    message: msg,
		    choices:[
	        {label: $L('Close'), value:'dismissed', type:'color'}    
		    ]
		  });	
	},  
	
	cleanup:function() {
		this.controller.document.body.removeClassName("no-wallpaper");
		//TODO: stop the update.
	}
	
});
