//////////////////////////// HORARIO DE RESERVA /////////////////////////////////////////////////////////////////////
var oficinas = new Array();
//OFICINA DE MALAGA
oficinas[1] = {"D": {"iniciom": 9,"cierrem": 14,"iniciot": 17,"cierret": 20},"S": {"iniciom": 9,"cierrem": 13.30}};
//OFICINA DE LUCENA
oficinas[2] = {"D": {"iniciom": 8,"cierrem": 13.30,"iniciot": 16,"cierret": 20},"S": {"iniciom": 10,"cierrem": 13}};
//OFICINA DE ANTEQUERA
oficinas[3] = {"D": {"iniciom": 9,"cierrem": 14,"iniciot": 17,"cierret": 20},"S": {"iniciom": 9,"cierrem": 14}};
//OFICINA DE MONTILLA SABADOS CERRADOS POR ESO UNDEFINED
oficinas[4] = {"D": {"iniciom": 9,"cierrem": 14,"iniciot": 16,"cierret": 19},"S": {"iniciom": undefined,"cierrem": undefined}};
//OFICINA DE ECIJA
oficinas[5] = {"D": {"iniciom": 9,"cierrem": 14,"iniciot": 15.30,"cierret": 19},"S": {"iniciom": 9,"cierrem": 13}};
//OFICINA DE MANCHA REAL SABADOS CERRADOS POR ESO UNDEFINED
oficinas[6] = {"D": {"iniciom": 9,"cierrem": 14,"iniciot": 16,"cierret": 19},"S": {"iniciom": undefined,"cierrem": undefined}};

var tiposVehiculos = new Array();
tiposVehiculos[1] = {"0": "Selecciona un tipo de vehículo","1": "Furgonetas","2": "Furgones carrozados","3": "Turismos y monovolúmenes"};
tiposVehiculos[2] = {"0": "Selecciona un tipo de máquina","1": "Carretillas elevadoras","2": "Plataformas de tijera","3": "Plataformas telescópicas y articuladas"};

var duracionVehiculos = new Array();
//duracionVehiculos = {"km_ilimitados": {"inicio": 1,"fin": 31,"otros": {"cinco_horas": "5 Horas","fin_de_semana": "Fin de Semana"}},
//					 "tarifa_175kms": {"inicio": 1,"fin": 6},
//					 "maquinaria": {"inicio": 1,"fin": 15}}
duracionVehiculos = { "km_ilimitados": {"inicio": 1,"fin": 31},
		      "tarifa_175kms": {"inicio": 1,"fin": 6},
                      "cinco_horas":   {"inicio": undefined, "fin": undefined, "otros":{"cinco_horas":"5 Horas"}},
                      "fin_de_semana": {"inicio": undefined, "fin": undefined, "otros":{"fin_de_semana":"Fin de Semana"}},
		      "maquinaria":    {"inicio": 1,"fin": 31}
                    }

var tipoSeleccionado;
var diarecogida;
var diaentrega;
var flag_cambiando = false;
					
$(function(){
	
	//DA VALORES A LAS VARIABLES
	tipoSeleccionado = 	$("input[name='tipo']").val();

	$("input[name='tipo']").click(function() {
		tipoSeleccionado = $(this).val();
		$("#seleccion_vehiculos").removeOption(/./).addOption(tiposVehiculos[tipoSeleccionado]).selectOptions("0");
		
		if (tipoSeleccionado == 2) {//SELECCIONA TIPO DE VEHICULO MAQUINARIA
			//DESHABILITA LA MODALIDAD DE ALQUILER
			$("#modalidad").selectOptions("km_ilimitados").attr("disabled","disabled");
		} else {//SELECCIONA TIPO DE VEHICULO FURGONETAS
			//HABILITA LA MODALIDAD DE ALQUILER
			$("#modalidad").selectOptions("km_ilimitados").attr("disabled","");
		}
		//MODIFICA EL SELECT DE DURACION
		$("#modalidad").change();
	});/* FIN INPUT[NAME='TIPO'].CLICK */
	
	//AL CAMBIAR LA FECHA SE MODIFICA EL HORARIO
	$("#fecha").click(function(){
		displayDatePicker('fecha');
	}).blur(function() {
		var sfecha = $("#fecha").val().split('/');
		fecharecogida = new Date(eval('"' + sfecha[1] + '/' + sfecha[0] + '/' + sfecha[2] + '"'));
		diarecogida = fecharecogida.getDay();
		
		var oficina = $("#recogida").val();
		horarios(diarecogida,"horariorecogida",oficina);
		oficina = $("#devolucion").val();
		//horarios(diarecogida,"horarioentrega",oficina);
		//horarios_ent(diarecogida,"horarioentrega",oficina);
                //if ($("#duracion_vehiculos").val() == 'cinco_horas' || $("#duracion_vehiculos").val() == 'fin_de_semana') {
        		$("#duracion_vehiculos").change();
                //}
	});
	
	$("#modalidad").change(function(){
		var duracion;
		if (tipoSeleccionado == 2) {
			duracion = duracionVehiculos.maquinaria;
		} else {
			var modalidad = $("#modalidad option:selected").val();
			duracion = duracionVehiculos[modalidad];
		}

	        $("#duracion_vehiculos").removeOption(/./).addOption(0,"Selecciona");
		if (isset(duracion.otros)) {
			$("#duracion_vehiculos").addOption(duracion.otros);
		}
		
		var texto;
		for (i = duracion.inicio;i <= duracion.fin; i++) {
			if (i == 1) {
				valor = "1 día";
				texto = "1 día";
			} else {
				valor = i + " días";
				texto = i + " días";
			}
			$("#duracion_vehiculos").addOption(valor,texto);
		}

                //alert($("#duracion_vehiculos").val());
                if ($("#duracion_vehiculos").val() == 'cinco_horas' || $("#duracion_vehiculos").val() == 'fin_de_semana') {
                        $("#duracion_vehiculos").removeOption("0");
                        //$("#duracion_vehiculos").selectOptions("1");
                        //$("#duracion_vehiculos").selectOptions("cinco_horas").attr("disabled","disabled");
                        //$("#duracion_vehiculos").selectOptions("fin_de_semana").attr("disabled","disabled");
                }
                else {
                        $("#duracion_vehiculos").selectOptions("cinco_horas").attr("disabled","");
                        $("#duracion_vehiculos").selectOptions("fin_de_semana").attr("disabled","");
                }
		$("#duracion_vehiculos").selectOptions("0");
		$("#duracion_vehiculos").change();
                $("#fecha").blur();
	});/* FIN MODALIDAD.CHANGE */

	$("#duracion_vehiculos").change(function() {
                if ($("#fecha").val() != 'dia/mes/año') {
        		var duracion = $(this).val();
        		var sfecha = $("#fecha").val().split('/');

        		if (duracion == 'cinco_horas' && ($("#recogida option:selected").val() == $("#devolucion option:selected").val())) {
        			//SI LA DURACION DEL ALQUILER SON 5 HORAS ENTONCES EL DIA DE ENTREGA ES EL MISMO QUE EL DE RECOGIDA
        			fechaentrega = new Date(eval('"' + sfecha[1] + '/' + sfecha[0] + '/' + sfecha[2] + '"'));
        			diaentrega = fecharecogida.getDay();
        			//horarios(diaentrega,"horarioentrega",$("#devolucion").val());
        			horarios_ent(diaentrega,"horarioentrega",$("#devolucion").val());

        		} else if (duracion == 'fin_de_semana' && ($("#recogida option:selected").val() == $("#devolucion option:selected").val())) {
        			//SI LA DURACION ES UN FIN DE SEMANA SE RECOGE UN VIERNES Y SE ENTREGA UN LUNES
        			fecharecogida = new Date(eval('"' + sfecha[1] + '/' + sfecha[0] + '/' + sfecha[2] + '"'));
        			diarecogida = fecharecogida.getDay();
        			//EL DIA DE RECOGIDA SELECCIONADO DEBE SER VIERNES
        			if (diarecogida == 5) {
        				var oficina = $("#recogida").val();
        				//RECOGIDA EL VIERNES
        				horarios(5,"horariorecogida",$("#recogida").val());
        				//ENTREGA EL LUNES
        				//horarios(1,"horarioentrega",$("#devolucion").val());
        				horarios_ent(1,"horarioentrega",$("#devolucion").val());
        			} else {
        				//COMO NO ES VIERNES EL DIA DE RECOGIDA SE MUESTRA ERROR Y SE SELECCIONA EL PRIMER DIA DE LA SEMANA
        				alert('Para que la duración sea de un fin de semana debe recoger el vehículo un viernes por la tarde y entregarlo un lunes por la mañana');
        				$(this).selectOptions("0");
        			}

        		} else {
        			if (($("#recogida option:selected").val() != $("#devolucion option:selected").val()) && (duracion == 'cinco_horas' || duracion == 'fin_de_semana' || parseInt(duracion) < 3)) {
        				alert('Cuando la recogida y la entrega es en dos oficinas diferentes el tiempo mínimo de duración del alquiler es de 3 días');
        				$("#recogida").selectOptions("0");
        				$("#devolucion").selectOptions("0");
        				//$(this).selectOptions("0");
        			} else {
        				//AL SER LA DURACION DEL ALQUILER DE 1 DIA O 2, 3, 4, .... SE CALCULA EL DIA DE LA ENTREGA
        				fechaentrega = new Date(eval('"' + sfecha[1] + '/' + sfecha[0] + '/' + sfecha[2] + '"'));
        				fechaentrega.setDate(fechaentrega.getDate() + parseInt(duracion));
        				diaentrega = fechaentrega.getDay();
        				//horarios(diaentrega,"horarioentrega",$("#devolucion").val());
        				horarios_ent(diaentrega,"horarioentrega",$("#devolucion").val());
        			}
        		}
                }
	});//FIN DURACION_VEHICULOS.CHANGE
	
	//AL CAMBIAR EL LUGAR DE RECOGIDA SE MODIFICA EL HORARIO
	$("#recogida").change(function(){
		if ($("#fecha").val() != 'dia/mes/año') {
			var sfecha = $("#fecha").val().split('/');
			fecharecogida = new Date(eval('"' + sfecha[1] + '/' + sfecha[0] + '/' + sfecha[2] + '"'));
			diarecogida = fecharecogida.getDay();
			horarios(diarecogida,"horariorecogida",$(this).val());
                        // nuevo 2.jul.2009
                        horarios_ent(diaentrega,"horarioentrega",$("#devolucion").val());
		}
	});//FIN RECOGIDA.CHANGE

        // al cambiar el horario de recogida se modifica el horario de entrega
	$("#horariorecogida").change(function(){
                if (flag_cambiando == false) {
                        $("#duracion_vehiculos").change();
                        //horarios_ent(diaentrega,"horarioentrega",$("#devolucion").val());
                }
        });

	//AL CAMBIAR EL LUGAR DE ENTREGA SE MODIFICA EL HORARIO
	$("#devolucion").change(function(){
		if ($("#fecha").val() != 'dia/mes/año') {
			var sfecha = $("#fecha").val().split('/');
			var duracion = $("#duracion_vehiculos").val();
			
			fecharecogida = new Date(eval('"' + sfecha[1] + '/' + sfecha[0] + '/' + sfecha[2] + '"'));
			diarecogida = fecharecogida.getDay();

			if (duracion == 'cinco_horas' && ($("#recogida option:selected").val() == $("#devolucion option:selected").val())) {
				//SI LA DURACION DEL ALQUILER SON 5 HORAS ENTONCES EL DIA DE ENTREGA ES EL MISMO QUE EL DE RECOGIDA
				fechaentrega = new Date(eval('"' + sfecha[1] + '/' + sfecha[0] + '/' + sfecha[2] + '"'));	
				diaentrega = fecharecogida.getDay();
				//horarios(diaentrega,"horarioentrega",$(this).val());
				horarios_ent(diaentrega,"horarioentrega",$(this).val());

			} else if (duracion == 'fin_de_semana' && ($("#recogida option:selected").val() == $("#devolucion option:selected").val())) {
				//SI LA DURACION ES UN FIN DE SEMANA SE RECOGE UN VIERNES Y SE ENTREGA UN LUNES
				diarecogida = fecharecogida.getDay();
				//EL DIA DE RECOGIDA SELECCIONADO DEBE SER VIERNES
				if (diarecogida == 5) {
					var oficina = $("#recogida").val();
					//RECOGIDA EL VIERNES
					horarios(5,"horariorecogida",$("#recogida").val());
					//ENTREGA EL LUNES
					//horarios(1,"horarioentrega",$(this).val());
					horarios_ent(1,"horarioentrega",$(this).val());
				} else {
					//COMO NO ES VIERNES EL DIA DE RECOGIDA SE MUESTRA ERROR Y SE SELECCIONA EL PRIMER DIA DE LA SEMANA
					alert('Para que la duración sea de un fin de semana debe recoger el vehículo un viernes por la tarde y entregarlo un lunes por la mañana');
					$("#duracion_vehiculos").selectOptions("0");
				}
				
			} else {
				if (($("#recogida option:selected").val() != $("#devolucion option:selected").val()) && (duracion == 'cinco_horas' || duracion == 'fin_de_semana' || parseInt(duracion) < 3)) {
					alert('Cuando la recogida y la entrega es en dos oficinas diferentes el tiempo mínimo de duración del alquiler es de 3 días');
					$("#recogida").selectOptions("0");
					$("#devolucion").selectOptions("0");
				} else {
					//AL SER LA DURACION DEL ALQUILER DE 1 DIA O 2, 3, 4, .... SE CALCULA EL DIA DE LA ENTREGA
					fechaentrega = new Date(eval('"' + sfecha[1] + '/' + sfecha[0] + '/' + sfecha[2] + '"'));	
					fechaentrega.setDate(fechaentrega.getDate() + parseInt(duracion));
					diaentrega = fechaentrega.getDay();
					//horarios(diaentrega,"horarioentrega",$("#devolucion").val());
					horarios_ent(diaentrega,"horarioentrega",$("#devolucion").val());
				}
			}
		}
	});
	
	$("#enviarconsulta").click(function(){
		validar_formulario();
	});
	
	$("#recogida").change();
	$("#devolucion").change();
});

function horarios(diarecogida,select,oficina)
{
        flag_cambiando = true;

	if (diarecogida == 0) {
		//SI EL DIA DE RECOGIDA O ENTREGA ES DOMINGO ESTA CERRADO Y NO SE PUEDE
		$("#" + select).removeOption(/./).addOption({0: "Domingo Cerrado"});
	} else if (diarecogida > 0 && diarecogida < 6) {
		//SE LIMPIA EL SELECT DONDE SE MUESTRA EL HORARIO
		$("#" + select).removeOption(/./);
		//PRIMERA HORA QUE SERA SELECCIONADA MAS TARDE
		var primero = '';
		//EL TEXTO DE HORA QUE SE MUESTRA EN EL SELECT
		var htext = '';

		//SI LA DURACION DEL ALQUILER ES FIN DE SEMANA ENTONCES SE RECOGE SOLO POR LA TARDE
		if (!($("#duracion_vehiculos").val() == 'fin_de_semana' && diarecogida == 5)) {
			//EL DIA DE RECOGIDA O ENTREGA ES LUNES - VIERNES
			//HORARIO POR LA MAÑANA
			//MINUTOS DE INICIO DEL HORARIO		
			var iniciomins = 0;
			//MINUTOS DE FIN DEL HORARIO
			var finmins = 0;
			
			//SI EL HORARIO DE INICIO TIENE UN . ENTONCES LOS MINUTOS COMIENZAN EN 30
			if (strpos(oficinas[oficina].D.iniciom,'.')) {
				iniciomins = 30;
			}
			//SI EL HORARIO DE CIERRE TIENE UN . ENTONCES LOS MINUTOS COMIENZAN EN 30
			if (strpos(oficinas[oficina].D.cierrem,'.')) {
				finmins = 30;
			}
			
			//HORA LIMITE DE CIERRE
			var limite = sprintf('%02s',parseInt(oficinas[oficina].D.cierrem));
			limite = limite + ':' + sprintf('%02s',(finmins + 15));
			
			//EMPIEZA A GENERAR LOS HORARIOS
			//PRIMERO LA HORA
			for (h= parseInt(oficinas[oficina].D.iniciom);h <= parseInt(oficinas[oficina].D.cierrem); h++) {
				//LUEGO LOS MINUTOS
				for (m = iniciomins; m < 60; m = m + 15) {
					
					//SE GENERA EL TEXTO DE LA HORA QUE VA A SER MOSTRADO
					htext = sprintf('%02s',h) + ':' + sprintf('%02s',m);
					
					//SI LA HORA HA SUPERADO EL LIMITE ENTONCES SE FINALIZA
					if (htext == limite) {
						m = 60;
						continue;
					} else {
						//SE AGREGA LA OPCION DE LA HORA GENERADA
						$("#" + select).addOption(htext,htext);
					}//FIN if (htext == limite)
					
					//SI ES EL PRIMER HORARIO SE GUARDA PARA MAS TARDE SELECCIONARLO
					if (primero == '') {
						primero = htext;
					}//FIN if (primero == '') 
					
				}//FIN for (m = iniciomins; m < 60; m = m + 15) 
			}//FIN for (h= parseInt(oficinas[oficina].D.iniciom);h <= parseInt(oficinas[oficina].D.cierrem); h++)
		}//FIN DURACION ALQUILER FIN DE SEMANA

		//SI LA DURACION DEL ALQUILER ES FIN DE SEMANA ENTONCES SE ENTREGA SOLO POR LA MAÑANA
		if (!($("#duracion_vehiculos").val() == 'fin_de_semana' && diarecogida == 1)) {
		
			//HORARIO POR LA TARDE
			//MINUTOS DE INICIO DEL HORARIO
			var iniciomins = 0;
			//MINUTOS DE FIN DEL HORARIO
			var finmins = 0;
			
			//SI EL HORARIO DE INICIO TIENE UN . ENTONCES LOS MINUTOS COMIENZAN EN 30
			if (strpos(oficinas[oficina].D.iniciot,'.')) {
				iniciomins = 30;
			}
			
			//SI EL HORARIO DE CIERRE TIENE UN . ENTONCES LOS MINUTOS COMIENZAN EN 30
			if (strpos(oficinas[oficina].D.cierret,'.')) {
				finmins = 30;
			}
			
			//HORA LIMITE DE CIERRE
			limite = sprintf('%02s',parseInt(oficinas[oficina].D.cierret));
			limite = limite + ':' + sprintf('%02s',(finmins + 15));
			
			//EMPIEZA A GENERAR LOS HORARIOS
			//PRIMERO LA HORA
			for (h= parseInt(oficinas[oficina].D.iniciot);h <= parseInt(oficinas[oficina].D.cierret); h++) {
				//LUEGO LOS MINUTOS
				for (m = iniciomins; m < 60; m = m + 15) {
					
					//SE GENERA EL TEXTO DE LA HORA QUE VA A SER MOSTRADO
					htext = sprintf('%02s',h) + ':' + sprintf('%02s',m);
					
					//SI LA HORA HA SUPERADO EL LIMITE ENTONCES SE FINALIZA
					if (htext == limite) {
						m = 60;
						continue;
					} else {
						
						//SE AGREGA LA OPCION DE LA HORA GENERADA
						$("#" + select).addOption(htext,htext);
						
						//SI ES EL PRIMER HORARIO SE GUARDA PARA MAS TARDE SELECCIONARLO
						if (primero == '') {
							primero = htext;
						}//FIN if (primero == '') 
					}//FIN if (htext == limite)
				}//FIN for (m = iniciomins; m < 60; m = m + 15)
			}//FIN for (h= parseInt(oficinas[oficina].D.iniciot);h <= parseInt(oficinas[oficina].D.cierret); h++)
		}//FIN DURACION ALQUILER FIN DE SEMANA
		
		//SE SELECCIONA EL PRIMER HORARIO
		$("#" + select).selectOptions(primero);
		
	} else {
		//EL DIA SELECCIONADO ES SABADO Y ES ESPECIAL
		//SI EL SABADO SE ABRE
		if (isset(oficinas[oficina].S.iniciom)) {
			//HORARIO POR LA MAÑANA
			//MINUTOS DE INICIO DEL HORARIO		
			var iniciomins = 0;
			//MINUTOS DE FIN DEL HORARIO
			var finmins = 0;
			//SI EL HORARIO DE INICIO TIENE UN . ENTONCES LOS MINUTOS COMIENZAN EN 30
			if (strpos(oficinas[oficina].S.iniciom,'.')) {
				iniciomins = 30;
			}
			//SI EL HORARIO DE CIERRE TIENE UN . ENTONCES LOS MINUTOS COMIENZAN EN 30
			if (strpos(oficinas[oficina].S.cierrem,'.')) {
				finmins = 30;
			}
			//SE LIMPIA EL SELECT DONDE SE MUESTRA EL HORARIO
			$("#" + select).removeOption(/./);
			//PRIMERA HORA QUE SERA SELECCIONADA MAS TARDE
			var primero = '';
			//EL TEXTO DE HORA QUE SE MUESTRA EN EL SELECT
			var htext = '';
			//HORA LIMITE DE CIERRE
			var limite = sprintf('%02s',parseInt(oficinas[oficina].S.cierrem));
			limite = limite + ':' + sprintf('%02s',(finmins + 15));
			//EMPIEZA A GENERAR LOS HORARIOS
			//PRIMERO LA HORA
			for (h= parseInt(oficinas[oficina].S.iniciom);h <= parseInt(oficinas[oficina].S.cierrem); h++) {
				//LUEGO LOS MINUTOS
				for (m = iniciomins; m < 60; m = m + 15) {
					//SE GENERA EL TEXTO DE LA HORA QUE VA A SER MOSTRADO
					htext = sprintf('%02s',h) + ':' + sprintf('%02s',m);
					//SI LA HORA HA SUPERADO EL LIMITE ENTONCES SE FINALIZA
					if (htext == limite) {
						m = 60;
						continue;
					} else {
						//SE AGREGA LA OPCION DE LA HORA GENERADA
						$("#" + select).addOption(htext,htext);
					}
					//SI ES EL PRIMER HORARIO SE GUARDA PARA MAS TARDE SELECCIONARLO
					if (primero == '') {
						primero = htext;
					}
				}
			}
			//SE SELECCIONA EL PRIMER HORARIO
			$("#" + select).selectOptions(primero);
		} else {
			//LOS SABADOS ESTA CERRADO
			$("#" + select).removeOption(/./).addOption({0: "Sabado Cerrado"});
		}
	}
        flag_cambiando = false;
}

function horarios_ent(diarecogida,select,oficina)
{
        var pontexto = false; // esta variable decide si se pone el texto o no
        var texto_si = 'Por las devoluciones fuera de horarios de oficina, consultarnos.';
        var texto_no = '&nbsp;';
        var shora, horaini, minuini, horalim, minulim, sumadia;
        var htext, iniciomins, finmins;

        flag_cambiando = true;

        // días extra: sólo se utilizan en la modalidad 5 horas cuando se alquila por la noche y se pasan
        // las 5 horas al día siguiente
        sumadia = 0;

	// se limpia el select donde se muestra el horario
        $("#" + select).removeOption(/./);

        if ($("#horariorecogida").val() == 0) {
                pontexto = false;
                htext = 'Domingo Cerrado';
                $("#" + select).addOption(0,htext);
        }
        else {
                // domingo
        	if (diarecogida == 0) {
        		// SI EL DIA DE RECOGIDA O ENTREGA ES DOMINGO ESTA CERRADO Y NO SE PUEDE
                        pontexto = true;
                        shora = $("#horariorecogida").val().split(':');
                        horaini = parseInt(shora[0],10);
                        minuini = parseInt(shora[1],10);
                        horalim = horaini;
                        minulim = minuini;
        		htext = sprintf('%02s',horalim) + ':' + sprintf('%02s',minulim);
                        $("#" + select).addOption(htext,htext);
        	}
                // de lunes a viernes
                else if (diarecogida > 0 && diarecogida < 6) {
        		//EL TEXTO DE HORA QUE SE MUESTRA EN EL SELECT
        		htext = '';

        		//EL DIA DE RECOGIDA O ENTREGA ES LUNES - VIERNES
        		//HORARIO POR LA MAÑANA
        		//MINUTOS DE INICIO DEL HORARIO
        		iniciomins = 0;
        		//MINUTOS DE FIN DEL HORARIO
        		finmins = 0;

        		//SI EL HORARIO DE INICIO TIENE UN . ENTONCES LOS MINUTOS COMIENZAN EN 30
        		if (strpos(oficinas[oficina].D.iniciom,'.')) {
        			iniciomins = 30;
        		}
        		//SI EL HORARIO DE CIERRE TIENE UN . ENTONCES LOS MINUTOS COMIENZAN EN 30
        		if (strpos(oficinas[oficina].D.cierrem,'.')) {
        			finmins = 30;
        		}

                        // si es fin de semana, la entrega es la primera hora de la sucursal
        		if (($("#duracion_vehiculos").val() == 'fin_de_semana')) {
                		h=parseInt(oficinas[oficina].D.iniciom);
                                m=iniciomins;
        			htext = sprintf('%02s',h) + ':' + sprintf('%02s',m);
        			$("#" + select).addOption(htext,htext);
                                pontexto = false;
                        }
                        else {
                                shora = $("#horariorecogida").val().split(':');
                                horaini = parseInt(shora[0],10);
                                minuini = parseInt(shora[1],10);

                                horalim = horaini;
                                minulim = minuini;

                		if (($("#duracion_vehiculos").val() == 'cinco_horas')) {
                                        horalim = horalim + 5;
                                        if (horalim >= 24) {
                                                horalim = horalim - 24;
                                                // a fines informativos tengo que añadir un día a la fecha
                                                sumadia = 1;
                                        }
                                        else sumadia = 0;
                                }

                		htext = sprintf('%02s',horalim) + ':' + sprintf('%02s',minulim);
        			$("#" + select).addOption(htext,htext);

                                if ( ( ( horalim > parseInt(oficinas[oficina].D.iniciom) ||
                                         horalim == parseInt(oficinas[oficina].D.iniciom) && minulim >= iniciomins) &&
                                       ( horalim < parseInt(oficinas[oficina].D.cierrem)  ||
                                         horalim == parseInt(oficinas[oficina].D.cierrem) && minulim <= finmins)
                                     ) ||

                                     ( ( horalim > parseInt(oficinas[oficina].D.iniciot) ||
                                         horalim == parseInt(oficinas[oficina].D.iniciot) && minulim >= iniciomins) &&
                                       ( horalim < parseInt(oficinas[oficina].D.cierret) ||
                                         horalim == parseInt(oficinas[oficina].D.cierret) && minulim <= finmins)
                                     )
                                   ) {
                                        pontexto = false;
                                }
                                else {
                                        pontexto = true;
                                }
        		} // if (fin de semana)
        	}
                // sábado
                else {
        		//EL DIA SELECCIONADO ES SABADO Y ES ESPECIAL
        		//SI EL SABADO SE ABRE
        		if (isset(oficinas[oficina].S.iniciom)) {
                		//EL TEXTO DE HORA QUE SE MUESTRA EN EL SELECT
                		var htext = '';

                		//MINUTOS DE INICIO DEL HORARIO
                		var iniciomins = 0;
                		//MINUTOS DE FIN DEL HORARIO
                		var finmins = 0;
        			//SI EL HORARIO DE INICIO TIENE UN . ENTONCES LOS MINUTOS COMIENZAN EN 30
        			if (strpos(oficinas[oficina].S.iniciom,'.')) {
        				iniciomins = 30;
        			}
        			//SI EL HORARIO DE CIERRE TIENE UN . ENTONCES LOS MINUTOS COMIENZAN EN 30
        			if (strpos(oficinas[oficina].S.cierrem,'.')) {
        				finmins = 30;
        			}
                                shora = $("#horariorecogida").val().split(':');
                                horaini = parseInt(shora[0],10);
                                minuini = parseInt(shora[1],10);

                                horalim = horaini;
                                minulim = minuini;

                		if (($("#duracion_vehiculos").val() == 'cinco_horas')) {
                                        horalim = horalim + 5;
                                        if (horalim >= 24) {
                                                horalim = horalim - 24;
                                                // a fines informativos tengo que añadir un día a la fecha
                                                sumadia = 1;
                                        }
                                        else sumadia = 0;
                                }

                		htext = sprintf('%02s',horalim) + ':' + sprintf('%02s',minulim);
        			$("#" + select).addOption(htext,htext);

                                if ( ( horalim > parseInt(oficinas[oficina].S.iniciom) ||
                                       horalim == parseInt(oficinas[oficina].S.iniciom) && minulim >= iniciomins) &&
                                     ( horalim < parseInt(oficinas[oficina].S.cierrem) ||
                                       horalim == parseInt(oficinas[oficina].S.cierrem) && minulim <= finmins)
                                   ) {
                                        pontexto = false;
                                }
                                else {
                                        pontexto = true;
                                }
        		}
                        else {
        			//LOS SABADOS ESTA CERRADO
                                pontexto = true;
        		}
        	} // if (sábado)

                if (pontexto == true) {
                        document.getElementById("horarioentrega").style.color = 'red';
                        document.getElementById("texto_fuera_horario").innerHTML = texto_si;
                }
                else {
                        document.getElementById("horarioentrega").style.color = 'black';
                        document.getElementById("texto_fuera_horario").innerHTML = texto_no;
                }
        }
        document.getElementById("diasextra").value = sumadia;

        flag_cambiando = false;
}


function validar_formulario() {
	var mensaje = "Algunos datos faltan o son incorrectos:\n\n";
	var OK = 1;
	var sfecha, duracion, diarecogida, fecharecogida;
        var dia,mes,ano,sumadia,dfecha;
        // 26.jun.2009 Se anula
        //var shora, horaini, minuini, horafin, minufin, horalim, minumin;

	if ($("#seleccion_vehiculos option:selected").val() == 0) {
		if (tipoSeleccionado == 1) {
			mensaje += "* Tipo de vehiculo\n";
		} else {
			mensaje += "* Tipo de maquina\n";
		}
		OK = 0;
	}
	
	if ($("#fecha").val() == "dia/mes/año") {
		mensaje += "* Fecha\n";
		OK = 0;
	}

	if ($("#duracion_vehiculos option:selected").val() == "" || $("#duracion_vehiculos option:selected").val() == 0) {
		mensaje += "* Duración de la reserva\n";
		OK = 0;
	}
	
	if ($("#horariorecogida option:selected").val() == 0) {
		mensaje += "* Horario de recogida\n";
		OK = 0;
	}
	if ($("#horarioentrega option:selected").val() == 0) {
		mensaje += "* Horario de entrega\n";
		OK = 0;
	}
	
	if (OK == 0) {
		alert(mensaje);
		return false;
	}
	else {
        	sfecha = $("#fecha").val().split('/');
                duracion = $("#duracion_vehiculos").val();

                // check 1: fecha tiene que ser 2 días después de la fecha actual
                dfecha = new Date();
                dia = dfecha.getDate()+2;
                mes = dfecha.getMonth()+1;
                ano = dfecha.getFullYear();
                if (dia > 31) {
                        sumadia = dia - 31;
                }
                else if (dia > 30 && (mes == 4 || mes == 6 || mes == 9 || mes == 11)) {
                        sumadia = dia - 30;
                }
                else if (dia > 29 && mes == 2 && (ano % 4) == 0) {
                        sumadia = dia - 29;
                }
                else if (dia > 28 && mes == 2 && (ano % 4) != 0) {
                        sumadia = dia - 28;
                }
                else {
                        sumadia = 0;
                }
                if (sumadia > 0) {
                        dia = sumadia;
                        mes = mes + 1;
                }
                if (mes > 12) {
                        mes = 1;
                        ano = ano + 1;
                }
                dia = '00' + dia;
                dia = dia.slice(dia.length-2,dia.length);
                mes = '00' + mes;
                mes = mes.slice(mes.length-2,mes.length);
                dfecha = ano + '-' + mes + '-' + dia;
        	fecharecogida = sfecha[2] + '-' + sfecha[1] + '-' + sfecha[0];
                if (fecharecogida < dfecha) {
        		alert('La fecha debe ser al menos 2 días después de la actual');
                        $("#fecha").select();
                        return false;
                }
                //alert('dfecha = ' + dfecha + '\n' + 'rfecha = ' + fecharecogida);


                // check 2: dos oficinas diferentes cuando la duración mayor de 3 días
        	if (($("#recogida option:selected").val() != $("#devolucion option:selected").val()) && (duracion == 'cinco_horas' || duracion == 'fin_de_semana' || parseInt(duracion) < 3)) {
        		alert('Cuando la recogida y la entrega es en dos oficinas diferentes el tiempo mínimo de duración del alquiler es de 3 días');
                        $("#recogida").select();
                        return false;
                }

                // check 3: el fin de semana tiene que recogerse viernes tarde y entregarse lunes mañana
                if ( duracion == 'fin_de_semana' && ($("#recogida option:selected").val() == $("#devolucion option:selected").val())) {
			fecharecogida = new Date(eval('"' + sfecha[1] + '/' + sfecha[0] + '/' + sfecha[2] + '"'));
			diarecogida = fecharecogida.getDay();
			if (diarecogida != 5) {
				alert('Para que la duración sea de un fin de semana debe recoger el vehículo un viernes por la tarde y entregarlo un lunes por la mañana');
                                $("#fecha").select();
                                return false;
			}
                        if ($("#horariorecogida option:selected").val() < "15:00") {
				alert('Para que la duración sea de un fin de semana debe recoger el vehículo el viernes por la tarde');
                                $("#horariorecogida").select();
                                return false;
                        }
                        if ($("#horarioentrega option:selected").val() > "15:00") {
				alert('Para que la duración sea de un fin de semana debe entregar el vehículo el lunes por la mañana');
                                $("#horarioentrega").select();
                                return false;
                        }
                }

                // check 4: para la modalidad de 5 horas, la entrega no puede ser mayor de 5 horas
                // 26.jun.2009 Se anula
                //if ( duracion == 'cinco_horas' ) {
                //        shora = $("#horariorecogida").val().split(':');
                //        horaini = parseInt(shora[0],10);
                //        minuini = parseInt(shora[1],10);
                //        shora = $("#horarioentrega").val().split(':');
                //        horafin = parseInt(shora[0],10);
                //        minufin = parseInt(shora[1],10);

                //        horalim = horaini + 5;
                //        minulim = minuini;

                //        if (horalim < horafin || horalim == horafin && minulim < minufin) {
                //                alert("La hora de entrega debe ser como máximo 5 horas después de la hora de recogida.");
                //                $("#horarioentrega").focus();
                //                return false;
                //        }
                //}

                // check 5: el resto de las duraciones la hora de entrega tiene que ser igual o mayor de la hora de salida
                if ($("#horarioentrega option:selected").val() > $("#horariorecogida option:selected").val() && duracion != 'cinco_horas') {
                        alert("La hora de entrega debe ser menor o igual que la hora de recogida.");
                        $("#horarioentrega").focus();
                        return false;
                }

       		$("#freserva").submit();
	}
}


function strpos( haystack, needle, offset){
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Onno Marsman    
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14
 
    var i = (haystack+'').indexOf( needle, offset ); 
    return i===-1 ? false : i;
}

function sprintf( ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Ash Searle (http://hexmen.com/blog/)
    // + namespaced by: Michael White (http://getsprink.com)
    // +    tweaked by: Jack
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Paulo Ricardo F. Santos
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: sprintf("%01.2f", 123.1);
    // *     returns 1: 123.10
    // *     example 2: sprintf("[%10s]", 'monkey');
    // *     returns 2: '[    monkey]'
    // *     example 3: sprintf("[%'#10s]", 'monkey');
    // *     returns 3: '[####monkey]'
 
    var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
    var a = arguments, i = 0, format = a[i++];
 
    // pad()
    var pad = function(str, len, chr, leftJustify) {
        if (!chr) chr = ' ';
        var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
        return leftJustify ? str + padding : padding + str;
    };
 
    // justify()
    var justify = function(value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
        var diff = minWidth - value.length;
        if (diff > 0) {
            if (leftJustify || !zeroPad) {
                value = pad(value, minWidth, customPadChar, leftJustify);
            } else {
                value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
            }
        }
        return value;
    };
 
    // formatBaseX()
    var formatBaseX = function(value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
        // Note: casts negative numbers to positive ones
        var number = value >>> 0;
        prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
        value = prefix + pad(number.toString(base), precision || 0, '0', false);
        return justify(value, prefix, leftJustify, minWidth, zeroPad);
    };
 
    // formatString()
    var formatString = function(value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
        if (precision != null) {
            value = value.slice(0, precision);
        }
        return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
    };
 
    // finalFormat()
    var doFormat = function(substring, valueIndex, flags, minWidth, _, precision, type) {
        if (substring == '%%') return '%';
 
        // parse flags
        var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, customPadChar = ' ';
        var flagsl = flags.length;
        for (var j = 0; flags && j < flagsl; j++) switch (flags.charAt(j)) {
            case ' ': positivePrefix = ' '; break;
            case '+': positivePrefix = '+'; break;
            case '-': leftJustify = true; break;
            case "'": customPadChar = flags.charAt(j+1); break;
            case '0': zeroPad = true; break;
            case '#': prefixBaseX = true; break;
        }
 
        // parameters may be null, undefined, empty-string or real valued
        // we want to ignore null, undefined and empty-string values
        if (!minWidth) {
            minWidth = 0;
        } else if (minWidth == '*') {
            minWidth = +a[i++];
        } else if (minWidth.charAt(0) == '*') {
            minWidth = +a[minWidth.slice(1, -1)];
        } else {
            minWidth = +minWidth;
        }
 
        // Note: undocumented perl feature:
        if (minWidth < 0) {
            minWidth = -minWidth;
            leftJustify = true;
        }
 
        if (!isFinite(minWidth)) {
            throw new Error('sprintf: (minimum-)width must be finite');
        }
 
        if (!precision) {
            precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : void(0);
        } else if (precision == '*') {
            precision = +a[i++];
        } else if (precision.charAt(0) == '*') {
            precision = +a[precision.slice(1, -1)];
        } else {
            precision = +precision;
        }
 
        // grab value using valueIndex if required?
        var value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
 
        switch (type) {
            case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
            case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
            case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
            case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'i':
            case 'd': {
                var number = parseInt(+value);
                var prefix = number < 0 ? '-' : positivePrefix;
                value = prefix + pad(String(Math.abs(number)), precision, '0', false);
                return justify(value, prefix, leftJustify, minWidth, zeroPad);
            }
            case 'e':
            case 'E':
            case 'f':
            case 'F':
            case 'g':
            case 'G': {
                var number = +value;
                var prefix = number < 0 ? '-' : positivePrefix;
                var method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
                var textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
                value = prefix + Math.abs(number)[method](precision);
                return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
            }
            default: return substring;
        }
    };
 
    return format.replace(regex, doFormat);
}

function isset(  ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: FremyCompany
    // +   improved by: Onno Marsman
    // *     example 1: isset( undefined, true);
    // *     returns 1: false
    // *     example 2: isset( 'Kevin van Zonneveld' );
    // *     returns 2: true
    
    var a=arguments; var l=a.length; var i=0;
    
    if (l==0) { 
        throw new Error('Empty isset'); 
    }
    
    while (i!=l) {
        if (typeof(a[i])=='undefined' || a[i]===null) { 
            return false; 
        } else { 
            i++; 
        }
    }
    return true;
}
