
google.load("maps", "2.181");
google.load("search", "1");

var map;
var ge;
var gdir;
var control;
var searchOptions;

function egiateInit(div) {
	searchOptions = new SchoolSearch();
	control = new SearchControl('info', 'control');
	control.changePage('search');
	
	if (GBrowserIsCompatible()) {
		// ADD MAP INSTANCE
		map = new GMap2(document.getElementById(div));
		// ADD GE MAP TYPE
		map.addMapType(G_SATELLITE_3D_MAP);
		// SET MAP TYPE
		map.setMapType(G_SATELLITE_3D_MAP);
		// REMOVE SINGLE MAP TYPE
		map.removeMapType(G_SATELLITE_MAP);

		// SET CENTER
		map.setCenter(new google.maps.LatLng(41.8489055052432, -95.90747171258352), 4);

		// ADD NAV CONTROLS
		var navControl = new GLargeMapControl3D();
		var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5, 5));
		map.addControl(navControl, topRight);
		
		// map.addControl(new ChangeMapTypeControl());

		// ADD MAP TYPE CONTROLS
		var mapTypeControl = new GMapTypeControl();
		var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 0)); //0,445 for bottom-left corner
		map.addControl(mapTypeControl, topLeft);
		
		// ADD GE API
		map.getEarthInstance(function(object) {
			ge = object;
			
			if(ge) {
				ge.getNavigationControl().getScreenXY().setXUnits(ge.UNITS_INSET_PIXELS);
				ge.getNavigationControl().getScreenXY().setYUnits(ge.UNITS_INSET_PIXELS);
	
				// add some layers
				ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, false);
				ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, false);
				ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, true);
				ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS_LOW_RESOLUTION, true);
				ge.getLayerRoot().enableLayerById(ge.LAYER_TERRAIN, true);
	
				// set flyto speed
				ge.getOptions().setFlyToSpeed(.15);
			} else {
				map.setMapType(G_NORMAL_MAP);
			}
		});

		gdir = new GDirections(map);
		GEvent.addListener(gdir, "error", handleErrors);		
		GEvent.addListener(gdir, "addoverlay", handleLoads);

		updateOptions();

		if(goIpeds) {
//			if (map.getCurrentMapType().getName() == 'Earth') {
//				preloadIpeds();
//			} else if(map.getCurrentMapType().getName() == 'Map' || map.getCurrentMapType().getName() == 'Hybrid') {
				preload = GEvent.addListener(map, "tilesloaded", preloadIpeds);
//			}
		}
	}
}

function preloadIpeds() {
//	alert('here');
//	if(map.getCurrentMapType().getName() == 'Map' || map.getCurrentMapType().getName() == 'Hybrid') {
		GEvent.removeListener(preload);
//	}
	
	var url = URL + 'php/ajaxDb.php';
	$.get(url, {"ipeds": goIpeds, "table": OVERVIEW}, function(data) {
		var json = JSON.parse(data);
		var jsonArray = [];
		
		jsonArray.push(json);
		control.loadSearchResults(jsonArray);

		map.getEarthInstance(function() {
			control.schoolResultsClick(json['lat'], json['lng'], goIpeds);
		});
	});	
}

function setDirections(fromAddress, toAddress) {
//	alert(fromAddress + ' ' + toAddress);
	gdir.load("from: " + fromAddress + " to: " + toAddress, { "getSteps": true });
	$('#emailMe').slideDown("slow");
}

function handleErrors() {
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	else alert("An unknown error occurred.");
}

function handleLoads() {
	var route = gdir.getRoute(0);
//	alert(route);
	var routeStr = '<ul>';
	routeStr += route.getSummaryHtml() ;
	for (var i=0; i<route.getNumSteps(); i++) {
		// getStatus.innerHTML += dirObj.getRoute(r).getStep(s).getLatLng() + '<br>';
		routeStr += '<li>'+route.getStep(i).getDescriptionHtml()+'</li>';		
		routeStr += '<li>'+route.getStep(i).getDistance().html+' '+route.getStep(i).getDuration().html+'</li>';
	}
	routeStr += '</ul>';
	$('#gTextDirections').html(routeStr);
}

function clearDirections() {
	$('#gTextDirections').html('');
	gdir.clear();
}

function emailDirections() {
	$(".emailError").remove();
	var hasError = false;
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

	var emailToVal = $("#emailTo").val();
//	alert(emailToVal);
	if(emailToVal == '') {
		$("#emailTo").after('<span class="emailError">You forgot to enter the email address to send to</span>');
		hasError = true;
	} else if(!emailReg.test(emailToVal)) {
		$("#emailTo").after('<span class="emailError">Enter a valid email address to send to.</span>');
		hasError = true;
	}
	
	if(!hasError) {
		$.post(URL + "php/sendEmail.php", {"emailTo": emailToVal, "message": $('#gTextDirections').html()}, function(data) {
			alert('email sent.');
		});
		// alert('here');
	}
}

// toggle layers
function updateOptions() {
	map.getEarthInstance(function(object) {
		if(ge) {
			var options = ge.getOptions();
			var form = document.options;
	
			//formatting: options.enableLayerById(form."id".checked);
			
			if (form.roads.checked) {
				ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
			} else {
				ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, false);
			}
	
			if (form.borders.checked) {
				ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
			} else {
				ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, false);
			}
	
			if (form.buildings.checked) {
				ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, true);
				ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS_LOW_RESOLUTION, true);
			} else {
				ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, false);
				ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS_LOW_RESOLUTION, false);
			}
		}
	});
}


