/***********************************************************************
Função para Mostrar/Esconder um Objeto
************************************************************************/
function fShowHide(pobj)
{
 if (pobj.style.visibility=='hidden')
 {
  pobj.style.visibility='';
 }
 else
 {
  pobj.style.visibility='hidden';
 }
}



/***********************************************************************
Função para Retornar o Index da chave pesquisada. Caso não encontre, retorna -1
Parametros:
			oSelect		= Objeto SELECT do formulário
			pChave		= Valor da Chave que deseja procurar
			pTipo		= 0=IGUAL, 1=INICIO, 2=CONTEM
			pSel		= Seleciona o Item? true ou false
************************************************************************/
function fComboFind(oSelect, pChave, pTipo, pSel)
{
 	var i;
    // Varre o SELECT procurando a chave
    for(i = 0; i < oSelect.length; i++)
    {
    	if (pTipo==0)
    	{
	        if(oSelect.options[i].value == pChave)
    	    {
    			if (pSel) {
    				oSelect.options[i].selected = true;
    			}
	        	return i;
    	    }
    	}
    	else if (pTipo==1)
    	{
    		if(Left(oSelect.options[i].value, Len(pChave))==pChave)
    		{
    			if (pSel) {
    				oSelect.options[i].selected = true;
    			}
    			return i;
    		}
    	}
    	else if (pTipo==2)
    	{
    		if(InStr(oSelect.options[i].value, pChave)>0)
    		{
    			if (pSel) {
    				oSelect.options[i].selected = true;
    			}
    			return i;
    		}
    	}
    }
    return -1;
}


/*******************************************************************
  Adiciona um Elemento para um ComboBox
  Parametros:
  				pNomeObj	=	Nome do objeto <SELECT> do formulario
  				pVlr		=	Valor que o novo elemento vai ter
  				pTxt		=	Texto que vai aparecer na Combo para o Novo elemento
  				pPesq		=	Flag que indica se deve pesquisar novo valor e colocar
  								como selecionado na Combo (0=Não; 1=Sim)
********************************************************************/
function fComboAdd(pNomeObj, pVlr, pTxt, pPesq)
{
	var vIndex;
	vIndex = document.getElementById(pNomeObj).selectedIndex;
	ComboAdd(document.getElementById(pNomeObj),pVlr, pTxt);
	if (pPesq==1)
	{
		document.getElementById(pNomeObj+'_txt').value=pTxt;
		fComboSearch(document.getElementById(pNomeObj), pVlr);
	}
	else
	{
		document.getElementById(pNomeObj).selectedIndex = vIndex;
	}
}


/*******************************************************************
  Função que Coloca ZEROS a ESQUERDA em uma STRING
  Pode ser usada no evento ONBLUR do campo.
  parametros:
  				pTxt	= Valor que será preenchido com Zeros a Esquerda
  				pTam	= Tamanho total que a String deve ficar
  						  incluindo os ZEROS a ESQUERDA
*******************************************************************/
function fPoeZero(pTxt, pTam)
{
	if (Trim(pTxt)=='')
	{
		return '';
	}
	return Right(ReturnString(pTam, '0') + Trim(pTxt),pTam);
}



/*******************************************************************
  Função que Coloca ANO com 4 digitos, segundo o ano limite e os
  seculos passados.
  parametros:
			pTxt		= Ano que será formatado
			pAnoLimite	= Ano limite de conversão. Se o ano
						  passado em pTxt for >= a este valor,
						  sera somado pSeculo1 senão pSeculo2
			pSeculo1	= Seculo que será somado caso pTxt>=pAnoLimite
			pSeculo2	= Seculo que será somado caso pTxt<pAnoLimite
 Default:
 			pAnoLimite	= 40
 			pSeculo1	= 1900
 			pSeculo2	= 2000
*******************************************************************/
function fPoeAno(pTxt, pAnoLimite, pSeculo1, pSeculo2)
{
	if (Trim(pTxt)=='')
	{
		return '';
	}
	if (Len(Trim(pTxt))>=3)
	{
		return pTxt;
	}
	if (pAnoLimite==null)
	{
		pAnoLimite=40;
	}
	if (pSeculo1==null)
	{
		pSeculo1=1900;
	}
	if (pSeculo2==null)
	{
		pSeculo2=2000;
	}
	if (parseInt(Trim(pTxt))>=pAnoLimite)
	{
		return pSeculo1+parseInt(Trim(pTxt));
	}
	else
	{
		return pSeculo2+parseInt(Trim(pTxt));
	}
}



/*******************************************************************
  Função que Valida um campo Hora (HH:MM)
  parametros:
			pObjHora	= Objeto INPUT a ser validado
			pDesc		= Texto descritivo do Objeto (usado para alert)
			pPodeVazio	= boolean que indica se pode ficar vazio
*******************************************************************/
function fHora(pObjHora,pDesc,pPodeVazio)
{
	if (pObjHora.value=='')
	{
		return pPodeVazio;
	}
	
	if (Mask(pObjHora.value, '9999'))
	{
		pObjHora.value = Left(pObjHora.value,2)+':'+Right(pObjHora.value,2);
	}
	if (Mask(pObjHora.value, '99'))
	{
		pObjHora.value = pObjHora.value+':00';
	}
	if (!(Mask(pObjHora.value, '99:99')))
	{
		alert(pDesc+': Deve ser no Formato HH:MM !!!');
		pObjHora.focus();
		return false;
	}
	else
	{
		vHor = parseFloat(Left(pObjHora.value,2));
		vMin = parseFloat(Right(pObjHora.value,2));
		if (vHor<0 || vHor>23)
		{
			alert(pDesc+': Hora deve ser entre 00-23 !!!');
			pObjHora.focus();
			return false;
		}
		if (vMin<0 || vMin>59)
		{
			alert(pDesc+': Minuto deve ser entre 00-59 !!!');
			pObjHora.focus();
			return false;
		}
	}
	return true;
}



/**************************************************************
 Mask: Returns a Boolean if the specified Expression match
       the specified Mask.

 Parameters:
      Expression = String to validate
      Mask       = String that can contain the following
                   options:
                   9 = only numbers (0..9)
                   X = only letters (a..z or A..Z)
                   * = Anything...
 Example: alert(Mask("(954) 572-4419", "(999) 999-9999")); => TRUE
          alert(Mask("33351-820", "99999-9999"));          => FALSE
          alert(Mask("This is a test", "XXXXXX"));         => FALSE
          alert(Mask("This 34 a test", "**************")); => TRUE

 Returns: Boolean
***************************************************************/
function Mask(Expression, Mask)
{
	Mask = Mask.toUpperCase();
	LenStr = Expression.length;
	LenMsk = Mask.length;
	if ((LenStr == 0) || (LenMsk == 0))
	{
		return (false);
	}
	if (LenStr != LenMsk)
	{
		return (false);
	}
	TempString = '';
	for (Count = 0; Count <= Expression.length; Count++)
	{
		StrChar = Expression.substring(Count, Count + 1);
		MskChar = Mask.substring(Count, Count + 1);
		if (MskChar == '9')
		{
			if(!IsNumber(StrChar))
			{
				return (false);
			}
		}
		else if (MskChar == 'X')
		{
			if(!IsChar(StrChar))
			{
				return (false);
			}
		}
		else if (MskChar == '*')
		{
			if(!IsAlphanumeric(StrChar))
			{
				return (false);
			}
		}
		else
		{
			if (MskChar != StrChar)
			{
				return (false);
			}
		}
	}
	return (true);
}


/**************************************************************
 AllowOnly: This function allow entering just the specified
            Expression to a textbox or textarea control.

 Parameters:
      Expression = Allowed characters.
                   a..z => ONLY LETTERS
                   0..9 => ONLY NUMBERS
                   other symbols...

 Example: use the onKeyPress event to make this function work:
          //Allows only from A to Z
          onKeyPress="AllowOnly('a..z');"

          //Allows only from 0 to 9
          onKeyPress="AllowOnly('0..9');"

          //Allows only A,B,C,1,2 and 3
          onKeyPress="AllowOnly('abc123');"

          //Allows only A TO Z,@,#,$ and %
          onKeyPress="AllowOnly('a..z|@#$%');"

                  //Allows only A,B,C,0 TO 9,.,,,+ and -
          onKeyPress="AllowOnly('ABC|0..9|.,+-');"

 Remarks: Use the pipe "|" symbol to separate a..z from 0..9 and symbols

 Returns: None
***************************************************************/
function AllowOnly(Expression)
{
	Expression = Expression.toLowerCase();
	Expression = Replace(Expression, 'a..z', 'abcdefghijklmnopqrstuvwxyz');
	Expression = Replace(Expression, '0..9', '0123456789');
	Expression = Replace(Expression, '|', '');
	var ch = String.fromCharCode(window.Event.which);
	ch = ch.toLowerCase();
	Expression = Expression.toLowerCase();
	var a = Expression.indexOf(ch);
	if (a == -1)
	{
		window.Event.keyCode = 0;
	}
}


/**************************************************************
 LeapYear: Return a Boolean if the speficied Year is a Leap
           Year

 Parameters:
      Year = Numeric expression that represents the Year.

 Returns: Boolean
***************************************************************/
function LeapYear(Year)
{
	if(Year % 4 == 0 && Year % 100 != 0 || Year % 400 ==0)
	{
		return true;
	}
	return false;
}



/**************************************************************
 IsDate: Returns a Boolean (true) if the date is true, false
         is not

 Parameters:
        - DateStr: String date in format (DD/MM/YYYY)

 Returns: Boolean
***************************************************************/
function IsDate(dateStr)
{
	// Checks for the following valid date formats:
	// DD/MM/YYYY   DD-MM-YYYY

	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

	var matchArray = dateStr.match(datePat);
	if (matchArray == null)
	{
		return false;
	}

	month = matchArray[3];
	day = matchArray[1];
	year = matchArray[4];

	if (month < 1 || month > 12)
	{
		return false;
	}

	if (day < 1 || day > 31)
	{
		return false;
	}

	if ((month==4 || month==6 || month==9 || month==11) && day==31)
	{
		return false;
	}

	if (month == 2)
	{
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap))
		{
			return false;
		}
	}
	return true;
}



/**************************************************************
 Abs: Returns a value of the same type that is passed to it
      specifying the absolute value of a number.

 Parameters:
      Number = The required number argument can be any valid
               numeric expression. If number contains Null,
               false is returned; if it is an uninitialized
               variable, false is returned.

 Returns: Long
***************************************************************/
function Abs(Number)
{
	Number = Number.toLowerCase();
	RefString = "0123456789.-";

	if (Number.length < 1)
	{
		return (false);
	}

	for (var i = 0; i < Number.length; i++)
	{
		var ch = Number.substr(i, 1);
		var a = RefString.indexOf(ch, 0);
		if (a == -1)
		{
			return (false);
		}
	}

	if (Number < 0)
	{
		return (Number * -1);
	}

	return Number;
}



/**************************************************************
 Len: Returns a Long containing the number of characters in a
      string or the number of bytes required to store a
      variable.

 Parameters:
      string = Any valid string expression. If string contains
               null, false is returned.

 Returns: Long
***************************************************************/
function Len(string)
{
	if (string == null)
	{
		return (false);
	}

	return String(string).length;
}



/**************************************************************
 Chr: Returns a String containing the character associated
      with the specified character code.

 Parameters:
      CharCode = Long that identifies a character.

 Returns: String
***************************************************************/
function Chr(CharCode)
{
	return String.fromCharCode(CharCode);
}



/**************************************************************
 Asc: Returns an Integer representing the character code
      corresponding to the first letter in a string

 Parameters:
      String = The required string argument is any valid
               string expression. If the string if not in
               the range 32-126, the function return ZERO

 Returns: Integer
***************************************************************/
function Asc(string)
{
	var symbols = " !\"#$%&'()*+'-./0123456789:;<=>?@";
	var loAZ = "abcdefghijklmnopqrstuvwxyz";
	symbols += loAZ.toUpperCase();
	symbols += "[\\]^_`";
	symbols += loAZ;
	symbols += "{|}~";
	var loc;
	loc = symbols.indexOf(string);
	if (loc > -1)
	{
		Ascii_Decimal = 32 + loc;
		return (32 + loc);
	}
	return (0);
}



/**************************************************************
 LTrim: Returns a String containing a copy of a specified
        string without leading spaces

 Parameters:
      String = The required string argument is any valid
               string expression. If string contains null,
               false is returned

 Returns: String
***************************************************************/
function LTrim(String)
{
	var i = 0;
	var j = String.length - 1;

	if (String == null)
	{
		return (false);
	}

	for (i = 0; i < String.length; i++)
	{
		if (String.substr(i, 1) != ' ' && String.substr(i, 1) != '\t')
		{
			break;
		}
	}

	if (i <= j)
	{
		return (String.substr(i, (j+1)-i));
	}
	else
	{
		return ('');
	}
}



/**************************************************************
 RTrim: Returns a String containing a copy of a specified
        string without trailing spaces

 Parameters:
      String = The required string argument is any valid
               string expression. If string contains null,
               false is returned

 Returns: String
***************************************************************/
function RTrim(String)
{
	var i = 0;
	var j = String.length - 1;

	if (String == null)
	{
		return (false);
	}

	for(j = String.length - 1; j >= 0; j--)
	{
		if (String.substr(j, 1) != ' ' && String.substr(j, 1) != '\t')
		{
			break;
		}
	}

	if (i <= j)
	{
		return (String.substr(i, (j+1)-i));
	}
	else
	{
		return ('');
	}
}



/**************************************************************
 RTrim: Returns a String containing a copy of a specified
        string without both leading and trailing spaces

 Parameters:
      String = The required string argument is any valid
               string expression. If string contains null,
               false is returned

 Returns: String
***************************************************************/
function Trim(String)
{
	if (String == null)
	{
		return (false);
	}

	return RTrim(LTrim(String));
}



/**************************************************************
 Left: Returns a String containing a specified number of
       characters from the left side of a string.

 Parameters:
      String = String expression from which the leftmost
               characters are returned. If string contains null,
               false is returned.
      Length = Numeric expression indicating how many characters
               to return. If 0, a zero-length string ("") is
               returned. If greater than or equal to the number
               of characters in string, the entire string is
               returned.

 Returns: String
***************************************************************/
function Left(String, Length)
{
	if (String == null)
	{
		return (false);
	}

	return String.substr(0, Length);
}



/**************************************************************
 Right: Returns a String containing a specified number of
        characters from the right side of a string.

 Parameters:
      String = String expression from which the leftmost
               characters are returned. If string contains null,
               false is returned.
      Length = Numeric expression indicating how many characters
               to return. If 0, a zero-length string ("") is
               returned. If greater than or equal to the number
               of characters in string, the entire string is
               returned.

 Returns: String
***************************************************************/
function Right(String, Length)
{
	if (String == null)
	{
		return (false);
	}

    var dest = '';
    for (var i = (String.length - 1); i >= 0; i--)
    {
		dest = dest + String.charAt(i);
	}

	String = dest;
	String = String.substr(0, Length);
	dest = '';

    for (var i = (String.length - 1); i >= 0; i--)
    {
		dest = dest + String.charAt(i);
	}

	return dest;
}



/**************************************************************
 Mid: Returns a String containing a specified number of
      characters from a string

 Parameters:
      String = String expression from which characters are
               returned. If string contains null, false is
               returned.
      Start  = Number. Character position in string at which
               the part to be taken begins. If Start is
               greater than the number of characters in
               string, Mid returns a zero-length string ("").
      Length = Number of characters to return. If omitted
               false is returned.

 Returns: String
***************************************************************/
function Mid(String, Start, Length)
{
	if (String == null)
	{
		return (false);
	}

	if (Start > String.length)
	{
		return '';
	}

	if (Length == null || Length.length == 0)
	{
		return (false);
	}

	return String.substr((Start - 1), Length);
}



/**************************************************************
 InStr: Returns a Long specifying the position of the first
        occurrence of one string within another. Is String1
        or String2 are null, false is returned.

 Parameters:
      String1 = String expression being searched.
      String2 = String expression sought

 Returns: Integer
***************************************************************/
function InStr(String1, String2)
{
	var a = 0;

	if (String1 == null || String2 == null)
	{
		return (false);
	}

	String1 = String1.toLowerCase();
	String2 = String2.toLowerCase();

	a = String1.indexOf(String2);
	if (a == -1)
	{
		return 0;
	}
	else
	{
		return a + 1;
	}
}


/**************************************************************
 LBound: Returns a Long containing the smallest available
         subscript for the indicated dimension of an array

 Parameters:
      array = Array to verify

 Returns: Integer       (-1 if Array does not contain
                            any subscript)
***************************************************************/
function LBound(array)
{
	var i = 0;
	var temp = '';

	if (array.length == 0)
	{
		return (-1);
	}

	for (i = 0; i < array.length; i++)
	{
		temp = array[i];
		if (temp != null)
		{
			var temp = i;
			return temp;
		}
	}
        return (-1);
}



/**************************************************************
 UBound: Returns a Long containing the largest available
         subscript for the indicated dimension of an array

 Parameters:
      array = Array to verify

 Returns: Integer       (-1 if Array does not contain
                            any subscript)
***************************************************************/
function UBound(array)
{
	return (array.length - 1);
}



/**************************************************************
 Join: Returns a string created by joining a number of
       substrings contained in an array.

 Parameters:
      array     = One-dimensional array containing substrings
                  to be joined
      Delimiter = String character used to separate the
                  substrings in the returned string.
                  If delimiter is a zero-length string (""),
                  all items in the list are concatenated
                  with no delimiters.

 Returns: String
***************************************************************/
function Join(array, Delimiter)
{
	var temp = '';

	if (array.length == 0)
	{
		return '';
	}

	if (Delimiter.length == 0)
	{
		Delimiter = ' ';
	}

	for (var i = 0; i < array.length; i++)
	{
		temp = temp + array[i];
		if (i < array.length - 1)
		{
			temp = temp + Delimiter;
		}
	}
	return temp;
}



/**************************************************************
 ReturnString: Returns a String containing a repeating
               character string of the length specified

 Parameters:
      Number    = Length of the returned string. If number
                  is less than 1, false is returned.
      Character = Character code specifying the character or
                  string expression whose first character is
                  used to build the return string. If character
                  contains null, false is returned.

 Returns: String
***************************************************************/
function ReturnString(Number, Character)
{
	var temp = '';

	if (Number < 1)
	{
		return (false);
	}

	if (Character.length == 0)
	{
		return (false);
	}

	if (Character.length > 1)
	{
		Character = Character.charAt(0);
	}

	for (var i = 0; i < Number; i++)
	{
		temp = temp + Character;
	}

	return temp;
}



/**************************************************************
 Split: Returns a zero-based, one-dimensional array containing
        a specified number of substrings

 Parameters:
      Expression = String expression containing substrings and
                   delimiters. If expression is a zero-length
                   string(""), Split returns an empty array,
                   that is, an array with no elements and no
                   data.
      Delimiter  = String character used to identify substring
                   limits. If delimiter is a zero-length
                   string (""), a single-element array
                   containing the entire expression string
                   is returned.

 Returns: String
***************************************************************/
function Split(Expression, Delimiter)
{
	var temp = Expression;
	var a, b = 0;
	var array = new Array();

	if (Delimiter.length == 0)
	{
		array[0] = Expression;
		return (array);
	}

	if (Expression.length == '')
	{
		array[0] = Expression;
		return (array);
	}

	Delimiter = Delimiter.charAt(0);

	for (var i = 0; i < Expression.length; i++)
	{
		a = temp.indexOf(Delimiter);
		if (a == -1)
		{
			array[i] = temp;
			break;
		}
		else
		{
			b = (b + a) + 1;
			var temp2 = temp.substring(0, a);
			array[i] = temp2;
			temp = Expression.substr(b, Expression.length - temp2.length);
		}
	}

	return (array);
}



/**************************************************************
 Replace: Returns a string in which a specified substring has
          been replaced with another substring a specified
          number of times.

 Parameters:
      Expression = String expression containing substring to
                   replace
      Find       = Substring being searched for.
      Replace    = Replacement substring.

 Returns: String
***************************************************************/
function Replace(Expression, Find, Replace)
{
	var temp = Expression;
	var a = 0;

	for (var i = 0; i < Expression.length; i++)
	{
		a = temp.indexOf(Find);
		if (a == -1)
		{
			break;
		}
		else
		{
			temp = temp.substring(0, a) + Replace + temp.substring((a + Find.length));
		}
	}
	return temp;
}



/**************************************************************
 IsChar: Returns a Boolean value indicating whether an
         expression can be evaluated as a character (this
         not only includes alpha chars but all symbols such as
         @#$%^&|\_+-/*="!?,.:;'(){}<>[]

 Parameters:
    - Expression = Variant containing a numeric expression or
                   string expression.

 Returns: Boolean
***************************************************************/
function IsChar(Expression)
{
	Expression = Expression.toLowerCase();
	RefString = "0123456789";

	if (Expression.length < 1)
	{
		return (false);
	}

	for (var i = 0; i < Expression.length; i++)
	{
		var ch = Expression.substr(i, 1);
		var a = RefString.indexOf(ch, 0);
		if (a != -1)
		{
			return (false);
		}
	}
	return(true);
}



/**************************************************************
 IsNumber: Returns a Boolean value indicating whether an
           expression can be evaluated as a number (this
           includes values like $15,656.00)

 Parameters:
      Expression = Variant containing a numeric expression or
                   string expression.

 Returns: Boolean
***************************************************************/
function IsNumber(Expression)
{
	Expression = Expression.toLowerCase();
	RefString = "0123456789.-";

	if (Expression.length < 1)
	{
		return (false);
	}

	for (var i = 0; i < Expression.length; i++)
	{
		var ch = Expression.substr(i, 1);
		var a = RefString.indexOf(ch, 0);
		if (a == -1)
		{
			return (false);
		}
	}
	return(true);
}



/**************************************************************
 IsAlphanumeric: Returns a Boolean value indicating whether an
                 expression can be evaluated as a number or
                 char.

 Parameters:
      Expression = Variant containing a numeric expression or
                   string expression.

 Returns: Boolean
***************************************************************/
function IsAlphanumeric(Expression)
{
	Expression = Expression.toLowerCase();
	RefString = "abcdefghijklmnopqrstuvwxyz0123456789 ";

	if (Expression.length < 1)
	{
		return (false);
	}

	for (var i = 0; i < Expression.length; i++)
	{
		var ch = Expression.substr(i, 1);
		var a = RefString.indexOf(ch, 0);
		if (a == -1)
		{
			return (false);
		}
	}
	return(true);
}






