//
//
// Refactorización de código en Agosto de 2008
// Conjunto de funciones que procesan los formularios rellenados en "Marbesol.com"
// y realizan las pertinentes llamadas al fichero "xmlhttp.php", que se comunica
// vía XML con el servidor


//
// Función imprescindible que crea un objeto AJAX (válido para los navegadores mas usados)
var esprimerotodos=true;
function nuevoAjax() {
	var xmlhttp=false;
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
		}
	}

	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}

var xmlhttp=nuevoAjax();

//
// Funciones que se encargan de procesar las peticiones de presupuestos
//		PedirPresupuesto()
//		xmlhttpspatechangePedirPresupuesto()
//		ComponerTablaPedirPresupuesto()

function PedirPresupuesto(logged) {

	var delivery=0;
	var marriottnumber = new String();
	var marriottnumberfirst;
	if (location.pathname.match("marriot") != null) { // Estamos en marriott, capturar numero de reserva
		marriottnumber = document.formPresupuesto.marriottnumber.value;
		marriottnumberfirst = marriottnumber.substr(0,1);
//		alert(marriottnumber);
//		alert(marriottnumberfirst);
	}
	
	if (	(location.pathname.match("marriot") != null) && // Estamos en marriott y no se ha indicado un numero de reserva correcto
			(document.getElementById('firsttimemarriott').value == "false") &&
			
			(	(marriottnumber.length != 8) ||
			  
			 	((marriottnumberfirst != '8') &&
			 	(marriottnumberfirst != '9')) // AND
			) // OR
			
		) { // if
		alert ("Please specify your Marriott Vacation Club reservation number.");
	} else if (SonFechasCorrectas() == false) {
		alert ("Please review the dates");
	} else {

		OcultarForms();
		scrollToBottom();
		
		CerrarHowToJoinPopUp2();

		// Se muestra la animación de espera, y se oculta el box del "supercódigo"
		document.getElementById("Presupuesto").innerHTML='<h3>Processing</h3><br><img src="/images/espera.gif">';

		var pres = document.formPresupuesto;
		
		// Paso del fuera de horas a [0-1]
		hora = pres.hrm_rtr.options[pres.hrm_rtr.selectedIndex].value;
		if (	(hora  < 700) || (hora  > 2300)	) {
			fuera_de_horas = 1;
		} else {
			fuera_de_horas = 0;
		}

		// Se extrae el código de promoción
		if (logged == true)  {
			fidelita = document.getElementById('fidelita').value;
		} else {
			fidelita = "";
		}
		
		// Si la oficina de recogida o de entrega es 100 (delivery), se le asigna el 5 (Málaga)
		// Eso significa que es una entrega especial
		// Si es marriott Marbella o Playa andaluza, también es delivery
		pres_lgr_rtr = pres.lgr_rtr.options[pres.lgr_rtr.selectedIndex].value;
		if (pres_lgr_rtr == 100) {
			pres_lgr_rtr = 5;
			document.getElementById("comentariosreserva").value = "Please write here the location of the delivery.";
			delivery = 1;
		} else if ( (pres_lgr_rtr == 201) || (pres_lgr_rtr == 202) ) {
			document.getElementById("comentariosreserva").value = "Delivery to hotel included. ";
			delivery = 2;
		} else if (pres_lgr_rtr == 205) {
			document.getElementById("comentariosreserva").value = "";
			pres_lgr_rtr = pres.lgr_res.options[pres.lgr_res.selectedIndex].value;
			delivery = 0;
		} else {
			document.getElementById("comentariosreserva").value = "";
			delivery = 0;
		}

		pres_lgr_ent = pres.lgr_ent.options[pres.lgr_ent.selectedIndex].value;
		if (pres_lgr_ent == 100) {
			pres_lgr_ent = 5;
			if (delivery == 1){
				delivery=2;
			}
			else{
				delivery=1;
			}
		} else if (pres_lgr_ent == 205) {
			pres_lgr_ent = pres.lgr_res.options[pres.lgr_res.selectedIndex].value;
		}

		cadena = "/xmlhttp.php?a=p&"+		// Action = Presupuestar
		"logged="	+logged+"&"+ // Informacion de si el usuario está logeado
		"fidelita=" 	+fidelita+"&"+ // Código de promoción
		"registrar="+"no"+"&"+
		"lgr_rtr="	+pres_lgr_rtr+"&"+
		"lgr_ent="	+pres_lgr_ent+"&"+
		"vhc="		+pres.vhc.options[pres.vhc.selectedIndex].value+"&"+
		"day_rtr="	+pres.day_rtr.options[pres.day_rtr.selectedIndex].value+"&"+
		"msn_rtr="	+pres.msn_rtr.options[pres.msn_rtr.selectedIndex].value+"&"+
		"hrm_rtr="	+pres.hrm_rtr.options[pres.hrm_rtr.selectedIndex].value+"&"+
		"day_ent="	+pres.day_ent.options[pres.day_ent.selectedIndex].value+"&"+
		"msn_ent="	+pres.msn_ent.options[pres.msn_ent.selectedIndex].value+"&"+
		"hrm_ent="	+pres.hrm_ent.options[pres.hrm_ent.selectedIndex].value+"&"+
		"num_dias="	+CalculaNumeroDeDias()+"&"+
		"baby="	    +pres.baby.options[pres.baby.selectedIndex].value+"&"+
		"booster="	+pres.booster.options[pres.booster.selectedIndex].value+"&"+
		"fdh="  	+fuera_de_horas+"&"+
		"extra_gps="		+pres.extra_gps.checked+"&"+
		"extra_driver="		+"false"+"&"+
		"extra_insurance="	+pres.extra_insurance.checked+"&"+
		"extra_fine="		+"false"+"&"+
		"delivery="  		+delivery;
	
		//document.getElementById("Presupuesto").innerHTML = cadena;
		// NOE 13-04-10 TODOS LOS GRUPOS
		if(pres.vhc.options[pres.vhc.selectedIndex].value=='99'){
		
			grupo_todos='99';
			PedirTodos('A');
			
		}
		else{
		xmlhttp.open("GET",	cadena, true);

		xmlhttp.onreadystatechange=xmlhttpstatechangePedirPresupuesto;
		xmlhttp.send(null);
		}
		// END NOE
	} // if
	
	// La primera vez que se entra en el script, no debe alertar sobre el numero de reserva
	// de Marriott incorrecto
	if (location.pathname.match("marriot") != null) { // Estamos en marriott
		document.getElementById("firsttimemarriott").value = false;
	}

} // PedirPresupuesto


function xmlhttpstatechangePedirPresupuesto() {
	if (xmlhttp.readyState==4) { // Transacción finalizada
	
		if (xmlhttp.status == 200) { // Estado correcto
			
			// Solo se muestran presupuestos de reservas de menos de 30 días
			num_dias = CalculaNumeroDeDias();
//			if (num_dias <= 30) {
			if (true) {
	
				// Se recoge el documento XML con la respuesta, ya sea 
				// satisfactoria, o con el mensaje de error correspondiente
				var xmlDoc=xmlhttp.responseXML.documentElement;
				
				// Ahora se compone la tabla HTML, a partir del XML
				var tabla = ComponerTablaPedirPresupuesto(xmlDoc);
				
				// Finalmente, se coloca todo lo anterior en el cuadro ajax
				document.getElementById("Presupuesto").innerHTML = tabla;
	
				// Se hace la llamada AJAX para el upgrade
				var pres = document.formPresupuesto;
				grupo_upgrade = pres.vhc.options[pres.vhc.selectedIndex].value;
				
				// Se inicializa el cuadro del upgrade con un retorno de carro, y
				// se hace la llamada correspondiente
				PedirUpgrade();
	
				scrollToBottom();
			
			} else {
				var errornum = "Reserva de mas de 30 dias";
				var tabla = DetallesError(errornum);

				// Finalmente, se coloca todo lo anterior en el cuadro ajax
				document.getElementById("Presupuesto").innerHTML = tabla;
			} // if num_dias <= 30

		} else {
			
			// Mostrar la posibilidad de rellenar el formulario para ser procesado manualmente
			alert('There were problems connecting with the server.');

			// Lo juntamos todo en una tabla
			var tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><td align="center">';
			tabla = tabla + '<h3>At this moment we are not able to confirm your booking. Please, fill the form with all the details and we will contact you as soon as possible. You can also contact us on</br> (0034) 952 233 507</h3>';
			tabla = tabla + '<INPUT TYPE="button" VALUE="Fill the form" onClick="JavaScript:CambiarVisibilidadFormularioReservaOffline();" class="booknow" !disabled></td></tr></table>';
			
			document.getElementById("Presupuesto").innerHTML = tabla;
			
			// Se anota el motivo de la reserva offline
			document.getElementById('reasonoffline').value = 'There were problems connecting with the server';
			
		} // if (xmlhttp.readyState==4)
		
	} // if (xmlhttp.status == 200)
	
} // xmlhttpstatechangePedirPresupuesto


function ComponerTablaPedirPresupuesto(xmlDoc) {
//BEGIN MSOLER 01/02/2010 MOSTRAR TODOS LOS GRUPOS
/*Comprobamos que el xml devuelto tenga un solo nodo envoltorio o mas de 1, si es asi siginifica que se ha seleccionado
la opcion de mostrar todos los grupos por lo que procesaremos el xml de forma diferente*/

var total = xmlDoc.getElementsByTagName('envoltorio').length;
	if (total>1)
	{
		//alert('Hay mas de un elemento envoltorio '+xmlDoc.getElementsByTagName('envoltorio').length);
	}
	else{
	// Lo primero a mirar es si se puede reservar
	if (xmlDoc.getElementsByTagName("reservable")[0].childNodes[0].nodeValue > 0) {
//		document.getElementById("reservar").disabled=false;

		// Imagen, familia y descripción del vehículo seleccionado
		vehic = document.getElementById("combovehiculos").value;
		
		lugar = document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value;

		// Se obtienen los valores del vehículo en particular
		var detalles = {familia:"", foto:"", descripcion:"", extras:""};
		DetallesVehiculo(vehic, lugar, detalles);
		
		// Precio del alquiler
		 precio = xmlDoc.getElementsByTagName("precio")[0].childNodes[0].nodeValue;
		
		// Precio del alquiler con el descuento aplicado
		precio_con_descuento = xmlDoc.getElementsByTagName("precio_con_descuento")[0].childNodes[0].nodeValue;
		//BEGIN RPUGA 17-02-10
		// Precio del alquiler con el descuento por tarjeta
		precio_tarjeta = xmlDoc.getElementsByTagName("precio_tarjeta")[0].childNodes[0].nodeValue;
		//END RPUGA 17-02-10
		// Precio de los extras devuelto por "xmlhttp"
		precio_extras = xmlDoc.getElementsByTagName("precio_extras")[0].childNodes[0].nodeValue;//TOTAL DE LOS EXTRAS
		var precio_baby= parseFloat(xmlDoc.getElementsByTagName("precio_baby")[0].childNodes[0].nodeValue);
		var precio_booster=parseFloat(xmlDoc.getElementsByTagName("precio_booster")[0].childNodes[0].nodeValue);
		var precio_fdh=parseFloat(xmlDoc.getElementsByTagName("precio_fdh")[0].childNodes[0].nodeValue);
		var precio_gps=parseFloat(xmlDoc.getElementsByTagName("precio_gps")[0].childNodes[0].nodeValue);
		var precio_delivery=parseFloat(xmlDoc.getElementsByTagName("precio_delivery")[0].childNodes[0].nodeValue);
		
		var cambio_libras=parseFloat(xmlDoc.getElementsByTagName("cambio_libras")[0].childNodes[0].nodeValue);
		
		
		
		// Precio total
		precio_con_extras = (parseFloat(precio_con_descuento) + parseFloat(precio_extras)).toFixed(2);
		precio_libras=(parseFloat(cambio_libras)*parseFloat(precio_con_extras)).toFixed(2);

		// BEGIN RPUGA 17-02-10
		precio_tarjeta_con_extras = (parseFloat(precio_tarjeta) + parseFloat(precio_extras)).toFixed(2);
		precio_tarjeta_libras=(parseFloat(cambio_libras)*parseFloat(precio_tarjeta_con_extras)).toFixed(2);
		// END RPUGA 17-02-10
		// Cliente logueado
		logged = xmlDoc.getElementsByTagName("logged")[0].childNodes[0].nodeValue;
		
		// Cliente de Marriott
		es_marriott = (	(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 201) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 202) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 205) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 215) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 225) );
		
		// Número de dias de la reserva
		num_dias = CalculaNumeroDeDias();
		if (num_dias == 1) {
			texto_dias = num_dias + ' day ';
		} else {
			texto_dias = num_dias + ' days ';
		}
		
		// Tipo de la pecitión (cofirmable u onrequest)
		if (xmlDoc.getElementsByTagName("reservable")[0].childNodes[0].nodeValue==1) {
			tipo_peticion = "OnRequest";
		} else if (xmlDoc.getElementsByTagName("reservable")[0].childNodes[0].nodeValue==2) {
			tipo_peticion = "Confirmable";
		}

		// Lo juntamos todo en una tabla
		
		// Datos del vehiculo y precios
		// BEGIN RPUGA 15-02-10 
		var tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><tr><td><iframe src="/admin/pasos/pedirpresupuesto.html" height="1px" width="1px" frameborder="0"></iframe></td></tr>';
		if ((tipo_peticion== "Confirmable") && (es_marriott!=true)&&(precio_delivery==0)&&(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 105)){
			tabla=tabla + '<td align="left" valign="center">' + detalles.familia + '<br />' + detalles.foto + '</td>' +
			'<td align="center" valign="center" width="20%"><font size="1">' + detalles.descripcion + '</font><br />' + detalles.extras +'</td>' +
			'<td align="center" valign="bottom" width="25%"></td>'+	
			'<td align="right" valign="bottom" width="45%">';
		}
		else{
			tabla= tabla + 		'<td align="left" valign="bottom">' + detalles.familia + '<br />' + detalles.foto + '</td>' +
		'<td align="center" valign="bottom"><font size="1">' + detalles.descripcion + '</font><br />' + detalles.extras + '</td>' +
		'<td align="right" valign="bottom" width="30%">';
		}
		// END RPUGA 15-02-10
		if (logged == 'true') { // Se muestra el precio normal y el VIP
			tabla = tabla + '<font color=#1F97BA><b>' + texto_dias +'<s>'+ precio + ' &#8364;</s></b></font><br>';
			tabla = tabla + '<font color=#12576B><b>VIP price ' + precio_con_descuento + ' &#8364;</b></font><br>';
		} else if (es_marriott) { // Se muestra el precio normal y el de Marriott
			tabla = tabla + '<font color=#1F97BA><b><s>' + texto_dias + precio + ' &#8364;</s></b></font><br>';
			tabla = tabla + '<font color=#12576B><b>Your price ' + precio_con_descuento + ' &#8364;</b></font><br>';
		} else {				// Se muestra solamente el precio normal
			tabla = tabla + '<font color=#1F97BA size=\'3\'><b> ' + texto_dias +'<br />'+ precio + ' &#8364;</b></font><br>';
		}
		if(precio_baby>0){
			tabla = tabla + '<font color=#1F97BA size=\'1\'><b>Baby Seat ' + precio_baby + ' &#8364;</b></font><br>';
		}
		if(precio_booster>0){
			tabla = tabla + '<font color=#1F97BA size=\'1\'><b>Booster Seat ' + precio_booster + ' &#8364;</b></font><br>';
		}
		if(precio_gps>0){
			tabla = tabla + '<font color=#1F97BA size=\'1\'><b>GPS ' + precio_gps + ' &#8364;</b></font><br>';
		}
		if(precio_delivery>0){
			tabla = tabla + '<font color=#1F97BA size=\'1\'><b>Delivery ' + precio_delivery + ' &#8364;</b></font><br>';
		}
		if(precio_fdh>0){
			tabla = tabla + '<font color=#1F97BA size=\'1\'><b>Out of time'  + precio_fdh + ' &#8364;</b></font><br>';
		}
		tabla=tabla+'<br>';
		//tabla = tabla + '<font color=#1F97BA><b>Extras ' + precio_extras + ' &#8364;</b></font><br>';
		if(!((tipo_peticion== "Confirmable")&& (es_marriott!=true)&&(precio_delivery==0)&&(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 105))){
		tabla = tabla + '<font color=#12576B size=\'4\'><b>Total <br>' + precio_con_extras + ' &#8364;</b></font><br>';
		tabla = tabla + '<font color=#12576B size=\'2\'><b>(' + precio_libras + ' &pound;)</b></font><br>';
		}
		// Muestra si es onrequest o no
		// tabla = tabla + '<tr><td align="center" colspan="3">' + tipo_peticion + '</td></tr>';
		
		// Reserva haciendose del club (solo en malaga y si no esta logueado)
//		if 	(	(logged == "false") &&
//				(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 10) &&
//				(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 105)) {

		// Reserva haciendose del club (solo si no esta logueado)
		if 	(	(logged == "false") &&
				(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 105) &&
				(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 201) &&
				(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 202) &&
				(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 205) &&
				(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 215) &&
				(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 225)) {
			// BEGIN RPUGA 15-02-10
			if (tipo_peticion=="OnRequest"|| precio_delivery>0){
					tabla = tabla + '<tr height="45">\
							<td align="left" colspan="2"><img src="/images/jointheclub.jpg"></td>\
							<td align="right" valign="top" colspan="1"><input NAME="booknow" id="booknow" type="button" VALUE="Book now"  onClick="JavaScript:CambiarVisibilidadFormularioReserva(true,true);" class="input-bold"></td>\
							</tr>';
			}
			else{
				// BEGIN RPUGA 15-02-10 
				tabla = tabla + '<tr height="45">\
							<td align="left" colspan="2"><img src="/images/jointheclub.jpg"></td>\
							<td align="center" valign="top" colspan="1"><font color=#12576B size=\'4\'><b>Total<br /> ' + precio_tarjeta_con_extras + ' &#8364;</b></font><br>' +	'<font color=#12576B size=\'2\'><b>(' + precio_tarjeta_libras + ' &pound;)</b></font><br><input NAME="booknow" id="booknow" type="button" VALUE="Pay&#13;&#10;Online"  onClick="JavaScript:CambiarVisibilidadFormularioReserva(true,false);" class="input-bold2"></td>\
							<td align="center" valign="top" colspan="1"><font color=#12576B size=\'4\'><b>Total <br>' + precio_con_extras + ' &#8364;</b></font><br><font color=#12576B size=\'2\'><b>(' + precio_libras + ' &pound;)</b></font><br><input NAME="booknow" id="booknow" type="button" VALUE="Pay&#13;&#10On Arrival"  onClick="JavaScript:CambiarVisibilidadFormularioReserva(true,true);" class="input-bold2"></td>\
							</tr>';
			}	//END RPUGA 15-02-10 
				
		} else {
			if (tipo_peticion=="OnRequest" || precio_delivery>0){
					tabla = tabla + '<tr><td align="right" colspan="3"><INPUT TYPE="button" VALUE="Book now" onClick="JavaScript:CambiarVisibilidadFormularioReserva(false,true);" name="booknow" id="booknow" class="booknow" !disabled></td></tr>';
					tabla = tabla + '</table>';
			}
			else{
				if ((!es_marriott) &&(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 105)){
					tabla = tabla + '<tr><td colspan="1"></td><td align="center" valign="top" colspan="2"><font color=#12576B size=\'4\'><b>Total ' + precio_tarjeta_con_extras + ' &#8364;</b></font><br><font color=#12576B size=\'2\'><b>(' + precio_tarjeta_libras + ' &pound;)</b></font><br><input NAME="booknow" id="booknow" type="button" VALUE="Pay&#13;&#10;Online"  onClick="JavaScript:CambiarVisibilidadFormularioReserva(false,false);" class="input-bold2"></td>\
							<td colspan="2" align="center" valign="top" colspan="1"><font color=#12576B size=\'4\'><b>Total ' + precio_con_extras + ' &#8364;</b></font><br><font color=#12576B size=\'2\' ><b>(' + precio_libras + ' &pound;)</b></font><br><input NAME="booknow" id="booknow" type="button" VALUE="Pay&#13;&#10On Arrival"  onClick="JavaScript:CambiarVisibilidadFormularioReserva(false,true);" class="input-bold2"></td></tr>';
					tabla = tabla + '</table>';
				}
				else{
					tabla = tabla + '<tr><td align="right" colspan="3"><INPUT TYPE="button" VALUE="Book now" onClick="JavaScript:CambiarVisibilidadFormularioReserva(false,true);" name="booknow" id="booknow" class="booknow" !disabled></td></tr>';
					tabla = tabla + '</table>';
				}
			}
					
		}
		// END RPUGA 15-02-10
		// Informacion del extra por entrega tardia
		if 	(	(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 201) &&
				(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 202) &&
				(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 205) &&
				(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 215) &&
				(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 225)) {
			tabla = tabla + '<tr><td align="center" colspan="3"><font size="1">*If return time is more than two hours later than pick up time, an extra day is added to the price.</font></td></tr>';
		} else {
			tabla = tabla + '<tr><td align="center" colspan="3"><font size="1">*If return time is more than two hours later than pick up time, an extra day is added to the price.<br />Full insurance is included. Please see the rental terms.</font></td></tr>';
		}

/*		// Reserva sin hacerse del club
		tabla = tabla + '<tr><td align="right" colspan="3"><INPUT TYPE="button" VALUE="Book now" onClick="JavaScript:CambiarVisibilidadFormularioReserva(false);" name="booknow" id="booknow" class="booknow" !disabled></td></tr>';
		tabla = tabla + '</table>';
*/		
		// No hay offline
		document.getElementById('reasonoffline').value = '';

	} else { // "reservable" == 0
	
		// Si la reserva pisa algún dia "chungo", mostrar un mensaje son opcion de offline
		xmlhttp.open("GET",	"/admin/stopdays_xmlhttp.php", false);
		xmlhttp.send(null);
		var xmlStopDays=xmlhttp.responseXML.documentElement;

		var x = xmlStopDays.getElementsByTagName("date");
		var x_filtrada = new Array();
		for (var i = 0; i < x.length; i++) {
			if (SolapaDia(x[i].childNodes[0].nodeValue)) {
				x_filtrada.push(x[i]);
			}
		} // For dejar solo los dias que solapen con el stop-sale
		if (x_filtrada.length > 0) {
			tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><td align="center">' +
			'<h3>We are sorry to inform you that the car you have selected is&nbsp;' +
			'<span style="color:#000000">not available</span>&nbsp;for the folowing day/s:';
			for (var i = 0; i < x_filtrada.length; i++) {
				if ( (x_filtrada.length > 1) && (i > 0) ) { tabla = tabla + ',';}
				tabla = tabla + ' <span style="color:#000000">' + x_filtrada[i].childNodes[0].nodeValue + '</span>';
			}
			tabla = tabla + '. Please, modify your pickup and return dates accordingly. ' +
			'You can also contact us on</br> (00 34) 952 233 507</h3></td></tr></table>';
		} else {
			// En otro caso, mostrar el mensaje offline del caso general
			var errornum = xmlDoc.getElementsByTagName("ERRORNUM")[0].childNodes[0].nodeValue;
			
			var tabla = DetallesError(errornum);

		} // if hay dias "chungos"
		
	} // if reservable

	return tabla;
	}
} // ComponerTablaPedirPresupuesto

function SolapaDia(fecha_solap) {
	
	day_rtr = document.formPresupuesto.day_rtr.options[document.formPresupuesto.day_rtr.selectedIndex].value;
	msn_rtr = document.formPresupuesto.msn_rtr.options[document.formPresupuesto.msn_rtr.selectedIndex].value;
	day_ent = document.formPresupuesto.day_ent.options[document.formPresupuesto.day_ent.selectedIndex].value;
	msn_ent = document.formPresupuesto.msn_ent.options[document.formPresupuesto.msn_ent.selectedIndex].value;
	
	// Separamos los valores de las fechas
	anno_ini = Math.floor(msn_rtr / 12); // Porque msn = (año * 12) + (mes - 1)
	mes_ini  = (msn_rtr % 12) + 1;
	dia_ini  = parseInt(day_rtr);
	
	anno_fin = Math.floor(msn_ent / 12); // Porque msn = (año * 12) + (mes - 1)
	mes_fin  = (msn_ent % 12) + 1;
	dia_fin  = parseInt(day_ent);

	// Separamos las fecha de posible solapamiento
	anno_solap = parseInt(fecha_solap.substring(0, 4));
	mes_solap  = parseInt(fecha_solap.substring(5, 7));
	dia_solap  = parseInt(fecha_solap.substring(8, 10));
	
	// Si la fecha de inicio es menor a la consultada
	ini_menor_que_solap =	(  (anno_ini < anno_solap)								||
							(  (anno_ini == anno_solap)	&& (mes_ini < mes_solap)  ) ||
							(  (mes_ini  == mes_solap)	&& (dia_ini <= dia_solap)  )	);
	
	// Si la fecha consultada es menor a la final
	solap_menor_que_fin =	(  (anno_solap < anno_fin)								||
							(  (anno_solap == anno_fin)	&& (mes_solap < mes_fin)  ) ||
							(  (mes_solap  == mes_fin)	&& (dia_solap <= dia_fin)  )	);
	
//	alert(anno_ini + " " + mes_ini + " " + dia_ini + "." + anno_solap + " " + mes_solap + " " + dia_solap + "." + anno_fin + " " + mes_fin + " " + dia_fin + "." + ini_menor_que_solap + " " + solap_menor_que_fin);
	return ini_menor_que_solap && solap_menor_que_fin;

return true;
}


//
// Funciones que se encargan de procesar las peticiones de reservas
//		ConfirmarReserva()
//		xmlhttpspatechangeConfirmarReserva()
//		ComponerTablaConfirmarReserva()

function ConfirmarReserva(logged) {
		
	var correo_valido;
	var delivery=0;

	var pres = document.formPresupuesto;
	pres_lgr_rtr = pres.lgr_rtr.options[pres.lgr_rtr.selectedIndex].value;
	if ( (pres_lgr_rtr == 201) || (pres_lgr_rtr == 202) || (pres_lgr_rtr == 205) ) {
		correo_valido = true;
	} else {
		if (document.getElementById('fidelita').value == '') { // Fuera del club
			correo_valido = ComprobarCorreo(false);
		} else {
			correo_valido = true;
		}
	}

	if (correo_valido) {
		
		var pres = document.formPresupuesto;
		
		if ((pres.nombre.value.length < 8) 	||
			(pres.movil.value == '')  		||
			(pres.email.value == '')  		||
			(pres.vuelo.value == '')	){
	
			alert ("Fields marked with * are required! (Name must be eight characters or more)");
		
		} else if (SonFechasCorrectas() == false) {
			alert ("Please review the dates");
		} else if (EsFechaViable() == false) {
			alert ("After 8:00 PM, you can only make bookings for the next day, at 10:00 AM or later.");
		} else if (EsFechaConMargen() == false) {
			alert ("Online bookings should be made with a minimum of two hours.");
		} else {
			OcultarForms();
	
			// Se extrae el código de promoción
			if (logged == true)  {
				fidelita = document.getElementById('fidelita').value;
			} else {
				fidelita = "";
			}

			// Se muestra el mensaje de reserva
			document.getElementById("Presupuesto").innerHTML='<h3>Booking</h3><br><img src="/images/espera.gif">';
	
			// Si la oficina de recogida o de entrega es superior a 100, se le resta 100
			// Eso significa que es una entrega especial
			pres_lgr_rtr = pres.lgr_rtr.options[pres.lgr_rtr.selectedIndex].value;
			if (pres_lgr_rtr == 100) {
				pres_lgr_rtr = 5;
				delivery = 1;
			} else if ( (pres_lgr_rtr == 201) || (pres_lgr_rtr == 202) ){
				delivery = 2;
			} else if (pres_lgr_rtr == 205) {
				pres_lgr_rtr = pres.lgr_res.options[pres.lgr_res.selectedIndex].value;
				delivery = 0;
			} else {
				delivery = 0;
			}
			pres_lgr_ent = pres.lgr_ent.options[pres.lgr_ent.selectedIndex].value;
			if (pres_lgr_ent == 100) {
				pres_lgr_ent = 5;
				if (delivery == 1){
					delivery=2;
				}
				else{
					delivery=1;
				}
			} else if (pres_lgr_ent == 205) {
				pres_lgr_ent = pres.lgr_res.options[pres.lgr_res.selectedIndex].value;
			}
			//BEGIN RPUGA 24-02-10
			es_marriott = (	(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 201) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 202) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 205) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 215) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 225) );
			if ((es_marriott)||(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 105)){
				pago_tarjeta=false;
			}
			else{
				pago_tarjeta=document.formPresupuesto.pago[1].checked;
			}
			//END RPUGA 24-02-10

			cadena = "/xmlhttp.php?a=r&"+
			"logged="		+	logged+"&"+ // Informacion de si el usuario está logeado
			"fidelita=" 		+	fidelita+"&"+ // Código de promoción
			"registrar="	+	document.getElementById('registroreserva').value+"&"+
			"lgr_rtr="		+	pres_lgr_rtr+"&"+
			"lgr_ent="		+	pres_lgr_ent+"&"+
			"vhc="			+	pres.vhc.options[pres.vhc.selectedIndex].value+"&"+
			"day_rtr="		+	pres.day_rtr.options[pres.day_rtr.selectedIndex].value+"&"+
			"msn_rtr="		+	pres.msn_rtr.options[pres.msn_rtr.selectedIndex].value+"&"+
			"hrm_rtr="		+	pres.hrm_rtr.options[pres.hrm_rtr.selectedIndex].value+"&"+
			"day_ent="		+	pres.day_ent.options[pres.day_ent.selectedIndex].value+"&"+
			"msn_ent="		+	pres.msn_ent.options[pres.msn_ent.selectedIndex].value+"&"+
			"hrm_ent="		+	pres.hrm_ent.options[pres.hrm_ent.selectedIndex].value+"&"+
			"num_dias="		+	CalculaNumeroDeDias()+"&"+
			"baby="	    	+	pres.baby.options[pres.baby.selectedIndex].value+"&"+
			"booster="		+	pres.booster.options[pres.booster.selectedIndex].value+"&"+
			"fdh="  		+	fuera_de_horas+"&"+
			
			"extra_gps="	+	pres.extra_gps.checked+"&"+
			"extra_driver="	+	"false"+"&"+
			"extra_insurance="+	pres.extra_insurance.checked+"&"+
			"extra_fine="	+	"false"+"&"+
			
			"customeremail="+	document.getElementById("useremail").value+"&"+
			"customerpass=" +	document.getElementById("userpass").value+"&"+
	
			"idioma=" 		+	"en&"+
			"nombre=" 		+	pres.nombre.value+"&"+
			"movil="  		+	pres.movil.value+"&"+
			"email="   		+	pres.email.value+"&"+
			"vuelo="		+	pres.vuelo.value+"&"+
			"comentarios="	+	"Tel:" + pres.movil.value + ". " + document.getElementById("comentariosreserva").value+"&"+
			"delivery="  	+	delivery+"&"+
			//BEGIN MSOLER/RPUGA 10/02/2010 VISA
			"tarjeta="      +   pago_tarjeta;
			//END MSOLER/RPUGA 10/02/2010
			
			
//			document.getElementById("Presupuesto").innerHTML=cadena;
	
			if ((delivery == 1)||(delivery==2)) {
				ConfirmarReservaDelivery(cadena, logged, fidelita, document.getElementById('registroreserva').value);
			} else {
				xmlhttp.open("GET",	cadena ,true);
		
				xmlhttp.onreadystatechange=xmlhttpstatechangeConfirmarReserva;
				xmlhttp.send(null);
			} // if delivery
	
		}  // if campos rellenos
		
	} // if correo válido

}

	
function ConfirmarReservaDelivery(cadena, logged, fidelita, registrar) {

	cadena = cadena.replace("xmlhttp.php?a=r", "offlinemail.php?a=o");
	
	reasonoffline = "DELIVERY PENDIENTE DE CONFIRMAR.";
	
	var pres = document.formPresupuesto;
	var pres_lgr_rtr = pres.lgr_rtr.options[pres.lgr_rtr.selectedIndex].value;

	if (pres_lgr_rtr == 201) {
		reasonoffline = reasonoffline + " Marriot Marbella.";
	} else if (pres_lgr_rtr == 202) {
		reasonoffline = reasonoffline + " Marriot Playa Andaluza.";
	}
	if (logged == true) {
		reasonoffline = reasonoffline + " Usuario que reserva desde DENTRO del club(" + fidelita + "). Aplicar el descuento corespondiente."
	}
	if (registrar == "si") {
		reasonoffline = reasonoffline + " Usuario NUEVO en el club. Aplicar descuento."
	}
	cadena = cadena + "&reasonoffline=" + reasonoffline;

	document.location.href = cadena; // Carga una nueva página, usando "cadena" como url

}


function xmlhttpstatechangeConfirmarReserva() {
	if (xmlhttp.readyState==4) { // Transacción finalizada
	
		if (xmlhttp.status == 200) { // Estado correcto
			
			// Se recoge el documento XML con la respuesta, ya sea 
			// satisfactoria, o con el mensaje de error correspondiente
			var xmlDoc=xmlhttp.responseXML.documentElement;
			
			// Ahora se compone la tabla HTML, a partir del XML
			var tabla = ComponerTablaConfirmarReserva(xmlDoc);
			
			// Finalmente, se coloca todo lo anterior en el cuadro ajax
			document.getElementById("Presupuesto").innerHTML = tabla;
			scrollToBottom();
			
		} else {
			
			// Mostrar la posibilidad de rellenar el formulario para ser procesado manualmente
			alert('There were problems connecting with the server.');
			
			// Lo juntamos todo en una tabla
			var tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><td align="center">';
			tabla = tabla + '<h3>At this moment we are not able to confirm your booking. Please, fill the form with all the details and we will contact you as soon as possible. You can also contact us on</br> (0034) 952 233 507</h3>';
			tabla = tabla + '<INPUT TYPE="button" VALUE="Fill the form" onClick="JavaScript:CambiarVisibilidadFormularioReservaOffline();" class="booknow" !disabled></td></tr></table>';
			
			document.getElementById("Presupuesto").innerHTML = tabla;
			
			// Se anota el motivo de la reserva offline
			document.getElementById('reasonoffline').value = 'There were problems connecting with the server';
			
		} // if (xmlhttp.readyState==4)
		
	} // if (xmlhttp.status == 200)
	
} // xmlhttpstatechangeConfirmarReserva


function ComponerTablaConfirmarReserva(xmlDoc) {

	var reservado = xmlDoc.getElementsByTagName("reservado")[0].childNodes[0].nodeValue;
	
	if (	(reservado == "2") || (reservado == "1")	) { // Reserva procesada de algún tipo
	
		var tabla = '';

		var par = new Array();
		
		par['nombre'] = xmlDoc.getElementsByTagName('nombre')[0].childNodes[0].nodeValue;
		par['email'] = xmlDoc.getElementsByTagName('email')[0].childNodes[0].nodeValue;
		par['telefono'] = xmlDoc.getElementsByTagName('telefono')[0].childNodes[0].nodeValue;
		par['llegada'] = xmlDoc.getElementsByTagName('llegada')[0].childNodes[0].nodeValue;
		if (xmlDoc.getElementsByTagName("comentarios")[0].childNodes[0] != null) {
			par["comentarios"]	= xmlDoc.getElementsByTagName("comentarios")[0].childNodes[0].nodeValue;
		} else {
			par["comentarios"] = "";
		}

		
		par['lgr_rtr_code'] = xmlDoc.getElementsByTagName('lgr_rtr_code')[0].childNodes[0].nodeValue;
		par['lgr_rtr'] = xmlDoc.getElementsByTagName('lgr_rtr')[0].childNodes[0].nodeValue;
		par['lgr_ent'] = xmlDoc.getElementsByTagName('lgr_ent')[0].childNodes[0].nodeValue;
		par['voucher'] = xmlDoc.getElementsByTagName('voucher')[0].childNodes[0].nodeValue;
		par['categoria_vehiculo'] = xmlDoc.getElementsByTagName('categoria_vehiculo')[0].childNodes[0].nodeValue;
		par['fecha_recogida'] = xmlDoc.getElementsByTagName('fecha_recogida')[0].childNodes[0].nodeValue;
		
		par['hora_recogida'] = xmlDoc.getElementsByTagName('hora_recogida')[0].childNodes[0].nodeValue;
		par['fecha_entrega'] = xmlDoc.getElementsByTagName('fecha_entrega')[0].childNodes[0].nodeValue;
		par['hora_entrega'] = xmlDoc.getElementsByTagName('hora_entrega')[0].childNodes[0].nodeValue;
		if (xmlDoc.getElementsByTagName("total_orig")[0].childNodes[0] != null) {
			par["total_orig"]	= xmlDoc.getElementsByTagName("total_orig")[0].childNodes[0].nodeValue;
		} else {
			par["total_orig"] = "";
		}
		par['total'] = xmlDoc.getElementsByTagName('total')[0].childNodes[0].nodeValue;
		
		par['baby'] = xmlDoc.getElementsByTagName('baby')[0].childNodes[0].nodeValue;
		par['booster'] = xmlDoc.getElementsByTagName('booster')[0].childNodes[0].nodeValue;
		par['extras'] = xmlDoc.getElementsByTagName('extras')[0].childNodes[0].nodeValue;
		if (xmlDoc.getElementsByTagName("textoconextras_orig")[0].childNodes[0] != null) {
			par["textoconextras_orig"]	= xmlDoc.getElementsByTagName("textoconextras_orig")[0].childNodes[0].nodeValue;
		} else {
			par["textoconextras_orig"] = "";
		}
		par['textoconextras'] = xmlDoc.getElementsByTagName('textoconextras')[0].childNodes[0].nodeValue;
		
		par['extra_gps'] = xmlDoc.getElementsByTagName('extra_gps')[0].childNodes[0].nodeValue;
		par['extra_insurance'] = xmlDoc.getElementsByTagName('extra_insurance')[0].childNodes[0].nodeValue;
		par['mensaje_customer'] = xmlDoc.getElementsByTagName('mensaje_customer')[0].childNodes[0].nodeValue;
		
		//BEGIN MSOLER-RPUGA 03/02/2010 VISA
		//Una vez dentro de aqui la reserva esta dentro del carplus, si el pago es con visa llamamos a nuestro PHP para realizar el pago
		//Si se ha seleccionado pago con visa...
		//BEGIN RPUGA 24-02-2010
		es_marriott = (	(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 201) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 202) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 205) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 215) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 225) );
		if ((!es_marriott)&&(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 105)&&(document.formPresupuesto.pago[1].checked))
		{
			
			// Se crea un formulario POST que va a contener toda la informacion
			// ya recopilada en el array "par"
			//alert(reservado);
			par['idioma']="en"; 
			par['reservado']=reservado;
			var pres = document.formPresupuesto;
			par['hora_rtr']=pres.hrm_rtr.options[pres.hrm_rtr.selectedIndex].value;
			par['mes_ano_rtr']=pres.msn_rtr.options[pres.msn_rtr.selectedIndex].value;
			par['dia_rtr']=pres.day_rtr.options[pres.day_rtr.selectedIndex].value;
			par['hora_ent']=pres.hrm_ent.options[pres.hrm_ent.selectedIndex].value;
			par['mes_ano_ent']=pres.msn_ent.options[pres.msn_ent.selectedIndex].value;
			par['dia_ent']=pres.day_ent.options[pres.day_ent.selectedIndex].value;
			par['precio_servidor'] = xmlDoc.getElementsByTagName('precio')[0].childNodes[0].nodeValue;
			par['precio_cliente'] = xmlDoc.getElementsByTagName('precio_con_descuento')[0].childNodes[0].nodeValue;
			par['vhc']=pres.vhc.options[pres.vhc.selectedIndex].value;
			par['lgr_ent_code']=pres_lgr_ent;
			if (xmlDoc.getElementsByTagName("coment")[0].childNodes[0] != null) {
			par["coment"]	= xmlDoc.getElementsByTagName("coment")[0].childNodes[0].nodeValue;
			} else {
			par["coment"] = "";
			}
			// BEGIN RPUGA 08-03-10
			par["coment_form"]=document.formPresupuesto.comentariosreserva.value;
			// END RPUGA 08-03-10
			var formu = document.createElement("form");
			
			formu.name = "formu";formu.target = "_self";formu.method = "post";
			if ((reservado == "2")	)
			{
				//Si la reserva esta confirmada // BEGIN RPUGA 19-02-10 CAMBIAR LUEGO
				//formu.action = "/admin/pasarela/confirmacion.php";
				formu.action = "http://www.marbesol.com/admin/pasarela/confirmacion.php";
			}
			else
			{
				//Si es una reserva ON-REQUEST
				formu.action = "/onrequest.php?lgr_rtr=" + par['lgr_rtr_code'];
			}
			// Se crea un "input type text" por cada elemento en el array
			for (x in par) {
				inserta_input(formu, x, par[x]);
			}
			
			// Se añade el formulario al documento y se envia
			document.body.appendChild(formu);
			document.forms[2].submit(); // Es [2] porque ya hay otros dos formularios en el html			
		}
		else{
		// Se crea un formulario POST que va a contener toda la informacion
		// ya recopilada en el array "par"
		var formu = document.createElement("form");
		
		formu.name = "formu";formu.target = "_self";formu.method = "post";
		if (reservado == "2") { // Llamar al proceso de una reserva Confirmada
			formu.action = "/confirmacion.php?lgr_rtr=" + par['lgr_rtr_code'];
		} else if (reservado == "1") { // Llamar al proceso de una reserva OnRequest
			formu.action = "/onrequest.php?lgr_rtr=" + par['lgr_rtr_code'];
		}
		
		// Se crea un "input type text" por cada elemento en el array
		for (x in par) {
			inserta_input(formu, x, par[x]);
		}
		
		// Se añade el formulario al documento y se envia
		document.body.appendChild(formu);
		document.forms[2].submit(); // Es [2] porque ya hay otros dos formularios en el html
		}
		//END MSOLER-RPUGA 03/02/2010
	} else if (reservado == "0") { // Error en la reserva (indicado en ERRORNUM)

		// Lo juntamos todo en una tabla
		var tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><td align="center">';
		tabla = tabla + '<h3>At this moment we are not able to confirm your booking. Please, fill the form with all the details and we will contact you as soon as possible. You can also contact us on</br> (0034) 952 233 507</h3>';
		tabla = tabla + '<INPUT TYPE="button" VALUE="Fill the form" onClick="JavaScript:CambiarVisibilidadFormularioReservaOffline();" class="booknow" !disabled></td></tr></table>';

		// Se anota el motivo de la reserva offline
		document.getElementById('reasonoffline').value = xmlDoc.getElementsByTagName("ERRORNUM")[0].childNodes[0].nodeValue;

	} else if (reservado == "10") { // Error en la reserva (alta con un mail ocupado)

		// Lo juntamos todo en una tabla
		var tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><td align="center">';
		tabla = tabla + '<h3>Please call us (0034) 952 233 507 providing your email address and our employees will finish the registration.</h3>';

	} // if
	
	return tabla;

} // ComponerTablaConfirmarReserva


function inserta_input(form, name, value) {

	var un_input = document.createElement('INPUT');
	un_input.type = "hidden";
	un_input.name = name;
	un_input.value = value;
	
	form.appendChild(un_input);
}


//
// Funciones que se encargan de procesar las peticiones offline
//		ConfirmarReservaOffline()

function ConfirmarReservaOffline() {

	var pres = document.formPresupuesto;

	if ((pres.nombreoffline.value.length < 8) 	||
		(pres.moviloffline.value == '')  		||
		(pres.emailoffline.value == '')  		||
		(pres.vuelooffline.value == '')			){

		alert ("Fields marked with * are required! (Name must be eight characters or more)");
		
	} else {
	
		OcultarForms();

		document.getElementById("Presupuesto").innerHTML='<h3>Booking offline</h3>';

		// Si la oficina de recogida o de entrega es superior a 100, se le resta 100
		// Eso significa que es una entrega especial
		pres_lgr_rtr = pres.lgr_rtr.options[pres.lgr_rtr.selectedIndex].value;
		if (pres_lgr_rtr == 100) {
			pres_lgr_rtr = 5;
			document.getElementById("comentariosoffline").value = "Please write here the location of the delivery.";
			delivery = "true";
		} else {
			document.getElementById("comentariosoffline").value = "";
			delivery = "false";
		}
		pres_lgr_ent = pres.lgr_ent.options[pres.lgr_ent.selectedIndex].value;
		if (pres_lgr_ent == 100) {
			pres_lgr_ent = 5;
		}

		cadena = "offlinemail.php?a=o&"+		// Action = Offline
		"lgr_rtr="		+	pres_lgr_rtr+"&"+
		"lgr_ent="		+	pres_lgr_ent+"&"+
		"vhc="			+	pres.vhc.options[pres.vhc.selectedIndex].value+"&"+
		"day_rtr="		+	pres.day_rtr.options[pres.day_rtr.selectedIndex].value+"&"+
		"msn_rtr="		+	pres.msn_rtr.options[pres.msn_rtr.selectedIndex].value+"&"+
		"hrm_rtr="		+	pres.hrm_rtr.options[pres.hrm_rtr.selectedIndex].value+"&"+
		"day_ent="		+	pres.day_ent.options[pres.day_ent.selectedIndex].value+"&"+
		"msn_ent="		+	pres.msn_ent.options[pres.msn_ent.selectedIndex].value+"&"+
		"hrm_ent="		+	pres.hrm_ent.options[pres.hrm_ent.selectedIndex].value+"&"+
		"num_dias="		+	CalculaNumeroDeDias()+"&"+
		"baby="	    	+	pres.baby.options[pres.baby.selectedIndex].value+"&"+
		"booster="		+	pres.booster.options[pres.booster.selectedIndex].value+"&"+
		"fdh="  		+	fuera_de_horas+"&"+

		"extra_gps="	+	pres.extra_gps.checked+"&"+
		"extra_driver="	+	"false"+"&"+
		"extra_insurance="+	pres.extra_insurance.checked+"&"+
		"extra_fine="	+	"false"+"&"+

		"reasonoffline="+	pres.reasonoffline.value+"&"+
		"nombre=" 		+	pres.nombreoffline.value+"&"+
		"movil="  		+	pres.moviloffline.value+"&"+
		"email="   		+	pres.emailoffline.value+"&"+
		"vuelo="		+	pres.vuelooffline.value+"&"+
		"comentarios="	+	document.getElementById("comentariosoffline").value

		document.location.href = cadena; // Carga una nueva página, usando "cadena" como url

	}  // if
}


//
// Funciones que se encargan de procesar las peticiones de upgrades
//		PedirUpgrade()
//		xmlhttpspatechangePedirUpgrade()
//		ComponerTablaPedirUpgrade()

function PedirUpgrade() {

	// Se obtiene el grupo del upgrade a partir del actual
	var pres = document.formPresupuesto;
	var lugar = pres.lgr_rtr.options[pres.lgr_rtr.selectedIndex].value;
	
	// De momento sólo hay upgrade en Málaga
	if ( (lugar == 10) ) {
		grupo_upgrade = 0;
	}
	
	switch (grupo_upgrade) {
		case 'A' : grupo_upgrade = 'B';
		break;
		case 'B' : grupo_upgrade = 'C';
		break;
		case 'C' : grupo_upgrade = 'D';
		break;
		case 'D' : grupo_upgrade = 'E';
		break;
		default : grupo_upgrade = '0'; // Sólo por seguridad
		break;
	}; 		
	
	if (grupo_upgrade != '0') {
		// Se muestra la animación de espera
//		var tabla = '<table width="98%" height="50" border="0" cellspacing="0" cellpadding="0">';
//		tabla = tabla + '<tr><td></td></tr></table>';
//		document.getElementById("Upgrade").innerHTML= tabla;
	
		cadena_upgrade = cadena.replace(/vhc=./, "vhc=" + grupo_upgrade);
		xmlhttp.open("GET",	cadena_upgrade, true);
	
		xmlhttp.onreadystatechange=xmlhttpstatechangePedirUpgrade;
		xmlhttp.send(null);
	} else {
		// No hay upgrade disponible		
//		document.getElementById("Upgrade").innerHTML='';
	}

} // PedirUpgrade


function xmlhttpstatechangePedirUpgrade() {
	if (xmlhttp.readyState==4) { // Transacción finalizada
	
		if (xmlhttp.status == 200) { // Estado correcto
			
			scrollToBottom();

			// Se recoge el documento XML con la respuesta, ya sea 
			// satisfactoria, o con el mensaje de error correspondiente
			var xmlDoc=xmlhttp.responseXML.documentElement;
			
			// Ahora se compone la tabla HTML, a partir del XML
			var tabla = ComponerTablaPedirUpgrade(xmlDoc);
			
			if (document.getElementById("Upgrade").innerHTML == '') {
				document.getElementById("Upgrade").innerHTML = '<br /><hr>';
			}
			// Se coloca la nueva información en el cuadro ajax
			document.getElementById("Upgrade").innerHTML += tabla;
			
			// Llamada recursiva
			PedirUpgrade();
			
		} else {

			// Si hay algún error con el servidor, ya se habrá mostrado en el precio normal		
			document.getElementById("Upgrade").innerHTML = '';
			
		} // if (xmlhttp.readyState==4)
		
	} // if (xmlhttp.status == 200)
	
} // xmlhttpstatechangePedirUpgrade


function ComponerTablaPedirUpgrade(xmlDoc) {
	
	// Lo primero a mirar es si se puede reservar
	if (xmlDoc.getElementsByTagName("reservable")[0].childNodes[0].nodeValue > 0) {

		// Imagen, familia y descripción del vehículo seleccionado
		var vehic = xmlDoc.getElementsByTagName("vhc")[0].childNodes[0].nodeValue;
		
		var lugar = document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value;

		// Se obtienen los valores del vehículo en particular
		var detalles = {familia:"", foto:"", descripcion:"", extras:""};
		DetallesVehiculo(vehic, lugar, detalles);
		
		// Precio del alquiler
		precio = xmlDoc.getElementsByTagName("precio")[0].childNodes[0].nodeValue;
		
		// Precio del alquiler con el descuento aplicado
		precio_con_descuento = xmlDoc.getElementsByTagName("precio_con_descuento")[0].childNodes[0].nodeValue;

		// Precio de los extras devuelto por "xmlhttp"
		precio_extras = xmlDoc.getElementsByTagName("precio_extras")[0].childNodes[0].nodeValue;
		
		// Precio total
		precio_con_extras_upgrade = (parseFloat(precio_con_descuento) + parseFloat(precio_extras)).toFixed(2);
		
		//precio_upgrade = (parseFloat(precio_con_extras_upgrade) - parseFloat(precio_con_extras)).toFixed(2);

		//precio_upgrade_dia = (parseFloat(precio_upgrade) / parseFloat(num_dias)).toFixed(2);

		var tabla = '<table width="98%" height="50" border="0" cellspacing="0" cellpadding="0">';

		tabla = tabla + '<tr height="45" valign="middle">';
		tabla = tabla + '<td align="left" colspan="2"><img src="/images/upgrade/upgrade-' + vehic + '.jpg"></td>';
		tabla = tabla + '<td align="right" width="30%"><font color=#12576B><b>Only ' + precio_con_extras_upgrade + ' &#8364;</b></br></font>';
		tabla = tabla + '<input NAME="booknow" id="booknow" type="button" VALUE="Select the upgrade" onClick="JavaScript:SelectUpgrade(\'' + vehic + '\');" class="booknow"></td></tr>';

		tabla = tabla + '</table>';

	} else { // "reservable" == 0
	
		var tabla = '';
		
	} // if reservable

	return tabla;
	
} // ComponerTablaPedirUpgrade


//
// Funciones que se encargan de procesar las peticiones de comprobación de email
//		ComprobarCorreo()
//		xmlhttpspatechangeComprobarCorreo()

function ComprobarCorreo(verbose) {

	correo = document.getElementById('correo_reserva').value;
	
	if (document.getElementById('correo_reserva').value != document.getElementById('repeat_correo_reserva').value) {
		alert ("\"Email\" and \"Repeat Email\" fields doesn\'t match!");
	} else if (esUnCorreo(correo)) {

		cadena = "checkmail.php?"+
		"correo="   +	correo;
		
		// Open con el flag síncrono, para esperar a que se compruebe el email
		xmlhttp.open("GET",	cadena, false);

		//xmlhttp.onreadystatechange=xmlhttpstatechangeComprobarCorreo;
		xmlhttp.send(null);
		
		// Se recoge el documento XML con la respuesta, ya sea 
		// satisfactoria, o con el mensaje de error correspondiente
		var xmlDoc=xmlhttp.responseXML.documentElement;
		
		if (xmlDoc.getElementsByTagName("status")[0].childNodes[0].nodeValue == 0) {
			// La dirección de correo está libre
			document.getElementById('correo_reserva').style.background = "#66CC99";
			document.getElementById('correo_reserva').style.color = "#FFFFFF";
			document.getElementById('repeat_correo_reserva').style.background = "#66CC99";
			document.getElementById('repeat_correo_reserva').style.color = "#FFFFFF";
			if (verbose) alert("That email address is free for you to use it.");
			return true;
			
		} else {
			// No está libre
			document.getElementById('correo_reserva').style.background = "#CC3333";
			document.getElementById('correo_reserva').style.color = "#FFFFFF";
			document.getElementById('repeat_correo_reserva').style.background = "#CC3333";
			document.getElementById('repeat_correo_reserva').style.color = "#FFFFFF";
			alert("You are already a client of Marbesol. Please go to \"Members login\" zone on the top of this page, and put your email address there. If you have any trouble, please call us: (00 34) 952 233 507");
			return false;
		}

	} else {
		document.getElementById('correo_reserva').style.background = "#FFFFFF";
		document.getElementById('correo_reserva').style.color = "#1F97BA";
		document.getElementById('repeat_correo_reserva').style.background = "#FFFFFF";
		document.getElementById('repeat_correo_reserva').style.color = "#1F97BA";
		alert("That email address is not valid. Please enter a valid one.");
		return false;
		
	} // if esUnCorreo

} // ComprobarCorreo

/* NO ES NECESARIO PORQUE SE HACE UNA LLAMADA JAVASCRIPT SINCRONA
function xmlhttpstatechangeComprobarCorreo() { // Util si hacemos la llamada asíncrona
	
	if (xmlhttp.readyState==4) { // Transacción finalizada
	
		if (xmlhttp.status == 200) { // Estado correcto
			
			// Se recoge el documento XML con la respuesta, ya sea 
			// satisfactoria, o con el mensaje de error correspondiente
			var xmlDoc=xmlhttp.responseXML.documentElement;
			
			if (xmlDoc.getElementsByTagName("status")[0].childNodes[0].nodeValue == 0) {
				// La dirección de correo está libre
				document.getElementById('correo_reserva').style.background = "#66CC99";
				document.getElementById('correo_reserva').style.color = "#FFFFFF";
				alert("That email address is free for you to use it.");
				
			} else {
				// No está libre
				document.getElementById('correo_reserva').style.background = "#CC3333";
				document.getElementById('correo_reserva').style.color = "#FFFFFF";
				alert("You are already a client of Marbesol. Please go to \"Members login\" zone on the top of this page, and put your email address there. If you have any trouble, please call us: 952 233 507");
				
			}
			
		} else {
			
		} // if (xmlhttp.readyState==4)
		
	} // if (xmlhttp.status == 200)
	
} // xmlhttpstatechangeComprobarCorreo
*/

//
// Funciones auxiliares que apoyan a la composición de información en los presupuestos
//		SelectUpgrade()
//		DetallesVehiculo()
//		DetallesError()

function SelectUpgrade(vehic) {

	//window.location.href = window.location.href.replace(/vhc=./, "vhc=" + vehic);

	// Selecciona el valor del combo que tenga por "value" a vehic
	for (var i=0; i<document.getElementById('combovehiculos').options.length;i++) {
		if(document.getElementById('combovehiculos').options[i].value == vehic)
		document.getElementById('combovehiculos').selectedIndex = i;
	}
	// Y vuelve a hacer una llamada de presupuesto
	document.getElementById('newquotebutton').click();
	
} // SelectUpgrade


function DetallesVehiculo(value, lugar, detalles) {

	if (lugar == 10) {
		// Colocar las imágenes de los vehículos de Lanzarote
		if (value == 'A') {
				foto='<img src="/images/coches/lanz/A.jpg">';
				familia = '<font size="2"><b>Economic Group</b></font>';
				descripcion = 'Ford Ka or similar*';
				extras = '<img src="/images/extras/3ps.jpg">';
		} else if (value == 'B') {
				foto='<img src="/images/coches/lanz/B.jpg">';
				familia = '<font size="2"><b>Medium Group</b></font>';
				descripcion = 'K.Picanto or similar*';
				extras = '<img src="/images/extras/3p.jpg">';
		} else if (value == 'C') {
				foto='<img src="/images/coches/lanz/C.jpg">';
				familia = '<font size="2"><b>Medium Group</b></font>';
				descripcion = 'F.Fiesta, SMART For Four or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'E') {
				foto='<img src="/images/coches/lanz/E.jpg">';
				familia = '<font size="2"><b>Medium Group</b></font>';
				descripcion = 'F.Focus, K.Cerato or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'G') {
				foto='<img src="/images/coches/lanz/G.jpg">';
				familia = '<font size="2"><b>Family Group</b></font>';
				descripcion = 'F.Focus Station Wagon or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'H') {
				foto='<img src="/images/coches/lanz/H.jpg">';
				familia = '<font size="2"><b>Family Group</b></font>';
				descripcion = 'O.Meriva or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'I') {
				foto='<img src="/images/coches/lanz/I.jpg">';
				familia = '<font size="2"><b>Minibus Group</b></font>';
				descripcion = 'S.Alhambra or similar*';
				extras = '<img src="/images/extras/5p7pl.jpg">';
		} else if (value == 'X') {
				foto='<img src="/images/coches/lanz/X.jpg">';
				familia = '<font size="2"><b>Convertible Group</b></font>';
				descripcion = 'M.Colt Cabrio or similar*';
				extras = '<img src="images/extras/5p.jpg">';
		} else if (value == 'P1') {
				foto='<img src="/images/coches/lanz/P1.jpg">';
				familia = '<font size="2"><b>Convertible Group</b></font>';
				descripcion = 'P.307 Cabrio or similar*';
				extras = '<img src="/images/extras/3p.jpg">';
		} else if (value == 'T') {
				foto='<img src="/images/coches/lanz/T.jpg">';
				familia = '<font size="2"><b>Luxury Group</b></font>';
				descripcion = 'Mercedes 320 CLK Cabrio (Aut.) or similar*';
				extras = '<img src="/images/extras/3p.jpg">';
		}
	} else {
		// Colocar las imágenes de los vehículos de Málaga
		if (value == 'A') {
				foto='<img src="/images/coches/A.jpg">';
				familia = '<font size="2"><b>Economic Group</b></font>';
				descripcion = 'Ch. Matiz or similar*';
				extras = '<img src="/images/extras/3ps.jpg">';
		} else if (value == 'B') {
				foto='<img src="/images/coches/B.jpg">';
				familia = '<font size="2"><b>Medium Group</b></font>';
				descripcion = 'Kia Picanto, Ford Ka or similar*';
				extras = '<img src="/images/extras/3p.jpg">';
		} else if (value == 'C') {
				foto='<img src="/images/coches/C.jpg">';
				familia = '<font size="2"><b>Medium Group</b></font>';
				descripcion = 'S.Ibiza, F.Fiesta, O.Corsa or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'D') {
				foto='<img src="/images/coches/D.jpg">';
				familia = '<font size="2"><b>Medium Group</b></font>';
				descripcion = 'S.Cordoba, T.Corolla or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'E') {
				foto='<img src="/images/coches/E.jpg">';
				familia = '<font size="2"><b>Medium Group</b></font>';
				descripcion = 'F.Focus, S.Leon, R.Megane, K.Cerato or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'F') {
				foto='<img src="/images/coches/F.jpg">';
				familia = '<font size="2"><b>Medium Group</b></font>';
				descripcion = 'F.Mondeo, N.Primera or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'F1') {
				foto='<img src="/images/coches/F1.jpg">';
				familia = '<font size="2"><b>Medium Group</b></font>';
				descripcion = 'Volkswagen Golf or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'F2') {
				foto='<img src="/images/coches/F2.jpg">';
				familia = '<font size="2"><b>Medium Group</b></font>';
				descripcion = 'Mini Manual or similar*';
				extras = '<img src="/images/extras/3p.jpg">';
		} else if (value == 'Z') {
				foto='<img src="/images/coches/Z.jpg">';
				familia = '<font size="2"><b>Family Group</b></font>';
				descripcion = 'F.Tourneo Connect, O.Combo or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'G') {
				foto='<img src="/images/coches/G.jpg">';
				familia = '<font size="2"><b>Family Group</b></font>';
				descripcion = 'F.Focus SW, O.Astra SW or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'H') {
				foto='<img src="/images/coches/H.jpg">';
				familia = '<font size="2"><b>Family Group</b></font>';
				descripcion = 'S.Altea XL, O.Meriva, C.Picasso or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'I') {
				foto='<img src="/images/coches/I.jpg">';
				familia = '<font size="2"><b>Minibus Group</b></font>';
				descripcion = '7 Seater S.Alhambra, F.Galaxy or similar*';
				extras = '<img src="/images/extras/5p7pl.jpg">';
		} else if (value == 'I1') {
				foto='<img src="/images/coches/I1.jpg">';
				familia = '<font size="2"><b>Minibus Group</b></font>';
				descripcion = '7 Seater O.Zafira or similar*';
				extras = '<img src="/images/extras/5p7pl.jpg">';
		} else if (value == 'K') {
				foto='<img src="/images/coches/K.jpg">';
				familia = '<font size="2"><b>Minibus Group</b></font>';
				descripcion = '9 Seater N.Primastar, F.Transit or similar*';
				extras = '<img src="/images/extras/5p9pl.jpg">';
		} else if (value == 'L') {
				foto='<img src="/images/coches/L.jpg">';
				familia = '<font size="2"><b>Minibus Group</b></font>';
				descripcion = '7 Seater AUTOMATIC S.Alhambra or similar*';
				extras = '<img src="/images/extras/5p7pl.jpg">';
		} else if (value == 'L1') {
				foto='<img src="/images/coches/L1.jpg">';
				familia = '<font size="2"><b>Luxury Group</b></font>';
				descripcion = 'AUT. 8 Seater Chevrolet Van Express XL or similar';
				extras = '<img src="/images/extras/5p7pl.jpg">';
		} else if (value == 'N') {
				foto='<img src="/images/coches/N.jpg">';
				familia = '<font size="2"><b>Automatic Group</b></font>';
				descripcion = 'AUTOMATIC S.Ibiza, O.Corsa or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'O') {
				foto='<img src="/images/coches/O.jpg">';
				familia = '<font size="2"><b>Automatic Group</b></font>';
				descripcion = 'AUTOMATIC F.Focus, S.Leon, R.Megane or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'P') {
				foto='<img src="/images/coches/P.jpg">';
				familia = '<font size="2"><b>Automatic Group</b></font>';
				descripcion = 'AUTOMATIC Mercedes "A" or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'P1') {
				foto='<img src="/images/coches/P1.jpg">';
				familia = '<font size="2"><b>Convertible Group</b></font>';
				descripcion = 'CONVERTIBLE P.307, R.Megane, O.Astra or similar*';
				extras = '<img src="/images/extras/3p.jpg">';
		} else if (value == 'P2') {
				foto='<img src="/images/coches/P2.jpg">';
				familia = '<font size="2"><b>Convertible Group</b></font>';
				descripcion = 'Mini Cabrio Manual or similar*';
				extras = '<img src="/images/extras/3p.jpg">';
		} else if (value == 'R') {
				foto='<img src="/images/coches/R.jpg">';
				familia = '<font size="2"><b>Luxury Group</b></font>';
				descripcion = 'Audi A4, BMW 320, Audi A3 AUT. or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'R1') {
				foto='<img src="/images/coches/R1.jpg">';
				familia = '<font size="2"><b>Luxury Group</b></font>';
				descripcion = 'Mini Cooper Cabrio Automatic or similar*';
				extras = '<img src="/images/extras/3p.jpg">';
		} else if (value == 'S') {
				foto='<img src="/images/coches/S.jpg">';
				familia = '<font size="2"><b>Luxury Group</b></font>';
				descripcion = 'AUT. Audi A4, BMW 320 or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'T') {
				foto='<img src="/images/coches/T.jpg">';
				familia = '<font size="2"><b>Luxury Group</b></font>';
				descripcion = 'Audi A6,  BMW 5 Series or similar*';	
				extras = '<img src="/images/extras/5p.jpg">';	
		}else if (value == 'T1') {
				foto='<img src="/images/coches/T1.jpg">';
				familia = '<font size="2"><b>Luxury Group</b></font>';
				descripcion = 'AUT. A4 Cabrio,Merc. CLK Cabrio,C70 Cabrio or similar*';	
				extras = '<img src="/images/extras/3p.jpg">';	
		} 
		else if (value == 'U') {
				foto='<img src="/images/coches/U.jpg">';
				familia = '<font size="2"><b>Luxury Group</b></font>';
				descripcion = 'AUT. Q7, A8, BMW X5, Merc.CLS or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		} else if (value == 'W') {
				foto='<img src="/images/coches/W.jpg">';
				familia = '<font size="2"><b>Luxury Group</b></font>';
				descripcion = 'AUTOMATIC BMW 6 Series, P.Cayenne, P.Carrera, Merc.S320 or similar*';
				extras = '<img src="/images/extras/5p.jpg">';
		}
	} // if lugar == Lanzarote
	
	detalles.foto = foto;
	detalles.familia = familia;
	detalles.descripcion = descripcion;
	detalles.extras = extras;
	
} // DetallesVehiculo


function DetallesError(Error) {

	// OPR004 Some necessary information is missing.
	if (Error=="OPR004") {
		// Lo juntamos todo en una tabla
		var tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><td><iframe src="/admin/pasos/pedirpresupuesto.html" height="1px" width="1px" frameborder="0"></iframe></td></tr><tr><td align="center">';
		tabla = tabla + '<h3>At this moment we are not able to confirm your booking. Please, fill the form with all the details and we will contact you as soon as possible. You can also contact us on</br> (0034) 952 233 507</h3>';
		tabla = tabla + '<INPUT TYPE="button" VALUE="Fill the form" onClick="JavaScript:CambiarVisibilidadFormularioReservaOffline();" class="booknow" !disabled></td></tr></table>';

		// Se anota el motivo de la reserva offline
		document.getElementById('reasonoffline').value = 'Some information is missing';

	// OPR106 Wrong date format or out of range. (#n)
	} else if (Error=="OPR106") {
		var tabla = '<h3>Please, review the date</h3>';

	// OPR107 Wrong time format or out of range.
	} else if (Error=="OPR107") {
		var tabla = '<h3>Please, review the time</h3>';

	// OPR108 PickUp location and/or DropOff location: Unavailable.
	} else if (Error=="OPR108") {
		var tabla = '<h3>Please choose a location</h3>';

	// OPR113 Group class is missing.
	} else if (Error=="OPR113") {
		var tabla = '<h3>Please choose a car</h3>';

	// OPR114 Wrong numeric format.
	} else if (Error=="OPR114") {
		// Lo juntamos todo en una tabla
		var tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><td><iframe src="/admin/pasos/pedirpresupuesto.html" height="1px" width="1px" frameborder="0"></iframe></td></tr><tr><td align="center">';
		tabla = tabla + '<h3>At this moment we are not able to confirm your booking. Please, fill the form with all the details and we will contact you as soon as possible. You can also contact us on</br> (0034) 952 233 507</h3>';
		tabla = tabla + '<INPUT TYPE="button" VALUE="Fill the form" onClick="JavaScript:CambiarVisibilidadFormularioReservaOffline();" class="booknow" !disabled></td></tr></table>';

		// Se anota el motivo de la reserva offline
		document.getElementById('reasonoffline').value = 'Wrong numeric format';

	// OPR115 Min. (n) days in advance.
	} else if (Error=="OPR115") {
		// Lo juntamos todo en una tabla
		var tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><td><iframe src="/admin/pasos/pedirpresupuesto.html" height="1px" width="1px" frameborder="0"></iframe></td></tr><tr><td align="center">';
		tabla = tabla + '<h3>At this moment we are not able to confirm your booking. Please, fill the form with all the details and we will contact you as soon as possible. You can also contact us on</br> ((0034) 952 233 507</h3>';
		tabla = tabla + '<INPUT TYPE="button" VALUE="Fill the form" onClick="JavaScript:CambiarVisibilidadFormularioReservaOffline();" class="booknow" !disabled></td></tr></table>';

		// Se anota el motivo de la reserva offline
		document.getElementById('reasonoffline').value = 'There are a minimmun of days in advance';

	// OPR118 Requested group is unavailable for this date.
	} else if (Error=="OPR118") {
		// Lo juntamos todo en una tabla
		var tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><td><iframe src="/admin/pasos/pedirpresupuesto.html" height="1px" width="1px" frameborder="0"></iframe></td></tr><tr><td align="center">';
		tabla = tabla + '<h3>At this moment we are not able to confirm the booking for the car group you\'ve selected. Please, choose a different car group or fill the form with all the details and we will contact you as soon as possible. You can also contact us on</br> (0034) 952 233 507</h3>';
		tabla = tabla + '<INPUT TYPE="button" VALUE="Fill the form" onClick="JavaScript:CambiarVisibilidadFormularioReservaOffline();" class="booknow" !disabled></td></tr></table>';

		// Se anota el motivo de la reserva offline
		document.getElementById('reasonoffline').value = 'Requested group is unavailable for this date';

	// OPR121 Unrecognized Siip Code.
	} else if (Error=="OPR121") {
		// Lo juntamos todo en una tabla
		var tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><td><iframe src="/admin/pasos/pedirpresupuesto.html" height="1px" width="1px" frameborder="0"></iframe></td></tr><tr><td align="center">';
		tabla = tabla + '<h3>At this moment we are not able to confirm your booking. Please, fill the form with all the details and we will contact you as soon as possible. You can also contact us on</br> (0034) 952 233 507</h3>';
		tabla = tabla + '<INPUT TYPE="button" VALUE="Fill the form" onClick="JavaScript:CambiarVisibilidadFormularioReservaOffline();" class="booknow" !disabled></td></tr></table>';

		// Se anota el motivo de la reserva offline
		document.getElementById('reasonoffline').value = 'Unrecognized Siip Code';

	// OPR122 Minimum rental period: Exceeded.
	} else if (Error=="OPR122") {
		// Lo juntamos todo en una tabla
		var tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><td><iframe src="/admin/pasos/pedirpresupuesto.html" height="1px" width="1px" frameborder="0"></iframe></td></tr><tr><td align="center">';
		tabla = tabla + '<h3>At this moment we are not able to confirm your booking. Please, fill the form with all the details and we will contact you as soon as possible. You can also contact us on</br> (0034) 952 233 507</h3>';
		tabla = tabla + '<INPUT TYPE="button" VALUE="Fill the form" onClick="JavaScript:CambiarVisibilidadFormularioReservaOffline();" class="booknow" !disabled></td></tr></table>';

		// Se anota el motivo de la reserva offline
		document.getElementById('reasonoffline').value = 'Minimum rental period: Exceeded';

	// OPR123 Rental period too long.
	} else if (Error=="OPR123") {
		var tabla = '<h3>Rental period too long</h3>';

	// OPR138 Unable to locate price list.
	} else if (Error=="OPR138") {
		// Lo juntamos todo en una tabla
		var tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><td><iframe src="/admin/pasos/pedirpresupuesto.html" height="1px" width="1px" frameborder="0"></iframe></td></tr><tr><td align="center">';
		tabla = tabla + '<h3>At this moment we are not able to confirm your booking. Please, fill the form with all the details and we will contact you as soon as possible. You can also contact us on</br> (0034) 952 233 507</h3>';
		tabla = tabla + '<INPUT TYPE="button" VALUE="Fill the form" onClick="JavaScript:CambiarVisibilidadFormularioReservaOffline();" class="booknow" !disabled></td></tr></table>';

		// Se anota el motivo de la reserva offline
		document.getElementById('reasonoffline').value = 'Unable to locate price list';

	// Branch not open at requested pick up time
	} else if (Error=="Branch not open at requested pick up time") {
		
		var combo = document.getElementById("combolugaresrecogida");
		
		if (combo.value == '5') { // Mostrar los horarios de Málaga - Aeropuerto
			horario = 'Málaga Airport<br>Monday to Saturday : 07,00 to 23,00<br>Sunday: 07,00 to 23,00';
		} else if (combo.value == '1') { // Mostrar los horarios de Marbella
			horario = 'Marbella<br>Monday to Saturday : 09,00 to 14,30 / 16,30 to 20,00<br>Sunday: 09,30 to 14,00';
		} else if (combo.value == '3') { // Mostrar los horarios de Cabopino
			horario = 'Cabopino<br>Monday to Friday : 09,00 to 14,00 / 16,00 to 20,00';
		} else if (combo.value == '4') { // Mostrar los horarios de Fuengirola
			horario = 'Fuengirola<br>Monday to Saturday : 09,00 to 14,00 / 16,30 to 19,30<br>Sunday: 09,30 to 13,00';
		}
		
		var tabla = '<h3>Please note that the office opening hours are:</h3>' +
				   	'<br><font size="1">' + horario + '</font><br><br>' + 
				   	'<h3>Please change the selection time as our office remains closed at the time requested. Thank you.</h3>';

	// Carres server is not responding to requests
	} else if (Error=="Carres server is not responding to requests") {
		// Lo juntamos todo en una tabla
		var tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><td><iframe src="/admin/pasos/pedirpresupuesto.html" height="1px" width="1px" frameborder="0"></iframe></td></tr><tr><td align="center">';
		tabla = tabla + '<h3>At this moment we are not able to confirm your booking. Please, fill the form with all the details and we will contact you as soon as possible. You can also contact us on</br> (0034) 952 233 507</h3>';
		tabla = tabla + '<INPUT TYPE="button" VALUE="Fill the form" onClick="JavaScript:CambiarVisibilidadFormularioReservaOffline();" class="booknow" !disabled></td></tr></table>';

		// Se anota el motivo de la reserva offline
		document.getElementById('reasonoffline').value = 'Carres server is not responding to requests';
		
	// Cualquier error nuevo
	} else {
		// Lo juntamos todo en una tabla
		var tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0"><tr><td><iframe src="/admin/pasos/pedirpresupuesto.html" height="1px" width="1px" frameborder="0"></iframe></td></tr><tr><td align="center">';
		tabla = tabla + '<h3>At this moment we are not able to confirm your booking. Please, fill the form with all the details and we will contact you as soon as possible. You can also contact us on</br> (0034) 952 233 507</h3>';
		tabla = tabla + '<INPUT TYPE="button" VALUE="Fill the form" onClick="JavaScript:CambiarVisibilidadFormularioReservaOffline();" class="booknow" !disabled></td></tr></table>';

		// Se anota el motivo de la reserva offline
		document.getElementById('reasonoffline').value = Error;

	} // if error
	
	return tabla;

} // DetallesError


// Funcion que devuelte "true" si ls reserva que se intenta realizar es realmente viable
// en tiempo,es decir, si ls hora actual está entre las 20:00 y las 9:00, sólo se puede
// reservar como muy pronto para el día siguiente a las 10:00.
// Si la hora actual está entre las 9:00 y las 20:00, se puede reservar sin restricción
// por este motivo.
function EsFechaViable() {

	hora_rtr = document.formPresupuesto.hrm_rtr.options[document.formPresupuesto.hrm_rtr.selectedIndex].value;
	day_rtr = document.formPresupuesto.day_rtr.options[document.formPresupuesto.day_rtr.selectedIndex].value;
	msn_rtr = document.formPresupuesto.msn_rtr.options[document.formPresupuesto.msn_rtr.selectedIndex].value;

	// Separamos los valores de las fechas
	anno_ini = Math.floor(msn_rtr / 12); // Porque msn = (año * 12) + (mes - 1)
	mes_ini  = (msn_rtr % 12) + 1;
	dia_ini  = parseInt(day_rtr);


	var d = new Date();
	var hora = d.getHours();
	
	if (  (hora >=20) || (hora < 9)  ) { // Desde las 20:00 hasta las 8:59 del día sig.
		// Solo permitir la reserva, si la fecha de recogida es para el día siguiente a
		// la fecha actual del ordenador del cliente

		var fecha_ret = new Date();
		if (  (hora >=20) && (hora <= 23)  ) { // Solo se suma un día si la hora es anterior a las 0:00
			fecha_ret.setDate(d.getDate() + 1);
		}

		// La fecha de retirada ha de ser igual o porterior a la ya almacenada en fecha_ret
		if (	(anno_ini < fecha_ret.getFullYear()) ||
				(  (anno_ini == fecha_ret.getFullYear())  && (mes_ini < (fecha_ret.getMonth())+1)  ) ||
				(  (mes_ini  == (fecha_ret.getMonth())+1) && (dia_ini < fecha_ret.getDate())       ) ||
				(  (dia_ini  == fecha_ret.getDate())      && (hora_rtr < 1000			       )   )	) {
				
					
			return false;
		} else {
			return true;
		}
		
	} else {
		return true;
	}
}


// Comprueba si la reserva se ahce con 2 horas de antelacion. Presupone que se ha hecho una llamada
// previa a "EsFechaViable", con resultado "true", por lo que se tiene 9 < hora < 20
function EsFechaConMargen() {

	hora_rtr = document.formPresupuesto.hrm_rtr.options[document.formPresupuesto.hrm_rtr.selectedIndex].value;
	day_rtr = document.formPresupuesto.day_rtr.options[document.formPresupuesto.day_rtr.selectedIndex].value;
	msn_rtr = document.formPresupuesto.msn_rtr.options[document.formPresupuesto.msn_rtr.selectedIndex].value;

	// Separamos los valores de las fechas
	anno_ini = Math.floor(msn_rtr / 12); // Porque msn = (año * 12) + (mes - 1)
	mes_ini  = (msn_rtr % 12) + 1;
	dia_ini  = parseInt(day_rtr);


	var d = new Date();
	var hora = d.getHours();

	hora = (hora+2)*100;

	if (	(anno_ini == d.getFullYear()) &&
			(mes_ini  == (d.getMonth()+1)) &&
			(dia_ini  == d.getDate()) &&
			(hora_rtr < hora)	) {
		return false;
	} else {
		return true;
	} // if
}


//
// Otras Funciones auxiliares
//		OcultarForms()
//		CambiarVisibilidadFormularioReserva()
//		function CambiarVisibilidadFormularioReservaOffline()
//		SonFechasCorrectas()
//		CalculaNumeroDeDias()
//		CuentaDias()
//		EsBisiesto()
//		getYScroll()
//		scrollToBottom()
//

function OcultarForms() {
	document.getElementById('Reserva').style.display = 'none';
	document.getElementById('Reservaoffline').style.display = 'none';

	// NUEVO: Se oculta el campo del "book and join"
//	document.getElementById('bookandjoin').style.display = 'none';

	// NUEVO: Se vacia el cuadro de los upgrades
	document.getElementById("Upgrade").innerHTML = '';

}


function CambiarVisibilidadFormularioReserva(conregistro,endestino){
	
	// Si se reserva y se registra a la vez, cambia la llamada
	if (conregistro) {
		document.getElementById('booknowbutton').value = "Book now";
		document.getElementById('registroreserva').value = "si";
		
		// Se activa la detección del mail
		document.getElementById('boton_check').style.display = "block";
		
	} else {
		document.getElementById('booknowbutton').value = "Book now";
		document.getElementById('registroreserva').value = "no";

		var pres = document.formPresupuesto;
		var lugar = pres.lgr_rtr.options[pres.lgr_rtr.selectedIndex].value;
		// Se añade el soporte para el agente Vivamar. cno se muestra el boton de comprobar correo
		// y no se bloquean los campos de input
		if ( (lugar == 201) || (lugar == 202) || (lugar == 205) || (lugar==105)) {
			document.getElementById('boton_check').style.display = "none";
		} else { // Es el caso general

			if (document.getElementById('fidelita').value == '') {	// Fuera del club
				document.getElementById('boton_check').style.display = "block";
				
			} else {												// Dentro del club
				document.getElementById('boton_check').style.display = "none";
				
				document.getElementById('correo_reserva').disabled = true;
				document.getElementById('repeat_correo_reserva').disabled = true;
			}
		} // if es marriot
	}

	// Se coloca la casilla de las condiciones como no marcada,
	// y el botón deshabilitado
	document.getElementById('accept').checked = false;
	document.getElementById('booknowbutton').disabled = true;
	
	// Se oculta "offline" y se muestra "reserva"
	document.getElementById('Reservaoffline').style.display = 'none';

	// Y ahora se cambia el display de "reserva"
	if (document.getElementById('Reserva').style.display == 'block') {
		document.getElementById('Reserva').style.display = 'none';
	} else {
		document.getElementById('Reserva').style.display = 'block';
		document.getElementById('Reserva').style.visibility = 'visible';

		document.getElementById("condiciones").focus();
	}
	//BEGIN RPUGA 18-02-10
	// Cliente de Marriott
	es_marriott = (	(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 201) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 202) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 205) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 215) ||
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 225) );
	if (!es_marriott){
	if(endestino){
		document.getElementById('pagodestino').checked=true;
		document.getElementById('TextoTituloOnline').style.display = 'none';
		document.getElementById('TextoTituloOnArrival').style.display = 'block';
	}
	else{
		document.getElementById('pagovisa').checked=true;
		document.getElementById('TextoTituloOnline').style.display = 'block';
		document.getElementById('TextoTituloOnArrival').style.display = 'none';
	}}		
	//END RPUGA 18-02-10
	
}

function CambiarVisibilidadFormularioReservaOffline(){

	// Se oculta "reserva" y se muestra "offline"
	document.getElementById('Reserva').style.display = 'none';

	// Y ahora se cambia el display de "reserva offline"
	if (document.getElementById('Reservaoffline').style.display == 'block') {
		document.getElementById('Reservaoffline').style.display = 'none';
	} else {
		document.getElementById('Reservaoffline').style.display = 'block';
		document.getElementById('Reservaoffline').style.visibility = 'visible';
	} // if style.display

}

// Funcion que vevuelve "true" si el día es correcto dentro del mes y del año,
// tanto en la recogida como en la entrega
function SonFechasCorrectas() {

	day_rtr = document.formPresupuesto.day_rtr.options[document.formPresupuesto.day_rtr.selectedIndex].value;
	msn_rtr = document.formPresupuesto.msn_rtr.options[document.formPresupuesto.msn_rtr.selectedIndex].value;
	day_ent = document.formPresupuesto.day_ent.options[document.formPresupuesto.day_ent.selectedIndex].value;
	msn_ent = document.formPresupuesto.msn_ent.options[document.formPresupuesto.msn_ent.selectedIndex].value;

	// Separamos los valores de las fechas
	anno_ini = Math.floor(msn_rtr / 12); // Porque msn = (año * 12) + (mes - 1)
	mes_ini  = (msn_rtr % 12) + 1;
	dia_ini  = parseInt(day_rtr);
	
	anno_fin = Math.floor(msn_ent / 12); // Porque msn = (año * 12) + (mes - 1)
	mes_fin  = (msn_ent % 12) + 1;
	dia_fin  = parseInt(day_ent);

	if (	(dia_ini > DiasQueTieneUnMes(mes_ini, anno_ini)) ||
			(dia_fin > DiasQueTieneUnMes(mes_fin, anno_fin))	) {
//		alert(dia_ini + " " + mes_ini + " " + anno_ini);
//		alert(dia_fin + " " + mes_fin + " " + anno_fin);
		return false;
	} else {
		return true;
	}
	
}


// Función que devuelve el número de dias que hay entre la fecha de recogida
// y la fecha de entrega
function CalculaNumeroDeDias() {

	day_rtr = document.formPresupuesto.day_rtr.options[document.formPresupuesto.day_rtr.selectedIndex].value;
	msn_rtr = document.formPresupuesto.msn_rtr.options[document.formPresupuesto.msn_rtr.selectedIndex].value;
	day_ent = document.formPresupuesto.day_ent.options[document.formPresupuesto.day_ent.selectedIndex].value;
	msn_ent = document.formPresupuesto.msn_ent.options[document.formPresupuesto.msn_ent.selectedIndex].value;
	
	result = 0;

	// Separamos los valores de las fechas
	anno_ini = Math.floor(msn_rtr / 12); // Porque msn = (año * 12) + (mes - 1)
	mes_ini  = (msn_rtr % 12) + 1;
	dia_ini  = parseInt(day_rtr);
	
	anno_fin = Math.floor(msn_ent / 12); // Porque msn = (año * 12) + (mes - 1)
	mes_fin  = (msn_ent % 12) + 1;
	dia_fin  = parseInt(day_ent);
	
	if (dia_ini > DiasQueTieneUnMes(mes_ini, anno_ini) ||	// El dia de inicio no es válido para el mes y año
		dia_fin > DiasQueTieneUnMes(mes_fin, anno_fin) ||	// El dia de fin no es válido para el mes y año
		anno_ini > anno_fin ||								// El año de inicio es mayor que el de fin
		((anno_ini == anno_fin) && (mes_ini > mes_fin)) ||		// O es igual y sí lo es el mes
		((anno_ini == anno_fin) && (mes_ini == mes_fin) && (dia_ini > dia_fin)) ) { // O es igual y sí lo es el día
	    
	    //alert (dia_ini + ' ' + mes_ini + ' ' + anno_ini + ' - ' + dia_fin + ' ' + mes_fin + ' ' + anno_fin +
		//		((anno_ini == anno_fin) && (mes_ini == mes_fin) && (dia_ini > dia_fin)));
		result = 0;
	} else {
	
		if (anno_ini == anno_fin) {
			dias_hasta_ini = CuentaDias(anno_ini, mes_ini, dia_ini);
			dias_hasta_fin = CuentaDias(anno_fin, mes_fin, dia_fin);

			//alert(CuentaDias(anno_ini, mes_ini, dia_ini) + ' - ' + CuentaDias(anno_fin, mes_fin, dia_fin));

			result = dias_hasta_fin - dias_hasta_ini;
		} else {
			dias_ini_rest = 0;
			dias_annos = 0;
			dias_hasta_fin = 0;

			if (EsBisiesto(anno_ini)) {
				dias_ini_rest = 366 - CuentaDias(anno_ini, mes_ini, dia_ini);
			} else {
				dias_ini_rest = 365 - CuentaDias(anno_ini, mes_ini, dia_ini);
			}
		
			for (i = anno_ini+1; i < anno_fin; i++) {
				dias_annos += 365;
				if (EsBisiesto(i)) dias_annos++;
			}
		
			dias_hasta_fin = CuentaDias(anno_fin, mes_fin, dia_fin);
		
			result = dias_ini_rest + dias_annos + dias_hasta_fin;
		} // if anno_ini == anno_fin
		
	} // if 
	
	// Ahora se calculan las horas de gracia
	hrm_rtr = document.formPresupuesto.hrm_rtr.options[document.formPresupuesto.hrm_rtr.selectedIndex].value;
	hrm_ent = document.formPresupuesto.hrm_ent.options[document.formPresupuesto.hrm_ent.selectedIndex].value;
	
	if (result >= 1) {
		if ((hrm_ent - hrm_rtr) >= 300) {
			result = result + 1;
		}
	}
	
	return result;

} // CalculaNumeroDeDias

// Cuenta los días que pasan desde el 1 de enero de "anno", hasta el "dia" de "mes"
function CuentaDias(anno, mes, dia) {
	total = 0;
	for (i = 1; i < mes; i++) {
		total += DiasQueTieneUnMes(i, anno);
	}
	total += dia;

	return total;
}

function EsBisiesto(anno) {
	return ((anno % 4 == 0) && ((anno % 100 != 0) || (anno % 400 == 0)))
}

function DiasQueTieneUnMes(mes,anno) { // 1: Enero
	var dms=new Array(31,28,31,30,31,30,31,31,30,31,30,31)
	dm=dms[mes-1];
	if (EsBisiesto(anno) && (mes == 2)) // Si es febrero
	dm++;
	return dm;
}

function getYScroll()
{
  var yScroll;	
	if (window.innerHeight && window.scrollMaxY) {			
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		yScroll = document.body.offsetHeight;
	}
	return yScroll;
}

function scrollToBottom() {
   window.scrollTo(0,getYScroll());
}


// Browser safe opacity handling function


function fadeInUpgrade() {
	setOpacityUpgrade(0);
	for( var i = 0 ; i <= 100 ; i++ ) {
		setTimeout( 'setOpacityUpgrade(' + (i / 10) + ')' , 8 * i );
	}
}

function fadeOutUpgrade() {
	for( var i = 0 ; i <= 100 ; i++ ) {
		setTimeout( 'setOpacityUpgrade(' + (10 - i / 10) + ')' , 8 * i );
	}
}

function setOpacityUpgrade(value) {
	document.getElementById("Upgrade").style.opacity = value / 10;
	document.getElementById("Upgrade").style.filter = 'alpha(opacity=' + value * 10 + ')';
}

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 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 + ")";
} 


// Función que valida una dirección de correo electrónico
function esUnCorreo(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
//	   alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
//	   alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
//	    alert("Invalid E-mail ID")
	    return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
//	    alert("Invalid E-mail ID")
	    return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
//	    alert("Invalid E-mail ID")
	    return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
//	    alert("Invalid E-mail ID")
	    return false
	 }
	
	 if (str.indexOf(" ")!=-1){
//	    alert("Invalid E-mail ID")
	    return false
	 }

	 return true					
}

//FUNCIONES NUEVAS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//BEGIN JOSE L. CRESPILLO 23-03-10

function PedirTodos(grupo_todos) {

	// Se obtiene el grupo del upgrade a partir del actual
	
	
	
	if (grupo_todos != '0') {
		// Se muestra la animación de espera
//		var tabla = '<table width="98%" height="50" border="0" cellspacing="0" cellpadding="0">';
//		tabla = tabla + '<tr><td></td></tr></table>';
//		document.getElementById("Upgrade").innerHTML= tabla;
		//cadena ="/xmlhttp.php?a=p&logged=false&fidelita=&registrar=no&lgr_rtr=5&lgr_ent=5&vhc=E&day_rtr=23&msn_rtr=24124&hrm_rtr=1000&day_ent=30&msn_ent=24124&hrm_ent=1000&num_dias=7&baby=0&booster=0&fdh=0&extra_gps=false&extra_driver=false&extra_insurance=false&extra_fine=false&delivery=0"
		
		cadena_upgrade = cadena.replace(/vhc=../, "vhc=" + grupo_todos);
		xmlhttp.open("GET",	cadena_upgrade, true);
	
		xmlhttp.onreadystatechange=xmlhttpstatechangePedirTodos;
		xmlhttp.send(null);
	} else {
		// No hay upgrade disponible		
//		document.getElementById("Upgrade").innerHTML='';
	}

} // PedirUpgrade


function xmlhttpstatechangePedirTodos() {

	if (xmlhttp.readyState==4) { // Transacción finalizada
	
		if (xmlhttp.status == 200) { // Estado correcto
			
				
			// Se recoge el documento XML con la respuesta, ya sea 
			// satisfactoria, o con el mensaje de error correspondiente
			var xmlDoc=xmlhttp.responseXML.documentElement;
			
			var tabla=ComponerTablaPedirTodos(xmlDoc);
			
			if(tabla!='no'){
			if(esprimerotodos || grupo_todos=='A'){
				
				esprimerotodos=false;
				document.getElementById("Presupuesto").innerHTML=tabla;
			}
			else{
				document.getElementById("Presupuesto").innerHTML+=tabla;	
			}
			}
			// Ahora se compone la tabla HTML, a partir del XML
			//alert (xmlDoc2);
			// Llamada recursiva
			
		switch (grupo_todos) {
		case '99' : grupo_todos='A';
		break;
		case 'E' :grupo_todos='F';
		break;
		case 'F' :grupo_todos='F1';
		break;
		case 'F1' :grupo_todos='F2';
		break;
		case 'F2' :grupo_todos='Z';
		break;
		case 'Z' :grupo_todos='G';
		break;
		case 'G' :grupo_todos='H';
		break;
		case 'H' :grupo_todos='I';
		break;
		case 'I' :grupo_todos='I1';
		break;
		case 'I1' :grupo_todos='K';
		break;
		case 'K' :grupo_todos='L';
		break;
		case 'L' :grupo_todos='O';
		break;
		case 'O' :grupo_todos='P';
		break;
		case 'P' :grupo_todos='P1';
		break;
		case 'P1' :grupo_todos='P2';
		break;
		case 'P2' :grupo_todos='R';
		break;
		case 'R' :grupo_todos='R1';
		break;
		case 'R1' :grupo_todos='S';
		break;
		case 'S' :grupo_todos='T';
		break;
		case 'T' :grupo_todos='T1';
		break;
		case 'T1' :grupo_todos='U';
		break;
		case 'U' : grupo_todos='W';
		break;	
		case 'A' : grupo_todos = 'B';
		break;
		case 'B' : grupo_todos = 'C';
		break;
		case 'C' : grupo_todos = 'D';
		break;
		case 'D' : grupo_todos = 'E';
		break;
		default : grupo_todos = '0'; // Sólo por seguridad
		break;
	}; 		
				
			PedirTodos(grupo_todos);
			
		} else {

			// Si hay algún error con el servidor, ya se habrá mostrado en el precio normal		
			//document.getElementById("Upgrade").innerHTML = '';
		} // if (xmlhttp.readyState==4)
		
	} // if (xmlhttp.status == 200)
	
} // xmlhttpstatechangePedirUpgrade





function ComponerTablaPedirTodos(xmlDoc){

	var m=0;
	var tabla = '<table width="98%" border="0" cellspacing="0" cellpadding="0">';
	if (xmlDoc.getElementsByTagName("reservable")[m].childNodes[0].nodeValue > 0) 											{
			
					//		document.getElementById("reservar").disabled=false;
		
					// Imagen, familia y descripción del vehículo seleccionado
					vehic = xmlDoc.getElementsByTagName("vhc")[m].childNodes[0].nodeValue;
					
					lugar = document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value;
				
				
					// Se obtienen los valores del vehículo en particular
					var detalles = {familia:"", foto:"", descripcion:"", extras:""};
					DetallesVehiculo(vehic, lugar, detalles);
				
					// Precio del alquiler
					 precio = xmlDoc.getElementsByTagName("precio")[m].childNodes[0].nodeValue;
					
					// Precio del alquiler con el descuento aplicado
					precio_con_descuento = xmlDoc.getElementsByTagName("precio_con_descuento")[m].childNodes[0].nodeValue;
		
					// Precio de los extras devuelto por "xmlhttp"
					precio_extras = xmlDoc.getElementsByTagName("precio_extras")[m].childNodes[0].nodeValue;//TOTAL DE LOS EXTRAS
					var precio_baby= parseFloat(xmlDoc.getElementsByTagName("precio_baby")[m].childNodes[0].nodeValue);
					var precio_booster=parseFloat(xmlDoc.getElementsByTagName("precio_booster")[m].childNodes[0].nodeValue);
					var precio_fdh=parseFloat(xmlDoc.getElementsByTagName("precio_fdh")[m].childNodes[0].nodeValue);
					var precio_gps=parseFloat(xmlDoc.getElementsByTagName("precio_gps")[m].childNodes[0].nodeValue);
					var precio_delivery=parseFloat(xmlDoc.getElementsByTagName("precio_delivery")[m].childNodes[0].nodeValue);
				
					var cambio_libras=parseFloat(xmlDoc.getElementsByTagName("cambio_libras")[m].childNodes[0].nodeValue);
				
				
				
					// Precio total
					precio_con_extras = (parseFloat(precio_con_descuento) + parseFloat(precio_extras)).toFixed(2);
				precio_libras=(parseFloat(cambio_libras)*parseFloat(precio_con_extras)).toFixed(2);
		
				// Cliente logueado
				logged = xmlDoc.getElementsByTagName("logged")[0].childNodes[0].nodeValue;
				
				// Cliente de Marriott
				es_marriott = (	(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 201) ||
								(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 202) ||
								(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 205) ||
								(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 215) ||
								(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value == 225) );
				
				// Número de dias de la reserva
				num_dias = CalculaNumeroDeDias();
				if (num_dias == 1) {
					texto_dias = num_dias + ' day ';
				} else {
					texto_dias = num_dias + ' days ';
				}
				
				// Tipo de la pecitión (cofirmable u onrequest)
				if (xmlDoc.getElementsByTagName("reservable")[m].childNodes[0].nodeValue==1) {
					tipo_peticion = "OnRequest";
				} else if (xmlDoc.getElementsByTagName("reservable")[m].childNodes[0].nodeValue==2) {
					tipo_peticion = "Confirmable";
				}
		
				// Lo juntamos todo en una tabla
				
				// Datos del vehiculo y precios
		
		
		//BEGIN CRESPY 04-03-10
				tabla=tabla +'<td align="left" valign="bottom">' + detalles.familia + '<br />' + detalles.foto + '</td>' +
		'<td align="center" valign="bottom"><font size="1">' + detalles.descripcion + '</font><br />' + detalles.extras + '</td>' +
		'<td align="right" valign="center" width="30%">';
		if (logged == 'true') { // Se muestra el precio normal y el VIP
			//tabla = tabla + '<font color=#1F97BA><b><s>' + texto_dias + precio + ' &#8364;</s></b></font><br>';
			tabla = tabla + '<font color=#12576B><b>VIP Price ' + precio_con_descuento + ' &#8364;</b></font><br>';
		}else if (es_marriott) { // Se muestra el precio normal y el de Marriott
					//tabla = tabla + '<font color=#1F97BA><b><s>' + texto_dias + precio + ' &#8364;</s></b></font><br>';
					tabla = tabla + '<font color=#12576B><b>Your price ' + precio_con_descuento + ' &#8364;</b></font><br>';
		} else {				// Se muestra solamente el precio normal
			//tabla = tabla + '<font color=#1F97BA><b>' + texto_dias + precio + ' &#8364;</b></font><br>';
		}
		//tabla = tabla + '<font color=#1F97BA><b>Extras ' + precio_extras + ' &#8364;</b></font><br>';
		tabla = tabla + '<font color=#12576B><b>Total ' + precio_con_extras + ' &#8364;</b></font><br>';
		tabla = tabla + '<font color=#12576B size="1"><b>(' + precio_libras + ' &pound;)</b></font><br>';
		//END CRESPY 04-03-10
		
				// Reserva haciendose del club (solo si no esta logueado)

				if 	(	(logged == "false") &&
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 105) &&
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 201) &&
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 202) &&
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 205) &&
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 215) &&
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 225)) {
			
					tabla = tabla + '<tr height="45">\
							<td align="left" colspan="2"></td>\
							<td align="right" valign="top" colspan="1"><input NAME="booknow" id="booknow" type="button" VALUE="Book now"  onClick="JavaScript:SelectUpgrade(\'' + vehic + '\');" class="input-bold"></td>\
							</tr><tr><td colspan="4"><hr align="center" width="100%"></td></tr>';
				} else {
					tabla = tabla + '<tr><td align="right" colspan="3"><INPUT TYPE="button" VALUE="Book now" onClick="JavaScript:SelectUpgrade(\'' + vehic + '\');" name="booknow" id="booknow" class="booknow" !disabled></td></tr><br><tr><td colspan="4"><hr align="center" width="100%"></td></tr>';
					//tabla = tabla + '</table>';
				}
		
				// Informacion del extra por entrega tardia
				if 	(	(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 201) &&
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 202) &&
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 205) &&
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 215) &&
						(document.formPresupuesto.lgr_rtr.options[document.formPresupuesto.lgr_rtr.selectedIndex].value != 225)) {
					
				} else {
					//tabla = tabla + '<tr><td align="center" colspan="3"><font size="1">*If return time is more than two hours later than pick up time, an extra day is added to the price.<br />Full insurance is included. Please see the rental terms.</font></td></tr>';
				}
		
		/*		// Reserva sin hacerse del club
				tabla = tabla + '<tr><td align="right" colspan="3"><INPUT TYPE="button" VALUE="Book now" onClick="JavaScript:CambiarVisibilidadFormularioReserva(false);" name="booknow" id="booknow" class="booknow" !disabled></td></tr>';
				tabla = tabla + '</table>';
		*/		
				// No hay offline
				document.getElementById('reasonoffline').value = '';

	} 
	else {
		return 'no';
	}
		
		return tabla;
}

//END JOSE L. CRESPILLO 