// ---------------------------------------------------------------------- //
//           FormCheq.js (c) ChaTo 1998,1999 [www.chato.cl]
//                           Basado en:
//           FormChek.js (c) Eric Krock (c) 1997 Netscape              
// ---------------------------------------------------------------------- //
// 18 Feb 97 creado por Eric Krock (c) 1997
//   Netscape Communications Corporation
// 18 Ago 98 modificado por Carlos Castillo (c) 1998 ChaTo
//   Los principales cambios son: esta version es simplificada, para
//   propositos de ensennanza y validacion basica de formularios, y esta
//   adaptada para recibir caracteres del alfabeto espannol (acentos, etc.)
// 20 Oct 99 modificado por Carlos Castillo (c) 1999 ChaTo
//   Se agrega la funcion isNice que ayuda a evitar comillas simples
//   o dobles que causan problemas con muchos CGIs
// 
// ---------------------------------------------------------------------- //
//                             RESUMEN                                    //
// ---------------------------------------------------------------------- //
// 
// El objetivo de las siguientes funciones en JavaScript es
// validar los ingresos del usuario en un formulario antes
// de que estos datos vayan al servidor.
//
// Varias de ellas toman un parametro opcional E.O.K (eok) (emptyOK
// - true si se acepta que el valor este vacio, false si no
// se acepta). El valor por omision es el que indique la
// variable global defaultEmptyOK definida mas abajo.
//
// ---------------------------------------------------------------------- //
//                      SINTAXIS DE LAS FUNCIONES                         //
// ---------------------------------------------------------------------- //
//
// FUNCION PARA CHEQUEAR UN CAMPO DE INGRESO:
//
// checkField (theField, theFunction, [, s] [,eok])
//        verifica que el campo de ingreso theField cumpla con la
//        condicion indicada en la funcion theFunction (que puede ser
//        una de las descritas en "FUNCIONES DE VALIDACION" o cualquier
//        otra provista por el usuario). En caso contrario despliega el
//        string "s" (opcional, hay mensajes por default para las
//        funciones de validacion provistas aqui).
//
// FUNCIONES DE VALIDACION:
//
// isInteger (s [,eok])                s representa un entero
// isNumber (s [,eok])                 s es entero o tiene punto decimal
// isAlphabetic (s [,eok])             s tiene solo letras
// isAlphanumeric (s [,eok])           s tiene solo letras y/o numeros
// isPhoneNumber (s [,eok])            s tiene solo numeros, (,),-
// isEmail (s [,eok])                  s es una direccion de e-mail
//
// FUNCIONES INTERNAS:
//
// isWhitespace (s)                    s es vacio o solo son espacios
// isLetter (c)                        c es una letra
// isDigit (c)                         c es un digito
// isLetterOrDigit (c)                 c es letra o digito
//
// FUNCIONES PARA REFORMATEAR DATOS:
//
// stripCharsInBag (s, bag)            quita de s los caracteres en bag
// stripCharsNotInBag (s, bag)         quita de s los caracteres NO en bag
// stripWhitespace (s)                 quita el espacio dentro de s
// stripInitialWhitespace (s)          quita el espacio al principio de s
//
// FUNCIONES PARA PREGUNTARLE AL USUARIO:
//
// statBar (s)                         pone s en la barra de estado
// warnEmpty (theField, s)             indica que theField esta vacio
// warnInvalid (theField, s)           indica que theField es invalido
//
// ---------------------------------------------------------------------- //
//                                VARIABLES                               //
// ---------------------------------------------------------------------- //

// Esta variable indica si está bien dejar las casillas
// en blanco como regla general
var defaultEmptyOK = false

// Esta variable indica si se debe verificar la presencia de comillas
// u otros símbolos extraños en un campo, por omisión no, porque
// siempre crea problemas con las bases de datos o programas CGI
var checkNiceness = true;

// listas de caracteres
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyzáéíóúñü "
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑ "
var whitespace = " \t\n\r";

// caracteres admitidos en nos de telefono
var phoneChars = "()-+ ";

// ---------------------------------------------------------------------- //
//                     TEXTOS PARA LOS MENSAJES                           //
// ---------------------------------------------------------------------- //

// m abrevia "missing" (faltante)
var mMessage = "Error: no puede dejar este espacio vacio"

// p abrevia "prompt"
var pPrompt = "Error: ";
var pAlphanumeric = "ingrese un texto que contenga solo letras y/o numeros";
var pAlphabetic   = "ingrese un texto que contenga solo letras";
var pInteger = "ingrese un numero entero";
var pNumber = "ingrese un numero";
var pPhoneNumber = "ingrese un número de teléfono";
var pEmail = "ingrese una dirección de correo electrónico válida";
var pName = "ingrese un texto que contenga solo letras, numeros o espacios";
var pNice = "no puede utilizar comillas aqui";

// ---------------------------------------------------------------------- //
//                FUNCIONES PARA MANEJO DE ARREGLOS                       //
// ---------------------------------------------------------------------- //

// JavaScript 1.0 (Netscape 2.0) no tenia un constructor para arreglos,
// asi que ellos tenian que ser hechos a mano. Desde JavaScript 1.1 
// (Netscape 3.0) en adelante, las funciones de manejo de arreglos no
// son necesarias.

function makeArray(n) {
//*** BUG: If I put this line in, I get two error messages:
//(1) Window.length can't be set by assignment
//(2) daysInMonth has no property indexed by 4
//If I leave it out, the code works fine.
//   this.length = n;
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}

// ---------------------------------------------------------------------- //
//                  CODIGO PARA FUNCIONES BASICAS                         //
// ---------------------------------------------------------------------- //


// s es vacio
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

// s es vacio o solo caracteres de espacio
function isWhitespace (s)
{   var i;
    if (isEmpty(s)) return true;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        // si el caracter en que estoy no aparece en whitespace,
        // entonces retornar falso
        if (whitespace.indexOf(c) == -1) return false;
    }
    return true;
}

// Quita todos los caracteres que que estan en "bag" del string "s" s.
function stripCharsInBag (s, bag)
{   var i;
    var returnString = "";

    // Buscar por el string, si el caracter no esta en "bag", 
    // agregarlo a returnString
    
    for (i = 0; i < s.length; i++)
    {   var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

// Lo contrario, quitar todos los caracteres que no estan en "bag" de "s"
function stripCharsNotInBag (s, bag)
{   var i;
    var returnString = "";
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}

// Quitar todos los espacios en blanco de un string
function stripWhitespace (s)
{   return stripCharsInBag (s, whitespace)
}

// La rutina siguiente es para cubrir un bug en Netscape
// 2.0.2 - seria mejor usar indexOf, pero si se hace
// asi stripInitialWhitespace() no funcionaria

function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}

// Quita todos los espacios que antecedan al string
function stripInitialWhitespace (s)
{   var i = 0;
    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    return s.substring (i, s.length);
}

// c es una letra del alfabeto espanol
function isLetter (c)
{
    return( ( uppercaseLetters.indexOf( c ) != -1 ) ||
            ( lowercaseLetters.indexOf( c ) != -1 ) )
}

// c es un digito
function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

// c es letra o digito
function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}

// ---------------------------------------------------------------------- //
//                          NUMEROS                                       //
// ---------------------------------------------------------------------- //

// s es un numero entero (con o sin signo)
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( i != 0 ) {
            if (!isDigit(c)) return false;
        } else { 
            if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
    }
    return true;
}
// s es un numero (entero o flotante, con o sin signo)
function isNumber (s)
{   var i;
    var dotAppeared;
    dotAppeared = false;
    if (isEmpty(s)) 
       if (isNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isNumber.arguments[1] == true);
    
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if ( c == "." ) {
                if( !dotAppeared )
                    dotAppeared = true;
                else
                    return false;
            } else     
                if (!isDigit(c)) return false;
        } else { 
            if ( c == "." ) {
                if( !dotAppeared )
                    dotAppeared = true;
                else
                    return false;
            } else     
                if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
    }
    return true;
}

// ---------------------------------------------------------------------- //
//                        STRINGS SIMPLES                                 //
// ---------------------------------------------------------------------- //

// s tiene solo letras
function isAlphabetic (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }
    return true;
}


// s tiene solo letras y numeros
function isAlphanumeric (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    return true;
}

// s tiene solo letras, numeros o espacios en blanco
function isName (s)
{
    if (isEmpty(s)) 
       if (isName.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);
    
    return( isAlphanumeric( stripCharsInBag( s, whitespace ) ) );
}

// ---------------------------------------------------------------------- //
//                           FONO o EMAIL                                 //
// ---------------------------------------------------------------------- //

// s es numero de telefono valido
function isPhoneNumber (s)
{   var modString;
    if (isEmpty(s)) 
       if (isPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isPhoneNumber.arguments[1] == true);
    modString = stripCharsInBag( s, phoneChars );
    return (isInteger(modString))
}

// s es una direccion de correo valida
function isEmail (s)
{
    if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
    if (isWhitespace(s)) return false;
    var i = 1;
    var sLength = s.length;
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

function isNice(s)
{
        var i = 1;
        var sLength = s.length;
        var b = 1;
        while(i<sLength) {
                if( (s.charAt(i) == "\"") || (s.charAt(i) == "'" ) ) b = 0;
                i++;
        }
        return b;
}

// ---------------------------------------------------------------------- //
//                  FUNCIONES PARA RECLAMARLE AL USUARIO                  //
// ---------------------------------------------------------------------- //

// pone el string s en la barra de estado
function statBar (s)
{   window.status = s
}

// notificar que el campo theField esta vacio
function warnEmpty (theField)
{   theField.focus()
    alert(mMessage)
    statBar(mMessage)
    return false
}

// notificar que el campo theField es invalido
function warnInvalid (theField, s)
{   theField.focus()
    theField.select()
    alert(s)
    statBar(pPrompt + s)
    return false
}

// el corazon de todo: checkField
function checkField (theField, theFunction, emptyOK, s)
{   
    var msg;
    if (checkField.arguments.length < 3) emptyOK = defaultEmptyOK;
    if (checkField.arguments.length == 4) {
        msg = s;
    } else {
        if( theFunction == isAlphabetic ) msg = pAlphabetic;
        if( theFunction == isAlphanumeric ) msg = pAlphanumeric;
        if( theFunction == isInteger ) msg = pInteger;
        if( theFunction == isNumber ) msg = pNumber;
        if( theFunction == isEmail ) msg = pEmail;
        if( theFunction == isPhoneNumber ) msg = pPhoneNumber;
        if( theFunction == isName ) msg = pName;
    }
    
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;

    if ((emptyOK == false) && (isEmpty(theField.value))) 
        return warnEmpty(theField);

    if ( checkNiceness && !isNice(theField.value))
        return warnInvalid(theField, pNice);

    if (theFunction(theField.value) == true) 
        return true;
    else
        return warnInvalid(theField,msg);

}

// ---------------------------------------------------------------------- //
//                  FUNCIONES PARA EL TRIM                  //
// ---------------------------------------------------------------------- //

function Trim( str ) {
	var resultStr = "";
	
	resultStr = TrimLeft(str);
	resultStr = TrimRight(resultStr);
	
	return resultStr;
}

function TrimLeft( str ) {
	var resultStr = "";
	var i = len = 0;

	// Return immediately if an invalid value was passed in
	if (str+"" == "undefined" || str == null)	
		return null;

	// Make sure the argument is a string
	str += "";

	if (str.length == 0) 
		resultStr = "";
	else {	
  		// Loop through string starting at the beginning as long as there
  		// are spaces.
//	  	len = str.length - 1;
		len = str.length;
		
  		while ((i <= len) && (str.charAt(i) == " "))
			i++;

   	// When the loop is done, we're sitting at the first non-space char,
 		// so return that char plus the remaining chars of the string.
  		resultStr = str.substring(i, len);
  	}

  	return resultStr;
}

function TrimRight( str ) {
	var resultStr = "";
	var i = 0;

	// Return immediately if an invalid value was passed in
	if (str+"" == "undefined" || str == null)	
		return null;

	// Make sure the argument is a string
	str += "";
	
	if (str.length == 0) 
		resultStr = "";
	else {
  		// Loop through string starting at the end as long as there
  		// are spaces.
  		i = str.length - 1;
  		while ((i >= 0) && (str.charAt(i) == " "))
 			i--;
 			
 		// When the loop is done, we're sitting at the last non-space char,
 		// so return that char plus all previous chars of the string.
  		resultStr = str.substring(0, i + 1);
  	}
  	
  	return resultStr;  	
}

// ---------------------------------------------------------------------- //
//                  FUNCIONES PARA VALIDAR CARACTERES ESPECIALES                  //
// ---------------------------------------------------------------------- //
function Validar_pagina(valor){
var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_1234567890//.:";
var checkStr = valor;
var allValid = true;
  for (i = 0; i < checkStr.length; i++) {
    ch = checkStr.charAt(i);
    for (j = 0; j < checkOK.length; j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length) {
      allValid = false;
      break;
    }
  }
 if (!allValid) {
	return (false);
  }
  else{
	return true;
  }
}

function Enviar(Form){
	if(Form.accion.value==0) 
	{
	alert("Revise los campos del formulario existen caracteres no validos...");
	return false;
	}
	else return true;
}

//
//-----------------------------------------------------------------------------
// Funciones de conversión entre VBScript y JavaScript				(15/Mar/99)
//
// (c)Guillermo 'guille' Som, 1999
//
//-----------------------------------------------------------------------------
// Las funciones son:
//		Left, Right, Mid, LTrim, RTrim, Trim, InStr, RInStr, Space, 
//		jString (esta se llamará así, ya que String es una palabra reservada)
//		UCase, LCase, Len, 
// Otras funciones adicionales:
//		StrReverse
// Constantes:
//		vbCrLf, vbCr, vbLf, vbTab, 
//
//-----------------------------------------------------------------------------
// Códigos escape:
//
// \b = Backspace
// \f = Form feed
// \n = Line feed
// \r = Carriage return
// \t = Horizontal tab
//-----------------------------------------------------------------------------
// 
// Nota: 
// Para que todo funcione bien, hay que respetar el estado de las instrucciones
// es decir: cuidado con las mayúsculas/minúsculas.
//
//-----------------------------------------------------------------------------
//

//
//-----------------------------------------------------------------------------
// Constantes
var vbCr = "\r";
var vbLf = "\n";
var vbCrLf = vbCr+vbLf;
var vbTab = "\t";

function Left(s, n){
	// Devuelve los n primeros caracteres de la cadena
	if(n>s.length)
		n=s.length;
		
	return s.substring(0, n);
}
function Right(s, n){
	// Devuelve los n últimos caracteres de la cadena
	var t=s.length;
	if(n>t)
		n=t;
		
	return s.substring(t-n, t);
}
function Mid(s, n, c){
	// Devuelve una cadena desde la posición n, con c caracteres
	// Si c = 0 devolver toda la cadena desde la posición n
	
	var numargs=Mid.arguments.length;
	
	// Si sólo se pasan los dos primeros argumentos
	if(numargs<3)
		c=s.length-n+1;
		
	if(c<1)
		c=s.length-n+1;
	if(n+c >s.length)
		c=s.length-n+1;
	if(n>s.length)
		return "";
		
	return s.substring(n-1,n+c-1);
}
function InStr(n, s1, s2){
	// Devuelve la posición de la primera ocurrencia de s2 en s1
	// Si se especifica n, se empezará a comprobar desde esa posición
	// Sino se especifica, los dos parámetros serán las cadenas
	var numargs=InStr.arguments.length;
	
	if(numargs<3)
		return n.indexOf(s1)+1;
	else
		return s1.indexOf(s2, n)+1;
}
function RInStr(n, s1, s2){
	// Devuelve la posición de la última ocurrencia de s2 en s1
	// Si se especifica n, se empezará a comprobar desde esa posición
	// Sino se especifica, los dos parámetros serán las cadenas
	var numargs=RInStr.arguments.length;
	
	if(numargs<3)
		return n.lastIndexOf(s1)+1;
	else
		return s1.lastIndexOf(s2, n)+1;
}
function Space(n){
	// Devuelve una cadena con n espacios
	var t="";
	
	for(var i=1; i<=n; i++)
		t=t+" ";
	
	return t;
}
function jString(n, c){
	// Devuelve n veces el caracter c
	var t="";
	
	for(var i=1; i<=n; i++)
		t=t+c;

	return t;
}
function UCase(s){
	// Devuelve la cadena convertida a mayúsculas
	return s.toUpperCase();
}
function LCase(s){
	// Devuelve la cadena convertida en minúsculas
	return s.toLowerCase();
}
function Len(s){
	// Devuelve la longitud de la cadena s
	return s.length;
}
function StrReverse(s){
	// Invierte la cadena
	var i=s.length;
	var t="";
	
	while(i>-1){
		t=t+ s.substring(i,i+1);
		i--;
	}
	return t;
}
//
//-----------------------------------------------------------------------------
// Fin del código con las funciones de conversión de VBScript para JavaScript
//-----------------------------------------------------------------------------
//

//-->

//Transformacion del Formato fecha del archivo FormatosVarios.vbs a Javascript
/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

// Función AJAX
function nuevoAjax()
{ 
	/* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, por
	lo que se puede copiar tal como esta aqui */
	var xmlhttp=false; 
	try 
	{ 
		// Creacion del objeto AJAX para navegadores no IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
	}
	catch(e)
	{ 
		try
		{ 
			// Creacion del objet AJAX para IE 
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
		} 
		catch(E) { xmlhttp=false; }
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp=new XMLHttpRequest(); } 

	return xmlhttp; 
}

function mOvr(src,clrOver) {
	if (document.layers) {
    	obj = document.layer.src; 
	}
	else {
    	obj = src; 
	}
	//if (!src.contains(event.fromElement)) 
	//{
	obj.style.cursor = 'pointer';
	obj.style.backgroundImage = "url("+clrOver+")";
	//}
}
function mOut(src,clrIn) {
	if (document.layers) {
    	obj = document.layer.src; 
	}
	else {
    	obj = src; 
	}
	//if (!src.contains(event.toElement)) {
	obj.style.cursor = 'pointer';
	obj.style.backgroundImage = "url("+clrIn+")";
	//}
}


// Funciones para el portal de la Gerencia de Recursos Humanos del SENIAT
function cerrar_sesion(modulo){
	cargarModulo(modulo);
	document.getElementById("variable_cerrar").value=1;
	document.formulario.submit();
}

function solo_numero(e){
	tecla_codigo = (document.all) ? e.keyCode : e.which;
	if(tecla_codigo==8 || tecla_codigo==0 || tecla_codigo==13)return true;
	patron =/[0-9]/;
	tecla_valor = String.fromCharCode(tecla_codigo);
	return patron.test(tecla_valor);
}

function solo_alfanumero(e){
	tecla_codigo = (document.all) ? e.keyCode : e.which;
	if(tecla_codigo==8 || tecla_codigo==0 || tecla_codigo==13)return true;
	patron =/[0-9,A-Z,a-z,@,\.,\_,\-]/;
	tecla_valor = String.fromCharCode(tecla_codigo);
	return patron.test(tecla_valor);
}

function solo_letra(e){
	tecla_codigo = (document.all) ? e.keyCode : e.which;
	if(tecla_codigo==8 || tecla_codigo==0)return true;
	patron =/[A-Z,a-z, ,á,é,í,ó,ú]/;
	tecla_valor = String.fromCharCode(tecla_codigo);
	return patron.test(tecla_valor);
}

function numero_telefono(e){
	tecla_codigo = (document.all) ? e.keyCode : e.which;
	if(tecla_codigo==8 || tecla_codigo==0 || tecla_codigo==32)return true;
	patron =/[0-9,(,)]/;
	tecla_valor = String.fromCharCode(tecla_codigo);
	return patron.test(tecla_valor);
}

function cargarModulo(modulo){
	document.getElementById("modulo").value=modulo;
}
function cargarVariable(valor){
	document.getElementById("variable").value=valor;
}
function cargarModuloInterno(modulo_interno){
	document.getElementById("modulo_interno").value=modulo_interno;
}
function enviarFormulario(){
	document.formulario.submit();
}
function validar_email(valor){
	patron=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
	if (patron.test(valor)){
		return (true);
	} 
	else {
		return (false);
	}
}
// Funciones de carga de modulos del sistema de Gerencia de Recursos Humanos del SENIAT
function cargarUnElemento(url, obj, area_carga, elemento_ajax)
{
	//document.getElementById(limpiar).innerHTML="&nbsp;";
	var valor=obj.options[obj.selectedIndex].value;
	elemento_ajax=nuevoAjax();
	var aleatorio=Math.random();
	elemento_ajax.open("GET", url+"?seleccionado="+valor+"&aleatorio="+aleatorio, true);
	elemento_ajax.onreadystatechange=function() 
	{ 
		if (elemento_ajax.readyState==1)
		{
			// Mientras carga elimino la opcion "Selecciona la ciudad" y pongo una que dice "Cargando"
			document.getElementById(area_carga).innerHTML="Cargando...";	
		}
		if (elemento_ajax.readyState==4)
		{ 
			document.getElementById(area_carga).innerHTML=elemento_ajax.responseText;
		} 
	}
	elemento_ajax.send(null);
}

function cargarHTML(area_carga, pagina){
	elemento_ajax=nuevoAjax();
	var aleatorio=Math.random();
	if(pagina.indexOf('?')==-1){
		cadena_envio=pagina+"?aleatorio="+aleatorio;
	}
	else{
		cadena_envio=pagina+"&aleatorio="+aleatorio;
	}
	elemento_ajax.open("GET", cadena_envio, true);
	elemento_ajax.onreadystatechange=function() 
	{ 
		if (elemento_ajax.readyState==1)
		{
			// Mientras carga elimino la opcion "Selecciona la ciudad" y pongo una que dice "Cargando"
			document.getElementById(area_carga).innerHTML="Cargando...";	
		}
		if (elemento_ajax.readyState==4)
		{ 
			document.getElementById(area_carga).innerHTML=elemento_ajax.responseText;
		} 
	}
	elemento_ajax.send(null);
}

function cargarUnValor(url, valor, area_carga, elemento_ajax)
{
	//document.getElementById(limpiar).innerHTML="&nbsp;";
	elemento_ajax=nuevoAjax();
	var aleatorio=Math.random();
	elemento_ajax.open("GET", url+"?seleccionado="+valor+"&aleatorio="+aleatorio, true);
	elemento_ajax.onreadystatechange=function() 
	{ 
		if (elemento_ajax.readyState==1)
		{
			// Mientras carga elimino la opcion "Selecciona la ciudad" y pongo una que dice "Cargando"
			document.getElementById(area_carga).innerHTML="Cargando...";	
		}
		if (elemento_ajax.readyState==4)
		{ 
			document.getElementById(area_carga).innerHTML=elemento_ajax.responseText;
		} 
	}
	elemento_ajax.send(null);
}

function abrirventana(url)
{
  // se crea la ventana
 ventana=window.open(url,"_blank","width=600,height=400,scrollbars=yes,resizable=yes,location=no,toolbar=yes");
}

function oNumero(numero)
{
	//Propiedades
	this.valor = numero || 0
	this.dec = -1;
	//Métodos
	this.formato = numFormat;
	this.ponValor = ponValor;

	//Definición de los métodos
	function ponValor(cad)
	{
		if (cad =='-' || cad=='+') return
		if (cad.length ==0) return
		if (cad.indexOf('.') >=0)
			this.valor = parseFloat(cad);
		else
			this.valor = parseInt(cad);
	}
	function numFormat(dec, miles)
	{
		var num = this.valor, signo=3, expr;
		var cad = ""+this.valor;
		var ceros = "", pos, pdec, i;
		for (i=0; i < dec; i++)
		ceros += '0';
		pos = cad.indexOf(',')
		if (pos < 0)
			cad = cad+","+ceros;
		else
			{
			pdec = cad.length - pos -1;
			if (pdec <= dec)
				{
				for (i=0; i< (dec-pdec); i++)
					cad += '0';
				}
			else
				{
				num = num*Math.pow(10, dec);
				num = Math.round(num);
				num = num/Math.pow(10, dec);
				cad = new String(num);
				}
			}
		pos = cad.indexOf(',')
		if (pos < 0) pos = cad.lentgh
		if (cad.substr(0,1)=='-' || cad.substr(0,1) == '+')
			   signo = 4;
		if (miles && pos > signo)
			do{
				expr = /([+-]?\d)(\d{3}[\.\,]\d*)/
				cad.match(expr)
				cad=cad.replace(expr, RegExp.$1+'.'+RegExp.$2)
				}
		while (cad.indexOf('.') > signo)
			if (dec<0) cad = cad.replace(/\./,'')
				return cad;
	}
}
function solo_numero_decimal(e){
	tecla_codigo = (document.all) ? e.keyCode : e.which;
	if(tecla_codigo==8 || tecla_codigo==0)return true;
	patron =/[0-9,',','.']/;
	tecla_valor = String.fromCharCode(tecla_codigo);
	return patron.test(tecla_valor);
}

//First things first, set up our array that we are going to use.
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + //all caps
"abcdefghijklmnopqrstuvwxyz" + //all lowercase
"0123456789+/="; // all numbers plus +/=

function encripto(inp)
{
	var out = ""; //This is the output
	var chr1, chr2, chr3 = ""; //These are the 3 bytes to be encoded
	var enc1, enc2, enc3, enc4 = ""; //These are the 4 encoded bytes
	var i = 0; //Position counter

	do { //Set up the loop here
		chr1 = inp.charCodeAt(i++); //Grab the first byte
		chr2 = inp.charCodeAt(i++); //Grab the second byte
		chr3 = inp.charCodeAt(i++); //Grab the third byte

		//Here is the actual base64 encode part.
		//There really is only one way to do it.
		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;

		if (isNaN(chr2)) {
			enc3 = enc4 = 64;
		} else if (isNaN(chr3)) {
			enc4 = 64;
		}

		//Lets spit out the 4 encoded bytes
		out = out + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) +
		keyStr.charAt(enc4);

		// OK, now clean out the variables used.
		chr1 = chr2 = chr3 = "";
		enc1 = enc2 = enc3 = enc4 = "";

	} while (i < inp.length); //And finish off the loop

	//Now return the encoded values.
	return out;
}

function desencripto(inp)
{
	var out = ""; //This is the output
	var chr1, chr2, chr3 = ""; //These are the 3 decoded bytes
	var enc1, enc2, enc3, enc4 = ""; //These are the 4 bytes to be decoded
	var i = 0; //Position counter

	// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
	var base64test = /[^A-Za-z0-9\+\/\=]/g;

	if (base64test.exec(inp)) { //Do some error checking
		alert("There were invalid base64 characters in the input text.\n" +
		"Valid base64 characters are A-Z, a-z, 0-9, ?+?, ?/?, and ?=?\n" +
		"Expect errors in decoding.");
	}
	inp = inp.replace(/[^A-Za-z0-9\+\/\=]/g, "");

	do { //Here.s the decode loop.

		//Grab 4 bytes of encoded content.
		enc1 = keyStr.indexOf(inp.charAt(i++));
		enc2 = keyStr.indexOf(inp.charAt(i++));
		enc3 = keyStr.indexOf(inp.charAt(i++));
		enc4 = keyStr.indexOf(inp.charAt(i++));

		//Heres the decode part. There.s really only one way to do it.
		chr1 = (enc1 << 2) | (enc2 >> 4);
		chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
		chr3 = ((enc3 & 3) << 6) | enc4;

		//Start to output decoded content
		out = out + String.fromCharCode(chr1);

		if (enc3 != 64) {
			out = out + String.fromCharCode(chr2);
		}
		if (enc4 != 64) {
			out = out + String.fromCharCode(chr3);
		}

		//now clean out the variables used
		chr1 = chr2 = chr3 = "";
		enc1 = enc2 = enc3 = enc4 = "";

	} while (i < inp.length); //finish off the loop

	//Now return the decoded values.
	return out;
}

function abrirpagina(url)
{
  // se crea la ventana
 ventana=window.open(url,"_blank","width=800,height=600,scrollbars=yes,resizable=yes,location=no,toolbar=yes");
}

function cargaPOST(url,capa,valores){
	var ajax=nuevoAjax();
	var capaContenedora = document.getElementById(capa);
	var aleatorio=Math.random();
	ajax.open ('POST', url, true);
	ajax.onreadystatechange = function() {
		if (ajax.readyState==1) {
			capaContenedora.innerHTML="Cargando...";
		}
		if (elemento_ajax.readyState==4){ 
			capaContenedora.innerHTML=ajax.responseText;
		}
	}
	ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	ajax.send(valores+"&"+aleatorio);
	return;
}

function abrirvideo(url)
{
	ventana=window.open(url,"_blank","width=325,height=245,scrollbars=no,resizable=no,location=no,toolbar=no");
}

function calculadora(){
	window.open('http://www.seniat.gov.ve/pls/portal/docs/PAGE/SENIAT_CA/SISTEMAS_EN_LINEA2/GUIAS_CONTRIBUYENTES/DEL_CONTRIBUYENTE/CALCBSF.HTM','_blank','width=165,height=180,scrollbars=no,resizable=no,location=no,toolbar=no');	
}

function cambiarColor(celda, estado){
	if(estado==1){ // Over
		celda.style.backgroundColor="#CCCCCC";
	}
	if(estado==2){ // Out
		celda.style.backgroundColor="#006699";
	}
}
