// ******* ********* ********* ********* ********* ********* ********* *********

var map;
/*
var gtl;
var gmt;
*/


var MAGIC_NUMBER=6356752.3142;
var WGS84_SEMI_MAJOR_AXIS = 6378137.0;
var WGS84_ECCENTRICITY = 0.0818191913108718138;

var DEG2RAD=0.0174532922519943;
var PI=3.14159267;

//Default image format, used if none is specified
var FORMAT_DEFAULT="image/png";

//Google Maps Zoom level at which we switch from Mercator to Lat/Long.
var MERC_ZOOM_DEFAULT = 15;
function dd2MercMetersLng(p_lng) {
	return WGS84_SEMI_MAJOR_AXIS * (p_lng*DEG2RAD);
}

function dd2MercMetersLat(p_lat) {
	var lat_rad = p_lat * DEG2RAD;
	return WGS84_SEMI_MAJOR_AXIS * Math.log(Math.tan((lat_rad + PI / 2) / 2) * Math.pow( ((1 - WGS84_ECCENTRICITY * Math.sin(lat_rad)) / (1 + WGS84_ECCENTRICITY * Math.sin(lat_rad))), (WGS84_ECCENTRICITY/2)));
}

function load(iniLat, iniLng) {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    // map.addControl(new GSmallMapControl());
    map.addControl(new GLargeMapControl());
    // map.setMapType(_HYBRID_TYPE);
//    map.addControl(new GOverviewMapControl());
    centrarMapaInicial(iniLat, iniLng);
    // Bounds CyL N: 43.17, E: -1.79, S: 40.06, W: -7.02
    var limites = definirLimites(43.17, 40.06, -1.79, -7.02);
/*
gtl = new GTileLayer(new GCopyrightCollection(""), 7, 14);
gmt = new GMapType(mytilelayers, G_SATELLITE_MAP.getProjection(), "Custom",
 {maxResolution:14, minResolution:7, errorMessage:_mMapError});
*/

    // ============================================================
      // == We now have to write our own getTileUrl function ========

      
      
      
      CustomGetTileUrl=function(a,b, p3){
        var lULP = new GPoint(a.x*256,(a.y+1)*256);
	      var lLRP = new GPoint((a.x+1)*256,a.y*256);
	      var lUL = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lULP,b,c);
	      var lLR = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lLRP,b,c);
	var lBbox=dd2MercMetersLng(lUL.x)+","+dd2MercMetersLat(lUL.y)+","+dd2MercMetersLng(lLR.x)+","+dd2MercMetersLat(lLR.y);
//        alert ("a: " + a + ", b: " + b + ",p3: " + p3 + "\nlbox: " + lBbox);

var northWest = calc_utm(lUL.y, lUL.x);
var southEast = calc_utm(lLR.y, lLR.x);

        var c=Math.pow(2,b);
        var d=a.x;
        var e=a.y;
        var f="t";
          for(var g=0;g<b;g++){
            c=c/2;
            if(e<c){
              if(d<c){
                f+="q"
              }
              else{
                f+="r";
                d-=c
              }
            }
          else{
            if(d<c){
              f+="t";
              e-=c
            }
            else{
              f+="s";
              d-=c;
              e-=c
            }
          }
        }

        urlServidor = "http://217.71.16.147/imageserver/aspimagedispatcher.aspx";
        urlServicio = "?function=getutmbitmap&Name=ORTOFOTOS&Tpc=0&Width=256&Height=256";
        var x1 = northWest.E;
        var y1 = northWest.N;
        var x2 = southEast.E;
        var y2 = southEast.N;
//        urlParams = "&x1=" + x1 + "&y1=" + y1 + "&x2=" + x2 + "&y2=" + y2 + "&Zone=" + southEast.Z;

// Correccion para obtener areas menos deformadas (deltaX != deltaY) (aunque sigpac devuelve fotos mal alineadas!)

        var cX = (x1 + x2) / 2;
        var cY = (y1 + y2) / 2;
        var deltaX = x2 - x1;
        var deltaY = y2 - y1;
        var delta = (deltaX + deltaY) / 2;
        var ratio = deltaX / deltaY;

        var x1_ = cX - delta / 2;
        var y1_ = cY - delta / 2;
        var x2_ = x1 + delta;
        var y2_ = y1 + delta;
        urlParams = "&x1=" + x1_ + "&y1=" + y1_ + "&x2=" + x2_ + "&y2=" + y2_ + "&Zone=" + southEast.Z;

        return urlServidor + urlServicio + urlParams;
      }

      // ============================================================
      // ====== Create a single layer "Old OSS" custom maptype ====== 
      //
      // == Create the GTileLayer ==
      var tilelayers = [new GTileLayer(new GCopyrightCollection("Mapa: SIGPAC"),13,17)];
      tilelayers[0].getTileUrl = CustomGetTileUrl;
      tilelayers[0].getCopyright = function(a,b) {
        return {prefix:"Mapa: ", copyrightTexts:["SIGPAC CyL"]};
      }
      
      // == Create the GMapType, copying most things from G_SATELLITE_MAP ==
      var custommap = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), "SIGPAC",{errorMessage:"Error obteniendo imagen de SIGPAC"});
      
      // == Add the maptype to the map ==
      map.addMapType(custommap);


      // ============================================================
      // ====== Create a two layer  "OSS Hybrid" layer ==============

      // === It has two layers one is the "Old OSS" map and the other is the top layer from G_HYBRID_MAP
      var htilelayers = [
         tilelayers[0],                  // a reference to the tile layer from the first custom map
         G_HYBRID_MAP.getTileLayers()[1] // a reference to the upper tile layer fo the hybrid map
      ];
      
      var custommap2 = new GMapType(htilelayers, G_SATELLITE_MAP.getProjection(), "SIGPAC+", {maxResolution:17,minResolution:13,errorMessage:"Error obteniendo imagen de SIGPAC"});

      // === Add it to the list of map types ===
      map.addMapType(custommap2);



    map.addControl(new GMapTypeControl());


    // Bounds CyL N: 43.17, W: -7.02, E: -1.79, S: 40.06
    GEvent.addListener(map, "dragend", function() {
      var bounds = map.getBounds();
      var centro = bounds.getCenter();
      // cadInfo = "Centro.long: " + centro.lng() + " Centro.lat: " + centro.lat();
      // document.getElementById("mensaje").innerHTML = "Final de arrastre " + cadInfo + " " + centro.toString();
      var latitud = Math.max(Math.min(limites.getNorthEast().lat(), centro.lat()), limites.getSouthWest().lat());
      var longitud = Math.max(Math.min(limites.getNorthEast().lng(), centro.lng()), limites.getSouthWest().lng());
      var centroLimitado = new GLatLng(latitud, longitud);
      map.panTo(centroLimitado);
    });
    // mostrarOverlay();
  }
}

// ******* ********* ********* ********* ********* ********* ********* *********

function iniciarPunto(lat, lng, descr, id) {
  var marcador = new GMarker(new GLatLng(lat, lng));
  GEvent.addListener(marcador, "click",
    function() {
      var url = 'mostrarInfo.php?punto=' + id;
      marcador.openInfoWindowHtml("<a href='" + url + "'>" + descr + "</a>");
    }
  );
  map.addOverlay(marcador);
}

// ******* ********* ********* ********* ********* ********* ********* *********

// Se centra aproximadamente sobre Palencia
function centrarMapaInicial(iniLat, iniLng) {
  // map.setCenter(new GLatLng(42.701109, -2.957468), 14, G_HYBRID_MAP); // Miranda de Ebro
  // map.setCenter(new GLatLng(42.939585, -6.318447), 14, G_HYBRID_MAP); // Villablino
  map.setCenter(new GLatLng(iniLat, iniLng), 14, G_HYBRID_MAP);
}

// ******* ********* ********* ********* ********* ********* ********* *********

function definirLimites(N, S, E, W) {
  var sw = new GLatLng(S, W);
  var ne = new GLatLng(N, E);
  // GLatLngBounds(sw?,  ne?)
  var bounds = new GLatLngBounds(sw, ne);
  return bounds;
}

// ******* ********* ********* ********* ********* ********* ********* *********
