GpsAssistant.prototype.id = 0;
GpsAssistant.prototype.AppId = "CROTEST";
GpsAssistant.prototype.GetFixRequest = null;
GpsAssistant.prototype.StartTrackingRequest = null;
GpsAssistant.prototype.FixRequestTime = 0;

function GpsAssistant()
{
	
}

GpsAssistant.prototype.handleCommand = function(event) {
	if(event.type == Mojo.Event.command) {
		if (event.command == Mojo.Menu.helpCmd) {
			Event.stop(event);
			var openParams = {
				target: 'http://help.palm.com/device_info/index.html'
			};
			this.controller.serviceRequest('palm://com.palm.applicationManager', {
				method: 'open',
				parameters: {
					id: 'com.palm.app.help',
					params: openParams
				}
			});
		}else if (typeof this[event.command] == "function") {
			this[event.command](event);
		}
	} else if (event.type == Mojo.Event.commandEnable && 
		 (event.command == Mojo.Menu.helpCmd)) {
		event.stopPropagation();
	}
}

GpsAssistant.prototype.setup = function()
{
	this.GPSNotEnabled = false;
	this.setGPSOn = false;
	this.appMenuModel = {
		visible: true,
		items: [Mojo.Menu.editItem, Mojo.Menu.helpItem]
	};
	this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.appMenuModel);

	this.controller.get('TryAgain').observe(Mojo.Event.tap, this.handleTryAgain.bindAsEventListener(this));
	 this.cmdMenuModel = {
			visible:true,
			items: [{ }] 
    };  
	var commandMenuItems = new Array();
    
	var cmdmenuItem1 = new Object();
    commandMenuItems.push(cmdmenuItem1);
	var cmdmenuItem2 = new Object();
    commandMenuItems.push(cmdmenuItem2);
	var cmdmenuItemDone = new Object();
    cmdmenuItemDone.label = $L("Done");
    cmdmenuItemDone.command = "handleDone";
    commandMenuItems.push(cmdmenuItemDone);
	
	this.cmdMenuModel.items = commandMenuItems;

	
    this.controller.setupWidget(Mojo.Menu.commandMenu, {}, this.cmdMenuModel);	
	//this.controller.get('Done').observe(Mojo.Event.tap, this.handleDone.bindAsEventListener(this));

	//this.controller.setupWidget( Mojo.Menu.commandMenu, undefined, this.commandMenuItems );

	this.controller.setupWidget('spinnerDiv', 
		{ spinnerSize: Mojo.Widget.spinnerLarge },  
		{ spinning: true });
		
	 this.gpsModel = {
            items: [],
			'listTitle':$L('GPS')
        };
	   
     
        this.controller.setupWidget('gpsList', {
            itemTemplate: 'gps/item',
			listTemplate: 'gps/listcontainer'
        }, this.gpsModel);
	
		this.getGPSPrefs();

}


GpsAssistant.prototype.handleTryAgain = function()
{

	this.controller.get('status').update( $L("Attempting to receive a signal using the GPS receiver.  Please wait.") );
	this.controller.get('gpsList').hide();
	this.controller.get('spinnerDiv').show();
	this.getCurrentPosition();

	/*
	this.GetFixRequest = new Mojo.Service.Request("palm://com.palm.location", {
			method: 'getCurrentPosition',
			parameters: {appId: this.AppId, accuracy:3, responseTime:3},
			onSuccess: this.GotGPSData.bind(this),
			onFailure: this.GotGPSData.bind(this)
		});
	*/

}

GpsAssistant.prototype.handleDone = function()
{
	this.controller.stageController.popScenesTo("interactivetests");
}

function roundNumber( number, places )
{
	return Math.round(number*Math.pow(10,places))/Math.pow(10,places);
}

function AddTableRow(item, data)
{
	var str = '<tr class="resultRow">';
	str += '<td align="center">' + item + '</td>';
	str += '<td align="center">' + data + '</td>';
	str += '</tr>';
	return str;
}

GpsAssistant.prototype.GotGPSData = function(data)
{
	//console.log( "GPS: Request complete: " + Object.toJSON(data) );
	this.gpsModel.items.clear();
	//this.controller.get('gpsList').show();
	this.controller.get('spinnerDiv').hide(); 
	if (data.errorCode == 0 && data.horizAccuracy < 100 && this.FixRequestTime < data.timestamp)
	{
		this.controller.get('gpsList').show();
		results = $L("The GPS radio receiver detected the signal.<br>");
		
		this.controller.get('status').update( results );
		var i = 0;
		var date = new Date( data.timestamp );
		var newdate =  Mojo.Format.formatDate( date, {date:"short"} ) ;
	    var newtimestamp = Mojo.Format.formatDate( date, {time:"short"} );
	   	
		this.gpsModel.items[i++] = {
			title: $L("Date"),
			data: newdate
		}
		this.gpsModel.items[i++] = {
			title: $L("Timestamp"),
			data: newtimestamp
		}
		if (data.latitude != 0) {
			var newlatitude = roundNumber(data.latitude, 3);
			this.gpsModel.items[i++] = {
			title: $L("Latitude"),
			data: newlatitude
		    }
		}
			
		if (data.longitude != 0) {
			var newlongitude = roundNumber(data.longitude, 3);
			this.gpsModel.items[i++] = {
			title: $L("Longitude"),
			data: newlongitude
		    }
		}
		if (data.velocity != 0)
		{
			var newvelocity = data.velocity + $L("m/s") ;
			var newvelocitykm = roundNumber(data.velocity* 3.6, 3) + $L("km/h");
			var newvelocitymph = roundNumber(data.velocity * 3.6 / 1.6, 3) + $L("mph");
			this.gpsModel.items[i++] = {
			title: $L("Velocity"),
			data: newvelocity
			}
			this.gpsModel.items[i++] = {
			title: $L("Velocity"),
			data: newvelocitykm
			}
			this.gpsModel.items[i++] = {
			title: $L("Velocity"),
			data: newvelocitymph
			}
		}
			
		if (data.altitude != 0) {
			var newaltitude = data.altitude + $L("meters");
			this.gpsModel.items[i++] = {
			title: $L("Altitude"),
			data: newaltitude
			}
		}
		this.controller.modelChanged(this.gpsModel); 
	
	}
	else 
	{
		var str = "<P>" + $L("No signal was detected.");

		if (data.errorCode == 1)
			str += "<BR>" + $L("(timeout)");
		if (data.errorCode == 2)
			str += "<BR>" + $L("(position unavailable)");
		if (data.errorCode == 4)
			str += "<BR>" + $L("(cell and wifi available, GPS not available)");
		if (data.errorCode == 5)
			str += "<BR>" + $L("(location service off)");

		str += "<P>" + $L("GPS works better outdoors.  Go outside and try again if you wish.");


		//str += "<P>Error returned: " + data.errorText;
		this.controller.get('status').update( str );

		Logging.log( "GPS", data.errorText );

	}
}

GpsAssistant.prototype.activate = function()
{
	//console.log( "GPS: activate called" );

	this.Step = 0;
	this.controller.get('status').update( $L("Attempting to receive a signal using the GPS receiver.  Please wait.") );
	
	//this.getCurrentPosition();
}

GpsAssistant.prototype.deactivate = function()
{
	console.log( "GPS: deactivate called" );
	this.controller.get('spinnerDiv').show(); 
	//we did successfully set GPS ON set it back to off
	if(this.setGPSOn == true)
	{
		console.log( "GPS: deactivate called set it back to off" );
		this.prefs = false;
		this.setUseGps(this.prefs);
	}
	this.getGPSPrefs();
		
	//console.log( "GPS: deactivate called" );
	//if (this.GetFixRequest != undefined)
	//	this.GetFixRequest.cancel();

}
GpsAssistant.prototype.GPSPrefsSuccess = function(result)
{
	console.log("------------------- GPSPrefsSuccess1 -----------------"+ Object.toJSON(result));
	if (result.useGps == false) {
		console.log("------------------- GPSPrefsSuccess1 set GPSNotEnabled true-----------------" + Object.toJSON(result.useGps) + this.GPSNotEnabled);
		this.GPSNotEnabled = true;
		this.prefs = true;
		this.setUseGps(this.prefs);
		
	}
	else {
		this.GPSNotEnabled = false;
		this.getCurrentPosition();
	}
	
	//Mojo.Log.info("------------------- GPSPrefsSuccess -----------------"+ Object.toJSON(result));
	
}

GpsAssistant.prototype.GPSPrefsFailure = function(result){
	console.log("------------------- GPSPrefsFailure1 -----------------"+ Object.toJSON(result));
	Mojo.Log.info("------------------- GPSPrefsFailure -----------------%j", $H(result));
	this.getCurrentPosition();
}
GpsAssistant.prototype.getGPSPrefs = function(useGps)
{
	//this.gpsPreference = true;
	this.GPSPrefs = new Mojo.Service.Request("palm://com.palm.location", {
			method: 'getLocationServicePrefs',
			parameters: {},
			onSuccess: this.GPSPrefsSuccess.bind(this),
			onFailure: this.GPSPrefsFailure.bind(this)
		});
}
GpsAssistant.prototype.setUseGpsSuccess = function(result)
{
	this.setGPSOn = true;
	console.log("------------------- setUseGpsSuccess1 -----------------"+Object.toJSON(result));
	Mojo.Log.info("------------------- setUseGpsSuccess -----------------%j", $H(result));
	this.getCurrentPosition();
}

GpsAssistant.prototype.setUseGpsFailure = function(result){
	this.setGPSOn = false;
	console.log("------------------- setUseGpsFailure1 -----------------"+ Object.toJSON(result));
	Mojo.Log.info("------------------- setUseGpsFailure -----------------%j", $H(result));
	this.getCurrentPosition();
}
GpsAssistant.prototype.setUseGps = function(useGps)
{
	//this.gpsPreference = true;
	
	this.setUseGpsCall = new Mojo.Service.Request("palm://com.palm.location", {
			method: 'setUseGps',
			parameters: {'useGps':useGps},
			onSuccess: this.setUseGpsSuccess.bind(this),
			onFailure: this.setUseGpsFailure.bind(this)
		});
}
GpsAssistant.prototype.getCurrentPosition = function()
{
	this.acc = 1;
	this.respTime = 3;
	this.FixRequestTime = (new Date()).getTime();
	this.StartTrackingRequest = new Mojo.Service.Request("palm://com.palm.location", {
			method: 'getCurrentPosition',
			parameters: {appId: this.AppId, accuracy: this.acc, responseTime: this.respTime, subscribe: 'false'},
			onSuccess: this.GotGPSData.bind(this),
			onFailure: this.GotGPSData.bind(this)
			});

}

GpsAssistant.prototype.stopTracking = function(payload)
{
	if (this.id > 0)
	{
		var request = new Mojo.Service.Request("palm://com.palm.location", {
				method: 'stopTracking',
				parameters: {"id": this.id},
				onSuccess: function()
					{
						console.log( "GPS: Stop tracking success" );
					},
				onFailure: function()
					{
						console.log( "GPS: Stop tracking failure" );
					}
				});
	}
}





