var gLat
var gLon
var compassHeading
var lastHeading = 0;
var north

var options = {
	enableHighAccuracy: true,
	timeout: (10 * 1000 * 1000),
	maximumAge: 0
};

function getLocation() {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(geo_success,geo_error, options);
	} else {
		window.alert('No GPS Support');
	}
}

function geo_success(position) {
	gLat = position.coords.latitude ;
	gLon = position.coords.longitude ;
	// add to span
	$('#current_lat').html(gLat)
	$('#current_lot').html(gLon) ;
	$('#current_lat_input').val(gLat)
	$('#current_lot_input').val(gLon) ;
	// Is the compass from magnetic north or true north
	// adjust for magnetic north.
	north = distance(81.3, -110.8, gLat,gLon) ;
	north = parseFloat(north[1])
	$('.geo').each(function(){
		tLat = $(this).find('.lat').html()
		tLon = $(this).find('.lon').html()
		dist = distance(tLat,tLon,gLat,gLon);
		d = parseInt(dist[0]*10)/10;
		a = parseFloat(dist[1])-north;
		$(this).find('.distance').html(d);
		// $(this).find('.direction').css('-webkit-transform','rotate(-' + a + 'deg)');
		// $(this).find('.angle').html(a);
		
		$(this).attr('data-arc',a);
	})
}

function geo_error() { return; }
function compass_error(){ window.alert('Error'); }
function compass_success(heading){
	window.alert('Success');
	compassHeading = heading
}

window.addEventListener('deviceorientation', function(e) {
	if(navigator.compass){
		navigator.compass.getCurrentHeading(compass_success, compass_error);			
	} else if (e.webkitCompassHeading){
		compassHeading = e.webkitCompassHeading
	}
	
	$('.geo').each(function(){
		var heading = $(this).attr('data-arc');
		heading = compassHeading + parseFloat(heading) + window.orientation
		$(this).find('.direction').css('-webkit-transform','rotate(-' + heading + 'deg)');
		$('.compass').html(compassHeading);
	});
}, false);


function distance(lat1,lon1,lat2,lon2){
	var R = 6371; // km
	var dLat = (lat2-lat1) * Math.PI / 180;
	var dLon = (lon2-lon1) * Math.PI / 180;
	var lat1 = (lat1) * Math.PI / 180;
	var lat2 = (lat2) * Math.PI / 180;

	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
			Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var d = R * c;

	arc = Math.atan2(dLat , dLon) * 180 / Math.PI

	return [d,arc]
}