
var _maxlat,_minlat,_maxlng,_minlng;
var _arrIds;
var ifmap; // iframe del mapa
var efecto=null;

function setExtent(maxlat,minlat,maxlng,minlng) {

    _maxlat = maxlat;
    _maxlng = maxlng;
    _minlat = minlat;
    _minlng = minlng;           
   
}
  
// Google streets view
var con3D;
var mostrarBusquedaLocal=false;
var mostrarMasCapas=false;
var urlCatastro='http://ovc.catastro.meh.es/Cartografia/WMS/ServidorWMS.aspx?';
var urlCartoCiudad='http://www.cartociudad.es/wms/CARTOCIUDAD/CARTOCIUDAD?';
//Estas son las capas disponibles "so far": 'FondoUrbano,Vial,Portal,Toponimo,SeccionCensal,CodigoPostal,DivisionTerritorial'

function esperaEInicia(funcion) { // esperamos a que se haya cargado el iframe
    ifmap = document.getElementById('ifmap'); // obtenemos el iframe donde está el mapa 
    
    if (ifmap && ifmap.contentWindow.iniciado ) { 
       
        eval.call(window,funcion);              
        
        if (mostrarMasCapas) {
   
            ifmap.contentWindow.nuevoMapaWMS(urlCatastro,'Catastro', 'Catastro',mostrarInfoCatastro,17);     
            ifmap.contentWindow.nuevoMapaWMS(urlCatastro,'LIMITES', 'Límites catastrales',mostrarInfoCatastro);
            ifmap.contentWindow.nuevoMapaWMS(urlCatastro,'CONSTRU', 'Construcciones',mostrarInfoCatastro);       
            ifmap.contentWindow.nuevoMapaWMS(urlCartoCiudad,'CodigoPostal', 'Códigos postales',null);   
            ifmap.contentWindow.nuevoMapaWMS(urlCartoCiudad,'SeccionCensal', 'Secciones Censales',null);       
        }         
        if (con3D) {
            ifmap.contentWindow.ver3D();
        }        
                   
    }
    else { 
  
        if (ifmap && ifmap.contentWindow.cargarScripts && !ifmap.contentWindow.map_loaded) {
           
            ifmap.contentWindow.cargarScripts(mostrarBusquedaLocal); // ya se ha cargado el iframe, ahora le toca inicializar el mapa
        }
        setTimeout('esperaEInicia(\''+funcion+'\')',100);
    }
}
        

function mostrarFotos() {
    ifmap = document.getElementById('ifmap');
    ifmap.contentWindow.muestraFotos();
}

function mostrarHexagonos(minlon,minlat,maxlon,maxlat) {

    ifmap.contentWindow.centrarExtension(maxlat,minlat,maxlon,minlon); 
    ifmap.contentWindow.muestraHexagonos(    
    function(tile, zoom) {    
        llamadaAJAX('/DesktopModules/Inzoco.UI/AjaxGeneral.ashx',null,'accion=obtMapa&x=' + tile.x + '&y=' + tile.y + '&z=' + (zoom),'',null,null,false);
        return respuestaAJAX;              
    });      
}

function mostrarInfoCatastro(linkCatastro) {
 
    if (linkCatastro!='') {
    
        if (linkCatastro.indexOf('http')!=-1) {
            var l = new formOverlay(false,null,linkCatastro,null,null,true);
            l.activate();
        }
        else {
            mostrarOverlay("Vaya, parece que algo va mal :(",linkCatastro);
        }
    }
    else {
        mostrarOverlay("No hay información catastral","No se ha encontrado información catastral en el lugar seleccionado");
    }
   
   
}

var iniciado=false;

function situarMarkers(JSONMarkers) {

    //if (!iniciado) {ifmap.contentWindow.centrarExtension(_maxlat,_minlat,_maxlng,_minlng); iniciado=true; }
    var center =  ifmap.contentWindow.map.getCenter();
    lngAct=center.lng();
    latAct=center.lat();
    zoomAct = ifmap.contentWindow.map.getZoom();	            
	ifmap.contentWindow.map.clearOverlays();  
	ifmap.contentWindow.actualizarSearch();	      
	ifmap.contentWindow.document.getElementById('ajaxMapa').style.display='none';
	  
	var icono;
    for (var i=0; i<JSONMarkers.length;i++) {        
       
        datosMarker = JSONMarkers[i];
        icono = datosMarker['icono'];
     
        if (icono=='cluster') { // cluster de markers
            
            ifmap.contentWindow.situarCluster(datosMarker["items_cluster"], datosMarker['longitud'],
                datosMarker['latitud']);
        }
        else {
        
            var marker=ifmap.contentWindow.situarMarker(
                datosMarker['longitud'],
                datosMarker['latitud'],
                datosMarker['html'],
                icono,
                datosMarker['tooltip'],
                datosMarker['url'],
                false,
                null,
                datosMarker['id']);
                
            // ficha del anuncio al pinchar
            ifmap.contentWindow.agregarEvento(marker, "click", fichaBanner);
         }       
            
         // al pasar por encima del marker nos desplazamos hasta la fila del listado relacionada
//         ifmap.contentWindow.agregarEvento(marker,"mouseover",function() {
//            if (efecto) { efecto.finish(); efecto.cancel(); }
//            efecto = new Effect.Highlight('prod'+this.id_relacionado, {startcolor:'#FDFF3F', endcolor:'#fafafa'})
//            if (scrollbar) scrollbar.scrollTo('prod'+this.id_relacionado,true);
//            ;
//             
//            
//         });                  

    } 
    
    inicializaAutoUpdate();
}


function fichaBanner(point) { // se le hace un bind(marker), con lo que this es el marker

  
    llamadaAJAX('/DesktopModules/Inzoco.UI/AjaxProductos.aspx',null,'accion=fichaBanner&id='+this.id_relacionado,this.id_relacionado,null,null,false);
   
    ifmap.contentWindow.verTooltip(respuestaAJAX,this.getLatLng(),true); 
    
}

function inicializaAutoUpdate() {

     // Lo hacemos solo si se desplaza una cuarta parte del mapa o se cambia el zoom
     var fncdoupdate = function() {
            var actualizar=false;
	        if (!false) 
	        {
	            ifmap.contentWindow.ocultarTooltip();
	            var center = ifmap.contentWindow.map.getCenter();
	            var zoom = ifmap.contentWindow.map.getZoom();
	            var bounds = ifmap.contentWindow.map.getBounds();
	            var sw = bounds.getSouthWest();
	            var ne = bounds.getNorthEast();                           
	            
	            if (zoom!=zoomAct) { actualizar=true; zoomAct=zoom; }
	            else {
	                var dx = (center.lng() - lngAct);
	                var dy = (center.lat() - latAct);
	                if (dx < 0) {
	                    dx = dx * (-1);
	                }
	                if (dy < 0) {
	                    dy = dy * (-1);
	                } 	
	                 
    	           
	                var rx = (ne.lng() - sw.lng()) / 4 ;
	                var ry = (ne.lat() - sw.lat()) / 4 ;
	                if(rx < 0) rx = rx * (-1) ;
	                if(ry < 0) ry = ry * (-1) ;
    	            
	                actualizar =  (dx > rx) || (dy > ry);
	                
	             }
	             
	             if (actualizar) { 
	                // los criterios están en forma JSON (ver listado.js)
	                jsoncriterios["_critGeo"]["_longitud"]=sw.lng();
	                jsoncriterios["_critGeo"]["_latitud"]=sw.lat();
	                jsoncriterios["_critGeo"]["_longitud_max"]=ne.lng();
	                jsoncriterios["_critGeo"]["_latitud_max"]=ne.lat();
	                AJAXUpdate();
	                
	                lngAct=center.lng();
	                latAct=center.lat();
	                
	            }
			
	        }
		}.bind(this.window);		
		
	    ifmap.contentWindow.agregarEvento(ifmap.contentWindow.map, "moveend", fncdoupdate);
	

}


function situarProducto(lat,lon) {

    ifmap.contentWindow.centrarEn(_maxlat,_maxlng,15); 
    ifmap.contentWindow.situarMarker(lon,lat,null);
                               
}

var _arrMunis;
function situarMunicipios() {

    if (_arrMunis) {
        if (_arrMunis.length>1) {
            ifmap.contentWindow.centrarExtension(_maxlat,_minlat,_maxlng,_minlng); 
           
        }
        else {
            ifmap.contentWindow.centrarEn(_maxlat,_maxlng,15);                
        }                       
        var ix,html;   
        
        var marker;
        for (ix=0; ix<_arrMunis.length; ix++) 
        {                           
        
            html = '<div style="background-color:#fff; border:2px solid #000; padding:4px 6px;"><h2 class="name">'+_arrMunis[ix][2] + " (" +  _arrMunis[ix][4] +")" +
                                    '</h2></div>';
            marker = ifmap.contentWindow.situarMarker(_arrMunis[ix][1],_arrMunis[ix][0],null,ifmap.contentWindow.baseIcon,html,_arrMunis[ix][3]);
           
        }            
    }   
}

var areas;
function pintarAreas() {
              
    ifmap.contentWindow.areas=areas;       
    ifmap.contentWindow.pintarAreas();  
   
}


function respuestaGeoAnuncio(args,ctx) {

    var xmlAJAX = loadXML(args);
    var latitud = xmlAJAX.getElementsByTagName('lat')[0].getAttribute("valor");
    var longitud = xmlAJAX.getElementsByTagName('lng')[0].getAttribute("valor");
    
    if (xmlAJAX.getElementsByTagName('html')[0].firstChild!=null) {
        var html = xmlAJAX.getElementsByTagName('html')[0].firstChild.nodeValue;
     
        var fila = $('prod' + ctx);
       var marker = ifmap.contentWindow.situarMarker(longitud,latitud,html,ifmap.contentWindow.baseIcon);
        
        if (fila) {
         
            Event.observe(fila, "click", function() {
                    marker.openInfoWindowHtml(html);
                },false); 
                
            ifmap.contentWindow.agregarEvento(marker,"mouseover",function() {
                    if (efecto) { efecto.finish(); efecto.cancel(); }
                    efecto = new Effect.Highlight('prod'+ctx, {startcolor:'#FDFF3F', endcolor:'#fafafa'})  });                  
                               
        }        
     }            
     
}