var win = null;

function GetVar(){
  var resul = document.getElementById(variable).value;
  return result;
}

function Abririnfos(ubicacion,nombre,w,h){
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	opciones ='height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars=auto,menubar=no,status=no,location=no,toolbar=no,resizable=yes';
	win = window.open(ubicacion,nombre,opciones);
	win.window.focus();
}

function Abririnfoscroll(ubicacion,nombre,w,h){
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	opciones ='height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars=yes,menubar=no,status=no,location=no,toolbar=no,resizable=no';
	win = window.open(ubicacion,nombre,opciones);
	win.window.focus();
}

function Abrir(ubicacion,nombre,w,h){
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	opciones ='height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars=yes,status=yes,MenuBar=yes,ToolBar=no,resizable';
	win = window.open(ubicacion,nombre,opciones);
	win.window.focus();
}

function AbrirSR(ubicacion,nombre,w,h){
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	opciones ='height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars=yes,status=no,MenuBar=no,ToolBar=no,resizable=no';
	win = window.open(ubicacion,nombre,opciones);
	win.window.focus();
}

function setAirport(pAirId, pAirName, pOrgDest) {
	if (pOrgDest=='autorelleno2') {
		$('aero_destino').value = pAirId;
		descuento();
		document.getElementById(pOrgDest).value = pAirId;
		document.getElementById(pOrgDest).value = pAirName;
	}
	else {
		$('aero_origen').value = pAirId;
		descuento();
		document.getElementById(pOrgDest).value = pAirId;
		document.getElementById(pOrgDest).value = pAirName;
	}
}

function selectAirport(pOrgDest){
	for (var i = 0; i < document.forms[0].elements.length; i++) {
		if (document.forms[0].elements[i].id == pOrgDest) {
			document.forms[0].elements[i].focus();
			break;
		}
	}
	if (pOrgDest=='autorelleno2') {
		Abrir('vuelos.aeropuertos.php?cn='+pOrgDest,'Aeropuertos',690,480);
	}
	else{
		Abrir('vuelos.aeropuertos.php?cn='+pOrgDest,'Aeropuertos',690,480);
	}
}

function descuento() {
	if  (($('aero_destino').value != '') && ($('aero_origen').value != '')) {
		var pars= 'origen='+ $('aero_origen').value + '&destino=' + $('aero_destino').value;
		var aj = new Ajax.Updater('descuentos','vuelos.descuento.php',{method:'get',parameters:pars});
	}
}

function descuento_marcado() {
	if  (($('aero_destino').value != '') && ($('aero_origen').value != '')) {
		var pars= 'origen='+ $('aero_origen').value + '&destino=' + $('aero_destino').value;
		var aj = new Ajax.Updater('descuentos','vuelos.descuento.php?marcado=1',{method:'get',parameters:pars});
	}
}

var origen='';
var destino='';

function mostrar_resultado(res)
{
	if (res.responseText == '1') { // siginifica que el origen y el destino estan OK
		$('boton').value=1;
		$('aero_destino').value=destino;
		$('aero_origen').value=origen;
		document.formBusc.submit() ;
	}else {
		if (res.responseText == '2') { //error en el origen
			try { document.formBusc.autorelleno.focus(); }
			catch(e) {}
			alert('El origen es ambiguo');
		}
		if (res.responseText == '3') { //error en ambos
			try { document.formBusc.autorelleno.focus(); }
			catch(e) {}
			alert('El origen y el destino son ambiguos');
		}
		if (res.responseText == '0') { //error en destino
			try { document.formBusc.autorelleno2.focus(); }
			catch(e) {}
			alert('El destino es ambiguo');
		}
	}
}

function validarcampo(id){  //esta funcion se carga cada vez que se llama al evento OnChange del destino o del origen. Re
	if (id=='1') {
		if($('aero_origen').value!='') var pars='id='+$('aero_origen').value;
		else var pars= 'id=' + $('autorelleno').value;

		var aj = new Ajax.Request('vuelos.validar_campos.php',
		{
		method:'get',
		parameters:pars,
		onSuccess:function (res){
			if (res.responseText!=''){
				var temp = new Array();
				temp = res.responseText.split('*');
				$('autorelleno').value=temp[0];
				$('aero_origen').value=temp[1];
			}
			else {
				$('autorelleno').value='no disponible';
			}
			descuento();
		}
		});
	}
	else{
		if($('aero_destino').value!='') var pars='id='+$('aero_destino').value;
		else var pars= 'id=' + $('autorelleno2').value;
		var temporal=$('autorelleno2').value;
		var aj = new Ajax.Request('vuelos.validar_campos.php',
		{
		method:'get',
		parameters:pars,
		onSuccess:	function (res){
			if (res.responseText!='') {
				var temp = new Array();
				temp = res.responseText.split('*');
				$('autorelleno2').value=temp[0];
				$('aero_destino').value=temp[1];
			}else {
				$('autorelleno2').value='no disponible';
			}
			descuento();
		}
		});
	}
	validar_fecha_de_salida($('dc1').value);
}


function enviarXML() {
	var descuento=0;
	try { descuento=document.getElementById('descuento_check').value; }
	catch(e) {}
	var pars= 'idavuelta=' + $('viaje').value + '&origen=' + $('aero_origen').value + '&destino=' + $('aero_destino').value + '&dc1=' + $('dc1').value +'&dc2=' + $('dc2').value +
	'&adultos=' + $('num_adultos').value +'&ninios=' + $('num_ninios').value + '&bebes=' + $('num_bebes').value + '&descuento='+ descuento + '&clase=' + $('clase').value+ '&f_origen=' + $('f_origen').value;
	var aj = new Ajax.Request('vuelos.enviarxml.php',{method:'get',parameters:pars,onComplete:controlXML});
}

function enviarXML_desde_MP() {  //envio de XML desde Motor Principal
	var descuento=0;
	try { descuento=$('descuento').value; }
	catch(e) {}
	var pars= 'idavuelta=' + $('viaje').value + '&origen=' + $('origen').value + '&destino=' + $('destino').value + '&dc1=' + $('dc1').value +'&dc2=' + $('dc2').value +
	'&adultos=' + $('adultos').value +'&ninios=' + $('ninios').value + '&bebes=' + $('bebes').value + '&descuento='+ descuento + '&clase=' + $('clase').value+ '&f_origen=' + $('f_origen').value;
	var aj = new Ajax.Request('vuelos.enviarxml.php',{method:'get',parameters:pars,onComplete:controlXML_MP});
}


function cambiar_descuento(valor) {
	if ($('descuento_check').value=='0')  {
		$('descuento_check').value=valor;
	}
	else {
		$('descuento_check').value='0';
	}
}

function validarfiltro() {
	var apretado = 0;
	for (i=0;i<document.formG.elements.length;i++) {
		if(document.formG.elements[i].type == "checkbox") {
			if (document.formG.elements[i].value!='vuelo_directo') {
				if (document.formG.elements[i].checked==1) apretado=apretado+1;
			}
		}
	}
	if (apretado==0) {
		alert ('No hay ninguna compania seleccionada !');
		return false;
	}
	aplicarfiltro()
}

function aplicarfiltro() {
	try{
		/*document.getElementById('img_filtrando').src='images/esperando.gif';*/
		document.getElementById('container').style.display='none';
		document.getElementById('filtrando').style.display='';
	}
	catch(e){}
	var companias='';
	for (i=0;i<document.formG.elements.length;i++) {
		if(document.formG.elements[i].type == "checkbox") {
			if (document.formG.elements[i].checked==1) {
				companias= companias + '&'+ document.formG.elements[i].value + '=' + document.formG.elements[i].value;
			}
		}
	}
	var pars = 'horario_ida=' + $('horario_ida').value + '&horario_vuelta=' + $('horario_vuelta').value + '&tipo=' + $('tipo').value + companias;
	var aj = new Ajax.Request('vuelos.aplicarfiltro.php',{method:'post',parameters:pars,onComplete:mostrar_vuelos_filtrados});
}

function controlXML(res) {
	if (res.responseText=='ERROR') {  //hay que controlar el error
		$('boton').value=0;
		$('captcha_codigo').value='';
		alert ('ERROR');
		Element.hide('loading');
		Element.show('container');
	}
	else {
		mostrar_vuelos();
	}
}

function controlXML_MP(res) {  //funcion que
	if (res.responseText=='ERROR') {  //hay que controlar el error
		alert ('ERROR');
		window.location.href="vuelos.motor.iframe.html";
	}
	else {
		mostrar_vuelos();
	}
}

function mostrar_vuelos_filtrados() {
	window.location='vuelos.resultados.php';
}

function mostrar_vuelos() {
	window.location='vuelos.resultados.php';
}

function mostrar_vuelos_sobreescribiendo_sesion(id_sesion_anterior) {
	var pars= 'foo=bar&id_sesion_sob=' + id_sesion_anterior;
	var aj = new Ajax.Request('vuelos.resultados.php',
	{
		method: 'get',
		parameters:pars,
		onSuccess: function (res) {
			Element.remove('loading');
			$('container').replace (res.responseText);
			Element.show('container');
		}
	});
}

function validar() {
	if (document.formBusc.autorelleno.value=="") {
		alert('Ingrese o elija el aeropuerto de origen.');
		document.formBusc.autorelleno.focus();
		return false;
	}
	if (document.formBusc.autorelleno2.value=="") {
		alert('Ingrese o elija el aeropuerto de destino.');
		document.formBusc.autorelleno2.focus();
		return false;
	}
	if (document.formBusc.autorelleno.value==document.formBusc.autorelleno2.value){
		alert('Los aeropuertos de origen y destino no pueden ser los mismos.');
		return false;
	}
	if (document.formBusc.dc1.value=="") {
		alert('Elija la fecha de Salida.');
		document.formBusc.dc1.focus();
		return false;
	}
	if (document.formBusc.dc2.value=="" && $('viaje').value==1) {
		alert('Elija la fecha de Regreso o seleccione Solo Ida.');
		document.formBusc.dc2.focus();
		return false;
	}
	if ($F('aero_origen')=="" || $F('aero_destino')=="" ) { //significa que escribio algo pero no uso el autocompletar. Entonces vamos a buscar si estan correctos los destinos.
		if ($F('aero_origen')!="") {//significa que el origen esta bien
			var id=$F('aero_origen');
		}
		else{
			var id=$F('autorelleno');
		}
		if ($F('aero_destino')!="") {//significa que el destino esta bien
			var id2=$F('aero_destino');
		}
		else{
			var id2=$F('autorelleno2');
		}
		origen=id;
		destino=id2;
		var pars= 'id=' + id +'&id2=' + id2;
		var aj = new Ajax.Request('vuelos.validar_destinos.php',{method:'get',parameters:pars,onComplete:mostrar_resultado});
		return false;
	}

	var descuento='';
	try { (descuento=$('descuento_check').checked); }
	catch(e) {}
	if((descuento!='')&&(descuento!=0)){
		try { $('txtdescuento').value='Los precios de los vuelos que esta buscando INERZIAnet llevan incluído el DESCUENTO de RESIDENTE'; }
		catch(e) {}
	}
	$('l_ida').value=$('autorelleno').value;
	$('l_vuelta').value=$('autorelleno2').value;
	$('l_ida_fecha').value=$('dc1').value;
	if($('clase').value=='B') $('l_clase').value='Business';
	else if($('clase').value=='F') $('l_clase').value='Primera';
	else $('l_clase').value='Turista';
	if ($('viaje').value==1) $('l_vuelta_fecha').value=$('dc2').value;
	if(document.getElementById('idavuelta_no').checked==true){
		Element.hide('lbl_regreso');
		$('l_vuelta_fecha').value='';
		$('dc2').value='';
	}
	$('l_adultos').value=$('num_adultos').value;
	if(!($('l_adultos').value>=1)){
		Element.hide('lbl_adultos');
		Element.hide('l_adultos');
	}
	$('l_ninios').value=$('num_ninios').value;
	if(!($('l_ninios').value>=1)){
		Element.hide('lbl_ninios');
		Element.hide('l_ninios');
	}
	$('l_bebes').value=$('num_bebes').value;
	if(!($('l_bebes').value>=1)){
		Element.hide('lbl_bebes');
		Element.hide('l_bebes');
	}
	$('boton').value=1;
	controlcaptcha('1');
	return false;
}

function validar_motor_principal() {
	if (document.formBusc.autorelleno.value=="") {
		alert('Ingrese o elija el aeropuerto de origen.');
		document.formBusc.autorelleno.focus();
		return false;
	}
	if (document.formBusc.autorelleno2.value=="") {
		alert('Ingrese o elija el aeropuerto de destino.');
		document.formBusc.autorelleno2.focus();
		return false;
	}
	if (document.formBusc.autorelleno.value==document.formBusc.autorelleno2.value){
		alert('Los aeropuertos de origen y destino no pueden ser los mismos.');
		return false;
	}
	if (document.formBusc.dc1.value=="") {
		alert('Elija la fecha de Salida.');
		document.formBusc.dc1.focus();
		return false;
	}
	if (document.formBusc.dc2.value=="" && $('viaje').value==1) {
		alert('Elija la fecha de Regreso o seleccione Solo Ida.');
		document.formBusc.dc2.focus();
		return false;
	}

	if ($F('aero_origen')=="" || $F('aero_destino')=="" ) { //significa que escribio algo pero no uso el autocompletar. Entonces vamos a buscar si estan correctos los destinos.
		if ($F('aero_origen')!="") {//significa que el origen esta bien
			var id=$F('aero_origen');
		}
		else{
			var id=$F('autorelleno');
		}
		if ($F('aero_destino')!="") {//significa que el destino esta bien
			var id2=$F('aero_destino');
		}else{
			var id2=$F('autorelleno2');
		}
		origen=id;
		destino=id2;
		var pars= 'id=' + id +'&id2=' + id2;
		var aj = new Ajax.Request('vuelos.validar_destinos.php',{method:'get',parameters:pars,onComplete:mostrar_resultado});

		return false;
	}
	if ($('boton').value!=1) {
		controlcaptcha('2');
	}
	return false;
}

function controlcaptcha(id) {
	if(($('captcha_codigo').value)==''){
		alert('Debe teclear el código INERZIAnet en la casilla vacía.');
	}
	else{
		if(id == '1'){
			if((hex_md5(document.getElementById('captcha_codigo').value))!=document.getElementById('c_uid').value) controlCaptcha('0');
			else controlCaptcha('1');
		}
		else{
			if((hex_md5(document.getElementById('captcha_codigo').value))!=document.getElementById('c_uid').value) controlCaptcha_motor_principal('0');
			else controlCaptcha_motor_principal('1');
		}
	}
}

function controlCaptcha(responseText) {
	if(responseText=='1'){
		/*try { document.getElementById('busqueda2').src='./iconosinerzianet/esperando.gif'; }		catch(e){}*/
		Element.hide('container');
		Element.show('loading');
		enviarXML();
	}else{
		$('boton').value=0;
		alert ('Puede que el Código INERZIAnet no estes tecleandolo correctamente o no sea válido porque ha caducado el mismo. Haz click en el botón y intentalo de nuevo.');
		try { document.getElementById('captcha_codigo').value=''; }
		catch(e){}
		return false;
	}
}

function controlCaptcha_motor_principal(responseText) {
	if  (responseText=='1') {
		document.formBusc.submit();
	}
	else {
		$('boton').value=0;
		alert ('Puede que el Código INERZIAnet no estes tecleandolo correctamente o no sea válido porque ha caducado el mismo. Haz click en el botón y intentalo de nuevo.');
		try { document.getElementById('captcha_codigo').value=''; }
		catch(e){}
		return false;
	}
}

function cargareserva(){
	/*try{ document.getElementById('img_reservando2').src='images/esperando.gif'; }
	catch(e){}*/
	try{ Element.hide('container'); }
	catch(e){}
	try{ Element.show('reservando2'); }
	catch(e){}
}

function descargareserva(){
	try{ document.getElementById('img_reservando2').src='images/esperando.jpg'; }
	catch(e){}
	try{ Element.show('container'); }
	catch(e){}
	try{ Element.hide('reservando2'); }
	catch(e){}
}

function validaEnvio(){
	cargareserva();
	if(document.getElementById('faltan_maletas_o').value=='Y') {
		descargareserva();
		alert('Debe indicar la cantidad de maletas para su vuelo de ida para poder proceder.');
		return false;
	}
	if(document.getElementById('faltan_maletas_i').value=='Y') {
		descargareserva();
		alert('Debe indicar la cantidad de maletas para su vuelo de vuelta para poder proceder.');
		return false;
	}
	if(!document.getElementById('checkbox32').checked) {
		descargareserva();
		alert('Debe aceptar las condiciones de contratación y las condiciones de tarifa para poder proceder.');
		return false;
	}
	else{
		if(validar_metodo_de_pago()==false){
			descargareserva();
			return false;
		}
		else{
			if(document.getElementById('estoy_registrado').checked==true){
				/*ver si se logueo*/
				if(document.getElementById('hid_user_existente_loginok').value!='true'){
					descargareserva();
					alert('Por favor, ingrese sus datos de usuario (e-mail y contraseña) y luego haga click en `Continuar´ para loguearse.');
					return false;
				}
			}
			else{
				/*no indico nada*/
				if((document.getElementById('datos_en_cookies').value!='true')&&(document.getElementById('ya_estaba_identificado').value!='true')&&(document.getElementById('no_estoy_registrado').checked!=true)){
					descargareserva();
					alert('Por favor, indique si está o no registrado.');
					return false;
				}
				else{
					/*no tiene usuario pero no lleno los datos*/
					if(document.getElementById('textfield3').value==''){
						descargareserva();
						alert('Ingrese su nombre en los datos de registro.');
						return false;
					}
					if(document.getElementById('usuario_datos_no_validar').value==false){
						if(document.getElementById('textfield32').value==''){
							descargareserva();
							alert('Ingrese su apellido en los datos de registro.');
							return false;
						}
					}
					if(document.getElementById('usuario_datos_no_validar_direccion').value==false){
						if(document.getElementById('textfield333').value==''){
							descargareserva();
							alert('Ingrese su dirección en los datos de registro.');
							return false;
						}
						if(document.getElementById('textfield3335').value==''){
							descargareserva();
							alert('Ingrese su localidad de residencia en los datos de registro.');
							return false;
						}
					}
					if(document.getElementById('usuario_datos_no_validar').value==false){
						if(document.getElementById('textfield335').value==''){
							descargareserva();
							alert('Ingrese su provincia de residencia en los datos de registro.');
							return false;
						}
					}
					if(document.getElementById('usuario_datos_no_validar_direccion').value==false){
						if(document.getElementById('textfield336').value==''){
							descargareserva();
							alert('Ingrese el código postal de su localidad de residencia en los datos de registro.');
							return false;
						}
					}
					if(document.getElementById('textfield33').value==''){
						descargareserva();
						alert('Ingrese su número de teléfono en los datos de registro.');
						return false;
					}
					if(document.getElementById('textfield339').value==''){
						descargareserva();
						alert('Ingrese su dirección de e-mail en los datos de registro.');
						return false;
					}
					if(document.getElementById('usuario_datos_no_validar').value==false){
						if(document.getElementById('textfield33m').value==''){
							descargareserva();
							alert('Ingrese su número de teléfono móvil en los datos de registro.');
							return false;
						}
						if(document.getElementById('textfield338').value==''){
							descargareserva();
							alert('Ingrese una contraseña en los datos de registro.');
							return false;
						}
					}
				}
			}
			/*
			las validaciones generales
			*/
			var localidad_pax=0;
			var cant_pasajeros=document.getElementById('hid_cant_pasajeros').value;
			for(var i=0;i<cant_pasajeros;i++){
				if(document.getElementById('nombre_pax_'+i).value.trim()==''){
					descargareserva();
					alert('Ingrese el nombre del pasajero nº '+(i+1)+'.');
					return false;
				}
				if(document.getElementById('ape_pax_'+i).value.trim()==''){
					descargareserva();
					alert('Ingrese el apellido del pasajero nº '+(i+1)+'.');
					return false;
				}
				if(document.getElementById('fecha_de_nacimiento_'+i).value.trim()==''){
					descargareserva();
					alert('Ingrese la fecha de nacimiento del pasajero nº '+(i+1)+'.');
					return false;
				}

				var age_ok=true;
				var fecha_nac=document.getElementById('fecha_de_nacimiento_'+i).value.trim();
				var fecha_nac_p=fecha_nac.split('/');
				var now= new Date();
				var myDate=new Date();
				myDate.setFullYear(fecha_nac_p[2],fecha_nac_p[1]-1,fecha_nac_p[0]);
				years = Math.floor((now.getTime() - myDate.getTime()) / (365.25 * 24 * 60 * 60 * 1000));

				if(document.getElementById('tipo_pax_'+i).value=='a'){
					if(years<12) age_ok=false;
				}
				else if(document.getElementById('tipo_pax_'+i).value=='n'){
					if(!(years>=2 && years<=12)) age_ok=false;
				}
				else if(document.getElementById('tipo_pax_'+i).value=='b'){
					if(years>2) age_ok=false;
				}

				if(!age_ok){
					descargareserva();
					alert('La edad del pasajero '+(i+1)+' es incompatible con el tipo de pasajero');
					return false;
				}

				if(document.getElementById('pax_document_'+(i+1)).value!='MR' && document.getElementById('pax_DNI_document_'+(i+1)).value.trim()==''){
					descargareserva();
					alert('Ingrese el nº de documento del pasajero nº '+(i+1)+'.');
					return false;
				}
				if((document.getElementById('pax_document_'+(i+1)).value=='DN')||(document.getElementById('pax_document_'+(i+1)).value=='TR')){
					if(!NormalizaDNIM(i+1)){
						descargareserva();
						return false;
					}
				}
				try{
					localidad_pax=document.getElementById('localidad_pax_'+(i));
					if(localidad_pax){
						if(localidad_pax.selectedIndex==0){
							descargareserva();
							alert('Elija la localidad de residencia del pasajero nº '+(i+1)+'.');
							return false;
						}
						if(document.getElementById('localidad_coincide_dni_'+(i)).value=='no'){
							if(document.getElementById('nro_cert_res_'+(i)).value==''){
								descargareserva();
								alert('Ingrese el nº de certificado del pasajero nº '+(i+1)+'.');
								return false;
							}
						}
					}
				}
				catch(e){}
			}
			return true;
		}
	}
}

function toggle_div_for(what){
	try{document.getElementById('nom_metodo_de_pago').value=what;}
	catch(e){}
	/**
	 * En principio dejamos el seguro visible, despues vemos bien que hacer
	 */
	try{document.getElementById('seguro_subtotal').style.display='none';}
	catch(e){}
	try{document.getElementById('metodo_tc1').style.display='none';}
	catch(e){}
	try{document.getElementById('metodo_tc2').style.display='none';}
	catch(e){}
	try{document.getElementById('metodo_cs1').style.display='none';}
	catch(e){}
	try{document.getElementById('metodo_cs2').style.display='none';}
	catch(e){}
	try{document.getElementById('metodo_ta1').style.display='none';}
	catch(e){}
	try{document.getElementById('metodo_ta2').style.display='none';}
	catch(e){}
	try{document.getElementById('metodo_tr1').style.display='none';}
	catch(e){}
	try{document.getElementById('metodo_tr2').style.display='none';}
	catch(e){}
	try{document.getElementById('metodo_td1').style.display='none';}
	catch(e){}
	try{document.getElementById('metodo_td2').style.display='none';}
	catch(e){}
	try{document.getElementById('metodo_'+what+'1').style.display='';}
	catch(e){}
	try{document.getElementById('metodo_'+what+'2').style.display='';}
	catch(e){}
	/**
	 * Si es tarjeta de credito o transferencia
	 */
	if(what=='tc'||what=='tr'||what=='TC'||what=='TR'){
		 try{
		 	var seguro_ocultar_trtc=document.getElementById('seguro_ocultar_trtc').value;
		 	/**
			 * Si faltan los datos de tarjeta
			 */
		 	if(seguro_ocultar_trtc=="1"){
		 		if(document.getElementById('ultimo_seguro').value!='0'&&document.getElementById('ultimo_seguro').value!='0.00'&&document.getElementById('ultimo_seguro').value!='0,00'){
			 		/**
			 		 * No puede habilitar el seguro
			 		 */
			 		toggleSeguros('off','0.00');
			 		alert('Por las condiciones de la agencia, no puede contratar el seguro en este momento.\r\nSi desea contratar un seguro, intente cambiar el método de pago y luego intente habilitarlo.');
			 		document.getElementById('checkbox22232').checked='';
			 		document.getElementById('seguro_subtotal').style.display='none';
		 		}
		 	}
		 }
		 catch(e){}
	}
}

function validar_metodo_de_pago(){
	var cual='';
	var cual_cs='';
	var cual_tr='';
	var cual_tc='';
	var cual_td='';
	var cual_ta='';
	try { cual_cs=document.getElementById('radiobutton_metodo_de_pagocs').checked; }
	catch(e){}
	try { cual_tr=document.getElementById('radiobutton_metodo_de_pagotr').checked; }
	catch(e){}
	try { cual_tc=document.getElementById('radiobutton_metodo_de_pagotc').checked; }
	catch(e){}
	try { cual_td=document.getElementById('radiobutton_metodo_de_pagotd').checked; }
	catch(e){}
	try { cual_ta=document.getElementById('radiobutton_metodo_de_pagota').checked; }
	catch(e){}
	if(cual_cs) cual='CS';
	else if(cual_tr) cual='TR';
	else if(cual_tc) cual='TC';
	else if(cual_td) cual='TD';
	else if(cual_ta) cual='TA';
	else cual='';
	if(cual==''){
		alert('Seleccione un método de pago.');
		return false;
	}
	if(cual=='CS'){
		return true;
	}
	else if(cual=='TA'){
		return true;
	}
	else if(cual=='TR'){
		var errors=false;
		if(document.getElementById('textfield355tr').value=='') errors=true;
		if(document.getElementById('textfield355apetr').value=='') errors=true;
		if(!errors) return true;
		else{
			alert('Por favor, ingrese el nombre y apellido del ordenante de la transferencia.');
			return false;
		}
	}
	else if(cual=='TC'){
		var errors=false;
		if(document.getElementById('textfield355').value=='') errors=true;
		if(document.getElementById('textfield355telefono').value=='') errors=true;
		if(document.getElementById('textfield355email').value=='') errors=true;
		if(document.getElementById('textfield33342').value=='') errors=true;
		if(document.getElementById('textfield333422').value=='') errors=true;
		if(!validateCC(document.getElementById('textfield33342').value,TipoTarjeta())){
			alert('Por favor, revise todos los datos de su tarjeta de crédito.')
			return false;
		}
		var mes		=parseInt(document.getElementById('select18vh').value);
		var mes_min	=parseInt(document.getElementById('select18vh_min').value);
		var anio	=parseInt(document.getElementById('select19').value);
		var anio_min=parseInt(document.getElementById('select19_min').value);
		if(!((anio==anio_min&&mes>=mes_min)||anio>anio_min)){
			alert('Por favor, revise todos los datos de su tarjeta de crédito.')
			return false;
		}

		if(!Mod10(document.getElementById('textfield33342').value)){
			return false;
		}

		if(!errors) return true;
		else{
			alert('Por favor, ingrese todos los datos de su tarjeta de crédito.');
			return false;
		}
	}
	else if(cual=='TD'){
		var errors=false;
		if(document.getElementById('textfield355d').value=='') errors=true;
		if(document.getElementById('textfield33342d').value=='') errors=true;
		if(document.getElementById('textfield333422d').value=='') errors=true;
		if(!errors) return true;
		else{
			alert('Por favor, ingrese todos los datos de su tarjeta de débito.');
			return false;
		}
	}
}

function ValidaFecha(field){
	var checkstr = "0123456789";
	var DateField = field;
	var Datevalue = "";
	var DateTemp = "";
	var seperator = "/";
	var day;
	var month;
	var year;
	var leap = 0;
	var err = 0;
	var i;
	err = 0;
	DateValue = DateField.value;
	/* Delete all chars except 0..9 */
	for (i = 0; i < DateValue.length; i++) {
		if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
			DateTemp = DateTemp + DateValue.substr(i,1);
		}
	}
	DateValue = DateTemp;
	/* Always change date to 8 digits - string*/
	/* if year is entered as 2-digit / always assume 20xx */
	if (DateValue.length == 6) {
		DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); }
		if (DateValue.length != 8) {
			err = 19;}
			/* year is wrong if year = 0000 */
			year = DateValue.substr(4,4);
			if (year == 0) {
				err = 20;
			}
			/* Validation of month*/
			month = DateValue.substr(2,2);
			if ((month < 1) || (month > 12)) {
				err = 21;
			}
			/* Validation of day*/
			day = DateValue.substr(0,2);
			if (day < 1) {
				err = 22;
			}
			/* Validation leap-year / february / day */
			if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
				leap = 1;
			}
			if ((month == 2) && (leap == 1) && (day > 29)) {
				err = 23;
			}
			if ((month == 2) && (leap != 1) && (day > 28)) {
				err = 24;
			}
			/* Validation of other months */
			if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
				err = 25;
			}
			if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
				err = 26;
			}
			/* if 00 ist entered, no error, deleting the entry */
			if ((day == 0) && (month == 0) && (year == 00)) {
				err = 0; day = ""; month = ""; year = ""; seperator = "";
			}
			/* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
			if (err == 0) {
				DateField.value = day + seperator + month + seperator + year;
			}
			/* Error-message if err != 0 */
			else {
				alert("La fecha ingresada es incorrecta.");
				DateField.select();
				DateField.focus();
			}
}

function ValidaFechaM(field){
	var checkstr = "0123456789";
	var DateField = field;
	var Datevalue = "";
	var DateTemp = "";
	var seperator = "/";
	var day;
	var month;
	var year;
	var leap = 0;
	var err = 0;
	var i;
	err = 0;
	DateValue = DateField.value;
	/* Delete all chars except 0..9 */
	for (i = 0; i < DateValue.length; i++) {
		if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
			DateTemp = DateTemp + DateValue.substr(i,1);
		}
	}
	DateValue = DateTemp;
	/* Always change date to 8 digits - string OBSOLETO*/
	/* if year is entered as 2-digit / always assume 20xx */
	/*if (DateValue.length == 6) {
	DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); }*/

	if (DateValue.length != 8) {
		err = 19;}
		/* year is wrong if year = 0000 */
		year = DateValue.substr(4,4);
		if (year == 0) {
			err = 20;
		}
		/* Validation of month*/
		month = DateValue.substr(2,2);
		if ((month < 1) || (month > 12)) {
			err = 21;
		}
		/* Validation of day*/
		day = DateValue.substr(0,2);
		if (day < 1) {
			err = 22;
		}
		/* Validation leap-year / february / day */
		if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
			leap = 1;
		}
		if ((month == 2) && (leap == 1) && (day > 29)) {
			err = 23;
		}
		if ((month == 2) && (leap != 1) && (day > 28)) {
			err = 24;
		}
		/* Validation of other months */
		if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
			err = 25;
		}
		if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
			err = 26;
		}
		/* if 00 ist entered, no error, deleting the entry */
		if ((day == 0) && (month == 0) && (year == 00)) {
			err = 0; day = ""; month = ""; year = ""; seperator = "";
		}
		/* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
		if (err == 0) {
			DateField.value = day + seperator + month + seperator + year;
		}
		/* Error-message if err != 0 */
		else {
			alert("La fecha ingresada es incorrecta.");
			DateField.select();
			DateField.focus();
		}
}

/*
* ValidaEmail: Comprobamos que siga el patrón de una direccióin de email válida
*/
function ValidaEmail(src) {
	var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
	if (regex.test(src)) {
		return true;
	} else {
		return false;
	}
}

/*
*
*/
function TraduceDocumento(txt) {
	if (txt=="DN"){
		return "el DNI";
	} else if (txt=="TR"){
		return "la Tarjeta Residente";
	} else if (txt=="DL") {
		return "la Licencia de Conducir";
	} else if (txt=="PA") {
		return "el Pasaporte";
	} else if (txt=="MR") {
		return "el menor sin documento";
	} else {
		return txt
	}
}

/*
* Right: Saca la parte derecha.
*/
function Right(str, n){
	if (n <= 0)
	return "";
	else if (n > String(str).length)
	return str;
	else {
		var iLen = String(str).length;
		return String(str).substring(iLen, iLen - n);
	}
}

function NormalizaDNIM (pax)
{
	var documento=eval("document.getElementById('pax_document_"+pax+"').value");
	var numero=eval("document.getElementById('pax_DNI_document_"+pax+"').value");
	if(documento=='DN'){
		var numero_bak=numero;
		numero=numero.substring(0,numero.length-1);
		if(numero.len>9){
			alert('El DNI del pasajero '+pax+' debe tener 9 números.');
			return false;
		}
		cadena="TRWAGMYFPDXBNJZSQVHLCKET";
		posicion = numero % 23;
		letra = cadena.substring(posicion,posicion+1);
		if(letra!=(numero_bak.substring(numero_bak.length-1,numero_bak.length).toUpperCase())){
			alert('La letra de DNI del pasajero '+pax+' es incorrecta.');
			return false;
		}
		else{
			while(numero.length<9){
				numero='0'+numero;
			}
			var numero_final=numero+numero_bak.substring(numero_bak.length-1,numero_bak.length).toUpperCase();
			document.getElementById('pax_DNI_document_'+pax).value=numero_final;
		}
	}
	else if(documento=='TR'){
		if((numero.substr(0,1)!='x')&&(numero.substr(0,1)!='X')){
			alert('La letra de Tarjeta de Residencia del pasajero '+pax+' es incorrecta.');
			return false;
		}
		var numero_bak=numero;
		numero=numero.substring(1,numero.length-1);
		if(numero.len>9){
			alert('El DNI del pasajero '+pax+' debe tener 9 números.');
			return false;
		}
		cadena="TRWAGMYFPDXBNJZSQVHLCKET";
		posicion = numero % 23;
		letra = cadena.substring(posicion,posicion+1);
		if(letra!=(numero_bak.substring(numero_bak.length-1,numero_bak.length).toUpperCase())){
			alert('La letra de Tarjeta de Residencia del pasajero '+pax+' es incorrecta.');
			return false;
		}
		else{
			while(numero.length<9){
				numero='0'+numero;
			}
			var numero_final='X'+numero+numero_bak.substring(numero_bak.length-1,numero_bak.length).toUpperCase();
			document.getElementById('pax_DNI_document_'+pax).value=numero_final;
		}
	}
	return true;
}

/*
* NormalizaDNI: Sólamente dejamos que haya números.
*/
function NormalizaDNI(pax) {
	var _documento=eval("document.getElementById('pax_document_"+pax+"').value");
	var numero_tmp=eval("document.getElementById('pax_DNI_document_"+pax+"').value");
	var numero="00000000000";
	var letra="";
	var letra_inicial="";

	var ValidChars = "0123456789.-";
	var IsNumber=true;
	var Char='';
	var coletilla_txt="";
	var largo="9";

	if (pax==0) {
		coletilla="de contacto";
	} else {
		coletilla="número "+pax;
	}

	_documento=TraduceDocumento(_documento);

	if ( (_documento=="el DNI") || (_documento=="la Tarjeta Residente") ) {
		if (_documento=="la Tarjeta Residente") {
			largo="8";
			Char = numero_tmp.charAt(0);
			if(ValidChars.indexOf(Char) == -1) {
				letra_inicial=Char.toUpperCase();
			}
		}

		//Sólo hacemos esta validación para el DNI. El pasaporte, la tarjeta de residente, etc. no controlamos si tiene la letra o no.
		for(ii = 0; ii < numero_tmp.length && IsNumber == true; ii++) {
			Char = numero_tmp.charAt(ii);
			if(ValidChars.indexOf(Char) == -1) {
				letra=Char.toUpperCase();
			} else {
				if ( (Char!='.') && (Char!='-') ){
					numero=numero.concat(Char);
				}
			}
		}

		numero=Right(numero,largo);

		if (letra=="") {
			alert ("No existe la letra de "+_documento+" del pasajero "+coletilla);
			eval("document.getElementById('pax_DNI_document_"+pax+"').value='';");
			return false;
		} else {
			if (_documento=="la Tarjeta Residente") {
				numero=letra_inicial.concat(numero);
			}
			eval("document.getElementById('pax_num_document_"+pax+"').value='"+numero+"';");
			if (CalculaLetraNIF(pax)==letra) {
				eval("document.getElementById('pax_DNI_document_"+pax+"').value='"+numero+letra+"';");
				eval("document.getElementById('pax_num_document_"+pax+"').value='"+numero+"';");
				eval("document.getElementById('pax_document_letter_"+pax+"').value='"+letra+"';");
				if (pax==1) {
					eval("document.getElementById('pax_DNI_document_0').value='"+numero+letra+"';");
					eval("document.getElementById('pax_num_document_0').value='"+numero+"';");
					eval("document.getElementById('pax_document_letter_0').value='"+letra+"';");
				}
			} else {
				alert ("La letra de "+_documento+" del pasajero "+coletilla+" es incorrecta");
				eval("document.getElementById('pax_DNI_document_"+pax+"').value='';");
				eval("document.getElementById('pax_num_document_"+pax+"').value='';");
				eval("document.getElementById('pax_document_letter_"+pax+"').value='';");
				return false;
			}
		}
	} else {
		if ( (pax==0) || (pax==1) ){
			eval("document.getElementById('pax_DNI_document_0').value='"+numero_tmp+"';");
			eval("document.getElementById('pax_num_document_0').value='"+numero_tmp+"';");
			eval("document.getElementById('pax_document_letter_0').value='"+numero_tmp.charAt(numero_tmp.length-1)+"';");
		}
		return false;
	}
	return true;
}

/*
* QuitraLetras: Para extraer sólo un número de una cadena
*/
function QuitaLetras(sText) {
	var ValidChars = "0123456789.-";
	var Char;
	var res_txt="0000000000";

	for(ii = 0; ii < sText.length; ii++) {
		Char = sText.charAt(ii);
		if(ValidChars.indexOf(Char) == -1) {
			//No la actualizamos
		} else {
			if ( (Char!='.') && (Char!='-') ){
				res_txt=res_txt.concat(Char);
			}
		}
	}
	return res_txt;
}

/*
* CalculaLetraNIF(num_pax): Calculamos la letra que tiene un DNI.
*/
function CalculaLetraNIF(pax) {
	var letrasNIF="TRWAGMYFPDXBNJZSQVHLCKE";
	var numero="";
	var letters= new Array();
	letters[0] = "T" ;letters[1] = "R" ;letters[2] = "W" ;
	letters[3] = "A" ;letters[4] = "G" ;letters[5] = "M" ;
	letters[6] = "Y" ;letters[7] = "F" ;letters[8] = "P" ;
	letters[9] = "D" ;letters[10] = "X" ;letters[11] = "B" ;
	letters[12] = "N" ;letters[13] = "J" ;letters[14] = "Z" ;
	letters[15] = "S" ;letters[16] = "Q" ;letters[17] = "V" ;
	letters[18] = "H" ;letters[19] = "L" ;letters[20] = "C" ;
	letters[21] = "K" ;letters[22] = "E" ;
	var _documento=TraduceDocumento(eval("document.getElementById('pax_document_"+pax+"').value"));
	if (_documento=="la Tarjeta Residente") {
		numero=QuitaLetras(eval("document.getElementById('pax_num_document_"+pax+"').value"));
	}
	else{
		numero=eval("document.getElementById('pax_num_document_"+pax+"').value");
	}
	var Q=(Math.abs(numero%23));
	return letters[Q];
}

/*
*  Normaliza: Quitamos todos los acentos y signos de puntuaión
*/
function Normaliza(fieldname) {
	var campo=document.getElementById(fieldname).value;

	while (campo.indexOf(".")>=0) {
		campo=campo.replace(/./,'');
	}

	while (campo.indexOf("-")>=0) {
		campo=campo.replace(/-/,'');
	}

	while (campo.indexOf("_")>=0) {
		campo=campo.replace(/_/,'');
	}

	while (campo.indexOf("'")>=0) {
		campo=campo.replace(/'/,'');
 }

 while (campo.indexOf("´")>=0) {
    campo=campo.replace(/´/,'');
 }

 while (campo.indexOf("`")>=0) {
    campo=campo.replace(/`/,'');
 }

 while (campo.indexOf('"')>=0) {
    campo=campo.replace(/"/,'');
	}

	while (campo.indexOf('á')>=0) {
		campo=campo.replace(/á/,'a');
	}
	while (campo.indexOf('é')>=0) {
		campo=campo.replace(/é/,'e');
	}
	while (campo.indexOf('í')>=0) {
		campo=campo.replace(/í/,'i');
	}
	while (campo.indexOf('ó')>=0) {
		campo=campo.replace(/ó/,'o');
	}
	while (campo.indexOf('ú')>=0) {
		campo=campo.replace(/ú/,'u');
	}

	while (campo.indexOf('Á')>=0) {
		campo=campo.replace(/Á/,'A');
	}
	while (campo.indexOf('É')>=0) {
		campo=campo.replace(/É/,'E');
	}
	while (campo.indexOf('Í')>=0) {
		campo=campo.replace(/Í/,'I');
	}
	while (campo.indexOf('Ó')>=0) {
		campo=campo.replace(/Ó/,'O');
	}
	while (campo.indexOf('Ú')>=0) {
		campo=campo.replace(/Ú/,'U');
	}

	while (campo.indexOf('à')>=0) {
		campo=campo.replace(/à/,'a');
	}
	while (campo.indexOf('è')>=0) {
		campo=campo.replace(/è/,'e');
	}
	while (campo.indexOf('ì')>=0) {
		campo=campo.replace(/ì/,'i');
	}
	while (campo.indexOf('ò')>=0) {
		campo=campo.replace(/ò/,'o');
	}
	while (campo.indexOf('ù')>=0) {
		campo=campo.replace(/ù/,'u');
	}

	while (campo.indexOf('À')>=0) {
		campo=campo.replace(/À/,'A');
	}
	while (campo.indexOf('È')>=0) {
		campo=campo.replace(/È/,'E');
	}
	while (campo.indexOf('Ì')>=0) {
		campo=campo.replace(/Ì/,'I');
	}
	while (campo.indexOf('Ò')>=0) {
		campo=campo.replace(/Ò/,'O');
	}
	while (campo.indexOf('Ù')>=0) {
		campo=campo.replace(/Ù/,'U');
	}

	while (campo.indexOf('ñ')>=0) {
		campo=campo.replace(/ñ/,'n');
	}
	while (campo.indexOf('Ñ')>=0) {
		campo=campo.replace(/Ñ/,'N');
	}
	while (campo.indexOf('ç')>=0) {
		campo=campo.replace(/ç/,'c');
	}
	while (campo.indexOf('Ç')>=0) {
		campo=campo.replace(/Ç/,'C');
	}

	while (campo.indexOf('ä')>=0) {
		campo=campo.replace(/ä/,'a');
	}
	while (campo.indexOf('ë')>=0) {
		campo=campo.replace(/ë/,'e');
	}
	while (campo.indexOf('ï')>=0) {
		campo=campo.replace(/ï/,'i');
	}
	while (campo.indexOf('ö')>=0) {
		campo=campo.replace(/ö/,'o');
	}
	while (campo.indexOf('ü')>=0) {
		campo=campo.replace(/ü/,'u');
	}

	while (campo.indexOf('Ä')>=0) {
		campo=campo.replace(/Ä/,'A');
	}
	while (campo.indexOf('Ë')>=0) {
		campo=campo.replace(/Ë/,'E');
	}
	while (campo.indexOf('Ï')>=0) {
		campo=campo.replace(/Ï/,'I');
	}
	while (campo.indexOf('Ö')>=0) {
		campo=campo.replace(/Ö/,'O');
	}
	while (campo.indexOf('Ü')>=0) {
		campo=campo.replace(/Ü/,'U');
	}

	while (campo.indexOf('â')>=0) {
		campo=campo.replace(/â/,'a');
	}
	while (campo.indexOf('ê')>=0) {
		campo=campo.replace(/ê/,'e');
	}
	while (campo.indexOf('î')>=0) {
		campo=campo.replace(/î/,'i');
	}
	while (campo.indexOf('ô')>=0) {
		campo=campo.replace(/ô/,'o');
	}
	while (campo.indexOf('û')>=0) {
		campo=campo.replace(/û/,'u');
	}

	while (campo.indexOf('Â')>=0) {
		campo=campo.replace(/Â/,'A');
	}
	while (campo.indexOf('Ê')>=0) {
		campo=campo.replace(/Ê/,'E');
	}
	while (campo.indexOf('Î')>=0) {
		campo=campo.replace(/Î/,'I');
	}
	while (campo.indexOf('Ô')>=0) {
		campo=campo.replace(/Ô/,'O');
	}
	while (campo.indexOf('Û')>=0) {
		campo=campo.replace(/Û/,'U');
	}

	while (campo.indexOf('º')>=0) {
		campo=campo.replace(/º/,'o');
	}

	while (campo.indexOf('ª')>=0) {
		campo=campo.replace(/ª/,'a');
	}
	while (campo.indexOf('/')>=0) {
		campo=campo.replace(/\//,'');
	}
	while (campo.indexOf('\\')>=0) {
		campo=campo.replace(/\\/,'');
	}
	while (campo.indexOf('\|')>=0) {
		campo=campo.replace(/\|/,'');
	}
	while (campo.indexOf(',')>=0) {
		campo=campo.replace(/,/,'');
	}
	while (campo.indexOf(';')>=0) {
		campo=campo.replace(/;/,'');
	}
	document.getElementById(fieldname).value=campo;
}

/**
* Recibe:
* status=on/off
* seguro_cancelacion=	div con texto del precio del seguro
*/
function toggleSeguros(status, seguro_cancelacion){
	seguro_cancelacion.replace(/,/, ".");
	seguro_cancelacion=parseFloat(seguro_cancelacion);
	var seguro_ant=document.getElementById('ultimo_seguro').value;
	seguro_ant.replace(/,/, ".");
	seguro_ant=parseFloat(seguro_ant);

	var total_cargo_tarjeta=document.getElementById('total_cargo_tarjeta').innerHTML;
	total_cargo_tarjeta=stripHtml(total_cargo_tarjeta);
	total_cargo_tarjeta.replace(",", ".");
	total_cargo_tarjeta=parseFloat(total_cargo_tarjeta);
	//total servicios agencia
	var subtotal_2=(document.getElementById('subtotal_2').innerHTML);
	subtotal_2=stripHtml(subtotal_2);
	subtotal_2=subtotal_2.replace(",", ".");
	subtotal_2=parseFloat(subtotal_2);

	var hid_total=document.getElementById('hid_total').value;
	hid_total=hid_total.replace(",", ".");
	hid_total=parseFloat(hid_total);

	var hid_gastos=document.getElementById('hid_gastos').value;
	hid_gastos=hid_gastos.replace(",", ".");
	hid_gastos=parseFloat(hid_gastos);

	document.getElementById('seguro_cancelacion').innerHTML=(seguro_cancelacion.toFixed(2)).replace(".", ",");
	//total servicios agencia
	document.getElementById('subtotal_2').innerHTML=((subtotal_2+seguro_cancelacion-seguro_ant).toFixed(2)).replace(".", ",");
	document.getElementById('hid_gastos').value=hid_gastos+seguro_cancelacion-seguro_ant;
	document.getElementById('hid_seguros').value=seguro_cancelacion;
	//el total oculto
	document.getElementById('hid_total').value=hid_total+seguro_cancelacion-seguro_ant;
	var iac=((hid_total+seguro_cancelacion-seguro_ant).toFixed(2)).replace(".", ",");
	var iac_sf=(hid_total+seguro_cancelacion-seguro_ant);
	//el total del cuadro
	document.getElementById('total_cargo_tarjeta').innerHTML=iac;
	//el total de abajo
	document.getElementById('importe_a_cobrar').innerHTML='&nbsp;<strong>'+iac+'</strong>';

	document.getElementById('ultimo_seguro').value=seguro_cancelacion;

	checkAutoLimit();
	
	toggle_div_for(document.getElementById('nom_metodo_de_pago').value);
}

/**
 * @TODO hacer algo como la gente
 */
function stripHtml(s) {
	s=s.replace('<b>','');
	s=s.replace('</b>','');
	s=s.replace('<font>','');
	s=s.replace('</font>','');
	s=s.replace('<B>','');
	s=s.replace('</B>','');
	s=s.replace('<FONT>','');
	s=s.replace('</FONT>','');
	s=s.replace('<TR>','');
	s=s.replace('</TR>','');
	s=s.replace('<TD>','');
	s=s.replace('</TD>','');
	s=s.replace('<tr>','');
	s=s.replace('</tr>','');
	s=s.replace('<td>','');
	s=s.replace('</td>','');
	s=s.replace(' ','');
	return s;
}

function toggleEnvio(status,tasa_envio){
	try{
		document.getElementById('ultima_tasa').value=tasa_envio;
	}
	catch(e){}
	tasa_envio.replace(/,/, ".");
	tasa_envio=parseFloat(tasa_envio);
	//total gastos agencia
	var total_gastos_agencia=document.getElementById('total_gastos_agencia').innerHTML;
	total_gastos_agencia=stripHtml(total_gastos_agencia);
	total_gastos_agencia.replace(",", ".");
	total_gastos_agencia=parseFloat(total_gastos_agencia);

	var total_cargo_tarjeta=document.getElementById('total_cargo_tarjeta').innerHTML;
	total_cargo_tarjeta=stripHtml(total_cargo_tarjeta);
	total_cargo_tarjeta.replace(",", ".");
	total_cargo_tarjeta=parseFloat(total_cargo_tarjeta);
	//total servicios agencia
	var subtotal_2=(document.getElementById('subtotal_2').innerHTML);
	subtotal_2=stripHtml(subtotal_2);
	subtotal_2=subtotal_2.replace(",", ".");
	subtotal_2=parseFloat(subtotal_2);

	var hid_total=document.getElementById('hid_total').value;
	hid_total=hid_total.replace(",", ".");
	hid_total=parseFloat(hid_total);

	var hid_gastos=document.getElementById('hid_gastos').value;
	hid_gastos=hid_gastos.replace(",", ".");
	hid_gastos=parseFloat(hid_gastos);

	if(status=='on'){
		document.getElementById('id_envio_billete_papel').innerHTML=(tasa_envio.toFixed(2)).replace(".", ",");
		//total gastos agencia
		document.getElementById('total_gastos_agencia').innerHTML=((total_gastos_agencia+tasa_envio).toFixed(2)).replace(".", ",");
		//total servicios agencia
		document.getElementById('subtotal_2').innerHTML=((subtotal_2+tasa_envio).toFixed(2)).replace(".", ",");
		document.getElementById('hid_gastos').value=hid_gastos+tasa_envio;
		//el total oculto
		document.getElementById('hid_total').value=hid_total+tasa_envio;
		var iac=((hid_total+tasa_envio).toFixed(2)).replace(".", ",");
		var iac_sf=(hid_total+tasa_envio);
		//el total del cuadro
		document.getElementById('total_cargo_tarjeta').innerHTML=iac;
		//el total de abajo
		document.getElementById('importe_a_cobrar').innerHTML='&nbsp;<strong>'+iac+'</strong>';
	}
	else{
		document.getElementById('id_envio_billete_papel').innerHTML='0,00';
		//total gastos agencia
		document.getElementById('total_gastos_agencia').innerHTML=((total_gastos_agencia-tasa_envio).toFixed(2)).replace(".", ",");
		//total servicios agencia
		document.getElementById('subtotal_2').innerHTML=((subtotal_2-tasa_envio).toFixed(2)).replace(".", ",");
		document.getElementById('hid_gastos').value=hid_gastos-tasa_envio;
		//el total oculto
		document.getElementById('hid_total').value=hid_total-tasa_envio;
		var iac=((hid_total-tasa_envio).toFixed(2)).replace(".", ",");
		var iac_sf=(hid_total-tasa_envio);
		//el total del cuadro
		document.getElementById('total_cargo_tarjeta').innerHTML=iac;
		//el total de abajo
		document.getElementById('importe_a_cobrar').innerHTML='&nbsp;<strong>'+iac+'</strong>';
	}

	checkAutoLimit();
}

function eligeMaletas(ida_o_vuelta,obligatorias,cantidad,precio){
	var precio_bak=precio;
	precio=precio/100;
	if(parseInt(cantidad)>0 || obligatorias=='N'){
		//eligio 1 o mas maletas, o no es obligatorio que las elija
		document.getElementById('faltan_maletas_'+ida_o_vuelta).value='N';
	}
	else{
		//no eligio maletas pero es obligatorio que las elija
		document.getElementById('faltan_maletas_'+ida_o_vuelta).value='Y';
	}
	document.getElementById('maletas_'+ida_o_vuelta).value=cantidad+'@'+precio;

	var precio_ant=document.getElementById('ultimo_precio_maletas_'+ida_o_vuelta).value;

	precio=parseFloat(precio);
	//total gastos agencia
	var total_gastos_compania=document.getElementById('total_gastos_compania').innerHTML;
	total_gastos_compania=stripHtml(total_gastos_compania);
	var total_gastos_compania_f=total_gastos_compania.replace(",", ".");
	total_gastos_compania=parseFloat(total_gastos_compania_f);

	var total_cargo_tarjeta=document.getElementById('total_cargo_tarjeta').innerHTML;
	total_cargo_tarjeta=stripHtml(total_cargo_tarjeta);
	var total_cargo_tarjeta_f=total_cargo_tarjeta.replace(",", ".");
	total_cargo_tarjeta=parseFloat(total_cargo_tarjeta_f);
	//total servicios agencia
	var subtotal_2=(document.getElementById('subtotal_2').innerHTML);
	subtotal_2=stripHtml(subtotal_2);
	var subtotal_2_f=subtotal_2.replace(",", ".");
	subtotal_2=parseFloat(subtotal_2_f);

	var hid_total=document.getElementById('hid_total').value;
	var hid_total_f=hid_total.replace(",", ".");
	hid_total=parseFloat(hid_total_f);

	var hid_gastos=document.getElementById('hid_gastos').value;
	var hid_gastos_f=hid_gastos.replace(",", ".");
	hid_gastos=parseFloat(hid_gastos_f);

	//total gastos agencia
	//total_gastos_compania
	document.getElementById('total_gastos_compania').innerHTML=((total_gastos_compania-precio_ant+precio).toFixed(2)).replace(".", ",");
	//total servicios agencia
	document.getElementById('subtotal_2').innerHTML=((subtotal_2-precio_ant+precio).toFixed(2)).replace(".", ",");
	document.getElementById('hid_gastos').value=hid_gastos-precio_ant+precio;
	//el total oculto
	document.getElementById('hid_total').value=hid_total-precio_ant+precio;
	var iac=((hid_total-precio_ant+precio).toFixed(2)).replace(".", ",");
	var iac_sf=(hid_total-precio_ant+precio);
	//el total del cuadro
	document.getElementById('total_cargo_tarjeta').innerHTML=iac;
	//el total de abajo
	document.getElementById('importe_a_cobrar').innerHTML='&nbsp;<strong>'+iac+'</strong>';

	var precio_a_mostrar=(precio.toFixed(2)).replace(".", ",")
	document.getElementById('gastos_equipaje_'+ida_o_vuelta+'_html').innerHTML=precio_a_mostrar+'&euro;';

	document.getElementById('ultimo_precio_maletas_'+ida_o_vuelta).value=precio;

	checkAutoLimit();
}

function eligeTasaEnvio(precio){
	precio.replace(/,/, ".");
	precio=parseFloat(precio);

	if(!(precio>=0)) precio=0;

	if(precio=='NaN'||precio=='undefined') precio=0;
/*
ya no se usa
	var precio_minimo=parseFloat(document.getElementById('hid_tasa_z').value)+parseFloat(document.getElementById('hid_descuento_web').value);

	if(precio_minimo>precio) precio=precio_minimo;
*/
	var precio_porpersona=precio;
	precio=parseFloat(parseFloat(precio)*parseInt(document.getElementById('hid_cant_pasajeros').value));
	var precio_ant=parseFloat(parseFloat(document.getElementById('ultimo_precio_tasa_envio').value)*parseInt(document.getElementById('hid_cant_pasajeros').value));
	var precio_bak=precio;
	var tasa_envio=precio;

	//total gastos agencia
	var total_gastos_agencia=document.getElementById('total_gastos_agencia').innerHTML;
	total_gastos_agencia=stripHtml(total_gastos_agencia);
	total_gastos_agencia.replace(",", ".");
	total_gastos_agencia=parseFloat(total_gastos_agencia);

	var total_cargo_tarjeta=document.getElementById('total_cargo_tarjeta').innerHTML;
	total_cargo_tarjeta=stripHtml(total_cargo_tarjeta);
	total_cargo_tarjeta.replace(",", ".");
	total_cargo_tarjeta=parseFloat(total_cargo_tarjeta);
	//total servicios agencia
	var subtotal_2=(document.getElementById('subtotal_2').innerHTML);
	subtotal_2=stripHtml(subtotal_2);
	subtotal_2=subtotal_2.replace(",", ".");
	subtotal_2=parseFloat(subtotal_2);

	var hid_total=document.getElementById('hid_total').value;
	hid_total=hid_total.replace(",", ".");
	hid_total=parseFloat(hid_total);

	var hid_gastos=document.getElementById('hid_gastos').value;
	hid_gastos=hid_gastos.replace(",", ".");
	hid_gastos=parseFloat(hid_gastos);

	var hid_gastos_bak=document.getElementById('hid_gastos_bak').value;
	hid_gastos_bak=hid_gastos_bak.replace(",", ".");
	hid_gastos_bak=parseFloat(hid_gastos_bak);

	document.getElementById('subtotal_gastos_emision').innerHTML=(tasa_envio.toFixed(2)).replace(".", ",");
	//total gastos agencia
	document.getElementById('total_gastos_agencia').innerHTML=((total_gastos_agencia+tasa_envio-precio_ant).toFixed(2)).replace(".", ",");
	//total servicios agencia
	document.getElementById('subtotal_2').innerHTML=((subtotal_2+tasa_envio-precio_ant).toFixed(2)).replace(".", ",");
	document.getElementById('hid_gastos').value=hid_gastos+tasa_envio-precio_ant;
	document.getElementById('hid_gastos_bak').value=hid_gastos_bak+tasa_envio-precio_ant;
	//el total oculto
	document.getElementById('hid_total').value=hid_total+tasa_envio-precio_ant;
	var iac=((hid_total+tasa_envio-precio_ant).toFixed(2)).replace(".", ",");
	var iac_sf=(hid_total+tasa_envio-precio_ant);
	//el total del cuadro
	document.getElementById('total_cargo_tarjeta').innerHTML=iac;
	//el total de abajo
	document.getElementById('importe_a_cobrar').innerHTML='&nbsp;<strong>'+iac+'</strong>';
	document.getElementById('ultimo_precio_tasa_envio').value=precio_porpersona;
	document.getElementById('hid_tasa').value=precio_bak;

	checkAutoLimit();
}

function mostrarreserva_pre(){
	/*try{ document.getElementById('img_reservando2').src='images/esperando.gif'; }
	catch(e){}*/
	Element.hide('container');
	Element.show('reservando2');
}

function mostrarreserva_cancel(){
	Element.show('container');
	Element.hide('reservando2');
}

function mostrarreserva(id_vuelo,id_sesion,descuento){
	if(descuento=='') descuento=0;
	var pars= '?id_vuelo=' + id_vuelo +'&id_sesion=' + id_sesion+'&descuento='+descuento;
	var aj = new Ajax.Request('datos.php',
	{
		method: 'get',
		parameters:pars,
		onSuccess: function (res) {
			$('container').replace (res.responseText);
			Element.show('container');
			Element.hide('reservando2');
		}
	});
}

function mostrarConfirmacion(respuestaxml,id_sesion,id_sesion_anterior,product_id,postdata,duracion_ida,duracion_vuelta){
	try{
		window.clearTimeout(iTimeoutID);
	}
	catch(e){}
	var pars='?foo=bar&respuesta='+respuestaxml+'&id_sesion='+id_sesion+'&id_sesion_anterior='+id_sesion_anterior+'&product_id='+product_id+'&postdata='+postdata+'&di='+duracion_ida+'&dv='+duracion_vuelta;
	var aj2 = new Ajax.Request('vuelos.confirmacion.php',
	{
		method:'post',
		parameters:pars,
		onSuccess:function(res){
			try { document.getElementById('container').innerHTML=res.responseText; }
			catch(e) { alert("Error al intentar mostrar la confirmación de su vuelo. Recibirá el bono por correo."); }
			try { Element.show('container'); }
			catch(e) { alert("Error al intentar mostrar la confirmación de su vuelo. Recibirá el bono por correo."); }
			try { Element.hide('reservando2'); }
			catch(e) {}
		}
	});
}

function MM_preloadImages() { //v3.0
	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/

/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0;  /* hex output t. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }

/*
* Perform a simple self-test to see if the VM is working
*/
function md5_vm_test(){
	return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
function core_md5(x, len)
{
	/* append padding */
	x[len >> 5] |= 0x80 << ((len) % 32);
	x[(((len + 64) >>> 9) << 4) + 14] = len;

	var a =  1732584193;
	var b = -271733879;
	var c = -1732584194;
	var d =  271733878;

	for(var i = 0; i < x.length; i += 16)
	{
		var olda = a;
		var oldb = b;
		var oldc = c;
		var oldd = d;

		a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
		d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
		c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
		b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
		a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
		d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
		c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
		b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
		a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
		d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
		c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
		b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
		a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
		d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
		c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
		b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

		a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
		d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
		c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
		b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
		a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
		d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
		c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
		b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
		a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
		d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
		c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
		b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
		a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
		d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
		c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
		b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

		a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
		d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
		c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
		b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
		a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
		d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
		c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
		b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
		a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
		d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
		c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
		b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
		a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
		d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
		c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
		b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

		a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
		d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
		c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
		b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
		a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
		d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
		c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
		b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
		a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
		d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
		c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
		b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
		a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
		d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
		c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
		b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

		a = safe_add(a, olda);
		b = safe_add(b, oldb);
		c = safe_add(c, oldc);
		d = safe_add(d, oldd);
	}
	return Array(a, b, c, d);

}

/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t)
{
	return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
	return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
	return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
	return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
	return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
* Calculate the HMAC-MD5, of a key and some data
*/
function core_hmac_md5(key, data)
{
	var bkey = str2binl(key);
	if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

	var ipad = Array(16), opad = Array(16);
	for(var i = 0; i < 16; i++)
	{
		ipad[i] = bkey[i] ^ 0x36363636;
		opad[i] = bkey[i] ^ 0x5C5C5C5C;
	}

	var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
	return core_md5(opad.concat(hash), 512 + 128);
}

/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
	var lsw = (x & 0xFFFF) + (y & 0xFFFF);
	var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
	return (msw << 16) | (lsw & 0xFFFF);
}

/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt)
{
	return (num << cnt) | (num >>> (32 - cnt));
}

/*
* Convert a string to an array of little-endian words
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
*/
function str2binl(str)
{
	var bin = Array();
	var mask = (1 << chrsz) - 1;
	for(var i = 0; i < str.length * chrsz; i += chrsz)
	bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
	return bin;
}

/*
* Convert an array of little-endian words to a string
*/
function binl2str(bin)
{
	var str = "";
	var mask = (1 << chrsz) - 1;
	for(var i = 0; i < bin.length * 32; i += chrsz)
	str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
	return str;
}

/*
* Convert an array of little-endian words to a hex string.
*/
function binl2hex(binarray)
{
	var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
	var str = "";
	for(var i = 0; i < binarray.length * 4; i++)
	{
		str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
		hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
	}
	return str;
}

/*
* Convert an array of little-endian words to a base-64 string
*/
function binl2b64(binarray)
{
	var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
	var str = "";
	for(var i = 0; i < binarray.length * 4; i += 3)
	{
		var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
		| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
		|  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
		for(var j = 0; j < 4; j++)
		{
			if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
			else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
		}
	}
	return str;
}

function Mod10(s){
	var v = "0123456789";
	var w = "";
	for (var i=0; i < s.length; i++) {
		x = s.charAt(i);
		if (v.indexOf(x,0) != -1)
		w += x;
	}
	var j = w.length / 2;
	if (j < 6.5 || j > 8 || j == 7){
		alert('Número de tarjeta de crédito incorrecto.');
		return false;
	}
	var k = Math.floor(j);
	var m = Math.ceil(j) - k;
	var c = 0;
	for (var i=0; i<k; i++) {
		a = w.charAt(i*2+m) * 2;
		c += a > 9 ? Math.floor(a/10 + a%10) : a;
	}
	for (var i=0; i<k+m; i++) c += w.charAt(i*2+1-m) * 1;
	var result=(c%10 == 0);
	if(!result) alert('Número de tarjeta de crédito incorrecto.');
	return result;
}

function limpiar_busqueda_vuelos_secundario(){
	document.getElementById('formBusc').reset();
	document.getElementById('autorelleno').value='';
	document.getElementById('autorelleno2').value='';
	document.getElementById('dc1').value='';
	document.getElementById('dc2').value='';
	document.getElementById('num_adultos').value='1';
	document.getElementById('num_ninios').value='0';
	document.getElementById('num_bebes').value='0';
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
