var map;
var mapCenter;
var propSelect = 0;

var C_ID_PROPIEDAD = "";

var C_MAPA_LATITUD  = 0;
var C_MAPA_LONGITUD = 0;
var C_MAPA_ZOOM 	= 0;

  
var indicadoresCarga = new Array();
var arrayPuntosPatroc = new Array();
var arrayPProps  = new Array();

function cambiarFoto(strRutaFoto)
{
	var imagen = document.getElementById("imagen_slideshow");
	imagen.src = strRutaFoto;
}
function setDivCargando(argID,argTop, argLeft)
{			
			// *** Inactivado por el momento ***
			return true;

			var div = document.createElement("div");
			
			div.setAttribute("id",argID);
			div.style.position = "absolute";
			div.style.top      = argTop;
			div.style.left     = argLeft;
				
			var img = document.createElement("img");
			img.setAttribute("src","../globales/imagenes/animacion_cargando.gif");
			
			div.appendChild(img);
			div.style.visibility = "visible";
			div.style.zIndex = "6";
			document.body.appendChild(div);
	
			indicadoresCarga.push(div);
}
		
function borrarIndicador(argID)
{	// *** Inactivado por el momento
	return true;

	for (var i = 0; i < indicadoresCarga.length; i++)
	{	
		if (indicadoresCarga[i] != null)
			if (indicadoresCarga[i].getAttribute("id") == argID)
			{	
				document.body.removeChild(indicadoresCarga[i]);
				indicadoresCarga[i] = null;
				break;
			}
	}
}





function selCiudad(KeyCiudad)
{
	document.location = "../mapa/ciudad" + KeyCiudad + ".html"; 	
}

function mostrarListaCiudades()
{	
	document.getElementById("lista_ciudades").style.visibility = "visible";
	document.getElementById("divWrapCiudades").style.visibility = "visible";
}


function cerrarListaCiudades()
{	
	document.getElementById("lista_ciudades").style.visibility = "hidden";
	document.getElementById("divWrapCiudades").style.visibility = "hidden";
}
function mostrarLogin()
{	
	document.getElementById("divWrapLogin").style.visibility = "visible";
	document.getElementById("divWrapLogin").style.display    = "block";
	document.getElementById("ventana_login").style.visibility = "visible";
	document.getElementById("ventana_login").style.display    = "block";
	
	// document.getElementById("main").style.opacity = "0.5";
	// document.getElementById("main").style.filter = "alpha(opacity=50)"; 
}

function cerrarLogin()
{	
	document.getElementById("divWrapLogin").style.visibility = "visible";
	document.getElementById("divWrapLogin").style.display    = "none";
	document.getElementById("ventana_login").style.visibility = "visible";
	document.getElementById("ventana_login").style.display    = "none";
	
	// document.getElementById("main").style.opacity = "1";
	// document.getElementById("main").style.filter = "alpha(opacity=100)";
}


function buscarPropiedades()
{
	
	cargarPropiedades(); 
	map.setCenter(mapCenter, 11);
};

function buscarEnSitio(SubZonaKey,Sitio_Lat, Sitio_Lng, Sitio_Zoom,Icono, Icono_Alto, Icono_Ancho)
{
	document.forms[0].SUBZONAKEY.value = SubZonaKey;
	cargarPropiedades(); 
	
	var sitioCenter = new GLatLng(Sitio_Lat, Sitio_Lng);
	map.setCenter(sitioCenter, Sitio_Zoom);
	
	if ((Icono != "") && (Icono != null))
		setIconoSitio(map, Icono, Icono_Ancho, Icono_Alto);
}

function setIconoSitio(mapa, argIcono, argIcono_Ancho, argIcono_Alto)
{
	var icono = new GIcon();
	icono.image = "../globales/imagenes/" + argIcono;
    icono.iconSize = new GSize(argIcono_Ancho, argIcono_Alto);
    icono.iconAnchor = new GPoint(argIcono_Ancho/2, argIcono_Alto/2);
     
	// Agregar el marker
	var mapCenter = mapa.getCenter();
	var markerIcono = new GMarker(mapCenter, icono);
	mapa.addOverlay(markerIcono);
}

function obtenerFiltro()
{
	var strFiltro = "";
	
	// **** Palabras clave ****
	if (document.forms[0].TXTBUSQUEDA.value)
	{		
		strFiltro += "FILTROTEXTO=" + document.forms[0].TXTBUSQUEDA.value;
	};
	
	if (document.forms[0].SUBZONAKEY.value)
	{	
		if (strFiltro)
			strFiltro += "&";
			
		strFiltro += "FILTROSSUBZONA=" + document.forms[0].SUBZONAKEY.value;
		strFiltro += "&TIPOSUBZONA=" + intSubZonaSeleccionada;
		
	};
	
	return strFiltro;
}





function resetMap()
{
	mapCenter = new GLatLng(C_MAPA_LATITUD, C_MAPA_LONGITUD);
    map.setCenter(mapCenter, C_MAPA_ZOOM);
    map.clearOverlays();
    document.forms[0].FILTROTIPOPROP.selectedIndex = 0;
    resetColoniasMunicipios();
    
    ocultarDiv("filtroprecio");
    var infoDiv = document.getElementById("resultados_busqueda_alt");
    infoDiv.innerHTML = "";
    
    ocultarDiv("divWrapTipoPropiedades");
	ocultarDiv("div_tipo_prop");
}

function cargarMapa() 
{
      if (GBrowserIsCompatible()) 
      {
        map = new GMap2(document.getElementById("map_canvas"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        mapCenter = new GLatLng(C_MAPA_LATITUD, C_MAPA_LONGITUD);
        map.setCenter(mapCenter, C_MAPA_ZOOM);
        
      }
      
      // **** Carga los sitios de interés
      //avanzarPagina(1);
      
      // **** Carga una propiedad que se
      // **** ha llamado mediante el url
      if (C_ID_PROPIEDAD != "")
        cargarPropiedad(C_ID_PROPIEDAD);
      
     
      
}

function mostrarInfoWindow(markerIndex, info, imagen, precio)
{	
	var html = textoInfoWindow(info, imagen, precio);
	markersProp[markerIndex].openInfoWindow(html);
}

		

function textoInfoWindow(idpropiedad, point, info, imagen, precio,tipo)
{	
	   
	return '<table class="DataTD4" border="0" width="300">' +
					'<tr>' +
						'<td valign="top">' + 
							'<a href="javascript:maximizar()">' +
								'<img src="' + imagen +'" border="0" >' +
							'</a>' + 
						'</td>' +
						'<td valign="top" rowspan="2">' + 
							'<font color="blue" size="3"><b>' + tipo +'</b></font><br>' 
											+ info.unescapeHTML()  + '<br><br>' +
						 					'<font size="2">$ ' +  precio + '</font>' +
						'</td>' +
					'</tr>' +
				    '<tr>' +
						'<td align="center">' + 
							'<p><a href="javascript:maximizar()">Mas detalles</a><br>' +
							 '<a href="javascript:buscarPuntosPatrocinados(' + "'" 
							+ idpropiedad + "'," + point.lat() + "," + point.lng() + ')">' +
							"Puntos de Interes</a> </p>" + 
						'</td>' +
					'</tr>' +
				'</table>';
}


function maximizar()
{
	var iw = map.getInfoWindow();
	iw.maximize();
	
}

function cerrarDetalles()
{	
	var iw = map.getInfoWindow();
	iw.restore();
	
}
function createMarker(idpropiedad, point, info, imagen, precio,tipo, icono, icono_alto, icono_ancho) 
{  
   
   var iconMarker = new GIcon(); 
   iconMarker.image 		   = '../globales/imagenes/' + icono;
   iconMarker.iconSize         = new GSize(icono_ancho, icono_alto);
   iconMarker.iconAnchor       = new GPoint(icono_ancho/2, icono_alto/2);
   iconMarker.infoWindowAnchor = new GPoint(icono_ancho/2, icono_alto/2);
	
   //var marker = new GMarker(point, customIcons["bar"]);
   var marker = new GMarker(point, iconMarker);
   
   var divInfoWindow = document.createElement("div");
   divInfoWindow.innerHTML = textoInfoWindow(idpropiedad,point, info, imagen, precio,tipo);
   
   var maxContentDiv = document.createElement('div');
   
   
   maxContentDiv.innerHTML = "Cargando...";
   
   GEvent.addListener(marker, 'click', function() {
      	  propSelect = idpropiedad;
          marker.openInfoWindowHtml(divInfoWindow, 
          						   {maxContent: maxContentDiv, 
             					    maxTitle: "Mas Información", 
             					    maxWidth: "200"});
         
         marker.setImage("../globales/imagenes/icono_tipopropiedad_visitada.png");
         
         
         CExecuteUrlSync("get","infostats.html," + idpropiedad);
         
   });
      
      
    var iw = map.getInfoWindow();
         GEvent.addListener(iw, "maximizeclick", function() {
        				 	
            GDownloadUrl("../propiedad/detalle_" + idpropiedad + ".html", function(data) {
              maxContentDiv.innerHTML = data;
            });
          });
	
	
    return marker;
}


// *********************************************
// *****   BUSQUEDA  ALTERNATIVA 
// *********************************************

// **** Obtiene las propiedades sin tomar en cuenta el precio
function obtenerFiltroAlt()
{
	var strFiltro = "";
	
	// **** Tipo de propiedad ****
	if (document.forms[0].FILTROTIPOPROP.selectedIndex != 0)
	{		
		strFiltro += "FILTROTIPOPROP=" + 
				document.forms[0].FILTROTIPOPROP.options[document.forms[0].FILTROTIPOPROP.selectedIndex].value;
	};
	
	// **** Municipio ****
	if (document.forms[0].FILTROMUNICIPIO.selectedIndex != 0)
	{		
		strFiltro += "&FILTROMUNICIPIO=" + 
				document.forms[0].FILTROMUNICIPIO.options[document.forms[0].FILTROMUNICIPIO.selectedIndex].value;
	};
	
	// **** Colonia ****
	if (document.forms[0].FILTROCOLONIA.selectedIndex != 0)
	{		
		strFiltro += "&FILTROCOLONIA=" + 
				document.forms[0].FILTROCOLONIA.options[document.forms[0].FILTROCOLONIA.selectedIndex].value;
	};
	
	
	return "?" + strFiltro;
}

function resetColoniasMunicipios()
{	
	document.forms[0].FILTROMUNICIPIO.selectedIndex = 0;
	cargarListaMunicipios();
	cargarListaColoniasAlt();
}

function cargarListaMunicipios()
{   
    map.clearOverlays();
   
   
    var url = "";
    
    var strFiltroTipo = "-1";
    if (document.forms[0].FILTROTIPOPROP.selectedIndex != 0)
    { 
    	strFiltroTipo = document.forms[0].FILTROTIPOPROP.options[
    											document.forms[0].FILTROTIPOPROP.selectedIndex].value; 
    };
    	
    url = "municipios_" + strFiltroTipo + ".html";  
     
    
    CDownloadUrl("get",url, function(data) {
       var xml = GXml.parse(data);
       var municipios = xml.documentElement.getElementsByTagName("municipio");
      
       document.forms[0].FILTROMUNICIPIO.options.length = 0;
      
       for (var i = 0; i < municipios.length; i++) 
       {	
       		// Datos
       		var idmunicipio  = municipios[i].getAttribute("key");
       		var nombre       = municipios[i].getAttribute("nombre");
       		
       		document.forms[0].FILTROMUNICIPIO.options[i] = new Option(nombre,idmunicipio);
       }
       
     });
     
}

function cargarListaColoniasAlt()
{   
	setDivCargando("cargarListaColonias","50%", "50%");
    map.clearOverlays();
   
   
    var url = "";
    
    var strFiltroTipo = "-1";
    if (document.forms[0].FILTROTIPOPROP.selectedIndex != 0)
    { 
    	strFiltroTipo = document.forms[0].FILTROTIPOPROP.options[
    											document.forms[0].FILTROTIPOPROP.selectedIndex].value; 
    };
    	
    if (document.forms[0].FILTROMUNICIPIO.selectedIndex == 0)
    	url = "coloniascompletas_" + strFiltroTipo + ".html"  
    else 
    	url = "colonias_" + document.forms[0].FILTROMUNICIPIO.options[
    											document.forms[0].FILTROMUNICIPIO.selectedIndex].value  +
    					"_" + strFiltroTipo + ".html"; 
    
    
    CDownloadUrl("get",url, function(data) {
       var xml = GXml.parse(data);
       var colonias = xml.documentElement.getElementsByTagName("colonia");
      
       document.forms[0].FILTROCOLONIA.options.length = 0;
      
       for (var i = 0; i < colonias.length; i++) 
       {	
       		// Datos
       		var idcolonia = colonias[i].getAttribute("key");
       		var nombre     = colonias[i].getAttribute("nombre");
       		
       		document.forms[0].FILTROCOLONIA.options[i] = new Option(nombre,idcolonia);
       }
       
     });
     
     setTimeout('borrarIndicador("cargarListaColonias");',3000);
}




function existePrecio(precio, arrPrecios)
{	
   var existe = false;
   for (var i = 0; i < arrPrecios.length; i++) 
   {
       	if (arrPrecios[i] == precio)
       	{
       		existe = true;
       		break;
       	}
   }
   
   return existe;
}

function ejecutarBusqueda(url,refrescarPrecios)
{
	CDownloadUrl("get",url, function(data) {
       var xml = GXml.parse(data);
       var markers = xml.documentElement.getElementsByTagName("propiedad");
       var arrPrecios = new Array();
       
       
       for (var i = 0; i < markers.length; i++) 
       {	
       		// Datos
       		var idpropiedad = markers[i].getAttribute("idpropiedad");
       		var foto        = markers[i].getAttribute("archivominiatura");
       		var banos       = markers[i].getAttribute("banos");
       		var recamaras   = markers[i].getAttribute("recamaras");
       		var domicilio   = markers[i].getAttribute("domicilio");
            var precio      = markers[i].getAttribute("precio");
            var preciosinf  = markers[i].getAttribute("preciosinformato");
            var tipo        = markers[i].getAttribute("tipopropiedaddesc");	
            
            var icono       = markers[i].getAttribute("icono");
            var icono_alto  = markers[i].getAttribute("icono_alto");
            var icono_ancho = markers[i].getAttribute("icono_ancho");
            
            var point = new GLatLng(parseFloat(markers[i].getAttribute("propiedad_lat")),
                                    parseFloat(markers[i].getAttribute("propiedad_lng")));
            
            // **** Agrega el marker al mapa
            var info = domicilio;                       
            var marker = createMarker(idpropiedad, point, info, foto, precio,tipo, 
            						  icono, icono_alto,icono_ancho);
            map.addOverlay(marker);
            
            // **** Conforma el filtro de precios
            if ( !existePrecio(parseFloat(preciosinf),arrPrecios) )
            	arrPrecios.push(parseFloat(preciosinf));
            
            // **** Temporal ******
            if (C_ID_PROPIEDAD != "")
            {
            	var maxContentDiv = document.createElement('div');
   				maxContentDiv.innerHTML = "Cargando...";
   
	            var divInfoWindow = document.createElement("div");
	   			divInfoWindow.innerHTML = textoInfoWindow(idpropiedad, info, foto, precio,tipo);
	            marker.openInfoWindowHtml(divInfoWindow, 
	          						   {maxContent: maxContentDiv, 
	             					    maxTitle: "Mas Información"}); 
            };
       }
       
       
       
	   if (refrescarPrecios == true)
	   {
		   var objPrecioInicial = document.forms[0].FILTROPRECIOINICIAL;
		   fillLista(arrPrecios,objPrecioInicial, "Desde");
		   
		   var objPrecioFinal = document.forms[0].FILTROPRECIOFINAL;
		   fillLista(arrPrecios,objPrecioFinal, "hasta");
		   
		   var objResultados  = document.getElementById("resultados_busqueda_alt");
		   
	   	   objResultados.innerHTML = "<b>Se han encontrado <br>" + markers.length + " propiedad(es). " +
	   								  '<img src="../globales/imagenes/flecha_resultados.gif" ' + 
	   							 	   'width="24px" height="24px" align="absmiddle"> </b>';
	   							 	   
		  var objResultadosPrecios  = document.getElementById("resultados_busqueda_precios");
	   		  objResultadosPrecios.innerHTML = ""; 	   							 	
	   }
	   else
	   {
	   		var objResultados  = document.getElementById("resultados_busqueda_precios");
	   		objResultados.innerHTML = "<b>Se han encontrado <br>" + markers.length + " propiedad(es). " +
	   								  '<img src="../globales/imagenes/flecha_resultados_precios.gif" ' + 
	   							 	   'width="24px" height="24px" align="absmiddle"> </b>' 
	   }
	           
     });

}

// **** Obtiene las propiedades tomando en cuenta 
// **** el precio en cuenta el precio
function obtenerFiltroConPrecio()
{
	var strFiltro = "";
	
	// **** Tipo de propiedad ****
	if (document.forms[0].FILTROTIPOPROP.selectedIndex != 0)
	{		
		strFiltro += "FILTROTIPOPROP=" + 
				document.forms[0].FILTROTIPOPROP.options[document.forms[0].FILTROTIPOPROP.selectedIndex].value;
	};
	
	// **** Municipio ****
	if (document.forms[0].FILTROMUNICIPIO.selectedIndex != 0)
	{		
		strFiltro += "&FILTROMUNICIPIO=" + 
				document.forms[0].FILTROMUNICIPIO.options[document.forms[0].FILTROMUNICIPIO.selectedIndex].value;
	};
	
	// **** Colonia ****
	if (document.forms[0].FILTROCOLONIA.selectedIndex != 0)
	{		
		strFiltro += "&FILTROCOLONIA=" + 
				document.forms[0].FILTROCOLONIA.options[document.forms[0].FILTROCOLONIA.selectedIndex].value;
	};
	
	// **** Precio Inicial ****
	if (document.forms[0].FILTROPRECIOINICIAL.selectedIndex != 0)
	{		
		strFiltro += "&FILTROPRECIOINICIAL=" + 
				document.forms[0].FILTROPRECIOINICIAL.options[
							document.forms[0].FILTROPRECIOINICIAL.selectedIndex].value;
							
	};
	
	// **** Precio Final ****
	if (document.forms[0].FILTROPRECIOFINAL.selectedIndex != 0)
	{		
		strFiltro += "&FILTROPRECIOFINAL=" + 
				document.forms[0].FILTROPRECIOFINAL.options[
							document.forms[0].FILTROPRECIOFINAL.selectedIndex].value;
							
	};
	
	
	return "?" + strFiltro;
}

function filtrarPropiedadesPorPrecio()
{
	// setDivCargando("cargarPropiedades","50%", "50%");
	
    map.clearOverlays();
    C_ID_PROPIEDAD = "";
    
    var url = "../mapa/buscar.html,"  + obtenerFiltroConPrecio(); 
    ejecutarBusqueda(url,false);
    
    setTimeout('borrarIndicador("cargarPropiedades");',3000);
}



function cargarPropiedadesAlt()
{   
	setDivCargando("cargarPropiedades","50%", "50%");
    map.clearOverlays();
    C_ID_PROPIEDAD = "";
    
    var url = "../mapa/buscar.html,"  + obtenerFiltroAlt(); 
    ejecutarBusqueda(url,true);
    
    setTimeout('borrarIndicador("cargarPropiedades");',3000);
}


function cargarPropiedad(KeyPropiedad)
{   
	setDivCargando("cargarPropiedades","50%", "50%");
    map.clearOverlays();
   
    var url = "../mapa/buscarprop.html,"  + KeyPropiedad; 
    ejecutarBusqueda(url,false);
    setTimeout('borrarIndicador("cargarPropiedades");',3000);
    
}

function cerrarDivInfoTipos()
{
	ocultarDiv("divWrapTipoPropiedades");
	ocultarDiv("div_tipo_prop");
};

function buscarPropiedadesAlt()
{
	cargarPropiedadesAlt(); 
	mostrarDiv("filtroprecio");
	
	if (document.forms[0].FILTROTIPOPROP.selectedIndex == 0)
	{
		mostrarDiv("divWrapTipoPropiedades");
		mostrarDiv("div_tipo_prop");
	};
	
	var selecMunicipio = (document.forms[0].FILTROMUNICIPIO.selectedIndex != 0);
	var selecColonia = (document.forms[0].FILTROCOLONIA.selectedIndex != 0);
	
	if (selecColonia)
	{	
		var IDColonia = document.forms[0].FILTROCOLONIA.options[
									document.forms[0].FILTROCOLONIA.selectedIndex].value;
											
		cargarMapaZona("../colonias/obtenerinfo," + IDColonia, map);
	}
	 else
	{
		if (selecMunicipio)
		{	
			var IDMunicipio = document.forms[0].FILTROMUNICIPIO.options[
									document.forms[0].FILTROMUNICIPIO.selectedIndex].value;
									
			cargarMapaZona("../municipios/obtenerinfo," + IDMunicipio, map);
		}
		else
			map.setCenter(mapCenter, C_MAPA_ZOOM);
	};
};



function AgregarFavoritos(titulo,url)
{	
	// *** IE 
	if(document.all)
		window.external.AddFavorite(url,titulo);
	else 
	// *** Firefox
		if(window.sidebar)
			window.sidebar.addPanel (titulo,url,'');
		else 
			// **** opera 
			if(window.opera && window.print)
			{ 
				var elem = document.createElement('a');
				elem.setAttribute('href',url);
				elem.setAttribute('title',titulo);
				elem.setAttribute('rel','sidebar');
				elem.click();
			};
}
