// JavaScript Document

//Declaramos variables globales
var detallesPisoVisible = true;

//Declaramos constantes
VER_DETALLES_PISO_INGLES = "See more details";
VER_DETALLES_PISO_ESPANOL = "Ver más detalles";
OCULTAR_DETALLES_PISO_INGLES = "Hide details";
OCULTAR_DETALLES_PISO_ESPANOL = "Ocultar detalles";

//Calcula el numero de dias de un mes dado
function dias_mes(mes,ano){
	dias=[31,29,31,30,31,30,31,31,30,31,30,31];
	ultimo=0;
	if (mes==1){
		fecha=new Date(ano,1,29)
		vermes=fecha.getMonth();
		if(vermes!=mes){
			ultimo=28
		}
	}
	if(ultimo==0){
		ultimo=dias[mes]
	}
	//alert('mes: '+(parseInt(mes)+1)+' ano: '+ano+' dias_mes: '+ultimo);
	return ultimo;
}

//Verifica que los dias de entrada y de salida sean correctos
function verifica_fechas(dia1,mes1,ano1,dia2,mes2,ano2,idioma){
	if((ano2-ano1)<0 || (ano2==ano1 && (mes2-mes1)<0) || (ano2==ano1 && mes2==mes1 && (dia2-dia1)<1)){
		if(idioma==1){
			alert("Compruebe que la fecha de salida no es anterior o igual a la fecha de entrada");
		}else if(idioma==2){
			alert("Check the arrival and the departure dates");
		}
		return false;	
	}
	return true;
}

//Calcula la diferencia de dias entre dos fechas. Recibe los meses naturales, no Date (-1)
function calcula_dias(dia1,mes1,ano1,dia2,mes2,ano2,estancia_minima,idioma){
	dias=0;
	//Validamos que la fecha de salida no sea anterior a la fecha de entrada
	if((ano2-ano1)<0 || (ano2==ano1 && (mes2-mes1)<0) || (ano2==ano1 && mes2==mes1 && (dia2-dia1)<1)){
		if(idioma==1){
			alert("Compruebe que la fecha de salida no es anterior o igual a la fecha de entrada");
		}else if(idioma==2){
			alert("Check the arrival and the departure dates");
		}
		//Ocultamos la capa
		document.getElementById("calculo_precio").style.display="none";	
		return -1;	
	}
	
	//Validamos que la fecha de entrada no sea anterior a hoy
	var fechaEntrada=new Date();
	fechaEntrada.setFullYear(ano1,mes1-1,dia1);
	var hoy = new Date();
	
	if (fechaEntrada<hoy){
		if(idioma==1){
			alert("La fecha seleccionada ya ha pasado");
		}else{
			alert("Selected date has already passed");
		}
		//Ocultamos la capa
		document.getElementById("calculo_precio").style.display="none";	
		return -1;	
	}
	
	//Calculamos el numero de dias de reserva
	if(mes1==mes2 && ano1==ano2){
		dias=dia2-dia1;
	}else{
		//Sumo el primer mes. Restamos 1 al mes para ajustarlo al Date
		dias=dias_mes(mes1-1,ano1)-dia1+1;
		//Sumo los meses completos
		mes_en_curso=parseInt(0);
		ano_en_curso=parseInt(0);
		
		//Eliminamos ceros al inicio de las cadenas de meses
		while (mes1.charAt(0) == '0')
			mes1 = mes1.substring(1, mes1.length);
		while (mes2.charAt(0) == '0')
			mes2 = mes2.substring(1, mes2.length);

		if(mes1==12){
			mes_en_curso=parseInt(1);
			ano_en_curso=parseInt(ano1)+1;
		}else{
			mes_en_curso=parseInt(mes1)+1;
			ano_en_curso=parseInt(ano1);
			//alert('Mes: '+mes_en_curso+' Ano: '+ano_en_curso);
		}
		
		/*
		while(parseInt(mes_en_curso)!=parseInt(mes2) || parseInt(ano_en_curso)!=parseInt(ano2)){
			//alert('Mes: '+mes_en_curso+' Ano: '+ano_en_curso);
			dias+=dias_mes(mes_en_curso-1,ano_en_curso);
			if(mes_en_curso==12){
				mes_en_curso=1;
				ano_en_curso+=parseInt(1);
			}else{
				mes_en_curso+=parseInt(1);
			}			
		}
		*/
		
		//Sumo el ultimo mes
		dias+=parseInt(dia2-1);
	}
	
	//Verificamos que se cumpla la estancia minima
	if(dias<estancia_minima){
		if(idioma==1){
			alert("La estancia mínima en este piso es de "+estancia_minima+" días");
		}else if(idioma==2){
			alert("The minimum stay in this flat is "+estancia_minima+" days");
		}
		//Ocultamos la capa
		document.getElementById("calculo_precio").style.display="none";	
		return -1;	
	}

	//Verificamos que no se supera la estancia de tres semanas
	if(dias>21){
		if(idioma==1){
			alert("Para alquileres de más de 3 semanas consulte nuestro apartado 'alquiler por meses'");
		}else if(idioma==2){
			alert("For stays over 3 weeks see the section 'bookings per months'");
		}
		//Ocultamos la capa
		document.getElementById("calculo_precio").style.display="none";	
		return -1;	
	}
	
	//Verificamos que las fechas seleccionadas no coincidan con la de alguna reserva BLOQUE COPIADO DE validar_fechas en linea 601
	//Espanol
	if(idioma==1){
		var fechas_no_disponibles = "Las fechas seleccionadas no están disponibles";
	//Ingles
	}else if(idioma==2){
		var fechas_no_disponibles = "Selected dates are not available";
	}
	
	//Añadimos un cero si el dia o el mes tienen un solo digito
	reserva_entrada_dia = (dia1.length==1)?0+dia1:dia1;
	reserva_salida_dia = (dia2.length==1)?0+dia2:dia2;
	reserva_entrada_mes_suelto = (mes1.length==1)?0+mes1:mes1;
	reserva_salida_mes_suelto = (mes2.length==1)?0+mes2:mes2;
	
	var fecha_inicio = ano1+reserva_entrada_mes_suelto+reserva_entrada_dia;
	var fecha_fin = ano2+reserva_salida_mes_suelto+reserva_salida_dia;
	//alert("fecha_inicio: "+fecha_inicio+"   fecha_fin:"+fecha_fin);
	
	//Rocorremos el array reservas_ano donde se encuentran las reservas
	for (i=0;i<reservas_ano.length;i++) {
		var aux_inicio = reservas_ano[i][0].split("-");
		var aux_fin = reservas_ano[i][1].split("-");
		var fecha_convertida_inicio = aux_inicio[0]+aux_inicio[1]+aux_inicio[2];
		var fecha_convertida_fin = aux_fin[0]+aux_fin[1]+aux_fin[2];
		//alert(i+" fecha_convertida_inicio: "+fecha_convertida_inicio+"   fecha_convertida_fin:"+fecha_convertida_fin);
		if((fecha_convertida_inicio>=fecha_inicio && fecha_convertida_inicio<=fecha_fin) || (fecha_convertida_fin>=fecha_inicio && fecha_convertida_fin<=fecha_fin) || (fecha_convertida_inicio<=fecha_inicio && fecha_convertida_fin>=fecha_fin)){
			document.getElementById("calculo_precio").style.display="none";	
			alert(fechas_no_disponibles);
			return -1;
		}
	}
	
	return dias;
}

function calcular_precio(idioma)
{
	//Obtenemos los valores de los campos ocultos
	var clave_piso = document.getElementById('apa_id').value;
	var numero_ocupantes_base = document.getElementById('numero_ocupantes_base').value;
	var alquiler_diario_minimo = document.getElementById('alquiler_diario_minimo').value;
	var alquiler_diario_ocupante_adicional = document.getElementById('alquiler_diario_ocupante_adicional').value;
	var tarifa_limpieza = document.getElementById('tarifa_limpieza').value;
	var fianza = document.getElementById('fianza').value;
	var estancia_minima = document.getElementById('estancia_minima').value;
	var reserva_personas = document.getElementById('reserva_personas').value;
	var reserva_menores = document.getElementById('reserva_menores').value;
	var gestion_general = document.getElementById('gestion_general').value;
	var gestion_empresa = document.getElementById('gestion_empresa').value;
	var empresa = document.getElementById('empresa').value;
	var gestion = (empresa=='si')?gestion_empresa:gestion_general;
	
	var reserva_entrada_mes = document.getElementById('reserva_entrada_mes').value;
	var reserva_entrada_dia = document.getElementById('reserva_entrada_dia').value;
	reserva_entrada_dia = (reserva_entrada_dia.length==1)?'0'+reserva_entrada_dia:reserva_entrada_dia;
	var reserva_salida_mes = document.getElementById('reserva_salida_mes').value;
	var reserva_salida_dia = document.getElementById('reserva_salida_dia').value;
	reserva_salida_dia = (reserva_salida_dia.length==1)?'0'+reserva_salida_dia:reserva_salida_dia;
	//Descomponemos las fechas de entrada y salida mes en meses y anos
	var reserva_entrada_mes_suelto = reserva_entrada_mes.substr(5);
	reserva_entrada_mes_suelto = (reserva_entrada_mes_suelto.length==1)?'0'+reserva_entrada_mes_suelto:reserva_entrada_mes_suelto;
	var reserva_entrada_ano_suelto = reserva_entrada_mes.substr(0,4);
	var reserva_salida_mes_suelto = reserva_salida_mes.substr(5);
	reserva_salida_mes_suelto = (reserva_salida_mes_suelto.length==1)?'0'+reserva_salida_mes_suelto:reserva_salida_mes_suelto;
	var reserva_salida_ano_suelto = reserva_salida_mes.substr(0,4);
	
	//Vaciamos la capa
	var contenedor = document.getElementById('calculo_precio');
	while(contenedor.childNodes[0]){  
		contenedor.removeChild(contenedor.childNodes[0]);  
	}  
	
	//Generamos el html
	var noches = calcula_dias(reserva_entrada_dia,reserva_entrada_mes_suelto,reserva_entrada_ano_suelto,reserva_salida_dia,reserva_salida_mes_suelto,reserva_salida_ano_suelto,estancia_minima,idioma);
	if(noches==-1){
		return;
	}
	if(parseInt(reserva_menores!=0)){
		texto4+=" y "+reserva_menores+" menores de 4 años";
	}
	//Calculamos el precio base
	var precio_base_diario=parseInt(alquiler_diario_minimo);
	if(parseInt(reserva_personas)-parseInt(numero_ocupantes_base)>0){
		precio_base_diario+=(parseInt(reserva_personas)-parseInt(numero_ocupantes_base))*parseInt(alquiler_diario_ocupante_adicional);
	}
	var total = (parseInt(precio_base_diario*noches) + parseInt(tarifa_limpieza) + parseInt(gestion));
	var reserva = Math.floor((parseInt((precio_base_diario*noches)+parseInt(tarifa_limpieza)+parseInt(gestion)))*25/100);
	
	//Espanol
	if(idioma==1){
		var texto1 = " Entrada: "+reserva_entrada_dia+"/"+reserva_entrada_mes_suelto+"/"+reserva_entrada_ano_suelto;
		var texto2 = " Salida: "+reserva_salida_dia+"/"+reserva_salida_mes_suelto+"/"+reserva_salida_ano_suelto;
		var texto3 = " Noches: "+ noches;
		var texto4 = " Personas: "+reserva_personas+" Adultos";
		
		var texto5 = " Precio base: "+formatearEuros(precio_base_diario*noches)+String.fromCharCode(8364);
		var texto6 = " Limpieza final: "+formatearEuros(tarifa_limpieza)+String.fromCharCode(8364);
		var texto7 = " Total: "+ formatearEuros(total)+String.fromCharCode(8364);
		var texto8 = " Gestión: "+ formatearEuros(gestion)+String.fromCharCode(8364);
		//var texto8 = " Reserva: "+ formatearEuros(reserva)+String.fromCharCode(8364);
		var texto9 = " Fianza: "+ formatearEuros(fianza)+String.fromCharCode(8364);
	
		var texto10 = " Total estancia: "+ formatearEuros(total)+String.fromCharCode(8364);
		var texto11 = " Reserva: "+ formatearEuros(reserva)+String.fromCharCode(8364);
		var texto12 = " A pagar en efectivo a la entrada: "+formatearEuros(total-reserva)+String.fromCharCode(8364)+" + "+formatearEuros(fianza)+String.fromCharCode(8364)+" Fianza";
	
		var texto13 = "Confirmación y reserva";
		var texto14 = "Le enviaremos un e-mail confirmando la disponibilidad de la reserva e indicándole cómo proceder para pago del 25%";
		var texto15 = "del importe de la estancia, como señal para la reserva. El 75% restante y la fianza serán entregados en efectivo";
		var texto16 = "a la entrada en el apartamento.";	

		var acepto = "He leído y acepto las ";
		var condiciones = "condiciones";	
		var reservar = "Reservar"
		var documento_condiciones = "condiciones_castellano.pdf"
	//Ingles
	}else if(idioma==2){
		var texto1 = " Arrival date: "+reserva_entrada_dia+"/"+reserva_entrada_mes_suelto+"/"+reserva_entrada_ano_suelto;
		var texto2 = " Departure date: "+reserva_salida_dia+"/"+reserva_salida_mes_suelto+"/"+reserva_salida_ano_suelto;
		var texto3 = " Nights: "+ noches;
		var texto4 = " People: "+reserva_personas+" Adults";
		
		var texto5 = " Basic price: "+formatearEuros(precio_base_diario*noches)+String.fromCharCode(8364);
		var texto6 = " Cleaning rate: "+formatearEuros(tarifa_limpieza)+String.fromCharCode(8364);
		var texto7 = " Total: "+ formatearEuros(total)+String.fromCharCode(8364);
		var texto8 = " Procedure expenses: "+ formatearEuros(gestion)+String.fromCharCode(8364);
		//var texto8 = " Reservation: "+ formatearEuros(reserva)+String.fromCharCode(8364);
		var texto9 = " Caution money: "+ formatearEuros(fianza)+String.fromCharCode(8364);
	
		var texto10 = " Total stay: "+ formatearEuros(total)+String.fromCharCode(8364);
		var texto11 = " Reservation: "+ formatearEuros(reserva)+String.fromCharCode(8364);
		var texto12 = " To be paid in cash on arrival: "+formatearEuros(total-reserva)+String.fromCharCode(8364)+" + "+formatearEuros(fianza)+String.fromCharCode(8364)+" Caution money";
	
		var texto13 = "Confirmation and booking";
		var texto14 = "In short, we will send you an e-mail to confirm the availability.";
		var texto15 = "You will also be informed of how to proceed for the payment of the 25% to make the reservation.";
		var texto16 = "The remaining 75% and the caution money will be given in cash on arrival.";	

		var acepto = "I've read and I agree to the ";
		var condiciones = "terms and conditions";	
		var reservar = "Reserve"
		var documento_condiciones = "condiciones_ingles.pdf"
	}
	var condicionesespacio = " ";	
	
	flecha1 = document.createElement("img");
	flecha1.setAttribute("id","imagen_flecha");
	flecha1.setAttribute("src","images/flecha_gris.gif");
	flecha2 = document.createElement("img");
	flecha2.setAttribute("id","imagen_flecha");
	flecha2.setAttribute("src","images/flecha_gris.gif");
	flecha3 = document.createElement("img");
	flecha3.setAttribute("id","imagen_flecha");
	flecha3.setAttribute("src","images/flecha_gris.gif");
	flecha4 = document.createElement("img");
	flecha4.setAttribute("id","imagen_flecha");
	flecha4.setAttribute("src","images/flecha_gris.gif");
	flecha5 = document.createElement("img");
	flecha5.setAttribute("id","imagen_flecha");
	flecha5.setAttribute("src","images/flecha_gris.gif");
	flecha6 = document.createElement("img");
	flecha6.setAttribute("id","imagen_flecha");
	flecha6.setAttribute("src","images/flecha_gris.gif");
	flecha7 = document.createElement("img");
	flecha7.setAttribute("id","imagen_flecha");
	flecha7.setAttribute("src","images/flecha_gris.gif");
	flecha8 = document.createElement("img");
	flecha8.setAttribute("id","imagen_flecha");
	flecha8.setAttribute("src","images/flecha_gris.gif");
	flecha9 = document.createElement("img");
	flecha9.setAttribute("id","imagen_flecha");
	flecha9.setAttribute("src","images/flecha_gris.gif");
	flecha10 = document.createElement("img");
	flecha10.setAttribute("id","imagen_flecha");
	flecha10.setAttribute("src","images/flecha_gris.gif");
	flecha11 = document.createElement("img");
	flecha11.setAttribute("id","imagen_flecha");
	flecha11.setAttribute("src","images/flecha_gris.gif");
	flecha12 = document.createElement("img");
	flecha12.setAttribute("id","imagen_flecha");
	flecha12.setAttribute("src","images/flecha_gris.gif");
	
	span1 = document.createElement("span");
	span1.appendChild(document.createTextNode(texto1));
	span2 = document.createElement("span");
	span2.appendChild(document.createTextNode(texto2));
	span3 = document.createElement("span");
	span3.appendChild(document.createTextNode(texto3));
	span4 = document.createElement("span");
	span4.appendChild(document.createTextNode(texto4));
	span5 = document.createElement("span");
	span5.appendChild(document.createTextNode(texto5));
	span6 = document.createElement("span");
	span6.appendChild(document.createTextNode(texto6));
	span7 = document.createElement("span");
	span7.appendChild(document.createTextNode(texto7));
	span8 = document.createElement("span");
	span8.appendChild(document.createTextNode(texto8));
	span9 = document.createElement("span");
	span9.appendChild(document.createTextNode(texto9));
	span10 = document.createElement("span");
	span10.setAttribute("id","negrita");
	span10.appendChild(document.createTextNode(texto10));
	span11 = document.createElement("span");
	span11.setAttribute("id","negrita");
	span11.appendChild(document.createTextNode(texto11));
	span12 = document.createElement("span");
	span12.setAttribute("id","negrita");
	span12.appendChild(document.createTextNode(texto12));
	span13 = document.createElement("span");
	span13.setAttribute("id","negrita");
	span13.appendChild(document.createTextNode(texto13));
	
	reservaform = document.createElement("form");
	reservaform.setAttribute("id", "reservaform");
	reservaform.setAttribute("action", "realizar_reserva.php");
	reservaform.setAttribute("method", "post");
	reservaform.onsubmit = function(){return validarFormulario(idioma)};
	
	reservaform.appendChild(flecha1);
	reservaform.appendChild(span1);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha2);
	reservaform.appendChild(span2);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha3);
	reservaform.appendChild(span3);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha4);
	reservaform.appendChild(span4);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha5);
	reservaform.appendChild(span5);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha6);
	reservaform.appendChild(span6);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha8);
	reservaform.appendChild(span8);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha7);
	reservaform.appendChild(span7);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha9);
	reservaform.appendChild(span9);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha10);
	reservaform.appendChild(span10);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha11);
	reservaform.appendChild(span11);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha12);
	reservaform.appendChild(span12);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createTextNode(acepto));
	
	//Link a las condiciones
	var condicioneslink = document.createElement('a');
	condicioneslink.setAttribute('href', 'apartamento_files/'+documento_condiciones);
	condicioneslink.setAttribute('target', '_blank');
	condicioneslink.style.textDecoration='underline';
	condicioneslink.setAttribute("id", "condiciones");
	condicioneslink.appendChild(document.createTextNode(condiciones));
	reservaform.appendChild(condicioneslink);
	reservaform.appendChild(document.createTextNode(condicionesespacio));	
		
	//Check condiciones
	var checkbox = document.createElement("input");
	checkbox.setAttribute("type", "checkbox");
	checkbox.setAttribute("name", "aceptacondiciones");
	checkbox.setAttribute("id", "aceptacondiciones");
	addEvent(checkbox,'click',function(){document.getElementById("submitcondiciones").disabled=(document.getElementById("submitcondiciones").disabled==true)?false:true;},false);
	reservaform.appendChild(checkbox);
	
	reservaform.appendChild(document.createElement("br"));
	//Submit
	var condicionessubmit = document.createElement("input");
	condicionessubmit.setAttribute('type', 'button');
	condicionessubmit.setAttribute('name', 'submitcondiciones');
	condicionessubmit.setAttribute('id', 'submitcondiciones');
	condicionessubmit.setAttribute('value', reservar);
	condicionessubmit.disabled=true;
	addEvent(condicionessubmit,'click',function(){mostrar_form_reserva(reserva_entrada_dia,reserva_entrada_mes_suelto,reserva_entrada_ano_suelto,reserva_salida_dia,reserva_salida_mes_suelto,reserva_salida_ano_suelto,idioma);},false);
	reservaform.appendChild(condicionessubmit);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(span13);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createTextNode(texto14));
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createTextNode(texto15));
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createTextNode(texto16));
	
	//Mostramos la capa oculta
	document.getElementById("calculo_precio").style.display="block";
	
	//Creamos el formulario de envio de datos adicionales para la reserva, que permanecerá oculto hasta que se pulse el boton de "reservar"
	//Espanol
	if(idioma==1){
		var formulario0 = "* Campo obligatorio ";
		var formulario1 = "Nombre *  ";
		var formulario12 = "Apellidos *  ";
		var formulario2 = "DNI / Pasaporte *  ";
		var formulario3 = "Dirección *  ";
		var formulario301 = "Ciudad *  ";
		var formulario31 = "Código postal *  ";
		var formulario32 = "País *  ";
		var formulario4 = "E-mail *  ";
		var formulario5 = "Teléfono *  ";
		var formulario6 = "Comentarios: (hora de entrada, cuna para bebes...)  ";
		var formulario7 = "¿Cómo nos ha conocido?  ";
		var formularioaceptar = "Enviar";
	//Ingles
	}else if(idioma==2){
		var formulario0 = "* Required information ";
		var formulario1 = "Name *  ";
		var formulario12 = "Surname *  ";
		var formulario2 = "National Identity Card / Passport *  ";
		var formulario3 = "Address *  ";
		var formulario301 = "City *  ";
		var formulario31 = "P.O. Box *  ";
		var formulario32 = "Country *  ";
		var formulario4 = "E-mail *  ";
		var formulario5 = "Phone number *  ";
		var formulario6 = "Comments: (entry hour, baby cradle...)  ";
		var formulario7 = "How did you hear about us?  ";
		var formularioaceptar = "Send";
	}
	
	//Creamos el div que contendra el formulario
	var capaformulario = document.createElement("div");
	capaformulario.setAttribute("id", "capaformulario");
	
	//Creamos los campos
	var nombre = document.createElement("input");
	nombre.setAttribute('type', 'text');
	nombre.setAttribute('name', 'nombre');
	nombre.setAttribute('id', 'nombre');
	nombre.setAttribute('size', '32');
	nombre.setAttribute('maxlength', '32');
	var apellidos = document.createElement("input");
	apellidos.setAttribute('type', 'text');
	apellidos.setAttribute('name', 'apellidos');
	apellidos.setAttribute('id', 'apellidos');
	apellidos.setAttribute('size', '64');
	apellidos.setAttribute('maxlength', '64');
	var pasaporte = document.createElement("input");
	pasaporte.setAttribute('type', 'text');
	pasaporte.setAttribute('name', 'pasaporte');
	pasaporte.setAttribute('id', 'pasaporte');
	pasaporte.setAttribute('size', '14');
	pasaporte.setAttribute('maxlength', '14');
	var direccionPostal = document.createElement("input");
	direccionPostal.setAttribute('type', 'text');
	direccionPostal.setAttribute('name', 'direccionPostal');
	direccionPostal.setAttribute('id', 'direccionPostal');
	direccionPostal.setAttribute('size', '50');
	direccionPostal.setAttribute('maxlength', '128');
	var ciudadPais = document.createElement("input");
	ciudadPais.setAttribute('type', 'text');
	ciudadPais.setAttribute('name', 'ciudadPais');
	ciudadPais.setAttribute('id', 'ciudadPais');
	ciudadPais.setAttribute('size', '50');
	ciudadPais.setAttribute('maxlength', '128');
	var codigoPostal = document.createElement("input");
	codigoPostal.setAttribute('type', 'text');
	codigoPostal.setAttribute('name', 'codigoPostal');
	codigoPostal.setAttribute('id', 'codigoPostal');
	codigoPostal.setAttribute('size', '10');
	codigoPostal.setAttribute('maxlength', '10');
	var pais = document.createElement("input");
	pais.setAttribute('type', 'text');
	pais.setAttribute('name', 'pais');
	pais.setAttribute('id', 'pais');
	pais.setAttribute('size', '50');
	pais.setAttribute('maxlength', '64');
	var email = document.createElement("input");
	email.setAttribute('type', 'text');
	email.setAttribute('name', 'email');
	email.setAttribute('id', 'email');
	email.setAttribute('size', '50');
	email.setAttribute('maxlength', '64');
	var telefono = document.createElement("input");
	telefono.setAttribute('type', 'text');
	telefono.setAttribute('name', 'telefono');
	telefono.setAttribute('id', 'telefono');
	telefono.setAttribute('size', '20');
	telefono.setAttribute('maxlength', '20');
	var llegada = document.createElement("textarea");
	llegada.setAttribute('name', 'llegada');
	llegada.setAttribute('id', 'llegada');
	llegada.setAttribute('rows', '5');
	llegada.setAttribute('cols', '50');
	llegada.setAttribute('maxlength', '1024');
	var informacion = document.createElement("textarea");
	informacion.setAttribute('name', 'informacion');
	informacion.setAttribute('id', 'informacion');
	informacion.setAttribute('rows', '5');
	informacion.setAttribute('cols', '50');
	informacion.setAttribute('maxlength', '128');

	//Campos ocultos
	var entrada_oculto = document.createElement("input");
	entrada_oculto.setAttribute('type', 'hidden');
	entrada_oculto.setAttribute('name', 'entrada');
	entrada_oculto.setAttribute('value', reserva_entrada_ano_suelto+reserva_entrada_mes_suelto+reserva_entrada_dia);
	var salida_oculto = document.createElement("input");
	salida_oculto.setAttribute('type', 'hidden');
	salida_oculto.setAttribute('name', 'salida');
	salida_oculto.setAttribute('value', reserva_salida_ano_suelto+reserva_salida_mes_suelto+reserva_salida_dia);
	var personas_oculto = document.createElement("input");
	personas_oculto.setAttribute('type', 'hidden');
	personas_oculto.setAttribute('name', 'personas');
	personas_oculto.setAttribute('value', reserva_personas);
	var menores_oculto = document.createElement("input");
	menores_oculto.setAttribute('type', 'hidden');
	menores_oculto.setAttribute('name', 'menores');
	menores_oculto.setAttribute('value', reserva_menores);
	var reserva_oculto = document.createElement("input");
	reserva_oculto.setAttribute('type', 'hidden');
	reserva_oculto.setAttribute('name', 'reserva');
	reserva_oculto.setAttribute('value', reserva);
	var total_estancia_oculto = document.createElement("input");
	total_estancia_oculto.setAttribute('type', 'hidden');
	total_estancia_oculto.setAttribute('name', 'total_estancia');
	total_estancia_oculto.setAttribute('value', total);
	var fianza_oculto = document.createElement("input");
	fianza_oculto.setAttribute('type', 'hidden');
	fianza_oculto.setAttribute('name', 'fianza');
	fianza_oculto.setAttribute('value', fianza);
	var clave_piso_oculto = document.createElement("input");
	clave_piso_oculto.setAttribute('type', 'hidden');
	clave_piso_oculto.setAttribute('name', 'clave_piso');
	clave_piso_oculto.setAttribute('value', clave_piso);
	var empresa_oculto = document.createElement("input");
	empresa_oculto.setAttribute('type', 'hidden');
	empresa_oculto.setAttribute('name', 'empresa');
	empresa_oculto.setAttribute('value', empresa);
	
	//Anadimos los campos a la capa
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario0));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario1));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(nombre);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario12));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(apellidos);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario2));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(pasaporte);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario3));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(direccionPostal);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario301));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(ciudadPais);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario31));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(codigoPostal);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario32));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(pais);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario4));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(email);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario5));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(telefono);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario6));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(llegada);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario7));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(informacion);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createElement("br"));
	
	//Añadimos campos ocultos
	capaformulario.appendChild(entrada_oculto);
	capaformulario.appendChild(salida_oculto);
	capaformulario.appendChild(personas_oculto);
	capaformulario.appendChild(menores_oculto);
	capaformulario.appendChild(reserva_oculto);
	capaformulario.appendChild(total_estancia_oculto);
	capaformulario.appendChild(fianza_oculto);
	capaformulario.appendChild(clave_piso_oculto);
	
	//Boton de envio final para la reserva
	var reservafinalsubmit = document.createElement("input");
	reservafinalsubmit.setAttribute('type', 'submit');
	reservafinalsubmit.setAttribute('id', 'reservafinalsubmit');
	reservafinalsubmit.setAttribute('value', formularioaceptar);
	capaformulario.appendChild(reservafinalsubmit);
	
	//Anadimos el div al formulario
	reservaform.appendChild(capaformulario);

	contenedor.appendChild(reservaform);
}

function calcular_precio_sanfermin(idioma)
{
	//Obtenemos los valores de los campos ocultos
	var clave_piso = document.getElementById('apa_id').value;
	var tarifa_limpieza = document.getElementById('tarifa_limpieza_sanfermin').value;
	var alquiler_periodo_sanfermin = document.getElementById('alquiler_periodo_sanfermin').value;
	var alquiler_completo_sanfermin = document.getElementById('alquiler_completo_sanfermin').value;
	var entrada_sanfermin = document.getElementById('entrada_sanfermin').value;
	var salida_sanfermin = document.getElementById('salida_sanfermin').value;
	var reserva_personas = document.getElementById('reserva_personas').value;
	var fianza = document.getElementById('fianza_sanfermin').value;
	var linea_periodo_reserva = document.getElementById('linea_periodo_reserva').value;
	var linea_salida_mes_reserva = document.getElementById('linea_salida_mes_reserva').value;
	var ano = linea_salida_mes_reserva.substr(0,4);
	var reserva_menores = document.getElementById('reserva_menores').value;
		
	//Vaciamos la capa
	var contenedor = document.getElementById('calculo_precio');
	while(contenedor.childNodes[0]){  
		contenedor.removeChild(contenedor.childNodes[0]);  
	}  
	
	//Verificamos que las fechas seleccionadas no coincidan con la de alguna reserva
	//Espanol
	if(idioma==1){
		var fechas_no_disponibles = "Las fechas seleccionadas no están disponibles";
	//Ingles
	}else if(idioma==2){
		var fechas_no_disponibles = "Selected dates are not available";
	}
	
	var noches = "0";
	var reserva_entrada_dia = "0";
	var reserva_salida_dia = "0";
	var reserva_entrada_mes_suelto = "0";
	var reserva_salida_mes_suelto = "0";
	var precio_total = "0";
	
	if(linea_periodo_reserva==1){
		noches = 10;
		reserva_entrada_dia = "05";
		reserva_salida_dia = "15";
		reserva_entrada_mes_suelto = "07";
		reserva_salida_mes_suelto = "07";
		precio_total = alquiler_completo_sanfermin;
	}else if(linea_periodo_reserva==2){
		noches = 4;
		reserva_entrada_dia = "05";
		reserva_salida_dia = "09";
		reserva_entrada_mes_suelto = "07";
		reserva_salida_mes_suelto = "07";
		precio_total = alquiler_periodo_sanfermin;
	}else if(linea_periodo_reserva==3){
		noches = 4;
		reserva_entrada_dia = "11";
		reserva_salida_dia = "15";
		reserva_entrada_mes_suelto = "07";
		reserva_salida_mes_suelto = "07";
		precio_total = alquiler_periodo_sanfermin;
	}
	
	var fecha_inicio = ano+reserva_entrada_mes_suelto+reserva_entrada_dia;
	var fecha_fin = ano+reserva_salida_mes_suelto+reserva_salida_dia;
	//alert("fecha_inicio: "+fecha_inicio+"   fecha_fin:"+fecha_fin);
	
	//Rocorremos el array reservas_ano donde se encuentran las reservas
	for (i=0;i<reservas_ano.length;i++) {
		var aux_inicio = reservas_ano[i][0].split("-");
		var aux_fin = reservas_ano[i][1].split("-");
		var fecha_convertida_inicio = aux_inicio[0]+aux_inicio[1]+aux_inicio[2];
		var fecha_convertida_fin = aux_fin[0]+aux_fin[1]+aux_fin[2];
		//alert(i+" fecha_convertida_inicio: "+fecha_convertida_inicio+"   fecha_convertida_fin:"+fecha_convertida_fin);
		if((fecha_convertida_inicio>=fecha_inicio && fecha_convertida_inicio<=fecha_fin) || (fecha_convertida_fin>=fecha_inicio && fecha_convertida_fin<=fecha_fin) || (fecha_convertida_inicio<=fecha_inicio && fecha_convertida_fin>=fecha_fin)){
			document.getElementById("calculo_precio").style.display="none";	
			alert(fechas_no_disponibles);
			return;
		}
	}
	
	//Calculamos el precio base
	var total = (parseInt(precio_total) + parseInt(tarifa_limpieza));
	var reserva = Math.floor((parseInt(precio_total))*50/100);
	
	//Espanol
	if(idioma==1){
		var texto1 = " Entrada: A partir del "+reserva_entrada_dia+" de julio a las "+entrada_sanfermin+" hrs.";
		var texto2 = " Salida: Antes del "+reserva_salida_dia+" de julio a las "+salida_sanfermin+" hrs.";
		var texto3 = " Noches: "+ noches;
		var texto4 = " Personas: "+reserva_personas+" Adultos";
		
		var texto5 = " Precio base: "+formatearEuros(precio_total)+String.fromCharCode(8364);
		var texto6 = " Tarifa limpieza: "+formatearEuros(tarifa_limpieza)+String.fromCharCode(8364);
		var texto7 = " Total: "+ formatearEuros(total)+String.fromCharCode(8364);
		var texto8 = " Reserva: "+ formatearEuros(reserva)+String.fromCharCode(8364);
		var texto9 = " Fianza: "+ formatearEuros(fianza)+String.fromCharCode(8364);
	
		var texto10 = " Total estancia: "+ formatearEuros(total)+String.fromCharCode(8364);
		var texto11 = " Reserva: "+ formatearEuros(reserva)+String.fromCharCode(8364);
		var texto12 = " A pagar en efectivo a la entrada: "+formatearEuros(total-reserva)+String.fromCharCode(8364)+" + "+formatearEuros(fianza)+String.fromCharCode(8364)+" Fianza";
	
		var texto13 = "Confirmación y reserva";
		var texto14 = "Le enviaremos un e-mail confirmando la disponibilidad de la reserva e indicándole cómo proceder para pago del 50%";
		var texto15 = "del importe de la estancia, como señal para la reserva. El 50% restante y la fianza serán entregados en efectivo";
		var texto16 = "a la entrada en el apartamento.";	

		var acepto = "He leído y acepto las ";
		var condiciones = "condiciones";	
		var reservar = "Reservar"
		var documento_condiciones = "condiciones_sanfermin_castellano.pdf"
	//Ingles
	}else if(idioma==2){
		var texto1 = " Entry: From "+reserva_entrada_dia+"th July at "+entrada_sanfermin+" hrs.";
		var texto2 = " Departure: Before "+reserva_salida_dia+"th July at "+salida_sanfermin+" hrs.";
		var texto3 = " Nights: "+ noches;
		var texto4 = " People: "+reserva_personas+" Adults";
		
		var texto5 = " Basic price: "+formatearEuros(precio_total)+String.fromCharCode(8364);
		var texto6 = " Cleaning rate: "+formatearEuros(tarifa_limpieza)+String.fromCharCode(8364);
		var texto7 = " Total: "+ formatearEuros(total)+String.fromCharCode(8364);
		var texto8 = " Reservation: "+ formatearEuros(reserva)+String.fromCharCode(8364);
		var texto9 = " Caution money: "+ formatearEuros(fianza)+String.fromCharCode(8364);
	
		var texto10 = " Total stay: "+ formatearEuros(total)+String.fromCharCode(8364);
		var texto11 = " Reservation: "+ formatearEuros(reserva)+String.fromCharCode(8364);
		var texto12 = " To be paid in cash on arrival: "+formatearEuros(total-reserva)+String.fromCharCode(8364)+" + "+formatearEuros(fianza)+String.fromCharCode(8364)+" Caution money";
	
		var texto13 = "Confirmation and booking";
		var texto14 = "In short, we will send you an e-mail to confirm the availability.";
		var texto15 = "You will also be informed of how to proceed for the payment of the 50% to make the reservation.";
		var texto16 = "The remaining 50% and the caution money will be given in cash on arrival.";	

		var acepto = "I've read and I agree to the ";
		var condiciones = "terms and conditions";	
		var reservar = "Reserve"
		var documento_condiciones = "condiciones_sanfermin_ingles.pdf"
	}
	var condicionesespacio = " ";	
	
	flecha1 = document.createElement("img");
	flecha1.setAttribute("id","imagen_flecha");
	flecha1.setAttribute("src","images/flecha_gris.gif");
	flecha2 = document.createElement("img");
	flecha2.setAttribute("id","imagen_flecha");
	flecha2.setAttribute("src","images/flecha_gris.gif");
	flecha3 = document.createElement("img");
	flecha3.setAttribute("id","imagen_flecha");
	flecha3.setAttribute("src","images/flecha_gris.gif");
	flecha4 = document.createElement("img");
	flecha4.setAttribute("id","imagen_flecha");
	flecha4.setAttribute("src","images/flecha_gris.gif");
	flecha5 = document.createElement("img");
	flecha5.setAttribute("id","imagen_flecha");
	flecha5.setAttribute("src","images/flecha_gris.gif");
	flecha6 = document.createElement("img");
	flecha6.setAttribute("id","imagen_flecha");
	flecha6.setAttribute("src","images/flecha_gris.gif");
	flecha7 = document.createElement("img");
	flecha7.setAttribute("id","imagen_flecha");
	flecha7.setAttribute("src","images/flecha_gris.gif");
	flecha8 = document.createElement("img");
	flecha8.setAttribute("id","imagen_flecha");
	flecha8.setAttribute("src","images/flecha_gris.gif");
	flecha9 = document.createElement("img");
	flecha9.setAttribute("id","imagen_flecha");
	flecha9.setAttribute("src","images/flecha_gris.gif");
	flecha10 = document.createElement("img");
	flecha10.setAttribute("id","imagen_flecha");
	flecha10.setAttribute("src","images/flecha_gris.gif");
	flecha11 = document.createElement("img");
	flecha11.setAttribute("id","imagen_flecha");
	flecha11.setAttribute("src","images/flecha_gris.gif");
	flecha12 = document.createElement("img");
	flecha12.setAttribute("id","imagen_flecha");
	flecha12.setAttribute("src","images/flecha_gris.gif");
	
	span1 = document.createElement("span");
	span1.appendChild(document.createTextNode(texto1));
	span2 = document.createElement("span");
	span2.appendChild(document.createTextNode(texto2));
	span3 = document.createElement("span");
	span3.appendChild(document.createTextNode(texto3));
	span4 = document.createElement("span");
	span4.appendChild(document.createTextNode(texto4));
	span5 = document.createElement("span");
	span5.appendChild(document.createTextNode(texto5));
	span6 = document.createElement("span");
	span6.appendChild(document.createTextNode(texto6));
	span7 = document.createElement("span");
	span7.appendChild(document.createTextNode(texto7));
	span8 = document.createElement("span");
	span8.appendChild(document.createTextNode(texto8));
	span9 = document.createElement("span");
	span9.appendChild(document.createTextNode(texto9));
	span10 = document.createElement("span");
	span10.setAttribute("id","negrita");
	span10.appendChild(document.createTextNode(texto10));
	span11 = document.createElement("span");
	span11.setAttribute("id","negrita");
	span11.appendChild(document.createTextNode(texto11));
	span12 = document.createElement("span");
	span12.setAttribute("id","negrita");
	span12.appendChild(document.createTextNode(texto12));
	span13 = document.createElement("span");
	span13.setAttribute("id","negrita");
	span13.appendChild(document.createTextNode(texto13));
	
	reservaform = document.createElement("form");
	reservaform.setAttribute("id", "reservaform");
	reservaform.setAttribute("action", "realizar_reserva.php");
	reservaform.setAttribute("method", "post");
	reservaform.onsubmit = function(){return validarFormulario(idioma)};
	
	reservaform.appendChild(flecha1);
	reservaform.appendChild(span1);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha2);
	reservaform.appendChild(span2);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha3);
	reservaform.appendChild(span3);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha4);
	reservaform.appendChild(span4);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha5);
	reservaform.appendChild(span5);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha6);
	reservaform.appendChild(span6);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha7);
	reservaform.appendChild(span7);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha8);
	reservaform.appendChild(span8);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha9);
	reservaform.appendChild(span9);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha10);
	reservaform.appendChild(span10);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha11);
	reservaform.appendChild(span11);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha12);
	reservaform.appendChild(span12);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createTextNode(acepto));
	
	//Link a las condiciones
	var condicioneslink = document.createElement('a');
	condicioneslink.setAttribute('href', 'apartamento_files/'+documento_condiciones);
	condicioneslink.setAttribute('target', '_blank');
	condicioneslink.style.textDecoration='underline';
	condicioneslink.setAttribute("id", "condiciones");
	condicioneslink.appendChild(document.createTextNode(condiciones));
	reservaform.appendChild(condicioneslink);
	reservaform.appendChild(document.createTextNode(condicionesespacio));	
		
	//Check condiciones
	var checkbox = document.createElement("input");
	checkbox.setAttribute("type", "checkbox");
	checkbox.setAttribute("name", "aceptacondiciones");
	checkbox.setAttribute("id", "aceptacondiciones");
	addEvent(checkbox,'click',function(){document.getElementById("submitcondiciones").disabled=(document.getElementById("submitcondiciones").disabled==true)?false:true;},false);
	reservaform.appendChild(checkbox);
	
	reservaform.appendChild(document.createElement("br"));
	//Submit
	var condicionessubmit = document.createElement("input");
	condicionessubmit.setAttribute('type', 'button');
	condicionessubmit.setAttribute('name', 'submitcondiciones');
	condicionessubmit.setAttribute('id', 'submitcondiciones');
	condicionessubmit.setAttribute('value', reservar);
	condicionessubmit.disabled=true;
	addEvent(condicionessubmit,'click',function(){mostrar_form_reserva(reserva_entrada_dia,reserva_entrada_mes_suelto,ano,reserva_salida_dia,reserva_salida_mes_suelto,ano,idioma);},false);
	reservaform.appendChild(condicionessubmit);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(span13);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createTextNode(texto14));
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createTextNode(texto15));
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createTextNode(texto16));
	
	//Mostramos la capa oculta
	document.getElementById("calculo_precio").style.display="block";
	
	//Creamos el formulario de envio de datos adicionales para la reserva, que permanecerá oculto hasta que se pulse el boton de "reservar"
	//Espanol
	if(idioma==1){
		var formulario0 = "* Campo obligatorio ";
		var formulario1 = "Nombre *  ";
		var formulario12 = "Apellidos *  ";
		var formulario2 = "DNI / Pasaporte *  ";
		var formulario3 = "Dirección *  ";
		var formulario301 = "Ciudad *  ";
		var formulario31 = "Código postal *  ";
		var formulario32 = "País *  ";
		var formulario4 = "E-mail *  ";
		var formulario5 = "Teléfono *  ";
		var formulario6 = "Comentarios: (hora de entrada, cuna para bebes...)  ";
		var formulario7 = "¿Cómo nos ha conocido?  ";
		var formularioaceptar = "Enviar";
	//Ingles
	}else if(idioma==2){
		var formulario0 = "* Required information ";
		var formulario1 = "Name *  ";
		var formulario12 = "Surname *  ";
		var formulario2 = "National Identity Card / Passport *  ";
		var formulario3 = "Address *  ";
		var formulario301 = "City *  ";
		var formulario31 = "P.O. Box *  ";
		var formulario32 = "Country *  ";
		var formulario4 = "E-mail *  ";
		var formulario5 = "Phone number *  ";
		var formulario6 = "Comments: (entry hour, baby cradle...)  ";
		var formulario7 = "How did you hear about us?  ";
		var formularioaceptar = "Send";
	}
	
	//Creamos el div que contendra el formulario
	var capaformulario = document.createElement("div");
	capaformulario.setAttribute("id", "capaformulario");
	
	//Creamos los campos
	var nombre = document.createElement("input");
	nombre.setAttribute('type', 'text');
	nombre.setAttribute('name', 'nombre');
	nombre.setAttribute('id', 'nombre');
	nombre.setAttribute('size', '32');
	nombre.setAttribute('maxlength', '32');
	var apellidos = document.createElement("input");
	apellidos.setAttribute('type', 'text');
	apellidos.setAttribute('name', 'apellidos');
	apellidos.setAttribute('id', 'apellidos');
	apellidos.setAttribute('size', '64');
	apellidos.setAttribute('maxlength', '64');
	var pasaporte = document.createElement("input");
	pasaporte.setAttribute('type', 'text');
	pasaporte.setAttribute('name', 'pasaporte');
	pasaporte.setAttribute('id', 'pasaporte');
	pasaporte.setAttribute('size', '14');
	pasaporte.setAttribute('maxlength', '14');
	var direccionPostal = document.createElement("input");
	direccionPostal.setAttribute('type', 'text');
	direccionPostal.setAttribute('name', 'direccionPostal');
	direccionPostal.setAttribute('id', 'direccionPostal');
	direccionPostal.setAttribute('size', '50');
	direccionPostal.setAttribute('maxlength', '128');
	var ciudadPais = document.createElement("input");
	ciudadPais.setAttribute('type', 'text');
	ciudadPais.setAttribute('name', 'ciudadPais');
	ciudadPais.setAttribute('id', 'ciudadPais');
	ciudadPais.setAttribute('size', '50');
	ciudadPais.setAttribute('maxlength', '128');
	var codigoPostal = document.createElement("input");
	codigoPostal.setAttribute('type', 'text');
	codigoPostal.setAttribute('name', 'codigoPostal');
	codigoPostal.setAttribute('id', 'codigoPostal');
	codigoPostal.setAttribute('size', '10');
	codigoPostal.setAttribute('maxlength', '10');
	var pais = document.createElement("input");
	pais.setAttribute('type', 'text');
	pais.setAttribute('name', 'pais');
	pais.setAttribute('id', 'pais');
	pais.setAttribute('size', '50');
	pais.setAttribute('maxlength', '64');
	var email = document.createElement("input");
	email.setAttribute('type', 'text');
	email.setAttribute('name', 'email');
	email.setAttribute('id', 'email');
	email.setAttribute('size', '50');
	email.setAttribute('maxlength', '64');
	var telefono = document.createElement("input");
	telefono.setAttribute('type', 'text');
	telefono.setAttribute('name', 'telefono');
	telefono.setAttribute('id', 'telefono');
	telefono.setAttribute('size', '20');
	telefono.setAttribute('maxlength', '20');
	var llegada = document.createElement("textarea");
	llegada.setAttribute('name', 'llegada');
	llegada.setAttribute('id', 'llegada');
	llegada.setAttribute('rows', '5');
	llegada.setAttribute('cols', '50');
	llegada.setAttribute('maxlength', '1024');
	var informacion = document.createElement("textarea");
	informacion.setAttribute('name', 'informacion');
	informacion.setAttribute('id', 'informacion');
	informacion.setAttribute('rows', '5');
	informacion.setAttribute('cols', '50');
	informacion.setAttribute('maxlength', '128');

	//Campos ocultos
	var entrada_oculto = document.createElement("input");
	entrada_oculto.setAttribute('type', 'hidden');
	entrada_oculto.setAttribute('name', 'entrada');
	entrada_oculto.setAttribute('value', ano+reserva_entrada_mes_suelto+reserva_entrada_dia);
	var salida_oculto = document.createElement("input");
	salida_oculto.setAttribute('type', 'hidden');
	salida_oculto.setAttribute('name', 'salida');
	salida_oculto.setAttribute('value', ano+reserva_salida_mes_suelto+reserva_salida_dia);
	var personas_oculto = document.createElement("input");
	personas_oculto.setAttribute('type', 'hidden');
	personas_oculto.setAttribute('name', 'personas');
	personas_oculto.setAttribute('value', reserva_personas);
	var menores_oculto = document.createElement("input");
	menores_oculto.setAttribute('type', 'hidden');
	menores_oculto.setAttribute('name', 'menores');
	menores_oculto.setAttribute('value', reserva_menores);
	var reserva_oculto = document.createElement("input");
	reserva_oculto.setAttribute('type', 'hidden');
	reserva_oculto.setAttribute('name', 'reserva');
	reserva_oculto.setAttribute('value', reserva);
	var total_estancia_oculto = document.createElement("input");
	total_estancia_oculto.setAttribute('type', 'hidden');
	total_estancia_oculto.setAttribute('name', 'total_estancia');
	total_estancia_oculto.setAttribute('value', total);
	var fianza_oculto = document.createElement("input");
	fianza_oculto.setAttribute('type', 'hidden');
	fianza_oculto.setAttribute('name', 'fianza');
	fianza_oculto.setAttribute('value', fianza);
	var clave_piso_oculto = document.createElement("input");
	clave_piso_oculto.setAttribute('type', 'hidden');
	clave_piso_oculto.setAttribute('name', 'clave_piso');
	clave_piso_oculto.setAttribute('value', clave_piso);
	
	//Anadimos los campos a la capa
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario0));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario1));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(nombre);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario12));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(apellidos);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario2));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(pasaporte);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario3));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(direccionPostal);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario301));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(ciudadPais);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario31));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(codigoPostal);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario32));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(pais);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario4));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(email);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario5));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(telefono);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario6));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(llegada);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario7));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(informacion);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createElement("br"));
	
	//Añadimos campos ocultos
	capaformulario.appendChild(entrada_oculto);
	capaformulario.appendChild(salida_oculto);
	capaformulario.appendChild(personas_oculto);
	capaformulario.appendChild(menores_oculto);
	capaformulario.appendChild(reserva_oculto);
	capaformulario.appendChild(total_estancia_oculto);
	capaformulario.appendChild(fianza_oculto);
	capaformulario.appendChild(clave_piso_oculto);
	
	//Boton de envio final para la reserva
	var reservafinalsubmit = document.createElement("input");
	reservafinalsubmit.setAttribute('type', 'submit');
	reservafinalsubmit.setAttribute('id', 'reservafinalsubmit');
	reservafinalsubmit.setAttribute('value', formularioaceptar);
	capaformulario.appendChild(reservafinalsubmit);
	
	//Anadimos el div al formulario
	reservaform.appendChild(capaformulario);

	contenedor.appendChild(reservaform);
}

function calcular_precio_balcon(idioma)
{
	//Obtenemos los valores de los campos ocultos
	var clave_piso = document.getElementById('apa_id').value;
	var precio_persona = document.getElementById('precio_persona').value;
	var entrada_sanfermin = document.getElementById('reserva_entrada_dia').value;
	var salida_sanfermin = document.getElementById('reserva_salida_dia').value;
	var reserva_personas = document.getElementById('reserva_personas').value;
	var linea_salida_mes_reserva = document.getElementById('reserva_salida_mes').value;
	var ano = linea_salida_mes_reserva.substr(0,4);
	var reserva_menores = document.getElementById('reserva_menores').value;
		
	//Vaciamos la capa
	var contenedor = document.getElementById('calculo_precio');
	while(contenedor.childNodes[0]){  
		contenedor.removeChild(contenedor.childNodes[0]);  
	}  
	
	//Verificamos que las fechas seleccionadas no coincidan con la de alguna reserva
	//Espanol
	if(idioma==1){
		var fechas_no_disponibles = "Las fechas seleccionadas no están disponibles";
	//Ingles
	}else if(idioma==2){
		var fechas_no_disponibles = "Selected dates are not available";
	}
	
	var noches = "0";
	var reserva_entrada_dia = document.getElementById('linea_dia_balcon_reserva').value;
	var reserva_salida_dia = parseInt(reserva_entrada_dia)+1;
	reserva_entrada_dia = (reserva_entrada_dia.length==1)?'0'+reserva_entrada_dia:reserva_entrada_dia;
	reserva_salida_dia = (reserva_salida_dia.length==1)?'0'+reserva_salida_dia:reserva_salida_dia;
	var reserva_entrada_mes_suelto = "07";
	var reserva_salida_mes_suelto = "07";
	var precio_total = precio_persona*reserva_personas;
	
	var fecha_inicio = ano+reserva_entrada_mes_suelto+reserva_entrada_dia;
	var fecha_fin = ano+reserva_salida_mes_suelto+reserva_salida_dia;
	//alert("fecha_inicio: "+fecha_inicio+"   fecha_fin:"+fecha_fin);
	
	//Recorremos el array reservas_ano donde se encuentran las reservas
	if (reservas_balcones_sanfermin[reserva_entrada_dia-7]<reserva_personas){
		document.getElementById("calculo_precio").style.display="none";	
		alert(fechas_no_disponibles);
		return;	
	}
	
	//Espanol
	if(idioma==1){
		var texto1 = " Día: "+reserva_entrada_dia+" de julio.";
		var texto2 = " Personas: "+reserva_personas+" Adultos";
		var texto3 = " Precio: "+formatearEuros(precio_total)+String.fromCharCode(8364);
		
		var texto4 = "Confirmación y reserva";
		var texto5 = "Le enviaremos un e-mail confirmando la disponibilidad de la reserva e indicándole como proceder";
		var texto6 = "para el pago del 100% del importe.";
		
		var acepto = "He leído y acepto las ";
		var condiciones = "condiciones";	
		var reservar = "Reservar";
		var documento_condiciones = "condiciones_balcon_castellano.pdf";
	//Ingles
	}else if(idioma==2){
		var texto1 = " Entry: "+reserva_entrada_dia+"th July.";
		var texto2 = " People: "+reserva_personas+" Adults";
		var texto3 = " Price: "+formatearEuros(precio_total)+String.fromCharCode(8364);
		
		var texto4 = "Confirmation and booking";
		var texto5 = "In short, we will send you an e-mail to confirm the availability.";
		var texto6 = "You will also be informed of how to proceed for the payment of the 100 % to make the reservation.";
		
		var acepto = "I've read and I agree to the ";
		var condiciones = "terms and conditions";	
		var reservar = "Reserve";
		var documento_condiciones = "condiciones_balcon_ingles.pdf";
	}
	var condicionesespacio = " ";	
	
	flecha1 = document.createElement("img");
	flecha1.setAttribute("id","imagen_flecha");
	flecha1.setAttribute("src","images/flecha_gris.gif");
	flecha2 = document.createElement("img");
	flecha2.setAttribute("id","imagen_flecha");
	flecha2.setAttribute("src","images/flecha_gris.gif");
	flecha3 = document.createElement("img");
	flecha3.setAttribute("id","imagen_flecha");
	flecha3.setAttribute("src","images/flecha_gris.gif");
	flecha4 = document.createElement("img");
	flecha4.setAttribute("id","imagen_flecha");
	flecha4.setAttribute("src","images/flecha_gris.gif");
	flecha5 = document.createElement("img");
	flecha5.setAttribute("id","imagen_flecha");
	flecha5.setAttribute("src","images/flecha_gris.gif");
	flecha6 = document.createElement("img");
	flecha6.setAttribute("id","imagen_flecha");
	flecha6.setAttribute("src","images/flecha_gris.gif");
	
	span1 = document.createElement("span");
	span1.appendChild(document.createTextNode(texto1));
	span2 = document.createElement("span");
	span2.appendChild(document.createTextNode(texto2));
	span3 = document.createElement("span");
	span3.setAttribute("id","negrita");
	span3.appendChild(document.createTextNode(texto3));
	span4 = document.createElement("span");
	span4.setAttribute("id","negrita");
	span4.appendChild(document.createTextNode(texto4));
	span5 = document.createElement("span");
	span5.appendChild(document.createTextNode(texto5));
	span6 = document.createElement("span");
	span6.appendChild(document.createTextNode(texto6));
	
	reservaform = document.createElement("form");
	reservaform.setAttribute("id", "reservaform");
	reservaform.setAttribute("action", "realizar_reserva.php");
	reservaform.setAttribute("method", "post");
	reservaform.onsubmit = function(){return validarFormulario(idioma)};
	
	reservaform.appendChild(flecha1);
	reservaform.appendChild(span1);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha2);
	reservaform.appendChild(span2);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(flecha3);
	reservaform.appendChild(span3);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createTextNode(acepto));
	
	//Link a las condiciones
	var condicioneslink = document.createElement('a');
	condicioneslink.setAttribute('href', 'apartamento_files/'+documento_condiciones);
	condicioneslink.setAttribute('target', '_blank');
	condicioneslink.style.textDecoration='underline';
	condicioneslink.setAttribute("id", "condiciones");
	condicioneslink.appendChild(document.createTextNode(condiciones));
	reservaform.appendChild(condicioneslink);
	reservaform.appendChild(document.createTextNode(condicionesespacio));	
		
	//Check condiciones
	var checkbox = document.createElement("input");
	checkbox.setAttribute("type", "checkbox");
	checkbox.setAttribute("name", "aceptacondiciones");
	checkbox.setAttribute("id", "aceptacondiciones");
	addEvent(checkbox,'click',function(){document.getElementById("submitcondiciones").disabled=(document.getElementById("submitcondiciones").disabled==true)?false:true;},false);
	reservaform.appendChild(checkbox);
	
	reservaform.appendChild(document.createElement("br"));
	//Submit
	var condicionessubmit = document.createElement("input");
	condicionessubmit.setAttribute('type', 'button');
	condicionessubmit.setAttribute('name', 'submitcondiciones');
	condicionessubmit.setAttribute('id', 'submitcondiciones');
	condicionessubmit.setAttribute('value', reservar);
	condicionessubmit.disabled=true;
	addEvent(condicionessubmit,'click',function(){mostrar_formulario_balcon();},false);
	reservaform.appendChild(condicionessubmit);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(span4);
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createTextNode(texto5));
	reservaform.appendChild(document.createElement("br"));
	reservaform.appendChild(document.createTextNode(texto6));
	
	//Mostramos la capa oculta
	document.getElementById("calculo_precio").style.display="block";
	
	//Creamos el formulario de envio de datos adicionales para la reserva, que permanecerá oculto hasta que se pulse el boton de "reservar"
	//Espanol
	if(idioma==1){
		var formulario0 = "* Campo obligatorio ";
		var formulario1 = "Nombre *  ";
		var formulario12 = "Apellidos *  ";
		var formulario2 = "DNI / Pasaporte *  ";
		var formulario3 = "Dirección *  ";
		var formulario301 = "Ciudad *  ";
		var formulario31 = "Código postal *  ";
		var formulario32 = "País *  ";
		var formulario4 = "E-mail *  ";
		var formulario5 = "Teléfono *  ";
		var formulario6 = "Comentarios: ";
		var formulario7 = "¿Cómo nos ha conocido?  ";
		var formularioaceptar = "Enviar";
	//Ingles
	}else if(idioma==2){
		var formulario0 = "* Required information ";
		var formulario1 = "Name *  ";
		var formulario12 = "Surname *  ";
		var formulario2 = "National Identity Card / Passport *  ";
		var formulario3 = "Address *  ";
		var formulario301 = "City *  ";
		var formulario31 = "P.O. Box *  ";
		var formulario32 = "Country *  ";
		var formulario4 = "E-mail *  ";
		var formulario5 = "Phone number *  ";
		var formulario6 = "Comments: ";
		var formulario7 = "How did you hear about us?  ";
		var formularioaceptar = "Send";
	}
	
	//Creamos el div que contendra el formulario
	var capaformulario = document.createElement("div");
	capaformulario.setAttribute("id", "capaformulario");
	
	//Creamos los campos
	var nombre = document.createElement("input");
	nombre.setAttribute('type', 'text');
	nombre.setAttribute('name', 'nombre');
	nombre.setAttribute('id', 'nombre');
	nombre.setAttribute('size', '32');
	nombre.setAttribute('maxlength', '32');
	var apellidos = document.createElement("input");
	apellidos.setAttribute('type', 'text');
	apellidos.setAttribute('name', 'apellidos');
	apellidos.setAttribute('id', 'apellidos');
	apellidos.setAttribute('size', '64');
	apellidos.setAttribute('maxlength', '64');
	var pasaporte = document.createElement("input");
	pasaporte.setAttribute('type', 'text');
	pasaporte.setAttribute('name', 'pasaporte');
	pasaporte.setAttribute('id', 'pasaporte');
	pasaporte.setAttribute('size', '14');
	pasaporte.setAttribute('maxlength', '14');
	var direccionPostal = document.createElement("input");
	direccionPostal.setAttribute('type', 'text');
	direccionPostal.setAttribute('name', 'direccionPostal');
	direccionPostal.setAttribute('id', 'direccionPostal');
	direccionPostal.setAttribute('size', '50');
	direccionPostal.setAttribute('maxlength', '128');
	var ciudadPais = document.createElement("input");
	ciudadPais.setAttribute('type', 'text');
	ciudadPais.setAttribute('name', 'ciudadPais');
	ciudadPais.setAttribute('id', 'ciudadPais');
	ciudadPais.setAttribute('size', '50');
	ciudadPais.setAttribute('maxlength', '128');
	var codigoPostal = document.createElement("input");
	codigoPostal.setAttribute('type', 'text');
	codigoPostal.setAttribute('name', 'codigoPostal');
	codigoPostal.setAttribute('id', 'codigoPostal');
	codigoPostal.setAttribute('size', '10');
	codigoPostal.setAttribute('maxlength', '10');
	var pais = document.createElement("input");
	pais.setAttribute('type', 'text');
	pais.setAttribute('name', 'pais');
	pais.setAttribute('id', 'pais');
	pais.setAttribute('size', '50');
	pais.setAttribute('maxlength', '64');
	var email = document.createElement("input");
	email.setAttribute('type', 'text');
	email.setAttribute('name', 'email');
	email.setAttribute('id', 'email');
	email.setAttribute('size', '50');
	email.setAttribute('maxlength', '64');
	var telefono = document.createElement("input");
	telefono.setAttribute('type', 'text');
	telefono.setAttribute('name', 'telefono');
	telefono.setAttribute('id', 'telefono');
	telefono.setAttribute('size', '20');
	telefono.setAttribute('maxlength', '20');
	var llegada = document.createElement("textarea");
	llegada.setAttribute('name', 'llegada');
	llegada.setAttribute('id', 'llegada');
	llegada.setAttribute('rows', '5');
	llegada.setAttribute('cols', '50');
	llegada.setAttribute('maxlength', '1024');
	var informacion = document.createElement("textarea");
	informacion.setAttribute('name', 'informacion');
	informacion.setAttribute('id', 'informacion');
	informacion.setAttribute('rows', '5');
	informacion.setAttribute('cols', '50');
	informacion.setAttribute('maxlength', '128');

	//Campos ocultos
	var entrada_oculto = document.createElement("input");
	entrada_oculto.setAttribute('type', 'hidden');
	entrada_oculto.setAttribute('name', 'entrada');
	entrada_oculto.setAttribute('value', ano+reserva_entrada_mes_suelto+reserva_entrada_dia);
	var salida_oculto = document.createElement("input");
	salida_oculto.setAttribute('type', 'hidden');
	salida_oculto.setAttribute('name', 'salida');
	salida_oculto.setAttribute('value', ano+reserva_entrada_mes_suelto+reserva_salida_dia);
	var personas_oculto = document.createElement("input");
	personas_oculto.setAttribute('type', 'hidden');
	personas_oculto.setAttribute('name', 'personas');
	personas_oculto.setAttribute('value', reserva_personas);
	var menores_oculto = document.createElement("input");
	menores_oculto.setAttribute('type', 'hidden');
	menores_oculto.setAttribute('name', 'menores');
	menores_oculto.setAttribute('value', reserva_menores);
	var total_estancia_oculto = document.createElement("input");
	total_estancia_oculto.setAttribute('type', 'hidden');
	total_estancia_oculto.setAttribute('name', 'total_estancia');
	total_estancia_oculto.setAttribute('value', precio_total);
	var clave_piso_oculto = document.createElement("input");
	clave_piso_oculto.setAttribute('type', 'hidden');
	clave_piso_oculto.setAttribute('name', 'clave_piso');
	clave_piso_oculto.setAttribute('value', clave_piso);
	
	//Anadimos los campos a la capa
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario0));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario1));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(nombre);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario12));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(apellidos);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario2));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(pasaporte);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario3));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(direccionPostal);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario301));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(ciudadPais);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario31));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(codigoPostal);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario32));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(pais);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario4));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(email);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario5));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(telefono);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario6));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(llegada);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createTextNode(formulario7));
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(informacion);
	capaformulario.appendChild(document.createElement("br"));
	capaformulario.appendChild(document.createElement("br"));
	
	//Añadimos campos ocultos
	capaformulario.appendChild(entrada_oculto);
	capaformulario.appendChild(salida_oculto);
	capaformulario.appendChild(personas_oculto);
	capaformulario.appendChild(menores_oculto);
	capaformulario.appendChild(total_estancia_oculto);
	capaformulario.appendChild(clave_piso_oculto);
	
	//Boton de envio final para la reserva
	var reservafinalsubmit = document.createElement("input");
	reservafinalsubmit.setAttribute('type', 'submit');
	reservafinalsubmit.setAttribute('id', 'reservafinalsubmit');
	reservafinalsubmit.setAttribute('value', formularioaceptar);
	capaformulario.appendChild(reservafinalsubmit);
	
	//Anadimos el div al formulario
	reservaform.appendChild(capaformulario);

	contenedor.appendChild(reservaform);
}

function mostrar_formulario_balcon(){
	//Mostramos la capa oculta
	document.getElementById("capaformulario").style.display="block";
	document.getElementById("nombre").focus();
}

//Muestra el formulario de envio de datos para la reserva
function mostrar_form_reserva(reserva_entrada_dia,reserva_entrada_mes_suelto,reserva_entrada_ano_suelto,reserva_salida_dia,reserva_salida_mes_suelto,reserva_salida_ano_suelto,idioma)
{
	validar_fechas(reserva_entrada_dia,reserva_entrada_mes_suelto,reserva_entrada_ano_suelto,reserva_salida_dia,reserva_salida_mes_suelto,reserva_salida_ano_suelto,idioma);
}

//Valida que las fechas seleccionadas esten libres
function validar_fechas(reserva_entrada_dia,reserva_entrada_mes_suelto,reserva_entrada_ano_suelto,reserva_salida_dia,reserva_salida_mes_suelto,reserva_salida_ano_suelto,idioma)
{
	//Espanol
	if(idioma==1){
		var fechas_no_disponibles = "Las fechas seleccionadas no están disponibles";
	//Ingles
	}else if(idioma==2){
		var fechas_no_disponibles = "Selected dates are not available";
	}
	
	//Añadimos un cero si el dia o el mes tienen un solo digito
	reserva_entrada_dia = (reserva_entrada_dia.length==1)?0+reserva_entrada_dia:reserva_entrada_dia;
	reserva_salida_dia = (reserva_salida_dia.length==1)?0+reserva_salida_dia:reserva_salida_dia;
	reserva_entrada_mes_suelto = (reserva_entrada_mes_suelto.length==1)?0+reserva_entrada_mes_suelto:reserva_entrada_mes_suelto;
	reserva_salida_mes_suelto = (reserva_salida_mes_suelto.length==1)?0+reserva_salida_mes_suelto:reserva_salida_mes_suelto;
	
	var fecha_inicio = reserva_entrada_ano_suelto+reserva_entrada_mes_suelto+reserva_entrada_dia;
	var fecha_fin = reserva_salida_ano_suelto+reserva_salida_mes_suelto+reserva_salida_dia;
	//alert("fecha_inicio: "+fecha_inicio+"   fecha_fin:"+fecha_fin);
	
	//Rocorremos el array reservas_ano donde se encuentran las reservas
	for (i=0;i<reservas_ano.length;i++) {
		var aux_inicio = reservas_ano[i][0].split("-");
		var aux_fin = reservas_ano[i][1].split("-");
		var fecha_convertida_inicio = aux_inicio[0]+aux_inicio[1]+aux_inicio[2];
		var fecha_convertida_fin = aux_fin[0]+aux_fin[1]+aux_fin[2];
		//alert(i+" fecha_convertida_inicio: "+fecha_convertida_inicio+"   fecha_convertida_fin:"+fecha_convertida_fin);
		if((fecha_convertida_inicio>=fecha_inicio && fecha_convertida_inicio<=fecha_fin) || (fecha_convertida_fin>=fecha_inicio && fecha_convertida_fin<=fecha_fin) || (fecha_convertida_inicio<=fecha_inicio && fecha_convertida_fin>=fecha_fin)){
			alert(fechas_no_disponibles);
			return -1;
		}
	}
	//Mostramos la capa oculta
	document.getElementById("capaformulario").style.display="block";
	document.getElementById("nombre").focus();
}

function addEvent(elemento,nomevento,funcion,captura)
{
  if (elemento.attachEvent)
  {
    elemento.attachEvent('on'+nomevento,funcion);
    return true;
  }
  else  
    if (elemento.addEventListener)
    {
      elemento.addEventListener(nomevento,funcion,captura);
      return true;
    }
    else
      return false;
}

function abrirfoto(ruta,w,h)
{
	window.open(ruta,'','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width='+w+',height='+h+',top=0,left=0');
}

function addCss(cssCode)
{
	var styleElement = document.createElement("style");
	styleElement.type = "text/css";
	if (styleElement.styleSheet) {
		styleElement.styleSheet.cssText = cssCode;
	} else {
		styleElement.appendChild(document.createTextNode(cssCode));
	}
	document.getElementsByTagName("head")[0].appendChild(styleElement);
}  


//Mostramos u ocultamos la capa con el detalle del piso
/*
function mostrar_detalles(lg)
{
	//Si esta visible
	var boton = document.getElementById("enlace_detalles");
	if (detallesPisoVisible) {
		//Ocultamos la capa
		document.getElementById("detalles_piso").style.display="none";
		//Cambiamos el texto del boton
		if (lg == "es"){
			boton.value = VER_DETALLES_PISO_ESPANOL;
		}else{
			boton.value = VER_DETALLES_PISO_INGLES;
		}
		//Actualizamos la variable que informa de la visibilidad de la capa
		detallesPisoVisible = false;
	//Si esta oculta
	}else {
		//Mostramos la capa
		document.getElementById("detalles_piso").style.display="block";
		//Cambiamos el texto del boton
		if (lg == "es"){
			boton.value = OCULTAR_DETALLES_PISO_ESPANOL;
		}else{
			boton.value = OCULTAR_DETALLES_PISO_INGLES;
		}
		//Actualizamos la variable que informa de la visibilidad de la capa
		detallesPisoVisible = true;
	}
}
*/

//Validamos el formulario con los datos del cliente
function validarFormulario(idioma) {
	var alertaNombre = "";
	var alertaPasaporte = "";
	var alertaDireccion = "";
	var alertaCiudad = "";
	var alertaCodigoPostal = "";
	var alertaPais = "";
	var alertaEmail = "";
	var alertaTelefono = "";
	if (idioma==1) {
		alertaNombre = "El campo nombre es obligatorio";
		alertaPasaporte = "El campo DNI/pasaporte es obligatorio";
		alertaDireccionPostal = "El campo dirección es obligatorio";
		alertaCiudad = "El campo ciudad es obligatorio";
		alertaCodigoPostal = "El campo código postal es obligatorio";
		alertaPais = "El campo país es obligatorio";
		alertaEmail = "El campo email es obligatorio";
		alertaEmailIncorrecto = "La dirección de email no es válida";
		alertaTelefono = "El campo teléfono es obligatorio";
	}else{
		alertaNombre = "You are required to complete the 'Name' field";
		alertaPasaporte = "You are required to complete the 'National Identity Card/Passport' field";
		alertaDireccionPostal = "You are required to complete the 'Address' field";
		alertaCiudad = "You are required to complete the 'City' field";
		alertaCodigoPostal = "You are required to complete the 'Postal code' field";
		alertaPais = "You are required to complete the 'Country' field";
		alertaEmail = "You are required to complete the 'Email' field";
		alertaEmailIncorrecto = "Provide a correct email address";
		alertaTelefono = "You are required to complete the 'Phone number' field";	
	}
	//valido el nombre
	var campoNombre = document.getElementById("nombre");
    if (campoNombre.value.length==0){
       alert(alertaNombre);
       campoNombre.focus();
       return false;
    } 
	//valido el nif
	var campoPasaporte = document.getElementById("pasaporte");
    if (campoPasaporte.value.length==0){
       alert(alertaPasaporte);
       campoPasaporte.focus();
       return false;
    } 
	//valido la direccionPostal
	var campoDireccionPostal = document.getElementById("direccionPostal");
	if (campoDireccionPostal.value.length==0){
       alert(alertaDireccionPostal);
       campoDireccionPostal.focus();
       return false;
    } 
	//valido la ciudad
	var campoCiudad = document.getElementById("ciudadPais");
	if (campoCiudad.value.length==0){
       alert(alertaCiudad);
       campoCiudad.focus();
       return false;
    } 
	//valido el codigoPostal
	var campoCodigoPostal = document.getElementById("codigoPostal");
	if (campoCodigoPostal.value.length==0){
       alert(alertaCodigoPostal);
       campoCodigoPostal.focus();
       return false;
    } 
	//valido el pais
	var campoPais = document.getElementById("pais");
	if (campoPais.value.length==0){
       alert(alertaPais);
       campoPais.focus();
       return false;
    } 
	//valido el email
	var campoEmail = document.getElementById("email");
    var formato  = /^([\w-\.])+@([\w-]+\.)+([a-z]){2,4}$/;
    if (campoEmail.value.length==0){
       alert(alertaEmail);
       campoEmail.focus();
       return false;
    }else if (!(formato.test(campoEmail.value))){
	    alert (alertaEmailIncorrecto);    
    	return false;
	}
    
	//valido el telefono
	var campoTelefono = document.getElementById("telefono");
    if (campoTelefono.value.length==0){
       alert(alertaTelefono);
       campoTelefono.focus();
       return false;
    } 
    
    //Bloqueamos el submit poniendo false
	//return false;
	return true;
}

//Ajusta el combo del mes de salida segun el combo del mes de entrada para el buscador
function pon_mes_salida()
{
	document.form_buscador.buscador_salida_mes.selectedIndex=document.form_buscador.buscador_entrada_mes.selectedIndex;
	return true;
}

//Ajusta el combo del mes de salida segun el combo del mes de entrada para el apartado de reserva
function pon_mes_salida_reserva()
{
	document.form_reserva.reserva_salida_mes.selectedIndex=document.form_reserva.reserva_entrada_mes.selectedIndex;
	return true;
}

function ajustar_fecha(elementomes,fecha,elemento,elemento2){
	pon_mes_salida();
	actualizar_dias(fecha,elemento);
	actualizar_dias(fecha,elemento2);
}

function ajustar_fecha_reserva(elementomes,fecha,elemento,elemento2){
	pon_mes_salida_reserva();
	actualizar_dias(fecha,elemento);
	actualizar_dias(fecha,elemento2);
}

//Actualizacion del combo de dias segun el mes seleccionado
//Funcion principal
function actualizar_dias(fecha,elemento){
	var diaSeleccionado = document.getElementById(elemento).value;
	limpiaDias(document.getElementById(elemento));
	var ano = parseInt(fecha.substr(0,4));
	var mes = (parseInt(fecha.substr(5)))-1;
	if(mes>11){
		mes = mes-12;
	}
	var dias = dias_mes(mes,ano);
	anadeDias(document.getElementById(elemento),dias);
	document.getElementById(elemento).value = (dias<diaSeleccionado)?dias:diaSeleccionado;
}

//Elimina los dias del combo
function limpiaDias(elemento) { 
	while(elemento.hasChildNodes()){
		elemento.removeChild(elemento.lastChild);
   	} 
}

//Anade los dias al combo
function anadeDias(elemento, dias) { 
	for (var i=1;i<=dias;i++){
		var opcion=document.createElement("option"); 
	    opcion.appendChild(document.createTextNode(i) ); 
	    opcion.setAttribute("value",i); 
	    elemento.appendChild(opcion); 
	} 
}

//Validamos el formulario con los datos del cliente
function validarFormularioContacto(idioma) {
	var alertaNombre = "";
	var alertaEmail = "";
	var alertaEmailIncorrecto = "";
	var alertaComentario = "";
	if (idioma==1) {
		alertaNombre = "El campo nombre es obligatorio";
		alertaEmail = "El campo email es obligatorio";
		alertaEmailIncorrecto = "La dirección de email no es válida";
		alertaComentario = "El campo comentarios es obligatorio";
	}else{
		alertaNombre = "You are required to complete the 'Name' field";
		alertaEmail = "You are required to complete the 'Email' field";
		alertaEmailIncorrecto = "Provide a correct email address";
		alertaComentario = "You are required to complete the 'Comments' field";	
	}
	//valido el nombre
	var campoNombre = document.getElementById("nombre");
    if (campoNombre.value.length==0){
       alert(alertaNombre);
       campoNombre.focus();
       return false;
    } 
	//valido el email
	var campoEmail = document.getElementById("email");
    var formato  = /^([\w-\.])+@([\w-]+\.)+([a-z]){2,4}$/;
    if (campoEmail.value.length==0){
       alert(alertaEmail);
       campoEmail.focus();
       return false;
    }else if (!(formato.test(campoEmail.value))){
	    alert (alertaEmailIncorrecto);    
    	return false;
	}    
	//valido el comentario
	var campoComentario = document.getElementById("comentario");
    if (campoComentario.value.length==0){
       alert(alertaComentario);
       campoComentario.focus();
       return false;
    } 
	return true;
}

//Contrasena para loguearse en apartamentos sanfermin
function solicitarContrasena(idioma, telefono){
	//if (document.form_buscador.buscador_region.value==12){
		document.getElementById('contenedor').style.display = 'none';
		var mensaje = (idioma=="es")?"Área privada de alquiler de pisos en San Fermines<br/><br/>Pamplonahouse.com ofrece acceso a este área a empresas, instituciones y particulares. Si quieren solicitar una clave de acceso a este área pónganse en contacto con nosotros a través del teléfono "+telefono+" o por e-mail en info@pamplonahouse.com indicando quiénes son.<br/><br/><br/>Introduzca la contraseña":"Private area of apartments for rent in San Fermines<br/><br/>Pamplonahouse.com provides access to this area to companies, organizations and individuals. If you want to get an access code, contact us telling who you are in info@pamplonahouse.com or by calling: +34 "+telefono+"<br/><br/><br/>Enter the password";
		//var mensaje = (idioma=="es")?"Área privada de alquiler de pisos en San FerminesPamplonahouse.com":"Enter the password";
		ae_prompt(hw2,mensaje,'');
		//var contrasena = prompt(mensaje);
	//}
}

function hw2(n)
{
	if(n!=null)
    location.href="index.php?bm=no&log_sf="+n;
    //var hello = document.getElementById('hello');
    //hello.innerHTML = '<h1>Hello, ' + n + '!</h1>';
}

// ae_prompt function sources 
var ae_cb = null;
function ae$(a) { return document.getElementById(a); } 
function ae_prompt(cb, q, a) {
	ae_cb = cb;
	//ae$('aep_t').innerHTML = document.domain + ' question:';
	ae$('aep_prompt').innerHTML = q;
	ae$('aep_text').value = a; 
	ae$('aep_ovrl').style.display = ae$('aep_ww').style.display = ''; 
	ae$('aep_text').focus(); 
	ae$('aep_text').select(); 
}
function ae_clk(m) { 
	ae$('aep_ovrl').style.display = ae$('aep_ww').style.display = 'none'; 
	if (!m){
		document.getElementById('contenedor').style.display = 'block';
		ae_cb(null);
	} else {
		ae_cb(ae$('aep_text').value);
	}
}
// ae_prompt function sources 

function formatearEuros(num) {
	var numero = num.toString();
	var regx = /(\d+)(\d{3})/;
	while (regx.test(numero)) {
		numero = numero.replace(regx, '$1' + '.' + '$2');
	}
	numero = numero+',00';
	return numero;
}

function mostrarEntradaSalida(sf,balcon) {
	var entrada = document.getElementById("filas_dias_entrada");
	var salida = document.getElementById("filas_dias_salida");
	//if(sf=="si" && balcon=="no"){
	if(sf=="si"){
		entrada.style.display = "none";
		salida.style.display = "none";
	}else{
		entrada.style.display = "";	
		salida.style.display = "";
	}
}

function ajustarDiasPeriodo(valor) {
	var entrada = document.getElementById("buscador_entrada_dia")
	var salida = document.getElementById("buscador_salida_dia")
	if(valor==0){
		entrada.selectedIndex=0;
		salida.selectedIndex=10;
	}else if(valor==1){
		entrada.selectedIndex=0;
		salida.selectedIndex=4;
	}else if(valor==2){
		entrada.selectedIndex=6;
		salida.selectedIndex=10;
	}
}

function ajustarDiaBalcon(valor) {
	var entrada = document.getElementById("buscador_entrada_dia")
	var salida = document.getElementById("buscador_salida_dia")
	entrada.selectedIndex=valor+2;
	salida.selectedIndex=valor+3;
}

function mostrarEntradaSalidaReserva(sf,balcon) {
	var entrada = document.getElementById("filas_dias_entrada_reserva");
	var salida = document.getElementById("filas_dias_salida_reserva");
	if(sf=="si"){
		entrada.style.display = "none";
		salida.style.display = "none";
	}else{
		entrada.style.display = "";	
		salida.style.display = "";
	}
}

function ajustarDiasPeriodoReserva(valor) {
	var entrada = document.getElementById("reserva_entrada_dia")
	var salida = document.getElementById("reserva_salida_dia")
	if(valor==0){
		entrada.selectedIndex=0;
		salida.selectedIndex=10;
	}else if(valor==1){
		entrada.selectedIndex=0;
		salida.selectedIndex=4;
	}else if(valor==2){
		entrada.selectedIndex=6;
		salida.selectedIndex=10;
	}
}

function ajustarDiasBalconReserva(valor) {
	var entrada = document.getElementById("reserva_entrada_dia")
	var salida = document.getElementById("reserva_salida_dia")
	entrada.selectedIndex=valor+2;
	salida.selectedIndex=valor+3;
}

function cambiarTipo() {
	if(document.getElementById("buscador_region").selectedIndex==0){
		location.href="index.php?balcon=si";
	}else{
		location.href="index.php?balcon=no";
	}
}
