var aSolapas 				= new Array('pest_enventa','pest_obranueva','pest_enalquiler','pest_vacacional')
var array_nombres 			= new Array()
var array_nombres_aux
var array_id_poblacion 		= new Array()
var array_id_poblacion_aux
var busquedas 				= new Array()
var miLayer 				= new Clayer('',344)
var miLayerTel				= new Clayer('',400,160)
var opcion 					= ''
var modo 					= ''
var pre_move 				= true
var letras 					= ''
var tiempo 					= 400
var posicion 				= -1
var num_enlaces 			= 0
var posicion 				= -1
var ok_pred 				= 0
var idTO;	
var fbr_tipo				= ''
var ajax_predictivo			= new AjaxV4()
var ajaxQueBusco 			= new AjaxV4()
var ajax_resultado 			= new AjaxV4()
var BusqAnt					= ''
var caracteres_limit		= 3
var IntentandoBuscar		= 0

function verBien(id)
{
	window.open("http://casas.facilisimo.com/fi" + id + ".html", "b_" + id, "width=800,height=800,scrollbars=yes");
}

function verBienAmpl(id)
{
	document.location.href='/buscar/ampliados/?bien=' + id	
}

function verON(url, nombre, atributos)
{
	if (typeof(arguments[2]) == 'undefined')
		atributos = 'width=800,height=800,scrollbars=yes'
	if ((arguments[1] == '') || (arguments[1] == '-1'))
		nombre = 'v' + Math.ceil(Math.random() * 100000)	
	if (atributos != '')
		url += escape('?nv=nv')
	window.open(url, nombre, atributos);
}

// Función que obtiene el id_poblacion o lanza una ventana nueva si es un teléfono encontrado.
function puede_buscar(res,telefono)
{
	var res_prof = res
	if (res_prof == 'ERROR01 ') 
		$aviso('El número de teléfono introducido no se corresponde con ningún piso publicado.')
	else
	{
		var res_prof = res_prof.split('$$$$')
		if (res_prof.length > 1)
		{
			tipo = res_prof[0]
			if (tipo == 'profesional')
			{
				var anunciante	= res_prof[1]
				var poblacion 	= res_prof[2]
				var telefono1 	= res_prof[3]
				var telefono2 	= res_prof[4]
				var direccion 	= res_prof[5]
				var web 		= res_prof[6]
				var logo 		= res_prof[7]
				var id_oficina 	= res_prof[8]
				verViviendasPropietario('', anunciante, direccion, web, logo, telefono, telefono2, poblacion, id_oficina)
			}
		}
		else
		{
			obj = eval('(' + res + ')')
			
			if (obj.recordcount > 0)
			{
				if (obj.recordcount >1)
				{
					var listado = "Pisos encontrados con el telefono <b>"+telefono+"</b>:<br><br>";
					for (i=0;i<obj.recordcount;i++)
					{
						var id_bien = obj.data.id_bien[i].toString()
						var tipo_bien = obj.data.tipo_bien[i].toString()
						var provincia = obj.data.provincia[i].toString()
						var poblacion = obj.data.poblacion[i].toString()
						var habitaciones = obj.data.habitaciones[i].toString()
						var superficie = obj.data.superficie[i].toString()
						var contrato = obj.data.contrato[i].toString()				
						var texto_contrato = (contrato == 'V')?'en venta':'en alquiler'
						listado += '<span style="color:#666">&raquo;</span> <a href="#" onclick="verBien('+id_bien+')">' +tipo_bien + ' ' + texto_contrato + ' de ' + habitaciones + ' dormitorios con ' + superficie + ' m&sup2;, '+ poblacion + '('+provincia+')</a><br>'
					}
					miLayerTel.setMensaje(listado)
					miLayerTel.setTitulo('Resultados de la Busqueda:')
					miLayerTel.setActionDefault('miLayerTel.Cerrar()')
					miLayerTel.open()
				}
				else
				{
					var id_bien = obj.data.id_bien[0].toString()
					verBienAmpl(id_bien);
				}
			}
			else $aviso('El número de teléfono introducido no se corresponde con ningún piso publicado.')
		}
	}
}

// Función que obtiene el predictivo de la búsqueda rápida de la portada...
var llamada = 0;
function lanzar_predictivo()
{
	var f = document.busqueda_rapida
	var texto_buscado = quitar_acentos(f.texto_buscado.value)	
	var primera_letra = (texto_buscado != "")?texto_buscado.substr(0, 1):""
	f.id_poblacion.value = ""
	if (isNaN(texto_buscado.trim()))	
		modo = 'poblacion'
	else 
	{
		if ($10(primera_letra) < 6) 
		{
			if (texto_buscado.length > 5)
			{
				var texto_cortado = texto_buscado.substr(0, 5)
				f.texto_buscado.value = texto_cortado
				texto_buscado = texto_cortado
			}
			modo = "cod_postal"
		}
		else 
		{
			if (texto_buscado.length > 9)
			{
				var texto_cortado = texto_buscado.substr(0,9)
				f.texto_buscado.value = texto_cortado
				texto_buscado = texto_cortado
			}
			$("predictivo_busqueda").style.display = "none"			
		}
	}
	
	texto_buscado = quitar_acentos(f.texto_buscado.value).toLowerCase()
	if (texto_buscado.length >= caracteres_limit )
	{
		if (typeof(busquedas[texto_buscado.substr(0,caracteres_limit)]) == 'undefined')
		{
			if (llamada == 0)
			{
				ajax_predictivo.url = "/xml/obtener_predictivo_busqueda.cfm?texto_buscado=" + escape(texto_buscado.substr(0,caracteres_limit)) + "&modo=" + modo
				ajax_predictivo.f = "Pintar_Predictivo_Busqueda(ajax_predictivo.xmlDoc.responseText)"
				ajax_predictivo.run()	
				llamada = 1
			}
		}
		else
			Pintar_Predictivo_Busqueda(busquedas[texto_buscado.substr(0,caracteres_limit)])
	}
	else
		llamada = 0
}

function IrAbajo()
{
	if (posicion < (num_enlaces - 1) && posicion < (parseInt(array_nombres.length) - 1))	
	{
		posicion++
		PintarEnlace()
		pre_move = true
	}
}

function IrArriba()
{
	if (posicion != 0)	
	{
		posicion--
		PintarEnlace()
		pre_move = true
	}
}

function PintarEnlace()
{
	for (i = 0; i < num_enlaces; i++)
	{
		if (i == posicion)
		{
			$('enlace_' + i).className = "enlace_busqueda_rapida"
			f = document.busqueda_rapida
			f.texto_buscado.value = array_nombres[posicion]
			f.id_poblacion.value = array_id_poblacion[posicion]
		}
		else 
		{
			if ($('enlace_' + i))
				$('enlace_' + i).className = ''
		}
	}	
}

function quitar_acentos(letras)
{
	var l = letras.toLowerCase()
	l = l.replace("á","a")
	l = l.replace("à","a")
	l = l.replace("é","e")
	l = l.replace("è","e")
	l = l.replace("ó","o")
	l = l.replace("ò","o")
	l = l.replace("í","i")
	l = l.replace("ì","i")
	l = l.replace("ú","u")
	l = l.replace("ù","u")
	return l
}

function buscar()
{
	var e = new Object()
	e.keyCode = 13
	presionarTecla(e)	
}

function borrarBusqueda(campo)
{
	if (campo.value.indexOf('Poblaci') > -1)
		campo.value = campo.value.substr(0, campo.value.indexOf('Poblaci'))
	campo.style.color = '#666'
}

function llamarPredictivo()
{
	lanzar_predictivo(document.busqueda_rapida)
}

function presionarTecla(evento)
{
	if (document.busqueda_rapida.texto_buscado.value.length > 0)
	{
		if (document.busqueda_rapida.texto_buscado.value.indexOf('Poblaci') > -1)
			document.location.href = '/buscar/?pagina=buscar_mapas_mapa&quebusco=' + fbr_tipo
			
		IntentandoBuscar = 1
		var e = evento.keyCode
		borrarBusqueda(document.busqueda_rapida.texto_buscado)	
		letras = document.busqueda_rapida.texto_buscado.value
	
		var teclas = {"38":1,"40":2,"13":3, "27":4}
		if ((letras != '') && !(e in teclas))
			llamarPredictivo()
		else
		{
			if (e == 40)
				IrAbajo()
			else if (e == 38)
				IrArriba()
			else  if (e == 13)
			{
				contenido = $('predictivo_busqueda').innerHTML
				if (array_nombres.length > 0 &&  contenido.indexOf('enlace_busqueda_rapida') != -1)
				{
					if (posicion == -1 && document.busqueda_rapida.texto_buscado.value != '')
						posicion = 0
					else
					{
						if (document.busqueda_rapida.texto_buscado.value == '')
							document.location.href = '/buscar/?pagina=buscar_mapas_mapa&quebusco=' + fbr_tipo
					}
				
					if (posicion > -1)
						pulsar_opcion(array_id_poblacion[posicion], array_nombres[posicion].replace("'", "''"), document.busqueda_rapida)					
				}
				else
				{
					if (!isNaN(letras) && $10(letras.substr(0,2)) > 52) 
					{
						modo = 'telefono'
						ajax_resultado.url = '/xml/puede_buscar.cfm'
						param = 'modo=telefono&texto_buscado='+letras
						ajax_resultado.f = 'puede_buscar(ajax_resultado.xmlDoc.responseText,\''+letras+'\')'
						ajax_resultado.post = param
						ajax_resultado.run()
					}
					else if (letras != '') 
						document.location.href = '/buscar/?pagina=buscar_mapas_mapa&quebusco=' + fbr_tipo + '&texto_buscado=' + escape(letras) + '&q='+escape(letras)+'+portada_mapa'
				}
				
			}
			else 
			{
				if (e == 27)
				{
					$11('predictivo_busqueda','')
					$('predictivo_busqueda').style.display = 'none'
				}
				else if (letras == '')
				{
					$11('predictivo_busqueda', '')
					$('predictivo_busqueda').style.display = 'none'
				}		
			}
		}
	}
	else 
	{
		var e = evento.keyCode
		if (e != 8)
		 	document.location.href = '/buscar/?pagina=buscar_mapas_mapa&quebusco=' + fbr_tipo
	}
}

function pulsar_opcion(id_poblacion, nombre, form)
{
	var nombre = unescape(nombre)
	opcion = fbr_tipo
	var nav = navigator.appName
	if (nav == "Microsoft Internet Explorer") 
		$Loading('Realizando b&uacute;squeda...')
	else
		setTimeout("$Loading('Realizando b&uacute;squeda...')",150)
	$Label('Realizando búsqueda...')
	$('predictivo_busqueda').style.display = 'none'
	LanzarBusqueda(opcion,modo,id_poblacion,nombre)
}

function LanzarBusqueda(opcion,modo,id_poblacion,texto_buscado)
{
	if (opcion == '') opcion = 'enventa'
	document.busqueda_rapida.texto_buscado.value = texto_buscado
	
	if (modo == 'cod_postal')
		texto_buscado = id_poblacion +","+texto_buscado
	
	if (param_desde == 'desportada' || param_desde == 'desfotocasa' || param_desde == 'desidealista' || param_desde == 'desfacilisimo' || param_desde == 'desportae' || param_desde == 'desurbaniza' || param_desde == 'desportadafacilisimo')
		//document.location.href = '/buscar/?pagina=buscar_mapas_mapa&quebusco=' + opcion + '&texto_buscado=' + escape(texto_buscado)+ '&q='+escape(texto_buscado)+'+portada_mapa&desde='+param_desde + '&id_localizacion='+ id_poblacion
		document.location.href = '/buscar/?pagina=buscar_' + opcion + '_resultados' + ((modo == 'poblacion')?'&id_localizacion=':'&cp=') + id_poblacion	+ '&q='+escape(texto_buscado)+'+portada&desde='+ param_desde
	else
		//document.location.href = '/buscar/?pagina=buscar_mapas_mapa&quebusco=' + opcion + '&texto_buscado=' + escape(texto_buscado)+ '&q='+escape(texto_buscado)+'+portada_mapa&id_localizacion='+ id_poblacion
		document.location.href = '/buscar/?pagina=buscar_' + opcion + '_resultados' + ((modo == 'poblacion')?'&id_localizacion=':'&cp=') + id_poblacion	+ '&q='+escape(texto_buscado)+'+portada'
}

function Pintar_Predictivo_Busqueda(s)
{
	array_nombres_aux = null
	array_id_poblacion_aux= null
	array_nombres_aux = new Array()
	array_id_poblacion_aux = new Array()
	
	if (s != "" )
	{
		f = document.busqueda_rapida
		aux = letras.substr(0,caracteres_limit)
		letras_busqueda = aux.toLowerCase()
		
		busquedas[letras_busqueda] = s
		var salida_busqueda = s	
		var sb = salida_busqueda.split('$$$$$$')
		if (sb[0] != "error")
		{
			obj = eval('(' + sb[0] + ')')
			var modo = sb[1]
		
			var resultado = ""
			num_enlaces = obj.recordcount
			if (obj.recordcount > 0)
			{
				var fin_bucle = parseInt(obj.recordcount)
				var indice_acumulativo = 0	
				for (k = 0; k< parseInt(obj.recordcount); k++)
				{
					if (modo == 'poblacion')
						chrs = obj.data.nombre[k].toString()
					else
						chrs = obj.data.id_poblacion[k].toString()	
					longitud_busqueda = letras.length
					chrs_busqueda = chrs.substr(0,longitud_busqueda)
					if (quitar_acentos(chrs_busqueda.toLowerCase()) == quitar_acentos(letras.toLowerCase()))
					{
						array_nombres_aux[indice_acumulativo] = obj.data.nombre[k].toString()
						array_id_poblacion_aux[indice_acumulativo] = obj.data.id_poblacion[k].toString()
						indice_acumulativo++
					}
				}

				if (indice_acumulativo > 0)
				{
					if (indice_acumulativo > 5)
						fin_bucle = 5
					else fin_bucle = indice_acumulativo
				}
				else fin_bucle = 0
				resultado += "<table width='100%'>"
				var textoEnlace = ""
				for(i = 0; i < fin_bucle; i++) 
				{
					array_nombres[i] = array_nombres_aux[i]
					array_id_poblacion[i] = array_id_poblacion_aux[i]
					resultado += '<tr><td valign="top" id="enlace_' + i +'" ' + ((i!=0)?'class="txt-cuerpo" style="border-top:1px #999 dotted;"':'class="enlace_busqueda_rapida">')
					
					textoEnlace = (modo == 'poblacion')?('<b>' + array_nombres[i].left(f.texto_buscado.value.length) + '</b>'):array_nombres[i].left(f.texto_buscado.value.length)						
					textoEnlace += array_nombres[i].substr(f.texto_buscado.value.length, array_nombres[i].length)
					
					resultado += '<a onclick=\'pulsar_opcion("'+array_id_poblacion[i]+'","'+escape(array_nombres[i])+'",document.busqueda_rapida)\'>' + textoEnlace	
					resultado += (modo == 'cod_postal')?' - <b>' + array_id_poblacion[i].left(f.texto_buscado.value.length) + '</b>' + array_id_poblacion[i].substr(f.texto_buscado.value.length,array_id_poblacion[i].length) + '</a></td>':'</a></td>'
					resultado += '</tr>'
				}
				ok_pred = 1
				resultado += "</table>"
			}
			else
			{
				resultado = ''
				array_nombres.length = 0
				array_id_poblacion.length = 0
				f.id_poblacion.value = ''
			}
			posicion = -1
			$11("predictivo_busqueda", resultado)
			contenido = $('predictivo_busqueda').innerHTML;
			(contenido.indexOf('enlace_busqueda_rapida') != -1)?$1("predictivo_busqueda"):$5("predictivo_busqueda");
		}
		else 
		{
			$5("predictivo_busqueda")
			resultado = ''
			f.id_poblacion.value = ''
		}
	}
	else $5("predictivo_busqueda")
}

function cerrar_predictivo()
{
	if (pre_move == false)
		$('predictivo_busqueda').style.display='none'
}

function onFocus()
{
	document.busqueda_rapida.texto_buscado.value = ""
}

function cambioSolapa(id)
{
	var obj = $(id)
	var obj2 = null
	obj.className = 'pestAct'
	for (var i = 0; i < aSolapas.length; i++)
	{
		obj2 = $(aSolapas[i])
		
		if (obj2.id != obj.id)
			obj2.className = 'pestDes'
		else fbr_tipo = aSolapas[i].replace('pest_', '')
	}
}

function mostrarBocataPort()
{
	$1('bocataPort')
	borrarBusqueda(document.busqueda_rapida.texto_buscado)
}

function cambioEstado(valor)
{
	ajaxQueBusco.url = '/buscar/mapas/cambioQuebusco.cfm?' + valor
	fbr_tipo = valor
	if (arguments.length == 1)
		ajaxQueBusco.f = "mostrarBocataPort()"
	else
		ajaxQueBusco.f = ""
	ajaxQueBusco.run()
}

function RecuperarValueBR(campo)
{
	if (campo.value == '')
	{
		campo.value = 'Población, código postal o teléfono del anuncio'
		campo.style.color = '#ccc'
	}
}

function verViviendasPropietario(ref, anunciante, direccion, web, logo, telefono, telefono2, poblacion, id_oficina)
{
	verViviendasPropietario_alfinal(ref, anunciante, direccion, web, logo, telefono, telefono2, poblacion, id_oficina)
}

var caja_pisos_propietario = '<style>'+
'.infoContent { float:left; margin:0 0 0 17px; -margin:0 0 0 8px; width:666px; }'+
'.infoContent .titu { float:left; margin:15px 0 0 0; font-size:15px; text-align:center; width:680px; height:20px; background:url(/images/puntosGrisX.gif) repeat-x bottom; font-weight:bold; }'+
'.infoContent .datos { float:left; margin:5px 0 0 0; width:525px; font-size:15px; }'+
'.infoContent .datos li { float:left; margin:5px 0 0 0; width:450px; list-style:none; }'+
'.infoContent .logo { float:right; margin:5px 0 0 0; width:138px; }'+
'</style>'+
'<div class="infoContent">'+
'<div class="datos">'+
'<li>&raquo; Direcci&oacute;n: <span title="$title_direccion$">$direccion$</span></li>'+
'<li>&raquo; Poblaci&oacute;n: <span title="$title_poblacion$">$poblacion$</span></li>'+
'<li>&raquo; Anunciante: <span title="$title_anunciante$">$anunciante$</span></li>'+
'<li>&raquo; Web: <span title="$title_web$">$web$</span></li>'+
'<li>&raquo; Telefono: $telefono$</li>'+
'</div>'+
'<div class="logo" style="background:url($logo$) no-repeat center center;"><img src="/images/marcoLogoProfesional.gif" /></div>'+
'<div class="titu">Viviendas de este anunciante</div>'+
'<div class="datos">'+
'<iframe name="pisos_propietario" id="pisos_propietario" src="/buscar/enventa/pisos_propietario.cfm?id_oficina=$id_oficina$" width="690" frameborder="0" scrolling="no" height="470" style="background:none;margin:0 auto; padding:0;"></iframe>'+
'</div>'+
'</div>'

function verViviendasPropietario_alfinal(ref, anunciante, direccion, web, logo, telefono, telefono2, poblacion, id_oficina)
{
	var id_bien = ''
	if (direccion == '')
		direccion = 'No disponible'
	if (web.replace('http://', '') == '')
		web = 'No disponible'
	title_anunciante = anunciante
	title_direccion = direccion
	title_web = web
	
	anunciante 	= $CutText(anunciante, 65)
	direccion 	= $CutText(direccion, 50)
	web			= $CutText(web, 50)
	
	var caja = caja_pisos_propietario

	var logo = 'http://images3.facilisimo.com/' + logo
	var logo = logo.replace('/i/','')
	caja = caja.replace('$web$', web)
	caja = caja.replace('$anunciante$', anunciante)
	caja = caja.replace('$poblacion$', poblacion)
	caja = caja.replace('$direccion$', direccion)
	caja = caja.replace('$title_direccion$',direccion)
	caja = caja.replace('$title_anunciante$',anunciante)
	caja = caja.replace('$title_web$',web)
	caja = caja.replace('$title_poblacion$',poblacion)
	caja = caja.replace('$logo$', logo)
	caja = caja.replace('$telefono$', telefono)
	
	miLayer.setAncho(710)
	miLayer.setAlto(715)
	miLayer.setMensaje(caja)	
	miLayer.setTitulo(anunciante)
	miLayer.setActionDefault("miLayer.Cerrar()")
	miLayer.open()
	$('pisos_propietario').src = '/buscar/enventa/pisos_propietario.cfm?id_oficina=' + id_oficina + '&rnd=' + Math.random()
}


function muestra(nombre, id_oficina, telefono, telefono2, id_bien, id_localizacion, ref_inmo)
{
		muestra_alfinal(nombre,id_oficina,telefono,telefono2,id_bien,id_localizacion,ref_inmo)
}

function muestra_alfinal(nombre,id_oficina,telefono,telefono2,id_bien,id_localizacion,ref_inmo)
{
		var obj = $('imagen_contacto')
		var a = new Array()
		obj.src='/buscar/px_datos_contacto.cfm?ord='+Math.random()+'&id_bien='+id_bien
					
		obj = $('imagen_google')
		obj.src = 'http://www.googleadservices.com/pagead/conversion/1071788022/extclk?script=0'
		
		var texto = cajas.caja_ver_telefono_anunciante
		var nombre2 = nombre
		var MAXCAR = 32;
		
		if (parseInt(telefono,10) > 0)
		{
			aux_telefono = reverse(telefono)
			aux_telefono = parseInt(aux_telefono,10) - parseInt(id_bien,10)
			a_tel = aux_telefono.toString()
			aux_telefono = a_tel.substr(0,3) + ' ' + a_tel.substr(3,3) + ' ' + a_tel.substr(6,3)
			a[a.length] = aux_telefono
		}
		if (parseInt(telefono2,10) > 0)
		{
			aux_telefono2 = reverse(telefono2)
			aux_telefono2 = parseInt(aux_telefono2,10) - parseInt(id_bien,10)
			a_tel2 = aux_telefono2.toString()
			aux_telefono2 = a_tel2.substr(0,3) + ' ' + a_tel2.substr(3,3) + ' ' + a_tel2.substr(6,3)
			a[a.length] = aux_telefono2
		}
		
		if (a.length == 1)
			texto = texto.replace('$texto_telefono$', 'Su tel&eacute;fono es: ')
		else
			texto = texto.replace('$texto_telefono$', 'Sus tel&eacute;fonos son: ')
		
		texto = texto.replace('$telefono$', a.join(' - '))
		texto = texto.replace('$ref_inmo$', (ref_inmo == '')?id_bien:ref_inmo)
		texto = texto.replace('$id_bien$', id_bien)
		texto = texto.replace('$id_localizacion$', id_localizacion)
		
		if (nombre.length > MAXCAR)
			nombre2 = nombre.substr(0, MAXCAR) + '...'
			
		
		miLayer.setAncho(570)
		miLayer.setAlto(205)
		miLayer.setMensaje(texto)
		if (id_oficina.right(3) == '000')
			miLayer.setTitulo('Anunciante particular: <span class="font20" style="font-weight: bold" title="' + nombre + '">' + nombre2 + '</span>')
		else
			miLayer.setTitulo('Anuncio publicado por: <span class="font20" style="font-weight: bold" title="' + nombre + '">' + nombre2 + '</span>')
		miLayer.setActionDefault("miLayer.Cerrar()")
		miLayer.open()		
}