var lstPoints = [];
var contextmenu;
var mode = 1;
var unit = 0;
var point;
var pointDrag;

function initializeDP() {
  if (GBrowserIsCompatible()) {
    document.getElementById("coo").value = pointSes;
    document.getElementById("adr").value = adrSes;
    pointA = new GLatLng(Number(latSes), Number(lonSes));
    lstPoints.push(new GLatLng(pointA.y,pointA.x));
    map = new GMap2(document.getElementById("map"));
    if(Number(zoom)<5){
       zoom=14;
    };
    map.setCenter(pointA, Number(zoom));
    map.enableDoubleClickZoom();
    //map.enableScrollWheelZoom();
    map.addControl(new GMapTypeControl());
    map.addControl(new GLargeMapControl3D());
    selectedModeDP(document.getElementById('mapMode'));
    createContextMenuDP(map);
    map.addMapType(G_PHYSICAL_MAP);
    map.setMapType(G_HYBRID_MAP);
    map.setZoom( Number(zoom) );
    map.enableDragging();
    geocoder = new GClientGeocoder();
    createCustomMarkerDP(pointA, "A");
    GEvent.addListener(map, "click", function(overlay, point) { clickedDP(overlay, point);});
    GEvent.addListener(map, "mousemove", function(point) { mousemoveDP(point);});
  }
}

function clickedDP(overlay, point) {
  if (point) {
    geocoder.getLocations(point, function(response) {
      if(!response || response.Status.code != 200) {
        alert("reverse geocoder failed to find an address for " + latlng.toUrlValue());
      } else {
        //document.getElementById("coo").value = "p:"+point;
        lstPoints.push(new GLatLng(point.y, point.x));
        repaintMarkerDP(point);
      };
    });
  };
}

function showLocationDP(address) {
  if (geocoder) {
    geocoder.getLatLng( address,
      function(point) {
        if (!point) {
          alert(address + " not found");
        } else {
          map.setCenter(point, 16);
          //setPointDataDP(point);
          clearAndRepaintMarkerDP(point);
        }
      });
  };
}

function dragendDP(point, marker) {
  var point = marker.getPoint();
  var idL = lstPoints.length-1;
  var idD = idL;
  for (var i = 0; i <= idL; ++i) {
    pointT = lstPoints[i];
    if(pointT.lat() == pointDrag.lat() &&
      pointT.lng() == pointDrag.lng()){
      idD = i;
    }
  }
  lstPoints.splice(idD, 1, new GLatLng(point.y, point.x));
//document.getElementById("coo").value = "lstP:" +lstPoints.length+" id:"+idD+" p:"+point+"-pointDrag:"+pointDrag;
  repaintMarkerDP(point);
}

function mousemoveDP(point) {
  var mode = document.getElementById('mapMode').selectedIndex;
  if (point && mode==0) {
    document.getElementById("cooMouse").value = point.toUrlValue(5);
  } else {
    //document.getElementById("cooMouse").value = '';
  }
}

function createCustomMarkerDP(point, letter) {
  var customIcon = new GIcon(G_DEFAULT_ICON);
  var marker = null;
  var markerOption = { icon:customIcon, draggable:true };
  if(letter == 'A') {
    //markerOption = { icon:customIcon, draggable:false };
    customIcon.image = "../../dp/images/dpMarker_32_start.png";
  } else if(letter == 'B'){
    customIcon.image = "../../dp/images/dpMarker_32_" + letter + ".png";
  } else if(letter == 'D'){
    customIcon.image = "../../dp/images/dpMarker_20_blue.png";
    customIcon.iconSize = new GSize(15,25);
    customIcon.iconAnchor = new GPoint(7,25);
    //customIcon.iconSize = new GSize(10,20);
    //customIcon.iconAnchor = new GPoint(5,20);
  } else if(letter == 'P'){
    customIcon.image = "../../dp/images/dpMarker_20_yellow.png";
    customIcon.iconSize = new GSize(15,25);
    customIcon.iconAnchor = new GPoint(7,25);
  } else if(letter == 'S'){
    customIcon.image = "../../dp/images/dpMarker_9_blue.png";
    customIcon.iconSize = new GSize(9,9);
    customIcon.iconAnchor = new GPoint(4,4);
  } else if(letter == 'S2'){
    customIcon.image = "../../dp/images/dpMarker_9_yellow.png";
    customIcon.iconSize = new GSize(9,9);
    customIcon.iconAnchor = new GPoint(4,4);
  } else {
    customIcon.image = "../../dp/images/dpMarker_20_yellow.png";
    customIcon.iconSize = new GSize(15,25);
    customIcon.iconAnchor = new GPoint(7,25);
  }
  customIcon.shadow = "";
  if(markerOption != null){
    marker = new GMarker(point, markerOption);
  } else {
    marker = new GMarker(point);
  }
  setInfoPointDP(point);
  map.addOverlay(marker);
  map.closeInfoWindow();
  marker.openInfoWindowHtml(setInfoPointDP(marker.getPoint()));
  if(mode == 3){
     marker.closeInfoWindow();
  }
  GEvent.addListener(marker, "click", function() {
//      document.getElementById("coo").value = "click:" +lstPoints.length+"-io:"+infowindowopen();
    marker.openInfoWindowHtml(setInfoPointDP(marker.getPoint()));
  });
  GEvent.addListener(marker, "dblclick", function() {
    marker.closeInfoWindow();
  });
  GEvent.addListener(marker, "dragend", function() {
    dragendDP(point, marker);
  });
  GEvent.addListener(marker, "dragstart", function() {
    map.closeInfoWindow();
    pointDrag = marker.getPoint();
  });
  GEvent.addListener(marker, "drag", function() {
    document.getElementById("coo").value = marker.getPoint().lat().toFixed(5)+" , "+marker.getPoint().lng().toFixed(5);
  });
  return marker;
}

function clearAndRepaintMarkerDP(point) {
  lstPoints = [];
  lstPoints.push(new GLatLng(pointA.y, pointA.x));
  repaintMarkerDP(point);
}

function repaintMarkerDP(point){
  map.clearOverlays();
  if(point && mode == 1 && lstPoints.length > 1){
    lstPoints = [];
    lstPoints.push(new GLatLng(pointA.y, pointA.x));
    lstPoints.push(new GLatLng(point.y, point.x));
  }
  var last = lstPoints.length-1;
  var polyline = new GPolyline(lstPoints, "#D4FFD4", 3,1);
  createCustomMarkerDP(lstPoints[0], "A");
//document.getElementById("coo").value = "lstP:" +lstPoints.length+" p:"+point;
  for (var i = 1; i <= last; ++i) {
    point = lstPoints[i];
    if(mode == 0 || mode == 1){
      if(i == last){
        createCustomMarkerDP(point, "P");
      } else {
        createCustomMarkerDP(point, "D");
      }
    } else if(mode == 2){
      if(i == last){
        createCustomMarkerDP(point, "D");
      } else {
        createCustomMarkerDP(point, "P");
      }
    } else if(mode == 3){
      if(i==last){
        createCustomMarkerDP(point, "S2");
      } else {
        createCustomMarkerDP(point, "S");
      }
    }
  }
  if(mode == 1 || mode == 2){
    map.addOverlay(polyline);
    document.getElementById("cooMouse").value = getDistanceDP(polyline);
  }
  if(mode == 3){
    var lstA = lstPoints;
    if(lstPoints.length > 2){
      var lstA2 = [];
      lstA2.push(new GLatLng(pointA.y,pointA.x));
      lstA = lstPoints.concat(lstA2);
    }
    var polylineA = new GPolyline(lstA, "black", 3,1);
    var polygon = new GPolygon(lstA, "blue", 2, 1, "yellow", 0.4);
    map.addOverlay(polygon);
    document.getElementById("cooMouse").value = getAreaDP(polygon, polylineA);
  }
}

function setInfoPointDP(point) {
  var adr = "address";
  var latlng = new GLatLng(point.y, point.x);
  var latX = point.lat().toFixed(5);
  var lonX = point.lng().toFixed(5);
  var pntX = latX+" , "+lonX;
  if (geocoder) {
    geocoder.getLocations(latlng,
      function(response) {
        if (!response || response.Status.code != 200) {
          document.getElementById("coo").value = "address not found :-) ";
        } else {
          adr = response.Placemark[0].address;
          document.getElementById("address2").value = adr;
          document.getElementById("adr").value = adr;
        }
      });
  };
  document.getElementById("point").value = pntX;
  document.getElementById("coo").value = "lat,lng: "+pntX;
  document.getElementById("zoom").value = map.getZoom();
  adr = document.getElementById("adr").value + "<br>Latitude &nbsp;&nbsp;: " + point.lat().toFixed(6) + "<br>Longitude: " + point.lng().toFixed(6);
  return adr;
}

function selectedModeDP(selectobj){
  mode = selectobj.selectedIndex;
  if (mode==0){
    document.getElementById("cooMouse").value = "point";
  } else if (mode==1){
    document.getElementById("cooMouse").value = "distance";
  } else if (mode==2){
    document.getElementById("cooMouse").value = "polyline";
  } else if (mode==3){
    document.getElementById("cooMouse").value = "area";
  } else {
    document.getElementById("cooMouse").value = "mode "+mode;
  }
}

function selectedUnitDP(selectobj){
  unit = selectobj.selectedIndex;
  if (unit==0){
    document.getElementById("cooMouse").value = "km - mt";
  } else if (unit==1){
    document.getElementById("cooMouse").value = "mi - ft";
  } else if (unit==2){
    document.getElementById("cooMouse").value = "nmi";
  } else {
    document.getElementById("cooMouse").value = "unit "+mode;
  }
}

function getDistanceDP(polyline){
  var d = polyline.getLength();
  var mi  = 1.609344;
  var ya  = 0.9144;
  var ft  = 0.3048;
  var nmi = 1.853184;
  d = d.toFixed(1);
  if (d > 1000){
    d = (d / 1000).toFixed(3);
    if (unit == 1) {
      d = (d / mi).toFixed(3) + " mi";
    } else if (unit == 2){
      d = (d / nmi).toFixed(3) + " nmi";
    } else {
      d = d + " km";
    }
  } else {
    if (unit == 1) {
      d = (d / ft).toFixed(1) + " ft";
    } else if (unit == 2){
      d = (d / 1000 / nmi).toFixed(3) + " nmi";
    } else {
      d = d + " m";
    }
  }
  d = "Length: " + d + getBearingDP()+ " | zoom: " + map.getZoom();
  return d;
}

function getBearingDP() {
  var last = lstPoints.length-1;
  if(last > 0){
    var lat1 = lstPoints[last].lat();
    var lon1 = lstPoints[last].lng();
    var lat2 = pointA.lat();
    var lon2 = pointA.lng();
    if (mode==2 || mode==3){
      lat2 = lstPoints[last-1].lat();
      lon2 = lstPoints[last-1].lng();
    }
    lat1 = lat1 * Math.PI / 180;
    lat2 = lat2 * Math.PI / 180;
    var dLon = (lon2-lon1) * Math.PI / 180;
    var y = Math.sin(dLon) * Math.cos(lat2);
    var x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
    var b = Math.atan2(y, x) * 180 / Math.PI;
    b = b + 180;
    b = b%360;
    b = b.toFixed(2);
    return " | Dir: " + b + "°";
  } else {
    return " ! ";
  }
}

function getAreaDP(polygon, polylineA){
  var mi  = 1.609344;
  var ft  = 0.3048;
  var nmi = 1.853184;
  var a = polygon.getArea();
  if (a > 100000){
    a = (a / 1000000).toFixed(3); //km2
    if (unit == 1) {
      a = (a / mi / mi).toFixed(3) + " mi2";
    } else if (unit == 2){
      a = (a / nmi / nmi).toFixed(3) + " nmi2";
    } else {
      a = a + " km2";
    }
  } else {
    a = a.toFixed(1);
    if (unit == 1) {
      a = (a / ft / ft).toFixed(1) + " ft2";
    } else if (unit == 2){
      a = (a / 1000000 / nmi / nmi).toFixed(3) + " nmi2";
    } else {
      a = a + " m2";
    }
  }
  return "Area: " + a + " | " + getDistanceDP(polylineA);
}

function createContextMenuDP(map){
  contextmenu = document.createElement("div");
  contextmenu.style.visibility="hidden";
  contextmenu.style.background="#D4FFD4";
  contextmenu.style.border="1px solid #8888FF";

  contextmenu.innerHTML =
    '<a href="javascript:saveAsDefaultDP()"><div class="context">&nbsp;&nbsp;Save as default&nbsp;&nbsp;</div></a>'
  + '<a href="javascript:zoomInHereDP()"><div class="context">&nbsp;&nbsp;Zoom in here&nbsp;&nbsp;</div></a>'
  + '<a href="javascript:zoomOutHereDP()"><div class="context">&nbsp;&nbsp;Zoom out here&nbsp;&nbsp;</div></a>'
  + '<a href="javascript:clearMarkerDP()"><div class="context">&nbsp;&nbsp;clear Marker&nbsp;&nbsp;</div></a>'
  + '<a href="javascript:clearLastMarkerDP()"><div class="context">&nbsp;&nbsp;clear last Marker&nbsp;&nbsp;</div></a>'
  + '<a href="javascript:setModePointDP(0)"><div class="context">&nbsp;&nbsp;mode: Point&nbsp;&nbsp;</div></a>'
  + '<a href="javascript:setModePointDP(1)"><div class="context">&nbsp;&nbsp;mode: Distance&nbsp;&nbsp;</div></a>'
  + '<a href="javascript:setModePointDP(2)"><div class="context">&nbsp;&nbsp;mode: Polyline&nbsp;&nbsp;</div></a>'
  + '<a href="javascript:setModePointDP(3)"><div class="context">&nbsp;&nbsp;mode: Area&nbsp;&nbsp;</div></a>';

  map.getContainer().appendChild(contextmenu);
  GEvent.addListener(map,"singlerightclick",function(pixel,tile){
    clickedPixel = pixel;
    var x=pixel.x;
    var y=pixel.y;
    if (x > map.getSize().width - 120){
      x = map.getSize().width - 120
    }
    if (y > map.getSize().height - 100){
      y = map.getSize().height - 100
    }
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));
    pos.apply(contextmenu);
    contextmenu.style.visibility = "visible";
  });
  GEvent.addListener(map, "click", function(){
    contextmenu.style.visibility="hidden";
  });
}

function saveAsDefaultDP(){
  document.pointA.submit();
  contextmenu.style.visibility="hidden";
}

function setModePointDP(mode){
  document.getElementById('mapMode').value = mode;
  selectedModeDP(document.getElementById('mapMode'));
  clearMarkerDP();
  contextmenu.style.visibility="hidden";
}

function clearMarkerDP(){
  clearAndRepaintMarkerDP();
  contextmenu.style.visibility="hidden";
}

function clearLastMarkerDP(){
  lstPoints.pop();
  repaintMarkerDP(lstPoints[lstPoints.length-1]);
  contextmenu.style.visibility="hidden";
}

function saveAsPointBDP(){
  var latX = point.lat().toFixed(5);
  var lonX = point.lng().toFixed(5);
  var pntX = latX+" , "+lonX;
  document.getElementById('pointB').value = pntX;
  document.pointA.submit();
  createCustomMarkerDP(pointB, "B");
  contextmenu.style.visibility="hidden";
}


function zoomInHereDP(){
  var point = map.fromContainerPixelToLatLng(clickedPixel)
  map.zoomIn(point,true);
  contextmenu.style.visibility="hidden";
}

function zoomOutHereDP(){
  var point = map.fromContainerPixelToLatLng(clickedPixel)
  map.setCenter(point,map.getZoom()-1);
  contextmenu.style.visibility="hidden";
}

function zoomInDP(){
  map.zoomIn();
  contextmenu.style.visibility="hidden";
}

function zoomOutDP(){
  map.zoomOut();
  contextmenu.style.visibility="hidden";
}

function centreMapHereDP(){
  var point = map.fromContainerPixelToLatLng(clickedPixel)
  map.setCenter(point);
  contextmenu.style.visibility="hidden";
}
