﻿		/**************************************************************
		Functions com alerts para qualquer tipo de situação
		***************************************************************/
	
	
		function AlertaNecessidade(theField)
		{

			if (theField.nome != undefined){
				alert('O campo "' + theField.nome + '" é obrigatório. Por favor, digite-o.');
			}else{
				alert('O campo "' + theField.rel + '" é obrigatório. Por favor, digite-o.');
			}
				
			
			theField.focus();
		}

		function AlertaSelecao(theField)
		{
			if (theField.nome != undefined)
				alert('O campo "' + theField.nome + '" é obrigatório. Por favor, selecione uma opção.');
			else 
				alert('O campo "' + theField.rel + '" é obrigatório. Por favor, selecione uma opção.');
			
			theField.focus();
		}

		function AlertaInvalidez(theField)
		{
			alert('O campo "' + theField.nome + '" é inválido. Por favor, redigite-o.');
			theField.focus();
		}

		function AlertaNumerico(theField)
		{
			alert('O campo "' + theField.nome + '" deve conter apenas números. Por favor, corrija-o.');
			theField.focus();
		}

		function AlertaCaracteresInvalidos(theField)
		{
			alert('O campo "' + theField.nome + '" possui caracteres inválidos. Por favor, corrija-o.');
			theField.focus();
		}


		

		function AlertaNecessidadeNovo(theField)
		{

			if (theField != undefined){
				alert('O campo "' + theField.alt + '" é obrigatório. Por favor, digite-o.');
			}else{
				alert('O campo "' + theField.alt + '" é obrigatório. Por favor, digite-o.');
			}
				
			
			theField.focus();
		}

		function AlertaSelecaoNovo(theField)
		{
			if (theField != undefined)
				alert('O campo "' + theField.alt + '" é obrigatório. Por favor, selecione uma opção.');
			else 
				alert('O campo "' + theField.alt + '" é obrigatório. Por favor, selecione uma opção.');
			
			theField.focus();
		}

		function AlertaInvalidezNovo(theField)
		{
			alert('O campo "' + theField.alt + '" é inválido. Por favor, redigite-o.');
			theField.focus();
		}

		function AlertaNumericoNovo(theField)
		{
			alert('O campo "' + theField.alt + '" deve conter apenas números. Por favor, corrija-o.');
			theField.focus();
		}

		function AlertaCaracteresInvalidosNovo(theField)
		{
			alert('O campo "' + theField.alt + '" possui caracteres inválidos. Por favor, corrija-o.');
			theField.focus();
		}


		



		/**************************************************************
		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;
		}

		/**************************************************************
		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.keyCode);
			ch = ch.toLowerCase();
			Expression = Expression.toLowerCase();
			var a = Expression.indexOf(ch);
			if (a == -1) 
				window.event.keyCode = 0;
		}


		/**************************************************************
		hasInvalidChar: retorna true se um caractere inválido for encontrado;
			caso contrário, retorna false;

		Parâmetros::
				   texto = text a ser validado.
				   lista = caractere inválidos.
                   a..z => letras
                   0..9 => números
                   outros caracteres...
		  ***************************************************************/
		function hasInvalidChar(texto, lista)
		{
			lista = Replace(lista, 'a..z', 'abcdefghijklmnopqrstuvwxyz');
			lista = Replace(lista, 'A..Z', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
			lista = Replace(lista, '0..9', '0123456789');
			lista = Replace(lista, '|', '');

			for (var i=0; i<lista.length; i++) {
				if (texto.indexOf(lista.charAt(i)) >= 0)
					return true;
			}
			
			return false;
		}
		
		/************************************************
		* function clearField
		* Limpa um campo do formulário
		* Input: controlID = id do controle
		************************************************/               
		function clearField (controlID){
			var controle = document.getElementById(controlID);
			controle.value = "";
		}
		
		/************************************************
		* function switchControl
		* Habilita ou desabilita um campo do formulário
		* Input: nType - 0 = Desabilitado | 1 = Habilitado
		*        controlID = id do controle
		************************************************/               
		function switchControl (nType, controlID){
			var controle = document.getElementById(controlID);
			if (nType == 0){
				controle.disabled = true;
			}else if(nType == 1){
				controle.disabled = false;
			}
		}
				
		/************************************************
		* function isEmpty
		* Verifica se um campo está vazio
		* Input: s - campo a ser verificado
		************************************************/               
		function isEmpty(s) {
		return ((s == null) || (s.length == 0));
		}
		
		
		/*******************************************************************
		* function Trim
		* Elimina espaços em branco do conteúdo do parâmetro s
		* Input: s - campo a ser verificado
		********************************************************************/
		
		function Trim(s) {
		var sFinal = "";
		if (s != undefined)
		{
			for (x=0;x<s.length;x++)
			{
				if (s.charAt(x) != " ") 
					sFinal = sFinal + s.charAt(x);
			}
		}

		return sFinal;
		}
		
		

		/*******************************************************************************
		* function warnInvalid
		* Gera um alert para o usuário e volta o foco para o campo que está com problema
		* Input: theField - campo do formulário com problema
		*        warnText - texto a ser mostrado no alert
		*        temSelect - indica se deve aplicar select()
		********************************************************************************/
		function warnInvalid (theField, warnText, temSelect) {   
		theField.focus();
		if (temSelect) {
			theField.select();
		}
		alert(warnText);
		return false;
		}
		
		
		/************************************************	
		* function isDigit
		* Verifica se o caracter é um dígito de 0 a 9
		* Input: c - dígito a ser verificado
		************************************************/
		function isDigit (c) { 
		return ((c >= "0") && (c <= "9")) 
		}
		
		

		/*******************************************************************
		* function isNumeric
		* Verifica se um campo é numérico. Se contém apenas dígitos de 0 a 9
		* Input: s - campo a ser verificado
		********************************************************************/
		function isNumeric(s) {
		var i;
		if (isEmpty(s)) 
			return false;
			
		for (i = 0; i < s.length; i++) {   
			var c = s.charAt(i);
			if (!isDigit(c)) return false;
		}

		return true;
		}
		
		
		/*******************************************************************
		* function isFloat
		* Verifica se um campo é float. Se contém apenas dígitos de 0 a 9 mais "." ou ","
		* Input: s - campo a ser verificado
		********************************************************************/
		function isFloat(s) {
		var i;
		if (isEmpty(s)) 
			return false;
			
		for (i = 0; i < s.length; i++) {   
			var c = s.charAt(i);
			if (!isDigit(c)){
				if (((c != ".") && (c != ","))) return false;
			}
		}

		return true;
		}
		

		/*******************************************************************
		* function verificaTexto
		* Verifica se um campo é um RG válido quanto aos caracteres
		* Input: s - campo a ser verificado
		********************************************************************/
		function verificaTexto(s, expressao) {
			var i;
			if (isEmpty(s)) 
				return false;
				
			for (i = 0; i < s.length; i++) {   
				var c = s.charAt(i);
				if (expressao.indexOf(c) < 0) return false;
			}
	
			return true;
		}
		
		

		/************************************************
		* function verificaEmail
		* Verifica se um email é válido
		* Input: email a ser verificado
		************************************************/
		function verificaEmail(email) {
		var s = new String(email);
		var sNumeric;
		
		// { } ( ) < > [ ] | \ /
		if ( (s.indexOf("{")>=0) || (s.indexOf("}")>=0) || (s.indexOf("(")>=0) || (s.indexOf(")")>=0) || (s.indexOf("<")>=0) || (s.indexOf(">")>=0) || (s.indexOf("[")>=0) || (s.indexOf("]")>=0) || (s.indexOf("|")>=0) || (s.indexOf("\"")>=0) || (s.indexOf("/")>=0) )
			return false;
					
		/*			
		if (vogalAcentuada(email))
			return false;
		*/
					
		// & * $ % ? ! ^ ~ ` ' " espaço em branco
		if ( (s.indexOf("&")>=0) || (s.indexOf("*")>=0) || (s.indexOf("$")>=0) || (s.indexOf("%")>=0) || (s.indexOf("?")>=0) || (s.indexOf("!")>=0) || (s.indexOf("^")>=0) || (s.indexOf("~")>=0) || (s.indexOf("`")>=0) || (s.indexOf("'")>=0) || (s.indexOf(" ")>=0) )
			return false;
			
		// , ; : = #
		if ( (s.indexOf(",")>=0) || (s.indexOf(";")>=0) || (s.indexOf(":")>=0) || (s.indexOf("=")>=0) || (s.indexOf("#")>=0) )
			return false;
			
		// procura se existe apenas um @
		if ( (s.indexOf("@") < 0) || (s.indexOf("@") != s.lastIndexOf("@")) )
			return false;
			
		// verifica se tem pelo menos um ponto após o @
		if (s.lastIndexOf(".") < s.indexOf("@"))
			return false;

		// verifica se não tem "@" seguido de "."
		if (s.indexOf("@.") >= 0)
			return false;
			
		// verifica se existem somente números
		sNumeric = s.replace('@','');
		for (var i = 0; i < sNumeric.length; i++) {
			sNumeric = sNumeric.replace('.','');
		}
		if (isNumeric(sNumeric)){
			return false;
		}
			
		if ((s.substring(s.length,s.length - 1)) == '.') {
			return false;
		}
			
		return true;
		}

		
		/*******************************************************************
		* function anobissexto
		* Verifica se o ano eh bissexto
		* Input: iano - ano
		********************************************************************/
		function anobissexto(iano) {
		if (parseInt(iano, 10) % 4 == 0) {
			return true;
		} else
			return false;	
		}

		/*******************************************************************
		* function ver_data
		* Verifica se uma data eh valida
		* Input: idia - dia, imes - mes, iano - ano
		********************************************************************/
		function ver_data(idia, imes, iano) {
			if (isNumeric(idia) && isNumeric(imes) && isNumeric(iano)) {
				// verifica se a data eh invalida
				if (parseInt(idia, 10) < 1 || parseInt(idia, 10) > 31) {
					return false;
				}

				//verifica se o mes eh invalido
				if (parseInt(imes, 10) < 1 || parseInt(imes, 10) > 12) {
					return false;
				}
					
				//verifica se o dia estah de acordo com o mes
				//para os meses de jan a jul, os meses com dia 31 sao os impares
				if (parseInt(idia, 10) == 31 && parseInt(imes, 10) < 8 && (parseInt(imes, 10) % 2) == 0) {
					return false;
				}

				//para os meses de ago a dez, os meses com dia 31 sao os pares
				if (parseInt(idia, 10) == 31 && parseInt(imes, 10) > 7 && (parseInt(imes, 10) % 2) != 0) {
					return false;
				}

				//o mes de fevereiro so permite dia 29 se for um ano bissexto
				if ((parseInt(idia, 10) >= 29 && parseInt(imes, 10) == 2 && !(anobissexto(parseInt(iano, 10)))) || 
				(parseInt(idia, 10) >= 30 && parseInt(imes, 10) == 2 && anobissexto(parseInt(iano, 10)))) {
					return false;
				}
					
				//o ultimo dia do mes de fevereiro eh dia 28 para os anos comuns
				if (parseInt(idia, 10) > 28 && parseInt(imes, 10) == 2 && !(anobissexto(parseInt(iano, 10)))) {
					return false;
				}
					
				return true; 
			}	else
				return false;
		}
		
		/************************************************
		* function vogalAcentuada
		* Verifica se uma string tem vogais acentuadas
		* Input: string a ser verificada
		************************************************/	
		/*
		function vogalAcentuada(s) {
			ls = s.toLowerCase();
			if ((ls.indexOf("á")>=0) || (ls.indexOf("à")>=0) || (ls.indexOf("ã")>=0) || (ls.indexOf("â")>=0) || (ls.indexOf("é")>=0) || (ls.indexOf("í")>=0) || (ls.indexOf("ó")>=0) || (ls.indexOf("õ")>=0) || (ls.indexOf("ô")>=0) || (ls.indexOf("ú")>=0) || (ls.indexOf("ü")>=0)){
				return true;
			}
		}
		*/


		function cpf_check( cpf )
		{
			var dac = "", inicio = 2, fim = 10, soma, digito, i, j
			for (j=1;j<=2;j++)
			{
				soma = 0
				for (i=inicio;i<=fim;i++)
				{
					soma += parseInt(cpf.substring(i-j-1,i-j))*(fim+1+j-i)
				}
				if (j == 2) { soma += 2*digito }
				digito = (10*soma) % 11
				if (digito == 10) { digito = 0 }
				dac += digito
				inicio = 3
				fim = 11
			}
			return (dac == cpf.substring(cpf.length-2,cpf.length))
		}
		
		function cgc_check(cgc) {
			if ((cgc.indexOf("-") != -1) || (cgc.indexOf(".") != -1) || (cgc.indexOf("/") != -1)) {
				alert("O CGC deve conter somente números.")
				return( false )
			}
  			var df, resto, dac = ""
			df = 5*cgc.charAt(0)+4*cgc.charAt(1)+3*cgc.charAt(2)+2*cgc.charAt(3)+9*cgc.charAt(4)+8*cgc.charAt(5)+7*cgc.charAt(6)+6*cgc.charAt(7)+5*cgc.charAt(8)+4*cgc.charAt(9)+3*cgc.charAt(10)+2*cgc.charAt(11)
			resto = df % 11
			dac += ( (resto <= 1) ? 0 : (11-resto) )
			df = 6*cgc.charAt(0)+5*cgc.charAt(1)+4*cgc.charAt(2)+3*cgc.charAt(3)+2*cgc.charAt(4)+9*cgc.charAt(5)+8*cgc.charAt(6)+7*cgc.charAt(7)+6*cgc.charAt(8)+5*cgc.charAt(9)+4*cgc.charAt(10)+3*cgc.charAt(11)+2*parseInt(dac)
			resto = df % 11
			dac += ( (resto <= 1) ? 0 : (11-resto) )
			return (dac == cgc.substring(cgc.length-2,cgc.length))
		}
		function checkField( sStr, sChars )
		{
			var j=0;
			var bRetVal = true;
			while( j < sChars.length )
			{
				if( sStr.indexOf( sChars.substr(j,1) ) >= 0 )
				{
					bRetVal = false;
					break;
				}
				j++;
			}
			return bRetVal;
		}
		function dataCheck( campo )
		{
			var nome_mes = new Array();
			nome_mes[1]="Jan";
			nome_mes[2]="Feb";
			nome_mes[3]="Mar";
			nome_mes[4]="Apr";
			nome_mes[5]="May";
			nome_mes[6]="Jun";
			nome_mes[7]="Jul";
			nome_mes[8]="Aug";
			nome_mes[9]="Sep";
			nome_mes[10]="Oct";
			nome_mes[11]="Nov";
			nome_mes[12]="Dec";
		
			var data = campo;
			if(data.lastIndexOf("/") == data.indexOf("/"))
			{
				return false;
			}

			/*
			if( !checkField( data, "<|>@#$%&*!+- ()?[]{}~^´`,.\"_=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZáéíóúãõàüäëöïñçÁÉÍÓÚÃÕÀÜÄËÖÏÑÇ\\" ) )
			{
				return false;
			}
			*/

			if (data.length != 10) 
			{
				return false;
			} 

			var myDayStr = data.substr(0,2);
			var myMonthStr = nome_mes[Math.abs(data.substr(3,2))];
			var myYearStr = data.substr(6,4);
			var myDateStr = myDayStr + " " + myMonthStr + " " + myYearStr;
			var myDate = new Date( myDateStr );
			var myDate_string = myDate.toUTCString();
			var myDate_array = myDate_string.split(" ");

			// Array myDate_array:
			// Indices:
			// 0 - Dia da semana
			// 1 - Dia do mes (numero)
			// 2 - Nome do mes (Jan, Fev, etc)
			// 3 - Ano
			// 4 - Hora
			// 5 - Constante "UTC"

			if( ( myDate_array[2] != myMonthStr ) || ( Math.abs(data.substr(3,2) ) < 1 || Math.abs(data.substr(3,2) ) > 12) )
			{
				return false;
			}
			return true;
		}
		function numericoCheck(campo)
		{
			for( var y=0; y < campo.length; y++ )
			{
				if( (campo.substr(y,1) != "0") && (campo.substr(y,1) != "1") && 
					 (campo.substr(y,1) != "2") && (campo.substr(y,1) != "3") &&
					 (campo.substr(y,1) != "4") && (campo.substr(y,1) != "5") && 
					 (campo.substr(y,1) != "6") && (campo.substr(y,1) != "7") &&
					 (campo.substr(y,1) != "8") && (campo.substr(y,1) != "9"))
				{
					return false;
				}
			}
			return true;
		}

/************************************************
* function verificaIntervaloDatas
* Verifica se uma data é menor que outra dentro
* de um intervalo
* Input: dInicial - data inicial do intervalo
*		 dFinal - data final do intervalo
************************************************/
function verificaIntervaloDatas(dInicial, dFinal) {
	//Verifica se uma data inicial é maior que a final
	var dataini;
	var datafim;
	
	dataini = new Date(dInicial);
	datafim = new Date(dFinal);
	
	if (dataini > datafim)
		return false 
	else 
		return true;
}


// ************************************************************************************
// Função para limitar o número de caracteres que é permitido digitar em um campo TEXTAREA

// Recebe como parâmetros:
// - aField: campo Textarea (passado como this)
// - nChars: número máximo de caracteres permitidos
// - sFieldLabel: nome do Textarea para aparecer do alert
function limitArea( aField, nChars) 
{
	var txtmsg = new Array();
	var Msg = aField.value;
	var CharCount = Msg.length;

	if (CharCount <= nChars)	{ 
		txtmsg[1] = Msg;
	}
	else { 
		aField.value = aField.value.substring(0, nChars);
		alert("O Limite Máximo do Campo foi Excedido.");
	}
}

function Formatar(src, mask) {
 if (src.value.length > mask.length) {
  src.value = src.value.substring(0,mask.length);
  return false;
 }
 var i = src.value.length;
 var saida = mask.substring(0,1);
 var texto = mask.substring(i)
 if (texto.substring(0,1) != saida) 
  src.value += texto.substring(0,1);
}

		