/* 

------------------------------------------------------------------------------------------------------------------------------- 
 											Funcións específicas para panel de control Web emgrobes
												

-------------------------------------------------------------------------------------------------------------------------------
 
*/




// Devolve false si o código dun bono non ten o formato correcto. 
function validaCodigoBono(localizador){
	var patron = new RegExp("^[0-9]{2}/{1}[0-9]{10}-{1}[A-Za-z0-9]{16}$","gi");
	
	return patron.test(trim(localizador));
}


// Valida o formulario para buscar bonos de reserva
function validaFormBuscarBono(){
	
	
	if( vacio(xGetElementById('localizador').value)){
		alert('Debes introducir el código del bono.');
		xGetElementById('localizador').focus();
		
	}else if (!validaCodigoBono(xGetElementById('localizador').value)){
		
		alert('El código del bono no es correcto.');
		xGetElementById('localizador').focus();
		
		
	}else if (vacio(xGetElementById('dni').value)){
		alert('Debes introducir el DNI.');
		xGetElementById('dni').focus();	
		
	}else if(!validaDNI(xGetElementById('dni').value) ){
		alert('El DNI no es correcto.');
		xGetElementById('dni').focus();		
	
	}else{
		xGetElementById('formBuscarBono').action = "buscarBono.php";
		xGetElementById('formBuscarBono').submit();	
		return true;
		
	}
	return false;
}


/*Valida formulario de recuperacion de bono*/
function validaFormRecuperaBono(email){
	
	if(vacio(xGetElementById('email').value)) {
		alert('Introduzca su dirección de email.');
		xGetElementById('email').focus();
		return false;
	
	}else if(!validaEmail(xGetElementById('email').value)){
		alert('Ese email no parece correcto.');
		xGetElementById('email').focus();
		return false;
		
	}else{
		
		xGetElementById('formRecuperaBono').action = "recuperaBono.php";
		xGetElementById('formRecuperaBono').submit();
		
	}
}



/*

Función para actualizar o campo importe no formulario de reserva. 
Dependendo do tipo de formulario farao de distintas formas
tipo == 1 Aloxamentos: fechaFin-FechaEntrada * habitaciones * precioHabitacion
tipo == 3 Ocio/Otros: (dependerá da oferta)
tipo == 4 Paquetes predefinidos: precio paquete * persona
tipo == 5 Paquetes turísticos a medida
No resto 
	
	
 
 */
function actualizaImporte(){
	error = true;
	
	idTipoEstablecimiento = xGetElementById('idTipoEstablecimiento').value;
	
	if(idTipoEstablecimiento == 1){ 
	
		/* Actualizar importe  de reserva de aloxamento */
	
		if(!vacio(xGetElementById('fechaEntrada').value)){
			fecha1 = strtotime(fecha2js(xGetElementById('fechaEntrada').value)); // Paso 1ª fecha a strtotime
			
			if(!vacio(xGetElementById('fechaSalida').value)){
				fecha2 = strtotime(fecha2js(xGetElementById('fechaSalida').value)); // Paso 2ª fecha a strtotime	
				
				if(!vacio(xGetElementById('numHabitaciones').value) && !isNaN(xGetElementById('numHabitaciones').value) ){
					nHab = parseInt(xGetElementById('numHabitaciones').value);
					
					imp = Math.floor((fecha2-fecha1)/86400) * nHab * parseFloat(xGetElementById('precioDia').value);
					error = false;
					
				}
			}
			
		}
		
	}else if(idTipoEstablecimiento == 3){
		
		/* Actualizar importe  de reserva de Ocio/Otros*/
		
		
		// Paso 1ª fecha a strtotime
		if(!vacio(xGetElementById('fechaInicial').value))fecha1 = strtotime(fecha2js(xGetElementById('fechaInicial').value)); 
		
		parametroObligatorio =  parseInt(xGetElementById('parametroObligatorio').value); /* Indica si hai fecha final (1) ou hora para a reserva (2) ou ningunha (0) */
				
		// Defino os precios por día, por menor e por persona
		precioDia = parseFloat(xGetElementById('precioDia').value); 
		precioPersona = parseFloat(xGetElementById('precioPersona').value); 
		precioMenores = parseFloat(xGetElementById('precioMenores').value); 
		
		switch(parametroObligatorio){
			case 1: // A reserva ten fecha de entrada e fecha de saida
			
				if(!vacio(xGetElementById('fechaInicial').value)){
					
					fecha1 = strtotime(fecha2js(xGetElementById('fechaInicial').value));
					
					if(!vacio(xGetElementById('fechaFin').value)){
						
						fecha2 = strtotime(fecha2js(xGetElementById('fechaFin').value)); // Paso 2ª fecha a strtotime	
						
						/*Teño as 2 fechas. Agora miramos si se cobra por día (precioDia != 0) ou por persona (adultos e menores)*/	
						if(precioDia != 0){
							imp = Math.floor((fecha2-fecha1)/86400) * precioDia;
							error = false;
							
						}else{ 
							/* Cobramos por persona / menor */
							if(!vacio(xGetElementById('numPersonas').value) && !isNaN(xGetElementById('numPersonas').value) ){
								numPersonas = parseInt(xGetElementById('numPersonas').value);							
								
							}else numPersonas = 0;
							
							if(precioMenores !=0 && !vacio(xGetElementById('numMenores').value) && !isNaN(xGetElementById('numMenores').value) ){
								numMenores = parseInt(xGetElementById('numMenores').value);							
								
							}else numMenores = 0;
						
							imp = Math.floor((fecha2-fecha1)/86400) * ((numPersonas * precioPersona) + (numMenores * precioMenores));
							error = false;
						}
					}
				}
				
			break;
			
			case 2: // Reservase para un dia a determiñada hora!
				if(precioDia != 0){
					imp = precioDia; // un unico día, sin indicar personas nin menores!!
					error = false;
				}else{ 
					/* Cobramos por persona / menor */
					if(!vacio(xGetElementById('numPersonas').value) && !isNaN(xGetElementById('numPersonas').value) ){
						numPersonas = parseInt(xGetElementById('numPersonas').value);							
						
					}else numPersonas = 0;
					
					if(precioMenores !=0 && !vacio(xGetElementById('numMenores').value) && !isNaN(xGetElementById('numMenores').value) ){
						numMenores = parseInt(xGetElementById('numMenores').value);							
						
					}else numMenores = 0;
				
					imp = numPersonas * precioPersona + numMenores * precioMenores;
					error = false;
				}
						
			break;
			
			case 0: // Precio por día somentes, sin numero de personas nin hora nin fecha final. 
				if(precioDia > 0) {
					imp = precioDia;
					error = false;
					
				}else{ 
					/* Cobramos por persona / menor */
					if(!vacio(xGetElementById('numPersonas').value) && !isNaN(xGetElementById('numPersonas').value) ){
						numPersonas = parseInt(xGetElementById('numPersonas').value);							
						
					}else numPersonas = 0;
					
					if(precioMenores !=0 &&  !vacio(xGetElementById('numMenores').value) && !isNaN(xGetElementById('numMenores').value) ){
						numMenores = parseInt(xGetElementById('numMenores').value);							
						
					}else numMenores = 0;
				
					imp = numPersonas * precioPersona + numMenores * precioMenores;
					error = false;
				}
			
		}
		
	}else if(idTipoEstablecimiento == 5){
		
		/* Actualizar importe  de reserva de paquete turístico predefinido*/
		
		pr = xGetElementById('precio').value; // Precio por persona
		
		if(!vacio(xGetElementById('numPersonas').value)){
			np= parseInt(xGetElementById('numPersonas').value);
			if(np > 0){
				imp = pr * np;
				error = false;
			}
		}
			
			
	}
	

	if(!error && imp >0){
		xGetElementById('importe').value = imp;
		error = false;
		
	}else xGetElementById('importe').value = "";
}

/*
	Reserva de paquetes predefinidos
*/

function validaFormReservarPaquetePredef(){
	if ( vacio(xGetElementById('nombre').value)  || !caracteresValidos(xGetElementById('nombre').value, 4,100) ){
		alert('Revise el nombre.');
		xGetElementById('nombre').focus();		
	
	}else if (vacio(xGetElementById('dni').value)  || !validaDNI(xGetElementById('dni').value) ){
		alert('Revise el DNI.');
		xGetElementById('dni').focus();		
	
	}else if(vacio(xGetElementById('telefono').value)  && vacio(xGetElementById('email').value)){
		alert('Debe introducir el telefono o el email');
		xGetElementById('telefono').focus();
		
	}else if(!vacio(xGetElementById('telefono').value)  && !validaTelefono(xGetElementById('telefono').value)){
		alert('Revise el telefono.');
		xGetElementById('telefono').focus();
		
	}else if(!vacio(xGetElementById('email').value)  && !validaEmail(xGetElementById('email').value)){
		alert('Revise el email.');
		xGetElementById('email').focus();

	}else if( vacio(xGetElementById('numPersonas').value) || isNaN(xGetElementById('numPersonas').value) ){
		alert("Introduce el Nº de personas");
		xGetElementById('numPersonas').focus();
		
	}else if(vacio(xGetElementById('comentarios').value) ){
		alert('En el campo comentarios no puede quedar vacío. Solo letras y numeros.');
		xGetElementById('comentarios').focus();
				
	}else if(!xGetElementById('legal').checked){
		alert('Debes leer y aceptar la politicia de privacidad.');			
		
	}else{
		// Enviamos formulario, pero antes oculto a botonera
		ocultaBotonera('botonera');
		//xGetElementById('formReservar').action = "oQueSexa.php";
		xGetElementById('formReservar').submit();
		
	}


}


/*
	Reserva de aloxamentos tanto para metelos nun paquete coma para reserva directa
	
	creandoPaqueta: 1 estase a crear un paquete
					0 NON (Logo hai que pedir datos persoais)
	
*/
function validaFormReservarAloxamento(creandoPaquete){
	// collo as fechas máximas e mínimas
	var fMin = xGetElementById('fechaMin').value; // en segundos
	var fMax = xGetElementById('fechaMax').value; // en segundos	
	
	// Collo as fechas do formulario (entrada e saida)  en formato strtotime
	var f1 = strtotime(fecha2js(xGetElementById('fechaEntrada').value)); 
	var f2 = strtotime(fecha2js(xGetElementById('fechaSalida').value));

	//alert("f1:"+f1 + " , fMin:" + fMin);
	// comprobemos...
	//alert(comparaFecha(f1, fMin));
	
	if (!creandoPaquete && (vacio(xGetElementById('nombre').value)  || !caracteresValidos(xGetElementById('nombre').value, 4,100)) ){
		alert('Revise el nombre.');
		xGetElementById('nombre').focus();		
	
	}else if (!creandoPaquete && (vacio(xGetElementById('dni').value)  || !validaDNI(xGetElementById('dni').value)) ){
		alert('Revise el DNI.');
		xGetElementById('dni').focus();		
	
	}else if(!creandoPaquete && (vacio(xGetElementById('telefono').value)  && vacio(xGetElementById('email').value)) ){
		alert('Debe introducir el telefono o el email');
		xGetElementById('telefono').focus();
		
	}else if(!creandoPaquete && (!vacio(xGetElementById('telefono').value)  && !validaTelefono(xGetElementById('telefono').value)) ){
		alert('Revise el telefono.');
		xGetElementById('telefono').focus();
		
	}else if(!creandoPaquete && (!vacio(xGetElementById('email').value)  && !validaEmail(xGetElementById('email').value)) ){
		alert('Revise el email.');
		xGetElementById('email').focus();
			
	}else if (vacio(xGetElementById('fechaEntrada').value) || comparaFecha(f1,hoxe) != 1 || comparaFecha(f1, fMin) == 2  || comparaFecha(f1, fMax) == 1)   {
		alert('Revise la fecha de ENTRADA. Compruebe que sea superior a la fecha actual (' + hoxeStr + ')\n y que está comprendida en el período de la oferta. ');
		xGetElementById('fechaEntrada').focus();	

	}else if(vacio(xGetElementById('fechaSalida').value) || comparaFecha(f2,hoxe)!= 1 || comparaFecha(f2,fMin) !=1  || comparaFecha(f2, fMax)== 1)    {
		alert('Revise la fecha de SALIDA. Compruebe que no sea inferior a la fecha actual (' + hoxeStr + ')\n y que está comprendida en el período de la oferta. ');
		xGetElementById('fechaSalida').focus();
	

	}else if(comparaFecha(f1,f2)!=2){
		alert("Las fechas de salida debe ser posterior a la de entrada");
		xGetElementById('fechaSalida').focus();
		
	}else if(vacio(xGetElementById('numHabitaciones').value) || isNaN(xGetElementById('numHabitaciones').value) || parseInt(xGetElementById('numHabitaciones').value)<=0) {
		alert("Introduzca el numero de habitaciones");
		xGetElementById('numHabitaciones').focus();
		
		
	}else if( xGetElementById('numHabitaciones').value > parseInt(xGetElementById('numDisponible').value) ){
		alert("Esta oferta dispone de un máximo de " + xGetElementById('numDisponible').value + " habitaciones. Vd ha solicitado " + parseInt(xGetElementById('numHabitaciones').value));
		xGetElementById('numHabitaciones').focus();
		
	}else if(vacio(xGetElementById('comentarios').value) ){
		alert('En el campo comentarios no puede quedar vacío. Solo letras y numeros.');
		xGetElementById('comentarios').focus();
				
	}else if(!creandoPaquete && !xGetElementById('legal').checked){
		alert('Debes leer y aceptar la politicia de privacidad.');			
		
	}else{
		// Enviamos formulario, pero antes oculto a botonera
		ocultaBotonera('botonera');
		//xGetElementById('formReservar').action = "oQueSexa.php";
		xGetElementById('formReservar').submit();
		
		
	}
	
}





/*
	Reserva de aloxamentos tanto para metelos nun paquete coma para reserva directa
	
	creandoPaqueta: 1 estase a crear un paquete
					0 NON (Hai q pedir datos persoais)
	
*/
function validaFormReservarRestaurante(creandoPaquete){
	// collo as fechas máximas e mínimas
	var fMin = xGetElementById('fechaMin').value; // en segundos
	var fMax = xGetElementById('fechaMax').value; // en segundos	
	
	// Collo a fecha para o dia que se reserva
	var f1 = strtotime(fecha2js(xGetElementById('fecha').value)); 


	//alert("f1:"+f1 + " , fMin:" + fMin);
	// comprobemos...
	//alert(comparaFecha(f1, fMin));
	
	if (!creandoPaquete && (vacio(xGetElementById('nombre').value)  || !caracteresValidos(xGetElementById('nombre').value, 4,100)) ){
		alert('Revise el nombre.');
		xGetElementById('nombre').focus();		
	
	}else if (!creandoPaquete && (vacio(xGetElementById('dni').value)  || !validaDNI(xGetElementById('dni').value)) ){
		alert('Revise el DNI.');
		xGetElementById('dni').focus();		
	
	}else if(!creandoPaquete && (vacio(xGetElementById('telefono').value)  && vacio(xGetElementById('email').value)) ){
		alert('Debe introducir el telefono o el email');
		xGetElementById('telefono').focus();
		
	}else if(!creandoPaquete && (!vacio(xGetElementById('telefono').value)  && !validaTelefono(xGetElementById('telefono').value)) ){
		alert('Revise el telefono.');
		xGetElementById('telefono').focus();
		
	}else if(!creandoPaquete && (!vacio(xGetElementById('email').value)  && !validaEmail(xGetElementById('email').value)) ){
		alert('Revise el email.');
		xGetElementById('email').focus();
			
	}else if (vacio(xGetElementById('fecha').value) || comparaFecha(f1,hoxe) != 1 || comparaFecha(f1, fMin) == 2  || comparaFecha(f1, fMax) == 1)   {
		alert('Revise la fecha. Compruebe que sea superior a la fecha actual (' + hoxeStr + ')\n y que está comprendida en el período de la oferta. ');
		xGetElementById('fecha').focus();	

	}else if( !validaHora(xGetElementById('hora').value) ){
		alert("La hora debe ser en formato 24h. Ej 21:30");
		xGetElementById('hora').focus();
		
	}else if(vacio(xGetElementById('numPersonas').value) || isNaN(xGetElementById('numPersonas').value) || parseInt(xGetElementById('numPersonas').value)<=0) {
		alert("Introduzca el numero de personas");
		xGetElementById('numPersonas').focus();
		
		
	}else if(vacio(xGetElementById('comentarios').value) ){
		alert('En el campo comentarios no puede quedar vacío. Solo letras y numeros.');
		xGetElementById('comentarios').focus();
				
	}else if(!creandoPaquete && !xGetElementById('legal').checked){
		alert('Debes leer y aceptar la politicia de privacidad.');			
		
	}else{
		// Enviamos formulario, pero antes oculto a botonera
		ocultaBotonera('botonera');
		//xGetElementById('formReservar').action = "oQueSexa.php";
		xGetElementById('formReservar').submit();
		
		
	}
	
}



/*
	Valida formulario de reserva de Ocio/Servicios tanto directo como para engadir a unpaquete
	
*/
function validaFormReservarOtros(creandoPaquete){
	
	errorValidaOtro = true;
	
	// collo as fechas máximas e mínimas
	var fMin = xGetElementById('fechaMin').value; // en segundos
	var fMax = xGetElementById('fechaMax').value; // en segundos	
	
	// Collo a fecha da solicitud de reserva en formato strtotime
	var f1 = strtotime(fecha2js(xGetElementById('fechaInicial').value)); 
	var f2 = 0;
	
	/* Miro si hai fecha final (1) ou hora para a reserva (2) */
	parametroObligatorio =  parseInt(xGetElementById('parametroObligatorio').value); 
	
	if(parametroObligatorio == 1)f2= strtotime(fecha2js(xGetElementById('fechaFin').value)); 
	
	// Miro si se reserva por día ou por persona/menor */
	precioDia = parseFloat(xGetElementById('precioDia').value); 
	precioPersona = parseFloat(xGetElementById('precioPersona').value); 
	precioMenores = parseFloat(xGetElementById('precioMenores').value); 

																						 
	if (!creandoPaquete && (vacio(xGetElementById('nombre').value)  || !caracteresValidos(xGetElementById('nombre').value, 4,100)) ){
		alert('Revise el nombre.');
		xGetElementById('nombre').focus();		
	
	}else if (!creandoPaquete && (vacio(xGetElementById('dni').value)  || !validaDNI(xGetElementById('dni').value)) ){
		alert('Revise el DNI.');
		xGetElementById('dni').focus();		
	
	}else if(!creandoPaquete && (vacio(xGetElementById('telefono').value)  && vacio(xGetElementById('email').value)) ){
		alert('Debe introducir el telefono o el email');
		xGetElementById('telefono').focus();
		
	}else if(!creandoPaquete && (!vacio(xGetElementById('telefono').value)  && !validaTelefono(xGetElementById('telefono').value)) ){
		alert('Revise el telefono.');
		xGetElementById('telefono').focus();
		
	}else if(!creandoPaquete && (!vacio(xGetElementById('email').value)  && !validaEmail(xGetElementById('email').value)) ){
		alert('Revise el email.');
		xGetElementById('email').focus();
			
	}else if (vacio(xGetElementById('fechaInicial').value) || comparaFecha(f1,hoxe) != 1 || comparaFecha(f1, fMin) == 2  || comparaFecha(f1, fMax) == 1)   {
		alert('Revise la fecha de ENTRADA. Compruebe que sea superior a la fecha actual (' + hoxeStr + ')\n y que está comprendida en el período de la oferta. ');
		xGetElementById('fechaInicial').focus();	

	}else if( parametroObligatorio == 1	 && ( vacio(xGetElementById('fechaFin').value) || comparaFecha(f2,hoxe)!= 1 || comparaFecha(f2,fMin) !=1  || comparaFecha(f2, fMax)== 1) )    {
		alert('Revise la fecha de SALIDA. Compruebe que no sea inferior a la fecha actual (' + hoxeStr + ')\n y que está comprendida en el período de la oferta. ');
		xGetElementById('fechaFin').focus();
	

	}else if( parametroObligatorio == 1	 && comparaFecha(f1,f2)!=2){
		alert("Las fecha de salida debe ser posterior a la de entrada");
		xGetElementById('fechaFin').focus();
		
	}else if( parametroObligatorio == 2	 &&  !validaHora(xGetElementById('hora').value) ){
		alert("La hora debe ser en formato 24h. Ej 21:30");
		xGetElementById('hora').focus();
		
	}else if(precioDia == 0 && (vacio(xGetElementById('numPersonas').value) || isNaN(xGetElementById('numPersonas').value) ||  parseInt(xGetElementById('numPersonas').value)<=0)  ) {
		alert('Debes indicar el nº de personas para las que se realiza la reserva.');
		xGetElementById('numPersonas').focus();
			
	}else if(precioDia == 0 && precioMenores !=0 &&  !vacio(xGetElementById('numMenores').value) && (isNaN(xGetElementById('numMenores').value) || parseInt(xGetElementById('numMenores').value)<0 )){  
		alert('Revisa el campo Nº de niños.');
		xGetElementById('precioMenores').focus();
					
	}else if(vacio(xGetElementById('comentarios').value) ){
		alert('En el campo comentarios no puede quedar vacío. Solo letras y numeros.');
		xGetElementById('comentarios').focus();
				
	}else if(!creandoPaquete && !xGetElementById('legal').checked){
		alert('Debes leer y aceptar la politicia de privacidad.');			
		
	}else errorValidaOtro = false;
	
	
	
	if(!errorValidaOtro){
		// Enviamos formulario, pero antes oculto a botonera
		ocultaBotonera('botonera');
		//xGetElementById('formReservar').action = "oQueSexa.php";
		xGetElementById('formReservar').submit();
		
	}
	
}



function validaFormDatosPersonalizado(){
	
	if (vacio(xGetElementById('nombre').value)  || !caracteresValidos(xGetElementById('nombre').value, 4,100) ){
		alert('Revise el nombre.');
		xGetElementById('nombre').focus();		
	
	}else if (vacio(xGetElementById('dni').value)  || !validaDNI(xGetElementById('dni').value) ){
		alert('Revise el DNI.');
		xGetElementById('dni').focus();		
	
	}else if(vacio(xGetElementById('telefono').value)  && vacio(xGetElementById('email').value) ){
		alert('Debe introducir el telefono o el email');
		xGetElementById('telefono').focus();
		
	}else if(!vacio(xGetElementById('telefono').value)  && !validaTelefono(xGetElementById('telefono').value) ){
		alert('Revise el telefono.');
		xGetElementById('telefono').focus();
		
	}else if(!vacio(xGetElementById('email').value)  && !validaEmail(xGetElementById('email').value) ){
		alert('Revise el email.');
		xGetElementById('email').focus();
		
	}else if( !xGetElementById('legal').checked){
		alert('Debes leer y aceptar la politicia de privacidad.');			
		
	}else{
		// Enviamos formulario, pero antes oculto a botonera
		ocultaBotonera('botonera');
		//xGetElementById('formReservar').action = "oQueSexa.php";
		xGetElementById('formReservar').submit();
	}
}


/*
	Valida a solicitud de reserva asociada a unha oferta (recibe idOferta) é obligatorio o telef ou o email.
	Recibimos o tipo de establecemento (1 alox, 2 rest, 3 otros)
	Estas si van a BBDD
	A Eliminar
*/
function validaFormReservarOferta(tipoE){
	// collo as fechas máximas e mínimas
	var fMin = xGetElementById('fechaMin').value; // en segundos
	var fMax = xGetElementById('fechaMax').value; // en segundos	
	
	// Collo as fechas do formulario que poderán ser 1 (restaurantes/ocio) ou 2 (aloxamentos)
	var f1 = strtotime(fecha2js(xGetElementById('fecha').value)); // en formato strtotime
	if(tipoE==1)var f2 = strtotime(fecha2js(xGetElementById('fechaSalida').value)); // Só aloxamentos en formato strtotime

	//alert("hoxe: " + hoxe + ", f1: " + f1 + ", f2: " +f2);

	// comprobemos...
	
	if ( vacio(xGetElementById('nombre').value)  || !caracteresValidos(xGetElementById('nombre').value, 4,100)){
		alert('Revise el nombre.');
		xGetElementById('nombre').focus();		
	
	}else if (tipoE == 1 &&  (vacio(xGetElementById('dni').value)  || !validaDNI(xGetElementById('dni').value)) ){
		alert('Revise el DNI.');
		xGetElementById('dni').focus();		
	
	}else if(vacio(xGetElementById('telefono').value)  && vacio(xGetElementById('email').value)){
		alert('Debe introducir el telefono o el email');
		xGetElementById('telefono').focus();
		
	}else if(!vacio(xGetElementById('telefono').value)  && !validaTelefono(xGetElementById('telefono').value)){
		alert('Revise el telefono.');
		xGetElementById('telefono').focus();
		
	}else if(!vacio(xGetElementById('email').value)  && !validaEmail(xGetElementById('email').value)){
		alert('Revise el email.');
		xGetElementById('email').focus();
		
		// Axustar a comprobación de fechas	
		// Fecha1  definida, >= hoxe, >=fMin, <= fMax
		// Fecha2  definida, > hoxe, >=fMin, <= fMax
		// f2>f1
	}else if (vacio(xGetElementById('fecha').value) || comparaFecha(f1,hoxe) != 1 || comparaFecha(f1, fMin) == 2  || comparaFecha(f1, fMax) == 1)   {
		alert('Revise la fecha de ENTRADA. Compruebe que sea superior a la fecha actual (' + hoxeStr + ')\n y que está comprendida en el período de la oferta. ');
		xGetElementById('fecha').focus();
	

	}else if( tipoE== 1 &&  (vacio(xGetElementById('fechaSalida').value) || comparaFecha(f2,hoxe)!= 1 || comparaFecha(f2,fMin) !=1  || comparaFecha(f2, fMax)== 1) )   {
		alert('Revise la fecha de SALIDA. Compruebe que no sea inferior a la fecha actual (' + hoxeStr + ')\n y que está comprendida en el período de la oferta. ');
		xGetElementById('fechaSalida').focus();
	

	}else if(tipoE==1 && comparaFecha(f1,f2)!=2){
		alert("Las fechas de salida debe ser posterior a la de entrada");
		xGetElementById('fechaSalida').focus();
		
	}else if( tipoE==1 && (vacio(xGetElementById('numHabitaciones').value) || isNaN(xGetElementById('numHabitaciones').value)) ) {
		alert("Introduzca el numero de habitaciones");
		xGetElementById('numHabitaciones').focus();
		
		
	}else if(tipoE==1 && xGetElementById('numHabitaciones').value > parseInt(xGetElementById('numDisponible').value) ){
		alert("Esta oferta dispone de un máximo de " + xGetElementById('numDisponible').value + " habitaciones. Vd ha solicitado " + parseInt(xGetElementById('numHabitaciones').value));
		xGetElementById('numHabitaciones').focus();
		
	}else if(tipoE !=1 && !validaHora(xGetElementById('hora').value) ){
		alert("La hora debe ser en formato 24h. Ej 21:30");
		xGetElementById('hora').focus();
		
	}else if(tipoE !=1 && (vacio(xGetElementById('numPersonas').value) || isNaN(xGetElementById('numPersonas').value)) ){
		alert("Introduce el Nº de personas");
		xGetElementById('numPersonas').focus();
		
	}else if(vacio(xGetElementById('comentarios').value) ){
		alert('En el campo comentarios no puede quedar vacío. Solo letras y numeros.');
		xGetElementById('comentarios').focus();
				
	}else{
		
		cadena ="";
		cadena += 'idOferta=' + xGetElementById('idOferta').value  + '&idEstablecimiento=' + xGetElementById('idEstablecimiento').value + 
		'&idTipoEstablecimiento=' + xGetElementById('idTipoEstablecimiento').value + 
		'&nombreEstablecimiento=' + xGetElementById('nombreEstablecimiento').value + 
		'&nombre=' + xGetElementById('nombre').value + 
		'&telefono=' + xGetElementById('telefono').value + '&email=' +  xGetElementById('email').value + 
		'&fecha=' + xGetElementById('fecha').value;
		
		// Si é aloxamento
		if(tipoE==1){
			
			cadena += '&fechaSalida=' + xGetElementById('fechaSalida').value;
			cadena += '&numHabitaciones=' +  xGetElementById('numHabitaciones').value;
			cadena += '&dni=' + xGetElementById('dni').value;
			
		}else{
			cadena += '&hora=' + xGetElementById('hora').value;
			cadena += '&numPersonas='+ xGetElementById('numPersonas').value;
		}
		
		//cadena += '&numPersonas=' + xGetElementById('numPersonas').value;
		cadena += '&comentarios='+xGetElementById('comentarios').value;
		
		// Meter XHTMLRequest cando teña tempo
		
		//cadena += '&nocache=' + Math.random(); // Engadimos unha variable alatoria a url para evitar a cache.
											   // Ademáis metemos un <-header no cache -> no html.
											   
		//xGetElementById('formBuscarOfertas').action = "resultadosBusqueda.php";
		//xGetElementById('formBuscarOfertas').submit();
		//return true;
		// enviamos por post 			  GET  POST
		cargaPaxina('reservarOferta.php', '', cadena, 'principal', 'Enviando datos. Espera por favor...');
	
		
	}
	
}




/*

	Función para validar o formulario extenso de búsqueda de ofertas.
	
*/
function validaFormBuscarOferta(tipoEstablecimiento){
	
	//var hoxe = strtotime(fecha2js(diaActual()));  // Dia de hoxe en formato strtotime
	//var hoxeStr = diaActual(); // en formato humano
	
	try{
		f1Str = xGetElementById('fecha1').value;
		var f1 = strtotime(fecha2js(xGetElementById('fecha1').value)); // Fecha escollida en formato strtotime
		
	
	}catch(err){
		// Nada
		//txt+="Error description: " + err.description + "\n\n";
  		//alert(txt);

	}
	/*alert("hoxe: " + hoxeStr + "(" + hoxe + ") \n f1: " + f1Str + "(" + f1 + ")");
	alert(comparaFecha(f1, hoxe));
	alert(vacio(f1));*/
	if (!compSelect(xGetElementById('idTipoEstablecimiento').value, 0) ){
		
		alert("¡Debe seleccionar el tipo de establecimiento!");
		xGetElementById('idTipoEstablecimiento').focus();	
	
	}else if (vacio(xGetElementById('fecha1').value) || comparaFecha(f1, hoxe) != 1)   {
		alert('Revise la fecha. Compruebe que sea superior a la fecha actual (' + hoxeStr + '). ');
		xGetElementById('fecha1').focus();
	

	}else{
		xGetElementById('formBuscarOfertas').action = "resultadosOfertas.php";
		xGetElementById('formBuscarOfertas').submit();

	}

	return false;

}



/*

	Función para validar o formulario abreviado de búsqueda de ofertas.
	Si non se mete ningún dato, listamos todas ofertas do tipo de establecemento en cuestión
*/
function validaFormOfertasMini(tipoEstablecimiento){
	

	try{
		f1Str = xGetElementById('fecha1').value;
		var f1 = strtotime(fecha2js(xGetElementById('fecha1').value)); // Fecha escollida en formato strtotime
		
	
	}catch(err){
		// Nada
		//txt+="Error description: " + err.description + "\n\n";
  		//alert(txt);

	}
	
	// Comprobo fechas
	//if ( !vacio( xGetElementById('fecha1').value) && ( comparaFecha(f1,hoxe)==2 || ( comparaFecha(f1,hoxe)==0 && tipoEstablecimiento !=2 ))    )   {
	if ( !vacio( xGetElementById('fecha1').value) && comparaFecha(f1, hoxe) != 1)   {
																   
		alert('Revise la fecha. Compruebe que sea superior a la fecha actual (' + hoxeStr + '). ');
		xGetElementById('fecha1').focus();
	

	}else{
		xGetElementById('formBuscarOfertas').action = "resultadosOfertas.php"; // busqueda abreviada
		xGetElementById('formBuscarOfertas').submit();
	}

	return false;
}





/*

Rutina para realixzar unha caga via AJAX. Recibe:
	- paxina a cargar
	- si o método e get recibese a cadena valorget
	- si o método e post recibese a cadena valorpost
	- capa donde cargar activar o contido cargado
	- si text !='' hai q poñer preloader.

*/



function cargaPaxina(paxinaDestino, valorget, valorpost, capa, texto){ 
    
	ajax = validaAJAX(paxinaDestino);
	
    if(valorpost != ""){
        ajax.open("POST", paxinaDestino + "?" + valorget + "&tiempo=" + new Date().getTime(), true); // get date para evitar vcache cambiando a url
    } else {
        ajax.open("GET", paxinaDestino + "?" + valorget + "&tiempo=" + new Date().getTime(), true);
    }
	
    ajax.onreadystatechange=function() {
		
        if (ajax.readyState==1){
            xGetElementById(capa).innerHTML = '<div style="width:90%; margin:50px auto; text-align:center;"><img src="imaxes/ajax-loader.gif" class="ajaxLoader"><br>'+texto+'</div>'; // Ou unha páxina que poña cargando....
        }
		
        if (ajax.readyState==4) {
			
            if(ajax.status==200){
				xGetElementById(capa).innerHTML = ajax.responseText; // Tûdo bôm
				
				// Redimensionar capas
				setH();
				
			}else if(ajax.status==404){
				
                xGetElementById(capa).innerHTML = "Se ha producido un error al cargar el script. 404 No encontrado"; // Páxina de error--> usar unha función para cerar esa páxina
				
            }else{
                xGetElementById(capa).innerHTML = "Error: ".ajax.status; // A saber que pasou...
            }
        }
    }
	
    if(valorpost != ""){
		// Si non usamos o método post
        ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        ajax.send(valorpost);
		
    } else {
        ajax.send(null);
    }
} 



// 			Averigua método ajax axeitado
// --------------------------------------------------------------------------------------------------------------------	
function validaAJAX(file) {
    xmlhttp=false;
	
    this.AjaxFailedAlert = "Su navegador no soporta las funciónalidades de este sitio y podria funcionar de forma diferente a la que fue pensada. Por favor habilite javascript en su navegador para verlo normalmente.\n";
    this.requestFile = file;
    this.encodeURIString = true;
    this.execute = false;
	
    if (window.XMLHttpRequest) { 
	
        this.xmlhttp = new XMLHttpRequest();
		
        if (this.xmlhttp.overrideMimeType) {
			
            this.xmlhttp.overrideMimeType('text/xml');
        }
		
    }else if (window.ActiveXObject) { // IE
        try {
            this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			
        }catch (e) {
            try {
                this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				
            } catch (e) {
                this.xmlhttp = null;
            }
        }
		
        if (!this.xmlhttp && typeof XMLHttpRequest!='undefined') {
			
            this.xmlhttp = new XMLHttpRequest();
			
            if (!this.xmlhttp){
                this.failed = true; 
            }
        } 
    }
    return this.xmlhttp ;
}










/*

	Función para xenerar un popUp co calendario
*/
var ventanaCalendario=false

function muestraCalendario(raiz,formulario_destino,campo_destino,mes_destino,ano_destino){
	//funcion para abrir una ventana con un calendario.
	//Se deben indicar los datos del formulario y campos que se desean editar con el calendario, es decir, los campos donde va la fecha.
	if (typeof ventanaCalendario.document == "object") {
		ventanaCalendario.close()
	}
	ventanaCalendario = window.open("include/calendario/index.php?formulario=" + formulario_destino + "&nomcampo=" + campo_destino,"calendario","width=300,height=300,left=100,top=100,scrollbars=no,menubars=no,statusbar=NO,status=NO,resizable=YES,location=NO")
}


/*

	Función para xenerar un poUp coas tarifas
*/
var ventanaTarifas=false
function muestraTarifas(idEstablecimiento){
	//funcion para abrir una ventana con un calendario.
	//Se deben indicar los datos del formulario y campos que se desean editar con el calendario, es decir, los campos donde va la fecha.
	if (typeof ventanaCalendario.document == "object") {
		ventanaCalendario.close()
	}
	ventanaCalendario = window.open("include/calendario/index.php?formulario=" + formulario_destino + "&nomcampo=" + campo_destino,"calendario","width=300,height=300,left=100,top=100,scrollbars=no,menubars=no,statusbar=NO,status=NO,resizable=YES,location=NO")
}









/*

	Función que abre un popUp co localizador de tarifas

*/
var ventanaLocalizador = false;

function abreLocalizador(){
	//funcion para abrir unha ventana para crear/editar articulos
	if (typeof ventanaLocalizador.document == "object") {
		ventanaLocalizador.close()
	}
	ancho=400; alto = 100;
	

	// Coordenadas
	leftPosition=(screen.width)?(screen.width-ancho)/2:100; 
	topPosition=(screen.height)?(screen.height-alto)/2:100;
	
	url ="localizadorReservas.php";
	url += "&nocache=" + Math.random();
		
	ventanaAvisoError = window.open( 'localizadorEntradaDatos.php' ,"Localizador_Reservas","width=" + ancho +",height="+ alto +",left=" + leftPosition +",top=" + topPosition +",scrollbars=no,menubars=no,statusbar=NO,status=NO,resizable=NO,location=NO")
}

















/*

	Función que abre un popUp indicando que houbo un error

*/
var ventanaAvisoError = false;

function avisoError(url, ancho, alto){
	//funcion para abrir unha ventana para crear/editar articulos
	if (typeof ventanaAvisoError.document == "object") {
		ventanaAvisoError.close()
	}
	
	

	// Coordenadas
	leftPosition=(screen.width)?(screen.width-ancho)/2:100; 
	topPosition=(screen.height)?(screen.height-alto)/2:100;
	
	url += "&nocache=" + Math.random();
		
	ventanaAvisoError = window.open( url ,"Error","width=" + ancho +",height="+ alto +",left=" + leftPosition +",top=" + topPosition +",scrollbars=no,menubars=no,statusbar=NO,status=NO,resizable=NO,location=NO")
}








//=============================================================================================================================
// Nova Janela by Dani
/*
O codigo correcto abrir un popup dende un enlace é este:
<a href="/index.htm" target="_blank" onClick="javascript:void window.open(this.href, this.target, 'width=300,height=400'); return false;">Lanzar correctamente</a>
*/

