var explanation = "<span>Use the map below to define a rectangular area of interest.";
explanation += "<ol><li>Click the point for the top-left corner of the rectangle.</li>";
explanation += "<li>Click the point for the bottom-right corner of the rectangle.</li>";
explanation += "<li>Optionally modify the selected points in the text boxes below the map.</li>";
explanation += "<li>Click the &quot;Generate and View Map/Grid&quot; button to view the Vs30 output.</li>";
explanation += "</ol></span>";

// Used to track how many points the user has clicked.
var pointCount = 0;

// This is going to be the map.  Declare here for global scope
var map = null;

// These are the input elements
var top_left_lat;
var top_left_lon;
var bottom_right_lat;
var bottom_right_lon;

var marker_icon = null;

var top_left_marker = null;
var bottom_right_marker = null;
var overlay = null;

/**
 * Creates the actual Google Map and places it inside the
 * "div" with the id "map".  The map is by default centered
 * over the US and has the generic google controls.
 */
function loadMap() {
	if (!GBrowserIsCompatible()) { return; }

	// Create the GMap2 object
	map = new GMap2(document.getElementById("map"));

	// Add the controls and center the map
	map.setCenter(new GLatLng(35.000, -100.000), 3);
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());

	// Add an event listener for the "click"
	GEvent.addListener(map, "click", function(marker, point) {
		var lat = point.y;
		var lon = point.x;
		var success = true;

		if(pointCount == 0) {
			top_left_lat.value = lat;
			success = (success && validateLatitude(top_left_lat));

			top_left_lon.value = lon;
			success = (success && validateLongitude(top_left_lon));

			if(success) {
				createFirstPoint(lat, lon);
			}
		} else if (pointCount == 1) {
			bottom_right_lat.value = lat;
			success = (success && validateLatitude(bottom_right_lat));

			bottom_right_lon.value = lon;
			success = (success && validateLongitude(bottom_right_lon));

			if(success) {
				createSecondPoint(lat, lon);
			}
		}

		if(success) {
			pointCount = 1 - pointCount;
		}
	});
}

/**
 * Initializes the form components on the page to be optimized for
 * javascript functionality.  I.E. add event listeners, add
 * conditional content, set conditional styles etc...
 */
function initialize() {
	// Style the map so that it is visible
	var mapdiv = document.getElementById("map");
	try {
		mapdiv.style.width = "640px";
		mapdiv.style.height = "480px";
		mapdiv.style.borderStyle = "ridge";
		mapdiv.style.borderWidth = "4px";
		mapdiv.style.borderColor = "#333333";
		//mapdiv.style.border = "4px ridge #333333;";
	} catch (ex) {
		// Just ignore, this is a minor detail
	}

	// Add the user instructions for javascript version
	var mapexp = document.getElementById("map_explanation");
	mapexp.innerHTML = explanation;

	// Actually adds the map to the page
	loadMap();

	// Make sure that the clear button works properly
	var btnClear = document.getElementById("clearInputs");
	btnClear.onclick = clearInputs;

	// Make sure the inputs get validated
	top_left_lat = document.getElementById("top_left_lat");
	top_left_lon = document.getElementById("top_left_lon");
	bottom_right_lat = document.getElementById("bottom_right_lat");
	bottom_right_lon = document.getElementById("bottom_right_lon");

	top_left_lat.onchange = function() {validateLatitude(top_left_lat);}
	top_left_lon.onchange = function() {validateLongitude(top_left_lon);}

	bottom_right_lat.onchange = function() {validateLatitude(bottom_right_lat);}
	bottom_right_lon.onchange = function() {validateLongitude(bottom_right_lon);}

	// Add validation to the submit button
	var btnSubmit = document.getElementById("viewVs30");
	btnSubmit.onclick = validateInputs;

	// Create the marker icon to use
	marker_icon = new GIcon();
	// These have to be changed before production...
	marker_icon.image = "http://earthquake.usgs.gov/research/hazmaps/interactive/vs30/inc/marker_img.png";
	marker_icon.shadow = "http://earthquake.usgs.gov/research/hazmaps/interactive/vs30/inc/marker_shadow.png";
	marker_icon.iconSize = new GSize(25, 25);
	marker_icon.shadowSize = new GSize(25, 25);
	marker_icon.iconAnchor = new GPoint(13, 24);
	marker_icon.infoWindowAnchor = new GPoint(13, 1);
	
	// Finish up with some preferences
	//map.enableScrollWheelZoom();
	map.setMapType(map.getMapTypes()[2]);
}

function clearInputs() {
	top_left_lat.value = '';
	top_left_lon.value = '';
	bottom_right_lat.value = '';
	bottom_right_lon.value = '';

	if(top_left_marker) {
		map.removeOverlay(top_left_marker);
		top_left_marker = null;
	}

	if(bottom_right_marker) {
		map.removeOverlay(bottom_right_marker);
		bottom_right_marker = null;
	}

	if(overlay) {
		map.removeOverlay(overlay);
		overlay = null;
	}

	map.setCenter(new GLatLng(35.000, -100.000), 3);
	pointCount = 0;
}

function validateSlope() { 
	var modifybox = document.getElementById('toposlopeval');
	var slope = modifybox.value;
	slope = parseFloat(slope);

	if(!slope || slope <= 0.0 || slope >= 2.0) {
		alert("The input slope ("+slope+") value is out of range!\n" +
			"0.0 < slope < 2.0");
		var sbox = document.getElementById('toposlope');
		modifybox.value = sbox.options[sbox.selectedIndex].value;
	}

}

function validateInputs() {
	var tl_lat = parseFloat(top_left_lat.value);	
	var tl_lon = parseFloat(top_left_lon.value);
	var br_lat = parseFloat(bottom_right_lat.value);
	var br_lon = parseFloat(bottom_right_lon.value);

	if(!tl_lat || !tl_lon || !br_lat || !br_lon) {
		alert("All values are required.  Please try again.");
		clearInputs();
		return false;
	}

	if(isNaN(tl_lat) || isNaN(tl_lon) || isNaN(br_lat) || isNaN(br_lon)) {
		alert("Some of your input is not valid.\nLocation input should all be numerical with:\n"+
			"-90 < Latitude < 90\n-180 < Longitude < 180");
		clearInputs();
		return false;
	}

	if(tl_lat <= br_lat) {
		alert("Latitude values out of order. Please try again.");
		clearInputs();
		return false;
	}

	if(tl_lon >= br_lon) {
		alert("Longitude values out of order. Please try again.");
		clearInputs();
		return false;
	}

	if(Math.abs(tl_lat - br_lat) > 20 || Math.abs(tl_lon - br_lon) > 60) {
		alert("The region you specified is too large.\nMaximum size: 20 degrees Latitude x 60 degrees Longitude");
		clearInputs();
		return false;
	}
	
	return true;
}

function validateLatitude(elem) {
	if(elem.value.length == 0) { return false;}
	var value = parseFloat(elem.value);
	if ( isNaN(value) || value < -90 || value > 90) {
		elem.value = '';
		alert("The input latitude ("+elem.value+") value is not valid.\n" +
			"Latitude must be between -90 and +90 degrees.");
		elem.focus();
		return false;
	}
	return true;
}

function validateLongitude(elem) {
	if(elem.value.length == 0) { return false;}
	var value = parseFloat(elem.value);
	if( isNaN(value) || value < -180 || value > 180) {
		elem.value = '';
		alert("The input longitude ("+elem.value+") value is not valid.\n" +
			"Longitude values must be between -180 and +180 degrees.");
		return false;
		elem.focus();
	}
	return true;
}

function createFirstPoint(lat, lon) {
	// Remove stuff as needed
	if(bottom_right_marker) { 
		map.removeOverlay(bottom_right_marker); 
		bottom_right_marker = null;
		bottom_right_lat.value = '';
		bottom_right_lon.value = '';
	}
	if(overlay) {
		map.removeOverlay(overlay);
		overlay = null;
	}
	if(top_left_marker) {
		map.removeOverlay(top_left_marker);
		top_left_marker = null;
	}

	// Create the first marker
	top_left_marker = new GMarker(new GPoint(lon, lat), marker_icon);
	GEvent.addListener(top_left_marker, "click", function() {
		top_left_marker.openInfoWindow(
			"<strong>Northwest Corner...</strong><br />" +
			"<strong>Latitude:</strong> " + lat + "<br />" +
			"<strong>Longitude:</strong> " + lon);
	});
	map.addOverlay(top_left_marker);
}

function createSecondPoint(lat, lon) {
	if(bottom_right_marker) {
		map.removeOverlay(bottom_right_marker);
		bottom_right_marker = null;
	}
	bottom_right_marker = new GMarker(new GPoint(lon, lat), marker_icon);
	GEvent.addListener(bottom_right_marker, "click", function() {
		bottom_right_marker.openInfoWindow(
			"<strong>Southeast Corner...</strong><br />" +
			"<strong>Latitude:</strong> " + lat + "<br />" +
			"<strong>Longitude:</strong> " + lon);
	});
	map.addOverlay(bottom_right_marker);

	createOverlay();
}

function createOverlay() {
	if(overlay) {map.removeOverlay(overlay); overlay = null;}
	var rectBounds = new GLatLngBounds(
		new GLatLng(bottom_right_marker.getPoint().y, top_left_marker.getPoint().x),
		new GLatLng(top_left_marker.getPoint().y, bottom_right_marker.getPoint().x)
	);
	overlay = new Rectangle(rectBounds);
	map.addOverlay(overlay);
}

/** Attach the window event so the page is optimized for javascript. */
if(window.attachEvent) { // IE case
	window.attachEvent('onload', initialize);
} else if (window.addEventListener) {
	window.addEventListener('load', initialize, false);
}

