var infowindow;
var map;
var geocoder = new google.maps.Geocoder();
var mapa_iniciado = 0;
var inmuebles = [];
var inmuebles_referencias = [];	
var inmuebles_html = [];
var centro_mapa_lat;
var centro_mapa_lng;
var data_inmuebles;
var zoom_mapa = 12;
			
$(document).ready(function() { 
	initialize();
});
			
function initialize() {
	var myLatlng = new google.maps.LatLng(mapa_lat,mapa_long);
	var myOptions = {
		zoom: zoom_mapa,
		center: myLatlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		scrollwheel: false
	}
	
	mapa_iniciado = 1
	
	map = new google.maps.Map( document.getElementById("map_canvas"), myOptions );
	
	google.maps.event.addListener(map, 'dragend', function(event) {			cargarInmuebles(map.getCenter());	});	
	google.maps.event.addListener(map, 'zoom_changed', function(event) {	cargarInmuebles(map.getCenter());	});	
	
	codeAddress( mapa_lat+","+mapa_long );
	
	//cargarInmuebles();		
	
};

function codeAddress(localizacion) {			
	geocoder.geocode( { 'address': localizacion+"", 'language': "es", 'region': "es" }, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			//alert(results[0].geometry.location);
			centro_mapa_lat = results[0].geometry.location.lat();
			centro_mapa_lng = results[0].geometry.location.lng();	
			
			map.setCenter(results[0].geometry.location);
			if(zoom_mapa != ""){
				map.setZoom(zoom_mapa);
			}

		} else {
			//alert("Ubicación '"+localizacion +"' no encontrada");
		}
	});
}


function cargarInmuebles(geoLatLong){
	var aux			= ""+geoLatLong;
	aux 			= aux.replace("(", "");
	aux 			= aux.replace(")", "");
	var array_geo 	= aux.split(",");
	
	lat 	= array_geo[0];
	long 	= array_geo[1];
	
	//alert(" lat "+lat+" \n long"+long);
	
	var id_operacion		= $('#id_operacion').val();
	var id_tipo_inmueble	= $('#id_tipo_inmueble').val();				var id_subtipo_inmueble = $('#id_subtipo_inmueble').val();
	var id_provincia		= $('#id_provincia').val();					var id_poblacion		= $('#id_poblacion').val();
	
	var id_zona				= $('#id_zona').val();						var id_subzona			= $('#id_subzona').val();
	var id_tipo_obra		= $('#id_tipo_obra').val();					
	
	var habitaciones_minimo		= $('#habitaciones_minimo').val();		var habitaciones_maximo		= $('#habitaciones_maximo').val();
	var m2_minimo				= $('#m2_minimo').val();				var m2_maximo				= $('#m2_maximo').val();		
	var pvp_minimo				= $('#pvp_minimo').val();				var pvp_maximo				= $('#pvp_maximo').val();

	var ascensor				= $('#ascensor').val();					var procedente_embargo		= $('#procedente_embargo').val();
					
	var filtro = "?filtro=1&geoLatLong="+geoLatLong;
	
	if(id_operacion 		!= 0) {			filtro += "&id_operacion="+id_operacion;				}
	if(id_tipo_inmueble 	!= 0) {			filtro += "&id_tipo_inmueble="+id_tipo_inmueble;		}
	if(id_subtipo_inmueble 	!= 0) {			filtro += "&id_subtipo_inmueble="+id_subtipo_inmueble;	}
	if(id_provincia 		!= 0) {			filtro += "&id_provincia="+id_provincia;				}
	if(id_poblacion 		!= 0) {			filtro += "&id_poblacion="+id_poblacion;				}
	if(id_zona		 		!= 0) {			filtro += "&id_zona="+id_zona;							}
	if(id_subzona 			!= 0) {			filtro += "&id_subzona="+id_subzona;					}
	if(id_tipo_obra			!= 0) {			filtro += "&id_tipo_obra="+id_tipo_obra;				}				
	
	if(habitaciones_minimo	!= 0) {			filtro += "&habitaciones_minimo="+habitaciones_minimo;	}
	if(habitaciones_maximo	!= 0) {			filtro += "&habitaciones_maximo="+habitaciones_maximo;	}
	
	if(m2_minimo			!= 0) {			filtro += "&m2_minimo="+m2_minimo;						}
	if(m2_maximo			!= 0) {			filtro += "&m2_maximo="+m2_maximo;						}
	
	if(pvp_minimo			!= 0) {			filtro += "&pvp_minimo="+pvp_minimo;					}
	if(pvp_maximo			!= 0) {			filtro += "&pvp_maximo="+pvp_maximo;					}
	
	if(ascensor 			!= 0) {			filtro += "&ascensor="+ascensor;						}
	if(procedente_embargo 	!= 0) {			filtro += "&procedente_embargo="+procedente_embargo;	}
	
	downloadUrl(url_global+'ajax/mapa_inmuebles.php?provincia='+id_provincia+'&poblacion='+id_poblacion+'&zona='+id_zona+'&tipo='+id_tipo_inmueble+'&operacion='+id_operacion+'&habitaciones='+habitaciones_minimo+'&precio='+pvp_minimo+'&mapa_lat='+lat+"&mapa_long="+long, function(data) {	
		var html = "";
		if(data!=null){
			data_inmuebles = data;
			
			var markers = data.documentElement.getElementsByTagName("marker");						
			if(markers.length>0){
				for (var i = 0; i < markers.length; i++) {
					//miramos si el inmueble esta creado ya
					var encontrado = 0;
					for (inmueble in inmuebles_referencias){
						if( markers[i].getAttribute("name") == inmuebles_referencias[inmueble] ){
							encontrado = 1
						}
					}		
					if(encontrado == 0){
						var latlng = new google.maps.LatLng( parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")) );
						var marker = crearInm(markers[i].getAttribute("name"), latlng, markers[i].getAttribute("id_tipo_inmueble"), markers[i].getAttribute("id_tipo_obra"), markers[i].getAttribute("embargo"),markers[i].getAttribute("html"), markers[i].getAttribute("referencia"), markers[i].getAttribute("thumb"), markers[i].getAttribute("url"));
					
						html += "<tr><td><input type='checkbox' id='"+markers[i].getAttribute("name")+"_check' name='inmuebles_interes[]' value='"+markers[i].getAttribute("id_inmueble")+"' /></td>";
						html += "<td><a href='javascript:mostrar_datos_inmueble(\""+markers[i].getAttribute("name")+"\");' ><b>"+markers[i].getAttribute("name")+"</b></a></td>";	
						html += "<td>"+markers[i].getAttribute("habitaciones")+"</td>";	
						html += "<td>"+markers[i].getAttribute("superficie")+"</td>";
						html += "<td>"+markers[i].getAttribute("pvp")+"</td></tr>";
						html += "</tr>";
					}
				}
				html += "</table>";
			}	
		}		
	});		
}

function crearInm(name, latlng, id_tipo_inmueble, id_tipo_obra, embargo, html, referencia, thumb, url) {
	html  = html.replace("*", "<br />");
	html  = html.replace("*b*", "<b>");	
	html  = html.replace("*fb*", "</b>");
	html  = html.replace("*b*", "<b>");	
	html  = html.replace("*fb*", "</b>");			
	html  = html.replace("euros", "&euro;");
	thumb = thumb.replace("**", "&");
	thumb = thumb.replace("*", "=");	

	imagen = "segundamano.png";
	
	if(embargo==1){
		imagen = "embargos.png";
	}
	
	if(id_tipo_obra==2){
		imagen = "obranueva.png";
	}

	var html = "<div style='height:120px;'><table> <tr> <td colspan=2> <a href='"+url+"' target='_blank'>"+referencia+"</a> - <a href='"+url+"'  target='_blank' style='color:#06C'><b>Ver Inmueble</b></a>  </td> </tr> <tr> <td> <img src='"+thumb+"' style='margin-right:6px'/> </td> <td valign='top'>"+html+"</td> </tr> </table></div>";
	
	var image  = new google.maps.MarkerImage(url_global+'images/mapa/'+imagen, new google.maps.Size(32, 37), new google.maps.Point(0,0), new google.maps.Point(16, 16));				
	var marker = new google.maps.Marker({position: latlng, map: map, icon: image});
	google.maps.event.addListener(marker, "click", function() {
		if (infowindow) infowindow.close();
		infowindow = new google.maps.InfoWindow({content: html});
		infowindow.open(map, marker);
	});
	
	inmuebles.push(marker);
	inmuebles_referencias.push(name);
	inmuebles_html.push(html);

	return marker;
}

//

function ponerCentro(localizacion){
	geocoder.geocode( { 'address': localizacion+"", 'language': "es", 'region': "es" }, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			//alert(results[0].geometry.location);
			centro_mapa_lat = results[0].geometry.location.lat();
			centro_mapa_lng = results[0].geometry.location.lng();	
			
			map.setCenter(results[0].geometry.location);
			if(zoom_mapa != ""){
				map.setZoom(zoom_mapa);
			}
    		cargarInmuebles(centro_mapa_lat+", "+centro_mapa_lng);

		} else {
			//alert("Ubicación '"+localizacion +"' no encontrada");
		}
	});
}
