function CerrarSesion(){
   lResp= window.confirm('¿Desea cerrar su sesión?');
   if (lResp != true){
      return;
   }	
   window.open("CerrarSesion.php","_blank","directories=no,height=1,width=1,location=no,menubar=no,resizable=yes,toolbar=no,scrollbars=yes,status=yes,top=0,left=2000");
}

function MostrarAyuda(pRutaAyuda,pPagina){
       lLeft = screen.Width - 260;
       lURL = pRutaAyuda + pPagina + ".htm";
       window.open(lURL,'vf', 'width=250 height=500 top=25 left=' + lLeft + 'toolbar=0, scrollbars=1, location=0, status=0, resizable=0, menubar=0');
}


function ValidarFecha(Cadena){
	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 el año
	if (isNaN(Ano) || Ano.length<4 || parseFloat(Ano)<1900){
        	alert('Revise la fecha:Año inválido')
		return false
	}
	// Valido el Mes
	if (isNaN(Mes) || parseFloat(Mes)<1 || parseFloat(Mes)>12){
		alert('Revise la fecha:Mes inválido')
		return false
	}
	// Valido el Dia
	if (isNaN(Dia) || parseInt(Dia)<1 || parseInt(Dia)>31){
		alert('Revise la fecha:Día inválido')
		return false
	}
	if (Mes==4 || Mes==6 || Mes==9 || Mes==11 || Mes==2) {
		if (Mes==2 && Dia > 28 || Dia>30) {
			alert('Revise la fecha:Día inválido')
			return false
		}
	}
	
  //para que envie los datos, quitar las  2 lineas siguientes
  //alert("Fecha correcta.")
  return true	
}

function SoloNumero()
{
	if(event.keyCode<48 || event.keyCode>57){        // Deja escribir números (0-9)
		event.keyCode=0;
	}
}

function SoloNumeroyLetras()
{
//	alert("event.keyCode es: "+event.keyCode);
	if((event.keyCode<48 || event.keyCode>57) && (event.keyCode<65 || event.keyCode>90) && (event.keyCode<97 || event.keyCode>122)){        // Deja escribir números (0-9) y letras (A-Z) (a-z)
		event.keyCode=0;
	}
}

function ValidarDocIdentificacion(pTipo,pValor){
	if (pValor==""){
		return false
	}
	if (pTipo=="0"){
		return ValidarDNI(pValor);
	}else{
		if (pTipo=="1"){			
			return ValidarCIF(pValor);
		}else{
			if(pTipo=="2"){
				return true;
			}else{
				alert("El tipo de documento de identificación debe estar informado.");
				return false;
			}
		}
	}		
}

function ValidarCIF(texto){    
	try{      
		var pares = 0; 
		var impares = 0; 
		var suma; 
		var ultima; 
		var unumero; 
		var uletra = new Array("J", "A", "B", "C", "D", "E", "F", "G", "H", "I"); 
		var xxx; 
		 
		texto = texto.toUpperCase(); 
		 
		var regular =/^[ABCDEFGHKLMNPQS]\d\d\d\d\d\d\d[0-9,A-J]$/g; 
		 if (!regular.exec(texto)) {
			alert("El C.I.F. es incorrecto"); 
			return false; 
		}
			  
		 ultima = texto.substr(8,1); 
	
		 for (var cont = 1 ; cont < 7 ; cont ++){ 
			 xxx = (2 * parseInt(texto.substr(cont++,1))).toString() + "0"; 
			 impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1)); 
			 pares += parseInt(texto.substr(cont,1)); 
		 } 
		 xxx = (2 * parseInt(texto.substr(cont,1))).toString() + "0"; 
		 impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1)); 
		  
		 suma = (pares + impares).toString(); 
		 unumero = parseInt(suma.substr(suma.length - 1, 1)); 
		 unumero = (10 - unumero).toString(); 
		 if(unumero == 10) unumero = 0; 
		  
		 if ((ultima == unumero) || (ultima == uletra[unumero])) {
			 return true; 
		 }else{
			 alert("El C.I.F. es incorrecto"); 
			 return false;
		 }
	}catch(e){
		alert("Error en el ValidarCIF");			
	}
} 
	
function ValidarDNI (pDNI) 
{
	var pNum, pLetra, cadena, posicion, letra

	if(pDNI.length!=9) {
		alert("El D.N.I. es incorrecto.")
		return false
	}
	
	pNum = pDNI.substring(0,8)
	pLetra = pDNI.substring(8,9)
	pLetra = pLetra.toUpperCase();

	cadena="TRWAGMYFPDXBNJZSQVHLCKET"
	posicion = parseFloat(pDNI) % 23
	letra = cadena.substring(posicion,posicion+1)

	if(letra != pLetra){
		alert("El D.N.I. es incorrecto.")
		return false
	}else{
		return true
	}
} 


function ValidarEmail(emailStr) {
	/* The following pattern is used to check if the entered e-mail address fits the user@domain format.  It also is used to separate the username from the domain. */
	var emailPat=/^(.+)@(.+)$/
	/* The following string represents the pattern for matching all special characters.  We don't want to allow special characters in the address. These characters include ( ) < > @ , ; : \ " . [ ]    */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	/* The following string represents the range of characters allowed in a username or domainname.  It really states which chars aren't allowed. */
	var validChars="\[^\\s" + specialChars + "\]"
	/* The following pattern applies if the "user" is a quoted string (in which case, there are no rules about which characters are allowed and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")"
	/* The following pattern applies for domains that are IP addresses, rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	/* The following string represents an atom (basically a series of non-special characters.) */
	var atom=validChars + '+'
	/* The following string represents one word in the typical username. For example, in john.doe@somewhere.com, john and doe are words. Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")"
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	/* The following pattern describes the structure of a normal symbolic domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

	/* Finally, let's start trying to figure out if the supplied address is valid. */

	/* Begin with the coarse pattern to simply break up user@domain into different ??4??pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
		/* Too many/few @'s or something; basically, this address doesn't even fit the general mould of a valid e-mail address. */
		alert("La dirección de email introducida es incorrecta. Verifique si es de la forma: usuario@dominio.com")
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]

	// See if "user" is valid 
	if (user.match(userPat)==null) {
		// user is not valid
		alert("El nombre de usuario en la dirección de email es incorrecto.")
		return false
	}

	/* if the e-mail address is at an IP address (as opposed to a symbolic host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		// this is an IP address
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("Direccion IP no válida en la dirección de email.")
				return false
			}
		}
		return true
	}
	
	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("El nombre de dominio en la dirección de email es incorrecto.")
		return false
	}

	/* domain name seems valid, but now make sure that it ends in a three-letter word (like com, edu, gov) or a two-letter word, representing country (uk, nl), and that there's a hostname preceding the domain or country. */

	/* Now we need to break up the domain to get a count of how many atoms it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
		domArr[domArr.length-1].length>3) {
		// the address must end in a two letter or three letter word.
		alert("La dirección de email debe acabar en 3 letras de dominio o 2 de un país.")
		return false
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
		var errStr="El dominio introducido en la dirección de email es incorrecto."
		alert(errStr)
		return false
	}

	// If we've gotten this far, everything's valid!
	return true
}

function ValidarCodigoPostal(pCP)
{
	if (pCP.length!=5 ) {
		alert("El Código Postal debe ser de 5 dígitos");
		return false;
	}else{
		return true;
	}
}

// Validar CCC
function obtenerDigito(valor){ 
valores = new Array(1, 2, 4, 8, 5, 10, 9, 7, 3, 6); 
control = 0; 
for (i=0; i<=9; i++) control += parseInt(valor.charAt(i)) * valores[i]; control = 11 - (control % 11);
	if (control == 11) 
		control = 0; 
	else if (control == 10) 
		control = 1; 
	return control; 
}


function numerico(valor){ cad = valor.toString(); for (var i=0; i<cad.length; i++) { var caracter = cad.charAt(i); if (caracter<"0" || caracter>"9") return false; } return true; }

function validarCCC(f) { 
	try{
		if (f.CodigoBanco.value == "" || f.CodigoAgencia.value == "" || f.DC.value == "" || f.CCC.value == ""){ 
			alert("Por favor, introduzca los datos de su cuenta"); 
			return false
		}else { 
			if (f.CodigoBanco.value.length != 4 || f.CodigoAgencia.value.length != 4 || f.DC.value.length != 2 || f.CCC.value.length != 10) {
				alert("Por favor, introduzca correctamente los datos de su cuenta, no están completos"); 
				return false
			}else { 
				if (!numerico(f.CodigoBanco.value) || !numerico(f.CodigoAgencia.value) || !numerico(f.DC.value) || !numerico(f.CCC.value)) {
					alert("Por favor, introduzca correctamente los datos de su cuenta, no son numericos"); 
					return false
				}else { 
					if (!(obtenerDigito("00" + f.CodigoBanco.value + f.CodigoAgencia.value) == parseInt(f.DC.value.charAt(0))) || !(obtenerDigito(f.CCC.value) == parseInt(f.DC.value.charAt(1)))) {
						alert("Los dígitos de control no se corresponden con los demás" + " números de la cuenta"); 
						return false
					}else{ 
						//alert ("CCC correcto"); 
						return true
					}
				} 
			} 		
		} 
	}catch(e){
		alert("Error en el validarCCC")
		return false
	}		
}
function CambiaClase(vObjeto, vClase){
//alert("la clase que pongo es: "+vClase);
	vObjeto.className = vClase 
}
function Abre(nombre){
		ancho = (780)
		alto = (500)
		mgtop = ((screen.height / 2) - (alto/2))-10
		mgleft = (screen.width / 2) - (ancho/2)
		
		window.open(nombre,'_blank','width='+ancho+',height='+alto+',top='+mgtop+',left='+mgleft+',scrollbars=yes,status=no,resizable=yes');
}
function cierra(){

	window.close()
}

function MaxLenghtTexArea(pValor,pLimite)
{
	if ((pValor.length)>=pLimite)
	{
		event.keyCode=0;
	}
}
