var lstPoints = [];
var contextmenu;
var mode = 1;
var unit = 0;
var pointDrag;
var point = null;
var formE;


function initializeDP() {
  if ( GBrowserIsCompatible ) {
    map = new GMap2(document.getElementById("map"));
    geocoder = new GClientGeocoder();
    map.enableDoubleClickZoom();
    //map.enableScrollWheelZoom();
    map.addControl(new GMapTypeControl());
    map.addControl(new GLargeMapControl3D());
    createContextMenuDP(map);
    map.addMapType(G_PHYSICAL_MAP);
    map.setMapType(G_HYBRID_MAP);
    map.enableDragging();
    pointA = new GLatLng(Number(latSes), Number(lonSes));
		lstPoints.push(pointA);
	  if(Number(zoom) < 5){
	     zoom=14;
	  }
    map.setCenter(pointA, Number(zoom));
    map.setZoom( Number(zoom) );
    formE = document.forms["formE"];
    formE.coo.value = pointSes;
    formE.pmAddr.value = adrSes;
    selectedModeDP(formE.modeMap);
    createCustomMarkerDP(pointA, 'A');
    GEvent.addListener(map, "click", function(overlay, point) { clickedDP(point); });
    GEvent.addListener(map, "mousemove", function(point) { mousemoveDP(point); });
    GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) { onZoomDP(oldLevel, newLevel); }); 
  }
}

function showLocationDP(address) {
  if (geocoder) {
    geocoder.getLatLng( address,
      function(point) {
        if (!point) {
          alert(address + " not found");
        } else {
          pointA = point;
          setPointDP(point);
          map.setCenter(point, 16);
          document.formE.submit();
        }
      });
  };
	return false;
}

function setPointDP(point) {
	formE = document.forms["formE"];
  var adr = "";
  if (geocoder) {
    geocoder.getLocations((new GLatLng(point.y, point.x)),
      function(response) {
        if (!response || response.Status.code != 200) {
          formE.coo.value = "address not found :-) ";
          formE.point.value = "not found :-) ";
        } else {
          place = response.Placemark[0];
          adrSes = place.address;
          formE.pmAddr.value = place.address;
          formE.pmCoun.value = place.AddressDetails.Country.CountryNameCode;
          formE.address2.value = place.address;
//          formE.pmAbm1.value = place.AddressDetails.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;
//          formE.pmLoca.value = place.AddressDetails.AdministrativeArea.Locality.LocalityName;
//          formE.pmAlti.value = place.Point.coordinates[0];
//alert(" setPointDP: " + point + " - formE.pmAddr: "+formE.pmAddr.value);
				}
      });
  };
	formE.point.value = point.lat().toFixed(5)+" , "+point.lng().toFixed(5);
  formE.coo.value   = "lat,lng: "+formE.point.value;
  formE.zoom.value  = map.getZoom();
  return adr + point;
}

function getCooHtmlDP(point){
  var out = "<table cellpadding='2' cellspacing='0' border='0' >";
//  out += "<tr><td colspan='3'>" + adrSes + "</td></tr>";
  out += "<tr><td>" + "Latitude " + "</td><td>: " + point.lat().toFixed(6) + "</td><td>" + getCooDegree(point.lat().toFixed(6), true)  + "</td></tr>";
  out += "<tr><td>" + "Longitude" + "</td><td>: " + point.lng().toFixed(6) + "</td><td>" + getCooDegree(point.lng().toFixed(6), false) + "</td></tr>";
  out += "<tr><td colspan='3'>Drag the marker or click to get new point.</td></tr>";
  if(isEqualPoints(pointA, point)){
  	out += "<tr><td colspan='3'><a  href='http://www.sunearthtools.com/dp/tools/conversion.php"+lang+"' title='Coordinates'/>Other format</a></td></tr>";
  }
  out += "</table>";
  return out;
}

function getSunHtmlDP(){
  var out = "<table cellpadding='2' cellspacing='0' border='0' >";
	out += "<tr><td>" + date + "</td><td>|  time </td><td>| azimuth </td></tr>";
	out += "<tr><td>Rise:</td><td>| " + timeRise + "</td><td>| " + azmRise + "°</td></tr>";
	out += "<tr><td>Noon:</td><td>| " + timeNoon + "</td><td>| " + azmNoon + "°</td></tr>";
	out += "<tr><td>Set :</td><td>| " + timeSet  + "</td><td>| " + azmSet  + "°</td></tr>";
	out += "<tr><td colspan='3'><a  href='http://www.sunearthtools.com/dp/tools/pos_sun.php"+lang+"' title='Sun diagrams'/>View sun diagram</a></td></tr>";
  return out;
}

function openInfoMarkerDP(marker){
	if(marker){
		var point = marker.getPoint();
		var tabCoo = new GInfoWindowTab("Coordinate", getCooHtmlDP(point));
		var tabSun = null;
		
	  if(isEqualPoints(pointA, point)){
	  	tabSun = new GInfoWindowTab("Sun", getSunHtmlDP());
	//		if(mode == 4){
	//			marker.openInfoWindowTabsHtml([tabCoo, tabSun]).selectTab(1);
	//		} else {
				marker.openInfoWindowTabsHtml([tabCoo, tabSun]);
	//		}
		} else {
			marker.openInfoWindowTabsHtml([tabCoo]);
		}
	}
}

function clickedDP(point) {
  if (point) {
    geocoder.getLocations(point, function(response) {
      if(!response || response.Status.code != 200) {
        alert("reverse geocoder failed to find an address for: " + point);
      } else if(mode == 4){
          pointA = point;
          setPointDP(point);
          document.formE.submit();
      } else {
        lstPoints.push(new GLatLng(point.y, point.x));
        repaintMarkerDP(point);
      };
    });
  };
}

function onZoomDP(oldLevel, newLevel) {
	formE.zoom.value  = newLevel;
}

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(isEqualPoints(pointT, pointDrag)){
      idD = i;
      break;
    }
  }
  lstPoints.splice(idD, 1, new GLatLng(point.y, point.x));
  if(isEqualPoints(pointA, pointDrag)) {
    setPointDP(point);
    document.formE.submit();
  } else {
  	repaintMarkerDP(point);
  }
}

function mousemoveDP(point) {
  var mode = document.getElementById('modeMap').selectedIndex;
  if (point && mode==0) {
    document.getElementById("cooMouse").value = point.toUrlValue(5);
  }
}

function createCustomMarkerDP(point, letter) {
//alert(" createCustomMarkerDP: " + point+" :"+letter);  
  formE = document.forms["formE"];
  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){
    marker = new GMarker(point, markerOption);
  } else {
    marker = new GMarker(point);
  }
  map.closeInfoWindow();
  map.addOverlay(marker);
  if((mode == 2 || mode == 3) && letter != 'A'){
    marker.closeInfoWindow();
  } else if(mode == 4 && letter == 'A'){
		getSunRaysCoo();
	  openInfoMarkerDP(marker);
  } else {
	  openInfoMarkerDP(marker);
  }
  GEvent.addListener(marker, "click", function() {
    openInfoMarkerDP(marker);
  });
  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() {
    formE.coo.value = marker.getPoint().lat().toFixed(5)+" , "+marker.getPoint().lng().toFixed(5);
  });
  return marker;
}

function clearAndRepaintMarkerDP(point) {
//alert(" clearAndRepaintMarkerDP: " + point);  
	lstPoints = [];
  lstPoints.push(new GLatLng(pointA.y, pointA.x));
	if(!isEqualPoints(pointA, point)){
		point.lat() == point.lat().toFixed(5);
		point.lng() == point.lng().toFixed(5);
		lstPoints.push(new GLatLng(point.y, point.x));
	}
  repaintMarkerDP(point);
}

function repaintMarkerDP(point){
//alert(" repaintMarkerDP: " + point+" A:"+pointA);  
  var point2 = null;
  var marker = null;
  var marker2 = null;
  map.clearOverlays();
  if(!point){
  	return;
  }
  if(point && lstPoints.length > 1){
  	if(mode == 1){
	    lstPoints = [];
	    lstPoints.push(new GLatLng(pointA.y, pointA.x));
	    lstPoints.push(new GLatLng(point.y, point.x));
    } else if (mode == 4){
	    lstPoints = [];
	    lstPoints.push(new GLatLng(pointA.y, pointA.x));
	  }
  }
  var last = lstPoints.length-1;
  var polyline = new GPolyline(lstPoints, "#D4FFD4", 3,1);
  createCustomMarkerDP(lstPoints[0], "A");
  for (var i = 1; i <= last; ++i) {
    point2 = lstPoints[i];
    if(mode == 0 || mode == 1){
      if(i == last){
        marker2 = createCustomMarkerDP(point2, "P");
      } else {
        marker2 = createCustomMarkerDP(point2, "D");
      }
    } else if(mode == 2){
      if(i == last){
        marker2 = createCustomMarkerDP(point2, "D");
      } else {
        marker2 = createCustomMarkerDP(point2, "P");
      }
    } else if(mode == 3){
      if(i==last){
        marker2 = createCustomMarkerDP(point2, "S2");
      } else {
        marker2 = createCustomMarkerDP(point2, "S");
      }
    }
    if(isEqualPoints(point, point2)){
		  marker = marker2;
    }
  }
  if(mode == 1 || mode == 2){
    map.addOverlay(polyline);
    document.getElementById("cooMouse").value = getDistanceDP(polyline);
  } else 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);
  } else if(mode == 4){
  	getSunRaysCoo();
  }
  if(marker){
  	openInfoMarkerDP(marker);
  }
}

function isEqualPoints(point1, point2){
  if(point1 && point2 && 
  	 point1.lat().toFixed(5) == point2.lat().toFixed(5) &&
     point1.lng().toFixed(5) == point2.lng().toFixed(5)) {
     return true;
	}
	return false;
}

function getCooDegree(coo, isLat){
	var res = Number(coo);
	var deg = 0;
	var min = 0;
	var sec = 0;
	var dir = "N";
	if(isLat && coo < 0){
		dir = "S";
	} else if(!isLat && coo >= 0){
		dir = "E";
	} else if (!isLat && coo < 0){
		dir = "W";
	}
	deg = Math.abs(Math.floor(res));
	res = (res - Math.floor(res)) * 60;
	min = Math.floor(res);
	sec = (res - min) * 60;
  sec = sec.toFixed(3);
	res = "( " + deg + "° " + min + "' " + sec + "\" " + dir + " )";
	return res;
}

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 if (mode == 4){
    document.getElementById("cooMouse").value = "sun rays";
  } else {
    document.getElementById("cooMouse").value = "mode "+mode;
  }
  document.forms["formE"].modeMap.value = mode;
  repaintMarkerDP(pointA);
}

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 getSunRaysCoo(){
  var lstSunRaysCoo = [];
  var pointD = pointA;
  var markerR = null;
  var customIcon = new GIcon(G_DEFAULT_ICON);
  var markerOption = { icon:customIcon, draggable:false };
 
  lstSunRaysCoo.push(new GLatLng(pointA.y, pointA.x));
//alert("SunRaysCoo.length:"+arraySunRaysCoo.length+".0."+arraySunRaysCoo[0][0]+","+arraySunRaysCoo[0][1]+","+arraySunRaysCoo[0][2]);
  for (var i = 0; i < arraySunRaysCoo.length; ++i) {
		pointD = new GLatLng(Number(arraySunRaysCoo[i][1]), Number(arraySunRaysCoo[i][2]));
    lstSunRaysCoo.push(new GLatLng(pointD.y, pointD.x));
	  lstSunRaysCoo.push(new GLatLng(pointA.y, pointA.x));
    customIcon.image = "../images/dpMarkerH_" + arraySunRaysCoo[i][0] + ".png";
    customIcon.iconSize = new GSize(13,9);
	  customIcon.iconAnchor = new GPoint(0,9);
	  customIcon.shadow = "";
	 	markerR = new GMarker(pointD, markerOption);
	  map.addOverlay(markerR);
  }
  var plSunRaysCoo = new GPolyline(lstSunRaysCoo, "yellow", 1,1);
  document.getElementById("cooMouse").value = "SunRise: "+timeRise+" * "+azmRise+"° | SunSet: "+timeSet+" * "+azmSet+"° | zoom: "+map.getZoom();
  map.addOverlay(plSunRaysCoo);
}

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.formE.submit();
  contextmenu.style.visibility="hidden";
}

function setModePointDP(mode){
  document.getElementById('modeMap').value = mode;
  selectedModeDP(document.getElementById('modeMap'));
  clearMarkerDP();
  contextmenu.style.visibility="hidden";
}

function clearMarkerDP(){
  clearAndRepaintMarkerDP(point);
  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.formE.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";
}
