// Variables de búsqueda globales

var tipo_global = "0";
var idprovincia_global = "0";
var idlocalidad_global = "0";
var operacion_global = "0";
var precio_min_global = "0";
var precio_max_global = "0";
var filtro_global = "0";
var orden_global = "0";
var pagina_global = 1;

// Precarga de imagenes de buscador interior (mejora la estetica del efecto fade) //
var i; 
var imagenes = new Array("img/cargando1.gif","img/cargando2.gif","img/buscador_lateral.jpg","img/buscador.jpg","img/bot_buscar.gif","img/selector.gif","img/graf_selector.gif","img/filtros_izq.jpg","img/filtros_der.jpg","img/bot_filtrar.gif","img/bot_fecha_alta.gif","img/bot_precio.gif","img/bot_fecha_alta2.gif","img/bot_habitaciones.gif"); 
var lista_imagenes = new Array(); 

function precarga_imagenes(){ 

	for(i in imagenes){ 
	lista_imagenes[i] = new Image(); 
	lista_imagenes[i].src = imagenes[i]; 
	} 

} 
//--------------------------------------------------------------------------------//

function selec_provincia(tipo){
var myConn_selec_provincia = new XHConn();
document.getElementById('div_selec_idprovincia').innerHTML = '<img src="img/cargando1.gif" width="90" height="13">';
document.getElementById('div_selec_idlocalidad').innerHTML = '<select name="idlocalidad" class="campos_buscador"><option value="0" selected>-</option></select>';
document.getElementById('div_selec_operacion').innerHTML = '<select name="operacion" class="campos_buscador"><option value="0" selected>-</option></select>';
var fin_selec_provincia = function (oXML) { document.getElementById('div_selec_idprovincia').innerHTML = oXML.responseText;};
myConn_selec_provincia.connect("buscador/selec_idprovincia.php", "GET", "tipo="+tipo, fin_selec_provincia);
}

function selec_localidad(tipo,idprovincia){
	if (idprovincia != "0"){
		var myConn_selec_localidad = new XHConn();
		document.getElementById('div_selec_idlocalidad').innerHTML = '<img src="img/cargando1.gif" width="90" height="13">';
		document.getElementById('div_selec_operacion').innerHTML = '<select name="operacion" class="campos_buscador"><option value="0" selected>-</option></select>';
		var fin_selec_localidad = function (oXML) { document.getElementById('div_selec_idlocalidad').innerHTML = oXML.responseText;};
		myConn_selec_localidad.connect("buscador/selec_idlocalidad.php", "GET", "tipo="+tipo+"&idprovincia="+idprovincia, fin_selec_localidad);
	}
}

function selec_operacion(tipo,idlocalidad){
	if (idlocalidad != "0"){
		var myConn_selec_operacion = new XHConn();
		document.getElementById('div_selec_operacion').innerHTML = '<img src="img/cargando1.gif" width="90" height="13">';
		var fin_selec_operacion = function (oXML) { document.getElementById('div_selec_operacion').innerHTML = oXML.responseText;};
		myConn_selec_operacion.connect("buscador/selec_operacion.php", "GET", "tipo="+tipo+"&idlocalidad="+idlocalidad, fin_selec_operacion);
	}
}

function buscar_ini(){
precio_min_global = "0";
precio_max_global = "0";
filtro_global = "0";
orden_global = "0";
pagina_global = 1;

tipo_global = document.form_buscador_ini.tipo.value;
idprovincia_global = document.form_buscador_ini.idprovincia.value;
idlocalidad_global = document.form_buscador_ini.idlocalidad.value;
operacion_global = document.form_buscador_ini.operacion.value;


	if (idlocalidad_global == "0"){
	alert ("Seleccione una localidad");
	} else {
		new Effect.Fade('div_contenido_main',{afterFinish: function(){carga_buscador_int(tipo_global,idprovincia_global,idlocalidad_global,operacion_global);}});
		return false;
	}	
	

	function carga_buscador_int(tipo_global,idprovincia_global,idlocalidad_global,operacion_global){
	var myConn_buscador_int = new XHConn();
	var fin_buscador_int = function (oXML) { document.getElementById('div_contenido').innerHTML = oXML.responseText; document.getElementById("div_buscador_int").style.display = 'none'; new Effect.Appear('div_buscador_int',{afterFinish: function(){ancla_dinamica('a_contenido'); carga_mapa(tipo_global,idprovincia_global,idlocalidad_global,operacion_global); carga_selector_precios(); listado_inmuebles();}});};
	myConn_buscador_int.connect("buscador/buscador_int.php", "GET", "tipo="+tipo_global+"&idprovincia="+idprovincia_global+"&idlocalidad="+idlocalidad_global+"&operacion="+operacion_global, fin_buscador_int);
	}

}

function buscar_int(){
precio_min_global = "0";
precio_max_global = "0";
filtro_global = "0";
orden_global = "0";
pagina_global = 1;

tipo_global = document.form_buscador_ini.tipo.value;
idprovincia_global = document.form_buscador_ini.idprovincia.value;
idlocalidad_global = document.form_buscador_ini.idlocalidad.value;
operacion_global = document.form_buscador_ini.operacion.value;

if (idlocalidad_global == "0"){
	alert ("Seleccione una localidad");
} else {
	var cargando_mapa = '<table width="321" height="230" border="0" cellpadding="0" cellspacing="0"><tr><td align="center" valign="middle" bgcolor="#FFFFFF">';
	cargando_mapa += '<img src="img/cargando2.gif" width="21" height="25"><br><br><span class="txt_11">Cargando mapa de disponibilidades...</span>';
	cargando_mapa += '</td></tr></table>';
	document.getElementById('mapa_busqueda').innerHTML = cargando_mapa;
	carga_mapa(tipo_global,idprovincia_global,idlocalidad_global,operacion_global);
	carga_selector_precios();
	filtro_global = "0";
	orden_global = "0";
	pagina_global = 1;
	listado_inmuebles();
}

}

function listado_inmuebles(){
	ancla_dinamica('a_contenido');
	var myConn_listado_inmuebles = new XHConn();
	var cargando = '<table width="700" height="200" border="0" align="center" cellpadding="0" cellspacing="0"><tr>';
	cargando += '<td align="center" valign="middle"><img src="img/cargando3.gif" width="36" height="36" align="absmiddle"> <span class="verdana txt_11 negrita">&nbsp;&nbsp;Localizando Inmuebles... </span></td>';
	cargando += '</tr></table>';
	document.getElementById('div_listado_inmuebles').innerHTML = cargando;
	var fin_listado_inmuebles = function (oXML) { document.getElementById('div_listado_inmuebles').innerHTML = oXML.responseText; contador_historico(); bb_save_state();};
	myConn_listado_inmuebles.connect("buscador/listado_inmuebles.php", "GET", "pagina="+pagina_global+"&tipo="+tipo_global+"&idprovincia="+idprovincia_global+"&idlocalidad="+idlocalidad_global+"&operacion="+operacion_global+"&precio_min="+precio_min_global+"&precio_max="+precio_max_global+"&filtro="+filtro_global+"&orden="+orden_global, fin_listado_inmuebles);
}

function ir_a_pagina(pagina){
	pagina_global = pagina;
	listado_inmuebles();
}


function carga_selector_precios(){
	var myConn_carga_selector = new XHConn();
	var fin_carga_selector = function (oXML) { document.getElementById('div_selector_precios').innerHTML = oXML.responseText;};
	myConn_carga_selector.connect("buscador/selector_precios.php", "GET", "tipo="+tipo_global+"&idprovincia="+idprovincia_global+"&idlocalidad="+idlocalidad_global+"&operacion="+operacion_global, fin_carga_selector);
}

function selector_precios(precio_min, precio_max){
	pagina_global = 1;
	filtro_global = "0";
	orden_global = "0";
	precio_min_global = precio_min;
	precio_max_global = precio_max;
	listado_inmuebles();
}

function selec_filtroB(filtroA){
	var myConn_filtroB = new XHConn();
	document.getElementById('div_selec_filtroB').innerHTML = '<img src="img/cargando1.gif" width="90" height="13">';
	var fin_filtroB = function (oXML) { document.getElementById('div_selec_filtroB').innerHTML = oXML.responseText;};
	myConn_filtroB.connect("buscador/selec_filtroB.php", "GET", "filtroA="+filtroA+"&tipo="+tipo_global+"&idlocalidad="+idlocalidad_global+"&operacion="+operacion_global, fin_filtroB);
}

function filtro_busqueda(){
	var filtroA = document.getElementById('filtroA').value;
	var filtroB = document.getElementById('filtroB').value;
	if (filtroA == "0"){
		alert("Debe seleccionar una opción de filtrado");
	} else {
		filtro_global = filtroA+'/'+filtroB;
		listado_inmuebles();
	}
}

function orden_busqueda(orden){
	
	if (orden == orden_global){
		orden_global = orden+" DESC";
	} else {
		orden_global = orden;
	}
	
	if (orden == 'fecha_actualizacion'){ 
		if (orden_global == 'fecha_actualizacion DESC'){
		document.getElementById('td_orden_fecha').style.backgroundImage = "url('img/bot_fecha_alta2.gif')";
		} else {
		document.getElementById('td_orden_fecha').style.backgroundImage = "url('img/bot_fecha_alta.gif')";
		}
		document.getElementById('td_orden_precio').style.backgroundImage = "url('img/bot_precio_desac.gif')";
		document.getElementById('td_orden_superficie').style.backgroundImage = "url('img/bot_superficie_desac.gif')";
		document.getElementById('td_orden_habitaciones').style.backgroundImage = "url('img/bot_habitaciones_desac.gif')";
	}
	
	if (orden == 'precio'){ 
		if (orden_global == 'precio DESC'){
		document.getElementById('td_orden_precio').style.backgroundImage = "url('img/bot_precio2.gif')";
		} else {
		document.getElementById('td_orden_precio').style.backgroundImage = "url('img/bot_precio.gif')";
		}
		document.getElementById('td_orden_fecha').style.backgroundImage = "url('img/bot_fecha_alta_desac.gif')";
		document.getElementById('td_orden_superficie').style.backgroundImage = "url('img/bot_superficie_desac.gif')";
		document.getElementById('td_orden_habitaciones').style.backgroundImage = "url('img/bot_habitaciones_desac.gif')";
	}
	
	if (orden == 'superficie'){ 
		if (orden_global == 'superficie DESC'){
		document.getElementById('td_orden_superficie').style.backgroundImage = "url('img/bot_superficie2.gif')";
		} else {
		document.getElementById('td_orden_superficie').style.backgroundImage = "url('img/bot_superficie.gif')";
		}
		document.getElementById('td_orden_precio').style.backgroundImage = "url('img/bot_precio_desac.gif')";
		document.getElementById('td_orden_fecha').style.backgroundImage = "url('img/bot_fecha_alta_desac.gif')";
		document.getElementById('td_orden_habitaciones').style.backgroundImage = "url('img/bot_habitaciones_desac.gif')";
	}
	
	if (orden == 'habitaciones'){ 
		if (orden_global == 'habitaciones DESC'){
		document.getElementById('td_orden_habitaciones').style.backgroundImage = "url('img/bot_habitaciones2.gif')";
		} else {
		document.getElementById('td_orden_habitaciones').style.backgroundImage = "url('img/bot_habitaciones.gif')";
		}
		document.getElementById('td_orden_precio').style.backgroundImage = "url('img/bot_precio_desac.gif')";
		document.getElementById('td_orden_superficie').style.backgroundImage = "url('img/bot_superficie_desac.gif')";
		document.getElementById('td_orden_fecha').style.backgroundImage = "url('img/bot_fecha_alta_desac.gif')";
	}
	
	listado_inmuebles();
}

function ficha_inmueble(idinmueble,iddelegacion){
	var myConn_ficha_inmueble = new XHConn();
	var cargando = '<table width="700" height="200" border="0" align="center" cellpadding="0" cellspacing="0"><tr>';
	cargando += '<td align="center" valign="middle"><img src="img/cargando3.gif" width="36" height="36" align="absmiddle"> <span class="verdana txt_11 negrita">&nbsp;&nbsp;Cargando ficha de inmueble... </span></td>';
	cargando += '</tr></table>';
	document.getElementById('div_listado_inmuebles').innerHTML = cargando;
	var fin_ficha_inmueble = function (oXML) { document.getElementById('div_listado_inmuebles').innerHTML = oXML.responseText; contador_historico(); bb_save_state(); mapa_delegaciones(iddelegacion,'296','194'); ancla_dinamica('a_ficha');};
	myConn_ficha_inmueble.connect("buscador/ficha_inmueble.php", "GET", "idinmueble="+idinmueble+"&iddelegacion="+iddelegacion, fin_ficha_inmueble);
}

// Google Maps --------------------------------------------//

function clic_geomarca(idlocalidad){

idlocalidad_global = idlocalidad;
carga_selector_precios();
filtro_global = "0";
orden_global = "0";
pagina_global = 1;
listado_inmuebles();
}

// función que redimensiona el iframe que se carga en el div de detalles de marca
function redimensiona_alt()
{
  var altura=document.getElementById('f_detalles').contentWindow.document.body.scrollHeight;
  document.getElementById('f_detalles').height=altura;
  document.getElementById('div_detalle_mapa').style.height=altura;
}

var map; //hacemos global la variable para poder interactuar con otras funciones
function carga_mapa(tipo,idprovincia,idlocalidad,operacion) {
	var urlstr="buscador/xml_centro_mapa.php?idlocalidad="+idlocalidad;
	var request = GXmlHttp.create();
	request.open("GET", urlstr, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
		var xmlDoc = request.responseXML;
		var markers = xmlDoc.documentElement.getElementsByTagName("marker");
			for (var i = 0; i < markers.length; i++) {
			longitud_centro = parseFloat(markers[i].getAttribute("lng"));
			latitud_centro = parseFloat(markers[i].getAttribute("lat"));
       		inicia_mapa(longitud_centro,latitud_centro,tipo,idprovincia,idlocalidad,tipo,operacion);
			}
    	 }
	}
	request.send(null);
	
function inicia_mapa(longitud_centro,latitud_centro,tipo,idprovincia,idlocalidad,operacion){

	document.getElementById('mapa_busqueda').style.width = '321px';
	document.getElementById('mapa_busqueda').style.height = '230px';

	var icon = new GIcon();
	icon.image = "http://www.f3c.eu/img/marca_mapa.png";
	icon.shadow = "http://www.f3c.eu/img/sombra_marca.png";
	icon.iconSize = new GSize(27, 41);
	icon.shadowSize = new GSize(37, 34);
	icon.iconAnchor = new GPoint(6, 40);
	icon.infoWindowAnchor = new GPoint(5, 1);

	map = new GMap2(document.getElementById("mapa_busqueda"));
	map.addControl(new GSmallMapControl());
	map.setCenter(new GLatLng(latitud_centro, longitud_centro), 11);
	map.setMapType(G_NORMAL_MAP);

	function createInfoMarker(point,tipo,idprovincia,idlocalidad,operacion) {
	var marker = new GMarker(point, icon);
	// cargamos el contenido del detalle dentro de un iframe para solucionar el bug de Explorer con el z-index de los desplegables
	GEvent.addListener(marker, "mouseover", function() { ddrivetip('<div id=\'div_detalle_mapa\' align=\'center\'><IFRAME name=\'f_detalles\' id=\'f_detalles\' frameborder=0 scrolling=no marginwidth=0 src=\'buscador/detalles_mapa.php?idlocalidad='+idlocalidad+'\' marginheight=0 width=200 height=10></iframe></div>');} );
	GEvent.addListener(marker, "mouseout", function() { hideddrivetip(); } );
	GEvent.addListener(marker, "click", function() { document.location.href='javascript:clic_geomarca('+idlocalidad+')';} );
	return marker;
	}
	
	var urlstr="buscador/xml_marcas_mapa.php?tipo="+tipo+"&idprovincia="+idprovincia+"&idlocalidad="+idlocalidad;
	var request = GXmlHttp.create();
	request.open("GET", urlstr, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
		var xmlDoc = request.responseXML;
		var markers = xmlDoc.documentElement.getElementsByTagName("marker");
			for (var i = 0; i < markers.length; i++) {
			var point = new GPoint(parseFloat(markers[i].getAttribute("lng")), parseFloat(markers[i].getAttribute("lat")));
			//var address = '<table width=\"182\" height=\"90\" border=\"0\" class=\"borde_tabla_azul\" bgcolor=\"#FFFFCC\"><tr><td height=\"18\" bgcolor=\"#4D6DA8\" class=\"txt2 Estilo1\"><div align=\"center\">'+markers[i].getAttribute("localidad")+'</div></td></tr><tr><td class=\"txt2\"><div align=\"center\">'+markers[i].getAttribute("nom_tipo")+' en venta: <span class=\"Estilo4\">'+markers[i].getAttribute("inmuebles_venta")+'</span></div></td></tr><tr><td class=\"txt2\"><div align=\"center\">'+markers[i].getAttribute("nom_tipo")+' en alquiler: <span class=\"Estilo4\">'+markers[i].getAttribute("inmuebles_alquiler")+'</span> </div></td></tr><tr><td class=\"txt2\"><div align=\"center\">Precio medio venta: <span class=\"Estilo4\">'+markers[i].getAttribute("precio_medio")+' €</span> </div></td></tr></table>';
			//var address = 'prueba';
			var marker = createInfoMarker(point,tipo,idprovincia,parseFloat(markers[i].getAttribute("idlocalidad")),operacion);
			map.addOverlay(marker);
       		}
			bb_save_state();
    	 }
	}
 	 request.send(null);

} // fin funcion inicia mapa

} // fin carga_mapa


//----- Anclas dinámicas -----------------------------------------//

var scrollInt;
var scrTime, scrSt, scrDist, scrDur, scrInt;

function scrollPage(){
	scrTime += scrInt;
	if (scrTime < scrDur) {
		window.scrollTo( 0, easeInOut(scrTime,scrSt,scrDist,scrDur) );
	}else{
		window.scrollTo( 0, scrSt+scrDist );
		clearInterval(scrollInt);
	}
}

function ancla_dinamica(aname){
	var anchors, i, ele;

	if (!document.getElementById)
		return;
	
	// get anchor
	anchors = document.getElementsByTagName("a");
	for (i=0;i<anchors.length;i++) {
		if (anchors[i].name == aname) {
			ele = anchors[i];
			i = anchors.length;
		}
	}
	
	// set scroll target
	if (window.scrollY)
		scrSt = window.scrollY;
	else if (document.documentElement.scrollTop)
		scrSt = document.documentElement.scrollTop;
	else
		scrSt = document.body.scrollTop;

	scrDist = ele.offsetTop - scrSt - 20;
	scrDur = 500;
	scrTime = 0;
	scrInt = 10;
	
	// set interval
	clearInterval(scrollInt);
	scrollInt = setInterval( scrollPage, scrInt );
}

function easeInOut(t,b,c,d){
	return c/2 * (1 - Math.cos(Math.PI*t/d)) + b;
}


//-------------------------------------------------------------------
//FICHA

var con_foto = new XHConn();
var fin_foto= function (oXML) { document.getElementById('div_cont_img').innerHTML = oXML.responseText; };
function visu_img(foto){
	var cargando = '<table width="200" height="141" border="0" cellpadding="0" cellspacing="0"><tr>';
  	cargando += '<td><div align="center" class="txt_10"><img src="img/cargando2.gif" width="21" height="25"><br><br>cargando imagen...<br></div></td></tr></table>';
	document.getElementById('div_cont_img').innerHTML = cargando;
	window.setTimeout("con_foto.connect('buscador/visu_foto.php', 'GET', 'foto="+foto+"', fin_foto)", 1000);
}

function validar_contacto(){
	if (document.form_contacto.nombre.value == ''){
	alert ("Por favor, escribe tu nombre");
	} else {
		if ((document.form_contacto.telefono.value == '') && (document.form_contacto.email.value == '')){
		alert ("Por favor, especifica tu número de teléfono o tu dirección de e-mail para que podamos contactar contigo");
		} else {
				contacto_ficha(document.form_contacto.nombre.value,document.form_contacto.telefono.value,document.form_contacto.email.value,document.form_contacto.comentarios.value,document.form_contacto.idinmueble.value)
		}
	}
}

var con_contacto_ficha= new XHConn();
var fin_contacto_ficha = function (oXML) { document.getElementById('div_contacto').innerHTML = oXML.responseText; };
function contacto_ficha(nombre,telefono,email,comentarios,idinmueble){
document.getElementById('boton').innerHTML = "";
con_contacto_ficha.connect("mail_contacto_ficha.php", "GET", "nombre="+nombre+"&telefono="+telefono+"&email="+email+"&comentarios="+comentarios+"&idinmueble="+idinmueble, fin_contacto_ficha);
}

// Gerenador de etiquetas ALT--------------------------------------------

var offsetfromcursorX=12 //Customize x offset of tooltip
var offsetfromcursorY=10 //Customize y offset of tooltip

var offsetdivfrompointerX=10 //Customize x offset of tooltip DIV relative to pointer image
var offsetdivfrompointerY=14 //Customize y offset of tooltip DIV relative to pointer image. Tip: Set it to (height_of_pointer_image-1).

document.write('<div id="dhtmltooltip"></div>') //write out tooltip DIV
document.write('<img id="dhtmlpointer" src="http://www.f3c.eu/img/arrow2.gif">') //write out pointer image

var ie=document.all
var ns6=document.getElementById && !document.all
var enabletip=false
if (ie||ns6)
var tipobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : ""

var pointerobj=document.all? document.all["dhtmlpointer"] : document.getElementById? document.getElementById("dhtmlpointer") : ""

function ietruebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function ddrivetip(thetext, thewidth, thecolor){
if (ns6||ie){
if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px"
if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor
tipobj.innerHTML=thetext
enabletip=true
return false
}
}

function positiontip(e){
if (enabletip){
var nondefaultpos=false
var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
//Find out how close the mouse is to the corner of the window
var winwidth=ie&&!window.opera? ietruebody().clientWidth : window.innerWidth-20
var winheight=ie&&!window.opera? ietruebody().clientHeight : window.innerHeight-20

var rightedge=ie&&!window.opera? winwidth-event.clientX-offsetfromcursorX : winwidth-e.clientX-offsetfromcursorX
var bottomedge=ie&&!window.opera? winheight-event.clientY-offsetfromcursorY : winheight-e.clientY-offsetfromcursorY

var leftedge=(offsetfromcursorX<0)? offsetfromcursorX*(-1) : -1000

//if the horizontal distance isn't enough to accomodate the width of the context menu
if (rightedge<tipobj.offsetWidth){
//move the horizontal position of the menu to the left by it's width
tipobj.style.left=curX-tipobj.offsetWidth+"px"
nondefaultpos=true
}
else if (curX<leftedge)
tipobj.style.left="5px"
else{
//position the horizontal position of the menu where the mouse is positioned
tipobj.style.left=curX+offsetfromcursorX-offsetdivfrompointerX+"px"
pointerobj.style.left=curX+offsetfromcursorX+"px"
}

//same concept with the vertical position
if (bottomedge<tipobj.offsetHeight){
tipobj.style.top=curY-tipobj.offsetHeight-offsetfromcursorY+"px"
nondefaultpos=true
}
else{
tipobj.style.top=curY+offsetfromcursorY+offsetdivfrompointerY+"px"
pointerobj.style.top=curY+offsetfromcursorY+"px"
}
tipobj.style.visibility="visible"
if (!nondefaultpos)
pointerobj.style.visibility="visible"
else
pointerobj.style.visibility="hidden"
}
}

function hideddrivetip(){
if (ns6||ie){
enabletip=false
tipobj.style.visibility="hidden"
pointerobj.style.visibility="hidden"
tipobj.style.left="-1000px"
tipobj.style.backgroundColor=''
tipobj.style.width=''
}
}

document.onmousemove=positiontip