// JavaScript Document
function Confirmar (str)
{

}

/*Valida que una cadena solo contenga los caracteres de la variable validos*/
function validarCaracteres(str)
{
var validos="1234567890abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ.()-#ºóáíúé ";
for (var i=0; i< str.length; i++) {
       if (validos.indexOf(str.charAt(i)) == -1)
          return false;
    }
    return true;
}	
function validarClave(str)
{
var validos="1234567890abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ";
for (var i=0; i< str.length; i++) {
       if (validos.indexOf(str.charAt(i)) == -1)
          return false;
    }
    return true;
}	


/*valida que el año sea mayor al siglo pasado*/
function y2k(number) { return (number < 1000) ? number + 1900 : number; }

/*Valida que una fehca se valida*/
function FechaValida (dia,mes,anio) {
// Verifica si una fecha es valida

    var hoy = new Date();
    anio = ((!anio) ? y2k(today.getYear()):anio);
    mes = ((!mes) ? today.getMonth():mes-1);
    if (!dia) return false
    var test = new Date(anio,mes,dia);
    if ( (y2k(test.getYear()) == anio) &&
         (mes == test.getMonth()) &&
         (dia == test.getDate()) )
        return true;
    else
        return false
}

/*quita los espacios al lado de una cadena */
function LTrim(str)
{
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(0)) != -1) {

      var j=0, i = s.length;

      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;

      s = s.substring(j, i);
   }
   return s;
}


function RTrim(str)
{
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      var i = s.length - 1;      
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;

      s = s.substring(0, i+1);
   }

   return s;
}
/*quita esocios de la cadena a la derecha y a la izquierda*/
function Trim(str)
{
  return RTrim(LTrim(str));
}


/*escribe la fecha actual*/
function fecha()
 {
  var mydate=new Date()
  var year=mydate.getYear()
   if (year < 1000)
      year+=1900
   var day=mydate.getDay()
   var month=mydate.getMonth()
   var daym=mydate.getDate()
   if (daym<10)
     daym="0"+daym
   var dayarray=new Array("Domingo","Lunes","Martes","Miercoles","Jueves","Viernes","Sabado")
   var montharray=new Array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre")
   document.write(""+dayarray[day]+" "+daym+" de "+montharray[month]+" de "+year+"")
 }

/*busca un objeto dentro del documento*/
function BuscarObjeto(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=BuscarObjeto(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

/*compara fechas ... fecha1 vs fecha2 segun el parametro Compara*/
function CompararFechas(Fecha1,DescFecha1,Fecha2,DescFecha2,Compara)
{
	
	if (Compara == "<")
	{
		  if (Fecha1 > Fecha2)
		  {
			alert(DescFecha1+"("+Fecha1+") debe ser menor a "+DescFecha2+"("+Fecha2+")");  
			return false;
		  }
	}
	else if(Compara == ">")
	{
  	      if (Fecha1 < Fecha2)
		  {
			alert(DescFecha1+"("+Fecha1+") debe ser mayor a "+DescFecha2+"("+Fecha2+")");  
			return false;
		  }
	}
	else if(Compara == "=")
	{
		  if (Fecha1 != Fecha2)
		  {
			alert(DescFecha1+"("+Fecha1+") debe ser igual a "+DescFecha2+"("+Fecha1+")");  
			return false;
		  }
	}
	return true;
}

// Para validar Requerido : R
// Para valida Email : isEmail
// Para Validar Solo Numeros : isNaN
// Para Validar Solo Numeros y Rango : inRange  ej.: inRange1:21  Lo anterior es Rango de 1 hasta 21
// Para validar caracteres especiales : isEspecial
//para validar un radiobutton .. isCheck


function ValidaForma() { //v4.0
        var i, p,r, q, nm, test, num, min, max, errors = '', args = ValidaForma.arguments;
        for (i = 0; i < (args.length - 2); i += 3) {
            test = args[i + 2]; val = BuscarObjeto(args[i]);
            if (val) {
				var valTemp = val;
                nm=args[i+1];//nm = fncNombresCampos(val.name);
                if ((val = val.value) != "") {
					val = Trim(val);
					if (val.length == 0)
					    errors += '- ' + nm + ' es requerido.\n';
						

                    if (test.indexOf('isEmail') != -1) {
                        var patron=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
     			var bandera=patron.test(val);
		    	if (bandera==false){
                        	errors += '- ' + nm + ' debe contener una dirección de email valida.\n';
			}
                    } 
					else if (test.indexOf('isCheck') != -1)
					{
  					    var icheck,swcheck = 0;
						for (icheck=0;icheck<valTemp.length;icheck++)
						{
							if(valTemp[icheck].checked == true){
  						       swcheck = 1;break;
							}
						}
						if (swcheck == 0)
						{
							errors += '- ' + nm + ' requiere seleccionar una opcion.\n';   
						}
					}
					else if (test.indexOf('isEspecial') != -1 || test.indexOf('isNotNum') != -1)
					{
						if(test.indexOf('isEspecial') != -1)
						{
						 if(!validarCaracteres(val))
					       errors += '- ' + nm + ' contiene caracteres no válidos.\n';
						}
						if (test.indexOf('isNotNum') != -1)
						{
						  num = parseFloat(val);
                          if (!isNaN(num)) errors += '- ' + nm + ' NO debe contener solo números.\n';
						}
							
					}

                              else if (test.indexOf('isPassword') != -1)
					{
						if(!validarClave(val))
					      errors += '- ' + nm + ' contiene caracteres no válidos.\n';
							
                   
                    }
                    else if (test != 'R') {
                        num = parseFloat(val);
                        if (isNaN(val)) errors += '- ' + nm + ' debe contener solo números.\n';
						if (test.indexOf('isMayor') != -1) {
                        	num = parseFloat(val);
							p = test.indexOf(':');
                        	min = test.substring(p + 1);
                        	if (num < min)
                           	 errors += '- ' + nm + ' debe contener números mayores a ' + min + '\n';
                        }
                        if (test.indexOf('inRange') != -1) {
                            p = test.indexOf(':');
                            min = test.substring(8, p); max = test.substring(p + 1);
                            if (num < min || max < num)
                                errors += '- ' + nm + ' debe contener solo números entre ' + min + ' y ' + max + '.\n';
                        }
                    }
                } else if (test.charAt(0) == 'R') errors += '- ' + nm + ' es requerido.\n';
            }
        }
        if (errors)
        {
        alert('Se presentaron los siguientes errores:\n' + errors);
        return false;
        }
        else
        {
          return true;
        }
    }