
var mapWaypoints          = null;         // variable storing the map
var markerManager         = null;         // variable storing the marker manager
var markersWaypoints      = new Object(); // variable storing all markers for waypoints (the waypoint ID is the key and the marker is the value)
var maxZoomLevelWaypoints = 20;           // maximum zoom level
var noOfRowsWaypointTable = 0;            // variable storing the number of rows of the waypoint table (initialized by Waypoint.php)
var selectedWaypoints     = new Object(); // variable storing all selected waypoints as a map (the ID is the key and the waypoint data is the value)

function CalcLevelGoogleMap(degrees)
{
  if (degrees > 0)
    return Math.floor(Math.log(360.0/degrees)/Math.LN2);
  else
    return 12; // slightly less than 10 km total dimension
}
function ChangeCheckboxSelection(checkedStatus)
{
  for (var i=0; i<noOfRowsWaypointTable; ++i)
  {
    var element = document.getElementById("waypointCheckbox_"+i);
    
    if (element != null)
      element.checked = checkedStatus;
  }
}
function CreateMarker(latitude, longitude, dataWaypoint)
{
  var info;
  var marker = new GMarker(new GLatLng(latitude,longitude),{draggable:false,title:dataWaypoint["Name"]});

//  GEvent.addListener(marker,'dblclick', function() {mgr.removeMarker(marker)} );

  info = "<b>"+dataWaypoint["Name"]+"</b>";
  if (dataWaypoint["Abbreviation"] != null)
    info += " <small>("+dataWaypoint["Abbreviation"]+")</small>";
  info += "<br/><br/>";
  info += "<table>\n";
  info += "<tr><td>Latitude:</td><td>"+FormatGeodeticDegrees(latitude,'N','S')+"</td></tr>\n";
  info += "<tr><td>Longitude:</td><td>"+FormatGeodeticDegrees(longitude,'E','W')+"</td></tr>\n";
  if (dataWaypoint["Altitude"] != null)
    info += "<tr><td>Altitude:</td><td>"+FormatAltitude(parseFloat(dataWaypoint["Altitude"]))+"</td></tr>\n";
  info += "\n</table>";
  marker.bindInfoWindowHtml(info);

  return marker;
}

function DeselectWaypoints(uriProjectPath)
{
 // remove selection from database
  var request = new Request({url:uriProjectPath+"SkyView/PHP/DeselectAllWaypoints.php"});
  
  request.send();
 // remove selection from checkboxes:
  ChangeCheckboxSelection(false);
 // remove array containing the selected waypoints:
  selectedWaypoints = new Object();
 // remove markers:
  markersWaypoints = new Object();
  markerManager.clearMarkers();
 // update map:
  SetDefaultCenterAndLevel(mapWaypoints);
}

function DisplayWaypoints(map, waypoints)
{
  if ((map != null) && (waypoints != null))
  {
    for (var i in waypoints)
    {
      var latitude  = parseFloat(waypoints[i]["Latitude"]);
      var longitude = parseFloat(waypoints[i]["Longitude"]);
      var marker    = CreateMarker(latitude,longitude,waypoints[i]);

      markersWaypoints[i] = marker;
      markerManager.addMarker(marker,1,20);
    }
    markerManager.refresh();
  }
}

function FormatAltitude(altitude, unit, invalidReplacement)
{
  if (unit == null)
    unit = 'm';
  if (invalidReplacement == null)
    invalidReplacement = '';
  if (altitude != null)
    if (unit != '')
      return altitude+' '+unit;
    else
      return altitude;
  else
    return invalidReplacement;
}

function FormatGeodeticDegrees(degree, posIndicator, negIndicator, unit, invalidReplacement)
{
  if (unit == null)
    unit = '°';
  if (invalidReplacement == null)
    invalidReplacement = '';
  if (degree != null)
    if (degree >= 0)
      return degree+unit+posIndicator;
    else
      return -degree+unit+negIndicator;
  else
    return invalidReplacement;
}

function GetSelectedWaypoints(uriProjectPath)
{
  selectedWaypoints = new Object();
 // get selection from database
  var request = new Request.JSON({url:uriProjectPath+"SkyView/PHP/API/Visualization/GetSelectedWaypoints.php",
                                  onSuccess:function(jsonObject,jsonString)
                                            {
                                              if (jsonString != '[]')
                                                selectedWaypoints=jsonObject;
                                            }
                                 });
  
  request.post();
}

function LoadGoogleMap(uriProjectPath)
{ 
  if (GBrowserIsCompatible())
  { 
    mapWaypoints  = new GMap2(document.getElementById("map_canvas")); 

    mapWaypoints.addControl(new GLargeMapControl()); 
    mapWaypoints.addControl(new GMapTypeControl());
    mapWaypoints.addControl(new GOverviewMapControl());
    SetDefaultCenterAndLevel(mapWaypoints);
    markerManager = new MarkerManager(mapWaypoints,{maxZoom:maxZoomLevelWaypoints, trackMarkers:true}); // center must be set before marker manager can be created
    ShowSelectedWaypoints(uriProjectPath);
  }
  else
    mapWaypoints = null;
} 

function SelectAllWaypoints(uriProjectPath)
{
 // select waypoints in database
  var request = new Request({url:uriProjectPath+"SkyView/PHP/SelectAllWaypoints.php",
                             onComplete:function()
                             {
                              // add selection to checkboxes:
                               ChangeCheckboxSelection(true);
                              // get the selected waypoints and display them:
                               ShowSelectedWaypoints(uriProjectPath);
                             }
                            });
  
  request.post();
}
function SetCenterAndLevelMapWaypoints(map, waypoints)
{
  if (map != null)
    if (waypoints != null)
    {
      var existingWaypoints = false;
      var maxLatitude = -90.0;
      var minLatitude =  90.0;
      var maxLongitude = -180.0;
      var minLongitude =  180.0;
      
      for (var i in waypoints)
      {
        var latitude  = parseFloat(waypoints[i]["Latitude"]);
        var longitude = parseFloat(waypoints[i]["Longitude"]);

        if (latitude > maxLatitude) maxLatitude = latitude;
        if (latitude < minLatitude) minLatitude = latitude;
        if (longitude > maxLongitude) maxLongitude = longitude;
        if (longitude < minLongitude) minLongitude = longitude;
        existingWaypoints = true;
      }
      if (existingWaypoints)
        map.setCenter(new GLatLng(0.5*(minLatitude+maxLatitude),0.5*(minLongitude+maxLongitude)),
                      CalcLevelGoogleMap(Math.max(maxLatitude-minLatitude,maxLongitude-minLongitude)));
      else
        SetDefaultCenterAndLevel(map);
    }
}
function SetDefaultCenterAndLevel(map)
{
  map.setCenter(new GLatLng(52.2975083333333,4.68422222222222),12);
}
function ShowSelectedWaypoints(uriProjectPath)
{
 // remove previously added markers and their variables:
  markerManager.clearMarkers();
  markersWaypoints  = new Object();
  selectedWaypoints = new Object();
 // get selection from database and display it
  var request = new Request.JSON({url:uriProjectPath+"SkyView/PHP/API/Visualization/GetSelectedWaypoints.php",
                                  onSuccess:function(jsonObject,jsonString)
                                            {
                                              if (jsonString != '[]')
                                                selectedWaypoints=jsonObject;
                                              SetCenterAndLevelMapWaypoints(mapWaypoints,selectedWaypoints)
                                              DisplayWaypoints(mapWaypoints,selectedWaypoints);
                                           }
                                 });
  
  request.post();
}

function ToggleSelectionWaypoint(selectedCheckbox, idWaypoint, uriProjectPath)
{
  var idArray = new Array(1);
  var selectRequest;

  idArray[0] = idWaypoint;
  if (selectedCheckbox.checked == true)
  {
    var dataRequest = new Request.JSON({url:uriProjectPath+"SkyView/PHP/GetWaypoint.php",
                                       onSuccess:function(jsonObject,jsonString)
                                                 {
                                                   if (jsonString != '[]')
                                                   {
                                                     var receivedWaypoint = new Object();
                                                     
                                                     receivedWaypoint[idWaypoint] = jsonObject;
                                                     $extend(selectedWaypoints,receivedWaypoint);
                                                     SetCenterAndLevelMapWaypoints(mapWaypoints,selectedWaypoints);
                                                     DisplayWaypoints(mapWaypoints,receivedWaypoint);
                                                   }
                                                 }
                                      });

    dataRequest.post({'id':idWaypoint});
    selectRequest = new Request({url:uriProjectPath+"SkyView/PHP/API/Visualization/SelectWaypoints.php"});
  }
  else
  {
    markerManager.removeMarker(markersWaypoints[idWaypoint]);
    delete markersWaypoints[idWaypoint];
    delete selectedWaypoints[idWaypoint];
    SetCenterAndLevelMapWaypoints(mapWaypoints,selectedWaypoints);
    DisplayWaypoints(mapWaypoints,jsonObject);
    selectRequest = new Request({url:uriProjectPath+"SkyView/PHP/API/Visualization/DeselectWaypoints.php"});
  }
  selectRequest.post({'data':idArray});
}

