/*                                                                                Tooltips (Tt)
 *---------------------------------------------------------------------------------------------
 */
$(function() {
	var posicionarTt = function(event) {
		var tPosX = event.pageX - 10;
		var tPosY = event.pageY - 35;
		$("div.tooltip").css({
			top: tPosY,
			left: tPosX
		});
	}

	var mostrarTt = function(event){
	    $("div.tooltip").remove();
		var textoTt = (this.title) ? this.title : $(this).text();
		$("<div class='tooltip'>" + textoTt + "</div>")
		   .appendTo("body");
	    posicionarTt(event);
	}

	var ocultarTt = function() {
		$("div.tooltip").remove();
	}

	$(".conTt").hover(mostrarTt, ocultarTt).mousemove(posicionarTt);
});

/*                                                      Funciones agrupables al preparar el DOM
 *---------------------------------------------------------------------------------------------
 */
$(document).ready(function() {

    // Limpiador de inputs "onclick"
    $("input[name=referencia]").bind("focus", function() {
        if (!this.flag) {
            this.value = "";
            this.flag = true;
        };
    });
    
    // comprobar form de #ayudarte y mostrar error si es necesario
    $("#ayudarte button[type=submit]").bind("click", function() {
        if ($("#ayudarte input[name=nombre]").val() == "" || $("#ayudarte input[name=telefono]").val() == "" || !validarEmail($("#ayudarte input[name=email]").val()) || !$("#chkLegal").attr("checked")) {
            if ($("#mensajeDeError").html()) {
				$("#mensajeDeError").replaceWith("<div id='mensajeDeError'>" + mensajeDeError + "</div>");
			} else {
				$("#ayudarte").before("<div id='mensajeDeError' style='display: none'>"+ mensajeDeError +"</div>");
				$("#mensajeDeError").show(800);
			}
			setTimeout(function() {
				$("#mensajeDeError").hide(800, function() {
					$("#mensajeDeError").remove();
				});
			}, 7000);
            return false;
        }
        $("#ayudarte").submit();
    });
	
	// comprobar form de #sugerencias y mostrar error si es necesario
    $("#sugerencia button[type=submit]").bind("click", function() {
        if ($("#sugerencia input[name=mensaje]").val() == "" || !$("#chkLegal").attr("checked")) {
            if ($("#mensajeDeError").html()) {
				$("#mensajeDeError").replaceWith("<div id='mensajeDeError'>" + mensajeDeError + "</div>");
			} else {
				$("#sugerencia").before("<div id='mensajeDeError' style='display: none'>"+ mensajeDeError +"</div>");
				$("#mensajeDeError").show(800);
			}
			setTimeout(function() {
				$("#mensajeDeError").hide(800, function() {
					$("#mensajeDeError").remove();
				});
			}, 7000);
            return false;
        }
        $("#sugerencia").submit();
    });

	// Textos desplegables #fotoPrincipal
	$("#fotoPrincipal a").bind("click", function() {
		var bocadillo = $(this).parent("li").children("div");

        if (bocadillo.is(":visible")) {
			bocadillo.hide(500);
		} else {
			$("#fotoPrincipal div:visible").hide(500);
			bocadillo.show(500);
		}
	});

	// Pseudo pop-up #descCasos
	if (document.getElementById("descCasos")) {      // necesario para evitar que rompa al llamar al offset()
	    var desc = $("#descCasos");
	    var aMostrar = $("#casosExito a");

		desc.children().hide();                       // ocultamos hijos y preparamos el overlay
		desc.after("<div id='overlay' style='height: " + $(document).height() + "px'></div>");
		$("#overlay").css({
			"opacity": 0,
			width: $(window).width() + "px"
		});

		desc.find("a").bind("click", function(){      // los <a> internos ocultan los elementos visibles y el #overlay
			desc.children(":visible").add("#overlay").fadeOut(600, function(){
				$("#overlay").hide();
				$("select").removeAttr("disabled");
			});
			return false;
		});

		for (var i = 0; i < aMostrar.length; ++i) {   // los <a> de fuera abren los que corresponden y el overlay
			aMostrar[i].orden = i;
			$(aMostrar[i]).bind("click", function(){
				var topCSS = $(this).offset()["top"];
				desc.css("top", topCSS - 25 + "px").children("dt:eq(" + this.orden + "), dd:eq(" + this.orden + ")").fadeIn(600);
				$("#overlay").fadeTo(600, 0.8);
				$("#overlay").css("display", "block");
				$("select").attr({
					"disabled": "disabled"
				});
                return false;
			});
		}
	}

	// Eliminar de "Mi Seleccion"
	$(".eliminar").click(function() {
    	if ( confirm(eliminarMiSel) ) {
    	  var linkillo = $(this);
    	  linkillo.parent("li").hide("slow", function() {
    	    location.href = linkillo.attr("href");
    	  });
    	}
	  return false;
	});

	// Formulario prensa
	$("a.desplegarEnvio").click(function() {
		$(this).parent().next("form").slideToggle();
		return false;
	});

	// Banner testimoniales
    var testiVisible = Math.floor(Math.random()*7 + 1);
	$("#destTestimoniales div:not(:nth-child(" + testiVisible + "))").hide();
	setTimeout(cambiarTestimonial, 6000);

    // Paginador de destacados
    $("a", "#paginadorDest").click(function() {
		$("a.activo", "#paginadorDest").removeClass("activo");
		$(this).addClass("activo");
		var margen = ( parseInt($(this).text()) - 1 ) * ( $("#destacadosLateral").width() );
		$("#contenedorListadosDest").animate({
			marginLeft: -margen + "px"
		}, 600);
	}).filter(":first").addClass("activo");

    // Ficha producto
	$("#mostrarFotos").click(function() {
        $(this).addClass("activo")
            .parent().siblings().children("a").removeClass("activo");
		$('#flashFotos:hidden, #mapaProd:visible').toggle();
		return false;
	});

	$("#mostarMapa").click(function() {
        $(this).addClass("activo")
            .parent().siblings().children("a").removeClass("activo");
        $('#flashFotos:visible, #mapaProd:hidden').toggle();
		if (!$("#mapaProd iframe").is("iframe")) {
			initialize();
			mostrarDireccion(this.rel, this.name);
		}
        return false;
	});

	$("a.masInfo, a.envAmigo").click( function() {
        if ($(this).hasClass("activo")) return false;
        var clase = "." + this.className;
        $("#acciones a").removeClass("activo").filter(clase).addClass("activo");
        $("#principal form").slideUp().filter(clase).slideDown();
        return false;
    });
	$("button.masInfo, button.envAmigo").click( function() {
        var clase = "." + this.className;
        $("#acciones a").removeClass("activo");
        $("#principal form:visible").slideUp();
        return false;
    });

    $("#listado table.tablaProd tbody tr").click( function() {
		document.location = $(this).find("a:first").attr("href");
	});

});

function cambiarTestimonial() {
	var bannerVisible = $("#destTestimoniales div:visible");
	var bannerMostrar = (bannerVisible.is(":last-child")) ? $("#destTestimoniales div:first-child") : bannerVisible.next();
    bannerVisible.css("z-index", 2);
    bannerMostrar.css("z-index", 1).show();
	bannerVisible.fadeOut(1000);
	setTimeout(cambiarTestimonial, 7000);
}

/*                                                                                  Google maps
 *---------------------------------------------------------------------------------------------
 */
var map = null;
var geocoder = null;

function initialize(){
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("mapaProd"));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
		geocoder = new GClientGeocoder();
	}
}

function mostrarDireccion(address, zoom){
	zoom = parseInt(zoom);
	if (geocoder) {
		geocoder.getLatLng(address, function(point){
			if (!point) {
				alert(address + " not found");
			}
			else {
				if (zoom == 0) {
					zoom = 16;
				}
				map.setCenter(point, zoom);
			}
		});
	}
}
/*
...................
:: AJAX buscador ::
...................
*/
function cambiarParametrosBuscador(scriptLlamado) {
    $("#buscador").load(scriptLlamado,
                        {recarga: 1,
                         pbIdPoblacion:     $('#buscadorInm [name=pbIdPoblacion]').val(),
                         pbSuperficie:      $('#buscadorInm [name=pbSuperficie]').val(),
                         pbReferencia:      $('#buscadorInm [name=pbReferencia]').val(),
                         pbIdZona:          $('#buscadorInm [name=pbIdZona]').val(),
                         pbIdTipoOperacion: $('#buscadorInm [name=pbIdTipoOperacion]').val(),
                         pbIdTipoInmueble:  $('#buscadorInm [name=pbIdTipoInmueble]').val()
                        }
                       );
} // function


