
//*****************************************************************************************
//Nombre función: VACIO
//Descripción: Comprueba si un campo está vacío
//Parámetros: campo - path javascript hasta llegar al campo
//Resultado: true si el campo está vacío
//           false si el campo está informado
//*****************************************************************************************

function vacio(campo)
{
	cadena = new String(eval(campo + ".value"));
	if (cadena.length == 0)
	{
		return true;
	}
	return false;
}

//*****************************************************************************************
//Nombre función: COMPROBAR_LONGITUD
//Descripción: Comprueba la longitud de un texto y si se supera, se corta
//Parámetros:	limite - caracteres máximos
//				campo - campo al que hace referencia
//Resultado: true si el campo supera
//           false si el campo no supera
//*****************************************************************************************

function limitar_longitud(limite, campo)
{
	cadena = new String(campo.value);
	nueva_cadena = "";
	if (cadena.length > limite)
	{
		nueva_cadena = cadena.substring(0,limite);
		campo.value = nueva_cadena;
	}
	return false;
}

//*****************************************************************************************
//Nombre función: OBLIGATORIO
//Descripción: Comprueba si un campo es obligatorio o no, mostrando el error correspondiente
//Parámetros: campo - path javascript hasta llegar al campo
//            nombre_campo - nombre que se mostrará en los mensajes de error
//Resultado: true si el campo es obligatorio y no está lleno
//           false si el campo está informado
//*****************************************************************************************

function obligatorio(campo, nombre_campo)
{
	cadena = new String(eval(campo + ".value"));
	if (cadena.length == 0)
	{
		alert("El campo " + nombre_campo + " es obligatorio");
		eval(campo + ".select()");
		return true;
	}
	return false;
}
	
//*****************************************************************************************
//Nombre función: SUPERA
//Descripción: Comprueba si un campo supera el límite estipulado en longitud
//Parámetros: campo - path javascript hasta llegar al campo
//            maximo - límite de caracteres establecido
//            nombre_campo - nombre que se mostrará en los mensajes de error
//Resultado: true si el campo supera el límite
//           false si el campo no supera el límite
//*****************************************************************************************

function supera(campo, maximo, nombre_campo)
{
	cadena = new String(eval(campo + ".value"));
	if (cadena.length > maximo)
	{
		alert("El campo " + nombre_campo + " no puede tener más de " + maximo + " caracteres");
		eval(campo + ".select()");
		return true;
	}
	return false;	
}

//*****************************************************************************************
//Nombre función: NO_ALCANZA
//Descripción: Comprueba si un campo alcanza un mínimo estipulado en longitud
//Parámetros: campo - path javascript hasta llegar al campo
//            minimo - unmbral mínimo de caracteres establecido
//            nombre_campo - nombre que se mostrará en los mensajes de error
//Resultado: true si el campo no alcanza el mínimo
//           false si el campo alcanza el mínimo
//*****************************************************************************************

function no_alcanza(campo, minimo, nombre_campo)
{
	cadena = new String(eval(campo + ".value"));
	if (cadena.length < minimo)
	{
		alert("El campo " + nombre_campo + " ha tener como mínimo " + minimo + " caracteres");
		eval(campo + ".select()");
		return true;
	}
	return false;	
}
	

//*****************************************************************************************
//Nombre función: ESEMAIL
//Descripción: Comprueba si un string se corresponde a una dirección email válida
//Parámetros: campo - path javascript hasta llegar al campo
//            nombre_campo - nombre que se mostrará en los mensajes de error
//Resultado: true si el campo es válido como email
//           false si el campo no es válido como email
//*****************************************************************************************

function esemail(campo, nombre_campo)
{
	
	str = new String(eval(campo+".value"));
	// are regular expressions supported?
	var supported = 0;
	if (window.RegExp) {
		var tempStr = "a";
		var tempReg = new RegExp(tempStr);
		if (tempReg.test(tempStr)) supported = 1;
	}
	if (!supported) return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
	var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
	if (!r1.test(str) && r2.test(str))
	{
		return true;
	} else {
		alert("El formato de mail del campo " + nombre_campo + " no es válido");
		eval(campo + ".select()");
		return false;
	}
}


//*****************************************************************************************
//Nombre función: UNO_MARCADO
//Descripción: Comprueba si un check o radio tienen por lo menos una opcion marcada
//Parámetros: formulario: nombre del formulario
//			  campo - path javascript hasta llegar al campo
//			  alerta - nombre del campo para el alert
//Resultado: true por lo menos tiene uno marcado
//           false si no tiene ninguno marcado
//*****************************************************************************************

function uno_marcado(formulario, campo, alerta)
{
	limite = eval("document." + formulario + "." + campo + ".length")
	uno_seleccionado = false;
	for (i=0;i<limite;i++){
		if (eval("document." + formulario + "." + campo + "[" + i + "].checked")){
			i=limite;
			uno_seleccionado = true;
		}
	}
	if (!uno_seleccionado){
		alert ("Debes seleccionar como mínimo una opción de " + alerta)
	}
	
	return uno_seleccionado;
}	


function uno_seleccionado(campo, nombre_campo)
{
	if ( eval(campo + ".value <= 0") )
	{
		alert("Debe seleccionar un elemento del campo " + nombre_campo);
		eval(campo + ".focus()");
		return true;
	}
	
	return false;
}	

//*****************************************************************************************
//Nombre funci&oacute;n: NUMERICO
//Descripci&oacute;n: Comprueba si un campo es num&eacute;rico
//Para;metros: campo - path javascript hasta llegar al campo
//Resultado: false si el campo es num&eacute;rico
//           true si el campo NO es num&eacute;rico
//*****************************************************************************************

function numerico(campo,nombre_campo)
{
	cadena = new String(eval(campo + ".value"));

	cad = cadena;

	if ( cadena.match(".") == "." )
	{
		alert("El separador de decimales debe ser la ,");
		eval(campo + ".focus()");
		return true;
	}

	array_puntos = cadena.split(",")

	if ( array_puntos.length > 2 )
	{
		alert("El campo " + nombre_campo + " debe ser numerico");
		eval(campo + ".focus()");
		return true;
	}


	cad = replace(cad,",",".") 

	if ( isNaN(parseFloat(cad)) )
	{
		alert("El campo " + nombre_campo + " debe ser numerico");
		eval(campo + ".focus()");
		return true;
	}

	return false;
}

function replace(string,text,by) 
{
	// Replaces text with by in string
	var strLength = string.length, txtLength = text.length;
	if ((strLength == 0) || (txtLength == 0)) return string;

	var i = string.indexOf(text);
	if ((!i) && (text != string.substring(0,txtLength))) return string;
	if (i == -1) return string;

	var newstr = string.substring(0,i) + by;

	if (i+txtLength < strLength)
	newstr += replace(string.substring(i+txtLength,strLength),text,by);

	return newstr;
}

var defaultEmptyOK = false;

function makeArray(n)
{
   for (var i = 1; i <= n; i++)
   {
      this[i] = 0
   } 
   return this
}

var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;

function isDate (year, month, day)
{
    if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;

    var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);

    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}

function isYear (s)
{
	if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}

function isMonth (s)
{
	if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
}

function isDay (s)
{
	if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    return isIntegerInRange (s, 1, 31);
}

function isEmpty(s)
{
	return ((s == null) || (s.length == 0))
}

function daysInFebruary (year)
{
	return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}

function isNonnegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) >= 0) ) );
}

function isSignedInteger (s)
{
	if (isEmpty(s)) 
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}

function isIntegerInRange (s, a, b)
{
	if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    if (!isInteger(s, false)) return false;

    var num = parseInt (s);
    return ((num >= a) && (num <= b));
}

function isInteger (s)
{
	var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }

    return true;
}

function isDigit (c)
{
	return ((c >= "0") && (c <= "9"))
}
