
// ******* ********* ********* ********* ********* ********* ********* *********

var gatewayScript = "/gateway2.php";
var pathRootIcon = "/iconos/";

var idIni;
var tipoIdIni; // 1.- poblacion, 2.- casa, 3.- establecimiento

var lm; // lista de marcadores;
var map;
var Icon_1;
var Icon_2;
var Icon_3;
// var marcador;

function load(id, tipo, latIni, lngIni, zoomIni, tipoIni) {
  if (GBrowserIsCompatible()) {
    idIni = id;
    tipoIdIni = tipo;
    var dom_map = document.getElementById("map");
    map = new GMap2(dom_map);
    lm = new ListaMarcadores();

/*
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GScaleControl());
*/
//    map.setUIToDefault();

    // Get the default GMapUIOptions.
    var uiOptions = map.getDefaultUI();
    uiOptions.controls.maptypecontrol = false;
    map.setUI(uiOptions);

    var mapControl = new GHierarchicalMapTypeControl();
    mapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Mapa", false);
    map.addControl(mapControl);

    // ====== Restricting the range of Zoom Levels =====
    // Get the list of map types      
    var mt = map.getMapTypes();
    // Overwrite the getMinimumResolution() and getMaximumResolution() methods
    for (var i=0; i<mt.length; i++) {
      mt[i].getMinimumResolution = function() {return 11;}
      // mt[i].getMaximumResolution = function() {return 17;}
    }

    centrarMapaInicial(latIni, lngIni, zoomIni, tipoIni);
    firstShow = true;

    // 1.- Municipios (Marcador estandar) 
    // pathBaseIcon = './iconos/icon_1/';
    pathBaseIcon = pathRootIcon + 'icon_1_mini/';
    Icon_1 = new GIcon();
    // icon_1_mini
    Icon_1.iconSize = new GSize(12,20);
    Icon_1.shadowSize = new GSize(22,20);
    Icon_1.iconAnchor = new GPoint(6,20);
    Icon_1.infoWindowAnchor = new GPoint(6,0);
/*
    // icon_1
    Icon_1.iconSize = new GSize(20,34);
    Icon_1.shadowSize = new GSize(37,34);
    Icon_1.iconAnchor = new GPoint(10,34);
    Icon_1.infoWindowAnchor = new GPoint(10,0);
*/
    Icon_1.image = pathBaseIcon + 'image.png';
    Icon_1.shadow = pathBaseIcon + 'shadow.png';
    Icon_1.printImage = pathBaseIcon + 'printImage.gif';
    Icon_1.mozPrintImage = pathBaseIcon + 'mozPrintImage.gif';
    Icon_1.printShadow = pathBaseIcon + 'printShadow.gif';
    Icon_1.transparent = pathBaseIcon + 'transparent.png';

    // 2.- Alojamientos (casita)
//    pathBaseIcon = './iconos/marker_alojamientorural/';
    pathBaseIcon = pathRootIcon + 'icon_2/';
    Icon_2 = new GIcon();

    Icon_2.iconSize=new GSize(32,32);
    Icon_2.shadowSize=new GSize(48,32);
    Icon_2.iconAnchor=new GPoint(16,32);
    Icon_2.infoWindowAnchor=new GPoint(16,0);
/*
    Icon_2.iconSize=new GSize(20,34);
    Icon_2.shadowSize=new GSize(37,34);
    Icon_2.iconAnchor=new GPoint(10,34);
    Icon_2.infoWindowAnchor=new GPoint(10,0);
*/
    Icon_2.image = pathBaseIcon + 'image.png';
    Icon_2.shadow = pathBaseIcon + 'shadow.png';
    Icon_2.printImage = pathBaseIcon + 'printImage.gif';
    Icon_2.mozPrintImage = pathBaseIcon + 'mozPrintImage.gif';
    Icon_2.printShadow = pathBaseIcon + 'printShadow.gif';
    Icon_2.transparent = pathBaseIcon + 'transparent.png';
    // Icon_2.imageMap =

    // 3.- Restaurantes (copa de vino)
    pathBaseIcon = pathRootIcon + 'marker_restaurante/';
    Icon_3 = new GIcon();
/*
    Icon_3.iconSize = new GSize(32,32);
    Icon_3.shadowSize = new GSize(48,32);
    Icon_3.iconAnchor = new GPoint(16,32);
    Icon_3.infoWindowAnchor = new GPoint(16,0);
*/
    Icon_3.iconSize=new GSize(20,34);
    Icon_3.shadowSize=new GSize(37,34);
    Icon_3.iconAnchor=new GPoint(10,34);
    Icon_3.infoWindowAnchor=new GPoint(10,0);
    Icon_3.image = pathBaseIcon + 'image.png';
    Icon_3.shadow = pathBaseIcon + 'shadow.png';
    Icon_3.printImage = pathBaseIcon + 'printImage.gif';
    Icon_3.mozPrintImage = pathBaseIcon + 'mozPrintImage.gif';
    Icon_3.printShadow = pathBaseIcon + 'printShadow.gif';
    Icon_3.transparent = pathBaseIcon + 'transparent.png';

    GEvent.addListener(map, "moveend", function() {
      var bounds = map.getBounds();
      var centro = bounds.getCenter();
      cargarMarcadores();
    });

    GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {
      if (newLevel < oldLevel) {
        var bounds = map.getBounds();
        var centro = bounds.getCenter();
        cargarMarcadores();
      }
    });

    cargarMarcadores();
  }
}

// ******* ********* ********* ********* ********* ********* ********* *********
// ******* ********* ********* ********* ********* ********* ********* *********

function cargarMarcadores() {
  var bounds = map.getBounds();
  actualizarLimites(bounds, map.getZoom());
}

function actualizarLimites(bounds, zoom) {
//  var zoom = map.getZoom();
  var ne = bounds.getNorthEast();
  var sw = bounds.getSouthWest();
  var latS = sw.lat();
  var latN = ne.lat();
  var lngW = sw.lng();
  var lngE = ne.lng();
  var urlRequest = gatewayScript;
  urlRequest = urlRequest + '?latitud_d=' + latS + '&latitud_h=' + latN + '&longitud_d=' + lngW + '&longitud_h=' + lngE;
  makeRequest(urlRequest); 
}

// ******* ********* ********* ********* ********* ********* ********* *********

// Posicion, zoom y tipo de mapa inicial
function centrarMapaInicial(geoLat, geoLong, zoomLev, mapType) {
  map.setCenter(new GLatLng(geoLat, geoLong), zoomLev, mapType);
}

// ******* ********* ********* ********* ********* ********* ********* *********

function colocarMarcador(lat, lng, textoInfo, tipoIcono) {
    // alert("colocar marcador, lat: " + lat + ", lng: " + lng + "\n" + textoInfo);
    // 20080311: Marcador por defecto (sin icono)
    var marcador = new GMarker(new GLatLng(lat, lng), {draggable:false, icon:tipoIcono});
    GEvent.addListener(marcador, "click", function() {
      // alert(textoInfo);
      marcador.openInfoWindowHtml(textoInfo);
    });
    // map.addOverlay(marcador);
    return marcador;
}

// ******* ********* ********* ********* ********* ********* ********* *********
// ******* ********* ********* ********* ********* ********* ********* *********
// ******* ********* ********* ********* ********* ********* ********* *********

var http_request = false;

   function makeRequest(url) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      http_request.onreadystatechange = alertContents;
      // alert(url + parameters);
      http_request.open('GET', url, true);
      http_request.send(null);
   }

// ******* ********* ********* *********
  
  function valorNodoXML(nodoPadre, tagName) {
    var primerNodo = nodoPadre.getElementsByTagName(tagName)[0];
	var valor = false;
	if (primerNodo.firstChild)
	{
	  valor = primerNodo.firstChild.nodeValue;
	}
	return valor;
  }

// ******* ********* ********* *********

  function genTextoHtml(nomPobla, urlPobla, nomProvi, numHabit, altitud, urlFoto, geoLat, geoLng) {
    var spanCentrar = "<span class='spanEnlace' onclick='javascript:panToLL(" + geoLat + ", " + geoLng + ");'>Centrar</span>";
    var textoHtml = "<div class='interiorGlobo'><table style='display:block;margin:0;' border='0' cellspacing='0' cellpadding='0'><tr>";
    var strHabit = (numHabit == 0 ? "" : "Poblaci&oacute;n: " + numHabit + "<br/>");
    var strAltit = (altitud == 0 ? "" : "Altitud: " + altitud + "m<br/>");
    urlFoto = (urlFoto == "" ? "http://www.pueblos-espana.org/img/logo-pueblos-espana.png" : urlFoto);
    textoHtml = textoHtml + "<td><img src='" + urlFoto + "' height='68' alt='' />&nbsp;</td>";
    textoHtml = textoHtml + "<td><a href='" + urlPobla + "' target='_top'>" + nomPobla + "</a><br />";
    textoHtml = textoHtml + "(" + nomProvi + ")<br/>" + strHabit + strAltit + spanCentrar + "</td>";
    textoHtml = textoHtml + "</tr></table></div>";
    return textoHtml;
  }

// ******* ********* ********* *********

  function genTextoCasas(nomCasa, id_casa, poblacion, provincia, urlAlojamiento, urlFoto, geoLat, geoLng) {
    var spanCentrar = "<span class='spanEnlace' onclick='javascript:panToLL(" + geoLat + ", " + geoLng + ");'>Centrar</span>";
    var textoHtml = "<div class='interiorGlobo'><table style='display:block;margin:0;' border='0' cellspacing='0' cellpadding='0'><tr>";
    var urlCasa = "http://www.casas-turismo-rural.com/alojamiento.phtml?alojamiento=" + id_casa;
    textoHtml = textoHtml + "<td><img src='" + urlFoto + "' height='68' alt='' />&nbsp;</td>";
    textoHtml = textoHtml + "<td><a href='" + urlAlojamiento + "' target='_top'>" + nomCasa + "</a><br />";
    textoHtml = textoHtml + "(" + poblacion + " - " + provincia + ")<br/>" + spanCentrar + "</td>";
    textoHtml = textoHtml + "</tr></table></div>";
    return textoHtml;
  }

// ******* ********* ********* *********

  function genTextoRest(nomRest, id_rest, poblacion, provincia, urlFoto, geoLat, geoLng, descripcion) {
    var spanCentrar = "<span class='spanEnlace' onclick='javascript:panToLL(" + geoLat + ", " + geoLng + ");'>Centrar</span>";
    var textoHtml = "<div class='interiorGlobo'><table style='display:block;margin:0;' border='0' cellspacing='0' cellpadding='0'><tr>";
    var urlRest = "http://www.dondecomer.org/restaurante.php?id=" + id_rest;
    urlFoto = (urlFoto == "" ? "http://www.dondecomer.org/img/dondecomer.gif" : urlFoto);
    textoHtml = textoHtml + "<td><img src='" + urlFoto + "' height='68' alt='' />&nbsp;</td>";
    textoHtml = textoHtml + "<td><a href='" + urlRest + "' target='_top'>" + nomRest + "</a><br />";
    textoHtml = textoHtml + "(" + poblacion + " - " + provincia + ")<br/>" + spanCentrar + "</td>";
    textoHtml = textoHtml + "</tr></table></div>";
    return textoHtml;
  }

// ******* ********* ********* *********

  // Navegadores estandar (ECMA, DOM) + MSIE
  function alertContents() {
    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        var bounds = map.getBounds();

        var xmldoc = http_request.responseXML;
        // alert("responseText: " + http_request.responseText);
        // alert("responseXML: " + http_request.responseXML);
        // El elemento raiz es el primer (y unico) nodo 'casas'
        var root = xmldoc.getElementsByTagName('items')[0];
// alert("respuesta recibida-2");
        // alert("root (name): " + root.nodeName);
        var listaItems;

        listaItems = root.getElementsByTagName('poblacion');
        for (var numItem = 0; numItem < listaItems.length; numItem++) {
//    continue;
          var item = listaItems[numItem];

          var nomPobla = item.firstChild.nodeValue;
          var item_id = item.getAttribute("id_poblacion");
          var urlPobla = item.getAttribute("url_poblacion");
          var nomProvi = item.getAttribute("provincia");
          var geoLat = item.getAttribute("latitud");
          var geoLng = item.getAttribute("longitud");
          var numHabit = item.getAttribute("habitantes");
          var altitud = item.getAttribute("altitud");
          var urlFoto = item.getAttribute("url_foto");
          var textoHtml = genTextoHtml(nomPobla, urlPobla, nomProvi, numHabit, altitud, urlFoto, geoLat, geoLng);

          var marcador = colocarMarcador(geoLat, geoLng, textoHtml, Icon_1);
          var item_id_lm = "p_" + item_id;

          // Solo la primera vez!!!
          if (item_id == idIni && tipoIdIni == '1' && firstShow) {
            firstShow = false;
            lm.insertarMarcador(item_id_lm, marcador);
            map.addOverlay(marcador);
            marcador.openInfoWindowHtml(textoHtml);
          }
          if (!lm.contieneMarcador(item_id_lm)) {
            lm.insertarMarcador(item_id_lm, marcador);
            map.addOverlay(marcador);
            // alert("Nuevo marcador: " +  id_casa);
          }    
        }

        listaItems = root.getElementsByTagName('casa');
        for (var numItem = 0; numItem < listaItems.length; numItem++) {
          var item = listaItems[numItem];

          var nomCasa = item.firstChild.nodeValue;
          var item_id = item.getAttribute("id_casa");
          var nomPobla = item.getAttribute("poblacion");
          var nomProvi = item.getAttribute("provincia");
          var geoLat = item.getAttribute("latitud");
          var geoLng = item.getAttribute("longitud");
          var urlAlojamiento = item.getAttribute("url_alojamiento");
          var urlFoto = item.getAttribute("url_foto");
          var textoHtml = genTextoCasas(nomCasa, item_id, nomPobla, nomProvi, urlAlojamiento, urlFoto, geoLat, geoLng);
          var marcador = colocarMarcador(geoLat, geoLng, textoHtml, Icon_2);
          var item_id_lm = "c_" + item_id;

          if (item_id == idIni && tipoIdIni == '2' && firstShow) {
            firstShow = false;
            lm.insertarMarcador(item_id_lm, marcador);
            map.addOverlay(marcador);
            marcador.openInfoWindowHtml(textoHtml);
          }
          if (!lm.contieneMarcador(item_id_lm)) {
            lm.insertarMarcador(item_id_lm, marcador);
            map.addOverlay(marcador);
            // alert("Nuevo marcador: " +  id_casa);
          }    
        }

        listaItems = root.getElementsByTagName('establecimiento');
        for (var numItem = 0; numItem < listaItems.length; numItem++) {
          var item = listaItems[numItem];

          var nomCasa = item.firstChild.nodeValue;
          var item_id = item.getAttribute("id_establecimiento");
          var nomPobla = item.getAttribute("poblacion");
          var nomProvi = item.getAttribute("provincia");
          var geoLat = item.getAttribute("latitud");
          var geoLng = item.getAttribute("longitud");
          var urlFoto = item.getAttribute("url_foto");
          var descripcion = item.getAttribute("descripcion");
          var textoHtml = genTextoRest(nomCasa, item_id, nomPobla, nomProvi, urlFoto, geoLat, geoLng, descripcion);
          var marcador = colocarMarcador(geoLat, geoLng, textoHtml, Icon_3);
          var item_id_lm = "e_" + item_id;

          // Solo la primera vez!!!
          if (item_id == idIni && tipoIdIni == '3' && firstShow) {
            firstShow = false;
            lm.insertarMarcador(item_id_lm, marcador);
            map.addOverlay(marcador);
            marcador.openInfoWindowHtml(textoHtml);
          }
          if (!lm.contieneMarcador(item_id_lm)) {
            lm.insertarMarcador(item_id_lm, marcador);
            map.addOverlay(marcador);
            // alert("Nuevo marcador: " +  id_casa);
          }    
        }

        // alert(lm.longitud());
      } else {
        alert('ERROR al enviar datos.');
      }
    }
  }

  function panToLL(lat, lng) {
    // alert("lat: " + lat + ", lng: " + lng);
    var pos = new GLatLng(lat, lng);
    map.panTo(pos);
  }

  function panToLLZ(lat, lng, zoom) {
    var pos = new GLatLng(lat, lng);
    map.setCenter(pos,  zoom);
  }

// ******* ********* ********* ********* ********* ********* ********* *********

function ListaMarcadores() {
  this.lista = new Array();
}

function insertarMarcador(id, marcador) {
  with (this) {
    lista[id] = marcador;
    // alert("Insercion: " + id);
  }
}
ListaMarcadores.prototype.insertarMarcador = insertarMarcador;

function borrarMarcador(id) {
  with (this) lista.splice(id, 1);
}
ListaMarcadores.prototype.borrarMarcador = borrarMarcador;

function contieneMarcador(id) {
  with (this) {
    // alert("typeof: " + typeof lista[id]);
    return (typeof lista[id] == 'object');
  }
}
ListaMarcadores.prototype.contieneMarcador = contieneMarcador;

// ******* ********* ********* ********* ********* ********* ********* *********
// ******* ********* ********* ********* ********* ********* ********* *********

