var map, centre, geocoder, location1, location2;

function initialize() {
  if (GBrowserIsCompatible()) {
      map = new GMap2(document.getElementById("map_canvas"));
      
      centre = new GLatLng(0, 0);       
      map.setCenter(centre, 0);
      map.setUIToDefault();
    }
  
  geocoder = new GClientGeocoder();
}

function showLocation() {
	 //show the loader animation
   $('#ajax_loader').fadeIn();
	
	//check they entered a label for the journey
	if(!$('#field_label').val()){
		//hide the loader animation
    $('#ajax_loader').fadeOut();
		alert('Please enter a name for this journey.');
		return false;
	}
	
  geocoder.getLocations(document.forms.calculation_form.field_from.value, function (response) {
    if (!response || response.Status.code != 200)
    {
			//hide the loader animation
      $('#ajax_loader').fadeOut();
      alert("Unable to find the start location. Please enter more detail.");
    }
    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.calculation_form.field_to.value, function (response) {
        if (!response || response.Status.code != 200)
        {
					//hide the loader animation
          $('#ajax_loader').fadeOut();
          alert("Unable to find the finish location. Please enter more detail.");
        }
        else
        {
          location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
          calculateDistance();
        }
      });
    }
  });
}

function calculateDistance()
{
  try
  {
		
    map.clearOverlays();
    var glatlng1 = new GLatLng(location1.lat, location1.lon);
    var glatlng2 = new GLatLng(location2.lat, location2.lon);
    
    //put the markers on the map
    map.addOverlay(new GMarker(glatlng1));
    map.addOverlay(new GMarker(glatlng2));
    
     var waypoints = [
         glatlng1,
         glatlng2
      ];
    
    //draw line between start and end points
    var polyline = new GPolyline(waypoints, "#0000ff", 5, 0.4, {geodesic: true});
    map.addOverlay(polyline);
    
    //zoom and centre map on path
    var points = [
        new GPoint(location1.lat, location1.lon),
        new GPoint(location2.lat, location2.lon)
    ];        
    
    var bounds = new GBounds(points);
    var latLngBounds = new GLatLngBounds(
        new GLatLng(bounds.min().x, bounds.min().y),
        new GLatLng(bounds.max().x, bounds.max().y)
    );
    var zoom = map.getBoundsZoomLevel(latLngBounds);
      
    map.setCenter(new GLatLng(bounds.mid().x, bounds.mid().y), zoom);
    
    //calculate distance in miles and km      
    var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
    var kmdistance = (miledistance * 1.609344).toFixed(1);
		
		//find out if it's a return journey
		if($('#field_return_yes:checked').val()){
			miledistance = (miledistance*2);
			kmdistance = (kmdistance*2);
		}
    
		
		//call the foot print calculation unique to each calculator
    calculateCarbonFootprint(miledistance, kmdistance, true);
    
  }
  catch (error)
  {
    alert(error);
  }
}

function setOffsetSummary(location1_address, location2_address, miledistance, kmdistance, kg, price)
{
	//set values visible to user
	$('#location1_address').html(location1_address);
	$('#location2_address').html(location2_address);
	$('#distance').html(miledistance + ' miles (' + kmdistance + ' kilometers)');
	$('#footprint_amount').html(kg + ' Kg');
	$('#footprint_price').html('£' + price.toFixed(2));
	
	//set hidden input values for adding to cart
	$('#price').val(price.toFixed(2));
	$('#description').val('Travelling from ' + location1_address + ' to ' + location2_address);
	$('#kg').val(kg);
	
	//show the results 	
	$("#results").slideDown();
	
	//hide the loader animation
  $('#ajax_loader').fadeOut();
}

function addToCart(product_name)
{
	$('#name').val(product_name);
	$("#results").slideUp(function() { $('#add_to_cart_form').submit(); });
}

function addContributionToCart(product_name, price)
{
  $('#name').val('&pound;' + price + ' contribution towards ' + product_name);
	$('#price').val(price);
  $("#results").slideUp(function() { $('#add_to_cart_form').submit(); });
}
