var geocoder, location1, location2;

function toRad(deg) {
 return deg * Math.PI/180;
}
 
function initialize() {
	geocoder = new GClientGeocoder();
	
	gDir = new GDirections();
	GEvent.addListener(gDir, "load", function() {
		var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
		var drivingDistanceKilometers = (gDir.getDistance().meters/1000)+1;
		document.forms.payment.elements.distance.value=drivingDistanceKilometers.toFixed(0)
		sum2();
	});
}

//===================================== 
// function that check location details
//============= 
function showLocation() {
	var magazyn = "22926 Ahrensburg,Kurt-Fischer-Stra&#223;e 54";
	
	geocoder.getLocations(magazyn, function (response) {
	
		if(!response || response.Status.code != 200){
			alert("Sorry, we were unable to geocode the first address");
		}
		else{
			location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
		
			geocoder.getLocations(document.forms['payment'].address.value, function (response) {
		
				if (!response || response.Status.code != 200){
					alert("Sorry, we were unable to geocode the second address");
				}
				else{
					location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
				
				gDir.load('from: ' + location1.address + ' to: ' + location2.address)
				document.getElementById('results').innerHTML = 'Deine Address ist: </strong>' + location2.address;

				}
			});
		}
	});
}

//================================== 
// function that calculates distance
//==============	
function calculateDistance(){
	try{
		alert(location1.lon + ' ' + location1.lat + ' ' + location2.lon + ' ' + location2.lat)
		var R = 7500; // km
		var dLat = toRad(location2.lat-location1.lat);
		var dLon = toRad(location2.lon-location1.lon); 
		var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(toRad(location1.lat)) * Math.cos(toRad(location2.lat)) * Math.sin(dLon/2) * Math.sin(dLon/2); 
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
		var d = R * c;

//		var glatlng1 = new GLatLng(location1.lat, location1.lon);
//		var glatlng2 = new GLatLng(location2.lat, location2.lon);
//		var miledistance = glatlng1.distanceFrom(glatlng2,6371).toFixed(0);
//		var kmdistance = miledistance;
 
		document.getElementById('results').innerHTML = 'Deine Address ist: </strong>' + location2.address;
			
		document.forms.payment.elements.distance.value=d
		sum2();
	}
		
	catch (error){
		alert(error);
	}
}
