// Navegador
//------------------------------------------------------------------------------------------------
var ie = document.all ? 1 : 0;
var ns = document.layers ? 1 : 0;
var sepFecha = "/";

idi = new Array(20)
idi[1] = "El campo|O campo|The field|Le champ|O campo|Il campo|Das feld";
idi[2] = "es obligatorio|é obrigatorio|cannot remain blank|est obligatoire|é obrigatório|non può essere vuoto|ist verpflichtend";
idi[3] = "no puede ser menor de|non pode ser menor de|must have at least|doit avoir|debe ter|deve essere|muss mindestens";
idi[4] = "caracteres|caracteres|characters|caractères|caracteres no máximo|caratteri|Zeichen lang sein|";
idi[5] = "no puede ser mayor de|non pode ser maior de|cannot contain more than|doit avoir au maximum|debe ter|deve essere massimo|darf maximal";
idi[6] = "debe ser numérico|debe ser numérico|must be a numeric value|doit être une valeur numerique|deve ser numérico|debe essere numerico|muss ein numerischer Wert sein";
idi[7] = "debe ser DD"+ sepFecha +"MM"+ sepFecha +"AAAA|debe ser DD"+ sepFecha +"MM"+ sepFecha +"AAAA|must be DD"+ sepFecha +"MM"+ sepFecha +"YYYY|doit être JJ"+ sepFecha +"MM"+ sepFecha +"AAAA|deve ser: DD"+ sepFecha +"MM"+ sepFecha +"AAAA|debe essere GG"+ sepFecha +"MM"+ sepFecha +"AAAA|muss TT"+ sepFecha +"MM"+ sepFecha +"JJJJ sein";
idi[8] = "no puede elegir una fecha menor a la actual|non pode escoller unha data menor á actual|the selected date cannot be earlier than the current date|vous ne pouvez pas choisir une date précédente à l’actuelle|a data não pode ser menor que a atual|la data non può essere precedente alla data odierna|das gewählte Datum muss späterer als das laufende Datum sein";
idi[9] = "debe ser una dirección de correo válida|debe ser unha direción de correo válida|please enter a valid e-mail address|vous devez saisir une adresse e-mail correcte|deve introduzir um endereço de email válido|voi dovete inserire un'indirizzo e-mail valido|Sie müssen eine gültige E-Mail-Adresse eingeben";
idi[10]= "debe seleccionar un tipo de archivo válido|debe seleccionar un tipo de arquivo válido|please select a valid file format|vous devez sélectionner un fichier valide|deve selecionar um arquivo válido|voi dovete selezionare un formato file valido|bitte, wählen Sie eine gültige Datei aus";
idi[11]= "No existen restricciones de tipo|Non hai restricións de tipo|There are no restrictions of type|Il n’y a pas de restrictions du type|Não existem restrições do tipo|Non esistono restrizioni dei tipo|Es gibt keine abgrenzung der art";
idi[12]= "debe ser DD"+ sepFecha +"MM"+ sepFecha +"AAAA|debe ser DD"+ sepFecha +"MM"+ sepFecha +"AAAA hh:mm|must be DD"+ sepFecha +"MM"+ sepFecha +"YYYY hh:mm|doit être JJ"+ sepFecha +"MM"+ sepFecha +"AAAA hh:mm|deve ser: DD"+ sepFecha +"MM"+ sepFecha +"AAAA hh:mi|debe essere GG"+ sepFecha +"MM"+ sepFecha +"AAAA hh:mm|muss TT"+ sepFecha +"MM"+ sepFecha +"JJJJ sein hh:mm";
idi[13]= "Los campos fecha deben tener formato DD"+ sepFecha +"MM"+ sepFecha +"AAAA|Os campos de data deben ter formato DD"+ sepFecha +"MM"+ sepFecha +"AAAA|The date fields must have DD"+ sepFecha +"MM"+ sepFecha +"YYYY format|Le format des champs de date doit être JJ"+ sepFecha +"MM"+ sepFecha +"AAAA|Os campos de data devem ter formato DD"+ sepFecha +"MM"+ sepFecha +"AAAA|I campi di tipo data devono devono avere il formato GG"+ sepFecha +"MM"+ sepFecha +"AAAA|Die Datumsfelder müssen das TT"+ sepFecha +"MM"+ sepFecha +"JJJJ Format haben";
idi[14]= "El día no es correcto|O día non é correcto|You have entered a wrong day|Le jour entré est incorrect|O dia introduzido é incorrecto|Il giorno introdotto è scorretto|Falscher Tag eingegeben";
idi[15]= "El mes no es correcto|O mes non é correcto|You have entered a wrong month|Le mois entré est incorrect|O mês introduzido é incorrecto|Il mese introdotto è scorretto|Falscher Monat eingegeben";
idi[16]= "El año no es correcto|O ano non é correcto|You have entered a wrong year|L’an entré est incorrect|O ano introduzido é incorrecto|Il anno introdotto è scorretto|Falsches Jahr eingegeben";
idi[17]= "Las contraseñas son distintas|Os contrasinais son distintos|Your passwords don't match|Les mots de passe sont différents|As senhas são distintas|I contrassegni sono differenti|Die Passworter sind verschieden";
idi[18] = "¿Desea borrar el registro seleccionado?|Desexa borrar o rexistro?";


// DEVUELVE un texto del array idi pasándole una posición y un idioma
// -----------------------------------------------------------------------------------------------
function mIdiJS(id){
	aux = idi[id].split("|");
	return aux[idIdioma-1];
}

// AÑADE un 0 a la izda de un nº de una cifra
// ------------------------------------------------------------------------------------------------
function numDosCifras(num){
	var aux =num;
	if (num < 10){
		aux = "0" + aux;
	}
	return aux;
}

// DEVUELVE el nº de días de un mes
// -----------------------------------------------------------------------------------------------
function nDiasMes(ano, mes){
	var msDia, msFecha, fecha;
	msDia = 86400000; // nº de ms de un dia
	msFecha = new Date(ano, mes, 1).getTime(); // nº de ms hasta el dia 1 del mes siguiente al seleccionado
	fecha = new Date(msFecha - msDia); // fecha del último día del mes
	return fecha.getDate();
}

// -------------------------------------------------------------------------------------------
function escribeUrl(destino){
	while (destino.indexOf("&amp;") != -1) {
		destino = destino.replace("&amp;", "&");
	}
	return destino;
}

// función GENÉRICA para cualquier formulario
//------------------------------------------------------------------------------------------------
function chekea(cual) {
	var i, tipo, valor;
	if (cual.elements) {
		for (i=0; i<cual.elements.length; i++) {
			if (cual.elements[i].name != null && cual.elements[i].name.substr(0,4) == "chk|") {
				tipo = cual.elements[i].name.split("|");
				valor = cual.elements[i].value;
				switch (tipo[2]) {
					case "str":	// alfanumérico
						// Primero veo si es obligatorio RELLENARLO
						if ((valor.length == 0) && tipo[5] == "true") {
							alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(2));
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después veo si es menor que el mínimo
						if (tipo[5] == "true" && valor.length < parseInt(tipo[3],10)) {
							alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(3)+" "+tipo[3]+" "+mIdiJS(4));				
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Y por último si es mayor que el máximo
						if (valor.length > parseInt(tipo[4],10)) {
							alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(5)+" "+tipo[4]+" "+mIdiJS(4));
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						break;
					case "int":	// numerico
						// Primero veo si es obligatorio RELLENARLO
						if ((valor.length == 0) && tipo[5] == "true") {
							alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(2));
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después compruebo que sea NUMÉRICO
						if (!(esNumerico(valor))) {
							alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(6));
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
								cual.elements[i].select();
							}
							return false;
						}
						// Después veo si es menor que el mínimo
						if (parseInt(valor,10) < parseInt(tipo[3],10)) {
							alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(3)+" "+tipo[3]);
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Y por último si es mayor que el máximo
						if (parseInt(valor,10) > parseInt(tipo[4],10)) {
							alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(5)+" "+tipo[4]);
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
								cual.elements[i].select();
							}
							return false;
						}
						break;
					case "date":	// fecha
						// Primero veo si es obligatorio RELLENARLO
						if ((valor.length == 0) && tipo[5] == "true") {
							alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(2));
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después compruebo que sea FECHA
						if (validaFecha(valor) != "ok" && valor != "") {
							alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(7)+"\n"+validaFecha(valor));
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después veo si es menor que el mínimo
						if (convierteFecha(valor) < convierteFecha(tipo[3])) {
							alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(3)+" "+tipo[3]);
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después veo si es mayor que el máximo
						if (convierteFecha(valor) > convierteFecha(tipo[4])) {
							alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(5)+" "+tipo[4]);
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						break;
					case "eml":	//E-mail
						// Primero veo si es obligatorio RELLENARLO
						if ((tipo[5] == "true") && (valor.length == 0)) {
							alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(2));
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						// Después compruebo que sea EMAIL válido
						if ((esMail(valor)!=true) && (valor!="")){
							alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(9));
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}
						break;
					case "file":	// archivo
						// Primero veo si es obligatorio RELLENARLO

						if ((valor == "") && tipo[5] == "true") {
							alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(2));
							if (cual.elements[i].type!="hidden"){
								cual.elements[i].focus();
							}
							return false;
						}		

						break;
					case "combo": // Combo
							// comprobamos si es obligatorio RELLENARLO
							if (tipo[5] == "true") {
								// Después comprobamos que sea válido (distinto de -1)
								if (valor == "-1"){
									alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(2));
									if (cual.elements[i].type!="hidden"){
										cual.elements[i].focus();
									}
									return false;								
								}
							}
							break;
					case "fileArchivo": // archivo, para limitar las extensiones
							// Primero veo si es obligatorio RELLENARLO
	
							if ((valor == "") && tipo[5] == "true") {
								alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(2));
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
								}
								return false;
							}
							// Compruebo que el formato de imagen se una de los admitidos
							if ( (valor != "") && (!(validaArchivo(valor))) ) {
								alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(10));
								if (cual.elements[i].type!="hidden"){
									cual.elements[i].focus();
									cual.elements[i].select();
								}
								return false;
							}
							break;
					case "chkb"://checkbox
						if (tipo[5] == "true" && cual.elements[i].checked == false){
							alert(mIdiJS(1)+" \""+tipo[6]+"\" "+mIdiJS(2));
							cual.elements[i].focus();
							return false;
						}
						break;
					default:
						alert(mIdiJS(11)+" \""+tipo[2]+"\"");
						return false;
						break;
				}
			}
		}
	}
	return true;
}

// VALIDAMOS que el formato de archivo sea uno de los adecuados
// -----------------------------------------------------------------------------------------------
function validaArchivo(archivo){
	// Recogemos la extensiones permitidas en un array
	extensiones_permitidas = new Array(".jpg",".jpeg");
	// Recogemos la extensión del archivo
	extension = (archivo.substring(archivo.lastIndexOf("."))).toLowerCase();
	permitida = false;
	// Recorremos todas las extensiones admitidas y miramos si alguna coincide
	for (var i = 0; i < extensiones_permitidas.length; i++) {
		if (extensiones_permitidas[i] == extension) {
			permitida = true;
			break;
		}
	} 
	if (permitida) {
		return true;
	}else{
		return false;
	}
}


// COMPRUEBA el formato de los campos fecha en buscadores
// -----------------------------------------------------------------------------------------------
function chekeaBuscador(cual) {
	if (cual.elements){
		var i, valor;
		for (i=0; i<cual.elements.length; i++) {
			if (cual.elements[i].name != null) {
				// Comprobamos que no sea un campo oculto
				if (cual.elements[i].type != "hidden"){
				// Comprobamos el formato si es de tipo FECHA
					if (cual.elements[i].name.substr(0, 8) == "bsqFecha" || cual.elements[i].name == "bsqFechaInicio" || cual.elements[i].name == "bsqFechaFin") {
						valor = cual.elements[i].value;
						if (validaFecha(valor) != "ok" && valor != "") {
							alert(mIdiJS(13));
							cual.elements[i].focus();
							return false;
						}
					}
				}
			}
		}
	}
	return true;
}

// COMPRUEBA que una fecha sea correcta
//------------------------------------------------------------------------------------------------
function validaFecha(dato){
	var fecha, dia, mes, ano, aux, formato;

	dia 	= dato.substr(0, 2);
	mes 	= dato.substr(3, 2);
	ano 	= dato.substr(6, 4);

	aux		= "DD"+dato.substr(2, 1)+"MM"+dato.substr(5, 1)+"AAAA";
	formato	= "DD"+ sepFecha +"MM"+ sepFecha +"AAAA";	// formato de fecha y hora
	
//	comprobamos si el formato recibido es el correcto
	if(isNaN(dia+mes+ano)==false && aux==formato && dato.length==formato.length){
		fecha=new Date(ano, mes-1, dia);
		
		if(fecha.getDate() != dia){
			aux=mIdiJS(14);
		}else if(fecha.getMonth() != (mes-1)){
			 aux=mIdiJS(15);
		}else if(fecha.getFullYear() != ano){
			aux=mIdiJS(16);
		}else{
			aux="ok"; // la fecha es correcta
		}
	}else{
		aux="'"+dato+"'";
	}
	return aux;
}

// CONVIERTE una FECHA
// -----------------------------------------------------------------------------------------------
function convierteFecha(quien) {
	var fecha_split;	
	var tdia, tmes, tano;
	fecha_split = quien.split(sepFecha);
	tdia = parseInt(fecha_split[0],10);
	tmes = parseInt(fecha_split[1],10);
	tano = parseInt(fecha_split[2],10);
	return date = new Date(tano,tmes-1,tdia);
}

// VALIDA un email
// -----------------------------------------------------------------------------------------------
function esMail(texto){
    var valido = true;             
    var cadena = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890@._-";
    var arroba = texto.indexOf("@", 0);
    if ((texto.lastIndexOf("@")) != arroba) arroba = -1;
    var punto = texto.lastIndexOf(".");
	var i;
    for (i=0 ;i<texto.length;i++){
		if (cadena.indexOf(texto.substr(i, 1),0) == -1){
			valido = false;
			break;
    	}
    }
	if ((arroba > 1) && (arroba + 1 < punto) && (punto + 1 < (texto.length)) && (valido == true) && (texto.indexOf("..",0) == -1)){
    	valido = true;
	}else{
		valido = false;
	}
    return valido;
}

// VALIDA un texto de tipo alfanumerico
// -----------------------------------------------------------------------------------------------

function esNumerico(texto){
    var valido 	= true; 
	var decimal	= false;
    var cadena = "1234567890";
	var i;
    for (i=0;i<texto.length;i++){

		caracter=texto.substr(i, 1);

		if(caracter==","){		// la "," es el símbolo decimal
			if(decimal==false){
				decimal=true;
			}else{
				valido=false;	// se encontro mas de una coma
				break;
			}
		}else{
			if (cadena.indexOf(caracter, 0) == -1){
				valido=false;
				break;
			}
		}
    }
    return valido;
}

// Selecciona un elemento y copia su valor en otro
function selecciona(origen, destino){
	destino.value = origen;
}

// muestra la imagen del tipo de habitación seleccionado
function muestraTipoHabitacion(tipoHabitacionP){
	var simple = document.getElementById('single');
	var doble  = document.getElementById('double');
	var nRooms = document.getElementById('nRooms');
	var tipoHabitacion = document.getElementById('tipoHabitacion');
	switch(tipoHabitacionP){
		case 1: simple.style.visibility = 'visible';
				tipoHabitacion.value = 1;
				if(doble.style.visibility == 'visible'){
					doble.style.visibility = 'hidden';
				}
		break;
		case 2: doble.style.visibility = 'visible';
				tipoHabitacion.value = 2;
				if(simple.style.visibility == 'visible'){
					simple.style.visibility = 'hidden';
				}
		break;
	}
	if(!parseInt(nRooms.value)){
		nRooms.value = '1';
	}
	calculaTotal();
}

// DEVUELVE si la primera fecha es mayor o igual que la segunda
// -------------------------------------------------­----------------------------------------------
function esFechaMayor(fechaFin, fechaIni) {
	if (fechaFin == "") {
		return true;
	} else {
		if (convierteFecha(fechaFin) >= convierteFecha(fechaIni)) {
			return true;
		} else {
			return false;
		}
	}
}

//calcula el nº de dias entre la fecha de llegada y salida
function calculaNoches(){
	var inDate = document.getElementById('inDate').value;
	var outDate = document.getElementById('outDate').value;
	var nNightsV = document.getElementById('nNightsV');
	var nNights = document.getElementById('nNights');
	nNights.value = diasFechaDif(outDate, inDate);
	nNightsV.value = nNights.value;
	calculaTotal();
}

//calcula el nº de dias entre dos fechas, si las dos fechas son la misma devuelve 1 dia
function diasFechaDif(fechaFin, fechaIni){
	var aux;
	if(validaFecha(fechaIni) == "ok" && validaFecha(fechaFin) == "ok"){
		if(esFechaMayor(fechaFin, fechaIni)){
			aux = (convierteFecha(fechaFin) - convierteFecha(fechaIni))/86400000; 
			if(aux == 0){ aux = 1;}
		}else{
			aux = '';
		}
	}else{
		aux = '';
	}
	return aux;
}

//calcula el precio total de la reserva
function calculaTotal(){
	var precio = damePrecioHabitacion();
	var nRooms = document.getElementById('nRooms').value;
	var nNights = document.getElementById('nNights').value;
	var totalV = document.getElementById('totalV'); 
	var total = document.getElementById('total');
	var auxTotal = (nRooms*nNights*precio);
	if(auxTotal){
		total.value = redondea(auxTotal+'');
	}else{
		total.value = '';
	}
	totalV.value = redondea(''+total.value);
}

function redondea(cant){
	var cantSplit = cant.split('.');
	var unidades = cantSplit[0];
	var decimales = cantSplit[1];
	var auxDecimales;
	if(decimales != '' && decimales != null && decimales.length > 2){
		auxDecimales = ''+decimales.substr(0,2);
	}
	if(auxDecimales){ cant = unidades + "." + auxDecimales}
	return cant;
}

//devuelve el precio de la habitación actualmente seleccionada
function damePrecioHabitacion(){
	var simple = document.getElementById('single');
	var doble  = document.getElementById('double');
	if (simple.style.visibility != 'hidden' || doble.style.visibility != 'hidden'){
		if(simple.style.visibility == 'visible'){ return (66.35);}
		if(doble.style.visibility == 'visible'){ return (96.30);}
	}else{
		return (0);
	}
}

function validaFormaPago(){
	var txt = "Seleccionar una FORMA DE PAGO es obligatorio";
	var c1 = document.getElementById('c1');
	var c2 = document.getElementById('c2');
	var c3 = document.getElementById('c3');
	if(!c1.checked && !c2.checked && !c3.checked){
		alert(txt);
		return false;
	}else{
		if(c3.checked){
			return chekea(document.getElementById('frmSolicitud'));
		}else{
			return true;
		}
	}
}

//impide que se seleccione más de una forma de pago
function chck(element){
	var txt = "Seleccionar solo una FORMA DE PAGO";
	var c1 = document.getElementById('c1');
	var c2 = document.getElementById('c2');
	var c3 = document.getElementById('c3');
	c1.checked = c2.checked = c3.checked = false;
	element.checked = true;
	credit();
}

//desbloquea los capos de la forma de pago CREDIT CARD si la eleginos
function credit(){
	var c3 = document.getElementById('c3');
	var n = document.getElementById('n');
	var e = document.getElementById('e');
	var cd = document.getElementById('cd');
	if(c3.checked){
		if(n.disabled){
			n.disabled = false;
			n.name = "chk|number|str|x|x|true|NUMERO";
		}
		if(e.disabled){
			e.disabled = false;
			e.name = "chk|expired|date|x|x|true|CAD";
		}
		if(cd.disabled){
			cd.disabled = false;
			cd.name = "chk|secCode|str|x|x|true|COD. SEGURIDAD";
		}
	}else{
		n.name = "chk|number|str|x|x|false|NUMERO";
		n.value = "";
		n.disabled = true;
		e.name = "chk|expired|date|x|x|false|CAD";
		e.value = "";
		e.disabled = true;
		cd.name = "chk|secCode|str|x|x|false|COD. SEGURIDAD";
		cd.value = "";
		cd.disabled = true;
	}
}

//Obliga a seleccionar un tipo de habitación
function validaTipoHabitacion(){
	var tipoHabitacion = document.getElementById("tipoHabitacion");
	if (tipoHabitacion.value == ""){
		alert("Seleccionar TIPO DE HABITACIÓN es obligatorio");
		return false;
	}else{
		return true;
	}
}

function validaTodo(){
	if(chekea(document.frmSolicitud) && validaTipoHabitacion() && validaFormaPago()){
		document.frmSolicitud.submit();
		document.frmSolicitud.innerHTML = "";
	}
}