﻿/********************************************
	Funciones Generales de formularios 
*********************************************/
/*	ComprobarFormulario
		Funcion general que valida cualquier formulario con el formato correcto */
function VerificarFormulario (formulario, sender) {
	var caso = 0, error = false, elementos, regex, verificacion, type;
	var cases = new Array ( "", "", "VerificarCajaTexto", 1, "VerificarCajaTextoNumero", "", "VerificarCajaTextoMail", "", "VerificarCajaTextoWeb", "", "VerificarCajaTextoDNINIE", "1",  "VerificarCajaTextoRegexp", "^6\\d{8}$#6xxxxxxx", "VerificarCajaTextoRegexp", "^[89][1-9]\\d{7}$#9xxxxxxxx/8xxxxxxxx", "VerificarSeleccionNumero", -1, "VerificarCajaTextoCIF", "", "VerificarCajaTextoCP", 5, "VerificarCajaTextoFecha", "", "VerificarRadioNumero", "", "VerificarCajaTextoCCC", "" );
	error = (!error&&typeof(formulariosfin)=='boolean'&&typeof(formulariosgenfin)=='boolean'&&typeof(formulariosmsgsfin)=='boolean')?false:error;
	regex = (!error)?getNameRegExp (formulario, sender):null;
	for (k=0;(!error)&&(k<formulario.elements.length);k++) {
		if (!regex.test(formulario.elements[k].name) || (typeof (formulario.elements[k].disabled) == 'boolean') && formulario.elements[k].disabled ) {
			continue;
		}
		elementos = regex.exec (formulario.elements[k].name);
		caso = parseFloat(elementos[1]);
		type = Math.ceil(caso/2)*2;
		if (type>0&&type<cases.length) {
			verificacion = eval (cases[type]);
			error = (typeof (verificacion) == 'function' )?!verificacion (formulario.elements[k], cases[type+1], caso%2):true;
		}
	}
	return !error;
}
function getNameRegExp ( formulario, scope ) {
	scope = (scope!=null&&scope.length>0&&(scope.lastIndexOf(':')>0||scope.lastIndexOf('$')>0))?scope.replace(/\$/g,'\\$'):".*";
	return new RegExp (((typeof(formulario.lang)=='object'&&formulario.lang.type=='hidden')?"^"+scope+"[:\\$](?:[^:\\$]+[:\\$])*[n|t]{0,1}_(\\d{2})\\d{2}(\\d{2})_([a-z][a-z_0-9]{0,}[a-z0-9])$":"^[n|t]_(\\d{2})\\d{2}_([a-z_]+)$"));
}
/*	TextoMensaje
		Recibe el objeto campo de formulario, y a partir del nombre
		intenta encontrar el mensaje descriptivo */
function AlertaTextoMensaje ( campo, tipoerror, sustituciones, msg ) {
	var mensaje = "", lang = 'es', nombresCampos = new Array (), numeromensaje = -1, nombreCampo="", tipoCampo = -1;
	var scope = "";
	if ( campo.name!=null&&campo.name.length>0 ) {
		if ( campo.name.lastIndexOf(':')>0 ) {
			scope = campo.name.substring(0, campo.name.lastIndexOf(':')).replace(/:/g,'_');
		} else if ( campo.name.lastIndexOf('$')>0 ) {
			scope = campo.name.substring(0, campo.name.lastIndexOf('$')).replace(/\$/g,'_');
		}
	}
	var regex = getNameRegExp (campo.form, scope);
	var elementos = regex.exec (campo.name);
	if ( elementos!=null && ( elementos.length == 4 || elementos.length == 3 ) ) {
		tipoCampo = parseFloat(elementos[1]);
		tipoCampo = tipoCampo + (tipoCampo%2);
		numeromensaje = (elementos.length==4)?elementos[2]:-1;
		nombreCampo = (elementos.length==4)?elementos[3]:elementos[2];
		elementos = null;
	}
	if ( typeof (campo.form.lang) == 'object' && campo.form.lang.type=='hidden' ) {
		if ( campo.form.lang.value.length>0 )
			lang = campo.form.lang.value;
		if ( typeof(formulariosmsgsfin)=='boolean' )
			nombresCampos = eval(campo.form.id + scope + "Campos");
		if ( typeof (nombresCampos) == 'function' )
			nombresCampos = nombresCampos("N");
	}
	if ( parseFloat(numeromensaje)>0 && parseFloat(numeromensaje)<nombresCampos.length ) {
		nombreCampo=nombresCampos[parseFloat(numeromensaje)];
		nombreCampo=nombreCampo.replace(/<[^>]+>/g, '');
	}
	if ( typeof (msg) == 'string' )
		mensaje = msg;
	// tipoerror, tipoCampo, texto
	var mensajesGenerales = (typeof (mensajesGeneralesFormulariosGen)=='function')?mensajesGeneralesFormulariosGen():msgsGenerales('G');
	if ( mensaje.length==0 && tipoerror>=0 ) {
		if ( typeof (sustituciones) == 'object' && sustituciones!=null ) {
			// Busco el mensaje para este tipo de campo y este tipo de error
			for ( var z = 0; z<mensajesGenerales.length/4; z++) {
				if ( mensajesGenerales[z*4]==tipoerror && mensajesGenerales[z*4+1]==tipoCampo && mensajesGenerales[z*4+2]==lang) {
					mensaje = mensajesGenerales[z*4+3];
					break;
				}
			}
			if (mensaje.length == 0 ) {
				// Busco el mensaje general para este tipo de error
				for ( var z = 0; z<mensajesGenerales.length/4; z++) {
					if ( mensajesGenerales[z*4]==tipoerror && mensajesGenerales[z*4+1]==0 && mensajesGenerales[z*4+2]==lang ) {
						mensaje = mensajesGenerales[z*4+3];
						break;
					}
				}
			}
		} else {
			// Busco el mensaje especifico de este tipo
			var mensajes = eval(campo.form.id + scope + "Campos");
			if ( typeof (mensajes) == 'function' ) {
				mensajes = mensajes("F");
				mensaje = (typeof(mensajes[tipoerror])=='string')?mensajes[tipoerror]:mensaje;
			}
		}
	}
	if (mensaje.length > 0 ) {
		if ( typeof (sustituciones) == 'object' && sustituciones!=null ) {
			for ( var z = 0; z<sustituciones.length; z++)
				mensaje=mensaje.replace(/\(t\)/, sustituciones[z]);
		}
		//	Sustituyo lo que falta
		mensaje=mensaje.replace(/\=campo\=/g, nombreCampo);
	}
	if ( campo.type == 'text' || campo.type == 'textarea' || campo.type == 'select-one' || campo.type == 'password' || campo.type == 'radio' ) {
		campo.focus();
		if ( campo.type != 'select-one' )
			campo.select();
	}
	if ( mensaje.length>0 )
		window.alert (mensaje);
}
/***************************************************
 *	Funciones utilizadas en la verificación general
 *	Por orden alfabético.
 *	Todas comienzan por "Verificar"
*****************************************************/
/*	VerificarCajaTexto
		Verifica que una caja de texto tenga al menos 'param' caracteres */
function VerificarCajaTexto ( elemento, param, req ) {
	var sustituciones = new Array (), tipoerror = 0;
	elemento.value=elemento.value.replace(/\s+$/g,'');
	elemento.value=elemento.value.replace(/^\s+/g,'');
	if ( (req && (elemento.value.length<param) ) || (elemento.value.length>0) && (elemento.value.length<param) ) {
		tipoerror = 1;
		if ( param > 1 ) {
			sustituciones [0] = param;
			tipoerror = 2;
		}
		AlertaTextoMensaje ( elemento, tipoerror, sustituciones );
		return false;
	}
	return true;
}
/*	VerificarCajaTextoCCC
		Verifica que una caja de texto tenga una CCC valido */
function VerificarCajaTextoCCC ( elemento, param, req ) {
	var sustituciones = new Array (), tipoerror = 0;
	if ( !VerificarCajaTexto (elemento, 20, req ) )
		return false;
	if ( !VerificarCajaTextoNumero (elemento, '', req ) )
		return false;
	if ( !compruebaCCC (elemento.value) ) {
		tipoerror = 12;
		AlertaTextoMensaje ( elemento, tipoerror, sustituciones );
		return false;
	}
	return true;
}
/*	VerificarCajaTextoCIF
		Verifica que una caja de texto tenga una CIF valido */
function VerificarCajaTextoCIF ( elemento, param, req ) {
	var sustituciones = new Array (), tipoerror = 0;
	if ( !VerificarCajaTexto (elemento, 9, req ) )
		return false;
	if ( !req && (elemento.value.length==0) )
		return true;
	if ( !compruebaCIF (elemento.value) ) {
		tipoerror = 3;
		AlertaTextoMensaje ( elemento, tipoerror, sustituciones );
		return false;
	}
	return true;
}
function VerificarCajaTextoCP ( elemento, param, req ) {
	elemento.value = (elemento.value.length>0)?elemento.value.replace(/[^\d]/g, ''):elemento.value;
	return VerificarCajaTextoNumero(elemento, param, req);
}
/*
	VerificarCajaTextoDNINIE
		Verifica que una caja de texto tenga una DNI o un NIE valido
*/
function VerificarCajaTextoDNINIE ( elemento, param, req ) {
	var sustituciones = new Array (), tipoerror = 0;
	if ( !VerificarCajaTexto (elemento, 9, req ) )
		return false;
	if ( !req && (elemento.value.length==0) )
		return true;
	elemento.value = elemento.value.toUpperCase();
	if ( ( param == 1 && !compruebaNIF (elemento.value) ) || ( param == 3 && !compruebaNIE (elemento.value) ) ) {
		tipoerror = 4;
		sustituciones[0] = ((param==1)?"N.I.F.":"N.I.E.");
		AlertaTextoMensaje ( elemento, tipoerror, sustituciones );
		return false;
	}
	return true;
}
/*	VerificarCajaTextoFecha
		Verifica que una fecha */
function VerificarCajaTextoFecha ( elemento, param, req ) {
	var sustituciones = new Array (), tipoerror = 0;
	if ( !VerificarCajaTexto (elemento, 8, req ) )
		return false;
	if ( !req && (elemento.value.length==0) )
		return true;
	var resultado = compruebaFechaSimple (elemento.value, '%d/%m/%yyyy');
	if ( typeof(resultado)=="object" ) {
		tipoerror = 11;
		var error = resultado[resultado.length-1];
		compruebaFechaerrMsgs = (typeof (mensajesGeneralesCompruebaFecha)=='function')?mensajesGeneralesCompruebaFecha():msgsGenerales('F');
		if ( typeof (compruebaFechaerrMsgs) == 'object' ) {
			resultado.length--;
			sustituciones [0] = ": " + compruebaFechaerrMsgs[error];
			sustituciones = sustituciones.concat (resultado);
		} else {
			sustituciones [0] = "";
		}
		AlertaTextoMensaje ( elemento, tipoerror, sustituciones );
		return false;
	}
	return true;
}
/*	VerificarCajaTextoNumero
		Verifica que una caja de texto tenga un numero de 'param' caracteres */
function VerificarCajaTextoNumero ( elemento, param, req ) {
	var sustituciones = new Array (), tipoerror = 0;
	if ( !VerificarCajaTexto (elemento, 1, req ) )
		return false;
	if ( !req && (elemento.value.length==0) )
		return true;
	if ( !isNumber(elemento.value, 1, 1) ) {
		tipoerror = 5;
		AlertaTextoMensaje ( elemento, tipoerror, sustituciones );
		return false;
	}
	if ( isNumber(param, 0, 0) && (elemento.value.length != param)) {
		tipoerror = 6;
		sustituciones [0] = param;
		AlertaTextoMensaje ( elemento, tipoerror, sustituciones );
		return false;
	}
	return true;
}
/*	VerificarCajaTextoMail
	Verifica que una caja de texto tenga un e-mail */
function VerificarCajaTextoMail ( elemento, param, req ) {
	var sustituciones = new Array (), tipoerror = 0;
	if ( !VerificarCajaTexto (elemento, 1, req ) )
		return false;
	if ( !req && (elemento.value.length==0) )
		return true;
	var error = compruebaEmail(elemento.value);
	if ( error>0 ) {
		tipoerror = 7;
		compruebaEmailerrMsgs = (typeof (mensajesGeneralesCompruebaEmail)=='function')?mensajesGeneralesCompruebaEmail():msgsGenerales('E');
		if ( typeof (compruebaEmailerrMsgs) == 'object' ) {
			sustituciones [0] = compruebaEmailerrMsgs[error];
		} else {
			sustituciones [0] = "";
		}
		AlertaTextoMensaje ( elemento, tipoerror, sustituciones );
		return false;
	}
	return true;
}
/*	VerificarCajaTextoRegexp
	Verifica que una caja de texto verifique la expresion regular de 'param' */
function VerificarCajaTextoRegexp ( elemento, param, req ) {
	var sustituciones = new Array (), tipoerror = 0;
	if ( !VerificarCajaTexto (elemento, 1, req ) )
		return false;
	if ( !req && (elemento.value.length==0) )
		return true;
	var regex = new RegExp (param.split('#')[0]);
	if ( !regex.test(elemento.value) ) {
		tipoerror = 8;
		sustituciones [0] = param.split('#')[1];
		AlertaTextoMensaje ( elemento, tipoerror, sustituciones );
		return false;
	}
	return true;	
}
/*	VerificarCajaTextoTelefono ( en desuso)*/
function VerificarCajaTextoTelefono ( elemento, param, req ) {
	return VerificarCajaTextoRegexp(elemento, ((param=='6')?"^6\\d{8}$#6xxxxxxx":"^[89][1-9]\\d{7}$#9xxxxxxxx/8xxxxxxxx"), req);
}
/*	VerificarCajaTextoWeb
	Verifica que una caja de texto tenga una URL valida */
function VerificarCajaTextoWeb ( elemento, param, req ) {
	var sustituciones = new Array (), tipoerror = 0;
	if ( !VerificarCajaTexto (elemento, 1, req ) )
		return false;
	if ( !req && (elemento.value.length==0) )
		return true;
	if (!elemento.value.match(/^http:\/\/[a-zA-z0-9\-_\.]+\.\w{2,4}([\/]{1}[a-zA-z0-9\-_\.%]*)*$/)) {
		tipoerror = 9;
		AlertaTextoMensaje ( elemento, tipoerror, sustituciones );
		return false;
	}
	return true;
}
/*	VerificarRadioNumero
		Verifica que un Radio no tenga seleccionado 'param'
		y que sea un número */
function VerificarRadioNumero ( elemento, param, req ) {
	var sustituciones = new Array (), tipoerror = 0;
	var campo = obtenerRadioCheck ( elemento, elemento.type );
	if (campo == null && req==1) {
		tipoerror = 1;
		AlertaTextoMensaje ( elemento, tipoerror, sustituciones );
		return false;
	} else if  (campo == null ) {
		return true;
	}
	if ( !VerificarCajaTextoNumero (campo, '', req ) ) {
		return false;
	}
	if ( isNumber(param, 0, 0) && (newNumber(campo.value, 1, 1) == param)) {
		tipoerror = 1;
		AlertaTextoMensaje ( campo, tipoerror, sustituciones );
		return false;
	}
	return true;
}
/*	VerificarSeleccionNumero
		Verifica que un desplegable no tenga seleccionado 'param' */
function VerificarSeleccionNumero ( elemento, param, req ) {
	var sustituciones = new Array (), tipoerror = 0;
	if ( typeof (elemento.selectedIndex)=='number' && !(elemento.selectedIndex>0) ) {
		if ( elemento.options.length>0 )
			elemento.selectedIndex=0;
		else return (!req);
	}
	var valorCampo = ( typeof (elemento.selectedIndex)=='number' )?elemento.options[elemento.selectedIndex].value:elemento.value;
	if ( !req && (valorCampo.length==0) ) {
		return true;
	}
	if (req && isNumber(valorCampo, 0, 1) && (newNumber(valorCampo, 0, 1) == param )) {
		tipoerror = 10;
		sustituciones [0] = ( typeof (elemento.selectedIndex)=='number' )?elemento.options[elemento.selectedIndex].text:"";
		AlertaTextoMensaje ( elemento, tipoerror, sustituciones );
		return false;
	}
	return true;
}
/***************************************************
 *	Funciones generales
 *	Por orden alfabético.
*****************************************************/
/*	cambiaSelect y  cambiaSelectMulti*/
function cambiaSelect (campo, valores, valor) {
	cambiaSelectMulti ( campo, valores, -1, 3, 0, 1, 2, valor);
}
function cambiaSelectMulti ( campo, valores, valor, col, colval, coltext, colcond, cond ) {
	if ( typeof (campo.options) == 'object' ) {
		campo.options.length=(newNumber(campo.options[0].value, 0, 1)==-1)?1:0;
		for ( var i=0, j=0; i<valores.length/col; i++ ) {
			if ( valores[i*col+colcond]==cond ) {
				campo.options[j+1] = new Option (valores[i*col+coltext], valores[i*col+colval], 0, (valores[i*col+colval]==valor)?1:0);
				j++;
			}
		}
	}
}
/*	compruebaCCC
		Valida un CCC
	operaDC
		Funcion de apoyo de compruebaCCC */
function compruebaCCC (CCC) {
	var error = false;
	var regexCCC = new RegExp ("^(\\d{8})(\\d{2})(\\d{10})$");
	var elementos = regexCCC.exec (CCC);
	if ( elementos!=null && elementos.length==4 )
		error = (elementos[2]==operaDC("00"+elementos[1]) + "" + operaDC(elementos[3]))?false:true;
	else
		error = true;
	return !error;
}
function operaDC (numero) {
	var pesos = new Array (1,2,4,8,5,10,9,7,3,6);
	var digito=0;
	for ( i=0;i<10;i++ )
		digito += parseInt(numero.charAt(i))*pesos[i];
	digito = parseInt(digito%11);
	digito = (digito>=2)?11-digito:digito;
	return digito;
}
/*	compruebaCIF
		Valida un CIF
	calculaControl, calculaSuma, calculaTipo
		Funciones de apoyo de compruebaCIF */
function compruebaCIF (CIF) {
	var error = false;
	var regexCIF = new RegExp ("^[ABCDEFGHJKLMNPRQSUVW][0-9]{7}[0-9JABCDEFGHI]$");
	if ( regexCIF.test(CIF) ) {
		var letra = CIF.substring(0,1)
		var cif = CIF.substring(1,8);
		var dc = CIF.substring(8);
		if ( !compruebaCIFvalidaControl(cif, dc) ) {
			error = true;
		}
	} else {
		error = true;
	}
	return !error;
}
function compruebaCIFvalidaControl (cif, dc) {
	var letras = "JABCDEFGHI";
	var num = ( parseInt(cif.charAt(1)) + parseInt(cif.charAt(3)) + parseInt(cif.charAt(5)) ) + ( compruebaCIFcalculaSuma(cif.charAt(0)) + compruebaCIFcalculaSuma(cif.charAt(2)) + compruebaCIFcalculaSuma(cif.charAt(4)) + compruebaCIFcalculaSuma(cif.charAt(6)) ) + "";
	num = 10 - parseInt(num.charAt(num.length-1));
	num = (num>9)?0:num;
	return (dc==num||dc==letras.charAt(num));
}
function compruebaCIFcalculaSuma (num) {
	num = (parseInt(num)*2);
	if (num>9 ) {
		num = num + "";
		num = parseInt(num.charAt(0)) + parseInt(num.charAt(1));
	}
	return num;
}
/*	compruebaDocumento
		Valida que sea un NIF, CIF o NIE válido*/
function compruebaDocumento ( doc ) {
	var error = false;
	if ( !compruebaCIF (doc) || !compruebaNIF (doc) || !compruebaNIE (doc) )
		error = true;
	return !error;
}
/*	compruebaEmail
		Comprueba el formato de una direccion de e-mail, devuelve un código de error
		en lugar del clásico true-false.*/
function compruebaEmail ( emailStr ) {
	var errNumber = 0;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\x00-\\x1F\\s" + specialChars + "\\x7F-\\xFF\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	if ( matchArray==null ) {
		errNumber = 1
		return errNumber;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	
	if ( user.match(userPat)==null ) {
		errNumber = 2;
		return errNumber;
	}
	
	var IPArray=domain.match(ipDomainPat);
	if ( IPArray!=null ) {
		for ( var i=1; i<=4; i++ ) {
			if (IPArray[i]>255) {
				errNumber = 3;
				return errNumber;
			}
		}
		return errNumber;
	}
	var domainArray=domain.match(domainPat);
	if ( domainArray==null ) {
		errNumber = 4;
		return errNumber;
	}
	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>6 ) {
		errNumber = 5; 
		return errNumber;
	}
	if ( len<2 ) {
		errNumber = 6; 
		return errNumber;
	}
	return errNumber;
}
/*	compruebaFechaSimple
		Comprueba que una fecha tenga el formato valido*/
function compruebaFechaSimple ( dateStr, formatStr ) {
	var myObj = buildSimpleDate(dateStr, formatStr);
	if (typeof myObj == "object") {
		if ( typeof myObj.getDate == "function" ) {
			return true;
		} else {
			return myObj;
		}
	}
}
function FormatToken (token, type) {
	this.token=token;
	this.type=type;
}
function parseFormatString (formatStr) {
	var tokArr = new Array;
	var tokInd=0, strInd=0, foundTok=0;
	var tokPat=new RegExp("^yyyy|YYYY|m|M|d|D");

	while (strInd < formatStr.length) {
		if (formatStr.charAt(strInd)=="%" && (matchArray=formatStr.substr(strInd+1).match(tokPat)) != null) {
			strInd+=matchArray[0].length+1;
			tokArr[tokInd++]=new FormatToken(matchArray[0],"symbolic");
		} else {
			if (tokInd>0 && tokArr[tokInd-1].type=="literal") {
				tokArr[tokInd-1].token+=formatStr.charAt(strInd++);
			} else {
				tokArr[tokInd++]=new FormatToken(formatStr.charAt(strInd++), "literal");
			}
		}
	}
	return tokArr;
}
function buildSimpleDate ( dateStr, formatStr ) {
	var tokArr=parseFormatString(formatStr);
	var strInd=0, tokInd=0, intMonth, intDay, intYear, strOffset;
	while (strInd < dateStr.length && tokInd < tokArr.length) {
		if (tokArr[tokInd].type=="literal") {
			if (dateStr.indexOf(tokArr[tokInd].token,strInd)==strInd) {
				strInd+=tokArr[tokInd++].token.length;
				continue;
			} else {
				return  new Array (dateStr, formatStr.replace(/%/g,""), 0);
			}
		}
		switch (tokArr[tokInd].token.toLowerCase()) {
			case 'm':
			case 'd':
				curChar=dateStr.charAt(strInd);
				nextChar=dateStr.charAt(strInd+1);
				matchArr=dateStr.substr(strInd).match(/^\d{1,2}/);
				if (matchArr==null) {
					return new Array ( curChar, curChar + nextChar, 1);
				}
				strOffset=matchArr[0].length;
				switch (tokArr[tokInd].token.toLowerCase()) {
					case 'd': intDay=parseInt(matchArr[0],10); break;
					case 'm': intMonth=parseInt(matchArr[0],10); break;
				}
				break;
			case 'yyyy':
				if (dateStr.substr(strInd,4).search(/\d{4}/) != -1) {
					intYear=parseInt(dateStr.substr(strInd,4),10);
					strOffset=4;
				} else {
					return new Array (dateStr.substr(strInd,4), 4, 2);
				}
				break;
		}
		strInd += strOffset;
		tokInd++;
	}
	if (tokInd != tokArr.length || strInd != dateStr.length) {
		return new Array (dateStr, formatStr.replace(/%/g,"") ,3);
	}
	if (intMonth < 1 || intMonth > 12) {
		return new Array (intMonth, 4);
	}
	if (intDay < 1 || intDay > 31) {
		return  new Array (intDay, 5);
	}
	if ( ( (intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && intDay == 31 ) || (intMonth == 2 && (intDay > 29 || (intDay == 29 && !(intYear%4==0 && (intYear%100!=0 || intYear%400==0)))) ) ) {
		var meses = new Array ("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
		return new Array (meses[intMonth-1], intDay,  6);	
	}
	return new Date(intYear, intMonth-1, intDay);
}
/*
	compruebaNIE
		Valida un NIE
		Se apoya en letraDNI
*/
function compruebaNIE (NIE) {
	var error = false;
	var LetrasNIE = "XYZ";
	var regexNIE = new RegExp ("^[XYZ][0-9]{7}[A-Z]$");
	var numero = LetrasNIE.indexOf(NIE.charAt(0)).toString() + NIE.substring(1,NIE.length-1);
	var letra = NIE.charAt(NIE.length-1);
	if (!(regexNIE.test(NIE) && (letraDNI(numero)==letra) ))
		error = true;
	return !error;
}
/*	compruebaNIF
		Valida un NIF
		Se apoya en letraDNI */
function compruebaNIF (NIF) {
	var error = false;
	var regexDNI = new RegExp ("^[0-9]{8}[A-Z]$");
	var dni = NIF.substring(0 ,NIF.length-1);
	var letra = NIF.charAt(NIF.length-1);
	if (!(regexDNI.test(NIF) && (letraDNI(dni)==letra) ))
		error = true;
	return !error;
}
/*	letraDNI
		Funcion de apoyo de compruebaNIF y de compruebaNIE */
function letraDNI (DNI) { 
	var LetrasNIF = 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"); 
	return LetrasNIF[DNI%23]; 
}
/*	diferenciaDias
		Calcula la diferencia en dias entre fecha1 y fecha2 */
function diferenciaDias ( fecha1, fecha2 ) {
	if ( !diferenciaFechas ( fecha1, fecha2, 0, Number.POSITIVE_INFINITY ) )
		return 0;
	return 1+Math.round((buildSimpleDate ( fecha2, '%d/%m/%yyyy' ).valueOf() - buildSimpleDate ( fecha1, '%d/%m/%yyyy' ).valueOf())/86400000);
}
/*	diferenciaMeses
		Calcula la diferencia en meses entre fecha1 y fecha2 */
function diferenciaMeses ( fecha1, fecha2 ) {
	if ( !diferenciaFechas ( fecha1, fecha2, 0, Number.POSITIVE_INFINITY ) ) {
		return 0;
	}
	var fecha1 = buildSimpleDate ( fecha1, '%d/%m/%yyyy' );
	var fecha2 = buildSimpleDate ( fecha2, '%d/%m/%yyyy' );
	var duraciones = new Array (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	var meses = 0.0;
	var fechafinal = new Date(fecha1.getYear(), fecha1.getMonth(), fecha2.getDate());
	for ( ; fechafinal < fecha2; fechafinal.setMonth(fechafinal.getMonth()+1)) {
		meses += 1.0;
	}
	switch ( meses ) {
		case 0:
			meses += (1.0 + fecha2.getDate() - fecha1.getDate()) / duraciones[fecha1.getMonth()];
			break;
		default:
			if ( (fecha1.getDate() - fecha2.getDate()) != 1 ) {
				meses -= 1;
				meses += (1.0 + duraciones[fecha1.getMonth()] - fecha1.getDate()) / duraciones[fecha1.getMonth()];
				meses += fecha2.getDate() / duraciones[fecha2.getMonth()];
			}
	}
	meses = Math.round(meses * 100) /100;
	return meses;
}
/*	diferenciaFechas
		Verifica que entre  la diferencia entre fecha1
		y fecha2 esté entre diasMin y diasMax (en dias). */
function diferenciaFechas ( fecha1, fecha2, diasMin, diasMax ) {
	var error = false;
	if ( typeof (fecha1.getDate) != "function" ) {
		fecha1 = buildSimpleDate ( fecha1, '%d/%m/%yyyy' );
		error = ( typeof (fecha1.getDate) != "function" )?true:error;
	}
	if ( typeof (fecha2.getDate) != "function" ) {
		fecha2 = buildSimpleDate ( fecha2, '%d/%m/%yyyy' );
		error = ( typeof (fecha2.getDate) != "function" )?true:error;
	}
	if ( !error ) {
		var diferencia = (fecha2-fecha1)/86400000;
		if (!( (diasMin>=0 && diasMax>=0 && diasMin<diasMax && diferencia>=0 && diasMin<=diferencia && diasMax>=diferencia) || (diasMin<=0 && diasMax<=0 && diasMin>diasMax && diferencia<=0 && diasMin>=diferencia && diasMax<=diferencia ) || (diasMin<=0 && diasMax>=0 && diasMin<diasMax && diasMin<=diferencia && diasMax>=diferencia) || (diasMin<=0 && diasMax>=0 && diasMin<diasMax && diasMin<=diferencia && diasMax>=diferencia) )) {
			error = true;
		}
	}
	return !error;
}
/*	ganarFoco
		Da el foco al primer campo del primer formulario de la pagina */
function ganarFoco () {
	for ( var i=0; typeof(noFoco)=='undefined'&&i<document.forms.length; i++ ) {
		if ( document.forms[i].name.indexOf("_formulario")>0 ) {
			for ( var j=0, campo; j<document.forms[i].elements.length; j++ ) {
				campo = document.forms[i].elements[j];
				if ( campo.type == 'text' || campo.type == 'textarea' ) {
					campo.focus();
					i = document.forms.length;
					break;
				}
			}
		}
	}
}
/*	isNumber
		Verifica que un valor sea un numero */
function isNumber ( valor, dec, sig ) {
	var RegExNum = new RegExp (((sig==1)?"^[\-]{0,1}":"^") + "\\d+" + ((dec==1)?"([\,\.]{0,1}\\d+){0,1}$":"$"));
	return RegExNum.test(valor);
}
function msgsGenerales (type) {
	var mensajesE = new Array ("", "compruebe que ha introducido correctamente \"@\" y los \".\"", "el nombre del buzón de correo electrónico contiene algunos errores.", "la dirección IP proporcionada no es válida", "el nombre de dominio no es correcto", "la dirección de correo electrónico debe terminar con un dominio de tres letras si es genérico o de dos letras si se trata de un del país", "el nombre del dominio no está escrito correctamente");
	var mensajesF = new Array ("la fecha \"(t)\" no se corresponde con el formato esperado ((t))", "la fecha no es correcta en los caracteres \"(t)\" o \"(t)\"", "el año introducido \"(t)\" no tiene (t) dígitos.", "la fecha \"(t)\" tiene más información de la que el formato admite ((t))", "el mes \"(t)\" no está entre 1 y 12", "el día \"(t)\", debe estar entre 1 y 31", "el mes de (t) no tiene (t) días");
	var mensajesG = new Array (1, 0, 'es', "Por favor, complete correctamente el campo '=campo='", 2, 0, 'es', "Por favor, complete el campo '=campo=' con al menos (t) caracteres", 3, 18, 'es', "Por favor, introduzca un C.I.F. con un formato válido en el campo '=campo='", 4, 0, 'es', "Por favor, introduzca un (t) con un formato válido en el campo '=campo=' (8 números y una letra sin espacios)", 5, 0, 'es', "Por favor, complete el campo '=campo=' con un número", 6, 0, 'es', "Por favor, complete el campo '=campo=' con el número correcto de caracteres ((t))", 7, 6, 'es', "Por favor, complete correctamente el campo '=campo=' ((t))", 8, 0, 'es', "Por favor, complete correctamente el campo '=campo='. Los datos deben tener el formato/s (t)", 9, 8, 'es', "Por favor, introduzca una dirección Web con un formato correcto (http://...) en el campo '=campo='", 10, 0, 'es', "Por favor, seleccione algún elemento distinto del actual ((t)) en el campo '=campo='", 11, 22, 'es', "Por favor, revise el campo '=campo='(t)", 12, 26, 'es', "Por favor, introduzca un número de cuenta correcto en el campo '=campo='");
	return eval ('mensajes' + type);
}
/*	newNumber
		Crea un objeto numero a partir de una cadena */
function newNumber ( valor, dec, sig ) {
	if ( isNumber ( valor, dec, sig ) )
		return parseFloat (valor.replace (/,/g, "."));
	return Number.NaN;
}
function obtenerCampo ( formulario, scope, nombre ) {
	var k=0, regex, regexnombre;
	regex = getNameRegExp (formulario, scope);
	regexnombre = new RegExp ("^.*" + nombre.substring(0,3) + "\\d{4}" + nombre.substr(3, nombre.length-3)+"$");
	for (k=0;k<formulario.elements.length;k++) {
		if ( regex.test(formulario.elements[k].name) && regexnombre.test(formulario.elements[k].name) )
			return formulario.elements[k];
	}
	return null;
}
function obtenerCampos ( formulario, scope, nombres ) {
	var campos = new Array();
	for ( var k=0, i=0; i<nombres.length; k++ ) {
		var campo = obtenerCampo(formulario, scope, nombres[k]);
		if ( campo!=null )
			campos[i++] = campo;
	}
	return campos;
}
function obtenerRadioCheck ( campo, tipo ) {
	var nombre, campos, i;
	campos = ( typeof (campo.type) != 'undefined' && campo.type == tipo && typeof(campo.form)!='undefined' && typeof(campo.checked)!='undefined' )?campo.form.elements:campo;
	if ( typeof (campos.type) == 'undefined' && typeof (campos.length) == 'number' && (tipo=='checkbox'||tipo=='radio') ) {
		nombre = (typeof (campo.length) == 'number')?campo[0].name:campo.name;
		for ( i=0,campo=null; campo==null&&i<campos.length; i++ )
			campo = (campos[i].type==tipo && campos[i].name==nombre && campos[i].checked)?campos[i]:null;
	}
	return campo;
}
function obtenerDatoRadioCheck ( campo, tipo ) {
	var campo = obtenerRadioCheck ( campo, tipo );
	return (typeof (campo.value)!='undefined')?campo.value:null;
}
function select_pais_provincia ( formulario, sender, provinciasel, paissel ) {
	var value;
	provinciasel = obtenerCampo(formulario, sender, provinciasel);
	paissel = obtenerCampo(formulario, sender, paissel);
	if ( paissel==null || provinciasel==null) return;
	switch ( provinciasel.options[provinciasel.selectedIndex].value ) {
		case "-1":
			value = '-1';
			break;
		case "99":
			value = ( paissel.options[paissel.selectedIndex].value == '1' )? ( '-1' ):null;
			break;
		default:
			value = '1';
	}
	for ( var i = 0; (value!=null) && i < paissel.length; i++ ) {
		if ( paissel.options[i].value == value ) {
			paissel.selectedIndex = i;
			break;
		}
	}
}
var formulariosgenfin = true;
