jQuery.fn.exists = function(){return (this.length>0);}


// Debug para desarrollo
function dump(obj) {
	var out = '';
	for(var i in obj) {
		out += i + ": " + obj[i] + "\n";
	}
	alert(out);
}

function inArray(aguja, pajar) {
	var length = pajar.length;
	for(var i = 0; i < length; i++) {
		if(pajar[i] == aguja) return true;
	}
	return false;
}

// Validacion de emails
function validarEmail(valor) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(valor) == false)
		return false;
	else
		return true;
}

// Validacion de fechas
function validarFecha(FECHA) {  
	var Fecha= new String(FECHA)
	var RealFecha= new Date()
	var Ano= new String(Fecha.substring(Fecha.lastIndexOf("-")+1,Fecha.length))
	var Mes= new String(Fecha.substring(Fecha.indexOf("-")+1,Fecha.lastIndexOf("-")))
	var Dia= new String(Fecha.substring(0,Fecha.indexOf("-")))
  
	if(isNaN(Ano) || Ano.length<4 || parseFloat(Ano)<1900)
		return false;
	if(isNaN(Mes) || parseFloat(Mes)<1 || parseFloat(Mes)>12)
		return false;
	if(isNaN(Dia) || parseInt(Dia, 10)<1 || parseInt(Dia, 10)>31)
		return false;

	if((Mes==4 || Mes==6 || Mes==9 || Mes==11) && Dia>30)
		return false;
	if(Mes==2 && Dia > 29 || Mes==2 && Dia > 29 && Ano%4 > 0)
		return false;

	return true;
}

// Gestionamos los campos de tipo fecha
function newCalendario(CALENDARIO) {
	$("#" + CALENDARIO).datepicker();
	$("#" + CALENDARIO).datepicker("option", "minDate", minDate);
	$("#" + CALENDARIO).datepicker("option", "numberOfMonths", 2);
}

// Comprobaciones formulario de reserva
function checkFormReserva(f) {
	if(!f["form-nombre"].value || !f["form-apellidos"].value || !f["form-anyos"].value || !f["form-telefono"].value || !f["form-movil"].value || !f["form-email"].value || !f["form-email2"].value || !f["form-pais"].value) {
		alert(txt_error_obligatorios);
		return false;
	} else if(!validarEmail(f["form-email"].value)) {
		alert(txt_error_email);
		return false;
	} else if(f["form-email"].value != f["form-email2"].value) {
		alert(txt_error_email2);
		return false;
	} else if(!f["form-cg"].checked) {
		alert(txt_error_condiciones);
		return false;
	}

	var enviamos = confirm(txt_confirmar)
	if(enviamos)
		return true;
	else
		return false;
}

// Comprobaciones formulario de contacto
function checkFormContacto(f, SPAM) {
	if(!f["form-nombre"].value || !f["form-email"].value || !f[SPAM].value) {
		alert(txt_error_obligatorios);
		return false;
	} else if(!validarEmail(f["form-email"].value)) {
		alert(txt_error_email);
		return false;
	} else if(!f["form-cg"].checked) {
		alert(txt_error_condiciones2);
		return false;
	}

	return true;
}

// Comprobaciones formulario de búsqueda
function checkFormCalendar(f) {
	if(!validarFecha(f.entrada.value.replace(/\//g, "-"))) {
		alert(txt_error_fechaentrada);
		return false;
	} else if(!validarFecha(f.salida.value.replace(/\//g, "-"))) {
		alert(txt_error_fechasalida);
		return false;
	}
}


// Google maps
function loadMapa(CAPA, ANCHO, ALTO, GOOGLEX, GOOGLEY, DESCRIPCION) {
	if($("#" + CAPA).exists()) {
		$("#" + CAPA).html('<iframe width="' + ANCHO + '" height="' + ALTO + '" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps?q=' + GOOGLEX + ',' + GOOGLEY + '+%28' + DESCRIPCION + '%29&amp;hl=' + idioma + '&amp;output=embed"></iframe>');
	}
}


// Grabar la moneda elegida
function setMoneda(MONEDA) {
	$.post(ruta + 'ajax/moneda', {moneda: MONEDA}, function(data) {
		window.location.href = window.location.href;
	});
}


// Cambiar el orden de los pisos
function setOrden(ORDEN) {
	$.post(ruta + 'ajax/orden', {orden: ORDEN}, function(data) {
		window.location.href = url_apartamentos;
	});
}


function toggleCalendario(CALENDARIO) {
	$("#" + CALENDARIO).datepicker("show");
}


// Anular variables de sesión del formulario
function borraFecha(REDIR) {
	$.get(ruta + 'ajax/borrar-fechas?idioma=' + idioma, function(data) {
		if(data) {
			if($("#entrada").exists()) {
				$("#entrada").val("");
				$("#salida").val("");
				$("#salida").val("");
				$("#adultos").val("1");
				$("#ninios1").val("0");
				$("#ninios2").val("0");
				$("#bebes").val("0");
			}
			if(REDIR == 1)
				window.location.href = window.location.href;
			else if(REDIR)
				window.location.href = REDIR;
		}
	});
}


// Gestionar visibilidad filtros
function toggleFiltros(FILTROS) {
	if($("#filtros-" + FILTROS).exists() && $("#filtros-img-" + FILTROS).exists()) {
		if($("#filtros-" + FILTROS).is(":visible")) {
			$("#filtros-" + FILTROS).hide();
			$("#filtros-img-" + FILTROS).attr("src", ruta + "images/flecha-filtros-down.png");
		} else {
			$("#filtros-" + FILTROS).show();
			$("#filtros-img-" + FILTROS).attr("src", ruta + "images/flecha-filtros-up.png");
		}
	}
}

// Aplicar filtros marcados
function setFiltrosCheckboxes(FILTROS) {
	if($("#filtros-" + FILTROS).exists()) {
		$("#filtros-" + FILTROS + " input:checkbox").each( function() {
			if(this.checked)
				$("#" + this.id.replace("-" + FILTROS, "-" + FILTROS + "-valores")).val(1);
			else
				$("#" + this.id.replace("-" + FILTROS, "-" + FILTROS + "-valores")).val(0);
		});
		$("#form-filtros-" + FILTROS).submit();
	}
}

// Quitar filtros marcados
function unsetFiltrosCheckboxes(FILTROS) {
	if($("#filtros-" + FILTROS).exists()) {
		$("#filtros-" + FILTROS + " input:checkbox").each( function() {
			this.checked = false;
			$("#" + this.id.replace("-" + FILTROS, "-" + FILTROS + "-valores")).val(0);
		});
		$("#form-filtros-" + FILTROS).submit();
	}
}

// Aplicar filtros slider
function setFiltrosSlider(FILTROS) {
	$("#form-filtros-" + FILTROS).submit();
}

// Resetear filtros slider
function unsetFiltrosSlider(FILTROS) {
	$("#slider-" + FILTROS).slider("option", "values", [$("#slider-" + FILTROS).slider("option", "min"), $("#slider-" + FILTROS).slider("option", "max")]);
	$("#form-filtros-" + FILTROS).submit();
}


// Cambiar imagen principal de una galeria
function setFoto(FOTO) {
	if($("#imagenPrincipal").exists()) {
		$("#imagenPrincipal").attr("src", FOTO);
	}
}

// Mover las miniaturas de una galeria
function desplazaFotos(POS) {
	if($("#contenido-miniaturas").exists()) {
		$("#contenido-miniaturas div").addClass("oculto");
		primeraMiniaturas += POS;
		ultimaMiniaturas = primeraMiniaturas + filaMiniaturas - 1;

		for(var i=1; i<=totalMiniaturas; i++) {
			if(i >= primeraMiniaturas && i <= ultimaMiniaturas)
				$("#thumb" + i).removeClass("oculto");
		}

		// Deshabilitamos los botones
		if(primeraMiniaturas == 1)
			$("#miniaturas-flecha-left").addClass("oculto");
		else
			$("#miniaturas-flecha-left").removeClass("oculto");
		if(ultimaMiniaturas == totalMiniaturas)
			$("#miniaturas-flecha-right").addClass("oculto");
		else
			$("#miniaturas-flecha-right").removeClass("oculto");
	}
}

// Chequear disponibilidad apartamento
function checkAvailability(date) {
	tmp_anyo = date.getFullYear();
	tmp_mes = date.getMonth() + 1;
	if(tmp_mes < 10)
		tmp_mes = "0" + tmp_mes;
	tmp_dia = date.getDate();
	if(tmp_dia < 10)
		tmp_dia = "0" + tmp_dia;
	tmp_fecha = tmp_anyo + "-" + tmp_mes + "-" + tmp_dia;

	var tmp_hoy = new Date();
	var hoy = new Date(tmp_hoy.getFullYear(), tmp_hoy.getMonth(), tmp_hoy.getDate(), 0, 0, 0, 0);
	if(date < hoy)
		return [false, "nodisponible", txt_nodisponible];

	if(inArray(tmp_fecha, fechas_ocupadas))
		return [false, "nodisponible", txt_nodisponible];

	for(var i=0; i<fechas_descuentos.length; i++) {
		if(typeof fechas_descuentos[i] != "undefined") {
			if(inArray(tmp_fecha, fechas_descuentos[i]))
				return [false, "descuento", i + "% " + txt_descuento];
		}
	}

	return [false, "disponible", txt_disponible];
}



// Cambiar el detalle de un apartamento
function setPantalla(PANTALLA) {
	if(!$("#loading-div").is(":visible")) {
		if($("#menu-apartamentos-" + PANTALLA).exists() && $("#detalle-" + PANTALLA).exists()) {
			$("#menu-apartamentos ul li").removeClass("activo");
			$("#menu-apartamentos-" + PANTALLA).addClass("activo");

			$("#detalles-apartamentos div.pestanya").addClass("oculto");
			$("#detalle-" + PANTALLA).removeClass("oculto");

			if(PANTALLA == "mapa")
				loadGoogleMapDetalle(google_x, google_y, "google-maps-detalle");
			else if(PANTALLA == "descripcion")
				loadGoogleMapDetalle(google_x, google_y, "google-maps-description");
		}
	}
}


// Cambiar el listado de apartamentos
var googleLoaded = false;
function setPantallaList(PANTALLA) {
	if(!$("#loading-div").is(":visible")) {
		if(PANTALLA == "toggle") {
			if($("#apartamentos-list-text").hasClass("oculto"))
				PANTALLA = "text";
			else
				PANTALLA = "map";
		}

		$("#menu-apartamentos li").removeClass("activo");
		$("#menu-apartamentos-" + PANTALLA).addClass("activo");

		if(PANTALLA == "map") {
			$("#apartamentos-list-text").addClass("oculto");
			$("#apartamentos-list-map").removeClass("oculto");
			if(!googleLoaded) {
				loadGoogleMap();
				appendIcons();
				googleLoaded = true;
			}
		} else if(PANTALLA == "text") {
			$("#apartamentos-list-map").addClass("oculto");
			$("#apartamentos-list-text").removeClass("oculto");
		}
	}
}

// Twitter embed
function loadTwitter() {
	new TWTR.Widget({
		version: 2,
		type: 'profile',
		rpp: 2,
		interval: 30000,
		width: 254,
		height: 200,
		theme: {
			shell: {
				background: '#ffffff',
				color: '#000000'
			},
			tweets: {
				background: '#ffffff',
				color: '#000000',
				links: '#0099cc'
			}
		},
		features: {
			scrollbar: false,
			loop: false,
			live: false,
			hashtags: true,
			timestamp: true,
			avatars: false,
			behavior: 'all'
		}
	}).render().setUser('gobcnapartments').start();
}

// Google maps
var icon1 = false;
var icon2 = false;
var icon3 = false;
var icon4 = false;
var map = false;
function loadGoogleMap() {
	var x =41.379624;
	var y = 2.16988563537;
    
	if(GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(x, y), 14);
		map.addMapType(G_PHYSICAL_MAP);
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());

		icon1 = new GIcon();
		icon2 = new GIcon();
		icon3 = new GIcon();
		icon4 = new GIcon();
		var ticon = new GIcon();
		var cicon = new GIcon();	

		icon1.image = servidor + "/images/iconos/map-green.png";
		icon1.shadow = "";
		icon1.iconSize = new GSize(20, 30);
		icon1.shadowSize = new GSize(22, 30);
		icon1.iconAnchor = new GPoint(6, 20);
		icon1.infoWindowAnchor = new GPoint(20, 1);				

		icon2.image =  servidor + "/images/iconos/map-orange.png";
		icon2.iconSize = new GSize(20, 30);
		icon2.shadowSize = new GSize(22, 30);
		icon2.iconAnchor = new GPoint(6, 20);
		icon2.infoWindowAnchor = new GPoint(20, 1);				

		icon3.image = servidor + "/images/iconos/map-red.png";
		icon3.iconSize = new GSize(20, 30);
		icon3.shadowSize = new GSize(22, 30);
		icon3.iconAnchor = new GPoint(6, 20);
		icon3.infoWindowAnchor = new GPoint(20, 1);

		icon4.image = servidor + "/images/iconos/map-building.png";
		icon4.iconSize = new GSize(20, 30);
		icon4.shadowSize = new GSize(22, 30);
		icon4.iconAnchor = new GPoint(6, 20);
		icon4.infoWindowAnchor = new GPoint(20, 1);
	}
}

function loadGoogleMapDetalle(X, Y, CAPA) {
	if(GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById(CAPA));
		map.setCenter(new GLatLng(X, Y), 15);
		map.addMapType(G_PHYSICAL_MAP);
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());
		var point1 = new GLatLng(X, Y);
		var mark1 = new GMarker(point1);
		map.addOverlay(mark1);	  
	 }
}


/* SLIDES */
// Inicialización
var slide = Array();
function slideStart(SLIDE, TOTAL, TRANSICION) {
	if(typeof slide[SLIDE] == "undefined") {
		 // Parámetros: [0] Nombre, [1] total elementos, [2] segundos transicion, [3] timer, [4] capa activa, [5] capa siguiente, [6] transicion en curso
		slide[SLIDE] = Array(SLIDE, TOTAL, TRANSICION, false, 0, 1, false);
	}
	for(var i=0; i<slide[SLIDE][1]; i++) {
		if(i == slide[SLIDE][4]) {
			if((i + 1) < slide[SLIDE][1])
				slide[SLIDE][5] = slide[SLIDE][4] + 1;
			else
				slide[SLIDE][5] = 0;
			break;
		}
	}
	slide[SLIDE][3] = setTimeout("slideTrans('"+SLIDE+"')", slide[SLIDE][2] * 1000);
}
// Transiciones slides
function slideTrans(SLIDE) {
	slide[SLIDE][6] = true;
	clearInterval(slide[SLIDE][3]);
	$("#contentSlide" + SLIDE + slide[SLIDE][4]).animate({ opacity: 0 }, 250, function() {
		$("#contentSlide" + SLIDE + slide[SLIDE][4]).hide();
		$("#contentSlide" + SLIDE + slide[SLIDE][5]).show();

		// Valorizamos el eventual "círculo" del slide
		if($("#slide" + SLIDE + "Thumb" + slide[SLIDE][4]).exists() && $("#slide" + SLIDE + "Thumb" + slide[SLIDE][5]).exists()) {
			$("#slide" + SLIDE + "Thumb" + slide[SLIDE][4]).attr("src", "./images/slide-off.png");
			$("#slide" + SLIDE + "Thumb" + slide[SLIDE][5]).attr("src", "./images/slide-on.png");
		}

		$("#contentSlide" + SLIDE + slide[SLIDE][5]).animate({ opacity: 1 }, 250, function() {
			slide[SLIDE][4] = slide[SLIDE][5];
			slideStart(SLIDE, slide[SLIDE][1], slide[SLIDE][2]);
			slide[SLIDE][6] = false;
		});
	});
}
// Botones hacia atrás / adelante en los slides
function slideJump(SLIDE, DIRECCION) {
	if(typeof slide[SLIDE] != "undefined" && !slide[SLIDE][6]) {
		var pos = slide[SLIDE][4] + DIRECCION;

		if(pos == slide[SLIDE][1])
			slide[SLIDE][5] = 0;
		else if(pos == -1)
			slide[SLIDE][5] = slide[SLIDE][1] - 1;
		else
			slide[SLIDE][5] = pos;

		slideTrans(SLIDE);
	}
}
// Botones directos en los slides (no utilizados)
function slideGoto(SLIDE, CAPA) {
	if(typeof slide[SLIDE] != "undefined" && !slide[SLIDE][6]) {
		slide[SLIDE][5] = CAPA;
		slideTrans(SLIDE);
	}
}

// Gestión de los readmore
function readMore(IDTEXTO) {
	$("#read-more-" + IDTEXTO).hide();
	$("#read-more-txt-" + IDTEXTO).show();
}
function comprimir(IDTEXTO) {
	$("#read-more-txt-" + IDTEXTO).hide();
	$("#read-more-" + IDTEXTO).show();
}


// Tips
jQuery.fn.creaTip = function(textoTip) {
	this.each(function(){
		elem = $(this);
		var miTip = $('<div class="tip">' + textoTip + '</div>');
		$(document.body).append(miTip);
		elem.data("capatip", miTip);
      
		elem.mouseenter(function(e){
			var miTip = $(this).data("capatip");
			miTip.css("left", e.pageX + 10);
			miTip.css("top", e.pageY + 5);
			miTip.show(500);
		});

		elem.mouseleave(function(e){
			var miTip = $(this).data("capatip");
			miTip.hide(500);
		});
	});

	return this;
};
