function dump(arr,level) {
    var dumped_text = "";
    if(!level) level = 0;
    
    //The padding given at the beginning of the line.
    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";
    if(typeof(arr) == 'object') { //Array/Hashes/Objects
        for(var item in arr) {
            var value = arr[item];
            if(typeof(value) == 'Object') { //If it is an array,
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += dump(value,level+1);
            }
            else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    }
    else { //Stings/Chars/Numbers etc.
        dumped_text = "([> "+arr+" <]"+typeof(arr)+")";
    }
    return dumped_text;
}




function LimpiarPoblaciones(){
    var poblaciones = document.getElementById('poblacion');
    for (var i = 0; i > poblaciones.childNodes.length; i++) {
        poblaciones.removeChild(poblaciones.lastChild);
    }
    var option = document.createElement('option');
    var text = document.createTextNode('Población');
    option.value = "-1:"+latitudProvincia+":"+longitudProvincia;
    option.defaultSelected=true;
    option.appendChild(text);
    poblaciones.disabled = true;
}

function obtenerListaProvincias() {
    var pl = new SOAPClientParameters();
    pl.add('soloGeolocalizadas', document.getElementById('soloGeolocalizadas').checked);
    SOAPClient.invoke(
        wsdl,
        'obtenerListaProvincias',
        pl,
        asincrono,
        obtenerListaProvinciasCallback
    );
}

function obtenerListaProvinciasCallback(r) {
    LimpiarProvincias();
    var select = document.getElementById('provincia');
    var option;
	
    for (var i = 0; i < r.length; i++) {
        option = document.createElement('option');
        option.value = r[i][0]+':'+r[i][2]+':'+r[i][3];
        option.appendChild(document.createTextNode(r[i][1]));
        select.appendChild(option);
    }
}

function obtenerListaPoblaciones() {
    var idProvincia = document.getElementById('provincia').value;
	
    var lista = idProvincia.split(':')
    if (lista[0] == -1 || lista[0] == " ") return;
	LimpiarPoblaciones();
	var pl = new SOAPClientParameters();
	
    pl.add('idProvincia', lista[0]);
    pl.add('tipoVivienda', document.getElementById('tipoVivienda').value);
    pl.add('precioHasta', document.getElementById('precioHasta').value);
    pl.add('dormitorios', document.getElementById('dormitorios').value);
    pl.add('supDesde', document.getElementById('superficieDesde').value);
    pl.add('banyos', document.getElementById('banyos').value);
    pl.add('soloGeolocalizadas', document.getElementById('soloGeolocalizadas').checked);
    SOAPClient.invoke(
        wsdl,
        'obtenerListaPoblaciones',
        pl,
        asincrono,
        obtenerListaPoblacionesCallback
    );  
}

function obtenerListaPoblacionesCallback(r) {
    var select = document.getElementById('poblacion');
	
    for (var i = 0; i < r.length; i++) {
		
        var option;
        option = document.createElement('option');
        option.value = r[i][0]+':'+r[i][2]+':'+r[i][3];
        option.appendChild(document.createTextNode(r[i][1]));
        select.appendChild(option);
    }
    select.disabled = false
}

function crearMarcadorProvincia(info) {
    var latlng = new GLatLng(info[3], info[4]);
    var icono = new google.maps.Icon(google.maps.DEFAULT_ICON);
    icono.shadow = '';
    icono.iconSize = new google.maps.Size(imagen_provincia_tamx, imagen_provincia_tamy);
    icono.iconAnchor = new google.maps.Point(imagen_provincia_tamx/2, imagen_provincia_tamy);
    icono.image = imagen_provincia;
    var marcador = new GMarker(latlng, {icon: icono});
    google.maps.Event.addListener(marcador, 'click', function() {
        mapa.setCenter(latlng, zoomProvincia);
		mapa.closeExtInfoWindow();
    });
    google.maps.Event.addListener(marcador, 'mouseover', function() {
       marcador.openExtInfoWindow(
              mapa,
              "custom_info_window_red",
               "<div class='title'>"+info[1]+"</div>"+
              "<div class='section1'>"+info[2]+"</b> Inmuebles</div>"+
			  '<div align="center"><a class="enlace_ficha" onclick="irBusqueda('+info[0]+')" href="#">Ver inmuebles</a></div>',
			  "3"
            ); 

	    //marcador.openInfoWindowHtml('<table><tr><td  align=center><b>'+info[1]+'</b>, <b>'+info[2]+'</b> viviendas.</td></tr><tr>&nbsp;<td></td></tr><tr><td align=center><a class="enlace_ficha" onclick="irBusqueda('+info[0]+')" href="#">Ver listado de inmuebles de esta provincia</a></td></tr></table>'); 
        marcador.setImage(imagen_provincia_brillante);
    });
    google.maps.Event.addListener(marcador, 'mouseout', function() {
        marcador.setImage(imagen_provincia);
    });
    marcadoresProvincias.push(marcador);
}

function crearMarcadorInmueble(info) {
    var latlng = new google.maps.LatLng(info[5], info[6]);
    var tipo = parseInt(info[4]);
    var imagen, imagen_brillante, imagen_tamx, imagen_tamy;
    /*if (tipo == 1) {
        imagen = imagen_piso;
        imagen_brillante = imagen_piso_brillante;
        imagen_tamx = imagen_piso_tamx;
        imagen_tamy = imagen_piso_tamy;
    }
    else */if (tipo == 2) {
        imagen = imagen_garaje;
        imagen_brillante = imagen_garaje_brillante;
        imagen_tamx = imagen_garaje_tamx;
        imagen_tamy = imagen_garaje_tamy;
    }
    else if (tipo == 3) {
        imagen = imagen_local;
        imagen_brillante = imagen_local_brillante;
        imagen_tamx = imagen_local_tamx;
        imagen_tamy = imagen_local_tamy;        
    }
    else {
        imagen = imagen_inmueble;
        imagen_brillante = imagen_inmueble_brillante;
        imagen_tamx = imagen_inmueble_tamx;
        imagen_tamy = imagen_inmueble_tamy;           
    }
    var icono = new google.maps.Icon(google.maps.DEFAULT_ICON);
    icono.image = imagen;
    icono.iconSize = new google.maps.Size(imagen_tamx, imagen_tamy);
    icono.iconAnchor = new google.maps.Point(imagen_tamx/2, imagen_tamy);
    icono.shadow = '';
    var marcador = new google.maps.Marker(latlng, {icon: icono});
    marcador.id = parseInt(info[0]);
    marcador.precio = parseFloat(info[1]);
    marcador.superficie = parseFloat(info[2]);
    marcador.habitaciones = parseInt(info[7]);
    marcador.banyos = parseInt(info[3]);
	if(info[9].length >120)
   	 marcador.descripcion = info[9].substr(0,120);
	else
	 marcador.descripcion = info[9];
	if(info[8]!="")
	marcador.foto=info[8];
	else marcador.foto="modules/2mano/imagen_no_disponible.jpg";
    marcador.tipo = parseInt(info[4]);
    marcador.latitud = parseFloat(info[5]);
    marcador.longitud = parseFloat(info[6]);
    marcador.habitaciones = parseInt(info[7]);
    marcador.estado = parseInt(info[10]);
    var enlace = 'modules.php?name=';
    if (info[10] == 1) {
        enlace += 'obra_nueva';
    }
    else {
        enlace += '2mano';
    }
    enlace += '&tipo='+info[4];
    enlace += '&file=mostrar&id='+info[0]+'&latitud='+info[5]+'&longitud='+info[6];
    icono.iconSize = new google.maps.Size(imagen_inmueble_tamx, imagen_inmueble_tamy);
    /* Ponemos el icono en consecuencia */
    var inmueble = '<div class="foto">\
                    <img class="imagendeficha" src="http://www.aquicasa.com/'+marcador.foto+'"/>\
                </div>\
                <div class="div_datos">\
                    <div class="datos">\
                        <strong>Dormitorios</strong>: '+marcador.habitaciones+'<br />\
                        <strong>Superficie</strong>: '+marcador.superficie+'<br />\
                        <strong>Baños</strong>: '+marcador.banyos+'\
                    </div>\
                </div>\
                <div class="descripcion">\
                    <span>'+marcador.descripcion+'</span>\
                </div>\
                <a class="enlace_ficha" href="'+enlace+'">Ver Ficha Inmueble</a>';
			
			
			
			
			
			
    marcador.id=info[0];
    google.maps.Event.addListener(marcador, 'click', function() {
        //marcador.openInfoWindowHtml(inmueble);
		document.getElementById('buscador_mapa').style.display="none";
		document.getElementById('ir_a_mapa').style.display="none";
	    document.getElementById('ficha_mapa').style.display="block";
		document.getElementById('info_window').innerHTML=inmueble;
		document.getElementById('precio_ficha_mapa').innerHTML="Precio: "+number_format(marcador.precio,2,",",".")+" &euro;";
    });
    google.maps.Event.addListener(marcador, 'mouseover', function() {
        /*var resultados = document.getElementById('bodyResultados');
        document.getElementById(marcador.id).className="fila resaltado";
        //document.getElementById(marcador.id).scrollIntoView(true);*/
        marcador.setImage(imagen_brillante);
    });
    google.maps.Event.addListener(marcador, 'mouseout', function() {
        /*document.getElementById(marcador.id).className="fila";*/
        marcador.setImage(imagen);
    });
    marcadoresInmuebles.push(marcador);
    if (presentesGeolocalizados[info[0]] != undefined) {
        return;
    }
    return marcador;
} 

function crearMarcadorMasInmueble(info) {
    var latlng = new google.maps.LatLng(info[2], info[3]);
    
    var imagen, imagen_brillante, imagen_tamx, imagen_tamy;
   
        imagen = imagen_inmueble;
        imagen_brillante = imagen_inmueble_brillante;
        imagen_tamx = imagen_inmueble_tamx;
        imagen_tamy = imagen_inmueble_tamy;           
 
    var icono = new google.maps.Icon(google.maps.DEFAULT_ICON);
    icono.image = imagen;
    icono.iconSize = new google.maps.Size(imagen_tamx, imagen_tamy);
    icono.iconAnchor = new google.maps.Point(imagen_tamx/2, imagen_tamy);
    icono.shadow = '';
    var marcador = new google.maps.Marker(latlng, {icon: icono});
    
     icono.iconSize = new google.maps.Size(imagen_inmueble_tamx, imagen_inmueble_tamy);
	 //repasar y poner latitud y longitud
  var enlace = 'modules.php?name=2mano&latitud='+info[2]+'&longitud='+info[3];
 	if (document.getElementById('precioHasta').value != -1)
        enlace += '&precioHasta=' + document.getElementById('precioHasta').value;
    if (document.getElementById('superficieDesde').value != -1)
        enlace += '&supDesde=' + document.getElementById('superficieDesde').value;
    if (document.getElementById('dormitorios').value != -1)
        enlace += '&minHabitaciones=' + document.getElementById('dormitorios').value;
    if (document.getElementById('banyos').value != -1)
        enlace += '&minBanyos=' + document.getElementById('banyos').value;
    if (document.getElementById('tipoVivienda').value != -1)
        enlace += '&tipoVivienda=' + document.getElementById('tipoVivienda').value;
      var listado = '<div class="sin_localizar"> Hay <span id="numero">' + info[4] + '</span> inmuebles en esta localizacion.         </div>\
	          <br><br><a class="enlace_ficha" href="'+enlace+'">Ver Inmuebles</a>';
	/*if (info[1] != "") {
		var inmuebles = info[1].split("::");
		//alert(dump(inmuebles));
		var listado = "<table><tr style='background:#666666;color:#ffffff;font-weight:bold'>\
		<td>Estado</td><td>Tipo</td><td>Hab.</td><td>Banyos</td><td>Sup.</td><td>Precio</td></tr>";
		for (var i = 0; i < inmuebles.length - 1; i++) {
			var lista = inmuebles[i].split(";");
			 var enlace = 'modules.php?name=';
 
			if(i%2)var color="#EEEDED";
			else var color="#BDBCBC"  
			if (lista[6] == 1) {
				var estado = "A Estrenar"; 
				 enlace += 'obra_nueva';
			}
			else {
				var estado = "2ª Mano";
				 enlace += '2mano';
			}
			      enlace += '&file=mostrar&id='+lista[0]+'&latitud='+info[2]+'&longitud='+info[3];
			listado += "<tr onclick='location.href=\""+enlace+"\"' bgcolor='"+color+"' >\
			<td>" + estado + "</td><td>" + lista[5] + "</td><td>" + lista[4] + "</td><td>" + lista[3] + "</td><td>" + lista[2] + "</td><td>" + lista[1] + "</td></tr>";
		}
		listado += "</table>";
	}*/
			// alert(dump(inmuebles));
			
  
  google.maps.Event.addListener(marcador, 'click', function() {
       // marcador.openInfoWindowHtml(inmueble);
	   document.getElementById('buscador_mapa').style.display="none";
	   document.getElementById('ir_a_mapa').style.display='none';
	   document.getElementById('ficha_mapa').style.display="block";
	   document.getElementById('info_window').innerHTML=listado;
	   document.getElementById('precio_ficha_mapa').innerHTML="";
    });
  
    google.maps.Event.addListener(marcador, 'mouseover', function() {
        /*var resultados = document.getElementById('bodyResultados');
        document.getElementById(marcador.id).className="fila resaltado";
        //document.getElementById(marcador.id).scrollIntoView(true);*/
        marcador.setImage(imagen_brillante);
    });
    google.maps.Event.addListener(marcador, 'mouseout', function() {
        /*document.getElementById(marcador.id).className="fila";*/
        marcador.setImage(imagen);
    });
    marcadoresInmuebles.push(marcador);
    if (presentesGeolocalizados[info[0]] != undefined) {
        return;
    }
    return marcador;
} 

function situarNivelProvincia() {
    var valor = document.getElementById('provincia').value.split(':');
    latitudProvincia = valor[1];
    longitudProvincia = valor[2];
    var latitud;
    var longitud;
    zoom = zoomProvincia;
    latitud = valor[1];
    longitud = valor[2];
    identificadorProvincia = valor[0];
    if (valor == -1) {
        latitud = latitudInicial;
        longitud = longitudInicial;
        zoom = zoomInicial;
    }
    var latlng = new google.maps.LatLng(latitud, longitud);
    latitudeInicial = latitud;
    longitudInicial = longitud;
    mapa.setCenter(latlng, zoom);
    obtenerListaPoblaciones();
    //recalcularMoverRatonOZoom();
}

function situarNivelPoblacion() {
    var valor = document.getElementById('poblacion').value;
    var lista = valor.split(':');
    var zoom = zoomPoblacion;
    var latitud = lista[1];
    var longitud = lista[2]
    if (lista[0] == -1) {
        zoom = zoomProvincia;
        latitud = latitudProvincia;
        longitud = longitudProvincia;
    }
    var latlng = new google.maps.LatLng(latitud, longitud);
    mapa.setCenter(latlng, zoom);
    //recalcularMoverRatonOZoom();
}

function LimpiarProvincias() {
    var provincia = document.getElementById('provincia');
    while (provincia.childNodes.length > 0) {
        provincia.removeChild(provincia.lastChild);
    }
    var option = document.createElement('option');
    var texto = document.createTextNode('Provincia');
    option.value="-1:"+latitudInicial+":"+longitudInicial;
    option.appendChild(texto);
    provincia.appendChild(option);
}

function LimpiarPoblaciones() {
    var poblacion = document.getElementById('poblacion');
    while (poblacion.childNodes.length > 0) {
        poblacion.removeChild(poblacion.lastChild);
    }
    var option = document.createElement('option');
    option.value = "-1: : ";
    var texto = document.createTextNode('Población');
    option.appendChild(texto);
    poblacion.appendChild(option);
}

function obtenerMarcadoresProvincias() {
	//alert(nuevoFiltro);
//    if (!nuevoFiltro) return;
	//alert(2);
    var pl = new SOAPClientParameters();
    pl.add('tipoVivienda', document.getElementById('tipoVivienda').value);
    pl.add('precioHasta', document.getElementById('precioHasta').value);
    pl.add('dormitorios', document.getElementById('dormitorios').value);
    pl.add('supDesde', document.getElementById('superficieDesde').value);
    pl.add('banyos', document.getElementById('banyos').value);
    pl.add('soloGeolocalizadas', document.getElementById('soloGeolocalizadas').checked);
    SOAPClient.invoke(
        wsdl,
        'obtenerListaProvinciasNumeroInmuebles',
        pl,
        asincrono,
        obtenerMarcadoresProvinciasCallback
    );
}

function obtenerMarcadoresProvinciasCallback(r) {
    marcadoresProvincias = [];
    var provincias = document.getElementById('provincia');
	//alert(dump(r));
    for (var i = 0; i < r.length; i++) {
        var info = r[i];
        crearMarcadorProvincia(info);
    }
    mmProvincias.clearMarkers();
    mmProvincias.addMarkers(marcadoresProvincias, 0, zoomProvincia-1);
    mmProvincias.refresh();    
    obtenerListaPoblaciones();
}

function obtenerTiposInmueble() {
    var pl = new SOAPClientParameters();
    SOAPClient.invoke(
        wsdl,
        'obtenerListaTiposInmueble',
        pl,
        asincrono,
        obtenerTiposInmuebleCallback
    );        
}

function obtenerTiposInmuebleCallback(r) {
    var tipos = document.getElementById('tipoVivienda');
    while (tipos.childNodes.length > 0) {
        tipos.removeChild(tipos.lastChild);
    }
    var option = document.createElement('option');
    var texto = document.createTextNode('Tipo de inmueble');
    option.value = -1;
    option.appendChild(texto);
    tipos.appendChild(option);
    for (var i = 0; i < r.length; i++) {
        option = document.createElement('option');
        option.value = r[i][0];
        texto = document.createTextNode(r[i][1]);
        option.appendChild(texto);
        tipos.appendChild(option)
    }
}


function obtenerMarcadoresPoblaciones() {
    var pl = new SOAPClientParameters();
    pl.add('tipoVivienda', document.getElementById('tipoVivienda').value);
    pl.add('precioHasta', document.getElementById('precioHasta').value);
    pl.add('dormitorios', document.getElementById('dormitorios').value);
    pl.add('supDesde', document.getElementById('superficieDesde').value);
    pl.add('banyos', document.getElementById('banyos').value);
    pl.add('soloGeolocalizadas', document.getElementById('soloGeolocalizadas').checked);
    SOAPClient.invoke(
        wsdl,
        'obtenerListaMarcadoresPoblaciones',
        pl,
        asincrono,
        obtenerMarcadoresPoblacionesCallback
    );           
}

function obtenerMarcadoresPoblacionesCallback(r) {
    marcadoresPoblaciones = [];
    for (var i = 0; i < r.length; i++) {
        crearMarcadorPoblacion(r[i]);
    }
    mmPoblaciones.clearMarkers();
    mmPoblaciones.addMarkers(marcadoresPoblaciones, zoomProvincia, zoomPoblacion-1);
    mmPoblaciones.refresh();
}

function crearMarcadorPoblacion(info) {
    var latlng = new google.maps.LatLng(info[3], info[4]);
    var icono = new google.maps.Icon(google.maps.DEFAULT_ICON);
    icono.shadow = '';
    icono.image = imagen_poblacion;
    icono.iconSize = new google.maps.Size(imagen_poblacion_tamx, imagen_poblacion_tamy);
    icono.iconAnchor = new google.maps.Point(imagen_poblacion_tamx/2, imagen_poblacion_tamy);
    var marcador = new google.maps.Marker(latlng, {icon: icono});
    var enlace = 'modules.php?name=2mano&pob='+info[0]+'&latitud='+mapa.getCenter().lat().toString()+'&longitud='+mapa.getCenter().lng().toString()+'&zoom='+mapa.getZoom().toString();
    if (document.getElementById('precioHasta').value != -1)
        enlace += '&precioHasta=' + document.getElementById('precioHasta').value;
    if (document.getElementById('superficieDesde').value != -1)
        enlace += '&supDesde=' + document.getElementById('superficieDesde').value;
    if (document.getElementById('dormitorios').value != -1)
        enlace += '&minHabitaciones=' + document.getElementById('dormitorios').value;
    if (document.getElementById('banyos').value != -1)
        enlace += '&minBanyos=' + document.getElementById('banyos').value;
    if (document.getElementById('tipoVivienda').value != -1)
        enlace += '&tipoVivienda=' + document.getElementById('tipoVivienda').value;
    google.maps.Event.addListener(marcador, 'mouseover', function() {
        marcador.openExtInfoWindow(
              mapa,
              "custom_info_window_red",
               "<div class='title'>"+info[1]+"</div>"+
              "<div class='section1'>"+info[2]+"</b> Inmuebles</div>"+
			  '<div align="center"><a class="enlace_ficha" onclick="irBusqueda('+info[5]+','+info[0]+')" href="#">Ver inmuebles</a></div>',
			  "3"
            ); 
		//marcador.openInfoWindowHtml('<table><tr><td  align=center><b>'+info[1]+'</b>: <b>'+info[2]+'</b> inmuebles.</td></tr><tr>&nbsp;<td></td></tr><tr><td align=center><a class="enlace_ficha" onclick="irBusqueda('+info[5]+','+info[0]+')" href="#">Ver listado de inmuebles de esta poblaci&oacute;n</a></td></tr></table>');
        marcador.setImage(imagen_poblacion_brillante);
    });
    google.maps.Event.addListener(marcador, 'mouseout', function() {
        marcador.setImage(imagen_poblacion);
    });
    google.maps.Event.addListener(marcador, 'click', function() {
        mapa.setCenter(latlng, zoomPoblacion);
		mapa.closeExtInfoWindow();
    });
    marcadoresPoblaciones.push(marcador)
}

function obtenerListaPromociones() {
  
	var bordes = mapa.getBounds(); // Obtenemos las coordenadas actuales del mapa
    var ne = bordes.getNorthEast();
    var so = bordes.getSouthWest(); 
    var pl = new SOAPClientParameters();
    pl.add('norte', ne.lat());
    pl.add('sur', so.lat());
    pl.add('este', ne.lng());
    pl.add('oeste', so.lng());
    pl.add('tipoVivienda', document.getElementById('tipoVivienda').value);
    pl.add('precioHasta', document.getElementById('precioHasta').value);
    pl.add('dormitorios', document.getElementById('dormitorios').value);
    pl.add('supDesde', document.getElementById('superficieDesde').value);
    pl.add('banyos', document.getElementById('banyos').value);
    ++colaTareas;
	
    SOAPClient.invoke(
        wsdl,
        'obtenerListaPromociones',
        pl,
       asincrono,
	   obtenerListaPromocionesCallback
	  );    
}

function obtenerListaPromocionesCallback(r){
    if (nuevoFiltro) {
        presentesGeolocalizados = [];
        mmPromociones.clearMarkers();
    }
    marcadoresInmuebles = [];
    if (typeof(r.length) == "undefined")
        promocionesEncontradas = 0;
    else
        promocionesEncontradas = r.length;
    nuevosMarcadoresGeolocalizados = [];
    if (typeof(r.length) != "undefined") {
		
        //marcadoresInmuebles = new Array();
        for (var i = 0; i < r.length; i++) {
             var marcador = crearMarcadorPromocion(r[i]);
            if (presentesGeolocalizados[r[i][0]] == undefined) {
                presentesGeolocalizados[r[i][0]] = true;
                nuevosMarcadoresGeolocalizados.push(marcador);
				
            }

		}
		/*tabla.appendChild(tbody);*/
		//alert(nuevosMarcadoresGeolocalizados.length);
        mmPromociones.addMarkers(nuevosMarcadoresGeolocalizados, zoomPoblacion);
		
        if ((nuevosMarcadoresGeolocalizados.length > 0) || nuevoFiltro) {
            mmPromociones.refresh();
        }
		
        nuevosMarcadoresGeolocalizados = [];
		
    }
    nuevoFiltro = false;
	
	 //document.getElementById('contadorPromoGeolocalizadas').innerHTML = parseInt(r.length);
	 
     --colaTareas;
}

function crearMarcadorPromocion(info) {
    var latlng = new google.maps.LatLng(info[3], info[4]);
     var imagen, imagen_brillante, imagen_tamx, imagen_tamy;
    imagen = imagen_promo;
    imagen_brillante = imagen_promo_brillante;
    imagen_tamx = imagen_promo_tamx;
    imagen_tamy = imagen_promo_tamy;
	var enlace="";
	var icono = new google.maps.Icon(google.maps.DEFAULT_ICON);
	icono.image = imagen;
    icono.iconSize = new google.maps.Size(imagen_tamx, imagen_tamy);
    icono.iconAnchor = new google.maps.Point(imagen_tamx/2, imagen_tamy);
  	icono.shadow = '';
    var marcador = new google.maps.Marker(latlng, {icon: icono});
//alert(dump(info));
	var nombre=info[1];
	var descripcion=info[7];
	if(info[6]!="")
	var foto=info[6];
	else var foto="modules/2mano/imagen_no_disponible.jpg";
	var enlace="modules.php?name=promociones&file=mostrar1&id="+info[0]+'&latitud='+info[3]+'&longitud='+info[4];
	var enlace1="modules.php?name=obra_nueva&promo="+info[0]+'&latitud='+info[3]+'&longitud='+info[4];
	    var promo = '<div class="foto">\
                    <img class="imagendeficha" src="http://www.aquicasa.com/'+foto+'" />\
                </div>\
                <div class="div_datos">\
                    <div class="datos">\
                        <span style="font-weight: bolder; text-align:center">'+nombre+'</span><br /><br>\
                         '+info[2]+'\
                         '+info[5]+'\
                    </div>\
				</div>\
                <div class="descripcion">\
                    <span>'+descripcion.substr(0,120)+'...</span>\
                </div>\
                <a class="enlace_ficha" href="'+enlace+'">Ver Ficha Promocion</a><br><br>\
				<a class="enlace_ficha" href="'+enlace1+'">Ver Inmuebles de la Promocion</a>';
			
   
    google.maps.Event.addListener(marcador, 'click', function() {
        //marcador.openInfoWindowHtml(promo);
		document.getElementById('buscador_mapa').style.display="none";
		document.getElementById('ir_a_mapa').style.display="none";
	   document.getElementById('ficha_mapa').style.display="block";
		document.getElementById('info_window').innerHTML=promo;
		document.getElementById('precio_ficha_mapa').innerHTML="Precio desde: "+number_format(info[9],2,",",".")+" &euro;";
    });
	
	
  
  google.maps.Event.addListener(marcador, 'mouseover', function() {
        marcador.setImage(imagen_brillante);
    });
    google.maps.Event.addListener(marcador, 'mouseout', function() {
        /*document.getElementById(marcador.id).className="fila";*/
        marcador.setImage(imagen);
    });
   
	
     return marcador;
}

function generarListaDePrecios() {
    var precios = document.getElementById('precioHasta');
    for (var i = 0; i < precios.childNodes.length; i++) {
        precios.removeChild(precios.lastChild);
    }
    var texto = document.createTextNode('Precio Máximo');
    var opcion = document.createElement('option');
    opcion.value = -1;
    opcion.appendChild(texto);
    precios.appendChild(opcion);
    for (var i = 50000; i <= 600000; i += 10000) {
        var opcion = document.createElement('option');
        opcion.value = i;
        var numero = new oNumero(i);
        texto = document.createTextNode(numero.formato(0, true)+String.fromCharCode(8364));
        opcion.appendChild(texto);
        precios.appendChild(opcion)
    }
    
    // Establecemos el valor anterior, o el valor por defecto en caso de no ser posible
    if (precioHastaActual == -1) {
        precios.selectedIndex = 0;
    }
    else {
        for (var i = 1; i < precios.childNodes.length; i++) {
            if (precios.childNodes[i].value == precioHastaActual) {
                precios.selectedIndex = i;
            }
        }
        if (precios.selectedIndex == precios.childNodes.length) {
            precios.selectedIndex = 0;
        }
    }
}
/*
function obtenerCantidadInmueblesSinGeolocalizacion(){
    if (document.getElementById('soloGeolocalizadas').checked) {
        mmInmueblesSinGeolocalizar.clearMarkers();
        document.getElementById('contadorNoGeolocalizadas').innerHTML = 0;
        return false;
    }
    var bordes = mapa.getBounds(); // Obtenemos las coordenadas actuales del mapa
    var ne = bordes.getNorthEast();
    var so = bordes.getSouthWest(); 
    var pl = new SOAPClientParameters();
    pl.add('norte', ne.lat());
    pl.add('sur', so.lat());
    pl.add('este', ne.lng());
    pl.add('oeste', so.lng());
    pl.add('tipoVivienda', document.getElementById('tipoVivienda').value);
    pl.add('precioHasta', document.getElementById('precioHasta').value);
    pl.add('dormitorios', document.getElementById('dormitorios').value);
    pl.add('supDesde', document.getElementById('superficieDesde').value);
    pl.add('banyos', document.getElementById('banyos').value);
    SOAPClient.invoke(
        wsdl,
        'obtenerCantidadInmueblesSinGeolocalizar',
        pl,
        asincrono,
        obtenerCantidadInmueblesSinGeolocalizacionCallback
    );
}

function obtenerCantidadInmueblesSinGeolocalizacionCallback(r) {
    document.getElementById('contadorNoGeolocalizadas').innerHTML = parseInt(r);
}

function obtenerCantidadPromocionesSinGeolocalizacion(){
    if (document.getElementById('soloGeolocalizadas').checked) {
        mmInmueblesSinGeolocalizar.clearMarkers();
        document.getElementById('contadorPromoNoGeolocalizadas').innerHTML = 0;
        return false;
    }
    var bordes = mapa.getBounds(); // Obtenemos las coordenadas actuales del mapa
    var ne = bordes.getNorthEast();
    var so = bordes.getSouthWest(); 
    var pl = new SOAPClientParameters();
    pl.add('norte', ne.lat());
    pl.add('sur', so.lat());
    pl.add('este', ne.lng());
    pl.add('oeste', so.lng());
       SOAPClient.invoke(
        wsdl,
        'obtenerCantidadPromocionesSinGeolocalizar',
        pl,
        asincrono,
        obtenerCantidadPromocionesSinGeolocalizacionCallback
    );
}

function obtenerCantidadPromocionesSinGeolocalizacionCallback(r) {
    document.getElementById('contadorPromoNoGeolocalizadas').innerHTML = parseInt(r);
}*/

function calcularMarcadoresInmuebles(){
    // Borramos los marcadores actuales
    if (mapa.getZoom() < zoomPoblacion) {
        /*var tbody = document.getElementById('bodyResultados');
        if (tbody != undefined) {
            while (tbody.childNodes.length > 0) {
                tbody.removeChild(tbody.lastChild);
            }
        }*/
        return;
    }//alert("hola");
    var bordes = mapa.getBounds(); // Obtenemos las coordenadas actuales del mapa
    var ne = bordes.getNorthEast();
    var so = bordes.getSouthWest(); 
    var pl = new SOAPClientParameters();
    pl.add('norte', ne.lat());
    pl.add('sur', so.lat());
    pl.add('este', ne.lng());
    pl.add('oeste', so.lng());
    pl.add('tipoVivienda', document.getElementById('tipoVivienda').value);
    pl.add('precioHasta', document.getElementById('precioHasta').value);
    pl.add('dormitorios', document.getElementById('dormitorios').value);
    pl.add('supDesde', document.getElementById('superficieDesde').value);
    pl.add('banyos', document.getElementById('banyos').value);
    ++colaTareas;
    SOAPClient.invoke(
        wsdl,
        'obtenerListaInmuebles',
        pl,
        asincrono,
        calcularMarcadoresInmueblesCallback
    );
}

function calcularMarcadoresInmueblesCallback(r){
    if (nuevoFiltro) {
        presentesGeolocalizados = [];
        mmInmuebles.clearMarkers();
    }
    marcadoresInmuebles = [];
	
	var encontradas = document.getElementById('encontradas');   
   /* if (typeof(r.length) == "undefined")
        inmueblesEncontrados = 0;
    else
        inmueblesEncontrados = r.length;*/
    /*var tabla = document.getElementById('tablaResultados');
    while (tabla.childNodes.length > 0) {
        tabla.removeChild(tabla.lastChild);
    }
    var thead = document.createElement('thead');
    var trh = document.createElement('tr');
    var tituloSup = document.createElement('th');
    tituloSup.className="cabecera_lista";
    tituloSup.appendChild(document.createTextNode('Sup.'))
    tituloSup.style.width="50%";
    tituloSup.onclick = reordenarGridPorSuperficie;
    trh.appendChild(tituloSup);
    var tituloHab = document.createElement('th');
    tituloHab.className="cabecera_lista";
    tituloHab.appendChild(document.createTextNode('Hab.'));
    tituloHab.style.width="5%";
    tituloHab.onclick = reordenarGridPorHabitaciones;
    trh.appendChild(tituloHab);
    var tituloBan = document.createElement('th');
    tituloBan.className="cabecera_lista";
    tituloBan.appendChild(document.createTextNode('Ba'+String.fromCharCode(241)+'os'));
    tituloBan.style.width="5%";
    tituloBan.onclick = reordenarGridPorBanyos;
    trh.appendChild(tituloBan);
    var tituloPrecio = document.createElement('th');
    tituloPrecio.className="cabecera_lista";
    tituloPrecio.appendChild(document.createTextNode('Precio'));
    tituloPrecio.style.width="39%";
    tituloPrecio.onclick = reordenarGridPorPrecio;
    trh.appendChild(tituloPrecio);
    thead.appendChild(trh);
    tabla.appendChild(thead);
    var tbody = document.createElement('tbody');
    tbody.id = 'bodyResultados';*/
    nuevosMarcadoresGeolocalizados = [];
    if (typeof(r.length) != "undefined") {
        //marcadoresInmuebles = new Array();
        for (var i = 0; i < r.length; i++) {
            // Vamos a crear la linea en los resultados
            /*var tr = document.createElement('tr');
            tr.className = 'fila'
            tr.id = r[i][0];*/
            var marcador = crearMarcadorInmueble(r[i]);
            if (presentesGeolocalizados[r[i][0]] == undefined) {
                presentesGeolocalizados[r[i][0]] = true;
                nuevosMarcadoresGeolocalizados.push(marcador);
            }
            /*var sup = document.createElement('td');
            sup.className="celda";
            var metros = document.createElement('span');
            metros.appendChild(document.createTextNode(r[i][2]));
            var m = document.createElement('span');
            m.appendChild(document.createTextNode(' m'))
            var cuadrado = document.createElement('span');
            cuadrado.style.verticalAlign="super";
            cuadrado.style.fontSize = 'xx-small';
            cuadrado.appendChild(document.createTextNode('2'));
            sup.appendChild(metros);
            sup.appendChild(m);
            sup.appendChild(cuadrado);
            tr.appendChild(sup)
            var hab = document.createElement('td');
            hab.className="celda";
            hab.appendChild(document.createTextNode(r[i][7]));
            tr.appendChild(hab);
            var banyos = document.createElement('td');
            banyos.className="celda";
            banyos.appendChild(document.createTextNode(r[i][3]));
            tr.appendChild(banyos);
            var precio = document.createElement('td');
            precio.className="celda";
            var numero = new oNumero(r[i][1]);
            precio.appendChild(document.createTextNode(numero.formato(0, true)+String.fromCharCode(8364)));
            tr.appendChild(precio);
            var clase = tr.className;
            var id = r[i][0];
            var estado = r[i][10];
            tr.onclick=function(info) {
                var enlace = 'modules.php?name=';
                if (estado == 1) {
                    enlace += 'promociones';
                }
                else {
                    enlace += '2mano';
                }
                enlace += '&file=mostrar&id='+id+'&latitud='+mapa.getCenter().lat().toString()+'&longitud='+mapa.getCenter().lng().toString()+'&zoom='+mapa.getZoom().toString();
                document.location = enlace;
            }
            tbody.appendChild(tr);
            */
		}
		/*tabla.appendChild(tbody);*/
        mmInmuebles.addMarkers(nuevosMarcadoresGeolocalizados, zoomPoblacion);
        if ((nuevosMarcadoresGeolocalizados.length > 0) || nuevoFiltro) {
            mmInmuebles.refresh();
        }
        nuevosMarcadoresGeolocalizados = [];
    }
    nuevoFiltro = false;
	if(contadas==0 || contadas==1){
/*
    document.getElementById('contadorGeolocalizadas').innerHTML = parseInt(r.length) + parseInt(document.getElementById('contadorGeolocalizadas').innerHTML);
*/
	contadas++;
	}
    --colaTareas;
}


function calcularMarcadoresMasInmuebles(){
    // Borramos los marcadores actuales
    if (mapa.getZoom() < zoomPoblacion) {
        /*var tbody = document.getElementById('bodyResultados');
        if (tbody != undefined) {
            while (tbody.childNodes.length > 0) {
                tbody.removeChild(tbody.lastChild);
            }
        }*/
        return;
    }
    var bordes = mapa.getBounds(); // Obtenemos las coordenadas actuales del mapa
    var ne = bordes.getNorthEast();
    var so = bordes.getSouthWest(); 
    var pl = new SOAPClientParameters();
    pl.add('norte', ne.lat());
    pl.add('sur', so.lat());
    pl.add('este', ne.lng());
    pl.add('oeste', so.lng());
    pl.add('tipoVivienda', document.getElementById('tipoVivienda').value);
    pl.add('precioHasta', document.getElementById('precioHasta').value);
    pl.add('dormitorios', document.getElementById('dormitorios').value);
    pl.add('supDesde', document.getElementById('superficieDesde').value);
    pl.add('banyos', document.getElementById('banyos').value);
    ++colaTareas;
    SOAPClient.invoke(
        wsdl,
        'obtenerListaMasInmuebles',
        pl,
        asincrono,
        calcularMarcadoresMasInmueblesCallback
    );
}

function calcularMarcadoresMasInmueblesCallback(r){
    if (nuevoFiltro) {
        presentesGeolocalizados = [];
        mmInmuebles.clearMarkers();
    }
    marcadoresInmuebles = [];
    var encontradas = document.getElementById('encontradas');   
   /* if (typeof(r.length) == "undefined")
        inmueblesEncontrados = 0;
    else
        inmueblesEncontrados = r.length;*/
   var num=0;
    nuevosMarcadoresGeolocalizados = [];
    if (typeof(r.length) != "undefined") {
        //marcadoresInmuebles = new Array();
        for (var i = 0; i < r.length; i++) {
      num= parseInt(num)+ parseInt(r[i][3]);
	  
            var marcador = crearMarcadorMasInmueble(r[i]);
            if (presentesGeolocalizados[r[i][0]] == undefined) {
                presentesGeolocalizados[r[i][0]] = true;
                nuevosMarcadoresGeolocalizados.push(marcador);
				
            }

		}
		/*tabla.appendChild(tbody);*/
        mmInmuebles.addMarkers(nuevosMarcadoresGeolocalizados, zoomPoblacion);
        if ((nuevosMarcadoresGeolocalizados.length > 0) || nuevoFiltro) {
            mmInmuebles.refresh();
        }
        nuevosMarcadoresGeolocalizados = [];
		
		
    }
    nuevoFiltro = false;
	if(contadas==0 || contadas==1){
/*
    document.getElementById('contadorGeolocalizadas').innerHTML = parseInt(num) + parseInt(document.getElementById('contadorGeolocalizadas').innerHTML);
*/
	contadas++
	}
    --colaTareas;
}



function obtenerNumeroHabitaciones() {

    var habitaciones = document.getElementById('dormitorios');
    while (habitaciones.childNodes.length > 0) {
        habitaciones.removeChild(habitaciones.lastChild);
    }
    var option = document.createElement('option');
    option.value = -1;
    option.appendChild(document.createTextNode('Mínimo Habitaciones'));
    habitaciones.appendChild(option);
    for (var i = 0; i < 7; i++) {
        option = document.createElement('option');
        option.value = i;
        option.appendChild(document.createTextNode(i));
        habitaciones.appendChild(option);
    }

/*   var bordes = mapa.getBounds(); // Obtenemos las coordenadas actuales del mapa
    var ne = bordes.getNorthEast();
    var so = bordes.getSouthWest(); 
    var pl = new SOAPClientParameters();
    pl.add('norte', ne.lat());
    pl.add('sur', so.lat());
    pl.add('este', ne.lng());
    pl.add('oeste', so.lng());
    SOAPClient.invoke(
        wsdl,
        'obtenerCantidadesDormitoriosRegion',
        pl,
        asincrono,
        obtenerNumeroHabitacionesCallback
    );       */
}

function obtenerNumeroHabitacionesCallback(r) {
    var habitaciones = document.getElementById('dormitorios');
    while (habitaciones.childNodes.length > 0) {
        habitaciones.removeChild(habitaciones.lastChild);
    }
    var option = document.createElement('option');
    option.value = -1;
    option.appendChild(document.createTextNode('Mínimo Habitaciones'));
    habitaciones.appendChild(option);
    for (var i = 0; i < r.length; i++) {
        option = document.createElement('option');
        option.value = r[i][0];
        option.appendChild(document.createTextNode(r[i][0]));
        habitaciones.appendChild(option);
    }
}

function obtenerNumeroBanyos() {

 var banyos = document.getElementById('banyos');
    while (banyos.childNodes.length > 0) {
        banyos.removeChild(banyos.lastChild);
    }
    var option = document.createElement('option');
    option.value = -1;
    option.appendChild(document.createTextNode('Mínimo Baños'));
    banyos.appendChild(option);
    for (var i = 0; i < 6; i++) {
        option = document.createElement('option');
        option.value = i;
        option.appendChild(document.createTextNode(i));
        banyos.appendChild(option);
    }


/*   var bordes = mapa.getBounds(); // Obtenemos las coordenadas actuales del mapa
    var ne = bordes.getNorthEast();
    var so = bordes.getSouthWest(); 
    var pl = new SOAPClientParameters();
    pl.add('norte', ne.lat());
    pl.add('sur', so.lat());
    pl.add('este', ne.lng());
    pl.add('oeste', so.lng());
    SOAPClient.invoke(
        wsdl,
        'obtenerCantidadesBanyosRegion',
        pl,
        asincrono,
        obtenerNumeroBanyosCallback
    );    */   
}

function obtenerNumeroBanyosCallback(r) {
    var banyos = document.getElementById('banyos');
    while (banyos.childNodes.length > 0) {
        banyos.removeChild(banyos.lastChild);
    }
    var option = document.createElement('option');
    option.value = -1;
    option.appendChild(document.createTextNode('Mínimo Baños'));
    banyos.appendChild(option);
    for (var i = 0; i < r.length; i++) {
        option = document.createElement('option');
        option.value = r[i][0];
        option.appendChild(document.createTextNode(r[i][0]));
        banyos.appendChild(option);
    }
}

function obtenerSuperficies() {
  //creado por oscar
   var superficie = document.getElementById('superficieDesde');
    while (superficie.childNodes.length > 0) {
        superficie.removeChild(superficie.lastChild);
    }
    var option = document.createElement('option');
    option.value = -1;
    option.appendChild(document.createTextNode('Superficie desde'));
    superficie.appendChild(option);
	var i = 0;
    while( i < 610 ){
        option = document.createElement('option');
        option.value = i;
        option.appendChild(document.createTextNode(i));
        superficie.appendChild(option);
		i= i + 10;
    }
  
  
  /* var pl = new SOAPClientParameters();
    pl.add('soloGeolocalizadas', document.getElementById('soloGeolocalizadas').checked);
    SOAPClient.invoke(
        wsdl,
        'obtenerSuperficiesRegion',
        pl,
        asincrono,
        obtenerSuperficiesCallback
    );        */
}

function obtenerSuperficiesCallback(r) {
    var superficie = document.getElementById('superficieDesde');
    while (superficie.childNodes.length > 0) {
        superficie.removeChild(superficie.lastChild);
    }
    var option = document.createElement('option');
    option.value = -1;
    option.appendChild(document.createTextNode('Superficie desde'));
    superficie.appendChild(option);
    for (var i = 0; i < r.length; i++) {
        option = document.createElement('option');
        option.value = r[i][0];
        option.appendChild(document.createTextNode(r[i][0]));
        superficie.appendChild(option);
    }
}

function calcularMarcadoresInmueblesSinGeolocalizacion() {
 
   if (document.getElementById('soloGeolocalizadas').checked) {
         mmInmueblesSinGeolocalizar.clearMarkers();
        return false;
    }
    var bordes = mapa.getBounds(); // Obtenemos las coordenadas actuales del mapa
    var ne = bordes.getNorthEast();
    var so = bordes.getSouthWest(); 
    var pl = new SOAPClientParameters();
    pl.add('tipoVivienda', document.getElementById('tipoVivienda').value);
    pl.add('precioHasta', document.getElementById('precioHasta').value);
    pl.add('dormitorios', document.getElementById('dormitorios').value);
    pl.add('supDesde', document.getElementById('superficieDesde').value);
    pl.add('banyos', document.getElementById('banyos').value);
	
    SOAPClient.invoke(
        wsdl,
        'obternerInmueblesNoGeolocalizados',
        pl,
        asincrono,
        calcularMarcadoresInmueblesSinGeolocalizacionCallback
    );    
}

function calcularMarcadoresInmueblesSinGeolocalizacionCallback(r) {
    var inmueblesNoGeolocalizadosEncontrados = 0;
	
    for (var i = 0; i < r.length; i++) {

        crearMarcadorInmueblesSinGeolocalizacion(r[i]);
        inmueblesNoGeolocalizadosEncontrados +=  parseInt(r[i][4]);
    }
    mmInmueblesSinGeolocalizar.clearMarkers();
    mmInmueblesSinGeolocalizar.addMarkers(marcadoresInmueblesSinGeolocalizar , zoomPoblacion);
    mmInmueblesSinGeolocalizar.refresh();
}

function crearMarcadorInmueblesSinGeolocalizacion(r) {
    var latlng = new google.maps.LatLng(r[5], r[6]);
    var icono = new google.maps.Icon(google.maps.DEFAULT_ICON);
    var bordes = mapa.getBounds(); // Obtenemos las coordenadas actuales del mapa
    var ne = bordes.getNorthEast();
    var so = bordes.getSouthWest();
    var zoom = mapa.getZoom();
    var centro = mapa.getCenter();
    var enlace = 'modules.php?name=2mano';
    enlace += '&pob='+r[3];
    if (document.getElementById('precioHasta').value != -1)
        enlace += '&precioHasta=' + document.getElementById('precioHasta').value;
    if (document.getElementById('superficieDesde').value != -1)
        enlace += '&supDesde=' + document.getElementById('superficieDesde').value;
    if (document.getElementById('dormitorios').value != -1)
        enlace += '&minHabitaciones=' + document.getElementById('dormitorios').value;
    if (document.getElementById('banyos').value != -1)
        enlace += '&minBanyos=' + document.getElementById('banyos').value;
    if (document.getElementById('tipoVivienda').value != -1)
        enlace += '&tipoVivienda=' + document.getElementById('tipoVivienda').value;
    enlace += '&geolocalizados=0';//&latitud='+mapa.getCenter().lat().toString()+'&longitud='+mapa.getCenter().lng().toString()+'&zoom='+mapa.getZoom().toString();
	
	 var enlace2 = 'modules.php?name=promociones';
    enlace2 += '&pob='+r[3];
	  enlace2 += '&geolocalizados=0';
	  var mensaje='<div class="sin_localizar">'+r[2]+'</div><br><br><div class="sin_localizar"> Hay <span id="numero">'+r[4]+'</span> Inmuebles ';
	  if(r[8]!=0)
	  mensaje +='y <span id="numero">'+r[8]+'</span> Promociones ';
	  
	  mensaje +='sin geolocalizar.</div><br><br><a class="enlace_ficha" href="'+enlace+'">Ver Inmuebles </a>';
	if(r[8]!=0)
	mensaje +='<tr><td align=center><a class="enlace_ficha" href="'+enlace2+'">Ver el listado de Promociones </a>';
	
	 
	  
      icono.shadow = '';
    icono.image = imagen_inmueble_sin_geolocalizar;
    icono.iconSize = new google.maps.Size(imagen_inmueble_sin_geolocalizar_tamx, imagen_inmueble_sin_geolocalizar_tamy);
    var marcador = new google.maps.Marker(latlng, {icon: icono});
    google.maps.Event.addListener(marcador, 'click', function() {
		document.getElementById('buscador_mapa').style.display="none";
		document.getElementById('ir_a_mapa').style.display="none";
	   document.getElementById('ficha_mapa').style.display="block";
	   	document.getElementById('precio_ficha_mapa').innerHTML="";
       document.getElementById('info_window').innerHTML=mensaje;
    });
	
    marcadoresInmueblesSinGeolocalizar.push(marcador);
}

/*function reconstruirGrid() {
    var encontradas = document.getElementById('encontradas');   
    if (typeof(marcadoresInmuebles.length) == "undefined")
        inmueblesEncontrados = 0;
    else
        inmueblesEncontrados = marcadoresInmuebles.length;
    var tabla = document.getElementById('tablaResultados');
    tabla.removeChild(tabla.lastChild);
    var tbody = document.createElement('tbody');
	tbody.id = 'bodyResultados';
	tabla.appendChild(tbody);
    if (typeof(marcadoresInmuebles.length) != "undefined") {
        for (var i = 0; i < marcadoresInmuebles.length; i++) {
            // Vamos a crear la linea en los resultados
            var tr = document.createElement('tr');
            tr.className = 'fila'
            tr.id = marcadoresInmuebles[i].id;
            var sup = document.createElement('td');
            sup.className = "celda";
            sup.style.width="50%";
            var metros = document.createElement('span');
            metros.appendChild(document.createTextNode(marcadoresInmuebles[i].superficie));
            var m = document.createElement('span');
            m.appendChild(document.createTextNode(' m'))
            var cuadrado = document.createElement('span');
            cuadrado.style.verticalAlign = "super";
            cuadrado.style.fontSize = 'xx-small';
            cuadrado.appendChild(document.createTextNode('2'));
            sup.appendChild(metros);
            sup.appendChild(m);
            sup.appendChild(cuadrado);
            tr.appendChild(sup)
            var hab = document.createElement('td');
            hab.className = "celda";
            hab.style.width="5%";
            hab.appendChild(document.createTextNode(marcadoresInmuebles[i].habitaciones));
            tr.appendChild(hab);
            var banyos = document.createElement('td');
            banyos.className = "celda";
            banyos.appendChild(document.createTextNode(marcadoresInmuebles[i].banyos));
            banyos.style.width="5%";
            tr.appendChild(banyos);
            var precio = document.createElement('td');
            precio.className = "celda";
            precio.style.width="40%";
            var numero = new oNumero(marcadoresInmuebles[i].precio);
            precio.appendChild(document.createTextNode(numero.formato(0, true) + String.fromCharCode(8364)));
            tr.appendChild(precio);
            var clase = tr.className;
            var id = marcadoresInmuebles[i][0];
            var estado = marcadoresInmuebles[i][10];
            tr.onmouseover = function(){
                this.className = clase + ' resaltado';
                for (var i = 0; i < mmInmuebles.grid_[mapa.getZoom()].length; i++) {
                    for (var j = 0; j < mmInmuebles.grid_[mapa.getZoom()][i]; j++) {
                        if (mmInmuebles.grid_[mapa.getZoom()][i][j].id == marcadoresInmuebles[i][0]) {
                            mmInmuebles.grid_[mapa.getZoom()][i][j].setImage(imagen_inmueble_brillante);
                        }
                    }
                }
            }
            tr.onmouseout = function(){
                this.className = clase;
                for (var i = 0; i < mmInmuebles.grid_[mapa.getZoom()].length; i++) {
                    for (var j = 0; j < mmInmuebles.grid_[mapa.getZoom()][i]; j++) {
                        if (mmInmuebles.grid_[mapa.getZoom()][i][j].id == marcadoresInmuebles[i][0]) {
                            mmInmuebles.grid_[mapa.getZoom()][i][j].setImage(imagen_inmueble);
                        }
                    }
                }
            }
            tr.onclick = function(info){
                var enlace = 'modules.php?name=';
                if (estado == 1) {
                    enlace += 'promociones';
                }
                else {
                    enlace += '2mano';
                }
                enlace += '&file=mostrar&id=' + id + '&latitud=' + mapa.getCenter().lat().toString() + '&longitud=' + mapa.getCenter().lng().toString() + '&zoom=' + mapa.getZoom().toString();
                document.location = enlace;
            }
            //tbody.appendChild(tr);
            if (nuevoFiltro) {
                mmInmuebles.clearMarkers(),
            }
            mmInmuebles.addMarkers(marcadoresInmuebles, zoomPoblacion);
            mmInmuebles.refresh();
        }
    }
}

function reordenarGridPorPrecio() {
    var tmp;
    if (ordenPrecio == 0)
        ordenPrecio = 1;
    else
        ordenPrecio = -ordenPrecio;    
    for (var i = 0; i < (marcadoresInmuebles.length - 1); i++) {
        for (var j = i+1; j < marcadoresInmuebles.length; j++) {
            if (ordenPrecio < 0) {
                if (marcadoresInmuebles[i].precio > marcadoresInmuebles[j].precio) {
                    tmp = marcadoresInmuebles[i];
                    marcadoresInmuebles[i] = marcadoresInmuebles[j];
                    marcadoresInmuebles[j] = tmp;
                }
            }
            else {
                if (marcadoresInmuebles[i].precio < marcadoresInmuebles[j].precio) {
                    tmp = marcadoresInmuebles[i];
                    marcadoresInmuebles[i] = marcadoresInmuebles[j];
                    marcadoresInmuebles[j] = tmp;
                }
            }
        }
    }
    reconstruirGrid()    
}

function reordenarGridPorSuperficie() {
    if (ordenSuperficie == 0)
        ordenSuperficie = 1;
    else
        ordenSuperficie = -ordenSuperficie;
    var tmp;
    for (var i = 0; i < (marcadoresInmuebles.length - 1); i++) {
        for (var j = i+1; j < marcadoresInmuebles.length; j++) {
            if (ordenSuperficie < 0) {
                if (marcadoresInmuebles[i].superficie > marcadoresInmuebles[j].superficie) {
                    tmp = marcadoresInmuebles[i];
                    marcadoresInmuebles[i] = marcadoresInmuebles[j];
                    marcadoresInmuebles[j] = tmp;
                }
            }
            else {
                if (marcadoresInmuebles[i].superficie < marcadoresInmuebles[j].superficie) {
                    tmp = marcadoresInmuebles[i];
                    marcadoresInmuebles[i] = marcadoresInmuebles[j];
                    marcadoresInmuebles[j] = tmp;
                }                
            }
        }
    }
    reconstruirGrid()
}

function reordenarGridPorBanyos() {
    if (ordenBanyos == 0) 
        ordenBanyos = 1;
    else
        ordenBanyos = -ordenBanyos;
    var tmp;
    for (var i = 0; i < (marcadoresInmuebles.length - 1); i++) {
        for (var j = i+1; j < marcadoresInmuebles.length; j++) {
            if (ordenBanyos < 0) {
                if (marcadoresInmuebles[i].banyos > marcadoresInmuebles[j].banyos) {
                    tmp = marcadoresInmuebles[i];
                    marcadoresInmuebles[i] = marcadoresInmuebles[j];
                    marcadoresInmuebles[j] = tmp;
                }
            }
            else {
                if (marcadoresInmuebles[i].banyos < marcadoresInmuebles[j].banyos) {
                    tmp = marcadoresInmuebles[i];
                    marcadoresInmuebles[i] = marcadoresInmuebles[j];
                    marcadoresInmuebles[j] = tmp;
                }                
            }
        }
    }
    reconstruirGrid()
}

function reordenarGridPorHabitaciones() {
    if (ordenHabitaciones == 0)
        ordenHabitaciones = 1;
    else
        ordenHabitaciones = -ordenHabitaciones;
    var tmp;
    for (var i = 0; i < (marcadoresInmuebles.length - 1); i++) {
        for (var j = i+1; j < marcadoresInmuebles.length; j++) {
            if (ordenHabitaciones < 0) {
                if (marcadoresInmuebles[i].habitaciones > marcadoresInmuebles[j].habitaciones) {
                    tmp = marcadoresInmuebles[i];
                    marcadoresInmuebles[i] = marcadoresInmuebles[j];
                    marcadoresInmuebles[j] = tmp;
                }
            }
            else {
                if (marcadoresInmuebles[i].habitaciones < marcadoresInmuebles[j].habitaciones) {
                    tmp = marcadoresInmuebles[i];
                    marcadoresInmuebles[i] = marcadoresInmuebles[j];
                    marcadoresInmuebles[j] = tmp;
                }                
            }
        }
    }
    reconstruirGrid()
}
*/
function calcularTodo() {
    var encontradas = document.getElementById('encontradas');
    generarListaDePrecios();
    obtenerListaProvincias();
    obtenerTiposInmueble();  
    obtenerNumeroHabitaciones();
    obtenerNumeroBanyos();
    obtenerSuperficies();
    obtenerTiposInmueble();
    calcularMarcadoresInmueblesSinGeolocalizacion();
    obtenerMarcadoresPoblaciones();
    obtenerMarcadoresProvincias();
    calcularMarcadoresInmuebles();
	calcularMarcadoresMasInmuebles();
	obtenerListaPromociones();
   //obtenerCantidadInmueblesSinGeolocalizacion();
	//obtenerCantidadPromocionesSinGeolocalizacion();
	
}

function recalcularMoverRatonOZoom() {
    /*document.getElementById('inmueblesEncontrados').style.visibility='hidden';
	document.getElementById('contadorGeolocalizadas').innerHTML = 0;
    document.getElementById('contadorNoGeolocalizadas').innerHTML = 0;
	document.getElementById('contadorPromoGeolocalizadas').innerHTML = 0;
	document.getElementById('contadorPromoNoGeolocalizadas').innerHTML = 0;*/
	contadas=0;
    if (nuevoFiltro) {
        obtenerListaProvincias();
        obtenerMarcadoresPoblaciones();
        obtenerMarcadoresProvincias();
		
        if (!document.getElementById('soloGeolocalizadas').checked) {
            calcularMarcadoresInmueblesSinGeolocalizacion();
        }else{
			 mmInmueblesSinGeolocalizar.clearMarkers();
		}        
    }
    if (mapa.getZoom() >= zoomPoblacion) {
       // document.getElementById('inmueblesEncontrados').style.visibility='visible';
       // obtenerCantidadInmueblesSinGeolocalizacion();
		//obtenerCantidadPromocionesSinGeolocalizacion();
        calcularMarcadoresInmuebles();
		calcularMarcadoresMasInmuebles();
		obtenerListaPromociones();
        espera();
    }
}

function setCookie() {
    var centro = mapa.getCenter();
    var latitud = centro.lat();
    var longitud = centro.lng();
    var textoCookie = nombreCookie+'=';
    textoCookie += latitud.toString()+'|';
    textoCookie += longitud.toString()+'|';
    textoCookie += mapa.getZoom()+'|';
	//alert(document.getElementById('provincia').value.toString());
    textoCookie += document.getElementById('provincia').value.toString()+'|';
    textoCookie += document.getElementById('poblacion').value.toString()+'|';
    textoCookie += document.getElementById('tipoVivienda').value.toString()+'|';
    textoCookie += document.getElementById('precioHasta').value.toString()+'|';
    textoCookie += document.getElementById('superficieDesde').value.toString()+'|';
    textoCookie += document.getElementById('dormitorios').value.toString()+'|';
    textoCookie += document.getElementById('banyos').value.toString()+'|';
    textoCookie += document.getElementById('soloGeolocalizadas').checked;
    if (duracionHorasCookie > 0) {
        var fecha = new Date();
        fecha.setTime(fecha.getTime()+duracionHorasCookie*60*60*1000);
        textoCookie += ';expires=' + fecha.toGMTString();
    }
    document.cookie=textoCookie;
	//alert(textoCookie);
    google.maps.Unload();
}

function rellenar_combo_pob(trozos){
	
	 estado['poblacion'] = parseInt(trozos[4]);          
           
	document.getElementById('poblacion').selectedIndex = 0;
            for (var i = 0; i < document.getElementById('poblacion').options.length; i++) {
				var poblacion=document.getElementById('poblacion').options[i].value.split(":");
                if (poblacion[0] == estado['poblacion']) {
                    document.getElementById('poblacion').selectedIndex = i;
                    break;
                }
            }
	}
	
	
function rellenar_combos(trozos){
	
			estado['latitud'] = parseFloat(trozos[0]);
            estado['longitud'] = parseFloat(trozos[1]);
            estado['zoom'] = parseInt(trozos[2]);
            estado['provincia'] = parseInt(trozos[3]);
            estado['poblacion'] = parseInt(trozos[4]);
            estado['tipoVivienda'] = parseInt(trozos[5]);
            estado['precioHasta'] = parseInt(trozos[6]);
            estado['supDesde'] = parseInt(trozos[7]);
            estado['minHab'] = parseInt(trozos[8]);
            estado['minBanyos'] = parseInt(trozos[9]);
            estado['soloGeolocalizadas'] = (trozos[10] == 'true' ? true : false);
           
		  		 
            document.getElementById('soloGeolocalizadas').checked = estado['soloGeolocalizadas'];
            soloGeolocalizadas = document.getElementById('soloGeolocalizadas').checked;
         
            document.getElementById('provincia').selectedIndex = 0;
            for (var i = 0; i < document.getElementById('provincia').options.length; i++) {
				
				var provincia=document.getElementById('provincia').options[i].value.split(":");
				    if (provincia[0] == estado['provincia']) {
                    document.getElementById('provincia').selectedIndex = i;
                    break;
                }
            }
            obtenerListaPoblaciones();
            setTimeout("rellenar_combo_pob(trozos);",2000);
            generarListaDePrecios();
            for (var i = 0; i < document.getElementById('precioHasta').options.length; i++) {
                if (document.getElementById('precioHasta').options[i].value == estado['precioHasta']) {
                    document.getElementById('precioHasta').selectedIndex = i;
                    break;
                }
            }
            
            for (var i = 0; i < document.getElementById('tipoVivienda').options.length; i++) {
                if (document.getElementById('tipoVivienda').options[i].value == estado['tipoVivienda']) {
                    document.getElementById('tipoVivienda').selectedIndex = i;
                    break;
                }
            }
            obtenerSuperficies();
            document.getElementById('superficieDesde').selectedIndex = 0;
            for (var i = 0; i < document.getElementById('superficieDesde').options.length; i++) {
				    if (document.getElementById('superficieDesde').options[i].value == estado['supDesde']) {
                    document.getElementById('superficieDesde').selectedIndex = i;
                    break;
                }
            }
            obtenerNumeroHabitaciones();
			
            document.getElementById('dormitorios').selectedIndex = 0;
            for (var i = 0; i < document.getElementById('dormitorios').options.length; i++) {
                if (document.getElementById('dormitorios').options[i].value == estado['minHab']) {
                    document.getElementById('dormitorios').selectedIndex = i;
                    break;
                }
            }
            obtenerNumeroBanyos();
            document.getElementById('banyos').selectedIndex = 0;
            for (var i = 0; i < document.getElementById('banyos').options.length; i++) {
                if (document.getElementById('banyos').options[i].value == estado['minBanyos']) {
                    document.getElementById('banyos').selectedIndex = i;
                    break;
                }
            }
            document.getElementById('soloGeolocalizadas').check = estado['soloGeolocalizadas'];
			   if (estado['soloGeolocalizadas'] != true) {
                calcularMarcadoresInmueblesSinGeolocalizacion();
               // obtenerCantidadInmueblesSinGeolocalizacion();
				//obtenerCantidadPromocionesSinGeolocalizacion();
            }
            obtenerMarcadoresProvincias();
            obtenerMarcadoresPoblaciones();
            calcularMarcadoresInmuebles();
			calcularMarcadoresMasInmuebles();
			obtenerListaPromociones();
            mapa.setCenter(new google.maps.LatLng(estado['latitud'], estado['longitud']), estado['zoom']);
	}
	
	
function cargarEstado() {
	obtenerTiposInmueble(); 
	obtenerListaProvincias();
	
    if (document.cookie.length>0) {
        // Existe una cookie
        inicioCookie = document.cookie.indexOf(nombreCookie+'=');
        if (inicioCookie != -1) {
            inicioCookie += nombreCookie.length+1;
            finCookie = document.cookie.indexOf(';',inicioCookie);
            if (finCookie == -1) {
                finCookie=document.cookie.length;
            }
			
            textoCookie = document.cookie.substring(inicioCookie, finCookie);
			//alert(dump(textoCookie));
            trozos = textoCookie.split("|");
              setTimeout("rellenar_combos(trozos);",1000);
			 
			
        }
        else {            
            calcularTodo();
        }
    }
    else {
        calcularTodo();
	}
    var GET = obtenerGet();
    if (GET['zoom'] != undefined) {
        mapa.setCenter(new google.maps.LatLng(GET['latitud'], GET['longitud']), GET['zoom']);
    }
    nuevoFiltro = false;
}

function onLoad() {
    if (google.maps.BrowserIsCompatible()) {
        mapa = new google.maps.Map2(document.getElementById('mapa'));
        mapa.enableScrollWheelZoom();
        mapa.addControl(new google.maps.LargeMapControl());
        mapa.addControl(new google.maps.MenuMapTypeControl());
        mapa.setCenter(new google.maps.LatLng(latitudInicial, longitudInicial), zoomInicial);
		//mm = new MarkerManager(mapa, {borderPadding: 50});
        window.setInterval(cargando, 50);
        mmProvincias = new MarkerManager(mapa, {borderPadding: 50});
        mmPoblaciones = new MarkerManager(mapa);
        mmInmuebles = new MarkerManager(mapa);
		mmPromociones = new MarkerManager(mapa);
        mmInmueblesSinGeolocalizar = new MarkerManager(mapa, {borderPadding: 50});
        soloGeolocalizadas = document.getElementById('soloGeolocalizadas').checked;
        nuevoFiltro = true;
        google.maps.Event.addListener(mapa, 'dragend', function() {
            recalcularMoverRatonOZoom();
        });
        google.maps.Event.addListener(mapa, 'zoomend', function() {
            recalcularMoverRatonOZoom();
        });
        google.maps.Event.addListener(mapa, 'moveend', function() {
            recalcularMoverRatonOZoom();
        });
        cargarEstado();
    }
}

function cargando() {
	
    if (colaTareas > 0) {
		
        if (!cargandoCreado) {
            var capa = document.createElement('div');
            document.body.appendChild(capa);
            capa.id = 'cargando';
			var objImagen = document.createElement("img");
			objImagen.src = "images/cargando.gif";
			capa.appendChild(objImagen);
			
            capa.style.top = document.getElementById('mapa').offsetHeight/2;
            capa.style.left = document.getElementById('mapa').offsetWidth/2 + capa.offsetWidth/2;
            cargandoCreado = true;
        }
    }
    else {
        if (document.getElementById('cargando')!=undefined) {
            document.body.removeChild(document.getElementById('cargando'));
        }
        cargandoCreado = false;
    }
}

var mapa, mmInmuebles, mmPromociones, mmProvincias, mmInmueblesSinGeolocalizar;
var wsdl = 'ws/server.php?wsdl';
var marcadoresProvincias = [];
var marcadoresPoblaciones = [];
var marcadoresInmuebles = [];
var marcadoresInmueblesSinGeolocalizar = [];
var marcadoresPromociones = [];
var zoomProvincia = 11;
var zoomPoblacion = 13;
var zoomInmueble = 17;
var precioHastaActual = -1;
var habitacionesActual = -1;
var superficieDesdeActual = -1;
var tipoActual = -1;
var imagen_inmueble = 'ws/imagenes/geolocalizado.png';
var imagen_inmueble_brillante = 'ws/imagenes/geolocalizado2.png'
var imagen_inmueble_tamx = 29;
var imagen_inmueble_tamy = 35;
var imagen_inmueble_sin_geolocalizar = 'ws/imagenes/sin_geolocalizar.png';
var imagen_inmueble_sin_geolocalizar_tamx = 40;
var imagen_inmueble_sin_geolocalizar_tamy = 29;
var imagen_poblacion = 'ws/imagenes/poblacion.png';
var imagen_poblacion_brillante = 'ws/imagenes/poblacion2.png';
var imagen_poblacion_tamx = 16;
var imagen_poblacion_tamy = 16;
var imagen_provincia = 'ws/imagenes/provincia.png';
var imagen_provincia_brillante = 'ws/imagenes/provincia2.png';
var imagen_provincia_tamx = 16;
var imagen_provincia_tamy = 16;
var imagen_promo = 'ws/imagenes/promociones.png';
var imagen_promo_brillante = 'ws/imagenes/promociones2.png';
var imagen_promo_tamx = 29;
var imagen_promo_tamy = 45;
var imagen_garaje = 'ws/imagenes/garaje.png';
var imagen_garaje_brillante = 'ws/imagenes/garaje2.png';
var imagen_garaje_tamx = 29;
var imagen_garaje_tamy = 35;
var imagen_local = 'ws/imagenes/local.png';
var imagen_local_brillante = 'ws/imagenes/local2.png';
var imagen_local_tamx = 29;
var imagen_local_tamy = 35;
var pensando = false;
var latitudInicial = 40.407;
var longitudInicial = -3.68;
var latitudProvincia = -1;
var longitudProvincia = -1;
var zoomInicial = 5;
var nombreCookie = 'estadoMapa';
var duracionHorasCookie = 2;
var inmueblesEncontrados = 0;
var promocionesEncontradas = 0;
var estado = [];
var asincrono = true;
var ordenPrecio = 0;
var ordenHabitaciones = 0;
var ordenBanyos = 0;
var ordenSuperficie = 0;
var soloGeolocalizadas = false;
var presentesGeolocalizados = [];
var nuevosMarcadoresGeolocalizados = [];
var nuevoFiltro;// = true;
var identificadorProvincia = -1;
var colaTareas = 0;
var cargandoCreado = false;
var contadas=0;
google.maps.Marker.prototype.id = -1;
google.maps.Marker.prototype.precio = -1;
google.maps.Marker.prototype.superficie = -1;
google.maps.Marker.prototype.habitaciones = -1;
google.maps.Marker.prototype.banyos = -1;
google.maps.Marker.prototype.descripcion = '';
google.maps.Marker.prototype.foto = '';
google.maps.Marker.prototype.tipo = 0;
google.maps.Marker.prototype.latitud = 0.0;
google.maps.Marker.prototype.longitud = 0.0;
google.maps.Marker.prototype.habitaciones = 0;

function oNumero(numero) {
    //Propiedades
    this.valor = numero || 0
    this.dec = -1;
    //Métodos
    this.formato = numFormat;
    this.ponValor = ponValor;
    //Definiciï¿½n de los mï¿½todos
    function ponValor(cad) {
        if (cad =='-' || cad=='+') return
        if (cad.length ==0) return
        if (cad.indexOf('.') >=0)
            this.valor = parseFloat(cad);
        else
            this.valor = parseInt(cad);
    }
    function numFormat(dec, miles) {
        var num = this.valor, signo=3, expr;
        var cad = ""+this.valor;
        var ceros = "", pos, pdec, i;
        for (i=0; i < dec; i++)
        ceros += '0';
        pos = cad.indexOf('.')
        if (pos < 0)
            cad = cad+"."+ceros;
        else {
            pdec = cad.length - pos -1;
            if (pdec <= dec) {
                for (i=0; i< (dec-pdec); i++)
                    cad += '0';
            }
            else {
                num = num*Math.pow(10, dec);
                num = Math.round(num);
                num = num/Math.pow(10, dec);
                cad = new String(num);
            }
        }
        pos = cad.indexOf('.')
        if (pos < 0) pos = cad.lentgh
        if (cad.substr(0,1)=='-' || cad.substr(0,1) == '+')
               signo = 4;
        if (miles && pos > signo)
            do{
                expr = /([+-]?\d)(\d{3}[\.\,]\d*)/
                cad.match(expr)
                cad=cad.replace(expr, RegExp.$1+','+RegExp.$2)
            } while (cad.indexOf(',') > signo)
            if (dec<0) cad = cad.replace(/\./,'')
                return cad;
    }
}

function obtenerGet() {
   	var get = location.href;
   	var tocho = get.split('?', 1)[1];
   	var GET = [];
   	if (tocho == undefined || tocho.length == 0) {
       	return GET;
	}
   	var trozos = tocho.split('&');
   	if (trozos.length < 1) {
       	return GET;
	}
   	for (var i = 0; i < trozos.length; i++) {
       	var valores = trozos[i].split('=');
       	GET[unescape(valores[0])] = unescape(valores[1]);
   	}
   	return GET;
}

function espera() {
    if (nuevoFiltro != false) {
        window.setTimeout(espera, 100);
    }
}

function irBusqueda(provincia, poblacion){
    var param = '';
    param = provincia.toString();
    (poblacion != undefined) ? param += ','+poblacion.toString() : param += ',';
    (document.getElementById('tipoVivienda').value != -1) ? param += ','+document.getElementById('tipoVivienda').options[document.getElementById('tipoVivienda').selectedIndex].innerHTML : param += ',';
    (document.getElementById('precioHasta').value != -1) ? param += ','+document.getElementById('precioHasta').value.toString() : param += ',';
    (document.getElementById('superficieDesde').value != -1) ? param += ','+document.getElementById('superficieDesde').value.toString() : param += ',';
    (document.getElementById('dormitorios').value != -1) ? param += ','+document.getElementById('dormitorios').value.toString() : param += ',';
    (document.getElementById('banyos').value != -1) ? param += ','+document.getElementById('banyos').value.toString() : param += ',';
    BusquedaMapa(param);
}

function ocultar_fichas(){
	document.getElementById('buscador_mapa').style.display='block';
	document.getElementById('ir_a_mapa').style.display='block';
	document.getElementById('ficha_mapa').style.display='none';
}
