//*******************************************************************************
// Para cargar las imagenes
//*******************************************************************************

/*function Precarga(nombre,archivo,prof)
	{
	if (document.images)
		{
		eval('document.' + nombre + ' = new Image()');
		eval('document.' + nombre + '.src = "' + prof + archivo + '"');
		}
	}

function PrecargaCotizador()
	{
	Precarga("imagen_1","cotizador_1.jgp","img/")
	Precarga("imagen_2","cotizador_2.jgp","img/")
	Precarga("imagen_3","cotizador_3.jgp","img/")
	Precarga("imagen_4","cotizador_5.jgp","img/")
	Precarga("imagen_5","cotizador_6.jgp","img/")
	Precarga("imagen_6","cotizador_7.jgp","img/")
	Precarga("imagen_7","cotizador_8.jgp","img/")
	Precarga("imagen_8","cotizador_9.jgp","img/")
	}
*/
function ImagenModelo(form)
	{
	/*var ruta= "";
	if (form == "cotizador_index")
		var ruta = "daperton/";
		
	document.ver_modelo.src = ruta + "img/cotizador_" + eval("document."+form+".modelos.value")+".jpg";*/

	}

//*******************************************************************************


//*******************************************************************************
// Para Abrir las ventanas
//*******************************************************************************

var ventana;
var ventana_abierta = false;

function Abrir_Ventana(url,nombre,propiedades,ancho,alto,centro)
	{
	if (centro)
		{
		ancho_pantalla = screen.width;
		alto_pantalla = screen.height;
		ventana = window.open(url,nombre,propiedades + ",left=" + (ancho_pantalla/2 - ancho/2) + ",top=" + (alto_pantalla/2 - alto/2));		
		}
	else
		{
		ventana = window.open(url,nombre,propiedades);
		}
	ventana.focus ();
	ventana_abierta = true;		
	}

function Abrir_Ventana_Modal(url,nombre,propiedades,ancho,alto,centro)
	{
	if (centro)
		{
		ancho_pantalla = screen.width;
		alto_pantalla = screen.height;
		ventana = window.showModalDialog(url,propiedades + ",left=" + (ancho_pantalla/2 - ancho/2) + ",top=" + (alto_pantalla/2 - alto/2));
		}
	else
		{
		window.showModalDialog(url,"resizable: yes; help: no; status: no; scroll: no;");
		//ventana = window.showModalDialog(url,nombre, propiedades);
		}
	//ventana.focus ();
	//ventana_abierta = true;	
	}
//*******************************************************************************	
//*******************************************************************************
// Para el Cotizador
//*******************************************************************************

var DiasFestivos = new Array(11)

DiasFestivos[0] = "01/01/2010 (Año Nuevo)";
DiasFestivos[1] = "06/01/2010 (Epifanía del Señor)";
DiasFestivos[2] = "19/03/2010 (San José)";
DiasFestivos[3] = "01/04/2010 (Jueves Santo)";
DiasFestivos[4] = "02/04/2010 (Viernes Santo)";
DiasFestivos[5] = "01/05/2010 (Fiesta del Trabajo)";
DiasFestivos[6] = "12/10/2010 (Fiesta Nacional de España)";
DiasFestivos[7] = "01/11/2010 (Todos los Santos)";
DiasFestivos[8] = "06/12/2010 (Día de la Constitución Española)";
DiasFestivos[9] = "08/12/2010 (Inmaculada Concepción)";
DiasFestivos[10] = "25/12/2010 (Natividad del Señor)";

//Festivos de Barcelona
//var DiasFestivos_08 = new Array(6)

//DiasFestivos_08[0] = "24/03/2008 (Lunes de Pascua)";
//DiasFestivos_08[1] = "12/05/2008 (Fiesta Local)";
//DiasFestivos_08[2] = "24/06/2008 (San Juan)";
//DiasFestivos_08[3] = "11/09/2008 (Fiesta Nacional de Cataluña)";
//DiasFestivos_08[4] = "24/09/2008 (Nª Sra. de La Mercé)";
//DiasFestivos_08[5] = "26/12/2008 (San Esteban)";

//Festivos de Madrid
var DiasFestivos_28 = new Array(3)

DiasFestivos_28[0] = "15/05/2010 (San Isidro)";
DiasFestivos_28[1] = "03/06/2010 (Corpus Christi)";
DiasFestivos_28[2] = "09/11/2010 (Ntra. Sra. de la Almudena)";

function ValidarFecha(fecha) {
	var correcto = false;

	if ((fecha == null) || (fecha.length == 0)) 
		{
		alert("Debe especificar una fecha");
		return correcto;
		}
	
	dia= fecha.substring(0,2);
	mes= fecha.substring(3,5);
	anyo = fecha.substring(6,10);
	
	if(fecha.length!=10) 
		{
    	alert("El formato debe ser dd/mm/aaaa");
		
		return correcto;
		}
	if (isNaN(dia)) 
		{
		alert("Solo se pueden escribir números en el espacio de los días");
		return correcto;
		}
	if (isNaN(mes))
		{
		alert("Solo se pueden escribir números en el espacio de los meses");
		return correcto;
		}
	if (isNaN(anyo))
		{
		alert("Solo se pueden escribir números en el espacio de los años");
		return correcto;
		}
	sArray = fecha.split("/");
  	if (sArray.length > 3) 
  		{
  		alert("El formato debe ser dd/mm/aaaa");
    	return correcto;
    	}   	
  	if ((sArray[0].length!=2) || (sArray[1].length!=2) || (sArray[2].length!=4)) 
  		{
		alert("El formato debe ser dd/mm/aaaa");
		return correcto; 
		}	
	var dia = parseInt(fecha.substr(0,2),10);
    var mes = parseInt(fecha.substr(3,2),10);
    var anyo = parseInt(fecha.substr(6,4),10);

	var inicio = new Fecha (fecha_hoy);		
	var inicios = new Fecha (inicio.DateAdd ("y",2,2));
	inicio.DateAdd ("y",-2,2);	
	if((anyo< inicio.Year ()) || (anyo>inicios.Year ())) 
		{		
    	alert("El año debe estar comprendido entre el actual y el " + inicios.Year ());
    	return correcto;
    	}
	if((mes>12) || (mes<1)) 
		{
		alert("El mes debe estar comprendido entre 1 y 12");
		return correcto;
		}
	if((mes==4)||(mes==6)||(mes==9)||(mes==11)) 
		{
    	if((dia>30) || (dia<1)) 
    		{
	    	alert(" El valor del dia debe estar comprendido entre 1 y 30");
    		return correcto;
    		}
    	}
		
    if((mes==1)||(mes==3)||(mes==5)||(mes==7)||(mes==8)||(mes==10)||(mes==12)) 
		{
    	if((dia>31) || (dia<1)) 
    		{
	    	alert(" El valor del dia debe estar comprendido entre 1 y 31");
    		return correcto;
    		}
    	}
    if((mes==2) && (!Bisiesto(anyo))) 
		{
    	if((dia>28) || (dia<1)) 
    		{
	    	alert(" El valor del dia debe estar comprendido entre 1 y 28");
    		return correcto;
    		}
    	}
    else if((mes==2) && (Bisiesto(anyo))) 
    	{
    	if((dia>29) || (dia<1)) 
    		{
	    	alert(" El valor del dia debe estar comprendido entre 1 y 29");
    		return correcto;
    		}
    	}	
	return true
	}

function Bisiesto(anyo)
	{
	if ((anyo%4)==0 && (anyo%200!=0))
		{
		return true;
		}
	else
		{
		return false;
		}
	}

function CompararFechas(fecha_a,fecha_b,iguales)
	{
	//alert ("comparaFechas");
	dia_a = parseFloat(fecha_a.substring(0,2));
	mes_a = parseFloat(fecha_a.substring(3,5));
	ano_a = parseFloat(fecha_a.substring(6,10));
	
	dia_b = parseFloat(fecha_b.substring(0,2));
	mes_b = parseFloat(fecha_b.substring(3,5));
	ano_b = parseFloat(fecha_b.substring(6,10));
	
	if (ano_a < ano_b)
		{
		return true
		}
	else if (ano_a > ano_b)
		{
		return false
		}
	else
		{
		if (mes_a < mes_b)
			{
			return true
			}
		else if (mes_a > mes_b)
			{
			return false
			}
		else
			{
			if (dia_a < dia_b)
				{
				return true
				}
			else if (dia_a > dia_b)
				{
				return false
				}
			else
				{
				return iguales;
				}
			}
		}
	}
	
function ValidarHora(tiempo)
	{
	hora = tiempo.substring(0,2);
	minuto = tiempo.substring(3,5);
	
	if(tiempo.length!=5) 
		{
    	alert("El formato debe ser hh:mm");
		return false;
		}
	if (isNaN(hora)) 
		{
		alert("Solo se pueden escribir números en el espacio de las horas");
		return false;
		}
	if (isNaN(minuto)) 
		{
		alert("Solo se pueden escribir números en el espacio de los minutos");
		return false;
		}
	tiempoArray = tiempo.split(":");
  	if (tiempoArray.length > 2) 
  		{
  		alert("El formato debe ser hh:mm");
    	return false;
    	} 
	if ((tiempoArray[0].length!=2) || (tiempoArray[1].length!=2)) 
  		{
		alert("El formato debe ser hh:mm");
		return false; 
		}
	var hora = parseInt(tiempo.substr(0,2));
    var minuto = parseInt(tiempo.substr(3,2));
	
	if (hora < 0 || hora > 23)
		{
		alert("La hora debe estar entre 0 y 23");
		return false;
		}
	if (minuto < 0 || minuto > 59)
		{
		alert("Los minutos deben estar entre 0 y 59");
		return false;
		}
		
	return true;
	}

function CompararHoras(tiempo_a,tiempo_b,iguales)
	{
	hora_a = parseInt(tiempo_a.substring(0,2));
	minuto_a = parseInt(tiempo_a.substring(3,5));
	
	hora_b = parseInt(tiempo_b.substring(0,2));
	minuto_b = parseInt(tiempo_b.substring(3,5));

	if (hora_a < hora_b)
		{
		return true
		}
	else if (hora_a > hora_b)
		{
		return false
		}
	else
		{
		if (minuto_a < minuto_b)
			{
			return true
			}
		else if (minuto_a > minuto_b)
			{
			return false
			}
		else
			{
			return iguales;
			}
		}
	}


function HorasEntre(tiempo_a,tiempo_b,tiempo_c,iguales)
	{
	hora_a = parseInt(tiempo_a.substring(0,2));
	minuto_a = parseInt(tiempo_a.substring(3,5));
	
	hora_b = parseInt(tiempo_b.substring(0,2));
	minuto_b = parseInt(tiempo_b.substring(3,5));
	
	hora_c = parseInt(tiempo_c.substring(0,2));
	minuto_c = parseInt(tiempo_c.substring(3,5));
	
	if (hora_a < hora_b && hora_b < hora_c)
		{return true}
	else if (hora_a == hora_b && hora_b < hora_c)
		{
		if (minuto_a < minuto_b)
			{return true}
		else if (minuto_a > minuto_b)
			{return false}
		else
			{return iguales}
		}
	else if (hora_a < hora_b && hora_b == hora_c)
		{
		if (minuto_b < minuto_c)
			{return true}
		else if (minuto_b > minuto_c)
			{return false}
		else
			{return iguales}
		}
	}	

	
function RedondearEuro(numero)
	{
	if (!isNaN(numero))
		{
		X = 2;

		numero = Math.round(numero*Math.pow(10,X))/Math.pow(10,X);
		
		numero_s = numero + "";
		
		if (numero_s.indexOf(".") == -1)
			{
			numero_s = numero_s + ".00"
			return numero_s;
			}
		else
			{
			dec = numero_s.substring(numero_s.indexOf(".")+1,numero_s.indexOf(".")+3);
			
			if (dec.length == 1)
				{
				numero_s = numero_s + "0";
				}
			
			return numero_s;
			}
		}
	else
		{
		return numero;
		}
	}	
//***************************************************************************************************
//	Función para validar campos numéricos
//  Parámetro de entrada:
//		Formato
//			0.- Sólo acepta el formato numérico
//			1.- Acepta el "."
//			2.- Acepta el ","
//			3.- Acepta el " "
//			4.- Acepta el "." y ","
//			5.- Acepta el ".", "," y " "
//		valor: número a validar
//		nombrecampo: 
//	Parámetros de salida:
//		True si el formato es correcto
//		False si el formato no es correcto
//****************************************************************************************************
function ComprobarCampoNumerico (formato, valor, nombrecampo)
	{
	var caracteres = "!" + '"' + "#$%&'()*+/:;<=>?\]^`{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•—˜™š›œžŸ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæççèéêëìíîïðñòóôõö÷øùúûüýþ";
	for (i = 0 ; i < caracteres.length ; i++)
		{
		if (valor.indexOf(caracteres.substring(i,i+1)) != -1)
			{
			alert("El campo " + nombrecampo + " contiene caracteres no válidos.");
			return false;
			}
		}

	var sub_valor = "";
	// no acepta nada
	if (formato == 0)
		{
		if (isNaN (valor) || valor.indexOf (".") != -1)
			{			
			alert("El campo " + nombrecampo + " tiene que ser numérico.");
			return false;
			}					
		}
	// acepta el .
	else if (formato == 1)
		{
		sub_valor = valor.split (".");
		if (sub_valor.length == 1)
			{
			if (isNaN (valor))
				{			
				alert("El campo " + nombrecampo + " tiene que ser numérico.");
				return false;
				}			
			}
		else if (sub_valor.length == 2)
			{
			if (isNaN (sub_valor [0]) || isNaN (sub_valor [1]))
				{			
				alert("El campo " + nombrecampo + " tiene caracteres incorrectos.");
				return false;
				}				
			}
		else
			{
			alert("El campo " + nombrecampo + " no puede contener más de un punto.");
			return false;
			}
		}
	else if (formato == 2)
		{
		//acepta ,
		sub_valor = valor.split (",");

		if (sub_valor.length == 1)
			{
			if (isNaN (valor) || valor.indexOf (".") != -1)
				{			
				alert("El campo " + nombrecampo + " tiene que ser numérico.");
				return false;
				}			
			}
		else if (sub_valor.length == 2)
			{			
			//si pongo por ejemplo 22,3. o 22,.3 peta, PENDIENTE DE ARREGLAR
			if (isNaN (sub_valor[0]) || isNaN (sub_valor[1]) || sub_valor[0].indexOf (".") != -1 || sub_valor[1].indexOf (".") != -1)
				{			
				alert("El campo " + nombrecampo + " tiene caracteres incorrectos.");
				return false;
				}				
			}
		else
			{
			alert("El campo " + nombrecampo + " no puede contener más una coma.");
			return false;
			}
		}
	else if (formato == 3)
		{
		
		sub_valor = Reemplazar (valor," ", "");

		 if (isNaN (sub_valor) || sub_valor.indexOf (".") != -1)
				{			
				alert("El campo " + nombrecampo + " tiene que ser numérico.");
				return false;
				}
		}
	//acepta , y .
	else if (formato == 4)
		{
		if (valor.indexOf(" ") != -1)
			{
			alert("El campo " + nombrecampo + " no puede tener espacios.");
			return false;
			}
		var losdos = 0;
		//acepta ,
		sub_valor = valor.split (",");

		if (sub_valor.length == 1)
			{
			if (isNaN (valor))
				{			
				alert("El campo " + nombrecampo + " tiene que ser numérico.");
				return false;
				}			
			}
		else if (sub_valor.length == 2)
			{			
			//si pongo por ejemplo 22,3. o 22,.3 peta, PENDIENTE DE ARREGLAR
			if (isNaN (sub_valor[0]) || isNaN (sub_valor[1]))
				{			
				alert("El campo " + nombrecampo + " tiene caracteres incorrectos.");
				return false;
				}	
			losdos = 1;	
			}
		else
			{
			alert("El campo " + nombrecampo + " no puede contener más una coma.");
			return false;
			}
		//acepta .			
		sub_valor = valor.split (".");
		if (sub_valor.length == 1)
			{
			sub_valor = Reemplazar (valor,",","");
			if (isNaN (sub_valor))
				{			
				alert("El campo " + nombrecampo + " tiene que ser numérico.");
				return false;
				}			
			}
		else if (sub_valor.length == 2)
			{
			if (isNaN (Reemplazar (sub_valor [0],",", "")) || isNaN (Reemplazar (sub_valor [1],",", "")))
				{			
				alert("El campo " + nombrecampo + " tiene caracteres incorrectos.");
				return false;
				}		
			losdos = losdos +1;		
			}
		else
			{
			alert("El campo " + nombrecampo + " no puede contener más de un punto.");
			return false;
			}		
		if (losdos == 2)
			{
			alert("El campo " + nombrecampo + " tiene caracteres incorrectos.");
			return false;
			}	
			//controlar que no tenga espacios
		}
		return true;
	}
//******************************************************************************************************		
	
function ComprobarEntrada(formulario)
	{
	// Si es valida la fecha
	if (!ValidarFecha(eval('document.'+formulario+'.fecha_inicio.value'))) {eval('document.'+formulario+'.fecha_inicio.focus()'); return false}
	if (!ValidarFecha(eval('document.'+formulario+'.fecha_fin.value'))) {eval('document.'+formulario+'.fecha_fin.focus()'); return false}
	
	// Si es fin de semana
	diario = 0;
	var raiz, texto_error;
	if (formulario == "reservar_index"){raiz = "daperton/";}else{raiz=""};
	if (DiaDeLaSemana(eval('document.'+formulario+'.fecha_inicio.value')) != 5 || !CompararFechas(eval('document.'+formulario+'.fecha_inicio.value'),eval ('document.'+formulario+'.fecha_fin.value'),false) || DiaDeLaSemana(eval('document.'+formulario+'.fecha_fin.value')) != 1 || SiguienteDia(eval ('document.'+formulario+'.fecha_inicio.value'),1) != eval ('document.'+formulario+'.fecha_fin.value'))
		{
		diario = 1;
		}
	
	// Si es anterior a Hoy
	if (formulario == 'reservar' || formulario == 'reservar_index')
		{
		var inicio = new Fecha (fecha_hoy);
		if (!CompararFechas(fecha_hoy,eval ('document.'+formulario+'.fecha_inicio.value'),true))
			{
			texto_error = "La fecha mínima de inicio de alquiler es el <b>" + inicio.FormatDate(1) + "</b>.";
			abrirVentana(raiz + "error.asp?error=" + texto_error, 440, 200,"Error");
			eval('document.'+formulario+'.fecha_inicio.focus()');
			eval('document.'+formulario+'.fecha_inicio.select()');
			return false;
			}
		else if (!CompararFechas(fecha_hoy,eval ('document.'+formulario+'.fecha_inicio.value'),false))
			{
			if (!CompararHoras(hora_hoy, eval('document.'+formulario+'.hora_inicio.value'),true)){
				texto_error = "La fecha mínima de inicio de alquiler es el <b>" + inicio.FormatDate(1) + " " + hora_hoy + "</b>.";
				abrirVentana(raiz + "error.asp?error=" + texto_error, 460, 200,"Error");
				eval('document.'+formulario+'.hora_inicio.focus()');
				eval('document.'+formulario+'.hora_inicio.select()');
				return false;			
				}
			}
		}
	else 
		{
		if (!CompararFechas(fecha_hoy,eval ('document.'+formulario+'.fecha_inicio.value'),true))
			{
			alert("La fecha mínima de inicio de alquiler es el " + fecha_hoy + ".");
			eval('document.'+formulario+'.fecha_inicio.focus()');
			eval('document.'+formulario+'.fecha_inicio.select()');
			return false;
			}
		}
	
	// Igual o posterior a la de Fin

		var date_ini = new Fecha($("#fecha_inicio").val() + " " + $("#hora_inicio").val())
		var date_fin = new Fecha($("#fecha_fin").val() + " " + $("#hora_fin").val())
		
		//if (!CompararFechas(eval ('document.'+formulario+'.fecha_inicio.value'),eval ('document.'+formulario+'.fecha_fin.value'),false))
		// Change for end date to be same as start date ... also check the times!
		if (parseFloat(date_ini.DateDiff('d', date_fin.FormatDate(0))) <= 0)
		{
		texto_error = "La fecha de inicio de alquiler debe ser anterior a la de fin.";
		abrirVentana(raiz + "error.asp?error=" + texto_error, 400, 200,"Error");
		eval('document.'+formulario+'.fecha_inicio.focus()');
		eval('document.'+formulario+'.fecha_inicio.select()');
		return false;
		}	
	
	// FECHA FIN
	
	// Si es valida
	
	
	// Si es posterior a Hoy
	
	if (!CompararFechas(fecha_min,eval ('document.'+formulario+'.fecha_fin.value'),true))
		{
		texto_error = "La fecha mínima de fin de alquiler es el " + fecha_min + ".";
		abrirVentana(raiz + "error.asp?error=" + texto_error, 440, 200,"Error");
		eval('document.'+formulario+'.fecha_fin.focus()');
		eval('document.'+formulario+'.fecha_fin.select()');
		return false;
		}
	
	// Igual o posterior a la de Fin
	
	if (!(eval ('document.'+formulario+'.fecha_inicio.value'),eval ('document.'+formulario+'.fecha_fin.value'),true))
		{
		texto_error = "La fecha de fin de alquiler debe ser igual o posterior a la de inicio.";
		abrirVentana(raiz + "error.asp?error=" + texto_error, 440, 200,"Error");
		eval('document.'+formulario+'.fecha_fin.focus()');
		eval('document.'+formulario+'.fecha_fin.select()');
		return false;
		}
		return true;
	}

		
function SiguienteDia(fecha,dia)
	{
	var fecha_formato
	almacen = fecha.split("/")
	fecha_formato = new Date(almacen[2],almacen[1]-1,almacen[0]);			
	dia_fecha = fecha_formato.getDay();
	if (dia_fecha == 0)
		{
		dia_fecha = 7;
		}
	
	if (dia_fecha < dia)
		{
		fecha_nueva = new Date(fecha_formato.getTime() + (86400000 * (dia - dia_fecha)))
		}
	else if (dia_fecha == dia)
		{
		fecha_nueva = new Date(fecha_formato.getTime() + (86400000 * 7))
		}
	else if (dia_fecha > dia)
		{
		//Se cambia la hora el último fin de semana de octubre, por tanto añado una hora para el cálculo de la tarifa de fin de semana.
		if (fecha == "28/10/2005" || fecha == "27/10/2006" || fecha == "26/10/2007" || fecha == "24/10/2008")
			{
			fecha_nueva = new Date(fecha_formato.getTime() + (86400000 * ((dia + 7) - dia_fecha)) + 3600000)
			}
		else
			{
			fecha_nueva = new Date(fecha_formato.getTime() + (86400000 * ((dia + 7) - dia_fecha)))
			}
		
		}
	
	dia = fecha_nueva.getDate();
	mes = fecha_nueva.getMonth() + 1;
	ano = fecha_nueva.getFullYear();
	
	if (dia < 10) dia = "0" + dia; 
	if (mes < 10) mes = "0" + mes;
	
	return dia + "/" + mes + "/" + ano;
	}	

function DiaDeLaSemana(fecha)
	{
	buffer = fecha.split("/");
	tiempo = new Date(buffer[2],buffer[1] - 1,buffer[0]);
	
	dia = tiempo.getDay();
	if (dia == 0) {dia = 7;}
	return dia;
	}

//*******************************************************************************

function ComprobarEmail(email)
	{
	sub_correo = email.split("@");
	
	if (email.indexOf("@") == -1 || sub_correo.length != 2)
		{
		alert("El campo E-mail debe contener sólo una @.\n\n(Ejemplo: sumonbre@sudominio.es, .com, .net, etc.)");
		return false;
		}
	if (email.length < 6)
		{
		alert("El campo E-mail debe contener al menos 6 caracteres.\n\n(Ejemplo: sumonbre@sudominio.es, .com, .net, etc.)");
		return false;
		}
	if (sub_correo[1].indexOf(".") == -1)
		{
		alert("El campo E-mail debe contener al menos un punto (\".\") después de la @.\n\n(Ejemplo: sumonbre@sudominio.es, .com, .net, etc.)");
		return false;
		}
	
	var dominio = sub_correo[1].substring(sub_correo[1].indexOf(".")+1)
	
	if (dominio.length < 2)
		{
		alert("El campo E-mail no tiene el formato adecuado. El dominio \"" + sub_correo[1] + "\" parece no ser correcto.\n\n(Ejemplo: sumonbre@sudominio.es, .com, .net, etc.)");
		return false;
		}
	//ITG 28/04/08: Los correos .es aceptan cedilla, acentos y ñ. En principio pongo que acepten esos caracteres, pero hay que hacerlo sólo par los .es
	//var caracteres = "!" + '"' + "#$%&'()*+,/:;<=>?\]^`{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæççèéêëìíîïðñòóôõö÷øùúûüýþ";
	var caracteres = "!" + '"' + "#$%&'()*+,/:;<=>?\]^`{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàâãäåæççèêëìîïðòôõö÷øùûüýþ";
	
	for (i = 0 ; i < caracteres.length ; i++)
		{
		if (email.indexOf(caracteres.substring(i,i+1)) != -1)
			{
			alert("El campo E-mail contiene caracteres no válidos.");
			return false;
			}
		}
	return true;
	}

function ComprobarEmail_uk(email)
	{
	sub_correo = email.split("@");
	
	if (email.indexOf("@") == -1 || sub_correo.length != 2)
		{
		alert("The field e-mail must contain only one @.\n\n(For example: yourname@yourdomine.es, .com, .net, etc.)");
		return false;
		}
	if (email.length < 6)
		{
		alert("The field E-mail must contain minimun 6 caracters.\n\n(For example: yourname@yourdomine.es, .com, .net, etc.)");
		return false;
		}
	if (sub_correo[1].indexOf(".") == -1)
		{
		alert("The field E-mail must contain a dot. (\".\") before @.\n\n(For example: yourname@yourdomine.es, .com, .net, etc.)");
		return false;
		}
	
	var dominio = sub_correo[1].substring(sub_correo[1].indexOf(".")+1)
	
	if (dominio.length < 2)
		{
		alert("The field E-mail hasn´t the correct format.The domine \"" + sub_correo[1] + "\" looks not be correct.\n\n(For example: yourname@yourdomine.es, .com, .net, etc.)");
		return false;
		}
		
	var caracteres = "!" + '"' + "#$%&'()*+,/:;<=>?\]^`{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæççèéêëìíîïðñòóôõö÷øùúûüýþ";
	
	for (i = 0 ; i < caracteres.length ; i++)
		{
		if (email.indexOf(caracteres.substring(i,i+1)) != -1)
			{
			alert("The field E-mail hasn´t correct caracters or not valid.");
			return false;
			}
		}
	return true;
	}

//*******************************************************************************
// Formulario de Contacto
//*******************************************************************************

function EnviarConsulta(form)
	{
	error = 0;
	
	if (document.contacto.nombre.value == "")
		{
		alert("Debes indicar al menos el nombre de una persona de contacto.")
		document.contacto.nombre.focus();
		error = 1;
		}
	
	if (document.contacto.email.value != "" && error == 0)
		{		
		if (!ComprobarEmail(document.contacto.email.value))
			{	
			document.contacto.email.focus();
			error = 1;
			}
		}
		
	if (document.contacto.email.value == "" && document.contacto.telefono.value == "" && error == 0)
		{		
		alert("Debes indicar al menos un modo de contacto, teléfono o email.")
		document.contacto.nombre.focus();
		error = 1;		
		}
	if (document.contacto.aceptar_condiciones.checked == false && error == 0)
		{
		alert("Debes aceptar las condiciones.")
		document.contacto.aceptar_condiciones.focus();
		error = 1;
		}
		
	if (error == 0)
		{
		document.contacto.action = "t_contacto.asp";
		document.contacto.submit();
		}
	}
//** UK **
function EnviarConsulta_uk()
	{
	error = 0;
	
	if (document.contacto.nombre.value == "")
		{
		alert("You must write one contact person.")
		document.contacto.nombre.focus();
		error = 1;
		}
	
	if (document.contacto.email.value == "" && error == 0)
		{
		alert("You must write one contact e-mail.")
		error = 1;
		}
		
	if (error == 0)
		{
		if (!ComprobarEmail_uk(document.contacto.email.value))
			{	
			document.contacto.email.focus();
			error = 1;
			}
		}
				
	if (document.contacto.informacion.value == "" && error == 0)
		{
		alert("You must write one query.")
		error = 1;		
		}
				
	if (error == 0)
		{
		document.contacto.action = "t_contacto.asp";
		document.contacto.submit();
		}
	}
//**********
function EnviarConsultaEncuesta()
	{
	error = 0;
	
	if (document.contacto.nombre.value == "")
		{
		alert("Debes indicar al menos el nombre de una persona de contacto.")
		document.contacto.nombre.focus();
		error = 1;
		}
	
	if (document.contacto.email.value != "" && error == 0)
		{
		if (!ComprobarEmail(document.contacto.email.value))
			{	
			document.contacto.email.focus();
			error = 1;
			}
		}
	
	if (document.contacto.provincia.value == "" && error == 0)
		{
		alert("Debes indicar tu provincia.")
		document.contacto.provincia.focus();
		error = 1;
		}
		
	if (error == 0)
		{
		document.contacto.submit();
		}
	}	
//***************************************************************************
//********** Funcion adaptada para promocion Burger 24 de enero de 2008 *****
function EnviarConsultaBurger()
	{
	error = 0;
	if (document.burger.burger_importe.value == "")
		{
		alert("Es necesario indicar el importe del ticket.")
		document.burger.burger_importe.focus();
		error = 1;
		}

	if (isNaN (document.burger.burger_importe.value.replace(",", ".")) && error == 0)
		{
		alert("El campo Importe Ticket debe ser numérico")
		document.burger.burger_importe.focus();
		error = 1;
		}	
	if (document.burger.burger_ticket.value == "" && error == 0)
		{
		alert("Es necesario indicar el nº del ticket.")
		document.burger.burger_ticket.focus();
		error = 1;
		}	

	if (error == 0)
		{
		document.burger.submit();
		}
	}	
	
//***************************************************************************
//********** Funcion adaptada para promocion ES 24 de enero de 2008 *****
function EnviarConsultaES()
	{
	error = 0;
	if (document.es.es_importe.value == "")
		{
		alert("Es necesario indicar el importe del ticket.")
		document.es.es_importe.focus();
		error = 1;
		}

	if (isNaN (document.es.es_importe.value.replace(",", ".")) && error == 0)
		{
		alert("El campo Importe Ticket debe ser numérico")
		document.es.es_importe.focus();
		error = 1;
		}	
	if (document.es.es_ticket.value == "" && error == 0)
		{
		alert("Es necesario indicar el nº del ticket.")
		document.es.es_ticket.focus();
		error = 1;
		}	

	if (error == 0)
		{
		document.es.submit();
		}
	}	
//***************************************************************************

//***************************************************************************
function VerCalendario(campo,form)
	{
	var date_ini  = new Fecha (eval ("document." + form + ".fecha_inicio.value"))
	if (campo == 1 && (date_ini.CheckDate () && eval ("document." + form + ".fecha_inicio.value != ''")))
		{
		ahora = eval ("document." + form + ".fecha_inicio.value");
		}
	else
		{
		ahora = fecha_hoy;
		}
		
	date_fin  = new Fecha (eval ("document." + form + ".fecha_fin.value"))
	
	if ((campo == 1 && (!date_fin.CheckDate () || eval ("document." + form + ".fecha_fin.value == ''"))) || (campo == 0 && ahora == fecha_hoy))
		{
		if (eval ("document." + form + ".fecha_inicio.value == ''") || !date_ini.CheckDate ())
			{
			    inicio = new Fecha(fecha_hoy);
			    // Change to allow end date to be same as start date
			    // inicio = new Fecha(eval("document." + form + ".fecha_inicio.value"));			
			}
		else
			{
			inicio = new Fecha(eval ("document." + form + ".fecha_inicio.value"));			
			}
		}
	else
		{
		var inicio = new Fecha(eval ("document." + form + ".fecha_fin.value"));
		}
		
	if (form == "reservar_index") 
		{
		//ventana = window.open("daperton/calendario.asp?campo=" + campo + "&mes=" + inicio.Month () + "&ano=" + inicio.Year () + "&form=" + form + "&ahora=" + ahora,"Calendario","toolbar=no,location=no,status=no,menubar=no,scrollbars=no,width=320,height=240,left="+ (screen.width/2 - 320/2) +",top=" + (screen.height/2 - 240/2));
		abrirVentana("daperton/calendario.asp?campo=" + campo + "&mes=" + inicio.Month () + "&ano=" + inicio.Year () + "&form=" + form + "&ahora=" + ahora,320,260,"Calendario");
		}
	else
		{
		abrirVentana("calendario.asp?campo=" + campo + "&mes=" + inicio.Month () + "&ano=" + inicio.Year () + "&form=" + form + "&ahora=" + ahora,320,260,"Calendario");
		//ventana = window.open("calendario.asp?campo=" + campo + "&mes=" + inicio.Month () + "&ano=" + inicio.Year () + "&form=" + form + "&ahora=" + ahora,"Calendario","toolbar=no,location=no,status=no,menubar=no,scrollbars=no,width=320,height=240,left="+ (screen.width/2 - 320/2) +",top=" + (screen.height/2 - 240/2));
		}
	//ventana.focus ();	
	}	
	
function AsignarFecha(fecha,campo,form)
	{
	var inicio_fin;
	if (campo == 0){inicio_fin = "inicio";}else{inicio_fin = "fin";}
	eval ("window.parent.document."+form+".fecha_" + inicio_fin + ".value = fecha");
	eval ("window.parent.document."+form+".fecha_" + inicio_fin + ".focus()");
	eval ("window.parent.document."+form+".fecha_" + inicio_fin +".blur()");								
	parent.VentanaModal.cerrar();
	}	
	
/****************************************************************************
Condiciones de fechas y festivos locales de cada oficina para las reservas
*****************************************************************************/
function CondicionesReservas (form)
	{	
	cargo_inicio = "0";
	cargo_fin = "0";
	//Parámetros de las reserva online
	//max_TRA - Máxmimo Tiempo Reserva Alquiler - Máximo tiempo que hay desde que se hace la reserva hasta el inicio del alquiler
	var max_TRA = 90;
	//min_TRA - Mínimo Tiempo Reserva Alquiler - Mínimo tiempo que hay desde que se hace la reserva hasta el inicio del alquiler
	var min_TRA = 0;
	//DA - Máximos días de alquiler
	var DA = 90;
	//Horario telefónico
	var horario_telefono = "Nuestro horario de atención telefónica es: De lunes a viernes de 09:00 a 20:00 horas.";
	var raiz,texto_error; 
	if (form == "reservar_index"){raiz = "daperton/";}else{raiz=""};
	
	//Retirada y devolución

	if ( $("#cp_retirada").val() == '0' ) {

	    //alert('retirada es 0');
	    alert ("Indique el lugar donde quiere que le entreguemos el vehículo.");	
	    return false;
	}


	if ($("#cp_devolucion").val() == '0') {

	    //alert('dev es 0');
	    alert("Indique el lugar donde quiere devolver el vehículo.");
	    return false;
	}

	
	
//	if (eval ('document.'+form+'.lugar_retirada[3].checked') == true && eval ('document.'+form+'.cp_retirada.value') == 0){
//		alert ("Indique el Código Postal del lugar donde quiere que le entreguemos el vehículo.");	
//		return false;}
//	if (eval ('document.'+form+'.mismo_lugar_devolucion.checked') == false){
//		if (eval ('document.'+form+'.lugar_devolucion[3].checked') == true && eval ('document.'+form+'.cp_devolucion.value') == 0){
//			alert ("Indique el Código Postal del lugar donde quiere devolver el vehículo.");	
//			return false;}
//		
//		}		

	//
	var inicio = new Fecha(fecha_hoy);
	if (inicio.DateDiff("d", eval("document."+form+".fecha_inicio.value")) > max_TRA)
		{
		alert ("No es posible realizar reservas online con una fecha de inicio del alquiler superior a " + max_TRA + " días.\n\nPara realizar este tipo de reservas, puedes ponerte en contacto con nosotros llamando al teléfono 902 157 751.\n" + horario_telefono);
		eval('document.'+form+'.fecha_inicio.focus()');
		eval('document.'+form+'.fecha_inicio.select()');
		return false;
		}
	if (inicio.DateDiff("d", eval("document."+form+".fecha_inicio.value")) < min_TRA)
		{
		alert ("No es posible realizar el alquiler el mismo día de la reservas online.\n\nPara realizar este tipo de reservas, puedes ponerte en contacto con nosotros llamando al teléfono 902 157 751.\n" + horario_telefono);
		var inicio = new Fecha (fecha_hoy);
		eval ("document."+form+".fecha_inicio.value = inicio.DateAdd ('d',1,2)");
		eval('document.'+form+'.fecha_inicio.focus()');
		eval('document.'+form+'.fecha_inicio.select()');
		return false;
		}	
	var inicio = new Fecha(eval("document."+form+".fecha_inicio.value"));
	if (inicio.DateDiff("d", eval("document."+form+".fecha_fin.value")) > DA) 
		{
		texto_error = "No es posible realizar reservas online para alquileres superiores a " + DA + " días.<br><br>Para realizar este tipo de reservas, puedes ponerte en contacto con nosotros llamando al teléfono 902 157 751.<br><br>" + horario_telefono;
		abrirVentana(raiz + "error.asp?error=" + texto_error, 460, 350,"Error");

		eval('document.'+form+'.fecha_fin.focus()');
		eval('document.'+form+'.fecha_fin.select()');
		return false;
		}
	/*else if (inicio.DateDiff("d", eval("document."+form+".fecha_fin.value")) > 30)
		{
		texto_error = "Para realizar reservas entre de más de 30 días, le recomendamos que contacte telefócicamente en el 902 157 751 y le haremos un presupuesto personalizado sin compromiso.<br>" + horario_telefono;
		abrirVentana(raiz + "error.asp?error=" + texto_error, 460, 350,"Error");
		eval('document.'+form+'.fecha_fin.focus()');
		eval('document.'+form+'.fecha_fin.select()');
		return false;		
		}*/
		
	if (AplicaCargo (form))
		{
		return true;
		}
	else
		{
		return false
		}
	}
	

//**********************************************************************************************
// Función para aplicar el cargo por entrega y devolución fuera de horario y ver los festivos  *
//**********************************************************************************************

//var horario_08 = "\n\nEl horario de Barcelona (Joan Güel, 207-209) es:\n\n\tDe lunes a viernes de 09:30 a 20:00 horas.\n\tSábados de 10:00 a 14:00 horas.";
//var horario_08 = "\n\nEl horario de Barcelona (Joan Güel, 207-209) es:\n\n\tDe lunes a viernes de 09:30 a 14:00 (mañanas) y de 16:30 a 20:00 (tardes)\n\tSábados de 10:00 a 14:00 (con reserva previa)\n\n\tHorario con cargo extra de 30 € (IVA no incluido) por entrega y devolución:\n\tSábados de 14:00 a 20:00 horas.\n\tDomingos y festivos de 10:00 a 20:00 horas.";
//var horario_28 = "\n\nEl horario en Madrid es:\n\nPº de la Dirección, 9 \n\tDe lunes a viernes de 08:30 a 20:00 horas.\n\tSábados de 10:00 a 14:00 horas.\n\n\tHorario con cargo extra de 30 € (IVA no incluido) por entrega y devolución:\n\tSábados de 14:00 a 20:00 horas.\n\tDomingos y festivos de 10:00 a 20:00 horas.";
//var horario_OV = "<br><br>El horario en Madrid es:<br><br>Pº de la Dirección, 9 <br>De lunes a viernes de 09:00 a 20:00.<br>Sábados de 10:00 a 14:00 .<br><br>Estación de Tren de Atocha <br>De lunes a viernes de 09:30 a 19:00.<br>Sábados de 10:00 a 14:00 .<br><br>Estación de Tren de Chamartín <br>De lunes a viernes de 09:30 a 19:30.<br>Sábados de 10:00 a 14:00 .<br><br>Entrega/Devolución a Domicilio <br><br>De lunes a viernes de 09:30 a 19:00.<br>Sábados de 10:00 a 14:00 .<br><br>Horario con cargo extra de 30 € (IVA no incluido) por entrega y devolución:<br>Sábados de 14:00 a 20:00 horas.<br>Domingos y festivos de 10:00 a 20:00 horas.<br><br>Si desea reservar en fuera del horario indicado, por favor, póngase en contacto con nosotros: <br>Teléfono 902 157 751<br>E-Mail contacto@daperton.com.";
var horario_OV = "<table width=&quot;400&quot;><tr><td colspan=2 align=&quot;left&quot; class=&quot;normal&quot;><br><img src=&quot;img/icono_donde.gif&quot; width=&quot;17&quot; height=&quot;17&quot; alt=&quot;&quot; border=&quot;0&quot; vspace=&quot;0&quot; align=&quot;bottom&quot;>&nbsp;&nbsp;&nbsp;<b>Madrid:</b> Paseo de la Direcci&oacute;n, 9<br> (Semiesquina Francos Rodríguez, 86) 28039 Madrid<br></td></tr><tr><td colspan=2 align=&quot;left&quot;><img src=&quot;img/pixel_gris.gif&quot; width=&quot;380&quot; height=&quot;1&quot; alt=&quot;&quot; border=&quot;0&quot;></td></tr><tr><td valign=&quot;top&quot; class=&quot;normal&quot; width=&quot;200&quot;><br><b>Horario de atención al público:</b><br>Lunes a viernes: <b>9:00</b> a <b>20:00</b> (Continuado).</td><td valign=&quot;top&quot; class=&quot;normal&quot;><br><b>Horario especial con reserva previa:</b><br>Sábados, domingos y festivos de <b>10:00 a 20:00</b></td></table>";
var horario_PI = "<table width=&quot;400&quot;><tr><td colspan=2 align=&quot;left&quot; class=&quot;normal&quot;><br><img src=&quot;img/icono_donde.gif&quot; width=&quot;17&quot; height=&quot;17&quot; alt=&quot;&quot; border=&quot;0&quot; vspace=&quot;0&quot; align=&quot;bottom&quot;>&nbsp;&nbsp;&nbsp;<b>Madrid:</b> Estación de Tren de Atocha<br></td></tr><tr><td colspan=2 align=&quot;left&quot;><img src=&quot;img/pixel_gris.gif&quot; width=&quot;380&quot; height=&quot;1&quot; alt=&quot;&quot; border=&quot;0&quot;></td></tr><tr><td colspan=&quot;2&quot; valign=&quot;top&quot; class=&quot;normal&quot;><br><b>Horario especial con reserva previa:</b><br><br>De lunes a viernes de <b>9:30 a 19:00</b><br><br>Sábados, domingos y festivos de <b>10:00 a 20:00</b></td></table>";
//var horario_2 = "<table width=&quot;400&quot;><tr><td colspan=2 align=&quot;left&quot; class=&quot;normal&quot;><br><img src=&quot;img/icono_donde.gif&quot; width=&quot;17&quot; height=&quot;17&quot; alt=&quot;&quot; border=&quot;0&quot; vspace=&quot;0&quot; align=&quot;bottom&quot;>&nbsp;&nbsp;&nbsp;<b>Madrid:</b> Estación de Tren de Chamartín<br></td></tr><tr><td colspan=2 align=&quot;left&quot;><img src=&quot;img/pixel_gris.gif&quot; width=&quot;380&quot; height=&quot;1&quot; alt=&quot;&quot; border=&quot;0&quot;></td></tr><tr><td colspan=&quot;2&quot; valign=&quot;top&quot; class=&quot;normal&quot;><br><b>Horario especial con reserva previa:</b><br><br>De lunes a viernes de <b>9:30 a 19:30</b><br><br>Sábados, domingos y festivos de <b>10:00 a 20:00</b></td></table>";
var horario_CPV = "<table width=&quot;400&quot;><tr><td colspan=2 align=&quot;left&quot; class=&quot;normal&quot;><br><img src=&quot;img/icono_donde.gif&quot; width=&quot;17&quot; height=&quot;17&quot; alt=&quot;&quot; border=&quot;0&quot; vspace=&quot;0&quot; align=&quot;bottom&quot;>&nbsp;&nbsp;&nbsp;<b>Madrid:</b> Entrega/Devolución A Domicilio<br></td></tr><tr><td colspan=2 align=&quot;left&quot;><img src=&quot;img/pixel_gris.gif&quot; width=&quot;380&quot; height=&quot;1&quot; alt=&quot;&quot; border=&quot;0&quot;></td></tr><tr><td colspan=&quot;2&quot; valign=&quot;top&quot; class=&quot;normal&quot;><br><b>Horario especial con reserva previa:</b><br><br>De lunes a viernes de <b>9:30 a 19:00</b><br><br>Sábados, domingos y festivos de <b>10:00 a 20:00</b></td></table>";

function AplicaCargo (form)
	{

/* ***HORARIOS***
Oficina					lunes a viernes						sábado							domingos y festivos

OV      		9:00 - 20:00			10:00 - 14:00 -- Cargo (14:00 - 20:00)		Cargo (10:00 - 20:00)
PI				9:30 - 19:30			10:00 - 14:00 -- Cargo (14:00 - 20:00)		Cargo (10:00 - 20:00)
CPV				9:30 - 19:00			10:00 - 14:00 -- Cargo (14:00 - 20:00)		Cargo (10:00 - 20:00)
*/
	var inicio_fin,entreg_dev,oficina,lugar_retirada, lugar_devolucion, error, texto_error, horario_lugar, raiz;

	var oficina = "28039"; // used for holidays, it appears holidays are always the same - ITS MADRID!

	var typeOfLugar;

	
	
	cargo_inicio = 0;
	cargo_fin = 0;
	//var hora = new Fecha (eval("document."+form+".hora_inicio.value"));
	var hora;
	if (form == "reservar_index"){raiz = "daperton/";}else{raiz=""};

	var meta_ret = $("#cp_retirada_metadata").val().split('/');
	var meta_dev = $("#cp_devolucion_metadata").val().split('/');
	if (meta_dev.length != 2) {
	    meta_dev = meta_ret;
	}
	
	for (j = 0 ; j < 2 ; j++) {
	        var groupControlName;
		    if (j == 0) {
		        inicio_fin = "inicio";
		        entreg_dev = "ENTREGA";
		        groupControlName = "lugar_retirada";

		        typeOfLugar = meta_ret[0];
		        horario_lugar = typeOfLugar;
		        //alert("ret typeof " + typeOfLugar);
		        
		        hora = new Fecha(eval("document." + form + ".hora_inicio.value"));
		    }
		    else {
		        inicio_fin = "fin";
		        entreg_dev = "DEVOLUCIÓN";
		        groupControlName = "lugar_devolucion";

		        typeOfLugar = meta_dev[0];
		        horario_lugar = typeOfLugar;

		        //alert("dev typeof " + typeOfLugar);
		        
		        hora = new Fecha(eval("document." + form + ".hora_fin.value"));
		    }


		    
		    
		    
		
		for (i = 0 ; i < DiasFestivos.length ; i++)
			{		
			if (DiasFestivos[i].substring(0,10) == eval('document.'+form+'.fecha_'+inicio_fin+'.value'))
				{


				    if (typeOfLugar == "OV" && !hora.BetweenDates('10:00', '20:00'))
					{
					texto_error = "Está solicitando una <b>" + entreg_dev + "</b> fuera de nuestro horario comercial.<br>El día " + DiasFestivos[i] + " es festivo." + eval("horario_" + horario_lugar);
					abrirVentana(raiz + "error.asp?error=" + texto_error, 460, 350,"Error");
					return false;
					}
				else
					{
					eval ("cargo_" + inicio_fin + " = '" + cargo + "'");
					}
				}
			}	
		//Fiestas locales o autonómicas
			//for (i = 0 ; i < eval("DiasFestivos_" + oficina.substring(0,2)).length ; i++)
		for (i = 0; i < eval("DiasFestivos_" + oficina.substring(0, 2)).length; i++)
			{
			if (eval("DiasFestivos_" + oficina.substring(0,2))[i].substring(0,10) == eval('document.'+form+'.fecha_'+inicio_fin+'.value'))
				{
				if (!hora.BetweenDates ('10:00','20:00'))
					{
					texto_error = "Está solicitando una <b>" + entreg_dev + "</b> fuera de nuestro horario comercial.<br>El día " + eval("DiasFestivos_" + oficina.substring(0,2))[i] + " es festivo." + eval("horario_" + horario_lugar);
					abrirVentana(raiz + "error.asp?error=" + texto_error, 460, 350,"Error");
					return false;				
					}
				else
					{
					eval ("cargo_" + inicio_fin + " = '" + cargo + "'");
					}
				}
			}	
		
		//si es domingo
		var inicio = new Fecha (eval('document.'+form+'.fecha_'+inicio_fin+'.value'));
		if (inicio.WeekDay () == 7)
			{
			if (!hora.BetweenDates ('10:00','20:00'))
				{
				texto_error = "Está solicitando una <b>" + entreg_dev + "</b> fuera de nuestro horario comercial.<br>El día " + eval('document.'+form+'.fecha_'+inicio_fin+'.value') + " es domingo." + eval("horario_" + horario_lugar);
				abrirVentana(raiz + "error.asp?error=" + texto_error, 460, 350,"Error");
				return false;
				}
			else
				{
				eval ("cargo_" + inicio_fin + " = '" + cargo + "'");
				}	
			}		
		
		//si es sábado
		else if (inicio.WeekDay () == 6)
			{
			if (!hora.BetweenDates ('10:00','20:00'))
				{
				//alert ("Está solicitando una " + entreg_dev + " fuera de nuestro horario comercial.\n\nEl día " + eval('document.'+form+'.fecha_'+inicio_fin+'.value') + " es sábado." + eval("horario_" + horario_lugar));
				texto_error = "Está solicitando una <b>" + entreg_dev + "</b> fuera de nuestro horario comercial.<br>El día " + eval('document.'+form+'.fecha_'+inicio_fin+'.value') + " es sábado." + eval("horario_" + horario_lugar);
				abrirVentana(raiz + "error.asp?error=" + texto_error, 460, 350,"Error");
				return false;
				}
			else if (hora.BetweenDates ('14:00','20:00'))
				{				
				eval ("cargo_" + inicio_fin + " = '" + cargo + "'");
				}
			}
		//si es diario
		else
			{
			if (j==0){
				if ((!hora.BetweenDates ('9:00','20:00')) || (lugar_retirada != '2801' && (hora.BetweenDates ('9:00','9:29') || hora.BetweenDates ('19:31','20:00'))) || ((lugar_retirada != 'chamartin' && lugar_retirada != '2801') && (hora.BetweenDates ('19:01','19:30'))))
					{
					texto_error = "Está solicitando una <b>" + entreg_dev + "</b> fuera de nuestro horario comercial." + eval("horario_" + horario_lugar);
					abrirVentana(raiz + "error.asp?error=" + texto_error, 460, 350,"Error");
					return false;
					}
				}
			else
				{
				if ((!hora.BetweenDates ('9:00','20:00')) || (lugar_devolucion != '2801' && (hora.BetweenDates ('9:00','9:29') || hora.BetweenDates ('19:31','20:00'))) || ((lugar_devolucion != 'chamartin' && lugar_devolucion != '2801') && (hora.BetweenDates ('19:01','19:30'))))					{
					texto_error = "Está solicitando una <b>" + entreg_dev + "</b> fuera de nuestro horario comercial." + eval("horario_" + horario_lugar);
					abrirVentana(raiz + "error.asp?error=" + texto_error, 460, 350,"Error");
					return false;
					}
				
				}
			}						
		}
	return true;
	}

//*************************************************************
//var oficina_0 = "Madrid - Pº de la Dirección 9"
//var oficina_1 = "Estación de Tren de Atocha - Madrid"
//var oficina_2 = "Estación de Tren de Chamartín - Madrid"
//var oficina_3 = "Entrega/Devolución a Domicilio"

function ConfirmCargo (entreg_dev,fecha,hora,horario_lugar)
	{
	if (horario_lugar == "2801") {horario_lugar = "0";}
	else if (horario_lugar == "atocha") {horario_lugar = "1";}
	else if (horario_lugar == "chamartin") {horario_lugar = "2";}
	else {horario_lugar = "3";}
	//alert (entreg_dev + "," + fecha + "," + hora + "," + oficina);
	var texto_error;
	texto_error = "aa"//Con la fecha (" + fecha + "), hora (" + hora + ") y lugar de " + entreg_dev + " que ha seleccionado " + eval("oficina_"+horario_lugar) + ", le corresponde un cargo extra de 30 € (IVA no incluido)." + eval("horario_" + horario_lugar);
	return abrirVentana("error.asp?error=" + texto_error, 460, 350,"Error");
	return true;
	//return confirm ("Con la fecha (" + fecha + "), hora (" + hora + ") y lugar de " + entreg_dev + " que ha seleccionado " + eval("oficina_"+horario_lugar) + ", le corresponde un cargo extra de 30 € (IVA no incluido)." + eval("horario_" + horario_lugar));			
	}
	
//*********************************************************************//
//    Comprueba las entradas del cotizador, reservas y presupuestos    //
//*********************************************************************//
var cargo = "34,80"; // cargo por devolución fuera de horario 30 € + IVA (16%)

function CotizarPropuesta(form)
	{

	
	if (form == 'reservar' || form == 'reservar_index')
		{
		if (eval ('document.'+form+'.fecha_inicio.value') != "")
			{
			fecha_min = eval ('document.'+form+'.fecha_inicio.value')
			}
		if (ComprobarEntrada(form))// Comprueba las fechas
			{
			if (ValidarHora (eval("document."+form+".hora_inicio.value"))) // Si es una reserva comprueba las horas
				{
				if (CondicionesReservas (form)) // Comprueba las condiciones de las reservas
					{
					//document.reservar.action = "reserva_presupuesto.asp?fecha_inicio="+eval("document."+form+".fecha_inicio.value")+"&fecha_fin="+eval("document."+form+".fecha_fin.value")+ "&hora_inicio="+eval("document."+form+".hora_inicio.value")+"&modelo="+eval("document."+form+".modelos.value")+"&diario="+diario+"&form="+form+"&Oficina="+oficina+"&cargo_inicio="+cargo_inicio+"&cargo_fin="+cargo_fin;
					if (form=="reservar_index")
						{
						document.reservar_index.action = "daperton/reserva_presupuesto.asp?diario="+diario+"&cargo_inicio="+cargo_inicio+"&cargo_fin="+cargo_fin;
						document.reservar_index.submit();
						}
					else
						{
						document.reservar.action = "reserva_presupuesto.asp?diario="+diario+"&cargo_inicio="+cargo_inicio+"&cargo_fin="+cargo_fin;
						document.reservar.submit();
						}
					//Abrir_Ventana(url,"cotizando",'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,width=700,height=590,left=10,top=10',700,590,true)		
					}
				}
			}
		}
	else if (form == 'presupuesto')
		{
     	// cargos, descuentos y ofertas			
		var i,dscto_cargo = "";		
		for (i = 0; i <= cont_radio; i++)
			{												
			if (eval ("document.presupuesto.radio_" + i + "[0].checked"))
				{
				dscto_cargo = dscto_cargo + "*"+ eval ("document.presupuesto.radio_" + i + "[0].value");
				}
			else if (eval ("document.presupuesto.radio_" + i + "[1].checked"))
				{
				dscto_cargo = dscto_cargo + "*"+ eval ("document.presupuesto.radio_" + i + "[1].value");
				}
			else
				{
				dscto_cargo = dscto_cargo + "*"+ eval ("document.presupuesto.radio_" + i + "[2].value");							
				}
			}								
			// kilomentraje
		var km;
		if (eval("document.presupuesto.km[0].checked"))
			{
			km = 0;
			}
		if (eval("document.presupuesto.km[1].checked"))
			{
			km = 1;
			}
		if (eval("document.presupuesto.km[2].checked"))
			{
			km = 2;
			}
		// tarifa especial
		if ((!ComprobarCampoNumerico (4,document.presupuesto.tarifa_especial_diaria.value, "tarifa"))||(!ComprobarCampoNumerico (4,document.presupuesto.tarifa_especial_mensual.value, "tarifa")))
			{
			//break;
			}
		else
			{
			if ((document.presupuesto.tarifa_especial_diaria.value != "") || (document.presupuesto.tarifa_especial_mensual.value != ""))
				{
				answer = confirm ("Para poder modificar las tarifas tienes que tener autorización expresa de David.\nSi la tienes pulsa Aceptar y si no es así pulsa Cancelar.");			
				if (!answer){//break;}
				}
			}
		// Comprobar teléfono
		//if (isNaN(Reemplazar (document.presupuesto.user_telefono.value," ","")) || isNaN(Reemplazar (document.presupuesto.user_telefono2.value," ","")))
		if (!ComprobarCampoNumerico (3,document.presupuesto.user_telefono.value,"teléfono") || !ComprobarCampoNumerico (3,document.presupuesto.user_telefono2.value,"teléfono") || !ComprobarCampoNumerico (3,document.presupuesto.user_fax.value,"Fax"))
			{				
			//break;				
			}
		// Comprobar mail de persona de contacto de Daperton			
		if (document.presupuesto.user_email.value != "")
			{
			if (!ComprobarEmail (document.presupuesto.user_email.value))
				{				
				//break;				
				}
			}	
		//el campo Empresa o Cliente tiene que contener algún valor
		if (document.presupuesto.empresa.value == "" && document.presupuesto.cliente.value == "")
			{
			alert ("El campo Empresa o el campo Cliente tienen que contener algún valor.");
			//break;
			}
		// max_km: número de kilómetros / día en la tarifa no Básica
		if (!ComprobarCampoNumerico (4,document.presupuesto.max_km.value, "Cantidad"))
			{
			//break;
			}	
		// Cantidad de vehículos
		if (!ComprobarCampoNumerico (0,document.presupuesto.cantidad_vehiculos.value, "Nº de vehículos"))
			{
			//break;
			}		
		//Si pongo un nº concreto de días y no unas fechas
		if (document.presupuesto.dias.value != "")
			{
			if (isNaN(document.presupuesto.dias.value))
				{
				alert ("El campo de los días de alquiler tiene que ser un valor numérico.");
				//break;
				}
			else
				{															
				if (ComprobarDescuento ())   // descuentos directos
					{							
					url = "go/?navigate=53&modelo="+eval("document."+form+".modelos.value")+"&form="+form+"&Oficina="+eval("document."+form+".provincia.value")+"&km="+km+"&dscto_cargo="+dscto_cargo+"&dscto_cantidad="+document.presupuesto.dscto_cantidad.value+"&dscto_porcentaje="+document.presupuesto.dscto_porcentaje.value+"&dscto_descripcion="+document.presupuesto.dscto_descripcion.value+"&total_dias="+document.presupuesto.dias.value+"&tarifa_especial_diaria="+document.presupuesto.tarifa_especial_diaria.value+"&tarifa_especial_mensual="+document.presupuesto.tarifa_especial_mensual.value+"&diario=1"+"&aplicar_dscto_cargo="+document.presupuesto.aplicar_dscto_cargo.checked+"&empresa="+document.presupuesto.empresa.value+"&cliente="+document.presupuesto.cliente.value+"&user_nombre="+document.presupuesto.user_nombre.value+"&user_email="+document.presupuesto.user_email.value+"&user_direccion="+document.presupuesto.user_direccion.value+"&user_telefono="+document.presupuesto.user_telefono.value+"&user_telefono2="+document.presupuesto.user_telefono2.value+"&user_fax="+document.presupuesto.user_fax.value+"&max_km="+document.presupuesto.max_km.value+"&cantidad_vehiculos="+document.presupuesto.cantidad_vehiculos.value;
 					abrirVentana(url, 700, 590,"cotizando")
					}
				}							
	
			}				
		else //si pongo unas fechas
			{				
			if (document.presupuesto.fecha_inicio.value != "")
				{
				fecha_min = document.presupuesto.fecha_inicio.value;//pongo como fecha mínima la de inicio
				}
				if (ComprobarEntrada("presupuesto"))// Comprueba las fechas
					{
					if (ValidarHora (document.presupuesto.hora_inicio.value)) // Comprueba las horas
						{						
						if (AplicaCargo ("presupuesto"))
							{
							
							url = "go/?navigate=53&fecha_inicio="+eval("document."+form+".fecha_inicio.value")+"&fecha_fin="+eval("document."+form+".fecha_fin.value")+ "&hora_inicio="+eval("document."+form+".hora_inicio.value")+"&modelo="+eval("document."+form+".modelos.value")+"&diario="+diario+"&form="+form+"&Oficina="+eval("document."+form+".provincia.value")+"&km="+km+"&dscto_cargo="+dscto_cargo+"&dscto_cantidad="+document.presupuesto.dscto_cantidad.value+"&dscto_porcentaje="+document.presupuesto.dscto_porcentaje.value+"&dscto_descripcion="+document.presupuesto.dscto_descripcion.value+"&cargo_inicio="+cargo_inicio+"&cargo_fin="+cargo_fin+"&tarifa_especial_diaria="+document.presupuesto.tarifa_especial_diaria.value+"&tarifa_especial_mensual="+document.presupuesto.tarifa_especial_mensual.value+"&aplicar_dscto_cargo="+document.presupuesto.aplicar_dscto_cargo.checked+"&empresa="+document.presupuesto.empresa.value+"&cliente="+document.presupuesto.cliente.value+"&user_nombre="+document.presupuesto.user_nombre.value+"&user_email="+document.presupuesto.user_email.value+"&user_direccion="+document.presupuesto.user_direccion.value+"&user_telefono="+document.presupuesto.user_telefono.value+"&user_telefono2="+document.presupuesto.user_telefono2.value+"&user_fax="+document.presupuesto.user_fax.value+"&max_km="+document.presupuesto.max_km.value+"&cantidad_vehiculos="+document.presupuesto.cantidad_vehiculos.value;
							abrirVentana(url, 700, 590,"cotizando")
							}
						}
					}					
				}
			}
		}		
	else
		{	
		if (eval ("document." + form + ".fecha_inicio.value") != "")
			{
			fecha_min = eval ("document." + form + ".fecha_inicio.value");//pongo como fecha mínima la de inicio
			}
		if (ComprobarEntrada(form))// Comprueba las fechas
			{																
			if (form == "cotizador")
				{
				url = "go/?navigate=53&fecha_inicio="+eval("document."+form+".fecha_inicio.value")+"&fecha_fin="+eval("document."+form+".fecha_fin.value")+"&modelo="+eval("document."+form+".modelos.value")+"&diario="+diario+"&form="+form;
				}
			else
				{
				url = "daperton/go/?navigate=53&fecha_inicio="+eval("document."+form+".fecha_inicio.value")+"&fecha_fin="+eval("document."+form+".fecha_fin.value")+"&modelo="+eval("document."+form+".modelos.value")+"&diario="+diario+"&form="+form;
				}
			abrirVentana(url, 700, 590,"cotizando")
			}
		}						
	} 
	
//***********************************************************************************************************//
//   Presupuestos: si cambian la selección del combo de la oficina, cambia la dirección, el teléfono, etc... //
//***********************************************************************************************************//
function CambiarDireccion ()
	{
	var i_camb = 0;
	while (document.presupuesto.provincia.value != Array_Oficina [i_camb][0])
		{			
		i_camb++;
		if (Array_Oficina [i_camb][0]== null )
			{
			i_camb = -1;
			break;
			}
		}
	if (i_camb < 0)
		{
		document.presupuesto.user_direccion.value = "";		
		}
	else
		{
		var quitarbr = Array_Oficina [i_camb][2];
		quitarbr = quitarbr.replace ("<br>"," "); 
		document.presupuesto.user_direccion.value = quitarbr;
		document.presupuesto.user_telefono.value = Array_Oficina [i_camb][3];
		document.presupuesto.user_fax.value = Array_Oficina [i_camb][4];
		}
	}

//**************************************************************************************************//
//   Cuando en un presupuesto marcas unos días concretos, borra las fecha y la hora y viceversa	    //
//**************************************************************************************************//
function PresupuestoBorrarFecha (dias_fechas)
	{
	if (dias_fechas)
		{
		document.presupuesto.fecha_inicio.value = "";
		document.presupuesto.fecha_fin.value = "";
		document.presupuesto.hora_inicio.value = "";
		document.presupuesto.total_dias.value = "";
		}
	else
		{
		document.presupuesto.dias.value = "";
		}
	}

//*************************************************************************************************************************//
//   Mostrar la posibilidad de modificar las tarifas diarias, mensual o ambas, según seleccione km limitado o ilimitado    //
//*************************************************************************************************************************//
function ModificarTarifas (kilometraje)
	{
	switch (kilometraje)
		{
		case 0:
			document.presupuesto.tarifa_especial_mensual.disabled=true;
			document.presupuesto.tarifa_especial_mensual.value='';
			document.presupuesto.tarifa_especial_mensual.className='offcampo';
			
			document.presupuesto.max_km.disabled=true;
			document.presupuesto.max_km.value='';
			document.presupuesto.max_km.className='offcampo';
						
			document.presupuesto.tarifa_especial_diaria.disabled=false;
			document.presupuesto.tarifa_especial_diaria.className='oncampo';
		break;
		case 1:
			document.presupuesto.tarifa_especial_diaria.disabled=true;
			document.presupuesto.tarifa_especial_diaria.value='';
			document.presupuesto.tarifa_especial_diaria.className='offcampo';			
			document.presupuesto.tarifa_especial_mensual.disabled=false;
			document.presupuesto.tarifa_especial_mensual.className='oncampo';
			document.presupuesto.max_km.disabled=false;
			document.presupuesto.max_km.className='oncampo';			
		break;
		case 2:
			document.presupuesto.tarifa_especial_mensual.disabled=false;
			document.presupuesto.tarifa_especial_mensual.className='oncampo';
			document.presupuesto.tarifa_especial_diaria.disabled=false;
			document.presupuesto.tarifa_especial_diaria.className='oncampo';			
			document.presupuesto.max_km.disabled=false;	
			document.presupuesto.max_km.className='oncampo';						
		break;		
		}
	}

//*************************************************************************************//
//         Comprueba si hay un descuento directo y si es así que sea correcto          //
//*************************************************************************************//

function ComprobarDescuento ()
	{

	if (document.presupuesto.dscto_cantidad.value != "")
		{
		if (document.presupuesto.dscto_porcentaje.value != "")
			{
			alert ("Puedes descontar una cantidad concreta o un porcentaje, pero no ambos.");
			return false;		//Error: hay descuento directo y porcentaje				
			}
		else
			{
			if (!ComprobarCampoNumerico (4,document.presupuesto.dscto_cantidad.value, "descuento cantidad"))
				{				
				return false;
				}
			else
				{
				if (document.presupuesto.dscto_descripcion.value != "")
					{				
					return true;	//hay descuento directo y descripción
					}
				else
					{
					alert ("Tienes que introducir una breve descripción para el descuento.");
					return false;		//Error: hay descuento directo pero no descripción
					}
				}
			}
		}
	else
		{
		if (document.presupuesto.dscto_porcentaje.value != "")
			{
			if (ComprobarCampoNumerico (4,document.presupuesto.dscto_porcentaje.value, "descuento porcentaje"))				
				{
				if (document.presupuesto.dscto_descripcion.value != "")
					{
					return true;	//hay % de descuento y descripción
					}
				else
					{
					alert ("Tienes que introducir una breve descripción para el descuento.");
					return false;		//Error: hay % de descuento pero no descripción
					}
				}
			}
		else	
			{
			if (document.presupuesto.dscto_descripcion.value != "")
				{
				alert ("Tienes que introducir una cantidad o un porcentaje para el descuento que has indicado.");
				return false;		//Error: hay descripción pero no cantidad ni % de descuento
				}
			else
				{
				return true;	//no hay descuento directo
				}			
			}			
		}		
	}

//*******************************************************************************

function DiasTotales (form)
	{
	var date_ini  = new Fecha (eval ("document." + form + ".fecha_inicio.value") + " 12:45:00");
	var date_fin  = new Fecha (eval ("document." + form + ".fecha_fin.value") + " 12:45:00");
	if (date_ini.CheckDate () && eval ("document." + form + ".fecha_inicio.value != ''") && date_fin.CheckDate () && eval ("document." + form + ".fecha_fin.value != ''"))
		{	
		eval ("document." + form + ".total_dias.value = parseFloat(date_ini.DateDiff ('d',date_fin.FormatDate (0)))");			
		if (date_ini.DateDiff ('d',date_fin.FormatDate (2)) == 0)
			{
			eval ("document." + form + ".total_dias.value = 1");
			}
		else if ((date_ini.DateDiff ('d',date_fin.FormatDate (2)) < 0))
			{
			eval ("document." + form + ".total_dias.value = 0");
			}
		}
	else
		{eval ("document." + form + ".total_dias.value =0");}
	}	

// **********************************************************************************
//			Máscara para las fechas
// **********************************************************************************
function MascaraFecha (campo,form)
	{	 
	var inicio_fin;
	if (campo == 0){inicio_fin = "inicio";}else{inicio_fin = "fin";}
	if (eval ("document." + form + ".fecha_" + inicio_fin + ".value.length == 2"))
		{
		eval ("document." + form + ".fecha_" + inicio_fin + ".value = document." + form + ".fecha_" + inicio_fin + ".value + '/'");
		}
	}
		
//*******************************************************************************
// Formulario de Enviar a un Amigo
//*******************************************************************************

function EnviarAmigo()
	{
	error = 0;
	
	if (document.enviar_amigo.nombre.value == "")
		{
		alert("Debes indicar tu nombre.")
		document.enviar_amigo.nombre.focus();
		error = 1;
		}
	
	if (document.enviar_amigo.nombre_amigo.value == "" && error == 0)
		{
		alert("Debes indicar el nombre de tu amigo.")
		document.enviar_amigo.nombre_amigo.focus();
		error = 1;
		}
	
	if (document.enviar_amigo.email_amigo.value != "" && error == 0)
		{
		if (!ComprobarEmail(document.enviar_amigo.email_amigo.value))
			{	
			document.enviar_amigo.email_amigo.focus();
			error = 1;
			}
		}
	
	if (document.enviar_amigo.aceptar_condiciones.checked == false && error == 0)
		{
		alert("Debes aceptar las condiciones.")
		document.enviar_amigo.aceptar_condiciones.focus();
		error = 1;
		}	
		
	if (error == 0)
		{
			if (document.enviar_amigo.mensaje[0].checked)
			{
				document.enviar_amigo.comentarios.value = "Te envío una página que puede ser de tu interés";			
			}				
			else if (document.enviar_amigo.mensaje[1].checked)
			{				
				document.enviar_amigo.comentarios.value = "Te envío una página con la información que estabas buscando.";
			}
			
		document.enviar_amigo.action = "t_enviar_amigo.asp";
		document.enviar_amigo.submit();
		}
	}

//****************************************************************************
//   Marcar como check el radio button del text area
//****************************************************************************

function CheckRadio()
	{
		document.enviar_amigo.mensaje [2].click();
	}

//****************************************************************************
//   Oredena los presupuestos de la reserva online
//****************************************************************************

function OrdenarPresupuesto(ordenado_por)
	{
	
	document.reserva_presupuesto.action = "reserva_presupuesto.asp?ordenado_por=" + ordenado_por;
	document.reserva_presupuesto.submit();
	}
/// *************** Enviar Reservas *********************

function EnviarReserva ()
	{
	error = 0;

	if (document.reserva.nombre.value == "")
		{
		alert("Debes indicar tu nombre.")
		document.reserva.nombre.focus();
		error = 1;
		}		
	
	if (document.reserva.apellido1.value == "" && error == 0)
		{
		alert("Debes indicar tu primer apellido.")
		document.reserva.apellido1.focus();
		error = 1;
		}
	
	//if (error == 0)
	//	{
	//	if (document.reserva.email.value != "")
	//		{
	//		if (!ComprobarEmail(document.reserva.email.value))
	//			{	
	//			document.reserva.email.focus();
	//			error = 1;
	//			}	
	//		}
	//	}
	if (document.reserva.email.value == "" && error == 0)
		{
		alert("Debes indicar una dirección de correo electrónico.")
		document.reserva.email.focus();
		error = 1;
		}
	
	if (error == 0)
		{
		if (!ComprobarEmail(document.reserva.email.value))
			{	
			document.reserva.email.focus();
			error = 1;
			}	
		}
	
	if (document.reserva.telefono.value == "" && error == 0)
		{
		alert("Debes indicar un teléfono de contacto.")
		document.reserva.telefono.focus();
		error = 1;
		}
	
	if ((isNaN(document.reserva.telefono.value) || document.reserva.telefono.value.length < 9 || parseInt(document.reserva.telefono.value) != document.reserva.telefono.value) && error == 0)
		{
		alert("Por favor, comprueba el número de teléfono.")
		document.reserva.telefono.focus();
		error = 1;
		}		
	
		
	if (document.reserva.aceptar_condiciones.checked == false && error == 0)
		{
		alert("Debes aceptar las condiciones.")
		document.reserva.aceptar_condiciones.focus();
		error = 1;
		}
		
	if (error == 0)
		{
		document.reserva.action = "reserva_confirmacion.asp";
		document.reserva.submit();
		}
	}
/*
Con esta función se crea un objeto "Fecha" para manejas las fechas en JS

cF_Valor:
	- Puede ser cadena vacía "" con lo que Fecha se inicializa a la fecha
	  del sistema del cliente
	- Se puede inicializar con una fecha pasándola con el formato "dd/mm/aaaa",
	  con la posibilidad de incluir la hora en formato "hh:mm" o "hh:mm:ss"	
*/

function Fecha(cF_Valor)
	{
	if (cF_Valor != "")
		{
		var cF_partes = new Array(2);
		var cF_dias = new Array(3);
		var cF_horas = new Array(3);
		
		for (cF_i = 0; cF_i < 2; cF_i++)
			{
			cF_partes[cF_i] = "";
			}
		
		cF_dias[0] = 1;
		cF_dias[1] = 1;
		cF_dias[2] = 1900;
		
		for (cF_i = 0; cF_i < 3; cF_i++)
			{
			cF_horas[cF_i] = 0;
			}
		
		cF_partes = cF_Valor.split(" ");
		
		cF_indice = (cF_partes.length == 1) ? 0 : 1;
		
		if (cF_Valor.indexOf(":") >= 0)
				{
				cF_horas = cF_partes[cF_indice].split(":");
				
				if (cF_Valor.indexOf(":") == cF_Valor.lastIndexOf(":") && cF_Valor.indexOf(":") != -1)
					{
					cF_horas[2] = 0;
					}
				else if (cF_Valor.indexOf(":") != -1)
					{
					//cF_horas[1] = 0;
					}
				}
		
		if (cF_Valor.indexOf("/") >= 0)
			{
			cF_dias = cF_partes[0].split("/");
			}
		else
			{
			if (cF_Valor.indexOf(":") >= 0)
				{
				cF_horas = cF_partes[0].split(":");
				
				if (cF_Valor.indexOf(":") == cF_Valor.lastIndexOf(":") && cF_Valor.indexOf(":") != -1)
					{
					cF_horas[2] = 0;
					}
				else if (cF_Valor.indexOf(":") != -1)
					{
					//cF_horas[1] = 0;
					}
				}
			}
				
		this.FechaBase = new Date(parseFloat(cF_dias[2]), parseFloat(cF_dias[1] - 1), parseFloat(cF_dias[0]), parseFloat(cF_horas[0]), parseFloat(cF_horas[1]), parseFloat(cF_horas[2]));
		
		}
	else
		{
		this.FechaBase = new Date();
		}
	
	this.CV = cF_Valor;
	this.Day = Day;
	this.Month = Month;
	this.Year = Year;
	this.Hours = Hours;
	this.Minutes = Minutes;
	this.Seconds = Seconds;
	this.Milliseconds = Milliseconds;
	this.WeekDay = WeekDay;
	this.WeekDayName = WeekDayName;
	this.MonthName = MonthName;
	this.DaysInMonth = DaysInMonth;
	this.IsLeapYear = IsLeapYear;
	this.DateAdd = DateAdd;
	this.DateDiff = DateDiff;
	this.RentPeriod = RentPeriod; 
	this.CheckDate = CheckDate;
	this.BetweenDates = BetweenDates;
	this.NextWeekDay = NextWeekDay;
	this.FormatDate = FormatDate;
	}

// Obtiene el día		
function Day()
	{
	return this.FechaBase.getDate();
	}	

// Optiene el mes	
function Month()
	{
	return this.FechaBase.getMonth() + 1;
	}

// Obtiene el año	
function Year()
	{
	return this.FechaBase.getFullYear();
	}	

// Obtiene las cF_horas	
function Hours()
	{
	return this.FechaBase.getHours();
	}

// Obtiene los minutos	
function Minutes()
	{
	return this.FechaBase.getMinutes();
	}

// Obtiene los segundos	
function Seconds()
	{
	return this.FechaBase.getSeconds();
	}

// Obtiene los milisegundos
function Milliseconds()
	{
	return this.FechaBase.getTime();
	}

// Obtiene el dia de la semana (del 1 lunes al 7 domingo)	
function WeekDay()
	{
	return (this.FechaBase.getDay() == 0) ? 7 : this.FechaBase.getDay();
	}	

// Obtiene el nombre de día de la semana	
function WeekDayName()
	{
	var cF_NombresDiaSemana = new Array('','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado','Domingo');
	return cF_NombresDiaSemana[this.WeekDay()];
	}

// Obtiene el nombre del mes
function MonthName()
	{
	var cF_NombresMes = new Array('','Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre');
	return cF_NombresMes[this.Month()];
	}

// Obtiene los cF_dias del mes
function DaysInMonth()
	{
	var cF_DiasMes = Array(12);
	 cF_DiasMes[0] = 31;
	 cF_DiasMes[1] = 28;
	 cF_DiasMes[2] = 31;
	 cF_DiasMes[3] = 30;
	 cF_DiasMes[4] = 31;
	 cF_DiasMes[5] = 30;
	 cF_DiasMes[6] = 31;
	 cF_DiasMes[7] = 31;
	 cF_DiasMes[8] = 30;
	 cF_DiasMes[9] = 31;
	cF_DiasMes[10] = 30;
	cF_DiasMes[11] = 31;
	
	if (this.IsLeapYear())
		{
		cF_DiasMes[1] = 29;
		}
		
	return cF_DiasMes[this.Month() - 1];
	}	
	
// Obtiene si es año bisiesto (true) o no (false)
function IsLeapYear()
	{
	return (((this.Year() % 4 == 0) && (this.Year() % 100 != 0)) || (this.Year() % 400 == 0)) ? true : false;
	}

// Añade un periodo de tiempo en el formato de intervalo indicado 	
function DateAdd(cF_Parte, cF_Cantidad, cF_Formato)
	{
	if (cF_Parte == "y")
		{
		var cF_FechaDos = new Fecha(this.Day() + "/" + this.Month() + "/" + (this.Year() + parseFloat(cF_Cantidad)));
		this.FechaBase.setTime(cF_FechaDos.Milliseconds())
		}
	else if (cF_Parte == "m")
		{
		var cF_Anyo = this.Year();
		var cF_Mes = this.Month();
		var cF_Dia = this.Day()
		var cF_CantAbs = Math.abs(parseFloat(cF_Cantidad))
		var cF_Signo = (parseFloat(cF_Cantidad) < 0) ? -1 : 1
		
		// alert((parseFloat(cF_Cantidad) < 0) + " | " + cF_Mes + " - " + cF_CantAbs);
		
		for (cF_i = 1; cF_i <= cF_CantAbs; cF_i++)
			{
			cF_Mes += cF_Signo;
			
			if (cF_Mes == 13) { cF_Anyo += 1; cF_Mes = 1}
			if (cF_Mes == 0) { cF_Anyo -= 1; cF_Mes = 12}
			}
		
		var cF_FechaDias = new Fecha("01/" + cF_Mes + "/" + cF_Anyo);
		
		if (cF_Dia > cF_FechaDias.DaysInMonth())
			{
			cF_Dia = cF_FechaDias.DaysInMonth();
			}
		
		var cF_FechaDos = new Fecha(cF_Dia + "/" + cF_Mes + "/" + cF_Anyo);
		this.FechaBase.setTime(cF_FechaDos.Milliseconds())
		}
	else if (cF_Parte == "d")
		{
		this.FechaBase.setTime((parseFloat(DatePart(cF_Parte)) * parseFloat(cF_Cantidad)) + this.Milliseconds() + 10000000);
		}
	else
		{
		this.FechaBase.setTime((parseFloat(DatePart(cF_Parte)) * parseFloat(cF_Cantidad)) + this.Milliseconds());
		}
		
	return this.FormatDate(cF_Formato);
	}


// Saca la diferencia entre dos fechas en el formato de intervalo indicado	
function DateDiff(cF_Parte, cF_FechaComp)
	{
	var cF_FechaDos = new Fecha(cF_FechaComp);
	var cF_DifAnyos = cF_FechaDos.Year() - this.Year();
	var cF_DifMeses = (cF_DifAnyos * 12) + (cF_FechaDos.Month() - this.Month())
	var cF_FechaChk = new Fecha(this.Day() + "/" + this.Month() + "/" + cF_FechaDos.Year());
	
	if (cF_Parte == "y")
		{
		if (cF_FechaChk.Month() < cF_FechaDos.Month()) { return cF_DifAnyos; }
		else if (cF_FechaChk.Month() > cF_FechaDos.Month()) { return cF_DifAnyos - 1; }
		else { if (cF_FechaChk.Day() <= cF_FechaDos.Day()) { return cF_DifAnyos; } else { return cF_DifAnyos - 1; } }	
		}
	else if (cF_Parte == "m")
		{
		if (cF_FechaChk.Day() <= cF_FechaDos.Day()) { return cF_DifMeses; } else { return cF_DifMeses - 1; } 
		}
	else
		{
		// Apaño para el arreglo con fechas en UTC
		dif_1 = this.FechaBase.getTimezoneOffset() * 60 * 1000;
		dif_2 = cF_FechaDos.FechaBase.getTimezoneOffset() * 60 * 1000;
		
		//alert(dif_1 + " " + dif_2);
		return ((cF_FechaDos.Milliseconds() + dif_1) - (this.Milliseconds() + dif_2)) / DatePart(cF_Parte);
		}
	}	

// Saca la diferencia entre dos fechas en el formato de intervalo indicado PENSADO EN EL SISTEMA DE ALQUILER (1 día + 1 minuto = 2 días)
function RentPeriod(cF_Parte, cF_FechaComp)
	{
	var cF_FechaDos = new Fecha(cF_FechaComp);
	var cF_DifAnyos = cF_FechaDos.Year() - this.Year();
	var cF_DifMeses = (cF_DifAnyos * 12) + (cF_FechaDos.Month() - this.Month())
	var cF_FechaChk = new Fecha(this.Day() + "/" + this.Month() + "/" + cF_FechaDos.Year());
	
	if (cF_Parte == "y")
		{
		if (cF_FechaChk.Month() < cF_FechaDos.Month()) { return cF_DifAnyos; }
		else if (cF_FechaChk.Month() > cF_FechaDos.Month()) { return cF_DifAnyos - 1; }
		else { if (cF_FechaChk.Day() <= cF_FechaDos.Day()) { return cF_DifAnyos; } else { return cF_DifAnyos - 1; } }	
		}
	else if (cF_Parte == "m")
		{
		if (cF_FechaChk.Day() <= cF_FechaDos.Day()) { return cF_DifMeses; } else { return cF_DifMeses - 1; } 
		}
	else
		{
		return Math.ceil((cF_FechaDos.Milliseconds() - this.Milliseconds()) / DatePart(cF_Parte));
		}
	}

// Comprueba si la fecha y hora con que inicializa el objeto Fecha es correcta
function CheckDate()
	{
	return eval(this.FormatDate(0).indexOf(this.CV) != -1 && this.Year().toString().length == 4);
	}

// Comprueba si la fecha esta entre dos dadas
function BetweenDates(cF_Fecha1, cF_Fecha2)
	{
	cF_Fecha2 = (cF_Fecha2 == null) ? cF_Fecha1 : cF_Fecha2
	
	var cF_FechaUno = new Fecha(cF_Fecha1);
	var cF_FechaDos = new Fecha(cF_Fecha2);
	
	return (cF_FechaUno.Milliseconds() <= this.Milliseconds() && this.Milliseconds() <= cF_FechaDos.Milliseconds()) ? true : false;
	}

// Devueve la fecha correspondiente al siguiente día de la semana (1-7) especificado
function NextWeekDay(cF_Dia,cF_Formato)
	{
	cF_DiaActual = this.WeekDay();
	
	if (cF_Dia > cF_DiaActual)
		{
		cF_Suma = cF_Dia - cF_DiaActual;
		}
	else if (cF_Dia < cF_DiaActual)
		{
		cF_Suma = 7 - cF_DiaActual + cF_Dia;
		}
	else
		{
		cF_Suma = 7;
		}
	
	this.DateAdd("d", cF_Suma);
	return this.FormatDate(cF_Formato);
	}
	
// 	Para sacar los milisegundos de cada formato de intervalo
function DatePart(cF_Parte)
	{
	switch (cF_Parte)
		{
		case "d": return 86400000; // 1 día
		case "m": return 86400000 * 30; // 1 mes = 30 días
		case "y": return 86400000 * 365; // 1 año = 365 días
		case "h": return 3600000; // 1 hora
		case "n": return 60000; // 1 minuto
		case "s": return 1000; // 1 segundo
		case "t": return 1; // 1 milisegundo
		default: return 86400000; // por defecto 1 día
		}
	}	

// Para dar formato a la fecha
function FormatDate(cF_Formato)
	{
	switch (cF_Formato)
		{
		// "dd/mm/aaaa hh:mm:ss"
		case 0: return ((this.Day() < 10) ? "0" + this.Day() : this.Day()) + "/" + ((this.Month() < 10) ? "0" + this.Month() : this.Month()) + "/" + this.Year() + " " + ((this.Hours() < 10) ? "0" + this.Hours() : this.Hours()) + ":" + ((this.Minutes() < 10) ? "0" + this.Minutes() : this.Minutes()) + ":" + ((this.Seconds() < 10) ? "0" + this.Seconds() : this.Seconds());
		
		// Fecha en texto "Domingo, 18 de Abril de 2004"
		case 1: return this.WeekDayName() + ", " + this.Day() + " de " + this.MonthName() + " de " + this.Year();
		
		// "dd/mm/aaaa"
		case 2: return ((this.Day() < 10) ? "0" + this.Day() : this.Day()) + "/" + ((this.Month() < 10) ? "0" + this.Month() : this.Month()) + "/" + this.Year();
		
		// "hh:mm:ss"
		case 3: return ((this.Hours() < 10) ? "0" + this.Hours() : this.Hours()) + ":" + ((this.Minutes() < 10) ? "0" + this.Minutes() : this.Minutes()) + ":" + ((this.Seconds() < 10) ? "0" + this.Seconds() : this.Seconds());
		
		// "hh:mm"
		case 4: return ((this.Hours() < 10) ? "0" + this.Hours() : this.Hours()) + ":" + ((this.Minutes() < 10) ? "0" + this.Minutes() : this.Minutes());
		}
	}	


// ************************************************************************************************************
// ***************************************  Encuestas múltiples ***********************************************
// ************************************************************************************************************

function Encuesta_Multiple (contador, encuesta)
	{
	var opcion = 0;
	for (i=0 ; i<(contador-1); i++)
		{
		if (eval (document.contacto.cb_opcion[i].checked))
			{	
			opcion += 1;
			}
		}
	if (opcion == 0)
		{
		alert ("Tienes que marcar alguna casilla para poder votar.")
		return false;
		}
	if (opcion == 1)
		{
		alert ("Tiene que marcar 2 casillas para poder votar.")
		return false;
		}	
	else if (encuesta == 13 && opcion > 2)
		{
		alert ("Selecciona como máximo 2 opciones.")
		return false;
		}
	else
		{
		document.contacto.action = "t_votar_encuesta.asp?id_encuesta=" + encuesta;
		document.contacto.submit();
		}
	}
// ******************************************************************************************************************
// ***************************** Función para no poder seleccionar los textos ***************************************
//*******************************************************************************************************************
/*onSelectStart="javascript:NoSelect ('1')"
function NoSelect (form)
	{
	if (form == 1)
		{
		return false;
		}
	else
		{return true;}
	}
*/

//**********************************************************************************
// Máscara de teclado para las fechas y las horas
// 
// Para que funcione sólo tienes que poner en cada campo de formulario que quieres que
// lleve la máscara este código: onkeydown="MascaraFecha('NombreDelFormulario.NombreDelCampo')"

function MascaraFecha(campo)
	{
	Permitido = "0123456789";
	ValorComprobarF = eval("document." + campo + ".value");
	Cache = ValorComprobarF.substr(eval("document." + campo + ".value.length")-1,1)
	
	if (Permitido.indexOf(Cache) < 0)
		{
		eval("document." + campo + ".value = ValorComprobarF.substr(0,ValorComprobarF.length-1)");
		}
	else
		{
		if (ValorComprobarF.length == 2)
			{
			eval("document." + campo + ".value = document." + campo + ".value + '/'"); 
			}
		else if (ValorComprobarF.length == 3 && ValorComprobarF.charAt(2) != "/")
			{
			eval("document." + campo + ".value = document." + campo + ".value.substr(0,2) + '/' + document." + campo + ".value.substr(2,1)");
			}
		else if (ValorComprobarF.length == 5)
			{
			eval("document." + campo + ".value = document." + campo + ".value + '/'");
			}
		else if (ValorComprobarF.length == 6 && ValorComprobarF.charAt(5) != "/")
			{
			eval("document." + campo + ".value = document." + campo + ".value.substr(0,5) + '/' + document." + campo + ".value.substr(5,1)");
			}
		}	
	}

function MascaraHora(campo)
	{
	Permitido = "0123456789";
	ValorComprobarH = eval("document." + campo + ".value");
	Cache = ValorComprobarH.substr(eval("document." + campo + ".value.length")-1,1)
	
	if (Permitido.indexOf(Cache) < 0)
		{
		eval("document." + campo + ".value = ValorComprobarH.substr(0,ValorComprobarH.length-1)");
		}
	else
		{
		if (ValorComprobarH.length == 2)
			{
			eval("document." + campo + ".value = document." + campo + ".value + ':'"); 
			}
		else if (ValorComprobarH.length == 3 && ValorComprobarH.charAt(2) != ":")
			{
			eval("document." + campo + ".value = document." + campo + ".value.substr(0,2) + ':' + document." + campo + ".value.substr(2,1)");
			}
		}	
	}

//**********************************************************************************	

// *********** Función para quitar los espacios en blanco **************************
function Reemplazar (Texto,Quitar,Poner)
      {
      var NuevoTexto = "";      
      for (rempla_i = 0; rempla_i < Texto.length; rempla_i++)
            {
            NuevoTexto += Texto.charAt(rempla_i).replace(Quitar,Poner);
            }           
      return NuevoTexto;      
      }

//**********************************************************************************

//*******************************************************************************
//FORMULARIO RENTING
//*******************************************************************************

function EnviarPerfil(renting)
	{
	error = 0;

	if (document.renting.nombre.value == "")
		{
		alert("Debes indicar tu nombre.")
		document.renting.nombre.focus();
		error = 1;
		}
	
	if (document.renting.apellido1.value == "" && error == 0)
		{
		alert("Debes indicar tu primer apellido.")
		document.renting.apellido1.focus();
		error = 1;
		}
	//apellido2 no es obligatorio por los extranjeros
	if (document.renting.edad.value == 0 && error == 0)
		{
		alert("Debes indicar tu año de nacimiento.")
		document.renting.edad.focus();
		error = 1;
		}
	
	if (document.renting.carne.value == 0 && error == 0)
		{
		alert("Debes indicar el año de expedición de tu permiso de conducir.")
		document.renting.carne.focus();
		error = 1;
		}
	
	if ((document.renting.carne.value - document.renting.edad.value - 18) < 0 && error == 0)
		{
		alert("Por favor, comprueba tu año de nacimiento y la fecha de expedición de tu permiso de conducir.")
		document.renting.edad.focus();
		error = 1;
		}
	
	if (document.renting.provincia.value == 0 && error == 0)
		{
		alert("Debes indicar tu provincia de residencia.")
		document.renting.provincia.focus();
		error = 1;
		}

	if (document.renting.localidad.value == "" && error == 0)
		{
		alert("Debes indicar tu localidad de residencia.")
		document.renting.localidad.focus();
		error = 1;
		}

	if (document.renting.cp.value == "" && error == 0)
		{
		alert("Debes indicar tu Código Postal.")
		document.renting.cp.focus();
		error = 1;
		}

	
	if (! EsNumerico (document.renting.cp.value,false,false,false,5) && error == 0)
//	if ((isNaN(document.renting.cp.value) || (parseInt(document.renting.cp.value) != document.renting.cp.value) || document.renting.cp.value.length < 5) && error == 0)
		{
		alert ("Por favor, comprueba tu Código Postal. Este debe estar formado por 5 caracteres numéricos consecutivos.")
		document.renting.cp.focus();
		error = 1;
		}
	
	if (document.renting.email.value == "" && error == 0)
		{
		alert("Debes indicar una dirección de correo electrónico.")
		document.renting.email.focus();
		error = 1;
		}
	
	if (error == 0)
		{
		if (!ComprobarEmail(document.renting.email.value))
			{	
			document.renting.email.focus();
			error = 1;
			}	
		}
	
	
	if (document.renting.telefono.value == "" && error == 0)
		{
		alert("Debes indicar un teléfono de contacto.")
		document.renting.telefono.focus();
		error = 1;
		}
	
	if ((isNaN(document.renting.telefono.value) || document.renting.telefono.value.length < 9 || parseInt(document.renting.telefono.value) != document.renting.telefono.value) && error == 0)
		{
		alert("Por favor, comprueba el número de teléfono.")
		document.renting.telefono.focus();
		error = 1;
		}
	
	if (document.renting.aceptar_condiciones.checked == false && error == 0)
		{
		alert("Debes aceptar las condiciones.")
		document.renting.aceptar_condiciones.focus();
		error = 1;
		}
		
	if (error == 0)
		{
		document.renting.action = "r_t_inscripcion_c100_r.asp";
		document.renting.submit();
		}
	}
	
/********************************************************************
             Nombre: ComprobarNumero
Descripción: Comprueba el formato de un número
             Autor: Jorge Alcalá
             Fecha: 18/11/2003
Revisado: 19/11/2003
Entrada:    numero (string), numero a comprobar
             cero (true o false), se permite valor 0
             negativo (true o false), se permiten valores negativos
             decimales (true o false), se permiten decimales
             longitud (0 o int), longitud del string de entrada contando el punto en numeros decimales
Salida:      true o false

*********************************************************************/
function EsNumerico(numero,cero,negativo,decimales,longitud,EsJS)        
	{
	cero = (cero == null) ? true : cero;
	negativo = (negativo == null) ? true : negativo;
	decimales = (decimales == null) ? true : decimales;
	longitud = (longitud == null) ? 0 : longitud;
	EsJS = (EsJS == null) ? true : EsJS;
	if (EsJS)
		{
	    numero = Reemplazar(numero, ",", ".");
	    }
	if (isNaN(numero) || numero == "")
	   {
	   return false;
	   }            
	var buffer = parseFloat(numero);            
	if (!cero && buffer == 0)  // !cero es igual que cero == false
	    {
	    return false;
	    }
	if (!negativo && buffer < 0)
        {
        return false;
        }
	if (!decimales && buffer != parseInt(buffer))
        {
        return false;
        }
	if (longitud != 0)
        {
        numero += "";
        if (buffer < 0 && numero.length != (longitud + 1))
	        {
	        return false;
	        }
        else if (buffer >= 0 && numero.length != longitud)
            {
            return false;
            }
        }
	return true;       
	}
/********************************************************************
             Nombre: RentingCotizacion
Descripción: Comprueba los datos de la solicitud de cotización
             Fecha: 04/04/2006
Revisado: 
Entrada:     
Salida:     

*********************************************************************/

function RentingCotizacion()
	{
	error = 0;
	if (document.renting_cotizacion.modelo.value == 0)
		{
		alert("Debes seleccionar algún modelo.")
		document.renting_cotizacion.modelo.focus();
		error = 1;
		}
		
	if (error == 0)
		{
		var chequeado = false;
		for (var i=0;i<document.renting_cotizacion.duracion.length;i++)
			{
			if (document.renting_cotizacion.duracion[i].checked == true)
				{
				chequeado = true;
				}
			}
		if (chequeado == false)
			{
			alert("Debes indicar la duración del renting que te interesa.")
			error = 1;
			}
		}
		
	if ((isNaN (document.renting_cotizacion.kilometros.value) || document.renting_cotizacion.kilometros.value == "") && error == 0)
		{
		alert("Debes indicar los kilometros anuales (aproximados) que vas a realizar en formato numérico")
		document.renting_cotizacion.kilometros.focus();
		error = 1;
		}

	if (document.renting_cotizacion.kilometros.value < 0 && error == 0)
		{
		alert("La cantidad de kilómetros debe ser positiva")
		document.renting_cotizacion.kilometros.focus();
		error = 1;
		}
			
	if ((isNaN (document.renting_cotizacion.unidades.value) || document.renting_cotizacion.unidades.value == "") && error == 0)
		{
		alert("Debes indicar el numero de vehículos que te interesan")
		document.renting_cotizacion.unidades.focus();
		error = 1;
		}

	if (document.renting_cotizacion.unidades.value < 0 && error == 0)
		{
		alert("El número de unidades ha de ser positivo")
		document.renting_cotizacion.unidades.focus();
		error = 1;
		}
		
	if (document.renting_cotizacion.tipo_solicitante.checked == false && error == 0)
		{
		alert("Debes indicar si la cotización la solicita una Empresa, un Autónomo o un Particular.")
		document.renting_cotizacion.tipo_solicitante.focus();
		error = 1;
		}
	if (error == 0)
		{
		var chequeado = false
		for (i=0;i<document.renting_cotizacion.tipo_solicitante.length;i++)
			{
			if (eval(document.renting_cotizacion.tipo_solicitante[i].checked))
				{
				chequeado = true
				}
			}
		if (chequeado == false)
			{
			alert("Debes indicar si la cotización la solicita una Empresa, un Autónomo o un Particular.")
			error = 1;
			}
		}
	if (error == 0)
		{
		document.renting_cotizacion.action = "renting_datos.asp";
		document.renting_cotizacion.submit();
		}
}
/********************************************************************
             Nombre: RentingDatos
Descripción: Comprueba los datos de la solicitud de cotización
             Fecha: 04/04/2006
Revisado: 
Entrada:     
Salida:     

*********************************************************************/

function RentingDatos(tipo_solicitante)
	{
	error = 0;
	if (tipo_solicitante != "P")
		{
		if (document.renting_datos.razon_social.value == "" && error == 0)
			{
			alert("Debes indicar el nombre de la empresa.")
			document.renting_datos.razon_social.focus();
			error = 1;
			}
		
		if (document.renting_datos.cif.value == "" && error == 0)
			{
			alert("Debes indicar el C.I.F. de la empresa.")
			document.renting_datos.cif.focus();
			error = 1;
			}
		if (document.renting_datos.direccion_empresa.value == "" && error == 0)
			{
			alert("Debes indicar la dirección de la empresa.")
			document.renting_datos.direccion_empresa.focus();
			error = 1;
			}
		if (document.renting_datos.localidad_empresa.value == "" && error == 0)
			{
			alert("Debes indicar la ciudad en la que está la empresa.")
			document.renting_datos.localidad_empresa.focus();
			error = 1;
			}
		
		if (document.renting_datos.cp_empresa.value == "" && error == 0)
			{
			alert("Debes indicar el código postal.")
			document.renting_datos.cp_empresa.focus();
			error = 1;
			}
		if (! EsNumerico (document.renting_datos.cp_empresa.value,false,false,false,5) && error == 0)
	//	if ((isNaN(document.renting.cp.value) || (parseInt(document.renting.cp.value) != document.renting.cp.value) || document.renting.cp.value.length < 5) && error == 0)
			{
			alert ("Por favor, comprueba tu Código Postal. Este debe estar formado por 5 caracteres numéricos consecutivos.")
			document.renting_datos.cp_empresa.focus();
			error = 1;
			}
		if (document.renting_datos.provincia_empresa.value == 0 && error == 0)
			{
			alert("Debes indicar tu provincia de residencia.")
			document.renting_datos.provincia_empresa.focus();
			error = 1;
			}
		if (document.renting_datos.telefono_empresa.value == "" && error == 0)
			{
			alert("Debes indicar un teléfono de contacto.")
			document.renting_datos.telefono_empresa.focus();
			error = 1;
			}
		
		if ((isNaN(document.renting_datos.telefono_empresa.value) || document.renting_datos.telefono_empresa.value.length < 9 || parseInt(document.renting_datos.telefono_empresa.value) != document.renting_datos.telefono_empresa.value) && error == 0)
			{
			alert("Por favor, comprueba el número de teléfono.")
			document.renting_datos.telefono_empresa.focus();
			error = 1;
			}
			
		/*if (document.renting_datos.fax_empresa.value == "" && error == 0)
			{
			alert("Debes indicar un fax de contacto.")
			document.renting_datos.fax_empresa.focus();
			error = 1;
			}
		*/
		/*if ((isNaN(document.renting_datos.fax_empresa.value) || document.renting_datos.fax_empresa.value.length < 9 || parseInt(document.renting_datos.fax_empresa.value) != document.renting_datos.fax_empresa.value) && error == 0)
			{
			alert("Por favor, comprueba el número de fax.")
			document.renting_datos.fax_empresa.focus();
			error = 1;
			}*/	
		
		/*if (document.renting_datos.email_empresa.value == "" && error == 0)
			{
			alert("Debes indicar una dirección de correo electrónico válida.")
			document.renting_datos.email_empresa.focus();
			error = 1;
			}*/
		
		/*if (error == 0)
			{
			if (!ComprobarEmail(document.renting_datos.email_empresa.value))
				{	
				document.renting_datos.email_empresa.focus();
				error = 1;
				}	
			}*/
		}
		
	if (document.renting_datos.nombre_cliente.value == "" && error == 0)
		{
		alert("Debes indicar el nombre de la persona que solicita la cotización.")
		document.renting_datos.nombre_cliente.focus();
		error = 1;
		}
	
	if (document.renting_datos.apellido1.value == "" && error == 0)
		{
		alert("Debes indicar el primer apellido.")
		document.renting_datos.apellido1.focus();
		error = 1;
		}	
	
	/*if (document.renting_datos.apellido2.value == "" && error == 0)
		{
		alert("Debes indicar el segundo apellido.")
		document.renting_datos.apellido2.focus();
		error = 1;
		}
	*/	
	if (document.renting_datos.nif.value == "" && error == 0)
		{
		alert("Debes indicar el N.I.F. del solicitante.")
		document.renting_datos.nif.focus();
		error = 1;
		}
	
	if (document.renting_datos.direccion_cliente.value == "" && error == 0)
		{
		alert("Debes indicar tu dirección.")
		document.renting_datos.direccion_cliente.focus();
		error = 1;
		}
	if (document.renting_datos.localidad_cliente.value == "" && error == 0)
		{
		alert("Debes indicar tu ciudad.")
		document.renting_datos.localidad_cliente.focus();
		error = 1;
		}
	
	if (document.renting_datos.cp_cliente.value == "" && error == 0)
		{
		alert("Debes indicar el código postal.")
		document.renting_datos.cp_cliente.focus();
		error = 1;
		}
	
	if (! EsNumerico (document.renting_datos.cp_cliente.value,false,false,false,5) && error == 0)
//	if ((isNaN(document.renting.cp.value) || (parseInt(document.renting.cp.value) != document.renting.cp.value) || document.renting.cp.value.length < 5) && error == 0)
		{
		alert ("Por favor, comprueba tu Código Postal. Este debe estar formado por 5 caracteres numéricos consecutivos.")
		document.renting_datos.cp_cliente.focus();
		error = 1;
		}
	
	if (document.renting_datos.provincia_cliente.value == 0 && error == 0)
		{
		alert("Debes indicar tu provincia de residencia.")
		document.renting_datos.provincia_cliente.focus();
		error = 1;
		}		
	
	if (document.renting_datos.telefono_cliente.value == "" && error == 0)
		{
		alert("Debes indicar un teléfono de contacto.")
		document.renting_datos.telefono_cliente.focus();
		error = 1;
		}
	
	if ((isNaN(document.renting_datos.telefono_cliente.value) || document.renting_datos.telefono_cliente.value.length < 9 || parseInt(document.renting_datos.telefono_cliente.value) != document.renting_datos.telefono_cliente.value) && error == 0)
		{
		alert("Por favor, comprueba el número de teléfono.")
		document.renting_datos.telefono_cliente.focus();
		error = 1;
		}
		
	/*if (document.renting_datos.fax_cliente.value == "" && error == 0)
		{
		alert("Debes indicar un fax de contacto.")
		document.renting_datos.fax_cliente.focus();
		error = 1;
		}
	
	if ((isNaN(document.renting_datos.fax_cliente.value) || document.renting_datos.fax_cliente.value.length < 9 || parseInt(document.renting_datos.fax_cliente.value) != document.renting_datos.fax_cliente.value) && error == 0)
		{
		alert("Por favor, comprueba el número de fax.")
		document.renting_datos.fax_cliente.focus();
		error = 1;
		}
	*/
	/*if (document.renting_datos.email_cliente.value == "" && error == 0)
		{
		alert("Debes indicar una dirección de correo electrónico válida.")
		document.renting_datos.email_cliente.focus();
		error = 1;
		}
	*/
	/*if (error == 0)
		{
		if (!ComprobarEmail(document.renting_datos.email_cliente.value))
			{	
			document.renting_datos.email_cliente.focus();
			error = 1;
			}	
		}*/
	
	if (document.renting_datos.edad.value == 0 && error == 0)
		{
		alert("Debes indicar tu año de nacimiento.")
		document.renting_datos.edad.focus();
		error = 1;
		}
	
	if (document.renting_datos.carne.value == 0 && error == 0)
		{
		alert("Debes indicar el año de expedición de tu permiso de conducir.")
		document.renting_datos.carne.focus();
		error = 1;
		}
	
	if ((document.renting_datos.carne.value - document.renting_datos.edad.value - 18) < 0 && error == 0)
		{
		alert("Por favor, comprueba tu año de nacimiento y la fecha de expedición de tu permiso de conducir.")
		document.renting_datos.edad.focus();
		error = 1;
		}
		
	if (document.renting_datos.forma_oferta.checked == false && error == 0)
		{
		alert("Debes indicar si deseas recibir la cotización por fax, por e-mail, o bien recibir una visita comercial.")
		document.renting_datos.forma_oferta.focus();
		error = 1;
		}
	if (error == 0)
		{
		var chequeado = false
		for (i=0;i<document.renting_datos.forma_oferta.length;i++)
			{
			if (eval(document.renting_datos.forma_oferta[i].checked))
				{
				chequeado = true
				}
			}
		if (chequeado == false)
			{
			alert("Debes indicar si deseas recibir la cotización por fax, por e-mail, o bien recibir una visita comercial.")
			error = 1;
			}
		}
		
	if (document.renting_datos.aceptar_condiciones.checked == false && error == 0)
		{
		alert("Debes aceptar las condiciones.")
		document.renting_datos.aceptar_condiciones.focus();
		error = 1;
		}
			
if (error == 0)
		{
		document.renting_datos.action = "renting_t_inscripcion.asp";
		document.renting_datos.submit();
		}
}

/********************************************************************
             Nombre: RentingDatos
Descripción: Truco para solucionar el problema de los flash
             Fecha: 24/04/2006
Revisado: Ismael Teijón
Entrada:     
Salida:     

*********************************************************************/

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs, idName) 
{ 
  var str = '<object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';

    document.getElementsByName(idName)[0].innerHTML=str;
	//document.write(idName)
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs, ret.idName);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs, ret.idName);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  ret.idName = new String();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
	  case "idname":
	    ret.idName = args[i+1];
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "id":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

//*******************************************************************************
// Formulario Seminuevos
//*******************************************************************************

function EnviarSeminuevos(form)
	{
	error = 0;
	
	if (document.seminuevos.nombre.value == "")
		{
		alert("Debes indicar tu nombre.")
		document.seminuevos.nombre.focus();
		error = 1;
		}
	
	if (document.seminuevos.apellido1.value == "" && error == 0)
		{
		alert("Debes indicar al menos el primer apellido.")
		document.seminuevos.apellido1.focus();
		error = 1;
		}
	
	if (document.seminuevos.telefono.value == "" && error == 0)
		{		
		alert("Debes indicar tu teléfono")
		document.seminuevos.telefono.focus();
		error = 1;
		}	
	
	if ((isNaN(document.seminuevos.telefono.value) || document.seminuevos.telefono.value.length < 9 || parseInt(document.seminuevos.telefono.value) != document.seminuevos.telefono.value) && error == 0)
			{
			alert("Por favor, comprueba el número de teléfono.")
			document.seminuevos.telefono.focus();
			error = 1;
			}
	
	if (document.seminuevos.aceptar_condiciones.checked == false && error == 0)
		{
		alert("Debes aceptar las condiciones.")
		document.seminuevos.aceptar_condiciones.focus();
		error = 1;
		}		
	
	if (error == 0)
		{
		document.seminuevos.action = "t_seminuevos.asp";
		document.seminuevos.submit();
		}
	}
	
//************************************************************************************
// Carga en el combo de los Modelos los correspondientes a cada Categoria
//************************************************************************************
var ModeloSeleccionado;
function ModelosCategoria (formulario)
	{
	switch (eval('document.' + formulario + '.categoria.value'))
	{
	case '1':
		eval("document." + formulario + ".texto_categoria.value = 'Compactos/Urbanos'")
	break;
	case '2':
		eval("document." + formulario + ".texto_categoria.value = 'Deportivos/Cabrio'")
	break;
	case '3':
		eval("document." + formulario + ".texto_categoria.value = 'Lujo/Ejecutivos'")
	break;
	case '4':
		eval("document." + formulario + ".texto_categoria.value = 'Familiares/4x4'")
	break;
	default:
		eval("document." + formulario + ".categoria.value = '5'")
		eval("document." + formulario + ".texto_categoria.value = 'Todos los modelos'")
	break
	}

	//Borro los anteriores
	for (i=(eval('document.' + formulario + '.modelos.options.length')-1); i>=0; i--) 
		eval('document.' + formulario + '.modelos.options[i] = null');
	
	if (eval('document.' + formulario + '.categoria.value != 0'))
		{
		var auxModelos = eval("Modelos" + eval('document.' + formulario + '.categoria.value'))
		var auxIdModelos = eval("IdModelos" + eval('document.' + formulario + '.categoria.value'))
		eval("document." + formulario + ".modelos.options[eval('document.' + formulario + '.modelos.options.length')] = new Option('--- Todos los Modelo ---', 0)");
		eval("document." + formulario + ".modelos.options[0].selected = true");
		for (i = 0 ; i <  + auxModelos.length; i++){
			eval("document." + formulario + ".modelos.options[eval('document.' + formulario + '.modelos.options.length')] =  new Option(auxModelos[i], auxIdModelos[i])");
			if (ModeloSeleccionado == auxIdModelos[i]){
				eval("document." + formulario + ".modelos.options[eval('document.' + formulario + '.modelos.options.length-1')].selected = true");
				}
			}
		}
		//else {document.cotizador_index.modelos.options[document.cotizador_index.modelos.options.length] = new Option("---- Selecciona primero una categoría ----", 0);}
		//alert (document.pack_fechas.packs.options[1].value)
	}

//*******************************************************************************
// Enviar otros aspectos en Encuestas
//*******************************************************************************

function EnviarOtrosAspectos(form)
	{
	error = 0;
	if (document.otros_encuesta.otros_aspectos.value == "")
		{
		alert("Este campo no se puede dejar vacío.")
		document.otros_encuesta.otros_aspectos.value.focus();
		error = 1;
		}
	if (error == 0)
		{
		document.otros_encuesta.action = "t_encuesta_otros.asp";
		document.otros_encuesta.submit();
		}
	}

//*******************************************************************************
// Fin función Otros (Encuestas)
//*******************************************************************************	

function ReservaDatos ()
	{
	if (getCheckedValue(document.reserva_presupuesto.seleccion) == "")
		{
		alert ("Seleccione un presupuesto para continuar")
		}
	else
		{
		document.reserva_presupuesto.action = "reserva_datos_cliente.asp";
		document.reserva_presupuesto.submit();

		}	
	}
	
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}
//Funcines para el API de Google Maps
 function initialize(name, strSetCenterLat, strSetCenterLng, strPointLat, strPointLng) {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById(name));
		map.setCenter(new GLatLng(strSetCenterLat,strSetCenterLng), 17);
        var mapTypeControl = new GMapTypeControl();
        var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
        var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
        map.addControl(mapTypeControl, topRight);
        GEvent.addListener(map, "dblclick", function() {
          map.removeControl(mapTypeControl);
          map.addControl(new GMapTypeControl(), bottomRight);
        });
		
		
	
		
		
		
		
        map.addControl(new GSmallMapControl());
        var bounds = map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();
        var lngSpan = northEast.lng() - southWest.lng();
        var latSpan = northEast.lat() - southWest.lat();
		var point = new GLatLng(strPointLat,strPointLng);
        map.addOverlay(new GMarker(point));
      }
    }
//*******************************************************************************
// Formulario de Contacto
//*******************************************************************************

function comprobarPersonaEntrega(destino)
	{
	if (document.reserva.numero_documento.value.length < 6){
		alert("Debes indicar un documento identificativo correcto (DNI/NIE/Pasaporte) de la persona que retirará el vehículo");}
	else {
		switch (destino)
			{
			case 1:
				document.reserva.action = "t_inscripcion_reservas.asp";
				document.reserva.submit();
				break;
			case 2:
				return true;
			break;
			}
		}
	}
	
//-----------------------------------------------------------------------------
// AJAX
//-----------------------------------------------------------------------------

function handleHttpResponse() { 
    if (http.readyState == 4) { 
       if (http.status == 200) { 
		  if (http.responseText.indexOf('invalid') == -1) {
             // Armamos un array, usando la coma para separar elementos
             document.getElementById("divAyuda").innerHTML = http.responseText
             enProceso = false;
          }
       }
    }
}
var rutaAyuda
function txtGrabarVotosAyuda (idAyuda, ruta){
	var textoGrabarVotosAyuda;
	rutaAyuda = ruta
	textoGrabarVotosAyuda = "<br><br><div id='divAyuda' style='background-color:#E7E7E7;' align='left'>&nbsp;¿Ha sido &uacute;til esta ayuda?&nbsp;&nbsp;<a href='javascript:grabarVotosAyuda(" + idAyuda + ",1,0)' class='calendario'>Si</a>&nbsp;&nbsp;<a href='javascript:grabarVotosAyuda(" + idAyuda + ",0,1)' class='calendario'>No</a></div>";
	return textoGrabarVotosAyuda;
}

function grabarVotosAyuda (idAyuda, votosFavor, votosContra) {
    if (!enProceso && http) {

       var url = rutaAyuda + "t_votos_ayuda.asp?idAyuda=" + idAyuda + "&votosFavor=" + votosFavor + "&votosContra=" + votosContra;
       http.open("GET", url, true);
	   http.onreadystatechange = handleHttpResponse;
	   enProceso = true;
       http.send(null);
    }
}

function getHTTPObject() {
    var xmlhttp;
    /*@cc_on
    @if (@_jscript_version >= 5)
       try {
          xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
       } catch (e) {
          try {
             xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (E) { xmlhttp = false; }
       }
    @else
    xmlhttp = false;
    @end @*/
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
       try {
          xmlhttp = new XMLHttpRequest();
       } catch (e) { xmlhttp = false; }
    }
    return xmlhttp;
}

var enProceso = false; // lo usamos para ver si hay un proceso activo
var http = getHTTPObject(); // Creamos el objeto XMLHttpRequest

// Nuevas funciones para la cración de ventanas modales (capas)

/*
 * Static Class VentanaModal
 * 
 * Creado por Victor Manuel Merino Martinez
 * Version: 1.0
 *
 *
 * Metodos "publicos":
 *		- getInstancia()
 *		- setSize(Number: ancho, Number: alto)
 *		- setClaseVentana(String: nombreClase)
 *		- setSombra(Boolean: sombra)
 *		- setSombraSize(Number: sombraSize)
 *		- setClaseSombra(String: nombreClase)
 *		- setIdVentana(String: idVentana)
 *		- setClaseFondo(String: nombreClase)
 *		- setContenido(String: contenidoHtml)
 *		- mostrar()
 *		- cerrar()
 *
 * Metodos "privados":
 *		- inicializar()
 *		- redimensionar()
 *		- crear()
 *
 * Metodos de utilidades:
 *		- medio()
 *
 *
 *
 *
 */

var VentanaModal = {
	
	inicializado		: false,
	creado				: false,
	ancho				: 0,
	alto				: 0,
	sombra				: false,
	csombra				: null,
	tsombra				: 0,
	claseSombra			: "",
	ventana				: null,
	idVentana			: "",
	claseVentana		: "",
	MSIE				: false,
	fondo				: null,
	claseFondo			: "",
	
	getInstancia: function() {
		this.inicializar();
		this.crear();
		return this;
	},
	
	setSize: function(ancho, alto) {
		this.alto = parseInt(alto);
		this.ancho = parseInt(ancho);
		this.ventana.style.width = this.ancho + "px";
		this.ventana.style.height = this.alto + "px";
		this.csombra.style.width = this.ancho + "px";
		this.csombra.style.height = this.alto + "px";
		this.redimensionar();
		
	},
	
	setClaseVentana: function(nombreClaseVentana) {
		this.claseVentana = nombreClaseVentana;
		this.ventana.className = this.claseVentana;
	},
	
	setSombra: function(sombra) {
		if (sombra == true) {
			this.sombra = true;
			this.csombra.style.display = "inline";
		}
		else {
			this.sombra = false;
			this.csombra.style.display = "none";
		}
	},
	
	setSombraSize: function(tsombra) {
		this.tsombra = tsombra;
		this.redimensionar();
	},
	
	setClaseSombra: function(claseSombra) {
		this.claseSombra = claseSombra;
		this.csombra.className = this.claseSombra;
	},
	
	setIdVentana: function(id) {
		this.idVentana = id;
		this.ventana.id = this.idVentana;
	},
	
	setClaseFondo: function(claseFondo) {
		this.claseFondo = claseFondo;
		this.fondo.className = this.claseFondo;
	},
	
	setContenido: function(html) {
		this.ventana.innerHTML = html;
	},
	
	mostrar: function() {
		this.fondo.style.display = "inline";
		this.ventana.style.display = "inline";
		if (this.sombra)
			this.csombra.style.display = "inline";
		
		this.ventana.focus ();
	},

	cerrar: function() {
		this.ventana.style.display = "none";
		this.csombra.style.display = "none";
		this.fondo.style.display = "none";
	},
	
	medio: function(windowTam, capaTam, pageTam, clicPos) {
		if (isNaN(windowTam) && windowTam.indexOf("px") != -1)
			windowTam = windowTam.replace("px", "");
		if (isNaN(capaTam) && capaTam.indexOf("px") != -1)
			capaTam = capaTam.replace("px", "");
		if (clicPos > windowTam){
			//alert ("windowTam: " + windowTam + ", capaTam: " + capaTam + ", pageTam: " + pageTam + ", clicPos: " + clicPos);
			aux = parseInt(clicPos) - (parseInt(capaTam) / 2);
			if (parseInt(clicPos) + (parseInt(capaTam) / 2) > pageTam)
				aux = pageTam - capaTam - 20;
			}
		else{
			var aux = parseInt(windowTam) / 2;
			aux = aux - (parseInt(capaTam) / 2);
			if (aux < 0)
				aux = 1;
			}
		return parseInt(aux);
	},
	
	inicializar: function() {
		if (this.inicializado) 
			return;
		window.onresize = function() {
			VentanaModal.redimensionar();
		};
		
		this.ancho = 300;
		this.alto = 200;
		this.sombra = true;
		this.tsombra = 5;
				
		if (navigator.userAgent.indexOf('MSIE') >= 0) 
			this.MSIE = true;
			
		if (this.MSIE) {this.claseSombra = "ventana-modal-sombra-ie";
			this.claseFondo = "ventana-modal-fondo-ie";}
		else{this.claseSombra = "ventana-modal-sombra";
			this.claseFondo = "ventana-modal-fondo";}
		this.claseVentana = "ventana-modal-ventana";

		this.inicializado = true;
		this.crear();
	},
	
	redimensionar: function() {
		var top = 0;
		var left = 0;
		var alto = 0;
		//if (this.MSIE) {
		//	this.fondo.style.width = document.body.clientWidth;
        //if (document.body.clientHeight)
	  	//		this.fondo.style.height = document.body.clientHeight;
		//	else if (document.documentElement)
		//		this.fondo.style.height = document.documentElement.clientHeight;
		//}
		//else {
		var arrayPageSize = getPageSize();
		//alert("pageW: "+ arrayPageSize[0] + "pageH: "+ arrayPageSize[1] + "WindowW: "+ arrayPageSize[2]+ "WindowH: "+ arrayPageSize[3]);
		this.fondo.style.width = arrayPageSize[0];
		this.fondo.style.height = arrayPageSize[1];
		//}
		/*if (this.MSIE) {
			top = this.medio(document.body.clientHeight, this.alto);
			left = this.medio(document.body.clientWidth, this.ancho);
		}
		else {
			top = this.medio(innerHeight, this.alto);
			left = this.medio(innerWidth, this.ancho);
		}*/

		top = this.medio(arrayPageSize[3], this.alto, arrayPageSize[1], tempY);
		left = this.medio(arrayPageSize[2], this.ancho, 0, 0);
		this.ventana.style.top = top + "px";
		this.ventana.style.left = left + "px";
		this.csombra.style.top = (parseInt(top) + this.tsombra) + "px";
		this.csombra.style.left = (parseInt(left) + this.tsombra) + "px";
	},
	
	crear: function() {
		if (this.creado) 
			return;
		this.fondo = document.createElement("DIV");
		this.fondo.style.position = "absolute";
		this.fondo.style.left = "0px";
		this.fondo.style.top = "0px";
		this.fondo.style.display = "none";
		this.fondo.className = this.claseFondo;
		this.fondo.style.zIndex = 90000;
		this.fondo.style.textAlign = "center";
		document.body.appendChild(this.fondo);
		
		this.ventana = document.createElement("DIV");
		document.body.appendChild(this.ventana);
		this.ventana.style.display = "none";
		this.ventana.style.position = "absolute";
		//this.ventana.style.overflow = "auto";
		this.ventana.style.zIndex = 100000;
		this.ventana.style.width = this.ancho + "px";
		this.ventana.style.height = this.alto + "px";
		this.ventana.className = this.claseVentana;
		
		this.csombra = document.createElement("DIV");
		document.body.appendChild(this.csombra);
		this.csombra.style.display = "none";
		this.csombra.style.position = "absolute";
		this.csombra.style.zIndex = 95000;
		this.csombra.style.width = this.ancho + "px";
		this.csombra.style.height = this.alto + "px";
		this.csombra.className = this.claseSombra;
		
		this.creado = true;
		this.redimensionar();
	}
};

function abrirVentana(pagina, ancho, alto, nombre,sinCerrar) {
	VentanaModal.inicializar();
    var html = ""
    + "<table cellpadding='3' cellspacing='0' border='0' class='ventana-modal-ventana'><tr><td class='ventana-modal-barra' align='right'>"
    if (sinCerrar != true)
	html = html + "<img class='ventana-modal-cerrar' src='http://www.daperton.com/daperton/img/cerrar.gif' title='Cerrar ventana' onclick='VentanaModal.cerrar()'>"
	
    html = html + "</td></tr><tr><td valign='middle'>"	
    + "<iframe name='" + nombre + "' src='" + pagina + "' width='100%' height='" + (parseInt(alto) - 30) + "' frameborder='0'></iframe>"
    + "</td></tr></table>";
	VentanaModal.setSize(ancho, alto);
    VentanaModal.setClaseVentana("");
    VentanaModal.setContenido(html);
    VentanaModal.mostrar();
}
function abrirVentanaNavidad(pagina, ancho, alto, nombre) {
    VentanaModal.inicializar();
    var html = ""
    + "<table cellpadding='0' cellspacing='0' border='0' class='ventana-modal-ventana'><tr><td class='ventana-modal-barra' align='right'>"
    + "<img class='ventana-modal-cerrar' src='http://www.daperton.com/daperton/img/cerrar.gif' title='Cerrar ventana' onclick='VentanaModal.cerrar()'>"
    + "</td></tr><tr><td valign='middle' align='center'>"	
    + "<iframe name='" + nombre + "' src='" + pagina + "' width='100%' height='" + (parseInt(alto) - 30) + "' frameborder='0' scrolling='No'></iframe>"
    + "</td></tr></table>";
    
	VentanaModal.setSize(ancho, alto);
    VentanaModal.setClaseVentana("");
    VentanaModal.setContenido(html);
    VentanaModal.mostrar();
}


//-------------- Cookie -----------------
var validez = 30;//dÃ­as
var caduca = new Date(); 
caduca.setTime(caduca.getTime() + (validez*24*60*60*1000));

function getCookie(name){
  var cname = name + "=";               
  var dc = document.cookie;             
  if (dc.length > 0) {              
    begin = dc.indexOf(cname);       
    if (begin != -1) {           
      begin += cname.length;       
      end = dc.indexOf(";", begin);
      if (end == -1) end = dc.length;
        return unescape(dc.substring(begin, end));
    } 
  }
  return null;
}

function setCookie(name, value, expires, path, domain, secure) {
  document.cookie = name + "=" + escape(value) + 
  ((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
  ((path == null) ? "" : "; path=" + path) +
  ((domain == null) ? "" : "; domain=" + domain) +
  ((secure == null) ? "" : "; secure");
}

// --------------- Capa de Navidad -----------------

function cargarCapaNavidad(){
	var primeraVisita = getCookie('primeraVisita');
	if (primeraVisita == null) {
		abrirVentanaNavidad('daperton/capaNavidad.html',535,344,'Navidad');
		setTimeout('parent.VentanaModal.cerrar()',15000);
		setCookie ('primeraVisita', primeraVisita, caduca);
		}
	}
	
// -----------------------------------------------------------------------------------

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.com
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}
	/*detectar navegador y declaraciones*/
var IE = document.all?true:false
if (!IE) document.captureEvents(Event.MOUSEMOVE)
var tempX = 0
var tempY = 0/*llamada a la funcion con un handler*/
document.onclick = getMouseXY;

function getMouseXY(e) { //hace todo el trabajo
  if (IE) {
    tempX = event.clientX + document.body.scrollLeft
    tempY = event.clientY + document.body.scrollTop
  } else {
    tempX = e.pageX
    tempY = e.pageY
  }
  return true
}
if( document.getElementsByTagName ){
 var links = document.getElementsByTagName('a');
 for( var i=0; i < links.length; i++ ){
  links[i].onclick = function(){
   return getMouseXY(this);
  }
 }
}
//*******************************************************************************
// Formulario Oneway 9-6-2008
//*******************************************************************************

function EnviarOneway(form)
	{
	error = 0;
	
	if (document.oneway.nombre.value == "")
		{
		alert("Debes indicar tu nombre.")
		document.oneway.nombre.focus();
		error = 1;
		}
	
	if (document.oneway.apellido1.value == "" && error == 0)
		{
		alert("Debes indicar al menos el primer apellido.")
		document.oneway.apellido1.focus();
		error = 1;
		}
	
	if (document.oneway.email.value != "" && error == 0)
		{		
		if (!ComprobarEmail(document.oneway.email.value))
			{	
			document.oneway.email.focus();
			error = 1;
			}
		}
	if (document.oneway.telefono.value == "" && error == 0)
		{		
		alert("Debes indicar tu teléfono")
		document.oneway.telefono.focus();
		error = 1;
		}	
	
	if ((isNaN(document.oneway.telefono.value) || document.oneway.telefono.value.length < 9 || parseInt(document.oneway.telefono.value) != document.oneway.telefono.value) && error == 0)
			{
			alert("Por favor, comprueba el número de teléfono.")
			document.oneway.telefono.focus();
			error = 1;
			}
			
	if (error == 0)
		{
		document.oneway.action = "t_oneway.asp";
		document.oneway.submit();
		}
	}

//*******************************************************************************
// Formulario Empresas 9-6-2008
//*******************************************************************************

function EnviarEmpresas(form)
	{
	error = 0;
	
	if (document.empresas.empresa.value == "")
		{
		alert("Debe indicar el nombre de la empresa.")
		document.empresas.empresa.focus();
		error = 1;
		}
	if (document.empresas.nombre.value == "" && error == 0)
		{
		alert("Debe indicar tu nombre.")
		document.empresas.nombre.focus();
		error = 1;
		}
	if (document.empresas.apellidos.value == "" && error == 0)
		{
		alert("Debe indicar al menos el primer apellido.")
		document.empresas.apellidos.focus();
		error = 1;
		}
	if (document.empresas.email.value == "" && error == 0)
		{
		alert("Debe indicar el email de la empresa.")
		document.empresas.email.focus();
		error = 1;
		}
	if (document.empresas.email.value != "" && error == 0)
		{		
		if (!ComprobarEmail(document.empresas.email.value))
			{	
			document.empresas.email.focus();
			error = 1;
			}
		}
	if (document.empresas.telefono.value == "" && error == 0)
		{		
		alert("Debe indicar tu teléfono")
		document.empresas.telefono.focus();
		error = 1;
		}	
	
	if ((isNaN(document.empresas.telefono.value) || document.empresas.telefono.value.length < 9 || parseInt(document.empresas.telefono.value) != document.empresas.telefono.value) && error == 0)
			{
			alert("Por favor, compruebe el número de teléfono.")
			document.empresas.telefono.focus();
			error = 1;
			}
			
	if (document.empresas.aceptar_condiciones.checked == false && error == 0)
		{
		alert("Debes aceptar las condiciones.")
		document.empresas.aceptar_condiciones.focus();
		error = 1;
		}
	
	if (error == 0)
		{
		document.empresas.action = "t_empresas.asp";
		document.empresas.submit();
		}
	}
	
//*******************************************************************************
// Formulario Minirenting 15/7/2008 JMA
//*******************************************************************************

function EnviarMinirenting(form)
	{
	error = 0;
	
	if (document.minirent.nombre.value == "")
		{
		alert("Debes indicar tu nombre.")
		document.minirent.nombre.focus();
		error = 1;
		}
	
	if (document.minirent.apellido1.value == "" && error == 0)
		{
		alert("Debes indicar al menos el primer apellido.")
		document.minirent.apellido1.focus();
		error = 1;
		}
	
	if (document.minirent.telefono.value == "" && error == 0)
		{		
		alert("Debes indicar tu teléfono")
		document.minirent.telefono.focus();
		error = 1;
		}	
	
	if ((isNaN(document.minirent.telefono.value) || document.minirent.telefono.value.length < 9 || parseInt(document.minirent.telefono.value) != document.minirent.telefono.value) && error == 0)
			{
			alert("Por favor, comprueba el número de teléfono.")
			document.minirent.telefono.focus();
			error = 1;
			}
			
	if (error == 0)
		{
		document.minirent.action = "t_minirent.asp";
		document.minirent.submit();
		}
	}

//*******************************************************************************
// Funciones necesarias para 
//*******************************************************************************

function ponoff(formulario)
	{
		if (eval('old_categoria != document.' + formulario + '.categoria.value'))
			{
			if (formulario == 'reservar')
				eval("document.images['categoria_"+old_categoria+"'].src = 'img/reserva_categoria_"+old_categoria+"_off.gif'");
			else
				eval("document.images['categoria_"+old_categoria+"'].src = 'daperton/img/reserva_categoria_"+old_categoria+"_off.gif'");
			}
	}

function mostrar(nombreCapa)
{ 
document.getElementById(nombreCapa).style.display="block"; 
}

function ocultar(nombreCapa)
{ 
document.getElementById(nombreCapa).style.display="none"; 
}

function ActivaOficina(formulario, RetiradaDevolucion)
{
	var raiz;
	if (formulario == 'reservar_index')
		raiz = "daperton/";
	else
	    raiz = "";
	mostrar('estaciones_' + RetiradaDevolucion);
	mostrar('adomicilio_' + RetiradaDevolucion);
	mostrar('oficina_' + RetiradaDevolucion);
	document.images['boton_oficina_' + RetiradaDevolucion].src=raiz+'img/boton_oficina_on.gif';
	document.images['boton_estaciones_' + RetiradaDevolucion].src=raiz+'img/boton_estaciones_off.gif';
	document.images['boton_adomicilio_' + RetiradaDevolucion].src=raiz+'img/boton_adomicilio_off.gif';
	eval('document.'+formulario+'.lugar_' + RetiradaDevolucion + '[0].checked=true');
}

function ActivaEstaciones(formulario, RetiradaDevolucion)
{
	var raiz;
	if (formulario == 'reservar_index')
		raiz = "daperton/";
	else
		raiz = "";
	mostrar('estaciones_' + RetiradaDevolucion);
	mostrar('adomicilio_' + RetiradaDevolucion);
	mostrar('oficina_' + RetiradaDevolucion);
	document.images['boton_oficina_' + RetiradaDevolucion].src=raiz+'img/boton_oficina_off.gif';
	document.images['boton_estaciones_' + RetiradaDevolucion].src=raiz+'img/boton_estaciones_on.gif';
	document.images['boton_adomicilio_' + RetiradaDevolucion].src=raiz+'img/boton_adomicilio_off.gif';
	eval('document.'+formulario+'.lugar_' + RetiradaDevolucion + '[0].checked=false');
	eval('document.'+formulario+'.lugar_' + RetiradaDevolucion + '[3].checked=false');
}

function ActivaAdomicilio(formulario, RetiradaDevolucion)
{
	var raiz;
	if (formulario == 'reservar_index')
		raiz = "daperton/";
	else
	    raiz = "";
	mostrar('estaciones_' + RetiradaDevolucion);
	mostrar('adomicilio_' + RetiradaDevolucion);
	mostrar('oficina_' + RetiradaDevolucion);
	document.images['boton_oficina_' + RetiradaDevolucion].src=raiz+'img/boton_oficina_off.gif';
	document.images['boton_estaciones_' + RetiradaDevolucion].src=raiz+'img/boton_estaciones_off.gif';
	document.images['boton_adomicilio_' + RetiradaDevolucion].src=raiz+'img/boton_adomicilio_on.gif';
	eval('document.'+formulario+'.lugar_' + RetiradaDevolucion + '[3].checked=true');
	eval('document.'+formulario+'.cp_' + RetiradaDevolucion + '.disabled=false');
}

function CapaDevolucion(formulario, ocultar_capa)
{
	if (ocultar_capa){
		ocultar('capa_lugar_devolucion');
		ocultar('estaciones_devolucion');
		ocultar('adomicilio_devolucion');
		ocultar('oficina_devolucion');
			}
	else{
	    ActivaOficina(formulario, 'devolucion')
	    LoadLugares('OV', 'D');
		mostrar('capa_lugar_devolucion');
		
		}
}
//********** Funcion adaptada para promocion Qué! 3 de diciembre de 2008 *****
function EnviarConsultaQue()
	{
	document.que.submit();
	}	

//***************************************************************************