// JavaScript Document
var GPS_SHOW = 0;
var GPS_HIDE = 1;
var GPS_AVERAGE = 10;

gps = {
	ready: false,
	
	init: function () {
		//console.log('preparing GPS module');	
		gps.mode = GPS_AVERAGE;
		gps.gpsCntr = 0;
		gps.cntrMax = 100;
		gps.cntr = 0; gps.latVal = []; gps.lonVal = [];
		
		$(document).bind('gps-available',null,function() {
			//$('#gpsStat').html('GPS Available');
			$('#gpsFlag').html('GPS').removeClass('no').addClass('yes');
			gps.ready = true;
		});
		$(document).bind('gps-not_available',null,function() {
			//$('#gpsStat').html('No GPS')
			$('#gpsFlag').html('No GPS').removeClass('yes').addClass('no');
			gps.ready = false;
		});
		$(document).bind('gps-error',null,function(e) {
			//$('#gpsStat').html(e.msg);
			gps.ready = false;
		});
		
		gps.gpsAvailTest();
	},

	gpsAvailTest: function () {
  	if (navigator.geolocation){
      // snapshot of position:
      //navigator.geolocation.getCurrentPosition(gps.gpsUpdt, gps.renderError, {timeout:30000});

      // constantly updating position:
      navigator.geolocation.watchPosition(gps.gpsUpdt, gps.renderError, { timeout:30000,
																																					enableHighAccuracy:true
			});
    }
		else {
			//alert('No geo-location support is available with this browser.');
			$(document).trigger('gps-noservice');			
		}
	},

  gpsUpdt: function (position) {
		//alert('updating position now');
    // called when location object changes
		if (navigator.geolocation && position){
		  // in FireFox geo.enabled MUST be set to 'true'
	  	gps.lat = position.coords.latitude;
	  	gps.lon = position.coords.longitude;
			gps.makeAverage();
			if (gps.mode == GPS_SHOW) {
				gps.latDms = flos.deg2dms(gps.lat);
				gps.lonDms = flos.deg2dms(gps.lon);
			} else if (gps.mode == GPS_AVERAGE) {
				gps.latDms = flos.deg2dms(gps.latAvg);
				gps.lonDms = flos.deg2dms(gps.lonAvg);
			}
			if (!gps.ready){
				gps.ready = true;
				$(document).trigger('gps-available');
			}		
			// live display of current position
			var text = 	'GPS ('+gps.gpsCntr+') ==> '+
									'Lat: '+gps.latDms['d']+'&deg; '+gps.latDms['dm'].toFixed(4)+"' "+gps.latDms['dir'][0]+
									', '+
									'Lon: '+gps.lonDms['d']+'&deg; '+gps.lonDms['dm'].toFixed(4)+"' "+gps.lonDms['dir'][1];
			$('#gpsInfo').html(text);
		}
		else {
			$(document).trigger('gps-not_available');
			gps.ready = false;
		}
		//console.log('gps using:'+gps.lat+' & '+gps.lon)
  	return true;
	},
	
	showLoc: function (where){
		// display coordinates in user suppied location
		if (!gps.ready) return
		if (gps.mode == GPS_HIDE) return;
		if (!document.getElementById(where+"latDeg")) return
		//$('#container').html('  --> '+'#'+where+'latDeg');
		
		//$('#container').html('      latdms='+gps.latDms['d']+'D '+gps.latDms['m']+"'"+gps.latDms['ds']+'"');
		$('#'+where+'latDeg').val(gps.latDms['d']);
		$('#'+where+'latMin').val((gps.latDms['m']+(gps.latDms['ds']/60.0)).toFixed(4));
		$('#'+where+'latDir').val(gps.latDms['dir']);
		//	console.log('      latdms='+gps.lonDms['d']+'D '+gps.lonDms['m']+"'"+gps.lonDms['ds']+'"');
		$('#'+where+'lonDeg').val(gps.lonDms['d']);
		$('#'+where+'lonMin').val((gps.lonDms['m']+(gps.lonDms['ds']/60.0)).toFixed(4));
		$('#'+where+'latDir').val(gps.lonDms['dir']);
		$(document).trigger('gps-data',{"lat":gps.latDms,"lon":gps.lonDms})
  },
  
  resetAverage: function () {
  	gps.latVal=[];
  	gps.lonVal=[];
  	gps.gpsCntr=0;
	},
	
	makeAverage: function () {
		if(!gps.ready) return;
		// remove oldest elements from end
		if (gps.gpsCntr >= gps.cntrMax) {
			gps.latVal.pop();
			gps.lonVal.pop();
		}
		// add most recent sample start of array
		gps.gpsCntr = gps.latVal.unshift(gps.lat);
		gps.gpsCntr = gps.lonVal.unshift(gps.lon);
		
		// compute average of array values
		var latTtl = 0.0; 
		var lonTtl = 0.0;
		for (var i=0; i<gps.gpsCntr; i++) {
		  latTtl += gps.latVal[i];
		  lonTtl += gps.lonVal[i];
		}
		gps.latAvg = latTtl/gps.gpsCntr;
		gps.lonAvg = lonTtl/gps.gpsCntr;
	},
	
	renderError: function (err) {
		switch (err.code) {
		case err.PERMISSION_DENIED:
			errText = "Could not get position as permission was denied.";
			break;
		case err.POSITION_UNAVAILABLE:
			errText = "Could not get position as this information is not available at this time.";
			break;
		case err.TIMEOUT:
			errText = "Attempt to get position timed out.";
			break;
		default:
			errText = "Sorry, a location error occurred. \nCode: " + err.code + "\n Message: " + err.message;
			break;
		}
		gps.ready = false;
		$.event.trigger('gps-error',{"msg":errText,"code":err.code});
	}
};

$(document).ready(gps.init);

