//Funciones para contenedor de carga en procesos AJAX

function aparecer()

{	

	if(document.getElementById("procesandomsg"))

		document.getElementById("procesandomsg").style.display = "block";

}

function marca(element1) {  
 document.getElementById(element1).focus();  
 document.getElementById(element1).select();  
 }  

function desvanecer()

{

	//document.getElementById("procesandomsg").style.display = "none";

	//fader.fadeOut();

}

//Funciones que devuelven dimensiones y scroll del area de contenido del navegador

function f_clientWidth() {

	return f_filterResults (

		window.innerWidth ? window.innerWidth : 0,

		document.documentElement ? document.documentElement.clientWidth : 0,

		document.body ? document.body.clientWidth : 0

	);

}

function f_clientHeight() {

	return f_filterResults (

		window.innerHeight ? window.innerHeight : 0,

		document.documentElement ? document.documentElement.clientHeight : 0,

		document.body ? document.body.clientHeight : 0

	);

}

function f_scrollTop() {

	return f_filterResults (

		window.pageYOffset ? window.pageYOffset : 0,

		document.documentElement ? document.documentElement.scrollTop : 0,

		document.body ? document.body.scrollTop : 0

	);

}

function f_scrollLeft() {

    return f_filterResults (

        window.pageXOffset ? window.pageXOffset : 0,

        document.documentElement ? document.documentElement.scrollLeft : 0,

        document.body ? document.body.scrollLeft : 0

    );

}



function f_filterResults(n_win, n_docel, n_body) {

	var n_result = n_win ? n_win : 0;

	if (n_docel && (!n_result || (n_result > n_docel)))

		n_result = n_docel;

	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

/* RANDOM */

function isset(varname)  {
  if(typeof( window[ varname ] ) != "undefined") return true;
  else return false;
}
function firstborn(obj, element)
{
var act=document.getElementById(obj);
var divs=act.getElementsByTagName(element);

var firstborn = Array();
var j=0;
	for (var i = 0; i < divs.length; i++)
	{
		if(divs[i].parentNode.id==act.id)
		{
			firstborn[j]=divs[i].id;
			j++;
		}
	}
return firstborn;
}
/*random*/
// JavaScript Document
function opacity(id, opacStart, opacEnd, millisec) { 
    //speed for each frame 
    var speed = Math.round(millisec / 100); 
    var timer = 0; 

    //determine the direction for the blending, if start and end are the same nothing happens 
    if(opacStart > opacEnd) { 
        for(i = opacStart; i >= opacEnd; i--) { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
    } else if(opacStart < opacEnd) { 
        for(i = opacStart; i <= opacEnd; i++) 
            { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
    } 
} 

//change the opacity for different browsers 
function startrandom(rand){
if(isset('refres')){clearTimeout(refres);}

var controls=firstborn('controls','div');
for (var a=0;a<controls.length;a++){
	document.getElementById(controls[a]).className='boton';
}
var controls=firstborn('controls2','div');
for (var a=0;a<controls.length;a++){
	document.getElementById(controls[a]).className='boton';
}
var val=rand<arrayrandom.length?rand++:rand=0;

	document.getElementById('divl'+(val+1)).className='botonon';
	blendimage('blenddiv', 'blendimage', arrayrandom[val].src, 200);
	
	document.getElementById('randomlink1').href=vincrandom[val];
	document.getElementById('randomlink2').href=vincrandom[val];
	document.getElementById('randomlink3').href=vincrandom[val];
	document.getElementById('ts1').innerHTML=t1random[val];
	document.getElementById('ts2').innerHTML=t2random[val]; 
	document.getElementById('ts3').innerHTML=t3random[val]; 
	document.getElementById('lpromo').href=vincrandom[val];
	
	refres=setTimeout("startrandom(" + rand + ")",6000);

}
function changeOpac(opacity, id) { 
    var object = document.getElementById(id).style; 
    object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")"; 
}
function shiftOpacity(id, millisec) { 
    //if an element is invisible, make it visible, else make it ivisible 
    if(document.getElementById(id).style.opacity == 0) { 
        opacity(id, 0, 100, millisec); 
    } else { 
        opacity(id, 100, 0, millisec); 
    } 
}

function blendimage(divid, imageid, imagefile, millisec) {
    var speed = Math.round(millisec / 100); 
    var timer = 0; 
     
    //set the current image as background 
    document.getElementById(divid).style.backgroundImage = "url(" + document.getElementById(imageid).src + ")"; 
     
    //make image transparent 
    changeOpac(0, imageid); 
     
    //make new image 
    document.getElementById(imageid).src = imagefile; 

    //fade in image 
    for(i = 0; i <= 100; i++) { 
        setTimeout("changeOpac(" + i + ",'" + imageid + "')",(timer * speed)); 
        timer++; 
    }
}
function parsea(txt){
	var r1=["\&","\'","\+","http"];
	var r2=["_amp_","_com_","_mas_","hhhh"];
	  for (var i=0; i<r1.length; i++) {
		while(txt != txt.replace(r1[i], r2[i])) txt = txt.replace(r1[i], r2[i]);
	  } 
	return txt;
}

function parsealink(txt){
	txt=txt.replace("http","hhhh");
	txt=txt.replace("\&","_amp_");
	var r1=["\&","http"];
	var r2=["_amp_","hhhh"];
	  for (var i=0; i<r1.length; i++) {
		while(txt != txt.replace(r1[i], r2[i])) txt = txt.replace(r1[i], r2[i]);
	  } 
	return txt;
}

function pausem(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
}

// **************************** PARA LOS IDIOMAS EN JAVA **************************** //
var idioma;
if(!idioma) idioma='es';
function lengua(tipo){
idioma=tipo
}

function verficha(zona,id)
{
	var titulo;
	if(idioma=='en'){
		titulo="Loading info";
		if(zona==9) titulo="Leisure Activities";

		if(zona==10) titulo="Landscapes and Culture of Cantabria";
	}
	else{
	titulo="Mostrando informaci&oacute;n";
	if(zona==9) titulo="Actividades de ocio";
	if(zona==10) titulo="Paisajes y Cultura de Cantabria";
	}
	return GB_showCenter(titulo, '../../galeriab.php?zona='+zona+'&id='+id,500,960)
}
function tabtrans(num){ // pestanas de transportes
	document.getElementById("t1").style.display = "none";
	document.getElementById("t2").style.display = "none";
	document.getElementById("t3").style.display = "none";
	document.getElementById("t3b").style.display = "none";
	document.getElementById("t4").style.display = "none";
	document.getElementById("t5").style.display = "none";
	document.getElementById("t6").style.display = "none";
	document.getElementById("t7").style.display = "none";
	document.getElementById("t"+num).style.display = "block";
	if(num!="3b") {
	document.getElementById("s1").style.borderBottomStyle = "solid";
	document.getElementById("s2").style.borderBottomStyle = "solid";
	document.getElementById("s3").style.borderBottomStyle = "solid";
	document.getElementById("s4").style.borderBottomStyle = "solid";
	document.getElementById("s5").style.borderBottomStyle = "solid";
	document.getElementById("s6").style.borderBottomStyle = "solid";
	document.getElementById("s7").style.borderBottomStyle = "solid";
	document.getElementById("s"+num).style.borderBottomStyle = "none";
	}
}

function vemin(i){ // minutos de cerca de todo
	var f=document.getElementById(i);
	document.getElementById('min').innerHTML=f.value;
	var n=f.selectedIndex; n=n+1;
	var url='imagenes/cerca/cerca'+n+'.jpg';
	document.getElementById('min1').style.background="url('"+url+"')";
}

function cargari(imagenes){
	var lista_imagenes = new Array();
	var i;
	for(i in imagenes){
		lista_imagenes[i] = new Image();
		lista_imagenes[i].src = imagenes[i];
	}
} 

function go(what) {
  value = what.options[what.selectedIndex].value;
  if (value == "") return;
  window.location.href = value;
}

function validarEmail(valor) {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(valor)) return (true); else return (false);
}
function validarDni(dni) {
	  numero = dni.substr(0,dni.length-1);
	  let = dni.substr(dni.length-1,1);
	  numero = numero % 23;
	  letra='TRWAGMYFPDXBNJZSQVHLCKET';
	  letra=letra.substring(numero,numero+1);
	  if (letra!=let) 
	  	return false;
	  else
		return true;
}

function muestra(oculta,muestra){
	document.getElementById(oculta).style.display = "none";
	document.getElementById(muestra).style.display = "block";
return false;
}
var t;
function menu(id){ 
	t=setTimeout('animatedcollapse.show(\''+id+'\')',200);
}
function desc(id){ // muestra contenido oculto de restaurante
	t=setTimeout('animatedcollapse.toggle(\''+id+'\')',1);
}
function desco(id){ // muestra contenido oculto de ofertas
	t=setTimeout('animatedcollapse.show(\''+id+'\')',1);
}
function res(id){  // mas info de un tipo de habitacion
	if(document.getElementById(id).style.display=="block") var vista=1;
	animatedcollapse.toggle(id);
	t=setTimeout('segres(\''+id+'\','+vista+')',600);

}
function segres(id,vista){
	if(vista) document.getElementById(id).style.display = "none";
	else document.getElementById(id).style.display = "block";
}

function descout(id){
	t=setTimeout('fuera()',2000);
}
function fuera(){
	try{
	animatedcollapse.hide('desc1');
	animatedcollapse.hide('desc2');
	animatedcollapse.hide('desc3');
	animatedcollapse.hide('desc4');
	animatedcollapse.hide('desc5');
	animatedcollapse.hide('desc6');
	}
	catch(err){}
}
function menuout(id){
	clearTimeout(t);
}
function alarga_opinion(id){
	var d = document.getElementById(id);
	var anchd = parseInt(d.style.width);
	if(anchd>700){
		d.style.width = 355+ 'px'; 
	}else d.style.width = 770+ 'px';
	return false;
}
function restodia(fecha_x)
{
		var ini = new Date();
	ini.setFullYear(fecha_x.value.substr(6,4),parseInt(fecha_x.value.substr(3,2),10)-1,parseInt(fecha_x.value.substr(0,2),10)-1,0,0,0);
	var dia=ini.getDate();
	var mes=ini.getMonth()+1;
	var anio=ini.getFullYear();
	if (dia<10)
	   dia="0"+dia;
	if (mes<10)
	   mes="0"+mes;
	fecha_x.value=dia+"/"+mes+"/"+anio;	
}

function sumodia(fecha_x)
{
	var ini = new Date();
	ini.setFullYear(fecha_x.value.substr(6,4),parseInt(fecha_x.value.substr(3,2),10)-1,parseInt(fecha_x.value.substr(0,2),10)+1,0,0,0);
	var dia=ini.getDate();
	var mes=ini.getMonth()+1;
	var anio=ini.getFullYear();
	if (dia<10)
	   dia="0"+dia;
	if (mes<10)
	   mes="0"+mes;
	fecha_x.value=dia+"/"+mes+"/"+anio;	
}

//				#################################################################
//				############################ RESERVAS ###########################
//				#################################################################

var nnoches;
if(!personas)
	var personas=0;
var alojados=new Array;
var alojadosmin=new Array;

function cargapersonas(num){ personas=num; } 

function noches(){ // Muestra el numero de noches entre 2 fechas
	nnoches=0;
		var Fini=document.getElementById('fecha_ini').value;
		var Ffin=document.getElementById('fecha_fin').value;

		if(Fini && Ffin){

		var er = /(\d+)\/(\d+)\/(\d+)/;

		var aFini = Fini.replace(er,"$3");
		var mFini = Fini.replace(er,"$2")-1;
		var dFini = Fini.replace(er,"$1"); 

		var aFfin = Ffin.replace(er,"$3");
		var mFfin = Ffin.replace(er,"$2")-1;
		var dFfin = Ffin.replace(er,"$1");

		var oFini = new Date(aFini,mFini,dFini,0,0,0,0);
		var oFfin = new Date(aFfin,mFfin,dFfin,0,0,0,0);

		nnoches =Math.round((oFfin-oFini)/86400000); 
		var ese="s";
		if(nnoches==1) ese ="";
		if(idioma=='en'){
			var msjok= "Book "+nnoches+" night"+ ese;
			var msjno= "Check-out date is incorrect";
		}
		else{
			var msjok= "Reserva "+nnoches+" noche"+ ese;
			var msjno= "Revise fecha de salida";
		}
	
		if(nnoches>0)	document.getElementById('noches').innerHTML=msjok;
		   else {	document.getElementById('noches').innerHTML=msjno;
		   			document.getElementById('fecha_fin').value=""; 
		   }
		}// else if(Fini) document.getElementById('fecha_fin').value=;
		 return false;
}

function desplaza_entrada(tipo)
{
	f = document.getElementById('form1');
	if(tipo=='antes'){
		restodia(f.fecha_ini);
		restodia(f.fecha_fin);
	}
	if(tipo=='despues'){
		sumodia(f.fecha_ini);
		sumodia(f.fecha_fin);
	}
	noches();
	reserva1()
	return false;
}

function reserva1()
{
	noches();
	f = document.getElementById('form1');
	if(idioma=='en'){
		var msj1= "You must insert the check-in and check-out dates";
		var msj2= "Check-in date entered is before today.";
		var msj3= "Check-in date entered is before check-out date.";
	}
	else{
		var msj1= "Ha de introducir las fechas de entrada y salida.";
		var msj2= "La fecha de entrada introducida es anterior al d\xeda de hoy.";
		var msj3= "La fecha de salida introducida es anterior a la fecha de entrada.";
	}
	if(f.fecha_ini.value=='' || f.fecha_fin.value=='') alert(msj1);
	else {
		var hoy = new Date();
		var ini = new Date();
		ini.setFullYear(f.fecha_ini.value.substr(6,4),f.fecha_ini.value.substr(3,2)-1,f.fecha_ini.value.substr(0,2));
		var fin = new Date();
		fin.setFullYear(f.fecha_fin.value.substr(6,4),f.fecha_fin.value.substr(3,2)-1,f.fecha_fin.value.substr(0,2));
		if(ini<hoy) alert(msj2);
		else if(fin<ini) alert(msj3);
			else {
				// Cuadro mas preferencias
				var cadenamas="";
				var fuma=-1;
				try{
					if($("#fumador1:checked").length>0) fuma=1;
					else if($("#fumador0:checked").length>0) fuma=0;
					else if($("#fumador1:checked").length>0) fuma=-1;
					
					var promo;
					for(var i=1;i<30;i++){
						try{
						if(document.getElementById("promo["+i+"]").checked) promo=i;
						} catch(err){}
						}
					cadenamas="&fumador="+fuma+"&tipohab="+$("#tipohab").val()+"&promo="+promo;
				} catch(err){}
				//
				respuesta = document.getElementById('res');
				envia('ajax/reserva1.php',
				'&fecha_ini='+f.fecha_ini.value+
				'&fecha_fin='+f.fecha_fin.value+
				'&adultos='+f.adultos.value+
				'&ninos='+f.ninos.value+
				cadenamas);
				}
	}
}

function adicionales( hab, subid, pers, valor ){ // Cambio en el numero de habitaciones
	if(hab>0) {		
		document.getElementById("adicionales"+subid).style.display = "block";
		for (var i=1;i<=13;i++){try{  document.getElementById("habit["+subid+"]["+i+"]").style.display = "none"; } catch(err){}}
		for (var i=1;i<=hab;i++) {document.getElementById("habit["+subid+"]["+i+"]").style.display = "block";}
	}
		else document.getElementById("adicionales"+subid).style.display = "none";
	
	// Pongo a 0 los select superiores al numero de habitaciones seleccionadas
	var j=parseInt(hab,10)+1;
	while (j<=12){
		for (var i=0; i<document.getElementById("reservando").elements.length; i++) {
			objeto = document.getElementById("reservando").elements[i] ;
		    	 if( (objeto.id.lastIndexOf("habit["+subid+"]["+j+"]")>=0) && (objeto.lang!="g") )
		    		 document.getElementById(objeto.id).selectedIndex=0;
	
		} // for
	j++;} // while	
	
	alojados[subid]=pers.substr(pers.length-1,1)*hab;
	alojadosmin[subid]=pers.substr(0,1)*hab;
	// Veo si habia alguna supletoria
	for (i=1;i<=12;i++){
		try{ if( document.getElementById("habit["+subid+"]["+i+"][1]").selectedIndex>0 ) alojados[subid]++;} catch(err){}
		try{ if( document.getElementById("habit["+subid+"]["+i+"][3]").selectedIndex>0 ) alojados[subid]++;} catch(err){}
		try{ if( document.getElementById("habit["+subid+"]["+i+"][19]").selectedIndex>0 ) alojados[subid]++;} catch(err){}
	}
	aloja();
	
	var mensaje;
	try{if(f.promo.value) mensaje='&promo='+f.promo.value; } catch(err){}
	
    respuesta = document.getElementById('totaliza');
    respuesta.style.display = "block";
    envia('ajax/total_reserva.php','habit='+subid+'_'+hab+'_'+valor+mensaje);
    
}
function editaadi(subid, hab, servi, num, valor){ // Cambian un select de servicios

	// Si supletoria (1) o (19) o cuna (3) cambio los alojados
	if((servi==1) || (servi==3) || (servi==19)){

		if(num!=0) {
			var ensimple4=0;
			if((servi==1 || servi==19) && subid < 20 
				&& ( 
						$('#habit\\['+subid+'\\]\\['+hab+'\\]\\[1\\]').val()!=0 
						&& $('#habit\\['+subid+'\\]\\['+hab+'\\]\\[1\\]').length>0
					)
				&& $('#habit\\['+subid+'\\]\\['+hab+'\\]\\[19\\]').val()!=0 
			){
				ensimple4=1;
			}
			if(!ensimple4){
				alojados[subid] = (parseInt(alojados[subid],10) + 1);
				alojadosmin[subid] = (parseInt(alojadosmin[subid],10) + 1);
			}
			else {
				$('#habit\\['+subid+'\\]\\['+hab+'\\]\\['+servi+'\\]').val(0);
				alert("No es posible seleccionar juntas cama supletoria y cama supletoria ni\xf1o salvo en habitaciones superiores.");
			}
		}
		else{
			alojados[subid] = (parseInt(alojados[subid],10) -1);
			alojadosmin[subid] = (parseInt(alojadosmin[subid],10) -1);
		}
		aloja();
	}
	
	// Sistema de alerta
	var adi_id=document.getElementById('habit['+subid+']['+hab+']['+servi+']');
	if(adi_id.value>0 && adi_id.title!="") alert(adi_id.title);
	
	
	// Si supletoria (1) o (19)
	if((servi==1) || (servi==19)){	
		for (var i=0; i<document.getElementById("reservando").elements.length; i++) {
			objeto = document.getElementById("reservando").elements[i] ;
				// Si activo supletoria aumento en uno los campos pers/estancia
		    	 if( (objeto.id.lastIndexOf("habit["+subid+"]["+hab+"]")>=0) && (objeto.lang=="pe") ){
		    		
		    		if(num>0){ // Aumento supletoria
		    			objeto.length = objeto.length + 1; 
		    			var nuevo=objeto.length-1;
		    			objeto.options[nuevo].value = parseInt(objeto.options[nuevo-1].value,10) +1;
		    			objeto.options[nuevo].text = parseInt(objeto.options[nuevo-1].value,10) +1;
		    		} else {
		    			objeto.length = objeto.length - 1; 
		    			// Si se habia comprado mas servicios de los que ahora puede...
		    			if(indexanterior!=document.getElementById(objeto.id).selectedIndex){
		    				respuesta = document.getElementById('totaliza');
		    			    respuesta.style.display = "block";
		    			    //objeto.id = habit[subid_de_hab][#hab][subid_de_servicio]
		    			    var cadena = objeto.id.replace("habit[", "");
		    			    cadena = cadena.replace("][", "_");
		    			    cadena = cadena.replace("][", "_");
		    			    cadena = cadena.replace("]", "");
		    			    envia('ajax/total_reserva.php','servi='+cadena+'_0_0');
		    			}
		    		}
		    	 } // if pe
				// Si activo supletoria aumento en noches los campos pers/noche
		    	 if( (objeto.id.lastIndexOf("habit["+subid+"]["+hab+"]")>=0) && (objeto.lang=="pn") ){
		    		 
		    		 if(num>0){ // Aumento supletoria
			    		 for (var k=0;k<nnoches;k++){ 
				    		objeto.length = objeto.length + 1; 
				    		var nuevo=objeto.length-1; 
				    	 	objeto.options[nuevo].value = parseInt(objeto.options[nuevo-1].value,10) +1;
				    	 	objeto.options[nuevo].text = parseInt(objeto.options[nuevo-1].value,10) +1;
			    		 }
			    	} else {
			    		var indexanterior=document.getElementById(objeto.id).selectedIndex;
			    			objeto.length = objeto.length - nnoches; 
			    			// Si se habia comprado mas servicios de los que ahora puede...
			    			if(indexanterior!=document.getElementById(objeto.id).selectedIndex){
			    				respuesta = document.getElementById('totaliza');
			    			    respuesta.style.display = "block";
			    			    //objeto.id = habit[subid_de_hab][#hab][subid_de_servicio]
			    			    var cadena = objeto.id.replace("habit[", "");
			    			    cadena = cadena.replace("][", "_");
			    			    cadena = cadena.replace("][", "_");
			    			    cadena = cadena.replace("]", "");
			    			    envia('ajax/total_reserva.php','servi='+cadena+'_0_0');
			    			}
			    			
			    	}
		    	 } // if pn
		} // for
		
	} // fin if supletoria
	
	var mensaje;
	try{if(f.promo.value) mensaje='&promo='+f.promo.value; } catch(err){}
	
	respuesta = document.getElementById('totaliza');
    respuesta.style.display = "block";
    envia('ajax/total_reserva.php','servi='+subid+'_'+hab+'_'+servi+'_'+num+'_'+valor+mensaje);
}
function aloja(){ // Comprueba el numero de personas alojadas
	var suma=0;
	var sumamin=0;
	for (var i in alojados){ suma = suma + parseInt(alojados[i],10);	}
	for (var i in alojadosmin){ sumamin = sumamin + parseInt(alojadosmin[i],10);	}
	if(idioma=='en'){
		var msj1= "You selected too much rooms to accommodate people.\nCheck your choice before confirm booking.";
	}
	else{
		var msj1= "Ha seleccionado m\xe1s habitaciones que personas a alojar.\nCompruebe su selecci\xf3n antes de confirmar la reserva.";
	}
	if(sumamin>personas) alert(msj1);
}
function enviares(){ // Va al segundo paso de reserva (logueo o nuevo usuario)
	var suma=0;
	var sumamin=0;
	var mensaje="";
	for (var i in alojados){ suma = suma + parseInt(alojados[i],10);	}
	for (var i in alojadosmin){ sumamin = sumamin + parseInt(alojadosmin[i],10);	}
	if(idioma=='en'){
		var msj1= "You selected too much rooms to accommodate people.\nCheck your choice before confirm booking.";
		var msj2= "Fewer rooms than person to accommodate.\nCheck your choice before confirm booking.";
		var msj3= "You have not selected any room.\nCheck your choice before confirm booking.";
	}
	else{
		var msj1= "Ha seleccionado m\xe1s habitaciones que personas a alojar.\nCompruebe su selecci\xf3n antes de confirmar la reserva.";
		var msj2= "Ha seleccionado menos habitaciones que personas a alojar.\nCompruebe su selecci\xf3n antes de confirmar la reserva.";
		var msj3= "No ha seleccionado ninguna habitaci\xf3n.\nCompruebe su selecci\xf3n antes de confirmar la reserva.";
	}
	
	if(sumamin>personas) alert(msj1);
	if(suma<personas) alert(msj2);
	if(suma==0) alert(msj3);
	if(sumamin<=personas && suma>=personas){
	
	document.getElementById("habitaciones").style.display="none";
	
	var promo;
	for(var i=1;i<30;i++){
		try{
		if(document.getElementById("promo["+i+"]").checked) mensaje += "&promo="+i;
		} catch(err){}
		}
	
	// recorro todas las preferencias del usuario
		for (var i=0; i<document.getElementById("reservando").elements.length; i++) {
			objeto = document.getElementById("reservando").elements[i];
			var objId=objeto.id.split("hab");
			var subid = objId[1];
			var hab = parseInt(document.getElementById(objeto.id).selectedIndex,10);
							
			if( (subid>0) && (hab) ){ // para cada tipo de habitacion seleccionada
				mensaje += "&habid["+subid+"]="+hab;
				var j=1;
				while (j<=hab){ // para cada habitacion activa
					mensaje += "&serv["+subid+"]["+j+"]=";
					for (var k=0; k<document.getElementById("reservando").elements.length; k++) {
						subsel = document.getElementById("reservando").elements[k];
						if( (subsel.id.lastIndexOf("habit["+subid+"]["+j+"]")>=0) && (document.getElementById(subsel.id).selectedIndex>0)){
							//subsel.id = habit[subid_de_hab][#hab][subid_de_servicio]
							var subobjId=subsel.id.split("][");
							var subIds=subobjId[2].split("]");
							subIds=subIds[0]; // subId tiene el id del servicio
							var numS = parseInt(document.getElementById(subsel.id).selectedIndex,10); // cantidad de servicio
							mensaje += subIds+"."+numS+"_";
						}
					}
					mensaje=mensaje.substr(0, mensaje.length-1); // quito el ultimo "_"
					j++;

				} // fin while
	
			} // para cada tipo de habitacion
		} // for
		// mensaje tiene "&habid[(subid_hab)]=(#num)&serv[(subid_hab)][(foreach#num)]=(subid_serv).(#num_serv)_(subid_serv).(#num_serv)" para cada tipo de habitacion
		
		// Si es de oferta la recojo
		try{if(f.promo.value) mensaje+='&promo='+f.promo.value; } catch(err){}
		// Tomo linea de numero de clientes
		try{mensaje+='&linea='+$('#linea').text(); } catch(err){}
	
	document.getElementById('confirmar').style.display="none";
    respuesta = document.getElementById('datos');
    respuesta.style.display = "block";
    envia('ajax/reserva2.php',mensaje);
    document.getElementById('anular').style.display="block";
	} // if todo OK
}
function anulares(){ // Vuelve de registro2 a registro1 y elimina la reserva
	document.getElementById('anular').style.display="none";
	document.getElementById('confirmar').style.display="block";
	document.getElementById('habitaciones').style.display="block";
    respuesta = document.getElementById('datos');
	if(idioma=='en'){
		var msj1= "Make the appropriate changes and clic confirm booking again.";
	}
	else{
		var msj1= "Realice los cambios oportunos y vuelva a confirmar la reserva.";
	}
    alert(msj1);
    respuesta.style.display = "none";
    envia('ajax/reserva2.php','&anula=1');
}
function logueo(){
	var f=document.getElementById('log-in');
	if(idioma=='en'){
		var msj1= "Please, fill your login info.";
	}
	else{
		var msj1= "Ha de rellenar sus datos de acceso.";
	}
	if(f.usuario.value.length<3 || f.password.value.length<3) {
		alert(msj1);
		if(f.usuario.value.length<3) f.usuario.value="";
		if(f.password.value.length<3) f.password.value="";
	}
	else { 
		document.getElementById('divreg').style.display="block";
		respuesta = document.getElementById('divreg'); 
		envia('ajax/reserva3.php',
			'usuario='+f.usuario.value+
			'&password='+f.password.value
			);
	}
}
function nuevoreg(){
	document.getElementById('divreg').style.display="block";
	respuesta = document.getElementById('divreg');
	envia('ajax/reserva3.php','');
}
function validarTJ(numero_tarjeta) {
	 var cadena = numero_tarjeta.toString();
	 var longitud = cadena.length;
	 var cifra = null;
	 var cifra_cad=null;
	 var suma=0;
	 for (var i=0; i < longitud; i+=2){
	   cifra = parseInt(cadena.charAt(i))*2;
	   if (cifra > 9){ 
	     cifra_cad = cifra.toString();
	     cifra = parseInt(cifra_cad.charAt(0)) + 
	parseInt(cifra_cad.charAt(1));
	   }
	   suma+=cifra;
	 }
	 for (var i=1; i < longitud; i+=2){
	   suma += parseInt(cadena.charAt(i));
	 }
		
	 if ((suma % 10) == 0){ 
	  return 1;
	 } else {
	  return 0;
	 }
	}
function chequeares(){
	var f=document.getElementById('form3');
	var error="";
	if(idioma=='en'){
		var msj1= "Username must have at least 4 characters\n";
		var msj2= "Password must have at least 4 characters\n";
		var msj3= "Passwords entered do not match\n";
	}
	else{
		var msj1= "El nombre de usuario ha de tener al menos 4 caracteres\n";
		var msj2= "La contrase\xf1a ha de tener al menos 4 caracteres\n";
		var msj3= "Las contrase\xf1as introducidas no concuerdan\n";
	}
	if(f.usuario.value.length <4) error +=msj1;
	if(f.registrado.value==1){
		// Si es un usuario
		if(f.password.value.length && f.password.value.length <4) error +=msj2;
		if(f.password.value.length && f.password.value!=f.password2.value) error +=msj3;
	}
	else {
		// nuevo registro
		if(f.password.value.length <4) error +=msj2;
		if(f.password.value!=f.password2.value) error +=msj3;
	}
	if(idioma=='en'){
		var msj1= "You have not entered your name\n";
		var msj2= "You have not entered your surname\n";
		var msj3= "Did not specify documentation type\n";
		var msj4= "ID must follow the format 00000000L\n";
		var msj5= "You have not entered your country\n";
		var msj6= "You have not entered a valid email\n";
		var msj7= "You have not entered your phone number\n";
		var msj8= "Did not specify credit card type\n";
		var msj9= "Your credit card number is incorrect\n";
		var msj10= "Your credit card has expired\n";
	}
	else{
		var msj1= "No ha introducido su nombre\n";
		var msj2= "No ha introducido sus apellidos\n";
		var msj3= "No ha indicado tipo de documentaci\xf3n\n";
		var msj4= "Su documento de identidad ha de seguir el formato 00000000L\n";
		var msj5= "No ha introducido su pa\xeds\n";
		var msj6= "No ha introducido un email v\xe1lido\n";
		var msj7= "No ha introducido su tel\xe9fono\n";
		var msj8= "No ha indicado tipo de tarjeta de cr\xe9dito\n";
		var msj9= "Su tarjeta de cr\xe9dito es incorrecta\n";
		var msj10= "Su tarjeta de cr\xe9dito ha caducado\n";
	}
	// Pongo ceros...
	if(f.numero.value.length<16) f.numero.value='0'+f.numero.value;
	if(f.numero.value.length<16) f.numero.value='0'+f.numero.value;
	if(f.numero.value.length<16) f.numero.value='0'+f.numero.value;
	
	if(f.nombre.value.length<2) error +=msj1;
	if(f.apellidos.value.length<2) error +=msj2;
	if(f.doc.value<1) error +=msj3;
	if(f.doc.value==1 && (f.documento.value.length!=9 || !validarDni(f.documento.value) )) error +=msj4;
	if(f.pais.value.length<2) error +=msj5;
	if(!validarEmail(f.email.value)) error +=msj6;
	if(f.telefono.value.length<9) error +=msj7;
	if(f.tarjeta.value<0) error +=msj8;
	if(f.numero.value.substr(0,4)!="****" || f.registrado.value!=1){
		if(!validarTJ(f.numero.value) || f.numero.value.length<16) error +=msj9;
	}
	var hoy = new Date();
	if(
		(f.cadm.value<hoy.getMonth()+1 && f.cada.value==hoy.getFullYear()) ||
		( f.cada.value<hoy.getFullYear() )
		) error +=msj10;
	
	if(idioma=='en'){
		var msj1= "Did not specify the security code on the card\n";
		var msj2= "You must validate booking conditions\n";
		var msj3= "There have been errors while you proceeded to registration: \n\n";
		var msj4= "\nCorrect inaccurate information and try again."
	}
	else{
		var msj1= "No ha indicado el c\xf3digo de seguridad de la tarjeta que encontrar\xe1 en el reverso\n";
		var msj2= "Ha de validar las condiciones de la reserva\n";
		var msj3= "Han ocurrido errores mientras se proced\xeda al registro: \n\n";
		var msj4= "\nCorrija la informaci\xf3n incorrecta e int\xe9ntelo de nuevo.";
	}
	if(f.cvc.value.length<3) error +=msj1;
	if(!f.cond.checked) error +=msj2;
		if(error){
			alert(msj3+error+msj4);
			return false;
		}
		else {
			document.getElementById('completar').style.display="none";
		    document.getElementById('capa_cargando').style.display="block";
		    document.getElementById('capa_cargando2').style.display="block";
		    document.getElementById('mybody').style.overflow='hidden';
			respuesta = document.getElementById('reg4');
			envia('ajax/reserva4.php',
					'usuario='+f.usuario.value+
					'&password='+f.password.value+
					'&nombre='+parsea(f.nombre.value)+
					'&apellidos='+parsea(f.apellidos.value)+
					'&doc='+f.doc.value+
					'&documento='+f.documento.value+
					'&pais='+parsea(f.pais.value)+
					'&email='+f.email.value+
					'&telefono='+f.telefono.value+
					'&tarjeta='+f.tarjeta.value+
					'&numero='+f.numero.value+
					'&cadm='+f.cadm.value+
					'&cada='+f.cada.value+
					'&cvc='+f.cvc.value+
					'&registrado='+f.registrado.value+
					'&news='+f.news.checked+
					'&comentarios='+f.comentarios.value);
					
		return false; 
		}
}

			//########################################################################
			//############################ RESERVA OFERTAS ###########################
			//########################################################################

function noches_of(){ // Devuelve 
	var onoches=document.getElementById('onoches').value;
	var Fini=document.getElementById('fecha_ini').value;
	if(Fini){

	var er = /(\d+)\/(\d+)\/(\d+)/;

	var aFini = Fini.replace(er,"$3");
	var mFini = Fini.replace(er,"$2")-1;
	var dFini = Fini.replace(er,"$1"); 

	var oFini = new Date(aFini,mFini,dFini,1,0,0,0); 
	
	var milisecSumar= onoches*24*60*60*1000; 
	oFini.setTime(oFini.getTime()+milisecSumar);
	var dFfin=oFini.getDate(); if(dFfin<10) dFfin='0'+dFfin;
	var mFfin=oFini.getMonth()+1; if(mFfin<10) mFfin='0'+mFfin;
	var Ffin=dFfin+"/"+mFfin+"/"+oFini.getFullYear();
	
	var ese="s"; if(noches==1) ese="";

	document.getElementById('noches').innerHTML="Reserva "+onoches+" noche"+ ese;
	document.getElementById('Fecha_fin').value=Ffin;
	}
	 return false;
}

function reserva_of1()
{
	noches_of();
	f = document.getElementById('form1');
	if(idioma=='en'){
		var msj1= "You must insert the check-in date.";
		var msj2= "Check-in date entered is before today.";
	}
	else{
		var msj1= "Ha de introducir la fecha de entrada.";
		var msj2= "La fecha de entrada introducida es anterior al d\xeda de hoy.";
	}
	if(f.fecha_ini.value=='') alert(msj1);
	else {
		var hoy = new Date();
		var ini = new Date();
		ini.setFullYear(f.fecha_ini.value.substr(6,4),f.fecha_ini.value.substr(3,2)-1,f.fecha_ini.value.substr(0,2));
		if(ini<hoy) alert(msj2);
		else {
				// Cuadro mas preferencias
				var cadenamas="";
				var fuma=-1;
				var supli=0;
				try{
					if($("#fumador1:checked").length>0) fuma=1;
					else if($("#fumador0:checked").length>0) fuma=0;
					else if($("#fumador1:checked").length>0) fuma=-1;
					if(document.getElementById('supli1').checked) supli=1;
					
					cadenamas="&fumador="+fuma+"&tipohab="+$("#tipohab").val()+"&supli="+supli;
				} catch(err){}
				//
				respuesta = document.getElementById('res');
				envia('ajax/reserva_of1.php',
				'&fecha_ini='+f.fecha_ini.value+
				'&promo='+f.promo.value+
				'&adultos='+f.adultos.value+
				cadenamas);
				}
	}
}
function editaadi_of(subid, hab, servi, num, valor){ // Cambian un select de servicios
	// Sistema de alerta
	var adi_id=document.getElementById('habit['+subid+']['+hab+']['+servi+']');
	if(adi_id.value>0 && adi_id.title!="") alert(adi_id.title);
	
	var mensaje;
	try{if(f.promo.value) mensaje='&promo='+f.promo.value; } catch(err){}
	
	respuesta = document.getElementById('totaliza');
    respuesta.style.display = "block";
    envia('ajax/total_reserva.php','servi='+subid+'_'+hab+'_'+servi+'_'+num+'_'+valor+mensaje);
}
function enviares_of(){ // Va al segundo paso de reserva (logueo o nuevo usuario)
	var suma=0;
	var sumamin=0;
	var mensaje="";
	for (var i in alojados){ suma = suma + parseInt(alojados[i],10);	}
	for (var i in alojadosmin){ sumamin = sumamin + parseInt(alojadosmin[i],10);	}
	if(idioma=='en'){
		var msj1= "You selected too much rooms to accommodate people.\nCheck your choice before confirm booking.";
		var msj2= "Fewer rooms than person to accommodate.\nCheck your choice before confirm booking.";
		var msj3= "You have not selected any room.\nCheck your choice before confirm booking.";
	}
	else{
		var msj1= "Ha seleccionado m\xe1s habitaciones que personas a alojar.\nCompruebe su selecci\xf3n antes de confirmar la reserva.";
		var msj2= "Ha seleccionado menos habitaciones que personas a alojar.\nCompruebe su selecci\xf3n antes de confirmar la reserva.";
		var msj3= "No ha seleccionado ninguna habitaci\xf3n.\nCompruebe su selecci\xf3n antes de confirmar la reserva.";
	}
	if(sumamin>personas) alert(msj1);
	if(suma<personas) alert(msj2);
	if(suma==0) alert(msj3);
	if(sumamin<=personas && suma>=personas){
	
	document.getElementById("habitaciones").style.display="none";
	
	
	// recorro todas las preferencias del usuario
		for (var i=0; i<document.getElementById("reservando").elements.length; i++) {
			objeto = document.getElementById("reservando").elements[i];
			var objId=objeto.id.split("hab");
			var subid = objId[1];
			var hab = parseInt(document.getElementById(objeto.id).selectedIndex,10);
							
			if( (subid>0) && (hab) ){ // para cada tipo de habitacion seleccionada
				mensaje += "&habid["+subid+"]="+hab;
				var j=1;
				while (j<=hab){ // para cada habitacion activa
					mensaje += "&serv["+subid+"]["+j+"]=";
					for (var k=0; k<document.getElementById("reservando").elements.length; k++) {
						subsel = document.getElementById("reservando").elements[k];
						if( (subsel.id.lastIndexOf("habit["+subid+"]["+j+"]")>=0) && (document.getElementById(subsel.id).selectedIndex>0)){
							//subsel.id = habit[subid_de_hab][#hab][subid_de_servicio]
							var subobjId=subsel.id.split("][");
							var subIds=subobjId[2].split("]");
							subIds=subIds[0]; // subId tiene el id del servicio
							var numS = parseInt(document.getElementById(subsel.id).selectedIndex,10); // cantidad de servicio
							mensaje += subIds+"."+numS+"_";
						}
					}
					mensaje=mensaje.substr(0, mensaje.length-1); // quito el ultimo "_"
					j++;

				} // fin while
	
			} // para cada tipo de habitacion
		} // for
		// mensaje tiene "&habid[(subid_hab)]=(#num)&serv[(subid_hab)][(foreach#num)]=(subid_serv).(#num_serv)_(subid_serv).(#num_serv)" para cada tipo de habitacion
		
		// Si es de oferta la recojo
		mensaje+='&promo='+f.promo.value;
		mensaje+='&adultos='+document.getElementById('adultos1').value;
		var supli=0;
		try{
			if(document.getElementById('supli1').checked) supli=1;
		} catch(err){};
			mensaje+='&supli='+supli;
		
	
	document.getElementById('confirmar').style.display="none";
    respuesta = document.getElementById('datos');
    respuesta.style.display = "block";
    envia('ajax/reserva_of2.php',mensaje);
    document.getElementById('anular').style.display="block";
	} // if todo OK
}

