﻿var SnapToRoadEnabled=false;

var IndexOfPointBeingSnappedToRoad;

/*
 * Returns a LatLng for a point on the road.
 * A call to this method during an async lookup will cancel the previous async lookup
 *
 * If this method is being called to position a new last point on the path then we will
 * want to look up directions from the last point on the map to the location being clicked
 * instead of from the point being clicked to the point being clicked. When this behavior
 * is desired, pass true for the last parameter, BuildCourseToPoint
 */
function SnapLatLngToRoad(Index, LatLng, BuildCourseToPoint)
{
    // Remember which point we're working on.
    IndexOfPointBeingSnappedToRoad=Index;

    if(BuildCourseToPoint==null||BuildCourseToPoint==false||PathPoints.length<2)
    {
        // What we'll do here is get directions from the point where the cursor was clicked to itself.
        // This will fetch the nearest crossroads or address on the map.
        directions.loadFromWaypoints([LatLng.toUrlValue(6),LatLng.toUrlValue(6)],{getPolyline:true});
    }
    else
    {
        // Get directions from the last point to the point being clicked
        directions.loadFromWaypoints([PathPoints[Index-1].getLocation().toUrlValue(6),LatLng.toUrlValue(6)],{getPolyline:true});
    }
}

/*
 * Sets up event handlers used for the SnapToRoad feature.
 */
function InitializeSnapToRoad()
{
    GEvent.addListener(directions,"load",directions_OnLoad);
    //GEvent.addListener(directions,"error", function() {GLog.write("Failed: "+directions.getStatus().code);});
    GEvent.addListener(directions,"error", function()
        {
            // Disable the snap to roads feature
            SetSnapToRoadEnabled(false);
            
            // Tell the user there was a problem
            alert('Failed to snap this location to a road. This feature may not be available in the country you selected. The snap to roads feature has been disabled. You can re-enable it from the Map Options menu.\r\n\r\n'
                + "Failed: " + directions.getStatus().code);
        });

    SetSnapToRoadEnabled(false);
}

/*
 * This is an event handler that will be called when an async call to the google directions server completes.
 */
function directions_OnLoad()
{
    // The async request completed so now we've got to get the polyline that was returned
    var ThePolyline=directions.getPolyline();
    
    if(ThePolyline.getVertexCount()==1)
    {
        AdjustMarkerPosition(IndexOfPointBeingSnappedToRoad,ThePolyline.getVertex(0)); // simple, eh?
    }
    else if(ThePolyline.getVertexCount()>1)
    {
        // The first vertex is the position of the previous marker
        var LastPointIndex=PathPoints.length-1;
        PathPoints[LastPointIndex].setLocation(ThePolyline.getVertex(0));
    
        for(var i=1;i<ThePolyline.getVertexCount();i++)
        {
            PathPoints[i+LastPointIndex]=new PathPoint(ThePolyline.getVertex(i),'');
        }
        
        RefreshMap(LastCursorPosition);
        return;
    }
    
    // If a point is being dragged we don't want to mess with the markers but if the user's done dragging, why not
    // reposition the marker too?
    if(!DragIsInProgress)
        RefreshMap(LastCursorPosition);
}

/*
 * Toggles the snap to road feature on and off
 */
function ToggleSnapToRoadEnabled()
{
    SetSnapToRoadEnabled(!SnapToRoadEnabled);
}

/*
 * Enables or disables the snap to road feature based on the NewValue parameter
 */
function SetSnapToRoadEnabled(NewValue)
{    
    // Update checkbox
    if($get('chkSnapToRoad').checked!=NewValue)
        $get('chkSnapToRoad').click(); // We can't just check the box because we're using an extender
    else
       SnapToRoadEnabled = NewValue; 
}
