
//Revision de mensajes
 var MERROR = new Array();
 MERROR[1]="Dato inválido. Solo se permiten caracteres";
 MERROR[2]="El valor del campo debe ser numérico";
 MERROR[3]="Rango permitido para el código: 1 al 9";
 MERROR[4]="Rango permitido para el código: 1 al 99";
 MERROR[5]="Rango permitido para el código: 1 al 999";
 MERROR[6]=" no es aceptado en la descripción del campo";
 MERROR[7]="Favor introducir informacion en campo obligatorio (*)";
 MERROR[8]="Valor no puede ser cero";
 MERROR[9]="Espacios en blancos en el  inicio o el fin del campo";
 MERROR[10]="Solo se permiten caracteres";
 MERROR[11]="Modificacion no Permitida";
 MERROR[12]="Indique un numero de longitud 16"
 MERROR[13]="Indique un numero de longitud 8"
 MERROR[14]="Por favor confirme su contraseña correctamente"
 
 var MAVISO = new Array();
 MAVISO[1]="¿Eliminará este registro?";
 MAVISO[2]="¿Desactivará la baja de este registro?";
 MAVISO[3]="Baja no permitida";
 MAVISO[4]="¿Desea guardar los cambios efectuados al registro?";
 MAVISO[5]="Código existente";
 MAVISO[6]="Descripción existente";
 MAVISO[7]="La operación no pudo ser efectuada.";
 MAVISO[8]="Registro eliminado"
 MAVISO[9]="Registro activado"
 MAVISO[10]="Consulte al administrador de la aplicación."
 MAVISO[11]="Registro en tratamiento."


// =========================================================================================
//  NOMBRE:		sololetras

//  OBJETIVO:		Verifica si el valor del argumento "campo" contiene solo letras o 	//			contiene letras y espacios, para permitir que el argumento campo 
//			contenga espacios, debe indicarse por medio de la bandera "siespacio" 
//			en 1. El mensaje de error a mostrar, se debe indicar en el argumento 	//			"msg".
//						             	
//  PARAMETROS: 	campo, msg, siespacio 								
//  VALOR DE RETORNO:   boolean

//==========================================================================================
function sololetras(campo,msg,siespacio,otroschar) {
   campo.value=trimcad(campo.value)  
   if (siespacio==1)
	var valido = otroschar+"ABCDEFGHIJKLMNÑOPQRSTUVWXYZabcdefghijklmnñopqrstuvwxyz ";
   else
	var valido = otroschar+"ABCDEFGHIJKLMNÑOPQRSTUVWXYZabcdefghijklmnñopqrstuvwxyz";

	var ok = "yes";
	var temp;
	for (var i=0; i<campo.value.length; i++) {
		temp = "" + campo.value.substring(i, i+1);
		if (valido.indexOf(temp) == "-1") ok = "no";
	}
	if (ok == "no") {
	        alert(msg);
		return false;
  	}
return true
}



// FUNCION QUE PERMITE VALIDAR EL CODIGO EN DEPENDENCIA DEL NUMERO DE DIGITOS PERMITIDOS
// RECIBE COMO PARAMETROS EL CODIGO Y EL NUMERO DE DIGITOS PERMITIDOS

function validac(codigo,numdig) {

  if(codigo.value!=""){
    noesnumero=isNaN(codigo.value);      
	if (noesnumero){
        alert(MERROR[2]);
		codigo.select();
		codigo.focus();
		return false;
	}
	else 
	{ 
	   switch(numdig) {
		case 1: 
			if((codigo.value<0)||(codigo.value>9)){
				alert(MERROR[3]);   //Rango permitido para el código: 1 al 9
				codigo.select();
				codigo.focus();
				return false;
	  		}
		 case 2: 
			if((codigo.value<0)||(codigo.value>99)){
				alert(MERROR[4]);   //Rango permitido para el código: 1 al 99
				codigo.select();
				codigo.focus();
				return false;
	  		}
		 case 3: 
			if((codigo.value<0)||(codigo.value>999)){
				alert(MERROR[5]);   //Rango permitido para el código: 1 al 999
				codigo.select();
				codigo.focus();
				return false;
	  		}

           }// de switch
	 
      }//de numérico
  }//de vacio
	return true;
}

function validacaracteres(campoform)
{
 
	// campoform = Variable que denota el campo de un formulario
	// El siguiente for es utilizado para no permitir que el usuario introduzca
	// en el campo, caracteres no validos referidos en la variable invalidchar, 
 	
 	nocaracteres=""
 	invalidchar="~`!|@$%^&*()+=|\\{[}];<>?¿¡\""
 	for(i=0;i<invalidchar.length;i++)
	{
	badchar=invalidchar.charAt(i)
	if(campoform.value.indexOf(badchar,0)>-1)
	{
		nocaracteres=nocaracteres + badchar
	}
	} // fin del for invalidchar 
	
	if (nocaracteres!="")
	{
		nocaracteres="El Caracter : " + nocaracteres
		alert(nocaracteres + MERROR[6]);
		return false; // Envia el mensaje de error y restaura la descripcion del campo
	}
	else
	{
		return true
	}

} // fin de la funcion validacaracteres

function validacaracteres2(campoform)
{
 
	// campoform = Variable que denota el campo de un formulario
	// El siguiente for es utilizado para no permitir que el usuario introduzca
	// en el campo, caracteres no validos referidos en la variable invalidchar, 
	// esta funcion es menos resringida y acepta mas caracteres especiales que la funcion validacaracteres
 	
 	nocaracteres2=""
	charnoper="ÁÉÍÓÚáéíóú~`'!|@#·$%^&*()_+=|{};:<>?¿¡\""
	for(i=0;i<charnoper.length;i++)
	{
	badchar2=charnoper.charAt(i)
	if(campoform.value.indexOf(badchar2,0)>-1)
	{
		nocaracteres2=nocaracteres2 + badchar2
	}
	} // fin del for charnoper
	
	if (nocaracteres2!="")
	{
		nocaracteres2="El Caracter : " + nocaracteres2
		alert(nocaracteres2 + MERROR[6]);
		return false; // Envia el mensaje de error y restaura la descripcion del campo
	}
	else
	{
		//campoform.value=campoform.value.toUpperCase();
   		trim(campoform); 
		return true
	}

} // fin de la funcion validacaracteres2

//cero: valores posibles: 1 (acepta cero), 0 (no acepta cero)
function solonumeros(campoform,cero)
{
    if (isNaN(campoform.value))
	{   alert(MERROR[2]);
		return false;
 	}else{
	  if(cero==0){
	    if(campoform.value==0){
		  alert(MERROR[8]);
		  return false;
		}
	  }
	}
 return true;
}

function validatarjeta(obj){
   if(!solonumeros(obj,0)){
	   return false; 
  }else{
	  if(obj.value.length!=16){
		alert(MERROR[12]);
	    return false;
	  }
  }
 return true;
}

function validausuario(obj){
   if(!solonumeros(obj,0)){
	   return false; 
  }else{
	  if(obj.value.length!=8){
		alert(MERROR[13]);
	    return false;
	  }
  }
 return true;
}

function abrirventana(laURL,winNombre,Ancho, Alto) { 
        
	//var topVent = (window.screen.availHeight - Alto)/2;

   /**************** version anterior*******************
	var topVent = 0;

	if (Ancho >= window.screen.width){
	  var leftVent=0;
	}
	else{      
      var leftVent = (window.screen.width - Ancho)/2;
    }
	caracteristicas="resize=true,width="+Ancho+",height="+Alto+",left="+leftVent+",top="+topVent+"";
	window.open(laURL,winNombre,caracteristicas);

   ******************************************************/
        window.navigate(laURL);
}

/****** Remueve los espacios al inicio y final de una cadena *****/
function trim(item)
{
  var tmp = "";
  var item_length = item.value.length;
  var item_length_minus_1 = item.value.length - 1;
  for (index = 0; index < item_length; index++)
  {
    if (item.value.charAt(index) != ' ')
    {
      tmp += item.value.charAt(index);
    }
    else
    {
      if (tmp.length > 0)
      {
        if (item.value.charAt(index+1) != ' ' && index != item_length_minus_1)
        {
          tmp += item.value.charAt(index);
        }
      }
    }
  }
  item.value = tmp;
}

/********************************************************************************
     Indica si la tecla presionada por el usuario es el retorno del carro (ENTER)
     debe ser utilizada en el evento onKeyPress
*********************************************************************************/
function IsEnter()
{
 var whichKey = event.keyCode; 
 if (whichKey==13)
  return(true);
 else 
  return(false);

}


/** Remueve los espacios al inicio y final de una cadena, recibiendo como parametro la cadena y devolviendola sin los espacios***/
function trimcad(cad)
{
  var cadtmp = "";
  var cad_length = cad.length;
  var cad_length_minus_1 = cad.length - 1;
  for (ind = 0; ind < cad_length; ind++)
  {
    if (cad.charAt(ind) != ' ')
    {
      cadtmp += cad.charAt(ind);
    }
    else
    {
      if (cadtmp.length > 0)
      {
        if (cad.charAt(ind+1) != ' ' && ind != cad_length_minus_1)
        {
          cadtmp += cad.charAt(ind);
        }
      }
    }
  }
  return(cadtmp);
}

function ValidaCampo(Objeto,ValorInicial,Obligatorio,Etiqueta)
{
	
	// Funcion general que valida la entrada de campos del formulario
	// dependiendo de los parametros Obligatorio,Etiqueta
	// en caso de generarse un mensaje de error retorna falso y 
	// se carga el valor del campo del formulario con los valores iniciales 
	// referidos en la variable ValorInicial.
	//
	// Valores que debe recibir el parametro Obligatorio = 0,1
	// Valores que debe recibir el parametro Etiqueta = 0,1,2
	
	// Si Obligatorio = 0, no verifica que el campo debe ser obligatorio
	// Si Obligatorio = 1, verifica que el campo debe ser obligatorio
	
	// Si Etiqueta = 0, no hace ningun chequeo
	// Si Etiqueta = 1, verifica campos de tipo numerico
	// Si Etiqueta = 2, verifica campos de tipo alfanumericos
	// Desarrollado por Milton Martinez 24/12/2001
  
  if(Obligatorio==1)
  {	
  	if(Objeto.value=="")
  	{
      alert(MERROR[7]);
      Objeto.value=ValorInicial;
      Objeto.focus();
      return false;
     }
   }
    
  if (Etiqueta==1)
  {
  	if (solonumeros(Objeto)==false)
  	{
  	  Objeto.value=ValorInicial;
  	  Objeto.focus();
      return false;
  	}
  	
  }
  
  if (Etiqueta==2)
  {
  	if(!validacaracteres(Objeto))
  	{
  		Objeto.value=ValorInicial;
  		Objeto.focus();
      	return false;
  	}
  	else
  	{	
  		Objeto.value=Objeto.value.toUpperCase();
   		trim(Objeto); 
   		return true;
  	}
  }

return true;
}
function ValidaBusqueda(Cadena)
{
	// Si la cadena es correcta retorna true
	// Si la cadena no es correcta retorna false

	nocaracteres=""
	invalidchar="~`'!|@#·$%^&*()_=|\{[}]/;:<>,?¿¡\""
	 for(i=0;i<invalidchar.length;i++)
	 {
	badchar=invalidchar.charAt(i)
	if(Cadena.indexOf(badchar,0)>-1)
	{
		nocaracteres=nocaracteres + badchar
	}
	} // fin del for invalidchar 
	
	if (nocaracteres!="")
	{
		nocaracteres="El Caracter : " + nocaracteres
		alert(nocaracteres + 'no es permitido en la cadena de busqueda');
		return false; 
	}
return true;
}


function sololetrasynumeros(campo,msg,siespacio) {
     
   if (siespacio==1)
	var valido = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZabcdefghijklmnñopqrstuvwxyz0123456789 ";
   else
	var valido = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZabcdefghijklmnñopqrstuvwxyz0123456789";

	var ok = "yes";
	var temp;
	for (var i=0; i<campo.value.length; i++) {
		temp = "" + campo.value.substring(i, i+1);
		if (valido.indexOf(temp) == "-1") ok = "no";
	}
	if (ok == "no") {
	        alert(msg);
		return false;
  	}
return true
}

/******************** FUNCION DE FORMATO MONEDA***********************/
function currencyFormat(fld, milSep, decSep, e) 
	{ // Para el formato de moneda
		var sep = 0;
		var key = '';
		var i = j = 0;
		var len = len2 = 0;
		var strCheck = '0123456789';
		var aux = aux2 = '';
		var whichCode = (window.Event) ? e.which : e.keyCode;
		if (whichCode == 13) return true;  // Enter
		key = String.fromCharCode(whichCode);  // Get key value from key code
		if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
		len = fld.value.length;
		for(i = 0; i < len; i++) if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
		aux = '';
		for(; i < len; i++)	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
		aux += key;
		len = aux.length;
		if (len == 0) fld.value = '';
		if (len == 1) fld.value = '0'+ decSep + '0' + aux;
		if (len == 2) fld.value = '0'+ decSep + aux;
		if (len > 2) {
			aux2 = '';
			for (j = 0, i = len - 3; i >= 0; i--) {
				if (j == 3) {
					aux2 += milSep;
					j = 0;
				}
				aux2 += aux.charAt(i);
				j++;
			}
			fld.value = '';
			len2 = aux2.length;
			for (i = len2 - 1; i >= 0; i--)	fld.value += aux2.charAt(i);fld.value += decSep + aux.substr(len - 2, len);
		}
		return false;
	}
//  End -->



/******************** FUNCION DE FORMATO MONEDA***********************/
function currencyFormat1(fld, milSep, decSep, e) 
	{ // Para el formato de moneda con números de decimales libres sin máscara de entrada		
		var sep = 0;
		var key = '';
		var i = j = 0;
		var len = len2 = 0;
		var strCheck = '0123456789';
		var aux = aux2 = '';
		var whichCode = (window.Event) ? e.which : e.keyCode;
		if (whichCode == 13) return true;  // Enter
		key = String.fromCharCode(whichCode);  // Capta el valor desde código el teclado
		if (strCheck.indexOf(key) == -1 && key!='.') return false;  // Las teclas no validas
		len = fld.value.length;
		for(i = 0; i < len; i++) if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
		aux = '';
		punto='.';
		haypunto='';
		// Se verifica si ya se captó un decimnal
		for(; i < len; i++) if (fld.value.charAt(i)=='.') haypunto=1;		
		// se agregan más dígitos a la cadena del valor captado desde el teclado
		i=0;
		if (haypunto!=1 || key!='.'){
		 	for(; i < len; i++)	if (strCheck.indexOf(fld.value.charAt(i))!=-1 || key!='.') aux += fld.value.charAt(i);		
			aux += key;
			len = aux.length;
			fld.value=aux;
		}	
		return false;
	}

	
// End -->

//FUNCIONES PARA VALIDAR FECHAS EN FORMATO DD/MM/YYYY

function y2k(number) { return (number < 1000) ? number + 1900 : number; }

function isValidDate (myDate,sep) {

    if (myDate.length == 10) {
        if (myDate.substring(2,3) == sep && myDate.substring(5,6) == sep) {
            var date  = myDate.substring(0,2);
            var month = myDate.substring(3,5);
            var year  = myDate.substring(6,10);

            var test = new Date(year,month-1,date);

            if (year == y2k(test.getYear()) && (month-1 == test.getMonth()) && (date == test.getDate())) {
                return true;
            }
            else {
                alert('Formato válido pero la fecha no es válida');
                return false;
            }
        }
        else {
            alert('Separadores en fecha no válidos');
            return false;
        }
    }
    else {
        alert('Longitud de fecha no válida');
        return false;
    }
}

function validasello(obj){
   if(!sololetras(obj,"Valor contiene algun caracter no válido",0,"0123456789")){
	   return false; 
  }else{
	  if(obj.value.length!=16){
		alert(MERROR[12]);
	    return false;
	  }
  }
 return true;
}

function DatePosition(dateString,dateType) {
/*
   function DatePosition 
   parameters: dateString dateType
   returns: integer (-1, 0, 1)
   
   dateString is a date passed as a string in the following
   formats:

   type 1 : 19970529
   type 2 : 970529
   type 3 : 29/05/1997
   type 4 : 29/05/97
   type 5 : 05/29/1997
   type 6 : 05291997
   type 7 : 052997
   
   dateType is a numeric integer from 1 to 7, representing
   the type of dateString passed, as defined above.

   Returns -1 if the date passed is behind todays date
   Returns 0 if the date passed is equal to todays date
   or if dateType is not 1 to 7
   Returns 1 if the date passed is ahead of todays date
   
   Added Y2K checking.  (Works for any century cross over)
*/


    var now = new Date();
    var today = new Date(now.getYear(),now.getMonth(),now.getDate());
    var century = parseInt(now.getYear()/100)*100;
        
    if (dateType == 1)
        var date = new Date(dateString.substring(0,4),
                            dateString.substring(4,6)-1,
                            dateString.substring(6,8));
    else if (dateType == 2)
    {
        if ((now.getYear()%100)>=parseInt(dateString.substring(0,2)))
        {
            var date = new Date(century+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(2,4)-1),
                            dateString.substring(4,6));
        }
        else
        {
            var date = new Date(century-100+parseInt(dateString.substring(0,2)),
                            parseInt(dateString.substring(2,4)-1),
                            dateString.substring(4,6));
        }
        
    }
    else if (dateType == 3)
        var date = new Date(dateString.substring(6,10),
                            dateString.substring(3,5)-1,
                            dateString.substring(0,2));
    else if (dateType == 4)
    {
        if ((now.getYear()%100)>=parseInt(dateString.substring(6,8)))
        {
            //document.write(century+parseInt(dateString.substring(6,8)),'<P>');
            var date = new Date(century+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(3,5)-1),
                            dateString.substring(0,2));
        }
        else
        {
            //document.write(century-100+parseInt(dateString.substring(6,8)),'<P>');
            var date = new Date(century-100+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(3,5)-1),
                            dateString.substring(0,2));
        }
        
    }
    else if (dateType == 5)
        var date = new Date(dateString.substring(6,10),
                            dateString.substring(0,2)-1,
                            dateString.substring(3,5));
    else if (dateType == 6)
        var date = new Date(dateString.substring(4,8),
                            dateString.substring(0,2)-1,
                            dateString.substring(2,4));
    else if (dateType == 7)
    {
        if ((now.getYear()%100)>=parseInt(dateString.substring(4,6)))
        {
            //document.write('datestring Century:',century+parseInt(dateString.substring(4,6)),'<P>');
            var date = new Date(century+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(0,2)-1),
                            dateString.substring(2,4));
        }
        else
        {
            //document.write('datestring Century:',century-100+parseInt(dateString.substring(4,6)),'<P>');
            var date = new Date(century-100+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(0,2)-1),
                            dateString.substring(2,4));
        }
        
    }
    else
        return false;

    if (date < today)
    {
        //document.write(date.toString(),' is behind ',today.toString(),'<P>');
        return -1;
    }
    else if (date > today)
    {
        //document.write(date.toString(),' is ahead of ',today.toString(),'<P>');
        return 1;
        
    }
    else
    {
        //document.write(date.toString(),' is the same as ',today.toString(),'<P>');
        return 0;
    }
}


//validaciones EMAIL

function isEmail(string) {
    if (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
        return true;
    else
        return false;
}

function isProper(string) {
    if (string.search(/^\w+( \w+)?$/) != -1)
        return true;
    else
        return false;
}
