// JavaScript Document
/*Driving Directions Functions*/

function DrivingDirections(mapName,map){
	this.mapName = mapName;
	this.map = map;
	this.gmap = map.gmap;
	
	this.directionsRow = null;
	this.ddContainer = null;

	//Placemark ID Fields for src/dst
	this.placemarkFromField = null;
	this.placemarkToField = null;
	this.src = null;
	this.dst = null;

	this.ddPolyline = null;
	
	var self = this;
	
	self.findPlacemark = function(mapname, prikey)
	{
		if(typeof(findPlacemark) != "undefined")
			return findPlacemark(mapname, prikey);
		else
			return self.map.widget.findPlacemark(prikey);
	}

	this.init = function()
	{
		self.placemarkFromField = $("#directionsFromID");
		self.placemarkToField = $("#directionsToID");
		self.directionsRow = $("#ddRow");
		self.ddContainer = $("#ddContainer");
		
		self.gdirections = new GDirections(null);
		GEvent.bind(self.gdirections,"error", self,self.handleDrivingErrors);
		GEvent.bind(self.gdirections, "load", self,self.onGDirectionsLoad);
	}

	this.getDirectionsTo = function(driveTo,driveFrom){
		if(!driveFrom)
			var driveFrom = this.map.findPlacemark(this.placemarkFromField.val());
		this.placemarkToField.val(driveTo.prikey);
		var dirString = '' + driveFrom.latitude + ',' + driveFrom.longitude + '' + ' to ' +
		'' + driveTo.latitude + ',' + driveTo.longitude + '';
		this.directionsRow.css('display', '');
		if(this.ddPolyline != null)
			this.gmap.removeOverlay(this.ddPolyline);
		this.gdirections.load(dirString,{getPolyline:true,getSteps:true});
	}

	this.getDirections = function()
	{
		var dirString = "" + self.src.latitude + "," + self.src.longitude + "" + " to " +"" + self.dst.latitude + "," + self.dst.longitude + "";
		self.directionsRow.slideDown();
		if(self.ddPolyline != null)
			self.gmap.removeOverlay(self.ddPolyline);
		self.gdirections.load(dirString,{getPolyline:true,getSteps:true});
	}

	this.setCenterAndZoomOnBounds = function(bounds) {
		var center = bounds.getCenter();
		var newZoom = self.map.gmap.getBoundsZoomLevel(bounds);
		self.map.gmap.setCenter(center);
		self.map.gmap.setZoom(newZoom);
	} 

	//Handle Successful Directions Attempts
	this.onGDirectionsLoad = function()
	{
		/*Begin Try to set icons*/
		var prikey1 = this.placemarkFromField.val();
		var placemark1 = this.findPlacemark(mapName, prikey1);
		var prikey2 = this.placemarkToField.val();
		var placemark2 = this.findPlacemark(mapName, prikey2);
		
		var route = self.gdirections.getRoute(0);
		//Output starting point
		self.ddContainer.html(self.formatRoute(route,placemark1,placemark2));
		$(".MapExplorer_DirectionsSummary").html(route.getSummaryHtml());
		$("#ddRow:hidden").slideDown();
		self.ddPolyline = self.gdirections.getPolyline();
		self.gmap.addOverlay(self.ddPolyline);
		self.setCenterAndZoomOnBounds(self.ddPolyline.getBounds());
	}
	
	//Handle Errors acquiring directions
	this.handleDrivingErrors = function()
	{
		if (self.gdirections.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
			self.ddContainer.html("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: " + self.gdirections.getStatus().code);
		else if (self.gdirections.getStatus().code == G_GEO_SERVER_ERROR)
			self.ddContainer.html("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + self.gdirections.getStatus().code);
		else if (self.gdirections.getStatus().code == G_GEO_MISSING_QUERY)
			self.ddContainer.html("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: " + self.gdirections.getStatus().code);
		else if (self.gdirections.getStatus().code == G_GEO_BAD_KEY)
			self.ddContainer.html("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + self.gdirections.getStatus().code);
		else if (self.gdirections.getStatus().code == G_GEO_BAD_REQUEST)
			self.ddContainer.html("A directions request could not be successfully parsed.\n Error code: " + self.gdirections.getStatus().code);
		else
			self.ddContainer.html("An unknown error occurred.");
	}

	//Set Destination Marker
	this.directionsTo = function(prikey)
	{
		//var placemark = self.findPlacemark(self.mapName,prikey);
		//self.setToPlacemark(placemark);
		this.placemarkFromField.val(prikey);
	}
	
	//Set Source Marker
	this.directionsFrom = function(prikey)
	{
		//var placemark = self.findPlacemark(self.mapName,prikey);
		//self.setFromPlacemark(placemark);
		this.placemarkToField.val(prikey);
	}

	//Set Destination Marker
	this.setToPlacemark = function(placemark)
	{
		self.src = placemark;
		self.placemarkToField.val(placemark.prikey);
	}
	
	//Set Source Marker
	this.setFromPlacemark = function(placemark)
	{
		self.dst = placemark;
		self.placemarkFromField.val(placemark.prikey);
	}

	//Clear Current Driving Directions
	this.clearDirections = function()
	{
		if(self.ddPolyline != null){
			self.gmap.removeOverlay(self.ddPolyline);
			self.ddPolyline = null;
			self.ddContainer.html("");
		}
		self.directionsRow.css('display', 'none');
	}

	//Begin Route Formatting Functions
	//Output an individual step
	this.outputStep = function(step,stepNumber)
	{
		var str = "";
		str = "<li class=\"MapExplorer_Step" + (stepNumber % 2 == 0 ? " evenrow" : " oddrow") + "\">";
			str += "<div class=\"MapExplorer_StepDescription\">" + step.getDescriptionHtml() + "</div>";
			str += "<div class=\"MapExplorer_Distance\">" + step.getDistance().html + "</div><div class=\"clear\"></div>";
		str += "</li>";
		return str;
	}
	
	this.formatRoute = function(r,p1,p2)
	{
		var numSteps = r.getNumSteps();
		var s = self.showPlacemarkStep(p1,true);
		s += "<ol style=\"clear: both\">";
		
		for (var i = 0; i < numSteps; i++)
			s += self.outputStep(r.getStep(i), i + 1);
		
		s += "</ol>";
		s += self.showPlacemarkStep(p2,false);
		s += "<div class=\"clear\"></div>";
		return s;
	}

	this.showPlacemarkStep = function(placemark,start)
	{
		var s = "<div class=\"MapExplorer_Directions" + (start ? "Start" : "End") + "\">";
		s += "<img class=\"PlacemarkStepIcon\" align=\"left\" src=\"" + placemark.icon.smimage + "\">";
		s += "<div class=\"MapExplorer_DirectionsPlacemark\">" + placemark.name + "</div>";
		s += "</div>";
		return s;
	}
	//End Route Formatting Functions
}
