EXTRAS = {
	addEvent : function(obj, evType, fn, useCapture){
		if (obj.addEventListener){
			obj.addEventListener(evType, fn, useCapture);
			return true;
		} 
		else if (obj.attachEvent){
			var r = obj.attachEvent("on"+evType, fn);
			return r;
		} 
		else {
			return false;
		}
	},	
	getElementsByClass : function(className,node) {
		if(!node) node=document;
		var refTags = document.all ? node.all : node.getElementsByTagName("*");
		var retVal = new Array();
		for(var z=0;z<refTags.length;z++) {
			if(refTags[z].className == className) 
			retVal.push(refTags[z]);
		}
		return retVal; 
	}
}


/**
*FUNCIONES JAVASCRIPT PARA VALIDAR FECHAS EN FORMATO dd/mm/aaaa
*/
esdigito = function(schr) {
    var scod = schr.charCodeAt(0);
    return ((scod > 47) && (scod < 58));
}

valsep = function(otxt) {
    var bok = false;
    bok = bok || ((otxt.value.charAt(2) == "/") && (otxt.value.charAt(5) == "/"));
    return bok;
}

finmes = function(otxt) {
    var nmes = parseInt(otxt.value.substr(3, 2), 10);
    var nres = 0;
    switch (nmes){
        case 1: nres = 31; break;
        case 2: nres = 29; break;
        case 3: nres = 31; break;
        case 4: nres = 30; break;
        case 5: nres = 31; break;
        case 6: nres = 30; break;
        case 7: nres = 31; break;
        case 8: nres = 31; break;
        case 9: nres = 30; break;
        case 10: nres = 31; break;
        case 11: nres = 30; break;
        case 12: nres = 31; break;
    }
    return nres;
}

valdia = function(otxt){
    var bok = false;
    var ndia = parseInt(otxt.value.substr(0, 2), 10);
    bok = bok || ((ndia >= 1) && (ndia <= finmes(otxt)));
    return bok;
}

valmes = function(otxt){
    var bok = false;
    var nmes = parseInt(otxt.value.substr(3, 2), 10);
    bok = bok || ((nmes >= 1) && (nmes <= 12));
    return bok;
}

valano = function(otxt){
    var bok = true;
    var nano = otxt.value.substr(6);
    bok = bok && (nano.length == 4);
    if (bok){
        for (var i = 0; i < nano.length; i++){
            bok = bok && esdigito(nano.charAt(i));
        }
    }
    return bok;
}

valfecha = function(otxt){
    var bok = true;
    if (otxt.value != ""){
        bok = bok && (valano(otxt));
        bok = bok && (valmes(otxt));
        bok = bok && (valdia(otxt));
        bok = bok && (valsep(otxt));
        if (!bok){
            alert("Formato de fecha inválido.\nFormato correcto (dd/mm/aaaa)");
            otxt.value = "";
            otxt.focus();
        }
    }
}

fechaMayorIgual = function(fec0, fec1) {
    var bRes = false;
    var sDia0 = fec0.substr(0, 2);
    var sMes0 = fec0.substr(3, 2);
    var sAno0 = fec0.substr(6, 4);
    var sDia1 = fec1.substr(0, 2);
    var sMes1 = fec1.substr(3, 2);
    var sAno1 = fec1.substr(6, 4);
    if (sAno0 > sAno1) {
        bRes = true;
    } else {
        if (sAno0 == sAno1) {
            if (sMes0 > sMes1) {
                bRes = true;
            } else {
                if (sMes0 == sMes1) {
                    if (sDia0 >= sDia1) {
                        bRes = true;
                    }
                }
            }
        }
    }
    return bRes;
}

fechaMenorIgual = function(fec0, fec1) {
    var bRes = false;
    var sDia0 = fec0.substr(0, 2);
    var sMes0 = fec0.substr(3, 2);
    var sAno0 = fec0.substr(6, 4);
    var sDia1 = fec1.substr(0, 2);
    var sMes1 = fec1.substr(3, 2);
    var sAno1 = fec1.substr(6, 4);
    if (sAno0 < sAno1) {
        bRes = true;
    } else {
        if (sAno0 == sAno1) {
            if (sMes0 < sMes1) {
                bRes = true;
            } else {
                if (sMes0 == sMes1) {
                    if (sDia0 <= sDia1) {
                        bRes = true;
                    }
                }
            }
        }
    }
    return bRes;
}
/**
*FIN FUNCIONES JAVASCRIPT PARA VALIDAR FECHAS EN FORMATO dd/mm/aaaa
*/

ValidacionForm = function(){
    var form = document.getElementById("formValidaDatos");
    if (form != null) {
        for(var i = 0; i < form.length; i++) {
                EXTRAS.addEvent(form[i],'blur',accionarValidacionForm,false);
        }    
    }
}

accionarValidacionForm = function(){
  var form = document.getElementById("formValidaDatos");
  if(form.codigocliente){
   if(form.codigocliente.value != '') {
       if (isNaN(form.codigocliente.value)){
            alert("Debe insertar un valor numérico para el Código");
            //form.codigocliente.value="";
            form.codigocliente.focus();
            return false;
        } 
    }
 }
  
 if(form.dnicliente){
   if (form.dnicliente.value != '') {
      if(!ValidaDni(form.dnicliente.value)){
            alert("Debe insertar un DNI válido");
            //form.dnicliente.value="";
            form.dnicliente.focus();
            return false;
      }
    }
 }
  if(form.telefonocliente){
   if(form.telefonocliente.value != ''){
        form.telefonocliente.value = form.telefonocliente.value.split(' ').join('');
        if (isNaN(form.telefonocliente.value) || (form.telefonocliente.value.length < 9)){
            alert("Debe insertar un valor válido para el Teléfono.\nDebe tener al menos 9 dígitos ");
            //form.telefonocliente.value="";
            form.telefonocliente.focus();
            return false;
        }
    }
 }
  if(form.emailcliente){
   if(form.emailcliente.value !=''){
         if(!ValidaEmail(form.emailcliente.value)){
            alert("Dirección de email incorrecta.");
            //form.emailcliente.value="";
            form.emailcliente.focus();
            return false;
           }
        }
  }
    return true;
}


/**
**FUNCIÓN VALIDA DNI
**/
ValidaDni = function(valor){
    var temp=valor.toUpperCase();
	var cadenadni="TRWAGMYFPDXBNJZSQVHLCKE";
	if (temp!==''){
		//si no tiene un formato valido devuelve error
		if ((!/^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$/.test(temp) && !/^[T]{1}[A-Z0-9]{8}$/.test(temp)) && !/^[0-9]{8}[A-Z]{1}$/.test(temp)){
			return false;
		}
		//comprobacion de NIFs estandar
		if (/^[0-9]{8}[A-Z]{1}$/.test(temp)) {
			posicion = valor.substring(8,0) % 23;
			letra = cadenadni.charAt(posicion);
			var letradni=temp.charAt(8);
			if (letra == letradni) {
			   	return true;
			} else {
				return false;
			}
		}
 		//algoritmo para comprobacion de codigos tipo CIF
		suma = parseInt(valor[2])+parseInt(valor[4])+parseInt(valor[6]);
		for (i = 1; i < 8; i += 2) {
			temp1 = 2 * parseInt(valor[i]);
			temp1 += '';
			temp1 = temp1.substring(0,1);
			temp2 = 2 * parseInt(valor[i]);
			temp2 += '';
			temp2 = temp2.substring(1,2);
			if (temp2 == '') {
				temp2 = '0';
			}
			suma += (parseInt(temp1) + parseInt(temp2));
		}
		suma += '';
		n = 10 - parseInt(suma.substring(suma.length-1, suma.length));
		//comprobacion de NIFs especiales (se calculan como CIFs)
		if (/^[KLM]{1}/.test(temp)) {
			if (valor[8] == String.fromCharCode(64 + n)) {
				return true;
			} else {
				return false;
			}
		}
		//comprobacion de CIFs
		if (/^[ABCDEFGHJNPQRSUVW]{1}/.test(temp)) {
			temp = n + '';
			if (valor[8] == String.fromCharCode(64 + n) || valor[8] == parseInt(temp.substring(temp.length-1, temp.length))) {
				return true;
			} else {
				return false;
			}
		}
		//comprobacion de NIEs
		//T
		if (/^[T]{1}/.test(temp)) {
			if (valor[8] == /^[T]{1}[A-Z0-9]{8}$/.test(temp)) {
				return true;
			} else {
				return false;
			}
		}
		//XYZ
		if (/^[XYZ]{1}/.test(temp)) {
			pos = str_replace(['X', 'Y', 'Z'], ['0','1','2'], temp).substring(0, 8) % 23;
			if (valor[8] == cadenadni.substring(pos, pos + 1)) {
				return true;
			} else {
				return false;
			}
		}
	}
	return false;
}

function str_replace(search, replace, subject) {
    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };
    return sa ? s : s[0];
}

/**
**FUNCION VALIDA EMAIL
**/
ValidaEmail = function(valor){
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor))
      return true;
    else 
      return false;
}   

enviarDatosCeca = function() {
    try {
        var formularioCeca = document.getElementById("formularioCeca");
        if(formularioCeca != null) {
            formularioCeca.submit();
        }
    } catch (exception) {
        return true;
    }
}

cambiaDisplay = function (obj){
        try {
            var objetoEstilo = document.getElementById(obj);
            if(objetoEstilo!=null){
                 if (document.getElementById(obj).style.display == 'none'){
                        document.getElementById(obj).style.display = 'block';
                    } else {
                        document.getElementById(obj).style.display = 'none';
                    }
                }
                return true;
        }catch (exception) {
                return false;
            }
}
init=function() {
    ValidacionForm();
    enviarDatosCeca();
    cambiaDisplay('enlacesdet');
}

EXTRAS.addEvent(window, 'load', init, false);

