var map = null;

function LoadMap()
{
    // Load the Map
    map = new VEMap("myMap");
    // map.LoadMap();
    
    // Attach our onclick map event handler
    map.AttachEvent("onclick", Map_Click);
	// Set map center to St. John's
	// mapCenter = new VELatLong(47.6, -52.7);
	// Set map center to NL
	//mapCenter = new VELatLong(49.21, -55.32);
	// LoadMap(VELatLong, zoom, style, fixed, mode, showSwitch, tileBuffer, mapOptions);
	//map.LoadMap(mapCenter, 6, VEMapStyle.Road, false, VEMapMode.Mode2D, false, 0);
	
	
	// My Version.
	// Set map center to St. John's
	//mapCenter = new VELatLong(47.6, -52.7);
	mapCenter = new VELatLong(47.57, -52.8);
	// LoadMap(VELatLong, zoom, style, fixed, mode, showSwitch, tileBuffer, mapOptions);
	map.LoadMap(mapCenter, 11, VEMapStyle.Road, false, VEMapMode.Mode2D, false, 0);
	
	document.getElementById("myMap").childNodes[0].style.cursor = "crosshair";
}

// The Map onclick event handler
function Map_Click(eventArgs)
{
    var clickedLatLong = eventArgs.latlong;
    if (map.GetMapMode() == VEMapMode.Mode2D)
    {
        // In 2D Mode the eventArgs.latlong property doesn't contain the lat/long point that was clicked.
        // So we must figure it out using the x and y coordinates of the point on the map that was clicked.
        clickedLatLong = map.PixelToLatLong(new VEPixel(eventArgs.mapX, eventArgs.mapY));
    }
    
    // When the user Right-Clicks, Draw the Polygon
    if (eventArgs.rightMouseButton)
    {
		// Show the points in the textbox. seperate each coordinate with a ';'
		if (document.getElementById("txtPoints_Hidden").value != '')
		{
			document.getElementById("txtPoints_Hidden").value = document.getElementById("txtPoints_Hidden").value + ';' + clickedLatLong;
		}
		else
		{
			document.getElementById("txtPoints_Hidden").value = clickedLatLong;
		}
		
        var newShape = null;
        if (map.GetShapeLayerCount() > 0)
        {
            // Get reference to the Default Shape Layer
            var shapeLayer = map.GetShapeLayerByIndex(0);
            if (shapeLayer.GetShapeCount() > 0)
            {
                // Get points already plotted
                var points = shapeLayer.GetShapeByIndex(0).GetPoints();
                // Add the newly clicked point to the collection of points
                points[points.length] = clickedLatLong;
				
                newShape = new VEShape(VEShapeType.Polyline, points);
                // Don't show the shapes icon on the map, we only want to see the line
                newShape.HideIcon();
            }
        }
        
        if (newShape == null)
        {
            // If this is the first Point plotted, then show it as a Pushpin
            newShape = new VEShape(VEShapeType.Pushpin, clickedLatLong);
			// newShape.SetCustomIcon("<img src=\'pins.png\' />");
        }
        
        // Clear out the old shape
        map.DeleteAllShapes();
        
        // Add our new shape
        map.AddShape(newShape);
        
        CalculateDistance();
    }
}


function CalculateDistance()
{
    var distMessage = document.getElementById("spanDistanceMessage");
    var dist = document.getElementById("spanDistance");
	var txtDist = document.getElementById("txtDistanceKM_Hidden");
    
    var points = new Array();
    
    // Get all the Points being plotted
    if (map.GetShapeLayerCount() > 0)
    {
        var shapeLayer = map.GetShapeLayerByIndex(0);
        if (shapeLayer.GetShapeCount() > 0)
        {
            points = shapeLayer.GetShapeByIndex(0).GetPoints();
        }
    }
    
    if (points.length <= 1)
    {   
        // Display message to plot more points
        distMessage.style.display = "";
        dist.style.display = "none";
    }
    else
    {
        // Display the Distance of all the points being plotted
        distMessage.style.display = "none";
        dist.style.display = "";
        
        var dblDistance = 0.0;
        
        var unit = GeoCodeCalc.EarthRadiusInMiles;
        if (!document.getElementById("rdMiles").checked) unit = GeoCodeCalc.EarthRadiusInKilometers;
        
        for(var i = 1; i < points.length; i++)
        {
            dblDistance += GeoCodeCalc.CalcDistance(points[i - 1].Latitude, points[i - 1].Longitude, points[i].Latitude, points[i].Longitude, unit);
        }
        
        dist.innerHTML = (Math.round(dblDistance*100)/100).toString() + " " + (unit == GeoCodeCalc.EarthRadiusInMiles ? "Miles" : "Kilometers");
		txtDist.value = dblDistance.toString();
    }
}

function btnClearMap_Click()
{
    // Clear all points plotted
    map.DeleteAllShapes();
	// Clear textbox clicks
	document.getElementById("txtPoints_Hidden").value = '';
    // ReCalculate - so we can hide the last calculated distance
    CalculateDistance();
}

function Unit_Click()
{
    // ReCalculate the distance when the distance unit is changed
    CalculateDistance();
}

function trimString(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}

function checkRequired() {
	var errmsg = "";
	var errhdr = "";
	var errftr = "";
	if (trimString(document.forms.frmCreateMap.txtPoints_Hidden.value) == '') {
		errmsg = errmsg +  "   - Please right-click the map to create your route\n";
	}
	if (trimString(document.forms.frmCreateMap.txtTitle.value) == '') {
		errmsg = errmsg +  "   - Please enter a title\n";
	}
		if (errmsg != "") {
			errhdr = "The following fields are required:\n\n";
			errftr = "\nClick 'OK' to correct these errors.";
			errmsg = errhdr + errmsg + errftr;
			alert(errmsg);
			return false;
		} else {
			return true;
		}
}
