
google.load("maps", "2");

// carbon variables
var visitorMPG = null;
var averageMPG = 20;
var lbsPerGallon = 20;
var lbsPerMileFlightShort = 1.28;
var lbsPerMileFlightMedium = 0.88;
var lbsPerMileFlightLong = 0.8;

// map variables
var map = null;
var geocoder = null;
var mhcLatLng = null;

function initialize() {
  
	if (GBrowserIsCompatible()) {

		// geocoder
		geocoder = new GClientGeocoder();

		// mhc location
		//mhcLatLng = new GLatLng(42.2562514, -72.5764535);
		mhcLatLng = new GLatLng(42.2555514, -72.5745935);

		// map
		map = new GMap2(document.getElementById("map"));
		map.setMapType(G_NORMAL_MAP); // G_SATELLITE_MAP
		map.setCenter(mhcLatLng, 13);
		
		var location;
		
		// mpg
		var mpg = document.getElementById('vehicle_type').value;
		visitorMPG = mpg;
		
		// if we can get the client's location, then do so
		if (google.loader.ClientLocation != null) {
		
			if (google.loader.ClientLocation.address.city == 'South Hadley') {
				location = "Boston, MA";
				showDistanceFromAddress(location, visitorMPG);
			} else {
				location = getUserLocation(false);
				var pt = new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
				showDistanceFromLatLng(pt, visitorMPG);
			}
					
		} else {
		
			location = "Boston, MA";
			showDistanceFromAddress(location, visitorMPG);
						
		}
		
		//
		//map.setCenter(point, 13);
		//var marker = new GMarker(point);			
		
		// populate
		document.getElementById('address1').value = location;
		//document.getElementById('location').innerHTML = getUserLocation(true);
					
	}
  
}

function getUserLocation(withLatLng) {

	var location = 'unknown location';

	if (google.loader.ClientLocation != null) {
		
		if (withLatLng != null && withLatLng != false) {
			return google.loader.ClientLocation.address.city + ', ' + google.loader.ClientLocation.address.region + ', ' + google.loader.ClientLocation.address.country_code + ' (' + google.loader.ClientLocation.latitude + ', ' + google.loader.ClientLocation.longitude + ')';
		} else {
			return google.loader.ClientLocation.address.city + ', ' + google.loader.ClientLocation.address.region + ', ' + google.loader.ClientLocation.address.country_code;
		}
		
	}

	return location;

}

/**
 * Shows the distance from a text address to MHC
 */
function showDistanceFromAddress(address, mpg) {
	
	// set global
	visitorMPG = mpg;
	
	geocoder.getLatLng(address, function(start) { showDistanceFromLatLng(start); } );	

}

/**
 * Shows the distance from a Latitude/Longitude to MHC
 */
function showDistanceFromLatLng(start, mpg) {

	if (start == null) {
		
		document.getElementById('miles').innerHTML = 'unknown';
		
	} else {
		
		//var calcMPG = averageMPG;
		var calcMPG = (visitorMPG != null) ? visitorMPG : averageMPG;
		
		// get all distances
		var meters = mhcLatLng.distanceFrom(start);
		var kilometers = Math.ceil(meters / 1000);
		var miles = Math.ceil(0.000621371192 * meters);
		
		// miles
		var milestext = (miles != 1) ? 'miles' : 'mile';
		document.getElementById('milesround').innerHTML = addCommas(miles*2);
		
		// drive
		var poundsDrive = Math.round(lbsPerGallon * (miles * 1.15 / visitorMPG));
		var dtext = (poundsDrive != 1) ? 'pounds' : 'pound';
		document.getElementById('carbondriveround').innerHTML = addCommas(poundsDrive*2);
		
		// fly
		var flightPounds;
		if (miles < 300) {
			flightPounds = lbsPerMileFlightShort;
		} else if (miles >= 300 && miles < 500) {
			flightPounds = lbsPerMileFlightMedium;
		} else {
			flightPounds = lbsPerMileFlightLong;
		}
		var poundsFly = Math.round(miles / flightPounds);
		var ftext = (poundsFly != 1) ? 'pounds' : 'pound';
		document.getElementById('carbonflyround').innerHTML = addCommas(poundsFly*2);
		
		// draw a line
		drawLine(start, mhcLatLng);
		
	}

}

/**
 * Draws a line on the map
 */
function drawLine(start, end) {

	// clear
	map.clearOverlays();
	
	// create
	var polyline = new GPolyline([start, end], "#ff0000", 5);
	var start_marker = new GMarker(start);
	var end_marker = new GMarker(end);
	
	// add
	map.addOverlay(start_marker);
	map.addOverlay(end_marker);
	map.addOverlay(polyline);
	
	// reset bounds
	setMapBounds(start, end);

}

/**
 * Sets the map's zoom level and center to show all points
 */
function setMapBounds(start, end) {

	var bounds = new GLatLngBounds();
	bounds.extend(start);
	bounds.extend(end);
	map.setZoom(map.getBoundsZoomLevel(bounds)); 
	map.setCenter(bounds.getCenter());

}

/**
 * Adds commas to a number
 */
function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

/**
 * Add a page event
 */
function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	}
	else {
		elm['on' + evType] = fn;
	}
}


// add the first video
addEvent(window, 'load', initialize, false);
//addEvent(window, 'unload', GUnload, false);
