/*
* Maps Eptisa TI
* Copyright (c) 2008, Eptisa TI (http://www.ti.eptisa.com)
* 
* Descripción:
* Aplicación con Google Maps
*/

/** Textos utilizados 
var TEXTO_IDIOMA = "E";
var TEXTO_CARGANDO = "Cargando Datos";
var TEXTO_DIRECCION_NO_ENCONTRADA = "No se ha obtenido ninguna correspondencia con la direcci&oacute;n buscada";
var TEXTO_NINGUNA_DIRECCION_ENCONTRADA = "No se ha encontrado ninguna direcci&#243;n";
var TEXTO_ACERQUE_ZOOM = "Acerque el zoom para ver detalles";
var TEXTO_EN = "en";
var TEXTO_BORRAR_LISTA_SELECCIONADOS = "Borrar seleccionados";
var TEXTO_CLUSTERING = "Click to zoom in and see %count markers";
/****/

var EXTENSION_ICONOS = ".png";
var CATEGORIAS_SELECCIONADAS = "";
var CATEGORIAS_OPCIONES = new Object();
var CLASS_MARKER_INFO_EXTEND = "snow_window";
var IMAGEN_SOBRE_MAPA = "TurgaliciaGoogleMaps/images/provincias.png";
var ZOOM_MAXIMO_PROVINCIAS = 6;
var ZOOM_MAXIMO_MUNICIPIOS = 11;
var ZOOM_INTERVALO_ACTUAL = -1;
var DESFASE_ALTURA_MAPA = 292;
var PETICIONES_EN_CARGA = 0;
var FILTROS;
var tooltip = null;
var map;
var groundOverlay;
var geocoder;
var ovcontrol;
var AppCenter = new GLatLng(42.818381, -7.902539);
var AppZoom = 8;
var currentCenter = new GLatLng(42.818381, -7.902539);
var loadBounds;
var AppSW = new GLatLng(41.783089, -9.310913);
var AppNE = new GLatLng(43.804801, -6.657715);
var markerSearch;
var VENTANA_LOAD;
var ENABLE_CLUSTER = true;
var cluster;
var PUNTOS_FIJOS = undefined;
var PUNTOS_INICIALES = undefined;
var CARGAR_PUNTOS_FIJOS = true;
var VALORES_DE_SESSION = undefined;
var icon;
var baseIcon = new GIcon();

function setCentro(lat_centro,lng_centro,zoom) {
    AppCenter = new GLatLng(lat_centro, lng_centro);
    if (zoom) AppZoom = zoom;
}

function getZoom() {
    return map.getZoom();
}

function getLatitudCentro() {
    return map.getCenter().lat();
}

function getLongitudCentro() {
    return map.getZoom().lng();
}


function cargarMapa(LISTA_PUNTOS_INICIALES) {
    if (GBrowserIsCompatible()) {

        //map.clearOverlays();		  
        baseIcon.iconSize = new GSize(32, 32);
        baseIcon.shadowSize = new GSize(56, 32);
        baseIcon.iconAnchor = new GPoint(16, 32);
        baseIcon.infoWindowAnchor = new GPoint(16, 0);
        // create the map
        //showResize();
        map = new GMap2(document.getElementById("map"));
        cluster = new ClusterMarker(map, { clusterMarkerTitle: TEXTO_CLUSTERING,idioma: TEXTO_IDIOMA });

        // get array of map types
        var mapTypes = map.getMapTypes();
        // overwrite the getMinimumResolution() and getMaximumResolution() methods for each map type
        for (var i = 0; i < mapTypes.length; i++) {
            mapTypes[i].getMinimumResolution = function() { return 8; }
            //mapTypes[i].getMaximumResolution = function() { return 16; }
        }

        map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(1, 25)));
        map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(3, 3)));
        map.addMapType(G_PHYSICAL_MAP);
        map.addControl(new GScaleControl());
        map.enableContinuousZoom();
        map.enableScrollWheelZoom();

        ovcontrol = new GOverviewMapControl();
        map.addControl(ovcontrol);



        geocoder = new GClientGeocoder();

        map.setCenter(AppCenter, AppZoom);


        groundOverlay = new GGroundOverlay(IMAGEN_SOBRE_MAPA, new GLatLngBounds(AppSW, AppNE));
        map.addOverlay(groundOverlay);

        tooltip = document.createElement("div");
        map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
        tooltip.style.visibility = "hidden";

        VENTANA_LOAD = document.createElement("div");
        VENTANA_LOAD.setAttribute("id", "loading");
        VENTANA_LOAD.setAttribute("class", "loading");
        document.getElementById("map").appendChild(VENTANA_LOAD);
        VENTANA_LOAD.innerHTML = '<div class="loading"><p style="margin-top:250px;"><img  src="TurgaliciaGoogleMaps/images/progress.gif" /> ' + TEXTO_CARGANDO + '</p></div>';
        VENTANA_LOAD.style.display = "none";



        GEvent.addListener(map, "dragend", function() {
            if (map.getZoom() > ZOOM_MAXIMO_PROVINCIAS) {
                ActualizarListener(true);
            }
        });


        GEvent.addListener(map, "moveend", function() {
            var center = map.getCenter();
            if (!inAreaApp(center.lat(), center.lng())) {
                map.setCenter(currentCenter, map.getZoom());
            }
            else {
                currentCenter = center;
            }
        });


        GEvent.addListener(map, "zoomend", function(zoomold, zoomnew) {

            var zoom = map.getZoom();
            if (zoom <= ZOOM_MAXIMO_PROVINCIAS) {
                if (ZOOM_INTERVALO_ACTUAL != ZOOM_MAXIMO_PROVINCIAS) {
                    ActualizarListener();
                }
            }
            else if (zoom <= ZOOM_MAXIMO_MUNICIPIOS) {
                /*if (ZOOM_INTERVALO_ACTUAL != ZOOM_MAXIMO_MUNICIPIOS) {
                ActualizarListener();
                }*/
                ActualizarListener();
            }
            else if (ZOOM_INTERVALO_ACTUAL <= ZOOM_MAXIMO_PROVINCIAS && zoom > ZOOM_MAXIMO_MUNICIPIOS) {
                ActualizarListener();
            }
            else {
                ActualizarListener(true);
            }
        });

        /**
        * Cuando hacemos click sobre el mapa cierra el menú de categorias si éste está visible
        */
        GEvent.addListener(map, "click", function() {
            if (VISIBLE_CATEGORIAS) verCategorias("");
        });

        /**
        * Cuando movemos el mapa cierra el menú de categorias si éste está visible
        */
        GEvent.addListener(map, 'movestart', function() {
            if (VISIBLE_CATEGORIAS) verCategorias("");
        });


        /*GEvent.addListener(overviewMap.getOverviewMap(), 'moveend', function()	{ 
        ActualizarListener(); 
        }); 
	 
	GEvent.addDomListener(document.getElementById('map_overview'), 'click', function(){ 
        ActualizarListener(); 
        }); 
        */



        if (navigator.userAgent.indexOf("Opera") >= 0) {
            CLASS_MARKER_INFO_EXTEND = "";
        }

        if (CARGAR_PUNTOS_FIJOS) {
            peticion("TurgaliciaGoogleMaps/busquedas/buscar.aspx?get=puntosfijos", "getRegionesFijas");
        }

        GEvent.addListener(map, "addoverlay", function(overlay) {
            GEvent.clearListeners(overlay, "mouseover");
            GEvent.clearListeners(overlay, "mouseout");
            GEvent.addListener(overlay, "mouseover", function() {
                showTooltip(overlay);
            });
            GEvent.addListener(overlay, "mouseout", function() {
                tooltip.style.visibility = "hidden";
            });
        });

        var html = '';
        html += '<div id="borrar_lista_puntos_iniciales" class="htmlControlA" onclick="clearTodo();" style="display:none;" title="' + TEXTO_BORRAR_LISTA_SELECCIONADOS + '"><div class="htmlControlB">' + TEXTO_BORRAR_LISTA_SELECCIONADOS + '</div></div>';       
        html = '<div class="htmlControl">' + html + '</div>'
        var control = new HtmlControl(html);
        map.addControl(control, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(3, 3)));
        
        try {
            
            if (undefined != LISTA_PUNTOS_INICIALES) {
               peticion("TurgaliciaGoogleMaps/busquedas/buscar.aspx?id=" + LISTA_PUNTOS_INICIALES, "getRegionesIniciales");
            }
            else{
                try {
                    loadPuntosIniciales();
                    if (PUNTOS_INICIALES != undefined) {
                        mostrarPuntosIniciales();
                        centrarPuntosIniciales();                 

                    }
                } catch (e) {
                }
            
            }            
        } catch (e) {
            var LISTA_PUNTOS_INICIALES;            
        }      
        
        setTimeout("checkOverview()", 100);
    }
}
    

      function checkOverview() {
        var overmap = ovcontrol.getOverviewMap();
        if (overmap) {
          // ======== get a reference to the GMap2 ===========
          ovmap = ovcontrol.getOverviewMap();
          GEvent.addListener(ovmap, "dragend", function() {
              if (map.getZoom() > ZOOM_MAXIMO_PROVINCIAS) {
                  ActualizarListener(true);
              }
          });

          GEvent.addListener(ovmap, "dragstart", function() {
             if (map.getExtInfoWindow())
                map.closeExtInfoWindow();
          });
         
        } else {
          setTimeout("checkOverview()",100);
        }
      }
    


/*
* FUNCION REDIMENSIONA EL MAPA CON EL TAMAÑO DE LA PANTALLA ACTUAL
*/
function showResize() {

    var hght,wdth;
    if (typeof (window.innerWidth) == 'number') {
        // Non-IE
        wdth = window.innerWidth;
        hght = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        // IE 6+ in 'standards compliant mode'
        wdth = document.documentElement.clientWidth;
        hght = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        // IE 4 compatible
        wdth = document.body.clientWidth;
        hght = document.body.clientHeight;
    }
    hght = hght - DESFASE_ALTURA_MAPA;
    document.getElementById("map").style.height = hght + "px";
    if (document.getElementById("cuadromensaje")) {
        var wght = wdth / 2;
        wght = wght - (document.getElementById("cuadromensaje").clientWidth / 2);
        document.getElementById("cuadromensaje").style.left = wght + "px";
    }
    
    
}



function setEnableCluster(enable) {
    ENABLE_CLUSTER = enable.checked;    
    ActualizarListener();
}



/*
* FUNCION DE ACTUALIZACIÓN
*/
function ActualizarListener(comprobar_cargados) {
    if (comprobar_cargados && loadBounds != undefined && loadBounds.containsBounds(map.getBounds())) {
        if (cluster && ENABLE_CLUSTER) {
            //cluster.refresh();
        }
    }
    else {
        comprobar_categorias();
    }
}

/*
* FUNCION ACTUALIZA LOS MARKER DE LAS DISTINTAS CATEGORIAS
*/
function comprobar_categorias() {
    var llb = map.getBounds();
    var cat = CATEGORIAS_SELECCIONADAS;
    if (map.getExtInfoWindow())
        map.closeExtInfoWindow();
    map.clearOverlays();
    showMensaje("");
    if (cluster) {
        markersArray = [];
        cluster.removeMarkers();
    }

    //MUESTRA LOS PUNTOS FIJOS
    mostrarPuntosFijos();
    
    mostrarCategorias(cat, llb.getNorthEast(), llb.getSouthWest(), map.getZoom());
    if (markerSearch) {
        map.addOverlay(markerSearch);
    }

    //MUESTRA LOS PUNTOS INICIALES
    mostrarPuntosIniciales();
     
}

/*
* FUNCION QUE REALIZA LAS PETICIONES AL SERVIDOS PARA OBTENER LOS PUNTOS DE LAS CATEGORIAS SELECCIONADAS Y LOS PINTA SOBRE EL MAPA
*/
function mostrarCategorias(categorias, pArbDrch, pAbjIz, zoom) {

    var sufijo = "";
    if (zoom <= ZOOM_MAXIMO_PROVINCIAS) {
        map.addOverlay(groundOverlay);
    }    
    
    if (zoom <= ZOOM_MAXIMO_PROVINCIAS) {
        ZOOM_INTERVALO_ACTUAL = ZOOM_MAXIMO_PROVINCIAS;
        showMensaje("Se han agrupado los datos por Provincias.<br/>Acerque el zoom sobre la zona desada para m&aacute;s detalle. ");
    }
    else if (zoom <= ZOOM_MAXIMO_MUNICIPIOS) {
        ZOOM_INTERVALO_ACTUAL = ZOOM_MAXIMO_MUNICIPIOS;
        showMensaje("Se han agrupado los datos por Municipios.<br/>Acerque el zoom sobre la zona desada para m&aacute;s detalle. ");
    }
    else {
        ZOOM_INTERVALO_ACTUAL = ZOOM_MAXIMO_MUNICIPIOS + 1;
        showMensaje("");
    }

    if (cluster)
        cluster.removeMarkers();
    

    /*var aux = categorias.split(",");
    for (var i = 0; i < aux.length; i++) {
            if (aux[i] != null && aux[i].length > 1) {
                var cat = aux[i];
                var parametros_fijos = "&tipo=areas&zoom=" + zoom + "&cat=" + cat + "&NElon=" + pArbDrch.lng() + "&NElat=" + pArbDrch.lat() + "&SWlon=" + pAbjIz.lng() + "&SWlat=" + pAbjIz.lat()+"&mzoom=" +ZOOM_MAXIMO_MUNICIPIOS+"&pzoom=" +ZOOM_MAXIMO_PROVINCIAS;    
                if (CATEGORIAS_OPCIONES[cat]) {
                    peticion("TurgaliciaGoogleMaps/busquedas/buscar.aspx?" + CATEGORIAS_OPCIONES[cat] + parametros_fijos, "mostrarRegiones");
                }
                else {
                    peticion("TurgaliciaGoogleMaps/busquedas/buscar.aspx?" + parametros_fijos, "mostrarRegiones");
                }
            }
     }*/
    
    
    var parametros_fijos = "&tipo=areas&zoom=" + zoom + "&cat=" + categorias + "&NElon=" + pArbDrch.lng() + "&NElat=" + pArbDrch.lat() + "&SWlon=" + pAbjIz.lng() + "&SWlat=" + pAbjIz.lat() + "&mzoom=" + ZOOM_MAXIMO_MUNICIPIOS + "&pzoom=" + ZOOM_MAXIMO_PROVINCIAS;
    peticion("TurgaliciaGoogleMaps/busquedas/buscar.aspx?" + parametros_fijos, "mostrarRegiones");

    if (categorias.length > 3) {
        if (document.getElementById("borrar_lista_puntos_iniciales") != undefined)
            document.getElementById("borrar_lista_puntos_iniciales").style.display = "block";
    }
    else {
        if (document.getElementById("borrar_lista_puntos_iniciales") != undefined)
            document.getElementById("borrar_lista_puntos_iniciales").style.display = "none";
    }
    
     loadBounds = map.getBounds();
     
    
}

/*
* FUNCION QUE LEE LA RESPUESTA OBTENIDA EN UNA PETICION DE PUNTOS. INTERPRETE DE LA ESTRUCTURA JSON DE PUNTOS
*/
function mostrarRegiones(http_request) {
    var response = eval("(" + http_request.responseText + ")");
    var datos = response.regiones;
    var num_cat = datos.length;
    var tipo;
    var markersArray = [];
    for (i = 0; i < num_cat; i++) {
        var categoria = datos[i];
        if (categoria && categoria.zonas) {
            var num_zonas = categoria.zonas.length;
            tipo = categoria.nombre;
            for (z = 0; z < num_zonas; z++) {
                var zona = categoria.zonas[z];
                var point = new GLatLng(zona.lat, zona.lng);
                var html = "<div id='cabecera' style='font-weight:bold;font-size:1.2em;width:auto;max-width:300px;border-bottom:1px #dddddd solid;'>" + zona.num + " " + datos[i].nombre + "</div>";
                html += "<div id='cuerpo' style='  border-bottom:1px solid #dddddd;border-top:1px solid #dddddd;margin:0em;padding:0em;padding-left:5px;padding-bottom:8px;'>";
                html += "<p style='font-family: Verdana,Arial,Helvetica,sans-serif; font-size: 10px; color #333333; text-align left;'>";
                html += TEXTO_ACERQUE_ZOOM;
                html += "</p></div>";
                map.addOverlay(createMarkerIcono(point, tipo, html, map.getZoom(), categoria.nombre, zona.num));
            } // End for zonas
        } // end if zonas
        else if (categoria && categoria.puntos) {
            var num_puntos = categoria.puntos.length;
            tipo = categoria.nombre;
            for (z = 0; z < num_puntos; z++) {
                var punto = categoria.puntos[z];
                var point = new GLatLng(punto.lat, punto.lng);
                markersArray.push(createMarkerIcono(point, tipo, "", map.getZoom(), punto.nombre, punto.num, punto.id));                
            } // End for puntos
        } // end if puntos

        else if (categoria && categoria.provincias) {
            var num_zonas = categoria.provincias.length;
            tipo = categoria.nombre + "_provincia";
            for (z = 0; z < num_zonas; z++) {
                var zona = categoria.provincias[z];
                var point = new GLatLng(zona.lat, zona.lng);
                var html = "<div class='cabecera_burbuja'>" + zona.num + " " + TEXTO_PUNTOS_EN + " " + zona.nombre + "</div>";
                html += "<div class='cuerpo_burbuja'>";
                html += "<p style='font-family: Verdana,Arial,Helvetica,sans-serif; font-size: 10px; color #333333; text-align left;'>";
                if (zona.desc) {
                    html += zona.desc + "<br />";
                } 
                html += "<a href='javascript:map.setCenter(new GLatLng(" + zona.lat + "," + zona.lng + ")," + (ZOOM_MAXIMO_PROVINCIAS + 1) + ")'>" + TEXTO_ACERQUE_ZOOM + '</a>';
                html += "</p></div>";

                map.addOverlay(createMarkerIcono(point, tipo, html, map.getZoom(), zona.num + " " + TEXTO_PUNTOS_EN + " " + zona.nombre, zona.num,undefined,35));
            } // End for provincias
        } // end if provincias

        else if (categoria && categoria.municipios) {
            var num_zonas = categoria.municipios.length;
            tipo = categoria.nombre + "_municipio";
            for (z = 0; z < num_zonas; z++) {
                var zona = categoria.municipios[z];
                var point = new GLatLng(zona.lat, zona.lng);
                var html = "<div id='cabecera' style='font-weight:bold;font-size:1.2em;width:auto;max-width:300px;border-bottom:1px #dddddd solid;'>" + zona.num + " " + categoria.nombre + " " + TEXTO_EN + " " + zona.nombre + "</div>";
                html += "<div id='cuerpo' style='padding:8px;'>";
                html += "<p style='font-family: Verdana,Arial,Helvetica,sans-serif; font-size: 10px; color #333333; text-align left;'>";
                html += TEXTO_ACERQUE_ZOOM;
                html += "</p></div>";

                map.addOverlay(createMarkerIcono(point, tipo, html, map.getZoom(), zona.num + " " + categoria.nombre + " " + TEXTO_EN + " " + zona.nombre, zona.num));
            } // End for provincias
        } // end if provincias
    } // end for regiones
    if (markersArray.length > 0) {        
        if (cluster && ENABLE_CLUSTER) {
            cluster.addMarkers(markersArray);
            cluster.refresh();
        }
        else {
            for (var w = 0; w < markersArray.length; w++) {
                map.addOverlay(markersArray[w]);
            }
        }
        markersArray = [];
    }   
}

/*
* FUNCION QUE LEE LA RESPUESTA OBTENIDA EN UNA PETICION DE PUNTOS FIJOS.
*/
function getRegionesFijas(http_request) {
    var response = eval("(" + http_request.responseText + ")");
    var datos = response.regiones;
    var num_cat = datos.length;
    var tipo;
    PUNTOS_FIJOS = [];
    for (i = 0; i < num_cat; i++) {
        var categoria = datos[i];
        if (categoria && categoria.puntos) {
            var num_puntos = categoria.puntos.length;
            tipo = categoria.nombre;
            for (z = 0; z < num_puntos; z++) {
                var punto = categoria.puntos[z];
                var point = new GLatLng(punto.lat, punto.lng);
                
                //map.addOverlay(createMarkerIcono(point, tipo, html, map, map.getZoom(), punto.nombre, punto.num));
                PUNTOS_FIJOS.push(createMarkerIcono(point, tipo, "", map.getZoom(), punto.nombre, punto.num, punto.id));
            } // End for puntos
        } // end if puntos
        
    } // end for regiones
    mostrarPuntosFijos();
}

/**
* Añade al mapa los puntos fijos 
*/
function mostrarPuntosFijos() {
    if (PUNTOS_FIJOS != undefined) {
        for (var w = 0; w < PUNTOS_FIJOS.length; w++) {
            map.addOverlay(PUNTOS_FIJOS[w]);
        }
    }
}

/*
* FUNCION QUE LEE LA RESPUESTA OBTENIDA EN UNA PETICION DE PUNTOS FIJOS.
*/
function getRegionesIniciales(http_request) {
    var response = eval("(" + http_request.responseText + ")");
    var datos = response.regiones;
    var num_cat = datos.length;
    var tipo;
    if (PUNTOS_INICIALES) {
        for (var z = 0; z < PUNTOS_INICIALES.length; z++) {
            PUNTOS_INICIALES[z] = [];
        }
    }
    PUNTOS_INICIALES = [];    
    for (i = 0; i < num_cat; i++) {
        var categoria = datos[i];
        if (categoria && categoria.puntos) {
            var num_puntos = categoria.puntos.length;
            tipo = categoria.nombre;
            var ArrayTipo = [];
            ArrayTipo.tipo = tipo;
            for (z = 0; z < num_puntos; z++) {
                var punto = categoria.puntos[z];
                var point = new GLatLng(punto.lat, punto.lng);                
                //map.addOverlay(createMarkerIcono(point, tipo, html, map, map.getZoom(), punto.nombre, punto.num));
                ArrayTipo.push(createMarkerIcono(point, tipo, "", map.getZoom(), punto.nombre, punto.num, punto.id));
            } // End for puntos
            PUNTOS_INICIALES.push(ArrayTipo);
        } // end if puntos

    } // end for regiones
    mostrarPuntosIniciales();
    centrarPuntosIniciales();
}

/**
* Centra el mapa para que sean visibles todos los puntos iniciales 
*/
function centrarPuntosIniciales() {
    if (PUNTOS_INICIALES != undefined && PUNTOS_INICIALES) {
        for (var z = 0; z < PUNTOS_INICIALES.length; z++) {        
            if (PUNTOS_INICIALES[z].length <= 100){
                var  groupBounds = new GLatLngBounds();
                for (var w = 0; w < PUNTOS_INICIALES[z].length; w++) {
                     groupBounds.extend(PUNTOS_INICIALES[z][w].getLatLng());
                }
                map.setCenter(groupBounds.getCenter(), map.getBoundsZoomLevel(groupBounds));
                if (cluster && ENABLE_CLUSTER) {               
                    cluster.refresh();
                }

            } //Fin iflength <= 100
         }//Fin for z
     }//Fin if undefined
}
/**
* Añade al mapa los puntos iniciales 
*/
function mostrarPuntosIniciales() {
    if (PUNTOS_INICIALES != undefined && PUNTOS_INICIALES) {
        if (cluster && ENABLE_CLUSTER) {
            for (var z = 0; z < PUNTOS_INICIALES.length; z++) {
                if (CATEGORIAS_SELECCIONADAS.indexOf(PUNTOS_INICIALES[z].tipo) < 0) {
                    cluster.addMarkers(PUNTOS_INICIALES[z]);
                }                   
            }
            cluster.refresh();
        }
        else {
            for (var z = 0; z < PUNTOS_INICIALES.length; z++) {
                if (CATEGORIAS_SELECCIONADAS.indexOf(PUNTOS_INICIALES[z].tipo) < 0) {
                    for (var w = 0; w < PUNTOS_INICIALES[z].length; w++) {
                        map.addOverlay(PUNTOS_INICIALES[z][w]);
                    }
                }                
            }
        }       
        if (PUNTOS_INICIALES.length > 0 && document.getElementById("borrar_lista_puntos_iniciales") != undefined) {
            document.getElementById("borrar_lista_puntos_iniciales").style.display = "block";
        }
    }
}

/**
* Borra del mapa los puntos iniciales 
*/
function borrarPuntosIniciales() {
    if (PUNTOS_INICIALES != undefined) {
        if (cluster && ENABLE_CLUSTER) {
            for (var z = 0; z < PUNTOS_INICIALES.length; z++) {
                cluster.deleteMarkers(PUNTOS_INICIALES[z]);
            }
        }
        else {
            for (var z = 0; z < PUNTOS_INICIALES.length; z++) {
                for (var w = 0; w < PUNTOS_INICIALES[z].length; w++) {
                    map.removeOverlay(PUNTOS_INICIALES[z][w]);
                }
            }
        }       
    
       
    }
    if (document.getElementById("borrar_lista_puntos_iniciales") != undefined)
        document.getElementById("borrar_lista_puntos_iniciales").style.display = "none";
}

/**
* Borra del mapa los puntos iniciales y vacia la lista de puntos
*/
function clearPuntosIniciales() {
    LISTA_PUNTOS_INICIALES = undefined;    
    if (PUNTOS_INICIALES != undefined) {
        if (cluster && ENABLE_CLUSTER) {
            for (var z = 0; z < PUNTOS_INICIALES.length; z++) {
                cluster.deleteMarkers(PUNTOS_INICIALES[z]);
            }
        }
        else {
            for (var z = 0; z < PUNTOS_INICIALES.length; z++) {
                for (var w = 0; w < PUNTOS_INICIALES[z].length; w++) {
                    map.removeOverlay(PUNTOS_INICIALES[z][w]);
                }
            }
        }
        for (var z = 0; z < PUNTOS_INICIALES.length; z++) {
            PUNTOS_INICIALES[z] = [];
        }
    }
   
    PUNTOS_INICIALES = [];
    if(VALORES_DE_SESSION!=undefined) VALORES_DE_SESSION = false;
    if (document.getElementById("borrar_lista_puntos_iniciales") != undefined)
        document.getElementById("borrar_lista_puntos_iniciales").style.display = "none";
    if (document.getElementById("georesultados_rec") != undefined)
        document.getElementById('georesultados_rec').innerHTML = '';
    //if (document.getElementById("geosearch") != undefined)
        //document.getElementById("geosearch").value = "";
    if (document.getElementById("georesultados_txt") != undefined) {
        document.getElementById('georesultados_txt').innerHTML = '';
        document.getElementById('georesultados_txt').style.display = "none";
    }
}

/**
* Borra del mapa los puntos iniciales, las categorias seleccionadas y vacia la lista de puntos
*/
function clearTodo() {
    clearPuntosIniciales();
    if (CATEGORIAS_SELECCIONADAS.length > 2) {
        uncheckTodasCategorias(CATEGORIAS_SELECCIONADAS);
    }
}

/**
* Añade puntos iniciales a la lista y los muestra
*/
function addPuntosIniciales(nuevos) {
    if (PUNTOS_INICIALES != undefined) {

        if (cluster && ENABLE_CLUSTER) {
            var tipo = "";
            var ArrayPuntos=[];
            var PuntosAMostrar=[];
            for (var w = 0; w < nuevos.length; w++) {
                if (tipo != nuevos[w].tipo) {
                    tipo = nuevos[w].tipo;
                    var idx=-1;
                    for (var z = 0; z < PUNTOS_INICIALES.length; z++) {
                        if(PUNTOS_INICIALES[z].tipo==tipo){
                            idx=z;
                        }
                    }
                    if(idx>-1){
                        ArrayPuntos=PUNTOS_INICIALES[z];
                    }
                    else{
                        ArrayPuntos=[];
                        ArrayPuntos.tipo=tipo;
                        PUNTOS_INICIALES.push(ArrayPuntos);
                    }
                }
                ArrayPuntos.push(nuevos[w]);    
                if(CATEGORIAS_SELECCIONADAS.indexOf(nuevos[w].tipo)<0){
                    PuntosAMostrar.push(nuevos[w]);
                }          
            }
            cluster.addMarkers(PuntosAMostrar);
            cluster.refresh();
            PuntosAMostrar = undefined;
         }
         else {
           for (var w = 0; w < nuevos.length; w++) {
                    PUNTOS_INICIALES.push(nuevos[w]);
                    map.addOverlay(nuevos[w]);
            }
         }
           
        if (PUNTOS_INICIALES.length > 0 && document.getElementById("borrar_lista_puntos_iniciales") != undefined) {
            document.getElementById("borrar_lista_puntos_iniciales").style.display = "block";
        }
    }
}

/*
* FUNCION PARA CREAR UN MARKER
*/
function createMarkerIcono(point, tipo, html, zoom, nombre, total_puntos, id, size) {
    if (!size) size = 21; 
    var baseIcon = new GIcon();
    baseIcon.iconSize = new GSize(size, size);
    baseIcon.shadowSize = new GSize(size, size);
    baseIcon.iconAnchor = new GPoint(size / 2, size / 2);
    baseIcon.infoWindowAnchor = new GPoint(10, 5);
    var icono = new GIcon(baseIcon, "TurgaliciaGoogleMaps/images/" + tipo + EXTENSION_ICONOS);
    var marker = new GMarker(point, { icon: icono });
    // var marker = new OffsetableMarker(point,{icon:icono});    	
    marker.name = nombre;
    marker.tipo = tipo;
    if(id) marker.id = id;
    GEvent.addListener(marker, "click", function() {
    if (id) window.open("ficha_datos.asp?crec=" + id + "&cidi=" + TEXTO_IDIOMA, "_blank");

        /*if (CLASS_MARKER_INFO_EXTEND && CLASS_MARKER_INFO_EXTEND != "") {
        if (id) {
        marker.openExtInfoWindow(map, CLASS_MARKER_INFO_EXTEND, "<div> " + TEXTO_CARGANDO + "...</div>", {ajaxUrl: "TurgaliciaGoogleMaps/busquedas/buscar.aspx?id=" + id + "&format=html&language=" + TEXTO_IDIOMA });
        }
        else
        marker.openExtInfoWindow(map, CLASS_MARKER_INFO_EXTEND, html);
        }
        else {
        if (id) {
        marker.openInfoWindowHtml("<div> " + TEXTO_CARGANDO + "...</div>");
        GDownloadUrl("TurgaliciaGoogleMaps/busquedas/buscar.aspx?id=" + id + "&format=html&language=" + TEXTO_IDIOMA, function(response, status) {
        if (response == null || status == -1) {
        marker.openInfoWindowHtml('<span class="error">ERROR: The Ajax request failed to get HTML content</span>');
        } else {
        marker.openInfoWindowHtml(response);
        }
        });
        }
        else {
        marker.openInfoWindowHtml(html);
        }
        }*/
    });
    return marker;
}

/*
* FUNCION QUE REALIZA UNA PETICIÓN AJAX ASINCRONA
*/
function peticion(url, proceso) {
    //alert(url);
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        var http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) { http_request.overrideMimeType('text/xml'); }
    } else if (window.ActiveXObject) { // IE
        try {
            var http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                var http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { }
        }
    }
    if (!http_request) {
        alert('Giving up: Cannot create an XMLHTTP instance');
        return false;
    }
    else {
        http_request.onreadystatechange = function() {
            if (http_request.readyState == 4) {
                setTimeout('updatePeticionesEnCarga(-1)', 500);
                if (http_request.status == 200) {
                    eval(proceso + "(http_request)");
                }
                else if (http_request.status == 204)
                    alert('NO HAY RESPUESTA');
            }
        }

        http_request.open("get", url, true);
        updatePeticionesEnCarga(1);
        http_request.send(null);        
        return http_request;
    }
}





function updatePeticionesEnCarga(addPeticiones) {
    PETICIONES_EN_CARGA = PETICIONES_EN_CARGA + addPeticiones;
    if (PETICIONES_EN_CARGA <= 0) {
        PETICIONES_EN_CARGA = 0;
        VENTANA_LOAD.style.display = "none";
        //alert("TERMINARON LAS PETICIONES");
    }
    else {
        VENTANA_LOAD.style.display = "";
    }
}

/*
* FUNCION QUE GEOCODIFICA UNA DIRECCIÓN Y MUESTRA LOS RESULTADOS
*/
function MostrarSugerencias(search, proceso_resultados) {  
    var busqueda_concreta = true;
    if (!search) {
        busqueda_concreta = false;
        search = document.getElementById("geosearch").value;
    }
    if (search == "") return false;
    if (search.toLowerCase().indexOf("galicia")<0) {
        search = search + ", Galicia";
    }
    geocoder.getLocations(search, function(result) {
        var html = '';
        var pointSearch = null;
        if (result.Status.code == G_GEO_SUCCESS) {
            var encontrados = 0;
            if (result.Placemark.length >= 1) { //SI HA ENCONTRADO MAS DE UN RESULTADO 	   
                for (var i = 0; i < result.Placemark.length; i++) {
                    var accuracy = result.Placemark[i].AddressDetails.Accuracy;
                    var p = result.Placemark[i].Point.coordinates;
                    var es_direccion = result.Placemark[i].address;
                    var code_pais = result.Placemark[i].AddressDetails.Country.CountryNameCode;
                    if (accuracy == "2") {
                        es_direccion = result.Placemark[i].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName + ", Espa&#241;a";
                    }
                    else if (accuracy == "3") {
                        es_direccion = result.Placemark[i].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName + ", Espa&#241;a";
                    }
                    if (code_pais == "ES") {
                        es_direccion = es_direccion.replace('Spain', 'Espa&#241;a');
                        es_direccion = es_direccion.replace('Espanya', 'Espa&#241;a');

                        if (inAreaApp(p[1], p[0])) {
                            //html += "<p><a href='javascript:showAddressAux(" + p[1] + "," + p[0] + "," + accuracy + ",\"" + es_direccion + "\")' target='_top'>" + es_direccion + "</a></p>";
                            html += "<p><a href='javascript:showAddressAux(" + p[1] + "," + p[0] + "," + accuracy + ")' target='_top'>" + es_direccion + "</a></p>";
                            encontrados++;
                            //return;
                        }

                    }
                } // FIN FOR
                if (encontrados == 0) {
                    html = TEXTO_DIRECCION_NO_ENCONTRADA;
                }

            } // FIN  IF Placemark.length          
        }
        // ====== Decode the error status ======
        else {
            /* var reason = "Codigo " + result.Status.code;
            if (reasons[result.Status.code]) {
            reason = reasons[result.Status.code]
            }*/
            html = TEXTO_NINGUNA_DIRECCION_ENCONTRADA; 
            //alert('No se pudo encontrar "'+search+ '" ' + reason);
        }
        eval(proceso_resultados + "(html)");

    }
        );
    
}

/*
* FUNCION QUE VERIFICA SI UN PUNTO ESTA DENTRO DE LA CUADRICULA DEFINIDA POR LA APLICACIÓN
*/
function inAreaApp(lat, lng) {
    var point = new GLatLng(lat, lng);
    var bounds = new GLatLngBounds(AppSW, AppNE);
    return bounds.contains(point);
}

/*
* FUNCION PINTA Y SITUA EL MAPA EN UN PUNTO, Y ABRE SU BURBUJA DE INFORMACIÓN (PARA RESULTADOS DE LA BÚSQUEDA)
*/
function showAddressAux(lat, lng, accuracy, html) {
    var zoom;
    if (accuracy) {
        if (accuracy < 4)
            zoom = 7;
        else if (accuracy < 6)
            zoom = 13;
        else if (accuracy < 8)
            zoom = 15;
        else
            zoom = 16;
    }
    else zoom = 15;
    var point = new GLatLng(lat, lng);

    if (map.getExtInfoWindow())
        map.closeExtInfoWindow();
    if (markerSearch) {
        map.removeOverlay(markerSearch);
    }
    markerSearch = new GMarker(point);
    map.setCenter(point, zoom);
    map.addOverlay(markerSearch);
    ActualizarListener(true);
    if (html) {
        //markerSearch.name = html;
        GEvent.addListener(markerSearch, 'click', function() {
            markerSearch.openInfoWindowHtml(html);
            //markerSearch.openExtInfoWindow(map,"snow_window",html);        	
        });
        markerSearch.openInfoWindowHtml(html);
    }
    
}

/*
* FUNCION QUE MUESTRA EL TOOLTIP DE UN MARKER
*/
function showTooltip(marker) {
    //alert(marker.name);    
    if (marker.name && marker.id) {
        if (marker.html) {
            tooltip.innerHTML = '<div class="tooltip" id="tooltip_' + marker.id + '">' + marker.html + '<div id="tooltip_logo"></div><div id="tooltip_t"></div><div id="tooltip_tl"></div><div id="tooltip_tr"></div><div id="tooltip_b"></div><div id="tooltip_bl"></div><div id="tooltip_br"></div></div>';            
        }
        else {
            tooltip.innerHTML = '<div class="tooltip" id="tooltip_' + marker.id + '"><h3>' + marker.name + '</h3><p>' + TEXTO_CARGANDO + ' . . .</p><div id="tooltip_logo"></div><div id="tooltip_t"></div><div id="tooltip_tl"></div><div id="tooltip_tr"></div><div id="tooltip_b"></div><div id="tooltip_bl"></div><div id="tooltip_br"></div></div>';

            GDownloadUrl("TurgaliciaGoogleMaps/busquedas/buscar.aspx?id=" + marker.id + "&format=tooltip&language=" + TEXTO_IDIOMA, function(response, status) {
                if (response == null || status == -1) {
                    marker.html = '<div>Error</div>';
                } else {
                    if(response!="")
                        marker.html = response;
                    else
                        marker.html = '<h3>' + marker.name + '</h3><div id="tooltip_logo"></div><div id="tooltip_t"></div><div id="tooltip_tl"></div><div id="tooltip_tr"></div><div id="tooltip_b"></div><div id="tooltip_bl"></div><div id="tooltip_br"></div>';
                    
                    var divtooltip = document.getElementById("tooltip_" + marker.id);
                    if (divtooltip && tooltip.style.visibility == "visible") {
                        showTooltip(marker);                      
                    }
                }
            });            
        }
        var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0, 0), true), map.getZoom());
        var point2 = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(), map.getZoom());
        var point3 = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getNorthEast(), map.getZoom());
        var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(), map.getZoom());
        var anchor = marker.getIcon().iconAnchor;
        var height = marker.getIcon().iconSize.height;
        var width = marker.getIcon().iconSize.width;
        var alto = tooltip.clientHeight;
        var largo = tooltip.offsetWidth;
        //alert("offset=" + offset.x + "," + offset.y + " Point=" + point.x + "," + point.y  + " Point2=" + point2.x + "," + point2.y  + " Point3=" + point3.x + "," + point3.y  + " Anchor=" + anchor + " width=" + width + " height=" + alto);

        var desplz_x = (largo + anchor.x) / 2;
        var desplz_y = (alto);
        //Ajuste cuando el icono esta cerca de la parte superior
        if ((offset.y - point3.y) < (desplz_y + anchor.y)) {
            desplz_y = ((height / 2) + anchor.y + 1) * (-1);

        }        

        //Ajuste cuando el icono esta cerca de la parte izquierda
        if ((offset.x - point2.x) < desplz_x) {
            desplz_x = (offset.x - point2.x);

        }
        //Ajuste cuando el icono esta cerca de la parte derecha
        else if ((point3.x - offset.x) < desplz_x) {
            desplz_x = desplz_x + desplz_x - (point3.x - offset.x);

        }

        var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + (width - desplz_x), offset.y - point.y - anchor.y - ( desplz_y)));
        pos.apply(tooltip);
        tooltip.style.visibility = "visible";
    }
    else {
        tooltip.style.visibility = "hidden";
        tooltip.innerHTML = '';
    }
}

/*
* FUNCION MUESTRA UN MENSAJE SOBRE EL MAPA (div obligatorio <div id="cuadromensaje"> y <div id="cuadromensaje_content">)
*/
function showMensaje(mensaje) {
    var cuadro = document.getElementById("cuadromensaje");
    var cuadro_mensaje = document.getElementById("cuadromensaje_content");
    if (cuadro && cuadro_mensaje) {
        if (mensaje && mensaje != "") {
            cuadro.style.display = 'block';
            cuadro_mensaje.innerHTML = mensaje;
            var wght = document.documentElement.clientWidth / 2;
            wght = wght - (cuadro.clientWidth / 2);
            cuadro.style.left = wght + "px";
        }
        else {
            cuadro.style.display = 'none';
            cuadro_mensaje.innerHTML = "";
        }


    }

}


/*

*/
function Get_Cookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');
        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}




/*********************************************************/
/******* TRATAMIENTO DE COOKIES SOBRE EL MAPA ************/
/*********************************************************/
function Set_Cookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());
    // if the expires variable is set, make the correct expires time, the
    // current script below will set it for x number of days, to make it
    // for hours, delete * 24, for minutes, delete * 60 * 24
    if (expires) {
        expires = expires * 1000 * 60;
    }
    //alert( 'today ' + today.toGMTString() );// this is for testing purpose only
    var expires_date = new Date(today.getTime() + (expires));
    //alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

    document.cookie = name + "=" + escape(value) +
		((expires) ? ";expires=" + expires_date.toGMTString() : "") + //expires.toGMTString()
		((path) ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "") +
		((secure) ? ";secure" : "");
}

// this deletes the cookie when called
function Delete_Cookie(name, path, domain) {
    if (Get_Cookie(name)) document.cookie = name + "=" +
			((path) ? ";path=" + path : "") +
			((domain) ? ";domain=" + domain : "") +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


function Load_Map_State() {
    if (window.location.search.indexOf("reusar=on") >= 0 && !are_cookies_enabled()) {
        alert(TEXTO_COOKIES_EXIT);
    }
    var cookie = Get_Cookie("TurgaliciaMaps");
    if (cookie) {
        Delete_Cookie("TurgaliciaMaps");
        //alert("Cookie lograda = " + cookie);        
        var datos = eval("(" + cookie + ")");
        setCentro(datos.lat, datos.lng, datos.zoom);
        checkTodasCategorias('', datos.cat);
        if (datos.search != "" && datos.tipo_search != "") {
            if (document.getElementById("geosearch") && document.getElementById("tipo_geobusqueda")) {
                document.getElementById("geosearch").value = datos.search;
                //document.getElementById("tipo_geobusqueda").value = datos.tipo_search;
                document.getElementById("tipo_geobusqueda").value = "recurso";
                obtenerBusqueda('georesultados');               
            }
        }

    }

}

function Save_Map_State() {
    // alert("Se está guardando una cookie");
    try {
        if (!are_cookies_enabled())
            alert(TEXTO_COOKIES_EXIT);

        if (map) {

            var search = "";
            var tipo_search = "";
            try {
                if (PUNTOS_INICIALES && PUNTOS_INICIALES.length > 0) {
                    if (ULTIMA_BUSQUEDA_REALIZADA) {
                        search = ULTIMA_BUSQUEDA_REALIZADA;
                    }
                    if (document.getElementById("tipo_geobusqueda") && document.getElementById("tipo_geobusqueda").value != undefined) {
                        tipo_search = document.getElementById("tipo_geobusqueda").value;
                    }
                }
            } catch (e) { }
            var value = "{'lat':" + map.getCenter().lat() + ",'lng':" + map.getCenter().lng() + ",'zoom':" + map.getZoom() + ",'cat':'" + CATEGORIAS_SELECCIONADAS + "','search':'" + search + "','tipo_search':'" + tipo_search + "'}";
            Set_Cookie("TurgaliciaMaps", value, 1);
        }
    }
    catch (e) {

    }
}

function cambiarIdioma(url) {
    try {
        Save_Map_State();
    }
    catch (e) { }
    if (url.indexOf("&reusar=off") > 0) {
        url = url.replace('reusar=off', '');
    }
    if (VALORES_DE_SESSION!=undefined && VALORES_DE_SESSION==false) {
        if (url.indexOf("?")>0) {
            if (url.indexOf("reusar=on") > 0) {
                url = url.replace('reusar=on', 'reusar=off');
            }
            else {
                url = url + "&reusar=off";
            }
        }
        else {
            url = url + "?reusar=off";
        }
    }
    window.location = url;
}

function are_cookies_enabled() {
   
    Set_Cookie('test', 'none', '', '/', '', '');
    // if Get_Cookie succeeds, cookies are enabled, since
    //the cookie was successfully created.
    if (Get_Cookie('test')) {
        Delete_Cookie('test', '/', '');
        return true;
    }
    else {
        return false;
    }

}
