Array.prototype.indexOf = function(s) {
    for (var x=0;x<this.length;x++)
        if(this[x] == s)
            return x;
    return "-1";
}
    
var myLoad = function(hash) {  //cuando se halla cargado el popup, se marcan los checkboxs correspondientes
    var listaIDs=$("#listaMunicipios").val();
    if (listaIDs.length>0) {
        ArrayIDs=listaIDs.split(",");
        for (i=0;i<ArrayIDs.length;i++) {
            $("input[type=checkbox][value='"+ArrayIDs[i]+"']").attr("checked",true);
														
        }
        listaIDs=ArrayIDs.join(",");
    }
} 
    
function inicializaComboMunicipio(IDisla){
    //if(document.getElementById('textoLibre').value != ""){
        $("#listaMunicipios").val("");
        $("#inputMunicipio").val("- Seleccione municipio(s) -");
        $('#ventanaPopupMunicipios').jqm({
            ajax: 'ajax/popups/popupCheckboxMunicipios.php?IDisla='+IDisla,
            onLoad:myLoad,
            target: '#cuerpoPopupMunicipios',
            toTop: true
        });
    //}
}
        
function cambiaMunicipio(valor,nombre){
    var listaIDs=$("#listaMunicipios").val();
    ArrayIDs=listaIDs.split(",");
    if (ArrayIDs.indexOf(valor)>-1) {
        //el id del municipio ya se encuentra en la lista, asi que se elimina
        ArrayIDs=$.grep(ArrayIDs, function(value,index){
            return value!=valor;
        }); //eliminamos el id del municipio de "lista"
        listaIDs=ArrayIDs.join(",");
        $("#listaMunicipios").val(listaIDs);
		
        //ahora eliminamos el nombre del municipio que esta en el input que se le muestra al usuario
        var listaNombres=$('#inputMunicipio').val();
        ArrayNombres=listaNombres.split(",");

        ArrayNombres=$.grep(ArrayNombres, function(value,index){
            return $.trim(value)!=nombre;
        }); //eliminamos el nombre del municipio de "lista"

        listaNombres=ArrayNombres.join(",");
        if (listaNombres.length == 0)
            $("#inputMunicipio").val("- Seleccione municipio(s) -");
        else
            $("#inputMunicipio").val(listaNombres);
		
    }
    else { //el municipio no se encuentra en la lista, asi que se agrega
        var listaNombres=$('#inputMunicipio').val();
        if (listaIDs.length>0){ //si hay algun dato en la lista de IDs
            listaIDs=listaIDs+","+valor;
            listaNombres=listaNombres+","+nombre;
        }
        else {
            listaIDs=valor;
            listaNombres=nombre;
        }
        $("#listaMunicipios").val(listaIDs);
        $('#inputMunicipio').val(listaNombres);
    }
}
//*******************_____________________***********************___________________________***************************___________________________*******************************_____________________

function rellenaComboIsla(){
	
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    var textos = document.getElementById('textoLibre').value;
    
    if(textos == ""){
        url="ajax/obtenerIslas.php";
        xmlHttp.open("GET",url,false);   //lamada AJAX Sincrona
		
        combo = document.getElementById("comboIsla");
        combo.options[0]= new Option("..cargando...","-1");
		
        xmlHttp.send(null);

        respuesta = eval( "(" + xmlHttp.responseText + ")" ); //metemos la respuesta JSON en el objeto "respuesta"
					
        combo = document.getElementById("comboIsla");
        combo.options[0]= new Option("- Seleccione Isla -","-1");
        var numeroIslas = respuesta.islas.length;
        for (i=0;i<numeroIslas;i++){
            nombre=unescape(respuesta.islas[i].nombre);
            valor=respuesta.islas[i].valor;
            combo.options[i+1] = new Option(nombre,valor); //metemos los datos en el combo
        }
		
        //Si habia algo en la lista de municipios, lo borramos y ponemos el texto de "seleccione municipio(s)"
        $('#listaMunicipios').val('');
    }
//$('#inputMunicipio').val('  - Seleccione municipio(s) -');
}


/*******************************************
// Esta funcion hace una llamada AJAX SINCRONA.
//Recibe el elemento que se va a convertir en un "comobo de seleccion multiple". Siempre tiene que ser un elemento "<input type='text'>

 	function rellenaComboMunicipio(){

		var xmlHttp;
		try
		  {
		  // Firefox, Opera 8.0+, Safari
		  xmlHttp=new XMLHttpRequest();
		  }
		catch (e)
		  {
		  // Internet Explorer
		  try
			{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
			}
		  catch (e)
			{
			try
			  {
			  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			  }
			catch (e)
			  {
			  alert("Your browser does not support AJAX!");
			  return false;
			  }
			}
		  }
			//mostramos el mensaje de "cargando muncipios"
			$('#inputMunicipio').val('..cargando muncipios');
			
			IDisla= document.getElementById("comboIsla").value; //obtenemos el ID de la isla seleccionada para mandarselo a "obtenerMunicipios.php"
			url="ajax/obtenerMunicipios.php?IDisla="+IDisla;
			//a�adimos esto para evitar que la pagina se coja de la cache en la llamada AJAX
			var currentTime = new Date();
			var timestamp = currentTime.getTime();
			url=url+"&time="+timestamp; 

		  	xmlHttp.open("GET",url,false); 
		  	xmlHttp.send(null);
			respuesta = xmlHttp.responseText; 

			//Si habia algo en la lista de municipios, lo borramos y ponemos el texto de "seleccione municipio(s)"
			$('#listaMunicipios').val('');
			$('#inputMunicipio').val('  - Seleccione municipio(s) -');
			//los datos para cargar el combo deben almacenarse en el atributo "data"
			$('#inputMunicipio').attr('data',respuesta);
			//$('#inputMunicipio').multipleSelect({maxWidth:550, maxHeight:400,elementoSeleccion:'listaMunicipios' });

	} 

//**************************************************************************/

//se ejecuta cuando el usuario pincha sobre el icono del tipo. Esta funcion se encarga de seleccionar o deselccionar ese tipo	
function tipoSeleccionado(nombre){
    if (document.getElementById("tipo"+nombre).className=="seleccionado")
        desmarcaTipo(nombre);
    else
        marcaTipo(nombre);
}
//***************************************************************************************************************************	
//resalta el icono de tipo y marca los checkboxes de las subcategorias a TRUE
function marcaTipo (nombre) {
    document.getElementById("tipo"+nombre).className="seleccionado";
    document.getElementById("avanzada_"+nombre).style.display="block";
    switch(nombre) {
        case 'piso':
            document.getElementById('piso_subcategoria_habitacion').checked = true;
            document.getElementById('piso_subcategoria_estudio').checked = true;
            document.getElementById('piso_subcategoria_piso').checked = true;
            document.getElementById('piso_subcategoria_duplex').checked = true;
            document.getElementById('piso_subcategoria_triplex').checked = true;
            document.getElementById('piso_subcategoria_atico').checked = true;
            break;
        case 'casa':
            document.getElementById('casa_subcategoria_caserio').checked = true;
            document.getElementById('casa_subcategoria_adosada').checked = true;
            document.getElementById('casa_subcategoria_semiadosada').checked = true;
            document.getElementById('casa_subcategoria_chalet').checked = true;
            break;
        case 'local':
            document.getElementById('local_subcategoria_local').checked = true;
            document.getElementById('local_subcategoria_edificio').checked = true;
            document.getElementById('local_subcategoria_hotel').checked = true;
            document.getElementById('local_subcategoria_industrial').checked = true;
            break;
        case 'terreno':
            document.getElementById('terreno_subcategoria_rustico').checked = true;
            document.getElementById('terreno_subcategoria_caserio').checked = true;
            document.getElementById('terreno_subcategoria_urbano').checked = true;
            break;
        case 'garaje':
            document.getElementById('garaje_subcategoria_garaje').checked = true;
            break;
    }
}

//***************************************************************************************************************************
//quita el resalte el icono de tipo y marca los checkboxes de las subcategorias a FALSE	
function desmarcaTipo(nombre) {
    document.getElementById("tipo"+nombre).className="";
    document.getElementById("avanzada_"+nombre).style.display="none";
    switch(nombre) {
        case 'piso':
            document.getElementById('piso_subcategoria_habitacion').checked = false;
            document.getElementById('piso_subcategoria_estudio').checked = false;
            document.getElementById('piso_subcategoria_piso').checked = false;
            document.getElementById('piso_subcategoria_duplex').checked = false;
            document.getElementById('piso_subcategoria_triplex').checked = false;
            document.getElementById('piso_subcategoria_atico').checked = false;
            break;
        case 'casa':
            document.getElementById('casa_subcategoria_caserio').checked = false;
            document.getElementById('casa_subcategoria_adosada').checked = false;
            document.getElementById('casa_subcategoria_semiadosada').checked = false;
            document.getElementById('casa_subcategoria_chalet').checked = false;
            break;
        case 'local':
            document.getElementById('local_subcategoria_local').checked = false;
            document.getElementById('local_subcategoria_edificio').checked = false;
            document.getElementById('local_subcategoria_hotel').checked = false;
            document.getElementById('local_subcategoria_industrial').checked = false;
            break;
        case 'terreno':
            document.getElementById('terreno_subcategoria_rustico').checked = false;
            document.getElementById('terreno_subcategoria_caserio').checked = false;
            document.getElementById('terreno_subcategoria_urbano').checked = false;
            break;
        case 'garaje':
            document.getElementById('garaje_subcategoria_garaje').checked = false;
            break;
    }
}

//****************************************************************************************************************************	
function seleccionaSubCategorias(tipo) {
    switch(tipo) {
        case 'piso':
            if ((document.getElementById('piso_subcategoria_habitacion').checked == true) && (document.getElementById('piso_subcategoria_estudio').checked == true) && (document.getElementById('piso_subcategoria_piso').checked == true) && (document.getElementById('piso_subcategoria_duplex').checked == true) && (document.getElementById('piso_subcategoria_triplex').checked == true) && (document.getElementById('piso_subcategoria_atico').checked == true)) {
                document.getElementById('piso_subcategoria_habitacion').checked = false;
                document.getElementById('piso_subcategoria_estudio').checked = false;
                document.getElementById('piso_subcategoria_piso').checked = false;
                document.getElementById('piso_subcategoria_duplex').checked = false;
                document.getElementById('piso_subcategoria_triplex').checked = false;
                document.getElementById('piso_subcategoria_atico').checked = false;
            }
            else{
                document.getElementById('piso_subcategoria_habitacion').checked = true;
                document.getElementById('piso_subcategoria_estudio').checked = true;
                document.getElementById('piso_subcategoria_piso').checked = true;
                document.getElementById('piso_subcategoria_duplex').checked = true;
                document.getElementById('piso_subcategoria_triplex').checked = true;
                document.getElementById('piso_subcategoria_atico').checked = true;
            }
            break;
        case 'casa':
            if ((document.getElementById('casa_subcategoria_caserio').checked == true) && (document.getElementById('casa_subcategoria_adosada').checked == true) && (document.getElementById('casa_subcategoria_semiadosada').checked == true) && (document.getElementById('casa_subcategoria_chalet').checked == true)) {
                document.getElementById('casa_subcategoria_caserio').checked = false;
                document.getElementById('casa_subcategoria_adosada').checked = false;
                document.getElementById('casa_subcategoria_semiadosada').checked = false;
                document.getElementById('casa_subcategoria_chalet').checked = false;
            }
            else{
                document.getElementById('casa_subcategoria_caserio').checked = true;
                document.getElementById('casa_subcategoria_adosada').checked = true;
                document.getElementById('casa_subcategoria_semiadosada').checked = true;
                document.getElementById('casa_subcategoria_chalet').checked = true;
            }
            break;
        case 'local':
            if ((document.getElementById('local_subcategoria_local').checked == true) && (document.getElementById('local_subcategoria_edificio').checked == true) && (document.getElementById('local_subcategoria_hotel').checked == true) && (document.getElementById('local_subcategoria_industrial').checked == true)) {
                document.getElementById('local_subcategoria_local').checked = false;
                document.getElementById('local_subcategoria_edificio').checked = false;
                document.getElementById('local_subcategoria_hotel').checked = false;
                document.getElementById('local_subcategoria_industrial').checked = false;
            }
            else{
                document.getElementById('local_subcategoria_local').checked = true;
                document.getElementById('local_subcategoria_edificio').checked = true;
                document.getElementById('local_subcategoria_hotel').checked = true;
                document.getElementById('local_subcategoria_industrial').checked = true;
            }
            break;
        case 'terreno':
            if ((document.getElementById('terreno_subcategoria_rustico').checked == true) && (document.getElementById('terreno_subcategoria_caserio').checked == true) && (document.getElementById('terreno_subcategoria_urbano').checked == true)) {
                document.getElementById('terreno_subcategoria_rustico').checked = false;
                document.getElementById('terreno_subcategoria_caserio').checked = false;
                document.getElementById('terreno_subcategoria_urbano').checked = false;
            }
            else{
                document.getElementById('terreno_subcategoria_rustico').checked = true;
                document.getElementById('terreno_subcategoria_caserio').checked = true;
                document.getElementById('terreno_subcategoria_urbano').checked = true
            }
            break;
        case 'garaje':
            if (document.getElementById('garaje_subcategoria_garaje').checked == true) {
                document.getElementById('garaje_subcategoria_garaje').checked = false;
            }
            else{
                document.getElementById('garaje_subcategoria_garaje').checked = true;
            }
            break;
    }
}
	
//*****************************************************************************************************************************	

//Muestra en la pagina el numero de resultados de la consulta.
//Esta funcion solo hay que llamarla cuando se realice una nueva busqueda, ya que ser� cuando se produzcan cambios en el numero de resultados
function actualizaNumeroDeResultados(){ 
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    xmlHttp.onreadystatechange=function() {
        if(xmlHttp.readyState==4){
            document.getElementById("divNumeroDeResultados").innerHTML=xmlHttp.responseText;
            document.getElementById("numeroDeResultados").value=parseInt(xmlHttp.responseText);
	
        }
    }
    //generamos la direccion url con las variables de busqueda
    var parametrosURL=obtenerParametrosDelBuscador();
   
    url="ajax/resultados/numeroDeResultados.php?"+parametrosURL;
    //a�adimos esto para evitar que la pagina se coja de la cache en la llamada AJAX
    var currentTime = new Date();
    var timestamp = currentTime.getTime();
    url=url+"&time="+timestamp;
		
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}
//*************************************************************************************************
function actualizaNumeroDeResultadosult5dias(){ 
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    xmlHttp.onreadystatechange=function() {
        if(xmlHttp.readyState==4){
            
            document.getElementById("divNumeroDeResultados").innerHTML=xmlHttp.responseText;
            document.getElementById("numeroDeResultados").value=parseInt(xmlHttp.responseText);
        }
    }
    url="ajax/resultados/numeroDeResultados.php?pagina=1&ult5dias=1";
    //a�adimos esto para evitar que la pagina se coja de la cache en la llamada AJAX
    var currentTime = new Date();
    var timestamp = currentTime.getTime();
    url=url+"&time="+timestamp;
		
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}	
//*****************************************************************************************************************************	
function muestraTablaResultados(){ 
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    xmlHttp.onreadystatechange=function() {
        if(xmlHttp.readyState==4) {
            document.getElementById("divResultados").innerHTML=xmlHttp.responseText;
            //actualizamos el paginador
            pagina=parseInt(document.getElementById('paginaActual').value);
            actualizaPaginador(pagina);

            //Inicializamos las fotos de las propiedades
            $('a.fancyBox-fotos').fancybox({
                'zoomSpeedIn': 0,
                'zoomSpeedOut': 0,
                'overlayShow': true,
                'overlayOpacity':0.925
            });
					
        }
        else
            document.getElementById("divResultados").innerHTML="<div align='center' style='padding:10px 0px 10px 0px'><span style='color=#00cc00;font-size:16pt'>Cargando resultados</span><br><img src='images/design/greenLoadingBar1.gif'></div><br>";
    }
    var parametrosURL=obtenerParametrosDelBuscador();
    
    url="ajax/resultados/muestraTablaResultados.php?"+parametrosURL;
    //a�adimos esto para evitar que la pagina se coja de la cache en la llamada AJAX
    var currentTime = new Date();
    var timestamp = currentTime.getTime();
    url=url+"&time="+timestamp;
			
    //guardamos los parametros de la busqueda en la bbdd
    //guardaHistorialBusquedas(parametrosURL);
			
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}

//*****************************************************************************************************************************	
function muestraTablaResultadosult5dias(){ 
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    xmlHttp.onreadystatechange=function() {
        if(xmlHttp.readyState==4) {
            document.getElementById("divResultados").innerHTML=xmlHttp.responseText;
            //actualizamos el paginador
            pagina=parseInt(document.getElementById('paginaActual').value);
            actualizaPaginador(pagina);
					
            //Inicializamos las fotos de las propiedades
            $('a.fancyBox-fotos').fancybox({
                'zoomSpeedIn': 0,
                'zoomSpeedOut': 0,
                'overlayShow': true,
                'overlayOpacity':0.925
            });
					
        }
        else
            document.getElementById("divResultados").innerHTML="<div align='center' style='padding:10px 0px 10px 0px'><span style='color=#00cc00;font-size:16pt'>Cargando resultados</span><br><img src='images/design/greenLoadingBar1.gif'></div><br>";
    }
    url="ajax/resultados/muestraTablaResultados.php?pagina=1&ult5dias=1";
    //a�adimos esto para evitar que la pagina se coja de la cache en la llamada AJAX
    var currentTime = new Date();
    var timestamp = currentTime.getTime();
    url=url+"&time="+timestamp;
			
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}

//**************************************************************************************************************************

//**************************************************************************************************************************
//"paginaQueLLama": se utiliza para saber is esta funciuon ha sido llamada desde index o desde otra pagina
//ya que si se llama desde index.php, hay que hacer algo distinto al final de la funcion
function busca(paginaQueLLama,opcion){
       
    if(opcion == 2){

        document.getElementById('textoLibre').value= "";
    }
    var isla = document.getElementById('comboIsla').value;
    var textos = document.getElementById('textoLibre').value.length;
    // var textos = "";
    
    if (isla == -1 && textos < 1){
        
        alert ("debe seleccionar una isla");
        }
   /* else
    if (isla == -1 && textos > 0){
        alert(textos);
        var parametrosURL = obtenerParametrosDelBuscador();
        window.location.href="http://www.tenerpiso.com/resultados.php?"+parametrosURL;
    }*/
    else
    if (paginaQueLLama == 'index.php'){
        var parametrosURL = obtenerParametrosDelBuscador();
        window.location.href="http://www.tenerpiso.com/resultados.php?"+parametrosURL;
    }
    else {
        muestraTablaResultados();
        actualizaNumeroDeResultados();
    }

}

function buscaTextoLibre(paginaQueLLama){
    var texto = document.getElementById('textoLibre').value;
    if(texto == ""){
        alert("Para realizar este tipo de busqueda es necesario introducir algo de texto");
    }
    else{
        if (paginaQueLLama == 'index.php'){
            var parametrosURL = "text=" + texto;
            window.location.href="http://www.tenerpiso.com/resultados.php?"+parametrosURL;
        }
        else {
            muestraTablaResultados();
            actualizaNumeroDeResultados();
        }
    }
}

//***********************************************************************************************************	
function muestraOcultaCapaAvanzadaAlquiler(){
    var regimen = document.getElementById('comboRegimen').value;
    if (regimen == 1) {//alquiler
        //$("#capaAvanzadaAlquiler").slideDown("slow");
        document.getElementById('capaAvanzadaAlquiler').style.display = "block";
    }
    else {
        //$("#capaAvanzadaAlquiler").slideUp("slow");
        document.getElementById('capaAvanzadaAlquiler').style.display = "none";
    }
}

//***********************************************************************************************************	
function muestraOcultaCapa(capa) {
    //	Esta combinaci�n es la unica que funciona igual en IE y FF
		
    if (document.getElementById(capa).style.display=="block"){
        $("#"+capa).slideUp("slow");  //hide
        document.getElementById('imagenFlechaCapaAvanzada').src="images/design/flechaAbajo.jpg";
    //document.getElementById(capa).style.display="none";
    }
    else {
        $("#"+capa).slideDown("slow"); //show
        document.getElementById(capa).style.display="block";
        document.getElementById('imagenFlechaCapaAvanzada').src="images/design/flechaArriba.jpg";
    }
}
	
/* ********************************************************************************************************************
	Esta funci�n se ejecuta cuando se carga la p�gina.
	El buscador se puede actualizar de 2 maneras:
	- Obteniendo los parametros de la bbdd usando el parametro "idBusqueda" enviado en la URL  
	- Extrayendo los valores de las variables de la URL	


Nota:
Esta funcion se llama de forma original sin argumentos. Sin embargo, si se le pasa un argumento a esta funcion, este argumento sera el id de la busqueda que se debe cargar en el buscador.
*********************************************************************************************************************** */

function actualizaBuscador() {

    if(arguments.length>0){ //comprobamos si hemos llamado a esta funcion con 1 argumento
        actualizaBuscadorIndex=true;
        
    }
    else{
        actualizaBuscadorIndex=false;
         
    }
    url = unescape(window.document.location);
    if ((url.indexOf("?") > -1) || (actualizaBuscadorIndex)){
         
        var variablesBusqueda=new Array();
        if (url.indexOf("idBusqueda") > -1) {
            var temp = url.split("?");
            var temp2 = temp[1].split("=");
            idBusqueda = temp2[1];
            cadena = generaCadenaVariablesIdBusqueda(idBusqueda);
            parejas = cadena.split("&");
            
        }

        else {
            if (actualizaBuscadorIndex){
                cadena=generaCadenaVariablesIdBusqueda(arguments[0]);
                parejas = cadena.split("&");
               
            }
            else{
                //Ahora metemos todas las variables que se pasaron por URL en el array variablesBusqueda
                var comienzo = url.split("?");
                
                var parejas = comienzo[1].split ("&");
            //alert(parejas);
            }
        }
        for (i=0;i<parejas.length;i++){
            temp=parejas[i].split("=");
            variablesBusqueda[i]=new Array(2);
            variablesBusqueda[i][0] = temp[0];
            variablesBusqueda[i][1] = temp[1];
            
        }
        variablesBusqueda.length=parejas.length;
        //Ahora recorremos el array variablesBusqueda y metemos los valores en el buscador
        //He usado todos estos "IF" en lugar de un "SWITCH" ya que el "BREAK" del "SWITCH" rompia el bucle "IF"

        if(variablesBusqueda[0][0] == "text"){
            document.getElementById('textoLibre').value = variablesBusqueda[0][1];
        }else{
            var i=0;
        
            for (i=0;i<variablesBusqueda.length;i++) {
                if (variablesBusqueda[i][0]=="IDIsla") {
                    document.getElementById('comboIsla').value=variablesBusqueda[i][1];
                    inicializaComboMunicipio(document.getElementById('comboIsla').value); //ya que conocemos la isla seleccionada, podemos rellenar el municipio
                }
                else if (variablesBusqueda[i][0]=="IDMunicipio") {
                    //eliminamos la coma inicial y metemos el listado de municipios en el input oculto "listadoMunicipios"
                    listadoMunicipios=variablesBusqueda[i][1].substr(1);
                    document.getElementById('listaMunicipios').value=listadoMunicipios;
                    //Ahora mostramos en el combo de municipios "inputMunicipio",los nombres de los  municipios seleccionados
                    if($.trim($('#listaMunicipios').val())!="") {
                        $.ajax({
                            type: "GET",
                            url: "ajax/obtenerNombreMunicipios.php",
                            cache: false,
                            data: "IDMunicipios="+listadoMunicipios,
                            success: function(html){
                                nombreMunicipios=unescape(html); //ya se que unescape esta anticuado, pero no me funcionaba con decodeURIComponent
                                $('#inputMunicipio').val(nombreMunicipios);
                            }
                        });
                    }
                    else
                        $('#inputMunicipio').val("- Seleccione municipio(s) -");
                }
                else if (variablesBusqueda[i][0]=="preciomin") document.getElementById('comboPrecioMin').value=variablesBusqueda[i][1];
                else if (variablesBusqueda[i][0]=="preciomax") document.getElementById('comboPrecioMax').value=variablesBusqueda[i][1];
                else if (variablesBusqueda[i][0]=="rooms") document.getElementById('comboRooms').value=variablesBusqueda[i][1];
                else if (variablesBusqueda[i][0]=="piscina") document.getElementById('comboPiscina').value=variablesBusqueda[i][1];
                else if (variablesBusqueda[i][0]=="wc") document.getElementById('comboWC').value=variablesBusqueda[i][1];
                else if (variablesBusqueda[i][0]=="amueblado")	document.getElementById('comboAmueblado').value=variablesBusqueda[i][1];
                else if (variablesBusqueda[i][0]=="aparc")	document.getElementById('comboAparcamiento').value=variablesBusqueda[i][1];
                else if (variablesBusqueda[i][0]=="cocina") document.getElementById('comboCocina').value=variablesBusqueda[i][1];
                else if (variablesBusqueda[i][0]=="metrosint") document.getElementById('textMetros').value=variablesBusqueda[i][1];
                else if (variablesBusqueda[i][0]=="fianza") document.getElementById('textFianza').value=variablesBusqueda[i][1];
                else if (variablesBusqueda[i][0]=="fumador") document.getElementById('comboFumador').value=variablesBusqueda[i][1];
                else if (variablesBusqueda[i][0]=="genero") document.getElementById('comboGenero').value=variablesBusqueda[i][1];
                else if (variablesBusqueda[i][0]=="animales") document.getElementById('comboAnimales').value=variablesBusqueda[i][1];
                else if (variablesBusqueda[i][0]=="pagina") document.getElementById('paginaActual').value=variablesBusqueda[i][1];
                else if (variablesBusqueda[i][0]=="orderBy") document.getElementById('orderBy').value=variablesBusqueda[i][1];
                else
                if (variablesBusqueda[i][0]=="regimen") {
                    document.getElementById('comboRegimen').value=variablesBusqueda[i][1];
                    muestraOcultaCapaAvanzadaAlquiler();
                }
                else
                if (variablesBusqueda[i][0]=="IDTipo")	{
	
                    //primero deshacemos la seleccion que hay por defecto
                    document.getElementById("tipopiso").className="";
                    document.getElementById("tipocasa").className="";
                    document.getElementById("tipolocal").className="";
                    document.getElementById("tipoterreno").className="";
                    document.getElementById("tipogaraje").className="";
                    document.getElementById("avanzada_piso").style.display="none";
                    document.getElementById("avanzada_casa").style.display="none";
                    document.getElementById("avanzada_local").style.display="none";
                    document.getElementById("avanzada_terreno").style.display="none";
                    document.getElementById("avanzada_garaje").style.display="none";
                    document.getElementById('piso_subcategoria_habitacion').checked = false;
                    document.getElementById('piso_subcategoria_estudio').checked = false;
                    document.getElementById('piso_subcategoria_piso').checked = false;
                    document.getElementById('piso_subcategoria_duplex').checked = false;
                    document.getElementById('piso_subcategoria_triplex').checked = false;
                    document.getElementById('piso_subcategoria_atico').checked = false;
                    document.getElementById('casa_subcategoria_caserio').checked = false;
                    document.getElementById('casa_subcategoria_adosada').checked = false;
                    document.getElementById('casa_subcategoria_semiadosada').checked = false;
                    document.getElementById('casa_subcategoria_chalet').checked = false;
                    document.getElementById('local_subcategoria_local').checked = false;
                    document.getElementById('local_subcategoria_edificio').checked = false;
                    document.getElementById('local_subcategoria_hotel').checked = false;
                    document.getElementById('local_subcategoria_industrial').checked = false;
                    document.getElementById('terreno_subcategoria_rustico').checked = false;
                    document.getElementById('terreno_subcategoria_caserio').checked = false;
                    document.getElementById('terreno_subcategoria_urbano').checked = false
                    document.getElementById('garaje_subcategoria_garaje').checked = false;

                    //y ahora seleccionamos los tipos correspondientes
                    arrayTipos=variablesBusqueda[i][1].split(",");
                    var j=0;

                    for (j=1;j<arrayTipos.length;j++){

                        if (arrayTipos[j]==7) {
                            document.getElementById("avanzada_piso").style.display="block";
                            document.getElementById("tipopiso").className="seleccionado";
                            document.getElementById("piso_subcategoria_habitacion").checked=true;
                        }else
                        if (arrayTipos[j]==3){
                            document.getElementById("avanzada_piso").style.display="block";
                            document.getElementById("tipopiso").className="seleccionado";
                            document.getElementById("piso_subcategoria_estudio").checked=true;
                        }else
                        if (arrayTipos[j]==4){
                            document.getElementById("avanzada_piso").style.display="block";
                            document.getElementById("tipopiso").className="seleccionado";
                            document.getElementById("piso_subcategoria_piso").checked=true;
                        }else
                        if (arrayTipos[j]==17){
                            document.getElementById("avanzada_piso").style.display="block";
                            document.getElementById("tipopiso").className="seleccionado";
                            document.getElementById("piso_subcategoria_duplex").checked=true;
                        }else
                        if (arrayTipos[j]==18){
                            document.getElementById("avanzada_piso").style.display="block";
                            document.getElementById("tipopiso").className="seleccionado";
                            document.getElementById("piso_subcategoria_triplex").checked=true;
                        }else
                        if (arrayTipos[j]==16){
                            document.getElementById("avanzada_piso").style.display="block";
                            document.getElementById("tipopiso").className="seleccionado";
                            document.getElementById("piso_subcategoria_atico").checked=true;
                        }else
                        if (arrayTipos[j]==9){
                            document.getElementById("avanzada_casa").style.display="block";
                            document.getElementById("tipocasa").className="seleccionado";
                            document.getElementById("casa_subcategoria_caserio").checked=true;
                            document.getElementById("avanzada_terreno").style.display="block";
                            document.getElementById("tipoterreno").className="seleccionado";
                            document.getElementById("terreno_subcategoria_caserio").checked=true;
                        }else
                        if (arrayTipos[j]==5){
                            document.getElementById("avanzada_casa").style.display="block";
                            document.getElementById("tipocasa").className="seleccionado";
                            document.getElementById("casa_subcategoria_adosada").checked=true;
                        }else
                        if (arrayTipos[j]==6){
                            document.getElementById("avanzada_casa").style.display="block";
                            document.getElementById("tipocasa").className="seleccionado";
                            document.getElementById("casa_subcategoria_semiadosada").checked=true;
                        }else
                        if (arrayTipos[j]==10){
                            document.getElementById("avanzada_casa").style.display="block";
                            document.getElementById("tipocasa").className="seleccionado";
                            document.getElementById("casa_subcategoria_chalet").checked=true;
                        }else
                        if (arrayTipos[j]==8){
                            document.getElementById("avanzada_local").style.display="block";
                            document.getElementById("tipolocal").className="seleccionado";
                            document.getElementById("local_subcategoria_local").checked=true;
                        }else
                        if (arrayTipos[j]==11){
                            document.getElementById("avanzada_local").style.display="block";
                            document.getElementById("tipolocal").className="seleccionado";
                            document.getElementById("local_subcategoria_edificio").checked=true;
                        }else
                        if (arrayTipos[j]==12){
                            document.getElementById("avanzada_local").style.display="block";
                            document.getElementById("tipolocal").className="seleccionado";
                            document.getElementById("local_subcategoria_hotel").checked=true;
                        }else
                        if (arrayTipos[j]==13){
                            document.getElementById("avanzada_local").style.display="block";
                            document.getElementById("tipolocal").className="seleccionado";
                            document.getElementById("local_subcategoria_industrial").checked=true;
                        }else
                        if (arrayTipos[j]==1){
                            document.getElementById("avanzada_terreno").style.display="block";
                            document.getElementById("tipoterreno").className="seleccionado";
                            document.getElementById("terreno_subcategoria_rustico").checked=true;
                        }else
                        if (arrayTipos[j]==2){
                            document.getElementById("avanzada_terreno").style.display="block";
                            document.getElementById("tipoterreno").className="seleccionado";
                            document.getElementById("terreno_subcategoria_urbano").checked=true;
                        }else
                        if (arrayTipos[j]==14){
                            document.getElementById("avanzada_garaje").style.display="block";
                            document.getElementById("tipogaraje").className="seleccionado";
                            document.getElementById("garaje_subcategoria_garaje").checked=true;
                        }
											

                    }//for
                } //if

            } //for
        }//if
    }
}

//************************************************************************************************************************************
//Est funcion obtiene la informacion que hay en el buscador y la pone en un string, lista para ser enviada mediante AJAX
function obtenerParametrosDelBuscador() {

    //estos son los valores de los tipos en la tabla "tblTipo"
    var idRustico= 1;
    var idUrbano=2;
    var idEstudio=3;
    var idPiso= 4;
    var idAdosada = 5;
    var idSemiAdosada = 6;
    var idHabitacion = 7;
    var idLocal = 8;
    var idCaserio = 9;
    var idChalet = 10;
    var idEdificio = 11;
    var idHotel = 12;
    var idIndustrial = 13;
    var idParking = 14;
    var idOtro = 15;
    var idAtico = 16;
    var idDuplex = 17;
    var idTriplex = 18;
	
		
    //todos los tipos que el usuario haya seleccionado los metemos en una cadena, separados por ","
    var tipo="";
    if (document.getElementById('piso_subcategoria_habitacion').checked) tipo = tipo + "," + idHabitacion;
    if (document.getElementById('piso_subcategoria_estudio').checked) tipo = tipo + "," + idEstudio;
    if (document.getElementById('piso_subcategoria_piso').checked) tipo = tipo + "," + idPiso;
    if (document.getElementById('piso_subcategoria_duplex').checked) tipo = tipo + "," + idDuplex;
    if (document.getElementById('piso_subcategoria_triplex').checked) tipo = tipo + "," + idTriplex;
    if (document.getElementById('piso_subcategoria_atico').checked) tipo = tipo + "," + idAtico;
		
    if (document.getElementById('casa_subcategoria_caserio').checked) tipo = tipo + "," + idCaserio;
    if (document.getElementById('casa_subcategoria_adosada').checked) tipo = tipo + "," + idAdosada;
    if (document.getElementById('casa_subcategoria_semiadosada').checked) tipo = tipo + "," + idSemiAdosada;
    if (document.getElementById('casa_subcategoria_chalet').checked) tipo = tipo + "," + idChalet;

    if (document.getElementById('local_subcategoria_local').checked) tipo = tipo + "," + idLocal;
    if (document.getElementById('local_subcategoria_edificio').checked) tipo = tipo + "," + idEdificio;
    if (document.getElementById('local_subcategoria_hotel').checked) tipo = tipo + "," + idHotel;
    if (document.getElementById('local_subcategoria_industrial').checked) tipo = tipo + "," + idIndustrial;

    if (document.getElementById('terreno_subcategoria_rustico').checked) tipo = tipo + "," + idRustico;
    if (document.getElementById('terreno_subcategoria_caserio').checked) tipo = tipo + "," + idCaserio;
    if (document.getElementById('terreno_subcategoria_urbano').checked) tipo = tipo + "," + idUrbano;

    if (document.getElementById('garaje_subcategoria_garaje').checked) tipo = tipo + "," + idParking;
		
    //obtenemos los demas valores que haran falta en la busqueda
    var isla = document.getElementById('comboIsla').value;
    var textoLibre = document.getElementById('textoLibre').value;
    var municipio = document.getElementById('listaMunicipios').value;

    var regimen = document.getElementById('comboRegimen').value;
    var precioMin = document.getElementById('comboPrecioMin').value;
    var precioMax = document.getElementById('comboPrecioMax').value;
    var rooms = document.getElementById('comboRooms').value;
    var piscina = document.getElementById('comboPiscina').value;
    var wc = document.getElementById('comboWC').value;
    var amueblado = document.getElementById('comboAmueblado').value;
    var aparcamiento = document.getElementById('comboAparcamiento').value;
    var cocina = document.getElementById('comboCocina').value;
    var metros= document.getElementById('textMetros').value;
    var fianza = document.getElementById('textFianza').value;
    var fumador = document.getElementById('comboFumador').value;
    var genero = document.getElementById('comboGenero').value;
    var animales= document.getElementById('comboAnimales').value;
    var paginaActual = document.getElementById('paginaActual').value;
    var orderBy = document.getElementById('orderBy').value;
		
    var parametrosUrl = "";
    if (textoLibre != ""){
        parametrosURL = "text=" + textoLibre;
    }else{
        parametrosURL =  "IDIsla=" + isla;
    }
    //var parametrosUrl = "";

    // parametrosURL =  "IDIsla=" + isla;

    if (municipio != "") parametrosURL = parametrosURL + "&IDMunicipio=," + municipio; //la lista de municipios debe comenzar con una coma asi que no la quites!!
    if (precioMin != -1) parametrosURL = parametrosURL + "&preciomin=" + precioMin;
    if (precioMax != -1) parametrosURL = parametrosURL + "&preciomax=" + precioMax;
    if (rooms != -1) parametrosURL = parametrosURL + "&rooms=" + rooms;
    if (piscina != -1) parametrosURL = parametrosURL + "&piscina=" + piscina;
    if (wc != -1) parametrosURL = parametrosURL + "&wc=" + wc;
    if (amueblado != -1) parametrosURL = parametrosURL + "&amueblado=" + amueblado;
    if (aparcamiento != -1) parametrosURL = parametrosURL + "&aparc=" + aparcamiento;
    if (cocina != -1) parametrosURL = parametrosURL + "&cocina=" + cocina;
    if ((metros != "") && (metros>0)) parametrosURL = parametrosURL + "&metrosint=" + metros;
    if (tipo != "") parametrosURL = parametrosURL + "&IDTipo=" + tipo;
    if (regimen != -1) {
        parametrosURL = parametrosURL + "&regimen=" + regimen;
        if (regimen == 1) {//alquiler
            if ((fianza != "") && (fianza > 0)) parametrosURL = parametrosURL + "&fianza=" + fianza;
            if (fumador != -1) parametrosURL = parametrosURL + "&fumador=" + fumador;
            if (genero != -1) parametrosURL = parametrosURL + "&genero=" + genero;
            if (animales != -1) parametrosURL = parametrosURL + "&animales=" + animales;
        }
    }
    parametrosURL = parametrosURL + "&pagina=" + paginaActual;
    if (orderBy != -1)  parametrosURL = parametrosURL + "&orderBy=" + orderBy;
   
    return parametrosURL;
}
	
//********************************************************************************************	
//Esta funcion convierte caracteres HTML a caracteres reales en Javascript

function html_decode(cadena){
    var nuevaCadena=cadena;
	
    fromTo = new Array('&AElig;','�','&Aacute;','�','&Acirc;','�','&Agrave;','�','&Aring;','�','&Atilde;', '�','&Auml;','�','&Ccedil;','�','&ETH;','�','&Eacute;','�','&Ecirc;','�','&Egrave;','� ','&Euml;','�','&Iacute;','�','&Icirc;','�','&Igrave;','�','&Iuml;','�','&Ntilde;','�', '&Oacute;','�','&Ocirc;','�','&Ograve;','�','&Oslash;','�','&Otilde;','�','&Ouml;','�','&THORN; ','�','&Uacute;','�','&Ucirc;','�','&Ugrave;','�','&Uuml;','�','&Yacute;','�','&aacute;', '�','&acirc;','�','&aelig;','�','&agrave;','�','&aring;','�','&atilde;','�','&auml;','� ','&brvbar;','�','&ccedil;','�','&cent;','�','&copy;','�','&deg;','�','&eacute;','�', '&ecirc;','�','&egrave;','�','&eth;','�','&euml;','�','&frac12;','�','&frac14;','�','&frac34; ','�','&gt;','>','&gt','>','&iacute;','�','&icirc;','�','&iexcl;','�','&igrave;','�','&iquest;','�','&iuml;','�', '&laquo;','�','&lt;','<','&lt','<','&mdash;','�','&micro;','�','&middot;','�','&ndash;','�','&not;','�','&ntilde;','�', '&oacute;','�','&ocirc;','�','&ograve;','�','&oslash;','�','&otilde;','�','&ouml;','�','&para;','�','&plusmn;','�','&pound;',' �','&quot;','\"','&raquo;','�','&reg;','�','&sect;','�','&shy;','*','&sup1;','�','&sup2;','�', '&sup3;','�','&szlig;','�','&thorn;','�','&tilde;','�','&trade;','�','&uacute;','�','&ucirc; ','�','&ugrave;','�','&uuml;','�','&yacute;','�','&yen;','�','&yuml;','�');
	
    for (i=0; i < fromTo.length; i=i+2)
        nuevaCadena = nuevaCadena.replace(eval('/'+fromTo[i]+'/g'), fromTo[i+1]);
	
    return nuevaCadena;
}
//*******************************************************************************
function guardaHistorialBusquedas(parametros) {
    var xmlHttp;
    try{// Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    xmlHttp.onreadystatechange=function() {
        if(xmlHttp.readyState==4){
    //no ponemos nada aqui ya que insertamos la busqueda en la bbdd, pero esto es transparente para el usuarioWeb
    }
    }
		
    url="ajax/guardaDatosHistorialBusquedas.php?"+parametros;
    //a�adimos esto para evitar que la pagina se coja de la cache en la llamada AJAX
    var currentTime = new Date();
    var timestamp = currentTime.getTime();
    url=url+"&time="+timestamp;
		
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}

//*******************************************************************************
//Esta funcion obtiene mediante una llamada ajax la cadena de los parametros almacenados en la bbdd para la busqueda con idBusqueda=id
//La llamada ajax es SINCRONA
function generaCadenaVariablesIdBusqueda(id) {
    var xmlHttp;
    try{// Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
		
    url="ajax/busquedas/generaCadenaVariablesIdBusqueda.php?idBusqueda="+id;
		
    xmlHttp.open("GET",url,false);
    xmlHttp.send(null);
    return $.trim(xmlHttp.responseText);
}

