function mapaZona(latDec, lonDec) {
   fromId=String(((location.search.substring(1, location.search.length).split('&').slice(3))[0].split('='))[1]);

   var map = new GMap2(document.getElementById("map"));
   fromLatLng= new GLatLng(latDec,lonDec);
   pRef= fromLatLng;

   map.setCenter(fromLatLng, 8);
   map.setMapType(G_HYBRID_MAP);
   map.addControl(new GScaleControl());
   map.addControl(new GLargeMapControl());
   map.addControl(new GMapTypeControl());
   map.addMapType(G_PHYSICAL_MAP);
   map.enableScrollWheelZoom();

   var icoBase = new GIcon();
   icoBase.shadow = "/images/navegacion/google/icoSombra.png";
   icoBase.iconSize = new GSize(39, 37);
   icoBase.shadowSize = new GSize(76, 37);
   icoBase.iconAnchor = new GPoint(19, 37);
   icoBase.infoWindowAnchor = new GPoint(19, 37);

   icoAD = new GIcon(icoBase);
   icoAD.image = "/images/navegacion/google/icoAD.png";
   icoADV = new GIcon(icoBase);
   icoADV.image = "/images/navegacion/google/icoADV.png";
   icoULM = new GIcon(icoBase);
   icoULM.image = "/images/navegacion/google/icoULM.png";
   icoULMV = new GIcon(icoBase);
   icoULMV.image = "/images/navegacion/google/icoULMV.png";
   icoAF = new GIcon(icoBase);
   icoAF.image = "/images/navegacion/google/icoPF.png";
   icoAFV = new GIcon(icoBase);
   icoAFV.image = "/images/navegacion/google/icoPFV.png";
   icoZA = new GIcon(icoBase);
   icoZA.image = "/images/navegacion/google/icoZA.png";
   icoZAV = new GIcon(icoBase);
   icoZAV.image = "/images/navegacion/google/icoZAV.png";
   icoAP = new GIcon(icoBase);
   icoAP.image = "/images/navegacion/google/icoAP.png";
   icoAPV = new GIcon(icoBase);
   icoAPV.image = "/images/navegacion/google/icoAPV.png";
   icoMIL = new GIcon(icoBase);
   icoMIL.image = "/images/navegacion/google/icoMIL.png";
   icoMILV = new GIcon(icoBase);
   icoMILV.image = "/images/navegacion/google/icoMIL.png";

   gmarkers= [];
   var i = 0;

   tooltipSel= document.createElement("div");
   tooltipSel.id = "tooltipSel";
   map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltipSel);
   pintaZonas(map, "sel", "zona");

   tooltipNuevo= document.createElement("div");
   tooltipNuevo.id = "tooltipNuevo";
   map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltipNuevo);
   pintaZonas(map, "nuevos", "zona");

   GEvent.addListener(map, "moveend", function() {
      var centro= map.getCenter();
      if (centro.distanceFrom(pRef)/1000 > 70) {
         pRef= centro;
         var cuantos= gmarkers.length-1;
         for (var i= cuantos; i> 0; i--) {
            map.removeOverlay(gmarkers[i]);
         };
         gmarkers.splice(1, gmarkers.length-1);
         pintaZonas(map, "nuevos", "zona");
      }
   });

   GEvent.addListener(map, "zoomend", function() {
      showTooltip(map, gmarkers[0])
   });
}

function mapaPunto(lonDec, latDec) {
   var txt="Estás usando Microsoft Internet Explorer.\n\nLo siento pero, por un defecto del navegador, esta página puede bloquear o cerrar el programa.\n\nSe puede atenuar el problema cambiando la configuración de Internet.\nEn el Panel de Control > Opciones de Internet > pestaña General > botón Configuración > bajo \"Comprobar si hay nuevas versiones de las páginas guarnadas:\" seleccionar \"Cada vez que se inicia Internet Explorer\"\nÉsto solo retrasa la aparición del problema.\n\nPuedes ver la página sin problemas con otro navegador como Mozilla o Firefox.";
   var agent = navigator.userAgent.toLowerCase();
   if (agent.indexOf("msie") != -1) {alert(txt);}
   fromId=String(((location.search.substring(1, location.search.length).split('&').slice(3))[0].split('='))[1]);

   var map = new GMap2(document.getElementById("map"));
   fromLatLng= new GLatLng(latDec,lonDec);
   pRef= fromLatLng;

   map.setCenter(fromLatLng, 13);
   map.setMapType(G_HYBRID_MAP);
   map.addControl(new GScaleControl());
   map.addControl(new GLargeMapControl());

   var icoBase = new GIcon();
   icoBase.shadow = "/images/navegacion/google/icoSombra.png";
   icoBase.iconSize = new GSize(39, 37);
   icoBase.shadowSize = new GSize(76, 37);
   icoBase.iconAnchor = new GPoint(19, 37);
   icoBase.infoWindowAnchor = new GPoint(19, 37);

   icoAD = new GIcon(icoBase);
   icoAD.image = "/images/navegacion/google/icoAD.png";
   icoADV = new GIcon(icoBase);
   icoADV.image = "/images/navegacion/google/icoADV.png";
   icoULM = new GIcon(icoBase);
   icoULM.image = "/images/navegacion/google/icoULM.png";
   icoULMV = new GIcon(icoBase);
   icoULMV.image = "/images/navegacion/google/icoULMV.png";
   icoAF = new GIcon(icoBase);
   icoAF.image = "/images/navegacion/google/icoPF.png";
   icoAFV = new GIcon(icoBase);
   icoAFV.image = "/images/navegacion/google/icoPFV.png";
   icoZA = new GIcon(icoBase);
   icoZA.image = "/images/navegacion/google/icoZA.png";
   icoZAV = new GIcon(icoBase);
   icoZAV.image = "/images/navegacion/google/icoZAV.png";
   icoAP = new GIcon(icoBase);
   icoAP.image = "/images/navegacion/google/icoAP.png";
   icoAPV = new GIcon(icoBase);
   icoAPV.image = "/images/navegacion/google/icoAPV.png";
   icoMIL = new GIcon(icoBase);
   icoMIL.image = "/images/navegacion/google/icoMIL.png";
   icoMILV = new GIcon(icoBase);
   icoMILV.image = "/images/navegacion/google/icoMIL.png";

   gmarkers= [];
   var i = 0;

   tooltipSel= document.createElement("div");
   tooltipSel.id = "tooltipSel";
   map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltipSel);
   pintaZonas(map, "sel", "punto");

   tooltipNuevo= document.createElement("div");
   tooltipNuevo.id = "tooltipNuevo";
   map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltipNuevo);
   pintaZonas(map, "nuevos", "punto");

   circ= drawCircle(lonDec,latDec);
   map.addOverlay(circ);

   GEvent.addListener(map, "moveend", function() {
      var centro= map.getCenter();
      if (centro.distanceFrom(pRef)/1000 > 105) {
         pRef= centro;
         var cuantos= gmarkers.length-1;
         for (var i= cuantos; i> 0; i--) {
            map.removeOverlay(gmarkers[i]);
         };
         gmarkers.splice(1, gmarkers.length-1);
         pintaZonas(map, "nuevos");
      }
   });
}

function pintaZonas(map, tipoM, tipoP) {
   var s= pRef.lat() - 1;
   var n= pRef.lat() + 1;
   var w= pRef.lng() - 1.3;
   var e= pRef.lng() + 1.4;

   if (tipoM== "sel") {
      var xmlSourceURI= "/scripts/zonaSel.xml.php?punto=" + fromId;
   } else {
      var xmlSourceURI= "/scripts/zonaResto.xml.php?punto=" + fromId + "&s="+s + "&n="+n + "&w="+w + "&e="+e;
   }

   GDownloadUrl(xmlSourceURI, function(data, responseCode) {
      var xmlDoc= GXml.parse(data);
      zonas= xmlDoc.documentElement.getElementsByTagName("zona");
      if (tipoM== "nuevos") {
         var z= 1
      } else {
         var z= 0
      };
      for (iMarkers = z; iMarkers <= zonas.length; iMarkers++) {
         createMarker(map, iMarkers, tipoM, tipoP)
      };
   });
}

function createMarker(map, iMarkers, tipoM, tipoP) {
   var iZona = 0;
   if (tipoM == "nuevos") {iZona = iMarkers - 1};
   var latDec = zonas[iZona].getAttribute("latDec");
   var lonDec = zonas[iZona].getAttribute("lonDec");
   var dbID= zonas[iZona].getAttribute("id");

   var puntoMarker= new GLatLng(latDec,lonDec);
   var tipoAD = zonas[iZona].getAttribute("tipo");
   var veleros = zonas[iZona].getAttribute("veleros");
   switch (tipoAD) {
      case "Aeródromo":
         var strIcono = "icoAD";
         break;
      case "ULM":
         var strIcono = "icoULM";
         break;
      case "Pista forestal":
         var strIcono = "icoAF";
         break;
      case "Zona aterrizable":
         var strIcono = "icoZA";
         break;
      case "Aeropuerto":
         var strIcono = "icoAP";
         break;
      case "Militar":
         var strIcono = "icoMIL";
         break;
   }
   if (veleros == 1){strIcono = strIcono + "V";}
   var icono = new GIcon(eval(strIcono));

   var marker= new GMarker(puntoMarker, icono);
   marker.markerindex= iZona;
   marker.db_id= dbID;
   marker.pos= puntoMarker;
   marker.tipo= tipoM;
   marker.nombre= zonas[iZona].getAttribute("nombre");
   if (tipoM == "nuevos") {
      (tipoP == "zona")? marker.html= '<div id=\"divnuevos\", style=\"background-color: #f2efe9; padding: 4px; font-size: 0.7em;\"><nobr>A '+marker.nombre+':</nobr></div>' : marker.html= '<div id=\"divnuevos\", style=\"background-color: #f2efe9; padding: 4px; font-size: 0.7em;\"><nobr>Desde '+marker.nombre+':</nobr></div>';
      marker.txt= marker.html;
   } else {
      marker.html= '<div id=\"divsel\", style=\"background-color: #f2efe9; padding: 2px; font-size: 1em;\"><nobr>'+zonas[iZona].getAttribute("nombre")+'</nobr></div>';
      marker.txt= marker.html;
   }

   if (tipoM== "nuevos") {
      GEvent.addListener(marker,"mouseover", function() {
         (tipoP== "zona")? txtNuevo= distAz(iMarkers, marker.pos, "to") : txtNuevo= distAz(iMarkers, marker.pos, "from");
         marker.txt= txtNuevo;
         showTooltip(map, marker);
      });

      GEvent.addListener(marker,"mouseout", function() {
         tooltip.style.visibility="hidden"
         marker.txt= marker.html;
      });

      if (tipoP== "zona") {
         GEvent.addListener(marker, "dblclick", function(marker) {
            tooltip.style.visibility="hidden"
            fromId= this.db_id;
            fromLatLng= this.pos;
   //         for (var i= 0; i< gmarkers.length; i++) {
            for (var i= gmarkers.length-1; i>=0; i--) {
               map.removeOverlay(gmarkers[i]);
            };
            gmarkers= [];

            txFile= "/scripts/zonaDatosZona.xml.php?punto="+fromId;
            GDownloadUrl(txFile, function(data, responseCode) {
               var xmlDoc= GXml.parse(data);
               datos= xmlDoc.documentElement.getElementsByTagName("dato");
               for (var i = 0; i < datos.length; i++) {
                  var nombreDato= datos[i].attributes[0].name+"Origen";
                  var valorDato= datos[i].attributes[0].value;
                  document.getElementById(nombreDato).innerHTML=valorDato;
               };
            document.getElementById('tDestino').style.display='none';
            });

            pintaZonas(map, "sel", "zona");
            map.panTo(fromLatLng);
            if (fromLatLng.distanceFrom(pRef)/1000 < 70) {pintaZonas(map, "nuevos", "zona");};
         });

         GEvent.addListener(marker, "click", function(marker) {
            var id= this.db_id;
            txFile= "/scripts/zonaDatosZona.xml.php?punto="+id;
            GDownloadUrl(txFile, function(data, responseCode) {
               var xmlDoc= GXml.parse(data);
               datos= xmlDoc.documentElement.getElementsByTagName("dato");
                  for (var j = 0; j < datos.length; j++) {
                     var nombreDato= datos[j].attributes[0].name+"Destino";
                     var valorDato= datos[j].attributes[0].value;
                     document.getElementById(nombreDato).innerHTML=valorDato;
                  };
            });
            document.getElementById('tDestino').style.display='block';
         });
      }
   } else {
      if (tipoP== "zona") {showTooltip(map, marker);}
   };
   gmarkers[iMarkers]= marker;
   if ((tipoP== "zona") || (tipoM== "nuevos")) {map.addOverlay(marker);}
}

function showTooltip(map, marker) {
   if (marker.tipo== "sel") {
      tooltip= tooltipSel;
      var height=26
   } else {
      tooltip= tooltipNuevo;
      var height=51;
   }
   tooltip.innerHTML = marker.txt;
   var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
   var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
   var anchor=marker.getIcon().iconAnchor;
   var width=0;
   var offst= new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)
   var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, offst); 
   pos.apply(tooltip);
   tooltip.style.visibility="visible";
}

function distAz(iMarkers, toLatLng, dir) {
   if (dir== "from") {
      var dir= bearing(toLatLng, fromLatLng);
   } else {
      var dir= bearing(fromLatLng, toLatLng);
   }
   var distancia= (toLatLng.distanceFrom(fromLatLng)/1000).toFixed(1);
   var txt= gmarkers[iMarkers].txt;
   var re = /<\/nobr>/g;
   var txtMas= "</nobr><br><nobr>"+dir+"º, "+distancia+" Km.</nobr>";
   var txtNuevo= txt.replace(re, txtMas);

   return txtNuevo;
}

function bearing(from, to) {
  var degreesPerRadian = 180.0 / Math.PI;
  var radiansPerDegree = Math.PI / 180.0;

  var lat1 = from.y * radiansPerDegree;
  var lon1 = from.x * radiansPerDegree;
  var lat2 = to.y * radiansPerDegree;
  var lon2 = to.x * radiansPerDegree;

  var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ), Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
  if ( angle < 0.0 )
    angle += Math.PI * 2.0;

  angle = angle * degreesPerRadian;
  angle = angle.toFixed(1);
  return Math.round(angle);
}

function drawCircle(lng,lat) {
   var Cradius = 3;
   var Ccolor = '#00ff00';
   var Cwidth = 3;
   var d2r = Math.PI/180;
   var r2d = 180/Math.PI;
   var Clat = (Cradius/6378)*r2d;

   var Clng = Clat/Math.cos(lat*d2r);
   var Cpoints = [];

   for (var i=0; i < 33; i++) {
      var theta = Math.PI * (i/16);
      Cx = lng + (Clng * Math.cos(theta));
      Cy = lat + (Clat * Math.sin(theta));
      Cpoints.push(new GPoint(Cx,Cy));
   };

   var circ= new GPolyline(Cpoints,Ccolor,Cwidth,1);
   return circ;
}
