// ------------------------------------------------------------ //
// --------------    VBLE DE DESARROLLO/PRODUCCIÓN------------- //
// ------------------------------------------------------------ //
//	var MAIN_FOLDER= '/transhotel'; 	// Desarrollo
	var MAIN_FOLDER= '';				// Producción
// ------------------------------------------------------------ //
// ------------------------------------------------------------ //
// ------------------------------------------------------------ //





	// funciones básicas
	 
	function borrar() {	
	
		res = window.confirm("¿Estás seguro de querer borrar el registro?")
		
		if (res) {	 
			return true	
		} else {	 
			return false;
		}
	
	}

	function navegador_compatible()
	{
		var xmlHttp;
		
        try // Firefox, Opera 8.0+, Safari
        {xmlHttp=new XMLHttpRequest();}
		catch (e) // Internet Explorer
		{			
            try
            {xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}
            catch (e)
			{
				try
				{xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}
                catch (e)
				{
					alert("¡Su explorador no soporta AJAX!");
                    return false;
				}
			}
        }
		
		return xmlHttp;
	}

	function set_espera(num, div, cargando)
	{
		if (div=='')
		{
			div= 'espera';
			document.getElementById('cont').value = num;
		}
		//alert(div);
		document.getElementById(div).innerHTML = cargando+'...';	
	}

	function dec_espera(div)
	{
		if (div=='')
		{
			div= 'espera';
			document.getElementById('cont').value =document.getElementById('cont').value -1;
			if (document.getElementById('cont').value==0)
			{
				document.getElementById(div).innerHTML = '';
			}			
		}
	}

	// ------------------------------------------------------------------------------------------

	function actualizar_pais_ajax(cargando)
	{
		var xmlHttp1;
		var xmlHttp2;
		var xmlHttp3;
		
		var pais= document.getElementById('pais').value;
		set_espera(2,'', cargando);
		
		if (xmlHttp1=navegador_compatible())
		{			
			// Cambiamos las áreas
			actualizar_pais_sub_ajax(xmlHttp1, pais, 'area');
		}
		
		if (xmlHttp2=navegador_compatible())
		{
			// Cambiamos las provincias
			actualizar_pais_sub_ajax(xmlHttp2, pais, 'provincia');
		}		
/*
		if (xmlHttp3=navegador_compatible())
		{
			// Cambiamos las ciudades
			actualizar_pais_sub_ajax(xmlHttp3, pais, 'ciudad');
		}	*/
	}
	
	function actualizar_pais_sub_ajax(xmlHttp, pais, tipo)
	{
	    xmlHttp.onreadystatechange=function()
        {
		    if(xmlHttp.readyState==4)
            {				
        	    document.getElementById('d_'+tipo).innerHTML = xmlHttp.responseText;
				dec_espera('');
            }
        }
        xmlHttp.open('GET', MAIN_FOLDER+'/index.php?mod=ajax&f=pais_'+tipo+'&v1='+encodeURI(pais), true);
        xmlHttp.send(null);		
	}
	
	// ------------------------------------------------------------------------------------------	
	
	function actualizar_area_ajax(cargando)
	{
		var xmlHttp1;
		var xmlHttp2;

		var pais= document.getElementById('pais').value;
		var area= document.getElementById('area').value;
		set_espera(2,'', cargando);
			
		if (xmlHttp1=navegador_compatible())
		{
			// Cambiamos las provincias
			actualizar_area_sub_ajax(xmlHttp1, pais, area, 'provincia');
		}
		if (xmlHttp2=navegador_compatible())
		{
			// Cambiamos las ciudades
			actualizar_area_sub_ajax(xmlHttp2, pais, area, 'ciudad');			
		}
	}	

	function actualizar_area_sub_ajax(xmlHttp, pais, area, tipo)
	{
	    xmlHttp.onreadystatechange=function()
        {
		    if(xmlHttp.readyState==4)
            {
        	    document.getElementById('d_'+tipo).innerHTML = xmlHttp.responseText;
				dec_espera('');
            }
        }
        xmlHttp.open('GET', MAIN_FOLDER+'/index.php?mod=ajax&f=area_'+tipo+'&v1='+encodeURI(pais) +'&v2='+encodeURI(area), true);
        xmlHttp.send(null);		
	}

	// ------------------------------------------------------------------------------------------

	function actualizar_provincia_ajax(cargando)
	{
		var xmlHttp1;
		
		var pais= document.getElementById('pais').value;
		var area= document.getElementById('area').value;
		var provincia= document.getElementById('provincia').value;
		set_espera(1,'', cargando);
		
		if (xmlHttp1=navegador_compatible())
		{
			// Cambiamos las ciudades
			actualizar_provincia_sub_ajax(xmlHttp1, pais, area, provincia, 'ciudad');			
		}
	}	

	function actualizar_provincia_sub_ajax(xmlHttp, pais, area, provincia, tipo)
	{
	    xmlHttp.onreadystatechange=function()
        {
		    if(xmlHttp.readyState==4)
            {
        	    document.getElementById('d_'+tipo).innerHTML = xmlHttp.responseText;
				dec_espera('');
            }
        }
        xmlHttp.open('GET', MAIN_FOLDER+'/index.php?mod=ajax&f=provincia_'+tipo+'&v1='+encodeURI(pais) +'&v2='+encodeURI(area) +'&v3='+encodeURI(provincia), true);
        xmlHttp.send(null);		
	}	
	
	// ------------------------------------------------------------------------------------------
	
	function actualizar_tipo_servicio_ajax(cargando)
	{
		var xmlHttp;
		
		var al_tipo_servicio= document.getElementById('al_tipo_servicio').value;
		set_espera(1,'', cargando);
		
		if (xmlHttp=navegador_compatible())
		{
			// Cambiamos el servicio
			actualizar_tipo_servicio_sub_ajax(xmlHttp, al_tipo_servicio, 'al_servicio');			
		}
	}	

	function actualizar_tipo_servicio_sub_ajax(xmlHttp, al_tipo_servicio, tipo)
	{
	    xmlHttp.onreadystatechange=function()
        {
		    if(xmlHttp.readyState==4)
            {
        	    document.getElementById('d_'+tipo).innerHTML = xmlHttp.responseText;
				dec_espera('');
            }
        }
        xmlHttp.open('GET', MAIN_FOLDER+'/index.php?mod=ajax&f=al_tipo_servicio_'+tipo+'&v1='+encodeURI(al_tipo_servicio), true);
        xmlHttp.send(null);		
	}	
	
	// ------------------------------------------------------------------------------------------
	
	function contraer_habitacion(id, num, txt, cargando, regimen_opcional, bd)
	{
		//alert('>>>>   '+ id +'  ---  '+ num +'  --- '+ txt +' ---  '+ cargando +' ---  '+ regimen_opcional );
		//alert('<a href="javascript:;" onclick="desglosar_habitacion(\''+id+'\', \''+num+'\', \''+cargando+'\', \''+regimen_opcional+'\');">'+txt+'</a>');
/*		regimen_opcional= regimen_opcional.replace('Ñ','&Atilde;');
		regimen_opcional= regimen_opcional.replace('ñ','&atilde;');
		alert(regimen_opcional);*/
		//alert(bd);
		if (bd)
		{
			id_contraer= 'room_' + id;
			id_desglosar= id;
			//alert('estamos en base de datos');
		}
		else
		{
			id_contraer= 'room_' + id + '_' + num;
			id_desglosar= id ;//+ '_' + num;
			//alert('estamos con TRANSHOTEL');
		}
		
//desglosar_habitacion('form_hotel_1_1_3', '1', 'Cargando datos', '', 1);
//desglosar_habitacion('form_hotel_1_1_3', '1', 'Cargando datos', '', 1);
		//alert(id_contraer);
		document.getElementById(id_contraer).innerHTML ='<a class="desglose" href="javascript:;" onclick="desglosar_habitacion(\''+id_desglosar+'\', \''+num+'\', \''+cargando+'\', \''+regimen_opcional+'\', ' + bd + ');">'+txt+'</a>';
	}		
	

	function desglosar_habitacion(id, num, cargando, regimen_opcional, bd)
	{
		var xmlHttp;

		if (bd)
		{
			set_espera(1, 'room_'+id, cargando);
		}
		else
		{
			set_espera(1,'room_'+id+'_'+num, cargando);			
		}
		
		if (xmlHttp=navegador_compatible())
		{
			// Cambiamos el servicio			
			desglosar_habitacion_sub_ajax(xmlHttp, id, num, regimen_opcional, bd);			
		}
	}	

	function desglosar_habitacion_sub_ajax(xmlHttp, id, num, regimen_opcional, bd)
	{
	    xmlHttp.onreadystatechange=function()
        {
		    if(xmlHttp.readyState==4)
            {				
				if (bd)
				{
        	    	document.getElementById('room_'+id).innerHTML = xmlHttp.responseText;
					dec_espera('room_'+id);
				}
				else
				{
					document.getElementById('room_'+id+'_'+num).innerHTML = xmlHttp.responseText;	
					dec_espera('room_'+id+'_'+num);
				}				
            }
        }
        xmlHttp.open('GET', MAIN_FOLDER+'/index.php?mod=ajax&f=desglosar_habitacion&v1='+encodeURI(id) + '&v2='+encodeURI(num) + '&v3='+(regimen_opcional) + '&v4='+(bd), true);
        xmlHttp.send(null);		
	}		
	
	
	// ---------------------------------- funciones de ocultar datos de formulario ----------------------------------------
	
	function actualizarNumHabitaciones(num_habs)
	{		
		var n_hab= parseInt(document.getElementById('al_n_habs').value, 10);
		
		for (i=1;i<=n_hab;i++)
		{
			document.getElementById('fila_hab_'+i).style.visibility = "";			
		}

		for (i=(n_hab+1);i<=num_habs;i++)
		{
			document.getElementById('fila_hab_'+i).style.visibility = "hidden";
			//alert(document.getElementById('fila_hab_'+i).style.visibility);
		}					
		//alert(num_habs);
	}		
	
	function actualizarEdades(hab)
	{
		var n= parseInt(document.getElementById('al_n_ninyos_'+hab).value, 10);
		
		if (n==1)
		{
			document.getElementById('al_edad_ninyo_1_'+hab).style.visibility = "";
			document.getElementById('al_edad_ninyo_2_'+hab).style.visibility = "hidden";
			document.getElementById('al_regimen_ninyos_'+hab).style.visibility = "";
		}
		else if (n==2)
		{
			document.getElementById('al_edad_ninyo_1_'+hab).style.visibility = "";
			document.getElementById('al_edad_ninyo_2_'+hab).style.visibility = "";
			document.getElementById('al_regimen_ninyos_'+hab).style.visibility = "";
		}
		else
		{
			document.getElementById('al_edad_ninyo_1_'+hab).style.visibility = "hidden";
			document.getElementById('al_edad_ninyo_2_'+hab).style.visibility = "hidden";
			document.getElementById('al_regimen_ninyos_'+hab).style.visibility = "hidden";			
		}
	}		
	
	function onLoadForm(num_habs)
	{
		actualizarNumHabitaciones(num_habs);
		for (i=1;i<=num_habs;i++)
		{
			actualizarEdades(i);
		}		
	}
	
	function identificar_pestanya(v)
	{
		document.getElementById('buscar_por').value=v;
	}
	
	function inicializar_pestanyas()
	{
		//var index= parseInt(document.getElementById('buscar_por').value, 10);
		//$('#tabs').tabs('select', index);
	}
	
	function actualizar_totales_reservas(separador, moneda)
	{
		for (i=0;i<document.forms.length;i++)
		{
			if (document.forms[i].id.indexOf('form_hotel_')!=-1)
			{
				actualizar_total_reserva(document.forms[i].id, separador, moneda);
			}
		}
	}
	
	function deshabilitar_submit(form)
	{
		form.reservar.disabled= true;
	}
	
	function habilitar_submit(form)
	{
		form.reservar.disabled= false;
	}
	
	function actualizar_total_reserva(form, separador, moneda)
	{
		var total= 0;
		var radio;
		
		form= document.getElementById(form);
		
		for (j=0;j<form.elements.length;j++)
		{
			if (form.elements[j].type=='radio')	
			{
				if (form.elements[j].checked)
				{
					//alert(form.elements[j].value);
					radio= form.elements[j].value.split(separador);
					total= total + parseFloat(radio[2].replace(',','.'));
				}
			}
		}				
		//alert(form.total_reserva.value);
		form.total_reserva.value= formatoIdeal(total, moneda);
		habilitar_submit(form);
	}
	
	function formatoIdeal(n, moneda)
	{
		n= roundVal(n, 2);
		n= String(n.toFixed(2));
		return n/*.replace('.',',')*/ + ' ' + moneda;
	}	
	
	function roundVal(val, dec)
	{	
		var result = Math.round(val*Math.pow(10,dec))/Math.pow(10,dec);
		return result;
	}
	
	function valida_form_view(form, debe_rellenar, pais, area, provincia, ciudad, fecha_in, fecha_out, fechas_coherentes)
	{
		// pais
		// area o provincia y pais
		// fecha_, fecha_out y que sea mayor
		var str_alert= '';

		in_pais=document.getElementById('pais');
		if (in_pais.value=='-' || in_pais.value.length==0)
		{
		   str_alert= str_alert+ '-'+ pais+ '.\n';
		   in_pais.focus();
		} 		
		
		//>>> esto tb va a ser imporante, no poner el focus si ya lo hemos puesto antes.		
		in_buscar_por=document.getElementById('buscar_por');
		if (in_buscar_por.value!=0)
		{
			in_area=document.getElementById('area');
			if (in_area.value=='-' || in_area.value.length==0)
			{
				str_alert= str_alert+ '-'+ area+ '.\n';
				in_pais.focus();
				if (str_alert.length==0)
				{
					in_area.focus();
				}		   
			} 			
		}
		else
		{
			in_provincia=document.getElementById('provincia');			
			if (in_provincia.value=='-' || in_provincia.value.length==0)
			{
				str_alert= str_alert+ '-'+ provincia+ '.\n';
				in_provincia.focus();
				if (str_alert.length==0)
				{
					in_provincia.focus();
				}		   
			} 	
			
			in_ciudad=document.getElementById('ciudad');
			if (in_ciudad.value=='-' || in_ciudad.value.length==0)
			{
				str_alert= str_alert+ '-'+ ciudad+ '.\n';
				in_ciudad.focus();
				if (str_alert.length==0)
				{
					in_ciudad.focus();
				}		   
			} 			
		}
		
		// Ahora vamos a por las fechas.
		var inDate=new Date();
		var outDate=new Date();		
		var hoyDate=new Date();
		
		in_fecha_in=document.getElementById('fecha_in');
		if (in_fecha_in.value.length==0)
		{
		   	str_alert= str_alert+ '-'+ fecha_in+ '.\n';
			if (str_alert.length==0)
			{
				in_fecha_in.focus();
			}		
		} 			
		else
		{				
			inDate.setFullYear(in_fecha_in.value.substr(0,4),(parseInt(in_fecha_in.value.substr(5,2), 10)-1), in_fecha_in.value.substr(8,2));				
			hoyDate.setDate(hoyDate.getDate());
//			alert(inDate + ' --' + hoyDate + '------------ ' + inDate.getDate());
			if (inDate<hoyDate)
			{
				str_alert= str_alert+ '-'+ fecha_in+ '.\n';
				in_fecha_in.focus();			
			}
		}		
		
		in_fecha_out=document.getElementById('fecha_out');
		if (in_fecha_out.value.length==0)
		{
			str_alert= str_alert+ '-'+ fecha_out+ '.\n';
			if (str_alert.length==0)
			{
				in_fecha_out.focus();
			}		   		   		   
		} 				
		
		if (str_alert.length==0)
		{
			outDate.setFullYear(in_fecha_out.value.substr(0,4),(parseInt(in_fecha_out.value.substr(5,2), 10)-1), in_fecha_out.value.substr(8,2));	

			if (days_between(inDate, outDate)>15)
			{
				str_alert= '-'+ fechas_coherentes+ '.\n';
				in_fecha_out.focus();
			}			
		}			
		// hay q ver qué pinta aki el tema del input hidden pestanya area ese..
		
		if (str_alert.length>0)
		{
			str_alert= debe_rellenar + ':\n\n' + str_alert;
			alert(str_alert);
			return 0;
		}
		else
		{
			document.getElementById(form).submit();
			//alert('enviaría');
		}
	}
	
	function days_between(date1, date2) {
	 
		// The number of milliseconds in one day
		var ONE_DAY = 1000 * 60 * 60 * 24
	 
		// Convert both dates to milliseconds
		var date1_ms = date1.getTime()
		var date2_ms = date2.getTime()
	 
		// Calculate the difference in milliseconds
		var difference_ms = Math.abs(date1_ms - date2_ms)
		
		// Convert back to days and return
		return Math.round(difference_ms/ONE_DAY)
	 
	}
	
	
	function isEmailAddress(theElement)
	{
		var s = theElement.value;
		var filter=/^[A-Za-z][A-Za-z0-9_.]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
		if (s.length == 0 ) 
			return false;
		if (filter.test(s))
			return true;
		else
			return false;
	}
	
	function isNif(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);
	  return (letra==let);	
	}
		
	function valida_confirm_view(form, debe_rellenar, nombre, apellidos, email, tfno, dni, acepto)
	{
		var str_alert= '';

		in_acepto=document.getElementById('acepto');
		if (!in_acepto.checked)
		{
		   str_alert= str_alert+ '-'+ acepto + '.\n';
		   in_acepto.focus();
		} 		

		in_nombre=document.getElementById('nombre');
		if (in_nombre.value.length==0)
		{
		   str_alert= str_alert+ '-'+ nombre+ '.\n';
		   in_nombre.focus();
		} 		
		
		in_apellidos=document.getElementById('apellidos');
		if (in_apellidos.value.length==0)
		{
			str_alert= str_alert+ '-'+ apellidos+ '.\n';
			if (str_alert.length==0)
			{
				in_apellidos.focus();
			}			   		   	
		} 			
				
		in_email=document.getElementById('email');
		if (!isEmailAddress(in_email))
		{
			str_alert= str_alert+ '-'+ email+ '.\n';
			if (str_alert.length==0)
			{
				in_email.focus();
			}			   		   	
		} 		
		
		in_tfno=document.getElementById('telefono');
		if (in_tfno.value.length==0)
		{
			str_alert= str_alert+ '-'+ tfno+ '.\n';
			if (str_alert.length==0)
			{
				in_tfno.focus();
			}			   		   	
		} 			

		in_dni=document.getElementById('dni');
		var aux_dni= in_dni.value.toUpperCase();
		aux_dni= aux_dni.replace('-','');
		aux_dni= aux_dni.replace('/','');
		aux_dni= aux_dni.replace(' ','');

		if (aux_dni.length<=8 || !isNif(aux_dni))
		{
			str_alert= str_alert+ '-'+ dni+ '.\n';
			if (str_alert.length==0)
			{
				in_dni.focus();
			}			   		   	
		} 		
		else
		{
			in_dni.value= aux_dni;
		}
				
		if (str_alert.length>0)
		{
			str_alert= debe_rellenar + ':\n\n' + str_alert;
			alert(str_alert);
			return 0;
		}
		else
		{
			document.getElementById(form).submit();
			//alert('enviaría');
		}
	}	


	function actualizar_precio_habitacion_por_regimen(habitacion, form, num, op, separador, moneda, cargando, txt, bd)
	{
		//alert('   '+habitacion+'   '+form+'   '+num+'   '+separador+'   '+moneda+' (('+ txt + '))   --'+ cargando)
//		alert(bd);
		var xmlHttp1;
//		alert('board_'+form+'_'+num+'_'+habitacion);
		var regimen= document.getElementById('board_'+form+'_'+num+'_'+op+'_'+habitacion).value;
		if (bd=='1')
		{
			var datos= regimen.split(':');	
			regimen= datos[0];
			precio_bd= datos[1];
			id_hab= form + '_' + num + '_' + op;
			//alert(id_hab);
		}
		else
		{
			id_hab= habitacion;
			precio_bd= 0;
		}
		
		//regimen.htmlEntities();
		//alert(regimen);
		contraer_habitacion(id_hab, num, txt, cargando, regimen, bd);
//		alert(document.getElementById(form).id);
		if (xmlHttp1=navegador_compatible())
		{
			// Cambiamos las ciudades
			deshabilitar_submit(document.getElementById(form));
			actualiza_precio_habitacion_por_regimen_sub_ajax(xmlHttp1, habitacion, form, num, op, regimen, separador, moneda, bd, precio_bd);			
		}		
	}

	function actualiza_precio_habitacion_por_regimen_sub_ajax(xmlHttp, habitacion, form, num, op, regimen, separador, moneda, bd, precio_bd)
	{
	    xmlHttp.onreadystatechange=function()
        {
		    if(xmlHttp.readyState==4)
            {
        	    document.getElementById('td_check_'+form+'_'+num+'_'+op).innerHTML = xmlHttp.responseText;
				actualizar_total_reserva(form, separador, moneda);
            }
        }

		var check_value= document.getElementById('check_'+form+'_'+num+'_'+op).checked;
		//alert('check_'+form+'_'+num+'_'+op+'= '+check_value);
		// EL REGIMEN LO ENVIAMOS SIN CODIFICAR, PARA QUE VAYA LA Ñ, EN CASO DE QUE LO TENGA.
        xmlHttp.open('GET', MAIN_FOLDER+'/index.php?mod=ajax&f=precio_por_regimen&v1='+encodeURI(habitacion) +'&v2='+ regimen +'&v3='+encodeURI(form) +'&v4='+encodeURI(num) +'&v5='+encodeURI(op) +'&v6='+encodeURI(check_value) +'&v7='+ bd +'&v8='+encodeURI(precio_bd), true);
        xmlHttp.send(null);		
	}	
	
	function cambiar_idioma_select()
	{
		var idioma= document.getElementById('idioma').value;
		var xmlHttp1;
		if (xmlHttp1=navegador_compatible())
		{
			cambiar_idioma_sub_ajax(xmlHttp1, idioma);			
		}			
	}
	
	function cambiar_idioma(ind)
	{
		var xmlHttp1;
		if (xmlHttp1=navegador_compatible())
		{
			cambiar_idioma_sub_ajax(xmlHttp1, ind);			
		}			
	}	
	
	function cambiar_idioma_sub_ajax(xmlHttp, ind)
	{
	    xmlHttp.onreadystatechange=function()
        {
		    if(xmlHttp.readyState==4)
            {
				//alert(xmlHttp.responseText);
        	    location.reload();
            }
        }
		//alert('check_'+form+'_'+num+'_'+op+'= '+check_value);
        xmlHttp.open('GET', MAIN_FOLDER+'/index.php?mod=ajax&f=cambiar_idioma&v1='+encodeURI(ind) , true);
        xmlHttp.send(null);			
	}	



	function repartir_localizacion(loc, loc_txt)
	{
		var loc_a= loc.split(':');
		
		document.getElementById('pais').value= loc_a[2];
		document.getElementById('provincia').value= loc_a[1];
		document.getElementById('ciudad').value= loc_a[0];
		
		document.getElementById('localizacion_txt').value= loc_txt;
		document.getElementById('localizacion_txt_div').innerHTML= loc_txt;
		
		//alert(document.getElementById('pais').value + ':' + document.getElementById('provincia').value + ':' + document.getElementById('ciudad').value);
		//alert(document.getElementById('localizacion_txt').value);
	}
	
	function validar(e) 
	{		
	  tecla = (document.all) ? e.keyCode : e.which;
	  return tecla!=13;
	}  	
	