/**
 * Journey Planner
 */
var markers = []; // marker cache
var journeys = []; // journey cache
var shortest_walking_id = 0; // if of shourtest walking journey
var infoWindow;
var polylinePoints = [];
var routeLines = []

var rad;
var polyHandle = null;

var geocoder;

var directions = [];

var colours = {
	walk: 		"#00FF00",
	drive: 		"#FF0000",
	cycle: 		"#00FFFF",
	taxi: 		"#FF0000",
	scheduled:	"#CC6600",
	rad:		"#9999FF"
}

var user;

$(document).ready(function () {

  geocoder = new GClientGeocoder();
  rad = new GPolygon();
	
	// fetch back user profile
	$.ajax({
		url: rootUrl + "users/ajax_profile",
		cache: false,
		type: "GET",
		dataType: "json",
		async: false,
		success: function(json) {
	
			user = json;
			
		}
	
	});
	
});

/**
 * Add a circle to the global variable "map". This function won't work for circles that encompass
 * the North or South Pole. Also, there is a slight distortion in the upper-left, upper-right,
 * lower-left, and lower-right sections of the circle that worsens as it gets larger and/or closer
 * to a pole.
 * @param lat Latitude in degrees
 * @param lng Longitude in degrees
 * @param radius Radius of the circle in statute miles
 * @param {String} strokeColor Color of the circle outline in HTML hex style, e.g. "#FF0000"
 * @param strokeWidth Width of the circle outline in pixels
 * @param strokeOpacity Opacity of the circle outline between 0.0 and 1.0
 * @param {String} fillColor Color of the inside of the circle in HTML hex style, e.g. "#FF0000"
 * @param fillOpacity Opacity of the inside of the circle between 0.0 and 1.0
 */
function drawCircle(lat, lng, radius, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity) {
  var d2r = Math.PI/180;
  var r2d = 180/Math.PI;
  var Clat = radius * 0.014483;  // Convert statute miles into degrees latitude
  var Clng = Clat/Math.cos(lat*d2r); 
  var Cpoints = []; 
  for (var i=0; i < 33; i++) { 
    var theta = Math.PI * (i/16);
    Cy = lat + (Clat * Math.sin(theta));
    Cx = lng + (Clng * Math.cos(theta));
    var P = new GLatLng(Cy, Cx);
    Cpoints.push(P);
  }
  
  if (rad != null) {
	  map.removeOverlay(rad);
  }
  else {
	  GEvent.removeListener(polyHandle);
  }
  
  rad = new GPolygon(Cpoints, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity);
  map.addOverlay(rad);

	polyHandle=GEvent.addListener(rad, "click", function(latLng) {
		
		if (latLng !== undefined) {
			markers.tmp.type = "generic";
			markers.tmp.setLatLng(latLng);
			markers.tmp.content = undefined;
			markers.tmp.show();
			showInfoWindow(markers.tmp);
			
			drawCircle(latLng.lat(), latLng.lng(), $("#slider_amount").val(), colours.rad, 1, 0.75, colours.rad, .5);
			fetchFilteredMarkers(latLng.lat(), latLng.lng(), $("#slider_amount").val());
			
		}
		
	});
	
}


function fetchPolylineElevation(id, polyline, distance) {
	
	$(id).attr("src", rootUrl + "elevation_graph.php?polyline=" + polyline.ha.points);
	
}
/**
 * fetch content for an info window
 */
function loadInfoWindow(marker) {

	var content = "";
	
	switch (marker.type) {
		
		case "generic":

			// generic marker
			var address = "Address Unknown";
			
			// get address from google
			geocoder.getLocations(marker.getLatLng(), function(response) {
				
				if (response.Status.code == G_GEO_SUCCESS) {
					
					if (response.Placemark[0]) {
						
						address = response.Placemark[0].address;
						
					}
					
				}
				else {
				
					// failed to get address
					alert(status);
					
				}

				marker.title = address;
				
			});
		
			// fetch info window content
			$.ajax({
				url: rootUrl + "locations/generic_marker/" + escape(marker.getLatLng()) + "/" + escape(address) + "/" + escape($("#slider_value").text()),
				cache: false,
				type: "GET",
				success: function(html) {

					content = "<h2>" + address + "</h2>" + html;
					marker.content = content;
					marker.id = undefined;
					
					if (!marker.isHidden()) {
						marker.openInfoWindow(content, {maxWidth: "500"});
					

						if (marker.special == "from") {
							$("#JourneyPlannerFrom").val(address);
							$("#JourneyPlannerFromLatlng").val(latLngToStr(marker.getLatLng()));
							$("#JourneyPlannerFromId").val(marker.id);
						}
						else if (marker.special == "to") {
							$("#JourneyPlannerTo").val(address);
							$("#JourneyPlannerToLatlng").val(latLngToStr(marker.getLatLng()));
							$("#JourneyPlannerToId").val(marker.id);
						}
						
						var latLng = marker.getLatLng();
						
					}
					
					return content;
					
				}
			
			});
			
			break;
			
		case "known":	
			var id = marker.id;
			
			if (marker.content === undefined) {
				
				$.ajax({
					url: rootUrl + "locations/known_marker/" + escape(id) + "/" + escape($("#slider_value").text()),
					cache: false,
					type: "GET",
					success: function(html) {

						var title = $(html).find("h2.name").text();
					
						var latLng = $(html).find("span.set_from span.latLng").text();
						latLng = strToLatLng(latLng);
						
						marker.setLatLng(latLng);
						marker.content = html;
						marker.title = title;
						
						if (!marker.isHidden()) {
							marker.openInfoWindow(marker.content, {maxWidth: "500"});
																		
							// cache marker info
							markers[id] = marker;
							markers[id].content = html;
							markers[id].id = id;
							
							infoWindow = markers[id];
						}
					}
				
				});
				
			}
			else {
				
				marker.setLatLng(markers[id].latLng);
				
				if (!marker.isHidden()) {
					marker.openInfoWindow(markers[id].content, {maxWidth: "500"});
				}
				
				infoWindow = marker;
			
			}

			break;				
			
	}
	return "Information currently unavailable";
	
}

function showInfoWindow(marker) {
	
	if (marker.content === undefined) {
		
		marker.content = loadInfoWindow(marker);
		
	}
	else {
	
		marker.openInfoWindow(marker.content, {maxWidth: "500"});
		
	}
	
	infoWindow = marker;
	
}

function addMarker(options) {

	var icon = new GIcon();	
	
	if (options.icon !== undefined) {
		icon.image = options.icon;
		icon.iconSize = new GSize(32,37);
		icon.iconAnchor = new GPoint(16,37);
		icon.infoWindowAnchor = new GPoint(16,0);		
		icon.imageMap = [0,0,32,0,32,37,0,37];

		options.icon = icon;
	}
	
	
	var marker = new GMarker(new GLatLng(50.370376, -4.142661), options);
	
	if (options.special !== undefined) {
		
		marker.special = options.special;
		
	}
	
	map.addOverlay(marker);
	marker.hide();
		
	GEvent.addListener(marker, "click", function () {
		showInfoWindow(this);
	});
	
	if (options.draggable) {

		GEvent.addListener(marker, "dragstart", function () {
			marker.closeInfoWindow();
		});

		GEvent.addListener(marker, "drag", function(latLng) {
			var latLng = marker.getLatLng();
			
			drawCircle(latLng.lat(), latLng.lng(), $("#slider_amount").val(), colours.rad, 1, 0.75, colours.rad, .5);
		});
		
		GEvent.addListener(marker, "dragend", function () {
			
			this.type="generic";
			this.content = undefined;
			this.id = null;
			showInfoWindow(this);
			
			var latLng = marker.getLatLng();
			
			drawCircle(latLng.lat(), latLng.lng(), $("#slider_amount").val(), colours.rad, 1, 0.75, colours.rad, .5);
			fetchFilteredMarkers(latLng.lat(), latLng.lng(), $("#slider_amount").val());

		});
		
	}
	
	return marker;
	
}

$(document).ready(function () {
	
	$("#journey_details .detail_wrapper .detail ul ").idTabs();

	markers.tmp = addMarker({
		type: "generic",
		map: map,
		hide: true,
		draggable: true,
		icon: "http://google-maps-icons.googlecode.com/files/regroup.png",
		zIndexProcess:function(marker, tmp) {
			return 10000;
		}
	});
	
	markers.from = addMarker({
		type: "generic",
		special: "from",
		map: map,
		draggable: true,
		icon: "http://maps.gstatic.com/intl/en_ALL/mapfiles/icon_greenA.png",
		zIndexProcess:function(marker, tmp) {
			return 10001;
		}
	});

	markers.to = addMarker({
		type: "generic",
		special: "to",
		map: map,
		draggable: true,
		icon: "http://maps.gstatic.com/intl/en_ALL/mapfiles/icon_greenB.png",
		zIndexProcess:function(marker, tmp) {
			return 10002;
		}
	});
	
	function walkingJourney(from, to) {
		
		directions.walk = new GDirections(null, document.getElementById("walking_directions"));
		
		GEvent.addListener(directions.walk, "load", function() {

			var status = directions.walk.getStatus();
			
			var distance = directions.walk.getDistance();
			var distanceInMiles = distance['meters'] * 0.000621371192;
			var durationInMinutes = (distanceInMiles / user.Profile.urban_walking_speed) * 60;
			var burnRate = user.Profile.urban_walking_speed;
			var calories = user.Profile.urban_walking_speed * (user.Profile.weight / 2.2) * (durationInMinutes / 60);
			
			$("#journey_details .walking .duration .value").text(Math.round(durationInMinutes +.5) + " mins");
			$("#journey_details .walking .distance .value").text(Math.round(distanceInMiles*10.)/10 + " miles");
			$("#journey_details .walking .calories .value").text(Math.round(calories + .5));

			fetchPolylineElevation("#walking_gradient .elevation img", directions.walk.getPolyline(), distance);
			
			
		});
		
		GEvent.addListener(directions.walk, "error", function () {
			
			var status = directions.walk.getStatus();
			
		});

		directions.walk.load("from:" + from + " to:" + to, {
			travelMode: G_TRAVEL_MODE_WALKING,
			getPolyline:true,
			getSteps: true
		});
		
	}
	
	function cyclingJourney(from, to) {

		directions.cycle = new GDirections(null, document.getElementById("cycling_directions"));
		
		GEvent.addListener(directions.cycle, "load", function () {

			var duration = directions.cycle.getDuration();
			
			var distance = directions.cycle.getDistance();
			var distanceInMiles = distance['meters'] * 0.000621371192;
			var burnRate = 1.5;
			var durationInMinutes = (distanceInMiles / user.Profile.urban_cycle_speed) * 60;
			var calories = burnRate * (user.Profile.weight / 2.2) * (durationInMinutes / 10);
			
			$("#journey_details .cycling .duration .value").text(Math.floor(durationInMinutes + .5) + " mins");
			$("#journey_details .cycling .distance .value").text(Math.round(distanceInMiles*10.)/10 + " miles");
			$("#journey_details .cycling .calories .value").text(Math.floor(calories +.5));
			
			fetchPolylineElevation("#cycling_gradient .elevation img", directions.cycle.getPolyline(), distance);
			
		});

		directions.cycle.load("from:" + from + " to:" + to, {
			travelMode: G_TRAVEL_MODE_DRIVING,
			avoidHighways: true,
			getPolyline:true,
			getSteps: true
		});
		
	}
	
	function drivingJourney(from, to) {

		directions.drive = new GDirections(null, document.getElementById("driving_directions"));

		GEvent.addListener(directions.drive, "error", function () {

			alert("drive error");
			alert(GDirections.getStatus());
		});
		
		GEvent.addListener(directions.drive, "load", function () {

			var duration = directions.drive.getDuration();
			var seconds = duration.seconds * 1.2;
			var minutes = Math.floor(seconds / 60);
			
			var distance = directions.drive.getDistance();
			var distanceInKm = distance['meters'] / 1000;
			var distanceInMiles = distance['meters'] * 0.000621371192;
			var co2 = (user.Profile.car_co2_rating * distanceInKm);

			$("#journey_details .driving .duration .value").text(minutes + " mins");
			$("#journey_details .driving .distance .value").text(Math.floor(distanceInMiles * 10. ) / 10 + " miles");
			$("#journey_details .driving .emissions .value").text(Math.floor(co2 * 10 ) / 10);
			$("#journey_details .driving .cost .value").text((distanceInKm * .60).toFixed(2));
			//$("#journey_details .driving .emissions .value").text(co2inKg);

			fetchPolylineElevation("#driving_gradient .elevation img", directions.drive.getPolyline(), distance);
			
		});

		directions.drive.load("from:" + from + " to:" + to, {
			travelMode: G_TRAVEL_MODE_DRIVING,
			getPolyline:true,
			getSteps: true
		});
		
	}

	function taxiJourney(from, to) {

		directions.taxi = new GDirections(null, document.getElementById("taxi_directions"));
		
		GEvent.addListener(directions.taxi, "load", function () {

			var duration = directions.taxi.getDuration();
			var seconds = duration.seconds * 1.2;
			var minutes = Math.floor(seconds / 60);
			
			var distance = directions.taxi.getDistance();
			var distanceInKm = distance['meters'] / 1000;
			var co2 = (user.Profile.car_co2_rating * distanceInKm);
			
			$("#journey_details .taxi .duration .value").text(minutes + " mins");
			$("#journey_details .taxi .emissions .value").text(Math.floor(co2 * 10) / 10);
			
			var distanceInFeet = distance['meters'] * 1.0936133;
			var taxiCost = 0;

	        if (distanceInFeet <= 200) {
	        	taxiCost = 2.5;
			}
	        else if (distanceInFeet <= 400 ) {
				taxiCost = 2.5 + .3;
			}
			else {
				var chargeDistance = Math.ceil((distanceInFeet - 400 ) / 400);
				taxiCost = 2.5 + .3 + (chargeDistance * .3);
			}
	        
			$("#journey_details .taxi .cost .value").text(taxiCost.toFixed(2));

			fetchPolylineElevation("#taxi_gradient .elevation img", directions.taxi.getPolyline(), distance);
			
		});

		directions.taxi.load("from:" + from + " to:" + to, {
			travelMode: G_TRAVEL_MODE_DRIVING,
			getPolyline:true,
			getSteps: true,
			preserveViewport: true
		});
		
	}
	
	function scheduledDirections(route) {
		
		var result = "<table>";
		
		result += "<tr><th>Step</th><th>Description</th></tr>";
		
		var steps = route.steps.length;
		
		for(var i = 0; i < steps; i++) {
			
			var step = route.steps[i];
			
			result += "<tr><td>" + (i + 1) + "</td><td>" + step.description + "</td></tr>";
			
		}
		
		result += "</table>";
		
		return result;
		
	}
	
	function scheduledJourneys(from, to, xdate, xtime, arrDep) {
	
		xdate = xdate.replace(/\//gi, "-");
		xtime= xtime.replace(/:/gi, "-");
		
		var url = rootUrl + "journey_planners/scheduled_routes/" + escape(latLngToStr(from)) + "/" + escape(latLngToStr(to)) + "/" + escape(xdate) + "/" + escape(xtime) + "/" + escape(arrDep);
		
		$.ajax({
			url: url,
			cache: false,
			type: "GET",
			dataType: "json",
			success: function(json) {
			
				if (json.status == "OK") {
					
					for(var i = 1; i < 4; i++) {
						
						if (json.trips[i] === undefined) {
							
							$("#journey_details tr.scheduled_" + i).remove();
							$("#link_scheduled_" + i).remove();
							
						}
						else {
							
							var route = json.trips[i];
							journeys['scheduled_' + i] = route;
							
							$("#journey_details tr.scheduled_" + i + " td.duration .value").text(route.duration + " mins");
							
							var emissions = json.trips[i].scheduled_duration * 0.05365; 
							$("#journey_details tr.scheduled_" + i + " td.emissions .value").text(Math.floor(emissions * 10) / 10);

							$("#scheduled_" + i + "_directions").append(scheduledDirections(route));
							
							$("#link_scheduled_" + i).text(json.trips[i].mode).attr("title", json.trips[i].tooltip);
							//$(".scheduled_" + i + " .duration .value").text(json.trips[i].duration + " mins");
							//$(".scheduled_" + i + " .emissions .value").text(json.trips[i].duration);
							

							var burnRate = user.Profile.urban_walking_speed;
							var calories = user.Profile.urban_walking_speed * (user.Profile.weight / 2.2) * (json.trips[i].walk_duration / 60);
							
							$("#journey_details tr.scheduled_" + i + " td.calories .value").text(Math.floor(calories * 10) / 10);
							
							// add route provider telphone popup
							var popup = "";
							
							for (var j = 0; j < json.trips[i].operator.length; j++) {
								
								popup = popup + json.trips[i].operator[j] + "<br/>";
								
							}
							
							$(".scheduled_" + i + " .cost .value img").attr("src", rootUrl + "img/telephone.png").addClass("pointer");
							
							$(".scheduled_" + i + " .cost .value")
								.simpletip({
									content: popup,
									fixed: true
								})
							
						}
						
					}
					
				}
				else {
					
					// hide scheduled routes
					for(var i=0; i < 4; i++) {
						
						$("#journey_details tr.scheduled_" + i).remove();
						$("#link_scheduled_" + i).remove();
						
					}
					
					alert(json.message);
				
				}
				
			}
		
		});

	}
	/*
	 * show/hide the journey details panel
	 */
	function showRoutes() {

		var $showHide = $("#detail_tabs span.showhide");
		
		$showHide.click(function () {

			var $panel = $("#journey_details");
 
			if ($panel.is(":hidden")) {
				$panel.slideDown("slow");
				$("span.showhide img").attr("src", rootUrl + "img/detail_tab_close.gif");
			}
			else {
				$panel.slideUp("slow");
				$("span.showhide img").attr("src", rootUrl + "img/detail_tab_open.gif");
			}

		});
		
		$showHide.click();
		
		var $detailTabs = $("#detail_tabs");
		
		$detailTabs.show();
		
		$("li:first a", $detailTabs).live("click", function () {
		  var $panel = $("#journey_details");
		  if ($panel.is(":hidden")) {
				$panel.slideDown("slow");
				$("span.showhide img").attr("src", rootUrl + "img/detail_tab_close.gif");
			}
		});
		
		// bind the tab links to the tabs
		$("li a", $detailTabs).live("click", function () {

			var id = $(this).attr("href").substr(1);
			
			// cycle through tabs, hide all but the newly clicked one
			$("#journey_details .page[id!=" + id + "]").hide();
			$("#journey_details .page[id=" + id + "]").show();

			$("li", $detailTabs).removeClass("current");
			$(this).parent().addClass("current");

			var type = id.substr(7);

			//map.clearOverlays();

			map.removeOverlay(directions.walk.getPolyline());
			map.removeOverlay(directions.cycle.getPolyline());
			map.removeOverlay(directions.drive.getPolyline());
			map.removeOverlay(directions.taxi.getPolyline());
			
			// remove any polyline points
			for(var i in polylinePoints) {
				map.removeOverlay(polylinePoints[i]);
			}
			
			for (var i in routeLines) {
				map.removeOverlay(routeLines[i]);
			}
			
			switch (type) {
				case "walk":
				case "drive":
				case "cycle":
				case "taxi":
					
					var polyline = directions[type].getPolyline();
					polyline.setStrokeStyle({color: colours[type]});
					
					map.addOverlay(polyline);
		
					map.setZoom(map.getBoundsZoomLevel(polyline.getBounds()));
					map.setCenter(polyline.getBounds().getCenter());
					
					var route = directions[type].getRoute(0);
					var vertexes = route.getNumSteps();
					
					for(var i=0; i < vertexes; i++) {
						
						var step = route.getStep(i);
						var icon = new GIcon(G_DEFAULT_ICON);
						
						if (vertexes <= 99) {
							icon.image = rootUrl + "img/markers/marker" + (i + 1) + ".png";
						}
						else {
							icon.image = rootUrl + "img/markers/blank.png";
						}
						
						polylinePoints[i] = new GMarker(step.getLatLng(), {icon: icon});
						polylinePoints[i].bindInfoWindowHtml(step.getDescriptionHtml());
						map.addOverlay(polylinePoints[i]);
						
					}
					
					break;
					
				case "scheduled_1":
				case "scheduled_2":
				case "scheduled_3":

					routeLines = [];
					var route = journeys[type];
					
					var steps = route.steps.length;
					
					for(var i = 0; i < steps; i++) {
						
						var step = route.steps[i];
						var icon = new GIcon(G_DEFAULT_ICON);

						if (i == 0) {
							icon.image = "http://maps.gstatic.com/intl/en_ALL/mapfiles/icon_greenA.png";
						}
						else if (steps <= 99) {
							icon.image = rootUrl + "img/markers/marker" + (i + 1) + ".png";
						}
						else {
							icon.image = rootUrl + "img/markers/blank.png";
						}
						
						switch (step.mode) {
							
							case "walk":
								
								var polyline = new GPolyline([
									new GLatLng(step.from_lat, step.from_lng),
									new GLatLng(step.to_lat, step.to_lng)
									], colours.walk, 4);
								
								break;
								
							default:
								
								var polyline = new GPolyline([
									new GLatLng(step.from_lat, step.from_lng),
									new GLatLng(step.to_lat, step.to_lng)
								    ], colours.scheduled, 4);
															
								break;
						}
						
						routeLines[i] = polyline;
						map.addOverlay(routeLines[i]);
								
						
						polylinePoints[i] = new GMarker(new GLatLng(step.from_lat, step.from_lng), {icon: icon});
						polylinePoints[i].bindInfoWindowHtml(step.description);
						map.addOverlay(polylinePoints[i]);
						
					}
				
			}
			
			return false;
			
		});
		
		$("#journey_details .page[id!=detail_compare]").hide();
		
	}
	
	// if Start/End pos passed to page, update gui to match
	if ($("#JourneyPlannerFromLatlng").val() != "") {
		markers.from.setLatLng(strToLatLng($("#JourneyPlannerFromLatlng").val()));
		markers.from.show();
	}

	if ($("#JourneyPlannerFromId").val() != "") {
		markers.from.type = "known";
		markers.from.id = $("#JourneyPlannerFromId").val();
	}
	else {
		markers.from.type = "generic";
	}

	if ($("#JourneyPlannerToLatlng").val() != "") {
		markers.to.setLatLng(strToLatLng($("#JourneyPlannerToLatlng").val()));
		markers.to.show();
	}

	if ($("#JourneyPlannerToId").val() != "") {
		markers.to.type = "known";
		markers.to.id = $("#JourneyPlannerToId").val();
	}
	else {
		markers.to.type = "generic";
	}
	
	// caluclate journeys
	if ($("#JourneyPlannerFromLatlng").val() != "" && $("#JourneyPlannerToLatlng").val() != "") {

		var from = strToLatLng($("#JourneyPlannerFromLatlng").val());
		var to = strToLatLng($("#JourneyPlannerToLatlng").val());
		var xdate = $("#JourneyPlannerDate").val();
		var xtime = $("#JourneyPlannerH").val() + ":" + $("#JourneyPlannerM").val();
		var arrDep = null;
		
		if ($("#JourneyPlannerDepartArrive0").attr("checked") == true) {
			
			arrDep = "depart";
		
		}
		else {
			
			arrDep  ="arrive";
			
		}

		walkingJourney(from, to);
		cyclingJourney(from, to);
		drivingJourney(from, to);
		taxiJourney(from, to);
		scheduledJourneys(from, to, xdate, xtime, arrDep);

		showRoutes();
				
	}

	GEvent.addListener(map, "click", function(overlay, latLng) {
		
		if (latLng !== undefined) {
			markers.tmp.type = "generic";
			markers.tmp.setLatLng(latLng);
			markers.tmp.content = undefined;
			markers.tmp.show();
			showInfoWindow(markers.tmp);
			
			//drawCircle(latLng.lat(), latLng.lng(), $("#slider_amount").val(), colours.rad, 1, 0.75, colours.rad, .5);
			fetchFilteredMarkers(latLng.lat(), latLng.lng(), $("#slider_amount").val());

		}
		
	});

	$("#info_window li.goto").live("mouseup", function () {
		
		var id = $(this).find("span.id").text();

		markers.tmp.type = 'known';
		markers.tmp.id = id;
		markers.tmp.content = undefined;
		markers.tmp.show();
		showInfoWindow(markers.tmp);

		
	});
	
	// The "From here" link in the infoWindow has been clicked. Set the 
	// "From here" field in the Journey planner and remove the infoWindow.
	$("#info_window span.set_from").live("mouseup", function () {

		// Close the info window
		markers.tmp.closeInfoWindow();
		
		var latLng = $(this).find("span.latLng").text();
		$("#JourneyPlannerFromLatlng").attr("value", latLng);
		$("#JourneyPlannerFrom").val(infoWindow.title);
		$("#JourneyPlannerFromId").val(infoWindow.id);

		markers.from.type = infoWindow.type;
		markers.from.id = infoWindow.id;
		markers.from.title = infoWindow.title;
		markers.from.content = infoWindow.content;
		
		markers.tmp.hide();
		markers.from.setLatLng(strToLatLng(latLng));
		markers.from.show();
		checkSubmit();
		
	});
	
	// The "To here" link in the infoWindow has been clicked. Set the 
	// "To here" field in the Journey planner and remove the infoWindow.
	$("#info_window span.set_to").live("mouseup", function () {

		// Close the info window
		markers.tmp.closeInfoWindow();
		
		var latLng = $(this).find("span.latLng").text();
		$("#JourneyPlannerToLatlng").attr("value", latLng);
		$("#JourneyPlannerTo").val(infoWindow.title);
		$("#JourneyPlannerToId").val(infoWindow.id);

		markers.to.type = infoWindow.type;
		markers.to.id = infoWindow.id;
		markers.to.content = infoWindow.content;
		markers.to.title = infoWindow.title;

		markers.tmp.hide();
		markers.to.setLatLng(strToLatLng(latLng));
		markers.to.show();
		
		checkSubmit();
				
	});
	
	/*
	 * add auto complete to from/to input fields
	 */
	$("#JourneyPlannerFrom").filterSelect({
		url: rootUrl + "locations/select_filter/",
		loaderImg: rootUrl + "img/large-ajax-loader.gif",
		off: function () {
			markers.from.hide();
			markers.from.closeInfoWindow();
			$("#JourneyPlannerFromId").val("");
			$("#JourneyPlannerFromLatlng").val($(this).data("latLng"));
			checkSubmit();
		}
	});
	
	$("#JourneyPlannerTo").filterSelect({
		url: rootUrl + "locations/select_filter/",
		loaderImg: rootUrl + "img/large-ajax-loader.gif",
		marker: markers.to,
		off: function () {
			markers.to.hide();
			markers.to.closeInfoWindow();
			$("#JourneyPlannerToId").val("");
			$("#JourneyPlannerToLatlng").val($(this).data("latLng"));
			checkSubmit();
		}
	});
	
	$("#JourneyPlannerFrom_select li").live("click", function e() {
		
		$("#JourneyPlannerFrom").val($(this).text());
		// Hide the list
		$(this).parent().hide();

		if ($(this).data("id") == null) {
			$("#JourneyPlannerFromId").val("");
			$("#JourneyPlannerFromLatlng").val($(this).data("latLng"));
			markers.from.type = "generic";
			markers.from.content = undefined;
			markers.from.setLatLng(strToLatLng($(this).data("latLng")));
			showInfoWindow(markers.from);
		}
		else {
			
			$("#JourneyPlannerFromId").val($(this).data("id"));
			$("#JourneyPlannerFromLatlng").val($(this).data("latLng"));
			markers.from.type = "known";
			markers.from.id = $(this).data("id");
			markers.from.content = undefined;
			markers.from.setLatLng(strToLatLng($(this).data("latLng")));
			showInfoWindow(markers.from);

		}
		
		checkSubmit();
		markers.from.show();
		
	});

	$("#JourneyPlannerTo_select li").live("click", function e() {

		$("#JourneyPlannerTo").val($(this).text());
		// Hide the list
		$(this).parent().hide();
		
		if ($(this).data("id") == "") {
			$("#JourneyPlannerToId").val("");
			$("#JourneyPlannerToLatlng").val($(this).data("latLng"));
			markers.to.type = "generic";
			markers.to.content = undefined;
			markers.to.setLatLng(strToLatLng($(this).data("latLng")));
			showInfoWindow(markers.to);
		}
		else {
			
			$("#JourneyPlannerToId").val($(this).data("id"));
			$("#JourneyPlannerToLatlng").val($(this).data("latLng"));
			markers.to.type = "known";
			markers.to.id = $(this).data("id");
			markers.to.content = undefined;
			markers.to.setLatLng(strToLatLng($(this).data("latLng")));
			showInfoWindow(markers.to);

		}

		checkSubmit();
		markers.to.show();
	});
	
	var latLng = markers.tmp.getLatLng();
	drawCircle(latLng.lat(), latLng.lng(), $("#slider_amount").val(), colours.rad, 1, 0.75, colours.rad, .5);
	
	var $showHide = $("#instructions_showhide");
	
	$showHide.click(function () {

		var $panel = $("#instructions");

		if ($panel.is(":hidden")) {
			$panel.slideDown("slow");
			$("#instructions_showhide img").attr("src", rootUrl + "img/detail_tab_close.gif");
		}
		else {
			$panel.slideUp("slow");
			$("#instructions_showhide img").attr("src", rootUrl + "img/detail_tab_open.gif");
		}

	});
	
	/*
	 * Toggle the status of the submit and clear buttons on the Journey Planner
	 * form.
	 */
	function checkSubmit() {
	
	  if ($("#JourneyPlannerFromLatlng").val() == "" 
	  && $("#JourneyPlannerToLatlng").val() == "") {
			
			$("#JourneyPlannerIndexForm .submit input[name=clear]")
			  .attr("src", rootUrl + "img/btn_clear-off.gif");
			
		}
		else {
			
			$("#JourneyPlannerIndexForm .submit input[name=clear]")
			  .attr("src", rootUrl + "img/btn_clear-on.gif");
			
		}
	
		if ($("#JourneyPlannerFromLatlng").val() == "" || $("#JourneyPlannerToLatlng").val() == "") {
			
			$("#JourneyPlannerIndexForm .submit input[name=get_journey]")
			  .attr("src", rootUrl + "img/btn_get_journeys-off.gif");
			return false;
			
		}
		else {
			
			$("#JourneyPlannerIndexForm .submit input[name=get_journey]")
			  .attr("src", rootUrl + "img/btn_get_journeys-on.gif");
			return true;
			
		}
		
	}
	
	/*
	 * On page load, add a "clear form" button to the journey planner form
	 */
	$('#JourneyPlannerIndexForm div.submit').append($('<input />',{
	    'name': 'clear'
	    , 'src': rootUrl + "img/btn_clear-on.gif"
	    , 'type': 'image'
	    , 'click': function() {
	        $("#JourneyPlannerFrom, #JourneyPlannerTo, #JourneyPlannerFromId, #JourneyPlannerToId, #JourneyPlannerFromLatlng, #JourneyPlannerToLatlng").val("");
	        markers.to.hide(); markers.from.hide();
	      }
	  }));
	
	$("#JourneyPlannerIndexForm").submit(function (e) {
	
		if (!checkSubmit()) {
			return false;
		}
	
	});
	
	checkSubmit();
	
	$(".rtb_from").live("click", function (e) {
		
		var latLng = $(this).find(".latLng").text();
		var id = $(this).find(".id").text();
		
		$("#JourneyPlannerFromLatlng").attr("value", latLng);
		$("#JourneyPlannerFrom").val($("#checkthatbus").val());
		$("#JourneyPlannerFromId").val(id);

		markers.from.type = "known";
		markers.from.id = id;
		showInfoWindow(markers.from);
		markers.from.show();
		checkSubmit();
		
	});
	
	$(".rtb_to").live("click", function (e) {
		
		var latLng = $(this).find(".latLng").text();
		var id = $(this).find(".id").text();
		
		$("#JourneyPlannerToLatlng").attr("value", latLng);
		$("#JourneyPlannerTo").val($("#checkthatbus").val());
		$("#JourneyPlannerToId").val(id);

		markers.to.type = "known";
		markers.to.id = id;
		showInfoWindow(markers.to);
		markers.to.show();
		checkSubmit();

	});
	
});

