/*
Selector de provincias y localidades Ajax - non intrusive - Cross browser 
Copyright (C)Iñaki Gorostiza Esquerdeiro
http://www.hellogoogle.com
webmaster@hellogoogle.com 
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

var XmlHttpObj;

var destino = 1; // para el tipo de accion a realizar cuando se haya cargado la respuesta XML a la peticion

var Utf8 = {

    //Convierte de UTF-8 a ISO
    decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

function CreateXmlHttpObj()
{
	try
	{
		XmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
	
	}
	catch(e)
	{
		try
		{
			XmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch(oc)
		{
			XmlHttpObj = null;
		}
	}
		if(!XmlHttpObj && typeof XMLHttpRequest != "undefined") 
	{
		XmlHttpObj = new XMLHttpRequest();
	}
}


function GetInnerText (node)
{
	 return (node.textContent || node.innerText || node.text) ;
}



function StateChangeHandler()
{
	if(XmlHttpObj.readyState == 4)
	{
		if(XmlHttpObj.status == 200)
		{
			if (destino == 1)
				PopulatelocalidadList(XmlHttpObj.responseXML.documentElement);
			if (destino == 2)
				InmueblesList(XmlHttpObj.responseXML.documentElement);
		}
		else
		{
			alert("Código de error: "  + XmlHttpObj.status);
		}
	}
}

/* *************************************
************************************** */

function provinciaListOnChange() {
    var provinciaList = document.getElementById("provinciaList");
 
    var selectedprovincia = provinciaList.options[provinciaList.selectedIndex].value;

    destino = 1;
    var requestUrl;

     requestUrl = "poblacionesxml.php" + "?IdProvincia=" + encodeURIComponent(selectedprovincia);

	CreateXmlHttpObj();
	
	if(XmlHttpObj)
	{
		XmlHttpObj.onreadystatechange = StateChangeHandler;
		XmlHttpObj.open( "GET", requestUrl, true );
		XmlHttpObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		XmlHttpObj.send('');		
	}
}



function PopulatelocalidadList(localidadNode)
{	
    var localidadList = document.getElementById("localidadList");
	localidadList.options.length=1;

	var localidadNodes = localidadNode.getElementsByTagName('localidad');
	var textValue;
	var idValue;
	var optionItem;
	for (var count = 0; count < localidadNodes.length; count++)
	{ 
   		//textValue = Utf8.decode(GetInnerText(localidadNodes[count]));
   		textValue = GetInnerText(localidadNodes[count]);
		idValue = localidadNodes[count].getAttribute('c');
		optionItem = new Option( textValue, idValue, false, false);
		localidadList.options[localidadList.length] = optionItem;
	}
}



/* ******************************************************
******************************************************* */


function buscarMapa(centroX, centroY) {

    map.clearOverlays();

    var provinciaList = document.getElementById("provinciaList");
    var poblacionList = document.getElementById("localidadList");
    var tipoanuncioList = document.getElementById("tipoAnuncio");
    var tipoviviendaList = document.getElementById("tipoVivienda");

    var selectedprovincia = provinciaList.options[provinciaList.selectedIndex].value;
    var selectedpoblacion = poblacionList.options[poblacionList.selectedIndex].value;
    var seltipoanuncio = tipoanuncioList.options[tipoanuncioList.selectedIndex].value;
    var seltipovivienda = tipoviviendaList.options[tipoviviendaList.selectedIndex].value;
    if (document.getElementById("confoto").checked)
      var confoto = 1;
    else
      var confoto = 0;

    destino = 2;
    var requestUrl;

     requestUrl = "inmueblesxml.php" + "?IdProvincia=" + encodeURIComponent(selectedprovincia)
				+ "&IdPoblacion=" + encodeURIComponent(selectedpoblacion)
				+ "&tipoAnuncio=" + encodeURIComponent(seltipoanuncio)
				+ "&tipoVivienda=" + encodeURIComponent(seltipovivienda)
				+ "&confoto=" + encodeURIComponent(confoto);
     if (centroX != '')
       requestUrl += "&CoordX="+encodeURIComponent(centroX);
     if (centroY != '')
       requestUrl += "&CoordY="+encodeURIComponent(centroY);

	CreateXmlHttpObj();
	
	if(XmlHttpObj)
	{
		XmlHttpObj.onreadystatechange = StateChangeHandler;
		XmlHttpObj.open( "GET", requestUrl, true );
		XmlHttpObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		XmlHttpObj.send('');
	}
}


function InmueblesList(inmuebleXML)
{	
	var inmueblesNodes = inmuebleXML.getElementsByTagName('inmueble');

	if (inmueblesNodes.length == 0) {
		alert("No se han localizado propiedades del tipo indicado en la zona seleccionada.");
	}
	if (inmueblesNodes.length > 80) {
		alert("Se han localizado demsasiados inmuebles. Por favor, sea más específico con su búsqueda");
	}
	else {
		for (var count = 0; count < inmueblesNodes.length; count++) {
			idanuncio = GetInnerText(inmueblesNodes[count].getElementsByTagName('idanuncio')[0]);
			tipoanuncio = GetInnerText(inmueblesNodes[count].getElementsByTagName('tipoanuncio')[0]);
			tipovivienda = GetInnerText(inmueblesNodes[count].getElementsByTagName('tipovivienda')[0]);
			titulo = GetInnerText(inmueblesNodes[count].getElementsByTagName('titulo')[0]);
			precio = GetInnerText(inmueblesNodes[count].getElementsByTagName('precio')[0]);
			idfoto = GetInnerText(inmueblesNodes[count].getElementsByTagName('idfoto')[0]);
			if ((idfoto == "") || (idfoto ==undefined))
			  urlfoto = "img/sinimagen.gif";
			else
			  urlfoto = "verfotoanuncio.php?IdFoto="+idfoto;

			coordx = GetInnerText(inmueblesNodes[count].getElementsByTagName('coordenadax')[0]);
			coordy = GetInnerText(inmueblesNodes[count].getElementsByTagName('coordenaday')[0]);
		      point = new GLatLng(coordy,coordx);
			html = infohtml;
			html = html.replace("SRCFOTO", urlfoto);
			html = html.replace("TIPOANUNCIO", tipoanuncio);
			html = html.replace("TIPOINMUEBLE", tipovivienda);
			html = html.replace("TITULOANUNCIO", titulo);
			html = html.replace("PRECIOANUNCIO", precio);
			html = html.replace("WWW.URLANUNCIO.COM", "index.php?accion=veranuncio&IdAnuncio="+idanuncio);
		      marker = createMarker(point,html);
			map.addOverlay(marker);
		}
	}
}

