var ventanaCalendario=false

function muestraCalendario(raiz,formulario_destino,campo_destino,mes_destino,ano_destino){
	//funcion para abrir una ventana con un calendario.
	//Se deben indicar los datos del formulario y campos que se desean editar con el calendario, es decir, los campos donde va la fecha.
	if (typeof ventanaCalendario.document == "object") {
		ventanaCalendario.close()
	}
	ventanaCalendario = window.open("calendario/index.php?formulario=" + formulario_destino + "&nomcampo=" + campo_destino,"calendario","width=250,height=200,left=100,top=100,scrollbars=no,menubars=no,statusbar=NO,status=NO,resizable=YES,location=NO")
}

function desactiva(clave) {
	valor=document.getElementById(clave).disabled;
	if (valor == "") {
		document.getElementById(clave).checked=0;
		document.getElementById(clave).disabled="disabled";
	} else {
		document.getElementById(clave).disabled="";
	}
}

function compruebanacimiento(esteanio) {
	valor=document.getElementById("nace").value;
	trozos=valor.split("/");
	aniopuesto=parseInt(trozos[2]);
	aniominimo = esteanio - 25;
	anionoalquiler = esteanio - 21;
	if (aniopuesto > aniominimo) {
		document.forms[0].extra_PL.disabled=true;
		document.forms[0].extra_ME.checked=true;
	} else {
		document.forms[0].extra_PL.disabled=false;
		document.forms[0].extra_ME.checked=false;
		/*
		document.getElementById("PL").disabled=false;
		document.getElementById("CJ").checked="";
		*/
	}
	if (aniopuesto > anionoalquiler) {
		alert1("Edad minima 21 años");
		document.getElementById("nace").focus();
	}
}

function ayuda(pag){
window.open(pag,"popup","width=450,height=450,toolbar=no,scrollbars=yes");
}

function minanos(FechaComp,anios) {
  
  //FECHA A COMPROBAR
  var Ano= new String(FechaComp.substring(FechaComp.lastIndexOf("/")+1,FechaComp.length))
  // Cadena Mes
  var Mes= new String(FechaComp.substring(FechaComp.indexOf("/")+1,FechaComp.lastIndexOf("/")))
  // Cadena Día
  var Dia= new String(FechaComp.substring(0,FechaComp.indexOf("/")))
 
  //AÑO QUE DEBERIA SER PARA CUNPLIRSE
  var Anio = parseFloat(Ano)+parseFloat(anios);
  
  //FECHA DE RESERVA
  var time=new Date();
  var diareser = time.getDay();
  var mesreser = time.getMonth();
  var anioreser = time.getYear();
  if (anioreser < 2000) {
  	anioreser = anioreser + 1900;
  }
  var fechreserva = diareser + "/" + mesreser + "/" + anioreser;
  var esteanio= new String(fechreserva.substring(fechreserva.lastIndexOf("/")+1,fechreserva.length))
  // Cadena Mes
  var estemes= new String(fechreserva.substring(fechreserva.indexOf("/")+1,fechreserva.lastIndexOf("/")))
  // Cadena Día
  var estedia= new String(fechreserva.substring(0,fechreserva.indexOf("/")))
  
  
  if (Anio > parseFloat(esteanio) )
	{
	return false;
	}
  else if (Anio == parseFloat(esteanio))
  	{
	if ( parseFloat(Mes) > parseFloat(estemes))
		{
		return false;
		}
	else if (parseFloat(Mes) == parseFloat(estemes))
		{
		if (parseFloat(Dia) > parseFloat(estedia))
			{
			return false;
			}
		}
	}
  return true;
}

function validafecha(Cadena,campo) {
  //var Cadena = fecha;
  var Fecha= new String(Cadena)	// Crea un string
  var RealFecha= new Date()	// Para sacar la fecha de hoy
  // Cadena Año
  var Ano= new String(Fecha.substring(Fecha.lastIndexOf("/")+1,Fecha.length))
  // Cadena Mes
  var Mes= new String(Fecha.substring(Fecha.indexOf("/")+1,Fecha.lastIndexOf("/")))
  // Cadena Día
  var Dia= new String(Fecha.substring(0,Fecha.indexOf("/")))
  
  //Valido año
  if (isNaN(Ano) || Ano.length<4 || parseFloat(Ano)<1900){
       	alert1(campo+': Fecha Inválida, formato DD/MM/AAAA')
	return false
	}
  // Valido el Mes
  if (isNaN(Mes) || parseFloat(Mes)<1 || parseFloat(Mes)>12 || Mes.length<2){
	alert1(campo+': Fecha Inválida, formato DD/MM/AAAA')
	return false
	}
  // Valido el Dia
  if (isNaN(Dia) || parseFloat(Dia)<01 || parseFloat(Dia)>31 || Dia.length<2){
	alert1(campo+': Fecha Inválida, formato DD/MM/AAAA')
	return false
  }
  if (Mes==4 || Mes==6 || Mes==9 || Mes==11 || Mes==2) {
	if (Mes==2 && Dia > 28 || Dia>30) {
		alert1(campo+': Fecha Inválida, formato DD/MM/AAAA')
		return false
		}
	}
return true;
}

function validar(formulario)
{
  if (formulario.nombre.value.length < 1)
  {
    alert1("El campo Nombre es obligatorio");
    formulario.nombre.focus();
    return (false);
  }
  if (formulario.apellidos.value.length < 1)
  {
    alert1("El campo Apellidos es obligatorio.");
    formulario.apellidos.focus();
    return(false);
  }
  if (formulario.direc.value.length < 1)
  {
  	alert1("El campo Domicilio es obligatorio.");
	formulario.direc.focus();
	return(false);
  }
  if (formulario.poblacion.value.length < 1)
  {
  	alert1 ("El campo Población es obligatorio.");
	formulario.poblacion.focus();
	return(false);
  }
  if (formulario.codigo_postal.value.length <1)
  {
  	alert1("El campo Código Postal es obligatorio.");
	formulario.codigo_postal.focus();
	return(false);
  }

 // VALIDAMOS QUE EL CODIGO POSTAL SEAN NUMEROS SI ES EN ESPAÑA
 if (formulario.nacion.value == "E")
  {
  var checkOK = "0123456789";
  var checkStr = formulario.codigo_postal.value;
  var allValid = true;
  var decPoints = 0;
  var allNum = "";
    for (i = 0; i < checkStr.length; i++) {
      ch = checkStr.charAt(i);
      for (j = 0; j < checkOK.length; j++) {
        if (ch == checkOK.charAt(j))
          break;
	}
      if (j == checkOK.length) {
        allValid = false;
        break;
      }
      allNum += ch;
    }
    if ( (!allValid) || (formulario.codigo_postal.value.length != 5) ){
      alert1("Código postal incorrecto");
      formulario.codigo_postal.focus();
      return false;
    }
  }
  
   if ( !validafecha(formulario.nace.value,'Fecha de nacimiento'))
 	{
	formulario.nace.focus();
	return false;
	}
  if ( !minanos(formulario.nace.value,'21'))
  	{
	alert1("El conductor debe tener al menos 21 años");
	return false;
	}
 if (formulario.nacion.value == "E")
 {
  // VALIDAMOS EL FORMATO DEL NIF
  var checkOK = "0123456789ABCDEFGHIJKLMNÑLLOPQRSTUVWXYZabcdefghijklmnñlopqrstuvwxyz";
  var checkStr = formulario.nif_cli.value;
  var allValid = true;
  var decPoints = 0;
  var allNum = "";
    for (i = 0; i < checkStr.length; i++) {
      ch = checkStr.charAt(i);
      for (j = 0; j < checkOK.length; j++) {
        if (ch == checkOK.charAt(j))
          break;
	}
      if (j == checkOK.length) {
        allValid = false;
        break;
      }
      allNum += ch;
    }
    if (!allValid) {
      alert1("Escriba sólo dígitos y letras en el campo \"Nif\".");
      formulario.nif_cli.focus();
      return false;
    }
    if (formulario.nif_cli.value.length != 9)
    	{
	alert1("Nif Erroneo");
	formulario.nif_cli.focus();
	return false;
	}
}
  if (formulario.permiso.value.length <1)
  {
  	alert1("El campo Numero de Permiso es obligatorio");
	formulario.permiso.focus();
	return(false);
  }
  if (formulario.fechexpe.value.length <1)
  {
  	alert1("El campo Fecha de Expedicion es obligatorio");
	formulario.fechexpe.focus();
	return(false);
  }
   if ( !validafecha(formulario.fechexpe.value,'Fecha de expedición'))
	{
	return false
	}
  if ( !minanos(formulario.fechexpe.value,'3'))
  	{
	alert1("El conductor debe tener al menos 3 años de antiguedad");
	return false;
	}
	  
  if (formulario.nacion.value == "E")
  	{
	  if (formulario.fechaexpi.value.length <1)
	  {
	  	alert1("El campo Fecha de Caducidad es obligatorio");
		formulario.fechaexpi.focus();
		return(false);
	  }
	 }
   if ( (formulario.fechaexpi.value.length != 0) && (!validafecha(formulario.fechaexpi.value,'Fecha de expiración') ) )
	{
	return false
	}
  if (formulario.locexp.value.length <1)
  {
  	alert1("El campo Lugar de Expedicion es obligatorio");
	formulario.locexp.focus();
	return(false);
  }
  if (formulario.cat.value.length <1)
  {
  	alert1("El campo Categoria es obligatorio");
	formulario.cat.focus();
	return(false);
  }
 /* if (formulario.mail.value.length <1)
  {
  	alert1("El campo E-Mail es obligatorio");
	formulario.mail.focus();
	return(false);
  }
  */
    // VALIDAMOS EL FORMATO DEL MAIL
   if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(formulario.mail.value)){
    alert1("La dirección de email es incorrecta.");
    formulario.mail.focus();
    return (false);
  }
  if (formulario.contact.value.length <1)
  {
  	alert1("El campo Persona de contacto es obligatorio");
	formulario.contact.focus();
	return(false);
  }
  if (formulario.nacion.value == "E")
  {
  	/*
	if (formulario.telf.value.length != 9)
  	{
  		alert1("El campo Telefono es obligatorio y debe tener 9 cifras");
		formulario.telf.focus();
		return(false);
	}
	*/
  }
  else
  {
  	if (formulario.telf.value.length < 5)
	{
		alert1 ("El campo telefono es obligatorio");
		formulario.telf.focus();
		return false;
	}
  }
  if (formulario.movil.value.length != 9)
  {
  	alert1("El campo Telefono M&oacute;vil es obligatorio y debe tener 9 cifras");
	formulario.movil.focus();
	return(false);
  }
  return true;
}// FIN VALIDAR

//TOOLTIP
var theObj="";
 
function toolTip(text,me) {
       theObj=me;
       theObj.onmousemove=updatePos;
       document.getElementById('toolTipBox').innerHTML=text;
       document.getElementById('toolTipBox').style.display="block";
       window.onscroll=updatePos;
}
function updatePos() {
       var ev=arguments[0]?arguments[0]:event;
       var x=ev.clientX;
       var y=ev.clientY;
       diffX=24;
       diffY=-30;
       document.getElementById('toolTipBox').style.top  = y-2+diffY+document.body.scrollTop+ "px";
       document.getElementById('toolTipBox').style.left = x-2+diffX+document.body.scrollLeft+"px";
       theObj.onmouseout=hideMe;
}
 
function hideMe() {
       document.getElementById('toolTipBox').style.display="none";
}
