
//GE 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);
			}
		}
	});
}

// TOURS
function tours(tourItem){
	map.getEarthInstance(function(object) {
		if(ge) {
			// create the tour by fetching it out of a KML file
			var BASE_LOGO_URL = 'http://college.campusbird.com/assets_schools/';
			var href = BASE_LOGO_URL+data.ipeds+'/';
			href += tourItem;
		
			google.earth.fetchKml(ge, href, function(kmlObject) {
				if (!kmlObject) {
					// wrap alerts in API callbacks and event handlers
					// in a setTimeout to prevent deadlock in some browsers
					setTimeout(function() {
						alert('Bad or null KML.');
					}, 0);
					return;
				}
		
				// Show the entire KML file in the plugin.
				ge.getFeatures().appendChild(kmlObject);
		
				// Walk the DOM looking for a KmlTour
				walkKmlDom(kmlObject, function() {
					if (this.getType() == 'KmlTour') {
						tour = this;
						return false; // stop the DOM walk here.
					}
				});
				enterTour();
			});
		}
	});
}
	  
function enterTour() {
	map.getEarthInstance(function(object) {
		if(ge) {
			if (!tour) {
				alert('No tour found!');
				return;
			}
			ge.getTourPlayer().setTour(tour);
		}
	});
}


// DRIVING DIRECTIONS
function setDirections(fromAddress, toAddress) {
   gdir.load("from: " + fromAddress + " to: " + toAddress);
}

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 onGDirectionsLoad(){ 
   var poly = gdir.getPolyline();
   if (poly.getVertexCount() > 100) {
     //alert("This route has too many vertices");
     return;
   }
   var baseUrl = "http://maps.google.com/staticmap?";

   var params = [];
   var markersArray = [];
   markersArray.push(poly.getVertex(0).toUrlValue(5) + ",greena");
   markersArray.push(poly.getVertex(poly.getVertexCount()-1).toUrlValue(5) + ",greenb");
   params.push("markers=" + markersArray.join("|"));

   var polyParams = "rgba:0x0000FF80,weight:5|";
   var polyLatLngs = [];
   for (var j = 0; j < poly.getVertexCount(); j++) {
     polyLatLngs.push(poly.getVertex(j).lat().toFixed(5) + "," + poly.getVertex(j).lng().toFixed(5));
   }
   params.push("path=" + polyParams + polyLatLngs.join("|"));
   params.push("size=500x500");
   params.push("key=ABQIAAAAfIvhw596hIKUCeamLjl14xQzQ3062WI6BJIXWqr2W8kdLlTN1xSHFD9FbSZ9IhOhpcIP8UGjfOQZew");

   baseUrl += params.join("&");

   var extraParams = [];
   extraParams.push("center=" + map.getCenter().lat().toFixed(6) + "," + map.getCenter().lng().toFixed(6));
   extraParams.push("zoom=" + map.getZoom());
   addImg(baseUrl + "&" + extraParams.join("&"), "staticMapOverviewIMG");

   var extraParams = [];
   extraParams.push("center=" + poly.getVertex(0).toUrlValue(5));
   extraParams.push("zoom=" + 15);
   addImg(baseUrl + "&" + extraParams.join("&"), "staticMapStartIMG");

   var extraParams = [];
   extraParams.push("center=" + poly.getVertex(poly.getVertexCount()-1).toUrlValue(5));
   extraParams.push("zoom=" + 15);
   addImg(baseUrl + "&" + extraParams.join("&"), "staticMapEndIMG");
}

function addImg(url, id) {
 var img = document.createElement("img");
 img.src = url;
 document.getElementById(id).innerHTML = "";
 document.getElementById(id).appendChild(img);
}

function clearDirections() {
	gdir.clear();
}

$(document).ready(function() {
	$('#toAddress').val(data.streetAddress + ', ' + data.city + ', ' + data.state + ' ' + data.zip);

	if(toursData.length) {
		var tourTab = '	<a href="#"><b> Tours |</b></a>'
					+ '		<div class="accordion-panel-wrap" style="margin-top:10px;">'
					+ '			<div id="campus-tours" class="accordion-panel">'
					+ '				<div><h3>Campus Tours</h3></div>'
					+ '				<ul>';
		for(var i=0; i<toursData.length; i++) {
			var tourName = toursData[i].split('.');
			tourTab += '				<li><a href="#" onclick="tours(\''+toursData[i]+'\')">'+tourName[0]+'</a></li>';
		}
			tourTab	+='				</ul>'
					+ '			</div>'
					+ '		</div>';
		$('.accordion-panel-wrap:first').after(tourTab);
	}
	
	$("#accordion").accordion();	
});

