msje="Por favor, revise los errores en los siguientes campos:\n\n";
equivoc=0;

function emilio(contcorreo,nombrecampo){
        //compruebo el emilio
                var correo=contcorreo;
                var fallo_correo = 0;
                var pos = correo.indexOf("@");
                
                if (pos == -1){
                        equivoc=1;
                        fallo_correo = 1;
                }
        
        //compruebo q tenga al menos 1 carácter antes y después de le arroba y el punto
                if ((pos == 0)||(pos == correo.length-1)) {
                        equivoc=1;
                        fallo_correo = 1;
                }
                
                var pos2 = correo.lastIndexOf(".");
                if((pos2 < pos+1)||(pos2 == correo.length-1)){
                        equivoc=1;
                        fallo_correo = 1;        
                }
/*
                for (i=0; i<correo.length; i++){
                        if (correo.charCodeAt(i)==" ") {
                        equivoc=1;
                        fallo_correo = 1;
                        }
                }*/
                
                if (fallo_correo==1){
                        msje+="· El campo '"+nombrecampo+"' requiere una dirección de correo válida.\n";
                }
}

function validar_fecha(field){
        //compruebo la fecha mientras la mete el usuario
        var checkstr = "0123456789";
        var DateField = field;
        var Datevalue = "";
        var DateTemp = "";
        var seperator = "/";
        var day;
        var month;
        var year;
        var leap = 0;
        var err = 0;
        var i;
   err = 0;
   DateValue = DateField.value;
   /* borra todos los caracteres excepto 0..9 */
   for (i = 0; i < DateValue.length; i++) {
          if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
             DateTemp = DateTemp + DateValue.substr(i,1);
          }
   }
   DateValue = DateTemp;
   /* Siempre cambio la fecha a 8 dígitos - cadena */
   /* si el año tiene 2 digitos/ se asume 20xx */
   if (DateValue.length == 6) {
      DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); }
   if (DateValue.length != 8) {
      err = 19;}
   /* año incorrecto si es = 0000 */
   year = DateValue.substr(4,4);
   if (year == 0) {
      err = 20;
   }
   /* valido mes*/
   month = DateValue.substr(2,2);
   if ((month < 1) || (month > 12)) {
      err = 21;
   }
   /* valido día*/
   day = DateValue.substr(0,2);
   if (day < 1) {
     err = 22;
   }
   /* validación de año bisiesto */
   if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
      leap = 1;
   }
   if ((month == 2) && (leap == 1) && (day > 29)) {
      err = 23;
   }
   if ((month == 2) && (leap != 1) && (day > 28)) {
      err = 24;
   }
   /* validacion de otros meses */
   if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
      err = 25;
   }
   if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
      err = 26;
   }
   /* Si se mete 00, directamente borro */
   if ((day == 0) && (month == 0) && (year == 00)) {
      err = 0; day = ""; month = ""; year = ""; seperator = "";
   }
   /* si no hay error, lo meto en el campo */
   if (err == 0) {
      DateField.value = day + seperator + month + seperator + year;
   }
   /* Si el error es != 0 , mensaje */
   else {
      alert("La fecha es incorrecta");
      DateField.select();
          DateField.focus();
   }
}


function checkeacampo(tipo,campo,form){
        /*
        validacion de campos; "tipo" nos dice si es cadena, numero, fecha, dni,... Con "campo" le paso dos
        cosas: el nombre del campo y  si es o no obligatorio. por eso lo primero que hago es esplitear cada
        valor en la matriz "obligatorio"; la cadena que llega es así: "campo_n!1". 1 es obligatorio y 0, no. 
        Y finalmente, "form" es el nombre del formulario.
        */
        var obligatorio=new Array();
        obligatorio=campo.split("!");
        switch (tipo) {
                case 1:
                //numero
                        if (isNaN(eval("document."+form+"."+obligatorio[0]+".value"))) {
                                equivoc=1;
                                msje+="· El campo '"+obligatorio[0]+"' debe ser un número.\n";
                        }
                        if ( ((eval("document."+form+"."+obligatorio[0]+".value"))=="") && (obligatorio[1]==1) ) {
                                equivoc=1;
                                msje+="· El campo '"+obligatorio[0]+"' es obligatorio.\n";
                        }
                break;
                case 21:
                //numero DNI; quito la validacion de numero
                        /*if (isNaN(eval("document."+form+"."+obligatorio[0]+".value"))) {
                                equivoc=1;
                                msje+="· El campo '"+obligatorio[0]+"' debe ser un número.\n";
                        }*/
                        if ( ((eval("document."+form+"."+obligatorio[0]+".value"))=="") && (obligatorio[1]==1) ) {
                                equivoc=1;
                                msje+="· El campo '"+obligatorio[0]+"' es obligatorio.\n";
                        }
                break;
                case 4:
                //fecha corta
                        if ( ((eval("document."+form+"."+obligatorio[0]+".value"))=="") && (obligatorio[1]==1) ) {
                                equivoc=1;
                                msje+="· El campo '"+obligatorio[0]+"' es obligatorio.\n";
                        }
                break;
                case 20:
                //correo
                if (obligatorio[1]==1) {
                        emilio("'"+(eval("document."+form+"."+obligatorio[0]+".value"))+"'","'"+obligatorio[0]+"'");
                }else if ((eval("document."+form+"."+obligatorio[0]+".value"))!=""){
                        emilio("'"+(eval("document."+form+"."+obligatorio[0]+".value"))+"'","'"+obligatorio[0]+"'");
                }
                break;
                case 12:
                //editor
                break;

                default:
                //texto
                        if ( ((eval("document."+form+"."+obligatorio[0]+".value"))=="") && (obligatorio[1]==1) ) {
                                equivoc=1;
                                msje+="· El campo '"+obligatorio[0]+"' es obligatorio.\n";
                        }
        }
}
/*ejempo de cadena:
validar('Idestado_civil!0|10#numero_hijos!0|1#f_nac!1|4#email!0|20#email2!0|20#Idlugar_nacimiento!0|10#','formulario')
*/
function validar(valor,nombreform){

        var matriz_obligatorios=new Array();
        matriz_obligatorios=valor.split("#");
        var longitud=(matriz_obligatorios.length)-1;
        var matriztipo=new Array(2);
        var matrizcampos=new Array();
        
        for (i=0;i<longitud;i++){
                matriztipo=matriz_obligatorios[i].split("|");
                matrizcampos[i]=matriztipo;
        }
        
        for (i=0;i<longitud;i++){
                eval("checkeacampo("+matrizcampos[i][1]+",'"+matrizcampos[i][0]+"','"+nombreform+"')");
        }
        
        if (equivoc==0){
                eval("document."+nombreform+".submit()");
        }else{
                alert(msje);
                equivoc=0;
                msje="Por favor, revise los errores en los siguientes campos:\n\n";
        }
}

letras = new Array("T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E");
function calculonif() {
                cad = new String(document.formulario.dni.value);
                while(cad.substring(0,1)=="0" && cad.length>1){
                                                                  cad=cad.substring(1,cad.length);}
                indice=(document.formulario.dni.value)-(parseInt(cad/23)*23); 
                if (isNaN(document.formulario.dni.value)){
                                document.formulario.nif.value="";
                }else{
                                document.formulario.nif.value=letras[indice];
                }
}

function cambiarImagen(enlace,imagen){
        enlace.setAttribute('src',imagen);
        
}

function abrir(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function ConfirmarBorrado(direccion,titular){
        if (confirm(titular)){
                window.location = direccion;
        }        
}

function ConfirmarPop(titular,direccion,propiedades){
        if (confirm(titular)){
                abrir(direccion,'',propiedades);
        }        
}

function casilla(campo,id,url,formulario,idcambio,valor){
        document.location.href=url+"&id_registro="+id+"&campo="+campo+"&valor="+valor+"&idcambio="+idcambio;
}

function combo(formulario,id,nombrecampo,url,campoweb){
        aux_valorcambio=eval('document.'+formulario+'.'+nombrecampo+'.value');
        document.location.href=url+"&id_registro="+id+"&campo="+campoweb+"&valor="+aux_valorcambio;
}

anterior="";
function mostrar(id){
        //Anulado por la reunion &&(anterior!="subm_4")&&(anterior!="subm_7")
        if (((anterior!="")||(anterior==id))) {
                var queoculto=anterior+'.style.display="none"';
                eval(queoculto);
        }
        if ((id!='subm_0')&&(anterior!=id)&&(id!='subm_26')&&(id!='subm_27')){
                var quemuestro=id+'.style.display="inline"';
                eval(quemuestro);
                anterior=id;
        }else{
                anterior="";
        }
}

function busqueda(){
        /*var aux_termino=document.formul1.buscar.value;
                if (document.formul1.n_col.value=="1001"){*/
                        document.formul1.submit();
                /*}else{
                alert(aux_termino);
                }*/
}

function salto(formulario){
        eval("document."+formulario+".submit()");
}

function numero(formulario,nombrecampo){
        if (isNaN(eval("document."+formulario+"."+nombrecampo+".value"))){
                eval(("document."+formulario+"."+nombrecampo+".value=''"));
        }
}
function Google_Search(valor){
        /*
        <input type="text" name="w" size="15">
        <a href="javascript:Google_Search(document.forma)">Buscar en Google</a>
        */
  if(valor!=""){
        window.location="http://www.google.com/custom?q=" + valor + "&cof=L:http://www.coev.com/imagenes/nuevo_disenyo/logocab.gif;AH:center;AWFID:4200e643e223eac5;&safe=vss&vss=1&sa=Search&sitesearch=&domains=www.coev.com";
    //window.location="http://www.google.com/custom?q=" + inForm.w.value + "&cof=LW:228;L:http://www.coev.com/imagenes/logo.gif;LH:50;AH:center;AWFID:4200e643e223eac5;&safe=vss&vss=1&sa=Search&sitesearch=&domains=www.coev.com";
  }else{
    void(0);
  }
}
function denegar(tabla,id,idregop){
        if(confirm("Está seguro de denegar la presente solicitud?")){
                document.location.href="denegar.php?tabla="+tabla+"&id="+id+"&idregop="+idregop;
        }
        
}
function validarRDE(formulario) {
  if ((formulario.emailRDE.value.indexOf ('@', 0) == -1)||(formulario.emailRDE.value.length < 5)) {
    alert("Escriba una dirección de correo válida en el campo E-mail");
    return (false);
  }
  if (formulario.telefonoRDE.value.length < 9) {
    alert("El teléfono debe tener almenos 9 dígitos");
    formulario.telefonoRDE.focus();
    return (false);
  }
  var checkOK = "0123456789";
  var checkStr = formulario.telefonoRDE.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) {
    alert("Escriba sólo dígitos en el teléfono");
    formulario.telefonoRDE.focus();
    return (false);
  }
  
  
  return (true);
}

function nuevoAjax()
{ 
	/* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, por
	lo que se puede copiar tal como esta aqui */
	var xmlhttp=false; 
	try 
	{ 
		// Creacion del objeto AJAX para navegadores no IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
	}
	catch(e)
	{ 
		try
		{ 
			// Creacion del objet AJAX para IE 
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
		} 
		catch(E) { xmlhttp=false; }
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp=new XMLHttpRequest(); } 

	return xmlhttp; 
} 
function cargarContenido(url_redir, nombre_div){
	var contenedor;
	var ajax;
	contenedor = document.getElementById(nombre_div);
	ajax=nuevoAjax();
	ajax.open("GET", url_redir, true);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==1) {
//			document.getElementById("preload").style.display='';
        	//contenedor.innerHTML="<table width='100%' height='300' border='0' cellspacing='0' cellpadding='0'><tr><td><center><img src='../img/preload.gif'> Cargando...</center></td></tr></table>";
        }else if (ajax.readyState==4) {
//			document.getElementById("preload").style.display='none';
			contenedor.innerHTML = ajax.responseText;
		}
	}
	ajax.send(null);
}
function cargarContenidoRefresh(url_redir, nombre_div, url_refresh){
	var contenedor;
	var ajax;
	contenedor = document.getElementById(nombre_div);
	ajax=nuevoAjax();
	ajax.open("GET", url_redir, true);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==1) {
			document.getElementById("preload").style.display='';
        	//contenedor.innerHTML="<table width='100%' height='300' border='0' cellspacing='0' cellpadding='0'><tr><td><center><img src='../img/preload.gif'> Cargando...</center></td></tr></table>";
        }else if (ajax.readyState==4) {
//			document.getElementById("preload").style.display='none';
			contenedor.innerHTML = ajax.responseText;
			cargarContenido(url_refresh,'contenidos');
		}
	}
	ajax.send(null);
}
function cargarContenidoPost(url_redir, nombre_div, vars){
	var contenedor;
	var ajax;
	contenedor = document.getElementById(nombre_div);
	ajax=nuevoAjax();
	ajax.open("POST", url_redir, true);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==1) {
//			document.getElementById("preload").style.display='';
        	//contenedor.innerHTML="<table width='100%' height='300' border='0' cellspacing='0' cellpadding='0'><tr><td><center><img src='../img/preload.gif'> Cargando...</center></td></tr></table>";
        }else if (ajax.readyState==4) {
//			document.getElementById("preload").style.display='none';
			contenedor.innerHTML = ajax.responseText;
		}
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send(vars);
	return true;
}

function cargarContenidoPostArchivo(url_redir, nombre_div, vars){
	var contenedor;
	var ajax;
	contenedor = document.getElementById(nombre_div);
	ajax=nuevoAjax();
	ajax.open("POST", url_redir, true);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==1) {
//			document.getElementById("preload").style.display='';
        	//contenedor.innerHTML="<table width='100%' height='300' border='0' cellspacing='0' cellpadding='0'><tr><td><center><img src='../img/preload.gif'> Cargando...</center></td></tr></table>";
        }else if (ajax.readyState==4) {
//			document.getElementById("preload").style.display='none';
			contenedor.innerHTML = ajax.responseText;
		}
	}
	ajax.setRequestHeader("Content-Type", "multipart/form-data");
	ajax.send(vars);
	return true;
}
//Lo mismo pero sin ocultar el loading
function cargarContenidoPost2(url_redir, nombre_div, vars){
	var contenedor;
	var ajax;
	contenedor = document.getElementById(nombre_div);
	ajax=nuevoAjax();
	ajax.open("POST", url_redir, true);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==1) {
			document.getElementById("preload").style.display='';
        	//contenedor.innerHTML="<table width='100%' height='300' border='0' cellspacing='0' cellpadding='0'><tr><td><center><img src='../img/preload.gif'> Cargando...</center></td></tr></table>";
        }else if (ajax.readyState==4) {
//			document.getElementById("preload").style.display='none';
			contenedor.innerHTML = ajax.responseText;
		}
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send(vars);
	return true;
}

