// JavaScript Document
var geocoder;
var map;
var markersArray = [];
function initializeMap() {
  //alert('inicializa!');
	geocoder = new google.maps.Geocoder();
	var latlng = new google.maps.LatLng(40.39602, -3.55101);
	var myOptions = {
		zoom: 5,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	//alert('cargado!');
}

function codeAddress(tipoinmu) {
	var provincia = document.getElementById("ddn_provincia").options[document.getElementById("ddn_provincia").selectedIndex];
	var poblacion = document.getElementById("ddn_poblacion").options[document.getElementById("ddn_poblacion").selectedIndex];
	var zona = document.getElementById("ddn_zona").options[document.getElementById("ddn_zona").selectedIndex];
	var zoomNew = 5;
	var tipoloc;
	var valor;
	if(provincia.value != "" && provincia.value != "-")
	{
		tipoloc = 'provincia_id';
		valor = provincia.value;
		provincia = provincia.text;
		zoomNew = 7;
		if(poblacion.value != "" && poblacion.value != "-")
		{
			tipoloc = 'poblacion_id';
			valor = poblacion.value;
			poblacion = poblacion.text;
			zoomNew = 9;
			if(zona.value != "" && zona.value != "-")
			{
				tipoloc = 'zona_id';
				valor = zona.value;
				zona = zona.text;
				zoomNew = 14;
			}
			else
			{
				zona = '';
				zoomNew = 9;
			}
		}
		else
		{
			poblacion = '';
			zona = '';
		}

	}
	else
	{
		tipoloc = 'del_array';
		valor = 0;
		provincia = '';
		poblacion = '';
		zona = '';
		zoomNew = 5;
	}

	//var address = zona + ' ' + poblacion + ' ' + provincia + ' es';
	var address = poblacion + ' ' + provincia + ' es';
	address = address.replace(/\([^\)]*\)/g, "");
	requestInmuebles(tipoloc,valor,address,tipoinmu);
	geocoder.geocode( { 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			map.setCenter(results[0].geometry.location);
			map.setZoom(zoomNew);
		} else {
			//alert("Geocode was not successful for the following reason: " + status);
		}
	});
}

function requestInmuebles(campo,valor,locacion,tipoinmu)
{
	deleteMarkers();
	if (campo != 'del_array')
	{
		new Ajax.Request('/ajax/Inmuebles-Map-Get.php',
		{
			method: 'post',
			parameters: {tipo_loc: campo,id_loc: valor, tipo_inm: tipoinmu},
			onSuccess: function(transport){
				var theObject = transport.responseJSON;
				var inmuArray = theObject.array_inmuebles;
				if (theObject.array_inmuebles)
				{
					var direccion = '';
					var codpos = '';
					var referencia = '';
					var precio = '';
					var currency = '';
					var inmuid = '';
					var formattedAddress = '';
					for(i = 0; i<theObject.array_inmuebles.length; i++)
					{
            direccion = inmuArray[i][0];
						codpos = inmuArray[i][1];
						referencia = inmuArray[i][2];
						precio = inmuArray[i][4];
						currency = inmuArray[i][5];
						inmuid = inmuArray[i][6];
						//contentString = '<a href="index.php/Page,InmuebleView/RecordId,'+inmuid+'">Direccion: '+direccion+" - "+codpos;
						//contentString += '</a><br><a href="index.php/Page,InmuebleView/RecordId,'+inmuid+'">'+"Ref: "+referencia;
						contentString = '<a href="index.php/Page,InmuebleView/RecordId,'+inmuid+'">'+"Ref: "+referencia;
						contentString += "</a><br />Precio: "+precio+" "+currency;
						formattedAddress = direccion+', '+locacion;
						//if(i%1==0)
						//{
							//setTimeout("setMarks(formattedAddress,contentString);",1);
						//}
						//else
						//{
							setMarks(formattedAddress,contentString);
						//}
						contentString = '';
					}
					for (k = 0; k<markersArray.length; k++) {
					  markersArray[k].setMap(map);
					}
				}
			}
		});
	}
}

function setMarks(formAdd, contStr)
{
  
  geocoder.geocode( { 'address': formAdd}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var infowindow = new google.maps.InfoWindow({
              content: contStr
      });
      
      //var image = 'map_pin_fill_32x32.png';
      var marker = new google.maps.Marker({
          map: map, 
          position: results[0].geometry.location
      });
      
      google.maps.event.addListener(marker, 'click', function() {
              infowindow.open(map,marker);
      });
      
      markersArray.push(marker);
    } else {
      //alert("Geocode was not successful for the following reason: " + status);
    }
  });
}

function deleteMarkers()
{
	if (markersArray.length>0) {
		for (j = 0; j<markersArray.length; j++) {
			markersArray[j].setMap(null);
		}
		markersArray.length = 0;
		markersArray = [];
	}
}

