// Initialize google maps and the rounded corners
var application = null;

function initialize() {
	if (GBrowserIsCompatible()) {
		application = new Plan();
		application.initTripDate();
	}
}

function initializeDefault()
{
	initialize();
	if(application != null)
	{
		application.selectFirstTrip();		
	}	
}

function initializeTrailhead(id)
{
	initialize();
	if(application != null)
	{
		application.showTrailheadChooser();
		application.selectTrailhead(id);
		application.mode = TRAILHEAD;
	}
}

function initializeTrip(id)
{
	initialize();
	if(application != null)
	{
		application.selectTrip(id);
	}
}

var startDirections = new GDirections();
GEvent.addListener(startDirections, "load", onStartDirectionsLoad);
GEvent.addListener(startDirections, "error", handleStartDirectionsErrors);

var tripDirections = new GDirections();
GEvent.addListener(tripDirections, "load", onTripDirectionsLoad);
GEvent.addListener(tripDirections, "error", handleTripDirectionsErrors);

var endDirections = new GDirections();
GEvent.addListener(endDirections, "load", onEndDirectionsLoad);
GEvent.addListener(endDirections, "error", handleEndDirectionsErrors);

function showStartDrivingRoutes()
{
	if (application.startDrivingOverlay != null) {
		application.map.removeOverlay(application.startDrivingOverlay);
	}

	start_lat = $('start_from_lat').value
	start_lng = $('start_from_lng').value
	if (application.mode == application.TRIP) {
		end_lat = $('trip_start_lat').value
		end_lng = $('trip_start_lng').value
	}
	else if (application.mode == application.TRAILHEAD)
	{
		end_lat = $('trailhead_lat').value
		end_lng = $('trailhead_lng').value			
	}
	start = start_lat + "," + start_lng;
	end = end_lat + "," + end_lng;
	directionOptions = {
		travelMode : G_TRAVEL_MODE_DRIVING,
		getPolyline : true
	}
	startDirections.clear();
	startDirections.load("from: " + start + " to: " + end,directionOptions)		
}

function onStartDirectionsLoad() {
	application.startDrivingOverlay = startDirections.getPolyline();
	application.startDrivingOverlay.color = '#000000';
	application.map.addOverlay(application.startDrivingOverlay);
	application.startMiles = startDirections.getDistance().meters * 0.000621371192;
	startMilesHtml = startDirections.getDistance().html;
	if(application.tripMiles > 0) {
		startMilesHtml = startMilesHtml + ' x 2 Cars = ' + (application.startMiles * 2).toFixed(1) + ' mi';
	}
	$('_start_miles').innerHTML = startMilesHtml;
	
	showEndDrivingRoutes();
}	

function handleStartDirectionsErrors()
{
//	alert('start directions errors : ' + startDirections.getStatus().request + " : " + startDirections.getStatus().code);
	application.startMiles = 0;
	$('_start_miles').innerHTML = "0 mi (Could not calculate)";
	showEndDrivingRoutes();
}	


function showTripDrivingRoutes() {
	if (application.tripDrivingOverlay != null) {
		application.map.removeOverlay(application.tripDrivingOverlay);
	}

	if (application.mode == application.TRIP) {
		start_lat = $('trip_start_lat').value
		start_lng = $('trip_start_lng').value
	} else if (application.mode == application.TRIP) {
		start_lat = $('trailhead_lat').value
		start_lng = $('trailhead_lng').value		
	}
	end_lat = $('trip_end_lat').value
	end_lng = $('trip_end_lng').value
	if(application.mode == application.TRIP && start_lat != end_lat && start_lng != end_lng) {
		start = start_lat + "," + start_lng;
		end = end_lat + "," + end_lng;
		directionOptions = {
			travelMode : G_TRAVEL_MODE_DRIVING,
			getPolyline : true
		}
		tripDirections.clear();
		tripDirections.load("from: " + start + " to: " + end,directionOptions)		
	}		
	else {		
		application.tripMiles = 0;
		$(_trip_miles).innerHTML = '0 mi';
    	showStartDrivingRoutes();
	}
}

function onTripDirectionsLoad()
{
	application.tripDrivingOverlay = tripDirections.getPolyline();
	application.tripDrivingOverlay.color = '#000000';
	application.map.addOverlay(application.tripDrivingOverlay);
	application.tripMiles = tripDirections.getDistance().meters * 0.000621371192;
	if (application.mode === application.TRIP && start_lat != end_lat && start_lng != end_lng) {
		$('_trip_miles').innerHTML = application.tripMiles.toFixed(1) + ' mi x 2 Trips = ' + (application.tripMiles * 2).toFixed(1) + ' mi';	
		application.tripMiles = application.tripMiles * 2;	
	}
	else{
		$('_trip_miles').innerHTML = tripDirections.getDistance().html;

	}
	showStartDrivingRoutes();
}	

function handleTripDirectionsErrors()
{
//	alert('trip directions errors : ' + tripDirections.getStatus().request + " : " + tripDirections.getStatus().code);
	showStartDrivingRoutes();
	application.tripMiles = 0;
	$('_trip_miles').innerHTML = "0 mi (Could not calculate)";
}	


function showEndDrivingRoutes()
{

	if (application.endDrivingOverlay != null) {
		application.map.removeOverlay(application.endDrivingOverlay);
	}
	if (application.mode == application.TRIP) {
		start_lat = $('trip_end_lat').value
		start_lng = $('trip_end_lng').value
	} else if (application.mode == application.TRAILHEAD) {
		start_lat = $('trailhead_lat').value
		start_lng = $('trailhead_lng').value		
	}
	end_lat = $('end_lat').value
	end_lng = $('end_lng').value	
	start = start_lat + "," + start_lng;
	end = end_lat + "," + end_lng;
	directionOptions = {
		travelMode : G_TRAVEL_MODE_DRIVING,
		getPolyline : true
	}
	endDirections.clear();
	endDirections.load("from: " + start + " to: " + end,directionOptions)		
}

function onEndDirectionsLoad()
{
	application.endDrivingOverlay = endDirections.getPolyline();
	application.endDrivingOverlay.color = '#000000';
	application.map.addOverlay(application.endDrivingOverlay);
	application.endMiles = endDirections.getDistance().meters * 0.000621371192;
	endMilesHtml = endDirections.getDistance().html;
	if(application.mode === application.TRIP && application.tripMiles > 0)
	{
		endMilesHtml = endMilesHtml + ' x 2 Cars = ' + (application.endMiles * 2).toFixed(1) + ' mi';
		application.totalMiles = application.tripMiles + (application.startMiles*2) + (application.endMiles*2);
	}
	else{
		application.totalMiles = application.startMiles + application.endMiles;
	}
	$('_end_miles').innerHTML = endMilesHtml;
	$('_total_miles').innerHTML = application.totalMiles.toFixed(1) + ' mi';
	gallons = (application.totalMiles / 21).toFixed(1);
	$('_gallons_of_gas').innerHTML = gallons;
	cost = (gallons * 3).toFixed(2);
	$('_gas_cost').innerHTML = cost;
	carbon = gallons * 19.4;
	$('_pounds_of_carbon').innerHTML = (carbon).toFixed(1);
}	

function handleEndDirectionsErrors()
{
//	alert('end directions errors : ' + endDirections.getStatus().request + " : " + endDirections.getStatus().code);
	application.endMiles = 0;
	if(application.mode === application.TRIP && application.tripMiles > 0)
	{		
		application.totalMiles = application.tripMiles + (application.startMiles*2) + (application.endMiles*2);
	}
	else{
		application.totalMiles = application.startMiles + application.endMiles;
	}
	$('_end_miles').innerHTML = "0 (Could not calculate)";
	$('_total_miles').innerHTML = "At least " + application.totalMiles.toFixed(1) + ' mi';
	gallons = (application.totalMiles / 21).toFixed(1);
	$('_gallons_of_gas').innerHTML = gallons;
	cost = (gallons * 3).toFixed(2);
	$('_gas_cost').innerHTML = cost;
	carbon = gallons * 19.4;
	$('_pounds_of_carbon').innerHTML = (carbon).toFixed(1);
}	

function showDrivingRoutes(show)
{
	if(!show)
	{
		if (application.endDrivingOverlay != null) {
		application.map.removeOverlay(application.endDrivingOverlay);
		}
		if (application.mode == application.TRIP && application.tripDrivingOverlay != null) {
		application.map.removeOverlay(application.tripDrivingOverlay);
		}
		if (application.startDrivingOverlay != null) {
			application.map.removeOverlay(application.startDrivingOverlay);
		}
	}
	else{
		if (application.endDrivingOverlay != null) {
		application.map.addOverlay(application.endDrivingOverlay);
		}
		if (application.mode == application.TRIP && application.tripDrivingOverlay != null) {
		application.map.addOverlay(application.tripDrivingOverlay);
		}
		if (application.startDrivingOverlay != null) {
			application.map.addOverlay(application.startDrivingOverlay);
		}
		
	}
}

function Plan() {
	this.TRIP = 0;
	this.TRAILHEAD = 1;
	this.LOCATION = 2;
	this.mode = this.TRIP;

	this.startDrivingOverlay = null;
	this.tripDrivingOverlay = null;
	this.endDrivingOverlay = null;
	// Setup all the basic map stuff
	this.map = new GMap2(document.getElementById("drawMap"));
	
	this.startLatLng = new GLatLng(37.7750, -122.4190);
    
    this.map.setCenter(this.startLatLng, 10);

	this.map.addControl(new GLargeMapControl3D());
    var scaleControlPosition = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(10, 40));
    this.map.addControl(new GScaleControl(), scaleControlPosition);
    this.map.enableContinuousZoom();

	var copyOSM = new GCopyrightCollection("<a href=\"http://www.openstreetmap.org/\">OpenStreetMap</a>");
    copyOSM.addCopyright(new GCopyright(1, new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)), 0, " "));
    var tilesMapnik     = new GTileLayer(copyOSM, 1, 17, {tileUrlTemplate: 'http://tile.openstreetmap.org/{Z}/{X}/{Y}.png'});
    var mapMapnik     = new GMapType([tilesMapnik],     G_NORMAL_MAP.getProjection(), "OSM");
	this.map.addMapType(mapMapnik);
	
	this.map.addMapType(G_PHYSICAL_MAP);
	this.map.addMapType(G_SATELLITE_3D_MAP);
	this.map.setMapType(G_NORMAL_MAP);
	this.map.addControl(new GHierarchicalMapTypeControl());

	this.map.disableDoubleClickZoom();
	this.geocoder = new GClientGeocoder();

	this.tripLine = null;
	this.startLine = null;
	this.endLine = null;

	// Setup the plan points
	this.tripStartLatLng = new GLatLng(37.7750, -122.4190);
	this.tripEndLatLng = new GLatLng(37.7750, -122.4190);
	this.startFromLatLng = new GLatLng(37.7750, -122.4190);
	this.returnToLatLng = new GLatLng(37.7750, -122.4190);
	this.map.setCenter(this.tripStartLatLng, 10);

    // Create our start marker icon
    startIcon = new GIcon();
	startIcon.image = "/media/images/map/large_trip_start_map_icon.png";
    startIcon.shadow = "/media/images/map/large_map_icon_shadow.png";
    startIcon.iconSize = new GSize(52, 56);
    startIcon.shadowSize = new GSize(52, 56);
    startIcon.iconAnchor = new GPoint(23, 48);	

    
    // Set up our GMarkerOptions object
    
    markerOptions = {
        icon: startIcon,
        draggable: false
    };
	this.tripStartMarker = new GMarker(this.tripStartLatLng, markerOptions);

	    // Create our start marker icon

    endIcon = new GIcon();
	endIcon.image = "/media/images/map/large_trip_stop_map_icon.png";
    endIcon.shadow = "/media/images/map/large_map_icon_shadow.png";
    endIcon.iconSize = new GSize(52, 56);
    endIcon.shadowSize = new GSize(52, 56);
    endIcon.iconAnchor = new GPoint(23, 48);	

	
    // Set up our GMarkerOptions object
    
    endMarkerOptions = {
        icon: endIcon,
        draggable: false
    };

	this.tripEndMarker = new GMarker(this.tripEndLatLng, endMarkerOptions);

	startFromIcon = new GIcon();
    startFromIcon.image = "/media/images/map/large_home_start_map_icon.png";
    startFromIcon.shadow = "/media/images/map/large_map_icon_shadow.png";
    startFromIcon.iconSize = new GSize(52, 56);
    startFromIcon.shadowSize = new GSize(52, 56);
    startFromIcon.iconAnchor = new GPoint(23, 48);	

//	startFromIcon.image = "http://www.google.com/mapfiles/dd-start.png";
	// Set up our GMarkerOptions object

	markerOptions = {
		icon :startFromIcon,
		draggable :true
	};

	this.startFromMarker = new GMarker(this.startFromLatLng, markerOptions);

	// Create our "tiny" marker icon
	returnToIcon = new GIcon();
    returnToIcon.image = "/media/images/map/large_home_stop_map_icon.png";
    returnToIcon.shadow = "/media/images/map/large_map_icon_shadow.png";
    returnToIcon.iconSize = new GSize(52, 56);
    returnToIcon.shadowSize = new GSize(52, 56);
    returnToIcon.iconAnchor = new GPoint(23, 48);	

	endMarkerOptions = {
		icon :returnToIcon,
		draggable : true
	};

    var trailheadIcon = new GIcon();
    trailheadIcon.image = "/media/images/map/trailhead_map_icon.png";
    trailheadIcon.shadow = "/media/images/map/trailhead_map_icon_shadow.png";
    trailheadIcon.iconSize = new GSize(34, 36);
    trailheadIcon.shadowSize = new GSize(34, 36);
    trailheadIcon.iconAnchor = new GPoint(14, 30);
    trailheadIcon.infoWindowAnchor = new GPoint(14, 10);
    
    trailheadMarkerOptions = {
        icon: trailheadIcon,
        draggable: false,
        clickable: false
    };
	this.trailheadMarker = new GMarker(new GLatLng(37.7750, -122.4190),trailheadMarkerOptions);
	this.trailheadMarker.hide();

    var locationIcon = new GIcon();
    locationIcon.image = "/media/images/map/trailhead_map_icon.png";
    locationIcon.shadow = "/media/images/map/trailhead_map_icon_shadow.png";
    locationIcon.iconSize = new GSize(34, 36);
    locationIcon.shadowSize = new GSize(34, 36);
    locationIcon.iconAnchor = new GPoint(14, 30);
    locationIcon.infoWindowAnchor = new GPoint(14, 10);
    
    locationMarkerOptions = {
        icon: locationIcon,
        draggable: false,
        clickable: false
    };
	this.locationMarker = new GMarker(new GLatLng(37.7750, -122.4190), locationMarkerOptions);
	this.locationMarker.hide();

	this.returnToMarker = new GMarker(this.returnToLatLng, endMarkerOptions);

	this.map.addOverlay(this.tripEndMarker);
	this.map.addOverlay(this.tripStartMarker);
	this.map.addOverlay(this.trailheadMarker);
	this.map.addOverlay(this.returnToMarker);
	this.map.addOverlay(this.startFromMarker);
	this.map.addOverlay(this.locationMarker);
	
	this.trailheadMarker.hide();
	this.locationMarker.hide();
	
	GEvent.bind(this.startFromMarker, "dragend", this, this.dragMoveStartFrom);
	GEvent.bind(this.returnToMarker, "dragend", this, this.moveEnd);
	this.chooseStart();
}

Plan.prototype.syncDates = function()
    {
        if($('same_as_start').checked)
        {
            $('trip_end_date').value = $('trip_date').value;
            $('trip_end_hour').value = $('trip_hour').value;
            $('trip_end_minutes').value = $('trip_minutes').value;
            if($('trip_dep_arr').value == "arr")
            {
                $('trip_end_arr_option').selected = true;
            }
            else
            {
               $('trip_end_dep_option').selected = true;
            }
            if($('trip_ampm').value == "pm")
            {
                $('end_pm_option').selected = true;
            }
            else
            {
                $('end_am_option').selected = true;
            }
        }
    }

Plan.prototype.trailheadTab = function()
{
	this.showTrailheadChooser();
	this.selectFirstTrailhead();	
}

Plan.prototype.showTrailheadChooser = function()
{
    $('trip_chooser').style.display = "none";
    $('trailhead_chooser').style.display = "block";
	if (this.tripLine != null) {
		this.tripLine.hide();
	}
    this.trailheadMarker.show();
	this.tripStartMarker.hide();
	this.tripEndMarker.hide();
	this.centerOnTrailhead();
	application.mode = application.TRAILHEAD;
	selectedTab = 'trailheads';
    $('trips_tab_img').src = "/media/images/trips_tab.png";
    $('trailheads_tab_img').src = "/media/images/trailheads_tab_selected.png";

}

Plan.prototype.showTripChooser = function()
{
	this.mode = this.TRIP;
    $('trailhead_chooser').style.display = "none";
    $('trip_chooser').style.display = "block";
    this.tripStartMarker.show();
	this.tripEndMarker.show();
	this.trailheadMarker.hide();
	
	if (this.tripLine != null) {
		this.tripLine.show();
		this.centerOnTrip();
		showTripDrivingRoutes();
	}
	else{
		this.selectFirstTrip();
	}
    $('trips_tab_img').src = "/media/images/trips_tab_selected.png";
    $('trailheads_tab_img').src = "/media/images/trailheads_tab.png";
	selectedTab = 'trips';
	
}

function createMarker(pointId, pointIndex, pointTitle, latlng) {
	var tinyIcon = new GIcon();
	tinyIcon.image = "http://labs.google.com/ridefinder/images/mm_20_brown.png";
	tinyIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	tinyIcon.iconSize = new GSize(12, 20);
	tinyIcon.shadowSize = new GSize(22, 20);
	tinyIcon.iconAnchor = new GPoint(6, 20);
	tinyIcon.infoWindowAnchor = new GPoint(5, 1);

	pointMarkerOptions = {
		icon :tinyIcon,
		title :pointTitle,
		draggable :false,
		clickable :true
	};
	// this.application.trailheadMgr.addMarker(new
	// GMarker(latlng,pointMarkerOptions));
	newMarker = new GMarker(latlng, pointMarkerOptions);
	return newMarker;
}

Plan.prototype.dragMoveStartFrom = function(overlay, latlng) {
	if (overlay) {
		latlng = overlay;
		this.startFromMarker.setLatLng(latlng);
		this.updateStartFromLatLngDisplay(latlng);
		this.getStartFromReverseGeocode(latlng);
	}
}

Plan.prototype.moveEnd = function(overlay, latlng) {
	if (overlay) {
		this.getEndReverseGeocode(this.returnToMarker.getLatLng());
		this.updateEndLatLngDisplay(this.returnToMarker.getLatLng());
	}
	if (latlng) {
		this.returnToMarker.setLatLng(latlng);
		this.getEndReverseGeocode(latlng);
		this.updateEndLatLngDisplay(latlng);
	}

}

// Updates the return to display elements
Plan.prototype.updateEndLatLngDisplay = function(latlng) {
	$('end_latlng_label').innerHTML = latlng.toUrlValue();
	$('end_lat').value = latlng.lat();
	$('end_lng').value = latlng.lng();
}

// Updates the start from display elements
Plan.prototype.updateStartFromLatLngDisplay = function(latlng) {
	$('start_from_latlng_label').innerHTML = latlng.toUrlValue();
	$('start_from_lat').value = latlng.lat();
	$('start_from_lng').value = latlng.lng();
}

// Updates the fields in the UI based on reverse geocode of the latlng
Plan.prototype.getStartFromReverseGeocode = function(latlng) {
	if (latlng != null) {
		this.geocoder.getLocations(latlng, this.populateStartFromAddress);
	}
}

// Handles start reverse geocode requests (LatLng -> Address)
Plan.prototype.populateStartFromAddress = function(response) {
	if (!response || response.Status.code != 200) {
		//alert("Status Code:" + response.Status.code);
	} else {
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1],
				place.Point.coordinates[0]);
		$('start_from_address').value = place.address;
		var same_as_start = $('same_as_start').checked;		
		if(same_as_start)
		{			
			$('end_address').value=(place.address);
			application.setReturnTo(place.address);
		}
		else{
			showTripDrivingRoutes();
		}
	}

}

Plan.prototype.getEndReverseGeocode = function(latlng) {
	if (latlng != null) {
		address = latlng;
		this.geocoder.getLocations(latlng, this.populateEndAddress);
	}
}

Plan.prototype.populateEndAddress = function(response) {
	if (!response || response.Status.code != 200) {
		//alert("Status Code:" + response.Status.code);
	} else {
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1],
				place.Point.coordinates[0]);
		$('end_address').value = place.address;
		showTripDrivingRoutes();
	}

}

Plan.prototype.setStartFrom = function(address) {
	if (this.geocoder) {
		this.geocoder.getLatLng(address, function(point) {
			if (!point) {
//				alert(address + " not found");
			} else {
				application.startFromMarker.setLatLng(point);
				application.updateStartFromLatLngDisplay(point);
				saveKeyValueToSession("plan.startfrom",point.toUrlValue());
				var same_as_start = $('same_as_start').checked;
				if(same_as_start)
				{
					$('end_address').value=(address);
					application.setReturnTo(address);
				}
/*				
				if (this.mode == this.TRIP) {					
					application.centerOnTrip();
				}
				else
				{
					application.centerOnTrailhead();
				}
				*/
				showTripDrivingRoutes();
			}
		})
	}
}


Plan.prototype.setReturnTo = function(address) {
	if (this.geocoder) {
		this.geocoder.getLatLng(address, function(point) {
			if (!point) {
			//	alert(address + " not found");
			} else {
				application.returnToMarker.setLatLng(point);
				application.updateEndLatLngDisplay(point);
    			saveKeyValueToSession("plan.returnto",point.toUrlValue());
/*
				if (this.mode == this.TRIP) {					
					application.centerOnTrip();
				}
				else
				{
					application.centerOnTrailhead();
				}
				*/
				showTripDrivingRoutes();
			}
		})
	}
}

Plan.prototype.toggleSameAsStart = function(val)
{
	if(val)
	{
		$('end_address').value = $('start_from_address').value;
		this.setReturnTo($('start_from_address').value);
		$('end_address').disabled = true;
		$('set_end_button').disabled = true;
		this.returnToMarker.hide();
        this.syncDates();
	}
	else
	{
		$('end_address').disabled = false;
		$('set_end_button').disabled = false;
		this.returnToMarker.show();
	}
}

Plan.prototype.chooseStart = function() {
		var startFromLatLng = new GLatLng(37.7750, -122.4190);
		this.getStartFromReverseGeocode(startFromLatLng);
		this.updateStartFromLatLngDisplay(startFromLatLng);
		this.toggleSameAsStart(true);
	
}

Plan.prototype.showStartTransit511NewWindow = function() {
	dep_arr = $('trip_dep_arr').value;
	raw_trip_date = $('trip_date').value;
	trip_date_vals = raw_trip_date.split("/");
	trip_date_input = trip_date_vals[2] + trip_date_vals[0] + trip_date_vals[1]
	//alert(trip_date_input);
	start_lat = $('start_from_lat').value
	start_lng = $('start_from_lng').value
	end_lat = $('trip_start_lat').value
	end_lng = $('trip_start_lng').value
	if (this.mode == this.TRIP) {
		url = build511TransitURL(trip_date_input, $('trip_dep_arr').value, $('trip_hour').value, 
			$('trip_minutes').value, $('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Origin", "Trip Start");
		window.open(url, "start_511_transit");
	}
	else{
		end_lat = $('trailhead_lat').value
		end_lng = $('trailhead_lng').value
		url = build511TransitURL(trip_date_input, $('trip_dep_arr').value, $('trip_hour').value, 
		$('trip_minutes').value, $('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Origin", "Trailhead");
		window.open(url, "start_511_transit");		
	}
}

Plan.prototype.showStartTransitGoogleNewWindow = function() {
	start_lat = $('start_from_lat').value
	start_lng = $('start_from_lng').value
	end_lat = $('trip_start_lat').value
	end_lng = $('trip_start_lng').value
	if (this.mode == this.TRIP) {
		url = buildGoogleTransitURL($('trip_date').value,$('trip_dep_arr').value,$('trip_hour').value, $('trip_minutes').value, 
		$('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Origin", "Trip Start");
		window.open(url, "start_google_transit");
	}
	else{
		end_lat = $('trailhead_lat').value
		end_lng = $('trailhead_lng').value
		url = buildGoogleTransitURL($('trip_date').value,$('trip_dep_arr').value,$('trip_hour').value, 
		$('trip_minutes').value, $('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Origin", "Trailhead");
		window.open(url, "start_google_transit");
	}

}

Plan.prototype.showStartDrivingNewWindow = function() {
    start_lat = $('start_from_lat').value
    start_lng = $('start_from_lng').value
    end_lat = $('trip_start_lat').value
    end_lng = $('trip_start_lng').value
    if (this.mode == this.TRIP) {
        url = buildGoogleDrivingURL($('trip_date').value,$('trip_dep_arr').value,$('trip_hour').value, $('trip_minutes').value, 
        $('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Origin", "Trip Start");
        window.open(url, "start_google_driving");
    }
    else{
        end_lat = $('trailhead_lat').value
        end_lng = $('trailhead_lng').value
        url = buildGoogleDrivingURL($('trip_date').value,$('trip_dep_arr').value,$('trip_hour').value, 
        $('trip_minutes').value, $('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Origin", "Trailhead");
        window.open(url, "start_google_driving");
    }

}

Plan.prototype.showEndDrivingNewWindow = function() {
	start_lat = $('trip_end_lat').value
	start_lng = $('trip_end_lng').value
	end_lat = $('end_lat').value
	end_lng = $('end_lng').value

    if (this.mode == this.TRIP) {
        url = buildGoogleDrivingURL($('trip_date').value,$('trip_dep_arr').value,$('trip_hour').value, $('trip_minutes').value, 
        $('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Trip End", "Destination");
        window.open(url, "end_google_driving");
    }
    else{
		start_lat = $('trailhead_lat').value
		start_lng = $('trailhead_lng').value
        url = buildGoogleDrivingURL($('trip_date').value,$('trip_dep_arr').value,$('trip_hour').value, 
        $('trip_minutes').value, $('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Trailhead", "Destination");
        window.open(url, "end_google_driving");
    }

}

Plan.prototype.showStartBikingNewWindow = function() {
    start_lat = $('start_from_lat').value
    start_lng = $('start_from_lng').value
    end_lat = $('trip_start_lat').value
    end_lng = $('trip_start_lng').value
    if (this.mode == this.TRIP) {
        url = buildGoogleTransitURLBase($('trip_date').value,$('trip_dep_arr').value,$('trip_hour').value, $('trip_minutes').value, 
        $('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Origin", "Trip Start","b");
        window.open(url, "start_google_biking");
    }
    else{
        end_lat = $('trailhead_lat').value
        end_lng = $('trailhead_lng').value
        url = buildGoogleTransitURLBase($('trip_date').value,$('trip_dep_arr').value,$('trip_hour').value, 
        $('trip_minutes').value, $('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Origin", "Trailhead","b");
        window.open(url, "start_google_biking");
    }

}

Plan.prototype.showEndBikingNewWindow = function() {
	start_lat = $('trip_end_lat').value
	start_lng = $('trip_end_lng').value
	end_lat = $('end_lat').value
	end_lng = $('end_lng').value
    if (this.mode == this.TRIP) {
        url = buildGoogleTransitURLBase($('trip_date').value,$('trip_dep_arr').value,$('trip_hour').value, $('trip_minutes').value, 
        $('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Trip End", "Destination","b");
        window.open(url, "end_google_biking");
    }
    else{
		start_lat = $('trailhead_lat').value
		start_lng = $('trailhead_lng').value
        url = buildGoogleTransitURLBase($('trip_date').value,$('trip_dep_arr').value,$('trip_hour').value, 
        $('trip_minutes').value, $('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Trailhead", "Destination","b");
        window.open(url, "end_google_biking");
    }

}

Plan.prototype.showStartWalkingNewWindow = function() {
    start_lat = $('start_from_lat').value
    start_lng = $('start_from_lng').value
    end_lat = $('trip_start_lat').value
    end_lng = $('trip_start_lng').value
    if (this.mode == this.TRIP) {
        url = buildGoogleTransitURLBase($('trip_date').value,$('trip_dep_arr').value,$('trip_hour').value, $('trip_minutes').value, 
        $('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Origin", "Trip Start","w");
        window.open(url, "start_google_walking");
    }
    else{
        end_lat = $('trailhead_lat').value
        end_lng = $('trailhead_lng').value
        url = buildGoogleTransitURLBase($('trip_date').value,$('trip_dep_arr').value,$('trip_hour').value, 
        $('trip_minutes').value, $('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Origin", "Trailhead","w");
        window.open(url, "start_google_walking");
    }

}

// TODO FINISH THIS!
Plan.prototype.showEndWalkingNewWindow = function() {
	start_lat = $('trip_end_lat').value
	start_lng = $('trip_end_lng').value
	end_lat = $('end_lat').value
	end_lng = $('end_lng').value
    if (this.mode == this.TRIP) {
        url = buildGoogleTransitURLBase($('trip_date').value,$('trip_dep_arr').value,$('trip_hour').value, $('trip_minutes').value, 
        $('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Trip End", "Destination","w");
        window.open(url, "end_google_walking");
    }
    else{
		start_lat = $('trailhead_lat').value
		start_lng = $('trailhead_lng').value
        url = buildGoogleTransitURLBase($('trip_date').value,$('trip_dep_arr').value,$('trip_hour').value, 
        $('trip_minutes').value, $('trip_ampm').value, start_lat, start_lng, end_lat, end_lng, "Trailhead", "Destination","w");
        window.open(url, "end_google_walking");
    }

}

Plan.prototype.showEndTransit511NewWindow = function() {
	dep_arr = $('trip_end_dep_arr').value;
	raw_trip_date = $('trip_end_date').value;
	trip_date_vals = raw_trip_date.split("/");
	trip_date_input = trip_date_vals[2] + trip_date_vals[0] + trip_date_vals[1]
	start_lat = $('trip_end_lat').value;
	start_lng = $('trip_end_lng').value;
	end_lat = $('end_lat').value;
	end_lng = $('end_lng').value;
	if (this.mode == this.TRIP) {
		url = build511TransitURL(trip_date_input, $('trip_end_dep_arr').value, $('trip_end_hour').value, 
			$('trip_end_minutes').value, $('trip_end_ampm').value, start_lat, start_lng, end_lat, end_lng, "Trip End", "Destination");
		window.open(url, "end_511_transit");
	}
	else {
		start_lat = $('trailhead_lat').value
		start_lng = $('trailhead_lng').value
		url = build511TransitURL(trip_date_input, $('trip_end_dep_arr').value, $('trip_end_hour').value, 
			$('trip_end_minutes').value, $('trip_end_ampm').value, start_lat, start_lng, end_lat, end_lng, "Trailhead", "Destination");
		window.open(url, "end_511_transit");
	}

}


Plan.prototype.showEndTransitGoogleNewWindow = function() {
	start_lat = $('trip_end_lat').value
	start_lng = $('trip_end_lng').value
	end_lat = $('end_lat').value
	end_lng = $('end_lng').value
	if (this.mode == this.TRIP) {
		url = buildGoogleTransitURL($('trip_end_date').value,$('trip_end_dep_arr').value,
			$('trip_end_hour').value, $('trip_end_minutes').value, $('trip_end_ampm').value, 
			start_lat, start_lng, end_lat, end_lng, "Trip End", "Destination");
		window.open(url, "end_google_transit");
	}
	else {
		start_lat = $('trailhead_lat').value
		start_lng = $('trailhead_lng').value
		url = buildGoogleTransitURL($('trip_end_date').value,$('trip_end_dep_arr').value,
			$('trip_end_hour').value, $('trip_end_minutes').value, $('trip_end_ampm').value, 
			start_lat, start_lng, end_lat, end_lng, "Trailhead", "Destination");
     	window.open(url, "end_google_transit");
 	}

}

function buildGoogleDrivingURL(trip_date, trip_arr_dep, trip_hour, trip_minute, trip_ampm, start_lat, start_lng, end_lat, end_lng, originName, destinationName) {
    var url = "http://www.google.com/maps?f=d&source=s_d&saddr=" + escape(originName) + "%20@" + start_lat
            + "+,+" + start_lng + "&daddr=" + escape(destinationName) + "%20@" + end_lat + "+,+" + end_lng
            + "&hl=en&mra=ls&ttype=" + trip_arr_dep + "&noexp=0&noal=0&sort="
            + "&time=" + trip_hour + ":" + trip_minute + trip_ampm + "&date=" + escape(trip_date);      
    return url;
}

function buildGoogleTransitURLBase(trip_date, trip_arr_dep, trip_hour, trip_minute, trip_ampm, start_lat, start_lng, end_lat, end_lng, originName, destinationName, mode) {
	var url = "http://www.google.com/maps?f=d&source=s_d&saddr=" + escape(originName) + "%20@" + start_lat
			+ "+,+" + start_lng + "&daddr=" + escape(destinationName) + "%20@" + end_lat + "+,+" + end_lng
			+ "&hl=en&mra=ls&dirflg=" + mode + "&ttype=" + trip_arr_dep + "&noexp=0&noal=0&sort="
			+ "&time=" + trip_hour + ":" + trip_minute + trip_ampm + "&date=" + escape(trip_date);		
	return url;
}

function buildGoogleTransitURL(trip_date, trip_arr_dep, trip_hour, trip_minute, trip_ampm, start_lat, start_lng, end_lat, end_lng, originName, destinationName) {
    var url = buildGoogleTransitURLBase(trip_date, trip_arr_dep, trip_hour, trip_minute, trip_ampm, start_lat, start_lng, end_lat, end_lng, originName, destinationName, "r");
    return url;
}


/* 
 * This is an example google transit url
 * 
 * http://www.google.com/maps?f=d&source=s_d&saddr=37.774824+,+-122.418493&
 * daddr=37.1932879733327+,+-121.836673021317&geocode=FehlQAIdwwq0-A%3BFUiGNwIdf-u8-A&hl=en&
 * mra=ls&dirflg=r&date=07%2F04%2F09&time=7:00am&
 * ttype=dep&noexp=0&noal=0&sort=&tline=&output=js&vps=3&
 * jsv=164e&sll=37.784825,-122.121277&sspn=0.309318,2.113495&
 * abauth=f9328d12:Aq0GxXyltpkd_qYVJwXdlQTCtQo&absince=1510
 */

function build511TransitURL(trip_date, trip_arr_dep, trip_hour, trip_minute, trip_ampm, start_lat, start_lng, end_lat, end_lng, originName, destinationName) {
	var url = "http://tripplanner.transit.511.org/mtc/XSLT_TRIP_REQUEST2";
	var params = new Array();
	
	var params = ("language=en&sessionID=0&requestID=0&command=&verifyAnyLocViaLocServer=1&convertStopsPTKernel2LocationServer=1&anyHitListReductionLimit=20" + 
	"&itdLPxx_homepage=secondStep&useProxFootSearch=1&coordListOutputFormat=STRING&anySigWhenPerfectNoOtherMatches=1&execInst=normal&nextDepsPerLeg=1&" + 
	"itdLPxx_additonalOptions=&railSystems=&imageFormat=PNG&imageWidth=250&imageHeight=200&imageWidthO=500&imageHeightO=400&imageOnly=1&imageNoTiles=1&" + 
	"prevCommand=&placeInfo=Enter%2BCity%2BName&businessPlace=Enter%2BCity%2BName&businessName=Enter%2BBusinesses&nameRailStation=Select%2BRail%2BStation&" +
	"nameFerryLanding=Select%2BFerry%2BLanding&type_origin=coord&anyObjFilter_origin=0&type_destination=coord&anyObjFilter_destination=0&ptOptionsActive=1&" + 
	"itOptionsActive=1&selOP=1&useOnly=1&preferIncl=1&preferExcl=1&changeSpeed=normal&computationType=SEQUENCE&includedMeans=checkbox&inclMOT_0=on&inclMOT_5=on&" + 
	"inclMOT_9=on&hiddenYear=2009&hiddenMonth=March&itdLPxx_srcid=&name_origin=" 
	+ start_lng + ":" + start_lat + ":WGS84[DD.ddddd]:" + originName + "&place_origin=&name_destination=" + end_lng + ":" + end_lat + 
	":WGS84[DD.ddddd]:" + destinationName + "&place_destination=&routeType=LEASTTIME&itdLPxx_riderCategory=Regular&trITMOT=100&x=38&y=13&itOptionsActive=1&trITMOT=100&trITMOTvalue=24");
	if(trip_date != null)
	{
		params += "&itdDate=" + trip_date;
	}
	if(trip_ampm != null)
	{
		params += "&itdTimeAMPM=" + trip_ampm;
	}
	if(trip_arr_dep != null)
	{
		params += "&itdTripDateTimeDepArr=" + trip_arr_dep;
	}
	if(trip_hour != null)
	{
		params += "&itdTimeHour=" + trip_hour;
	}
	if(trip_minute != null)
	{
		params += "&itdTimeMinute=" + trip_minute;
	}
	
	return url + "?" + params;
}


/*
 * Example 511 trip planner URL
 * 
 * http://tripplanner.transit.511.org/mtc/XSLT_TRIP_REQUEST2?language=en&se
ssionID=0&requestID=0&command=&verifyAnyLocViaLocServer=1&convertStopsPT
Kernel2LocationServer=1&anyHitListReductionLimit=20&itdLPxx_homepage=sec
ondStep&useProxFootSearch=1&coordListOutputFormat=STRING&anySigWhenPerfe
ctNoOtherMatches=1&execInst=normal&nextDepsPerLeg=1&itdLPxx_additonalOpt
ions=&railSystems=&imageFormat=PNG&imageWidth=250&imageHeight=200&imageW
idthO=500&imageHeightO=400&imageOnly=1&imageNoTiles=1&prevCommand=&palce
Info=Enter%2BCity%2BName&businessPlace=Enter%2BCity%2BName&businessName=
Enter%2BBusinesses&nameRailStation=Select%2BRail%2BStation&nameFerryLand
ing=Select%2BFerry%2BLanding&type_origin=coord&anyObjFilter_origin=0&typ
e_destination=coord&anyObjFilter_destination=0&ptOptionsActive=1&itOptio
nsActive=1&selOP=1&useOnly=1&preferIncl=1&preferExcl=1&changeSpeed=norma
l&computationType=SEQUENCE&includedMeans=checkbox&inclMOT_0=on&inclMOT_5
=on&inclMOT_9=on&itdTimeAMPM=pm&hiddenYear=2009&hiddenMonth=March&itdLPx
x_srcid=&name_origin=-122.258893114:37.8077850605:WGS84[DD.ddddd]:Lake+M
erritt&place_origin=&name_destination=-122.4341433062:37.8682613217:WGS8
4[DD.ddddd]:Angel Island State
Park&place_destination=&itdTripDateTimeDepArr=dep&itdTimeHour=5&itdTimeM
inute=23&itdLPxx_TimeAMPM=pm&itdDate=20090515&routeType=LEASTTIME&itdLPx
x_riderCategory=Regular&trITMOT=100&trITMOTvalue=12&x=38&y=13
 */

Plan.prototype.initTripDate = function(){
        var now = new Date();
        var month = zeroPad(now.getMonth() + 1, 2);
        var day = zeroPad(now.getDate(), 2);
        var tripDate = month + '/' + day + '/' + now.getFullYear();
        $('trip_date').value = tripDate;
        $('trip_end_date').value = tripDate;
        var tripHour = now.getHours();
        var tripAMPM = 'AM';
        //alert(tripHour);
        if (tripHour > 11) {
            tripHour = tripHour - 12;
            tripAMPM = 'PM';
            jQuery("#pm_option").attr('selected', 'true')
            jQuery("#end_pm_option").attr('selected', 'true')
        }
        else {
            jQuery("#am_option").attr('selected', 'true')
            jQuery("#end_am_option").attr('selected', 'true')
        }
        if (tripHour == 0) {
            tripHour = 12;
        }
        $('trip_hour').value = zeroPad(tripHour, 2);
        $('trip_end_hour').value = zeroPad(tripHour, 2);
        $('trip_minutes').value = zeroPad(now.getMinutes(), 2);
        $('trip_end_minutes').value = zeroPad(now.getMinutes(), 2);
        
        jQuery("#trip_date").datepicker({
            minDate: 0,
            maxDate: 21,
            showButtonPanel: true
        });
        jQuery("#trip_end_date").datepicker({
            minDate: 0,
            maxDate: 21,
            showButtonPanel: true
        });
    }

Plan.prototype.loadTripIntoPlan = function(id) {
	url = "/trips/" + id + "/json/";
	GDownloadUrl(url, function(data) {
		trip = data.evalJSON();
		$('trip_start_lat').value = trip.start_lat;
		$('trip_start_lng').value = trip.start_lng;
		$('trip_end_lat').value = trip.end_lat;
		$('trip_end_lng').value = trip.end_lng;
		application.tripStartMarker.setLatLng(new GLatLng(
				parseFloat(trip.start_lat), parseFloat(trip.start_lng)));
		application.tripEndMarker.setLatLng(new GLatLng(
				parseFloat(trip.end_lat), parseFloat(trip.end_lng)));
		application.loadJSONRoute(trip.route);
		application.centerOnTrip();
		showTripDrivingRoutes();
	});
}

Plan.prototype.loadTrailheadIntoPlan = function(id) {
	url = "/json/Trailhead/" + id;
	GDownloadUrl(url, function(data) {
		trailhead = data.evalJSON();
		$('trailhead_lat').value = trailhead.latitude;
		$('trailhead_lng').value = trailhead.longitude;
		application.trailheadMarker.setLatLng(new GLatLng(
				parseFloat(trailhead.latitude), parseFloat(trailhead.longitude)));
		application.centerOnTrailhead();
		showTripDrivingRoutes();
	});
}

Plan.prototype.loadJSONRoute = function(json) {
	if (this.tripLine != null) {
		this.map.removeOverlay(application.tripLine);
	}

	var route = json.evalJSON();
	
	points = new Array();
	points.push(new GLatLng(route[0][0], route[0][1]));
	for (i = 1; i < route.length; i+=2) {
		points.push(new GLatLng(route[i][0],
				route[i][1]));
	}	
	this.tripLine = new GPolyline(points);
	this.map.addOverlay(application.tripLine);	
}

Plan.prototype.centerOnTrip = function() {
	points = new Array();
	points.push(this.tripStartMarker.getLatLng());
	points.push(this.tripEndMarker.getLatLng());
	points.push(this.startFromMarker.getLatLng());
	points.push(this.returnToMarker.getLatLng());
	newLine = new GPolyline(points);
	centerpoint = newLine.getBounds().getCenter();
	var zoom = this.map.getBoundsZoomLevel(newLine.getBounds());			
	this.map.setCenter(centerpoint, zoom-1);
}

Plan.prototype.centerOnTrailhead = function() {
	points = new Array();
	points.push(this.trailheadMarker.getLatLng());
	points.push(this.startFromMarker.getLatLng());
	points.push(this.returnToMarker.getLatLng());
	newLine = new GPolyline(points);
	centerpoint = newLine.getBounds().getCenter();
	var zoom = this.map.getBoundsZoomLevel(newLine.getBounds());			
	application.map.setCenter(centerpoint, zoom-1);
}

Plan.prototype.selectTrip = function(id) {
	select = $('trip_id');
	for (i = 0; i < select.length; i++) {
		if (select.options[i].value == id) {
			select.selectedIndex = i;
		}
	}
	this.loadTripIntoPlan(id);
}

Plan.prototype.selectTrailhead = function(id) {
	select = $('trailhead_id');
	for (i = 0; i < select.length; i++) {
		if (select.options[i].value == id) {
			select.selectedIndex = i;
		}
	}
	this.loadTrailheadIntoPlan(id);
}

Plan.prototype.selectFirstTrip = function() {
	select = $('trip_id');
	firstId = select.options[0].value;
	this.selectTrip(firstId);
}

Plan.prototype.selectFirstTrailhead = function() {
	select = $('trailhead_id');
	firstId = select.options[0].value;
	this.selectTrailhead(firstId);
}
