google.load("maps", "2");
		
var map = null;
var geocoder = null;
var directions = null;
var errmsg = "";
		
function showAddress(address) {

    if (address == "0") return;
		    
    geocoder.getLatLng(address,
        function(point) {
     
            if (!point) {
     
                alert(address + " not found.");
     
            } else {
     
                map.setCenter(point, 13);
     
                var marker = new google.maps.Marker(point);
     
                map.addOverlay(marker);
     
                marker.openInfoWindowHtml(address);
     
            }
     
        }
    );
		    
}

function calculateFare(distanceTraveled, tripDuration) {

    var disclaimer = "The calculated fares are an approximation; they do not "
        + "take into account traffic obstructions (trains, construction, etc.). "
        + "In the event that there is a discrepancy between the fare calculated "
        + "here and the actual fare present on the meter in the taxi, the fare "
        + "dictated by the taxi meter will be deemed correct.";
    document.getElementById("disclaimer").innerHTML = disclaimer;

    var totalFare = 0.00;
    var returnHTML = "";
    
    // stopTimeRatio is an empirically-provided number for approximating how often
    // the meter is going to start charging by time, as opposed to distance.
    var stopTimeRatio = 0.24822696;

    var baseFare = 3.50;

    var meterIncrement = 0.25;
    
    // The time interval between rate changes, in seconds.
    var timeInterval = 26;

    // The distance interval between rate changes, in meters.
    var distanceInterval = 130;
    
    // Various hours (in 24-hour format) to adjust the approximate ratio of stop time
    // (ie. when the timer takes over, as opposed to transmission pulses) during
    // different periods of the day, for calculating the approximate fare.
    var rushHourMorningStart = 7;
    var rushHourMorningEnd = 9;
    var rushHourAfternoonStart = 16;
    var rushHourAfternoonEnd = 18;
    
    var daytimeStart = rushHourMorningEnd;
    var daytimeEnd = rushHourAfternoonStart;
    
    var eveningStart = rushHourAfternoonEnd;
    var eveningEnd = rushHourMorningStart;
    
    var currentHour = new Date().getHours();
    
    // Setting the stop-time ratio during rush hour traffic.
    if (currentHour >= rushHourMorningStart && currentHour <= rushHourMorningEnd ||
        currentHour >= rushHourAfternoonStart && currentHour <= rushHourAfternoonEnd) {
        
        stopTimeRatio = 0.33;
        document.getElementById("rush_hour").innerHTML = "Note: It is currently rush hour.";
        
    } else if (currentHour >= daytimeStart && currentHour <= daytimeEnd) {
    
        // Setting the stop-time ratio during normal, day traffic.
        stopTimeRatio = 0.24822696;
        
    } else {
    
        // Setting the stop-time ratio during evening traffic.
        stopTimeRatio = 0.2;
        
    }
    
    var timeFactor = Math.round((stopTimeRatio * tripDuration) / timeInterval) * meterIncrement;
    
    // Raw distance calculation.
    totalFare += baseFare + (Math.round(distanceTraveled / distanceInterval) * meterIncrement);
    
    // Adding in the time factor.
    totalFare += timeFactor;
    
    // Rounding the fare.
    totalFare = Math.round(totalFare * 100) / 100;
    
    returnHTML += '<strong>Approximate fare: $' + totalFare + '</strong>';
    returnHTML += ' ($';
    
    if ((totalFare - 1.00) < 3.50) {
        
        returnHTML += "3.50";
        
    } else {
    
        returnHTML += (totalFare - 1.00);
        
    }
    
    returnHTML += ' to $' + (totalFare + 1.00) + ')';
    
    // Debugging portion.
    /*
    returnHTML += "<br />";
    returnHTML += "Time factor: " + timeFactor + " - " + "Hour: " + currentHour + " - ";
    returnHTML += "Distance traveled: " + distanceTraveled + "m";
    returnHTML += " - ";
    returnHTML += "Trip duration: " + tripDuration + "s";
    */
    
    return returnHTML;
    
}

function showDirections() {

    var departureFromText = window.document.main_form.departure2.value;
    var departureInLondon = window.document.main_form.departure_in_london.checked;
    var destinationFromText = window.document.main_form.destination2.value;
    var destinationInLondon = window.document.main_form.destination_in_london.checked;
    
    // Before we get too far into parsing, we are going to check and make sure
    // that there are, actually, two addresses to work with.
    var depstr = departureFromText;
    var deststr = destinationFromText;
    if (depstr.replace(/\s/g, "") == "") {
    	alert("The departure address cannot be blank.");
		return;
	}
	if (deststr.replace(/\s/g, "") == "") {
		alert("The destination address cannot be blank.");
		return;
	}

    var departure = null;
    var destination = null;
    
    if (departureInLondon) {
    
        departure = departureFromText + ", London ON";
        
    } else {
    
        departure = departureFromText;
        
    }
    
    if (destinationInLondon) {
    
        destination = destinationFromText + ", London ON";
        
    } else {
    
        destination = destinationFromText;
        
    }
    
    // Clear the overlays (polylines) from the map.
    map.clearOverlays();
    
    // Clear any previous directions.
    if (directions != null) directions.clear();

    directions = new google.maps.Directions(
        map, document.getElementById("directions")
    );
    
    var sMarker = null;
    var fMarker = null;
    
    google.maps.Event.addListener(directions, "load", function() {
        
        var distance = directions.getDistance().meters;
        var duration = directions.getDuration().seconds;
        //directions.getPolyLine().enableEditing(); // For future implementation.
        sMarker = directions.getMarker(0);
        fMarker = directions.getMarker(1);

	// -------------------------------------------------------------------	
	// THIS IS WHERE calculateFare() GETS CALLED!
	// -------------------------------------------------------------------
        document.getElementById("fare").innerHTML = calculateFare(distance, duration);
	// -------------------------------------------------------------------
        
    });
    
    google.maps.Event.addListener(directions, "error", function() {
    
        // The status returned when the GDirections class loads,
	// asynchronously.
        var dstatus = directions.getStatus().code;
        //alert(dstatus); // For debugging.
        
        alert("(" + dstatus + ") One of the addresses you supplied is invalid.");
        
        directions.clear();
    
    });
    
    directions.load("from: " + departure + " to: " + destination);
    
    // Add some controls to the map.
    map.addControl(new google.maps.MapTypeControl());
    map.addControl(new google.maps.LargeMapControl3D());
    
}
		
function init() {
    if (GBrowserIsCompatible()) {
	map = new google.maps.Map2(document.getElementById("map"));
	map.setCenter(new google.maps.LatLng(49, 80), 13);
	geocoder = new google.maps.ClientGeocoder();
    }
}

