function LimitaCaracteres(obj, tam) {
	if (obj.value.length > tam) {
		obj.value = obj.value.substring(0, tam-1)
	}
}

function TransformDate(txt) {
	// funciona com a data no formato dd/mm/yyyy
	strData = txt.split("/");
	dtA = new Date(strData[2], strData[1]-1, strData[0]);
	return(dtA);
}

/*** 
* Descrição.: formata um campo do formulário de 
* acordo com a máscara informada... 
* Parâmetros: - objForm (o Objeto Form) 
* - strField (string contendo o nome 
* do textbox) 
* - sMask (mascara que define o 
* formato que o dado será apresentado, 
* usando o algarismo "9" para 
* definir números e o símbolo "!" para 
* qualquer caracter... 
* - evtKeyPress (evento) 
* Uso.......: <input type="textbox" 
* name="xxx"..... 
* onkeypress="return txtBoxFormat(document.forms[0], 'str_cep', '99999-999', event);"> 
* Observação: As máscaras podem ser representadas como os exemplos abaixo: 
* CEP -> 99.999-999 
* CPF -> 999.999.999-99 
* CNPJ -> 99.999.999/9999-99 
* Data -> 99/99/9999 
* Tel Resid -> (99) 999-9999 
* Tel Cel -> (99) 9999-9999 
* Processo -> 99.999999999/999-99 
* C/C -> 999999-! 
* E por aí vai... 
***/ 

function txtBoxFormat(objForm, strField, sMask, evtKeyPress) { 
var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla; 

if(document.all) { // Internet Explorer 
nTecla = evtKeyPress.keyCode; } 
else if(document.layers) { // Nestcape 
nTecla = evtKeyPress.which; 
} 

sValue = objForm[strField].value; 

// Limpa todos os caracteres de formatação que 
// já estiverem no campo. 
sValue = sValue.toString().replace( "-", "" ); 
sValue = sValue.toString().replace( "-", "" ); 
sValue = sValue.toString().replace( ".", "" ); 
sValue = sValue.toString().replace( ".", "" ); 
sValue = sValue.toString().replace( "/", "" ); 
sValue = sValue.toString().replace( "/", "" ); 
sValue = sValue.toString().replace( "(", "" ); 
sValue = sValue.toString().replace( "(", "" ); 
sValue = sValue.toString().replace( ")", "" ); 
sValue = sValue.toString().replace( ")", "" ); 
sValue = sValue.toString().replace( ":", "" ); 
sValue = sValue.toString().replace( " ", "" ); 
sValue = sValue.toString().replace( " ", "" ); 
fldLen = sValue.length; 
mskLen = sMask.length; 

i = 0; 
nCount = 0; 
sCod = ""; 
mskLen = fldLen; 

while (i <= mskLen) { 
bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/")) 
bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " ") || (sMask.charAt(i) == ":")) 

if (bolMask) { 
sCod += sMask.charAt(i); 
mskLen++; } 
else { 
sCod += sValue.charAt(nCount); 
nCount++; 
} 

i++; 
} 

objForm[strField].value = sCod; 

if (nTecla != 8) { // backspace 
if (sMask.charAt(i-1) == "9") { // apenas números... 
return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9 
else { // qualquer caracter... 
return true; 
} } 
else { 
return true; 
} 
} 
//Fim da Função Máscaras Gerais


function ConverteHora(hora) {
	hora = new Number(hora.replace(":",""));
	return(hora);
}

/*
if (!ValidaHora(form.Input_IdealPiorCaso.value)) {
	form.Input_IdealPiorCaso.focus();
	return(false);
}
*/
function ValidaHora(Hora,SemLimiteHoras)
  {

   // Verifica se a hora está no formato: HH:MM
   //   Qualquer valor que seja passado no parâmetro "SemLimiteHoras" 
   //   fará com que seja permitido preencher hora com valor superior a 24
   //   e se não for passado esse parametro, então, hora terá que ser <= a 24

   var timePat = /^(\d{2}):(\d{2})?$/;
   var timeStr = Hora;
   var matchArray = timeStr.match(timePat);

   if (matchArray == null)
   {
    timePat = /^(\d{1}):(\d{2})?$/;
    matchArray = timeStr.match(timePat);

    if (matchArray == null)
    {
     alert("Formato inválido!\nUtilize o formato HH:MM");
     return false;
    }
   }

   hour = matchArray[1];
   minute = matchArray[2];

   if ((hour < 0  || (hour > 23 && SemLimiteHoras==null)))
   {
    alert("O Nº de Horas tem que estar entre 0 e 23");
    return false;
   }

   if (minute < 0 || minute > 59)
   {
    alert ("Os Minutos devem estar entre 0 e 59.");
    return false;
   }
   return true;
  }

  
	function DesmarcaLinha(ID,Selecoes)
	{
		var NewIds = "";
		var ids = Selecoes.split(",")
		for (var i=0; i < ids.length; i++){
			if (ids[i] != ID){
				NewIds = NewIds + "," + ids[i]
			} 
		}
		if (NewIds.substring(0,1) == ",") {
			NewIds = NewIds.substring(1,NewIds.length) 
		}
		return NewIds
	}


/*
 * This works on 1 character only if _ONE=1
 * if _ONE=0 then it will replace all occurances.
 */
var _ONE=0;
function Switch(item,OldChar,NewChar)
{
  var _ret="";
  var _flag=0;
  var _item=item.split("");
  for(var x=0;x<_item.length;x++)
  {
    if(!_flag&&_item[x]==OldChar)
	{
	  _item[x]=NewChar;
      _flag=_ONE;
	}
	_ret+=_item[x];
  }
  return(_ret);
}

function TrocaEspecialChars(str) {
	var vetor = [['Ç'],['Á'],['É'],['Í'],['Ó'],['Ú'],['Â'],['Ê'],['Ô'],['Ã'],['Õ']];
	var vetor2 = [['C'],['A'],['E'],['I'],['O'],['U'],['A'],['E'],['O'],['A'],['O']];
	if (str != '')
		for (j = 0; j < vetor.length; j++) {
			str = Switch(str,vetor[j][0],vetor2[j][0]);
		}
	
	return str;
}

function CriticaEspecialChars(){
	switch (event.keyCode){
		case 34:			// """
		case 42:			// "*"
		case 47:			// "/"
		case 58:			// ":"
		case 60:			// "<"
		case 62:			// ">"
		case 63:			// "?"
		case 92:			// "\"
		case 124:		// "|"
				event.keyCode = 0 ;
				break;
	}

}


// **** Feito por Daniel Garnier *** //
// Coloca o foco na combo conforme o que voce digitou na combo
//		<div onkeydown="return busca_posicao_na_combo('combo');">
//			<select name="combo" onblur="LimpaCapturaTeclado();">
var strBuscaCombo = "";
function busca_posicao_na_combo(combo) {
	
	//Se for Enter, executar funcao para popular combos
	if (event.keyCode == 9)
		ExecPop(combo);
	
	//Se for diferente das SETAS
	if (event.keyCode != 9 && event.keyCode != 37 && event.keyCode != 38 && event.keyCode != 39 && event.keyCode != 40) {
		form = document.forms[0];
		var txtcombo = "";
	
		// Se for ESC
		if (event.keyCode == 27)
			strBuscaCombo = "";
			
		// Se for um caracter de A - Z ou [SPACE] ou Numeros (0 a 9) ou (-, /, .)
		if ((event.keyCode >= 65 && event.keyCode <= 90) || (event.keyCode == 32) || (event.keyCode >=45 && event.keyCode <=57)) {
			strBuscaCombo = strBuscaCombo + String.fromCharCode(event.keyCode);
		}
	
		for (i = 0; i < form[combo].length; i++)
		{
			txtcombo = form[combo].options[i].innerText.substr(0,strBuscaCombo.length).toUpperCase();
			txtcombo = TrocaEspecialChars(txtcombo);
	
			if (strBuscaCombo.toUpperCase() == txtcombo) {
				form[combo].options[i].selected = true;
				event.keyCode = 0;
				return false;
			}
	
		}

		event.keyCode = 0;
		return false;
	}
}

function LimpaCapturaTeclado() {
	strBuscaCombo = "";
}

// Colocar o seguinte comando na caixa de texto que deseja utilizar data: onkeyup="BotaBarra(this.form,this.name);"
// Caso seja objeto, onkeyup="BotaBarra(this.form,this);"
function BotaBarra(form,objeto) {

		 if (typeof objeto != "object"){
			 	objeto = form.elements[objeto];
		 }

		 if (objeto.value.length != 2 && objeto.value.length != 5){
		 
			 if (objeto.value.substr(objeto.value.length-1,objeto.value.length) == "/") 
				objeto.value = objeto.value.substr(0,objeto.value.length-1); 
		 	
		 } 

		 if (objeto.value.length == 2 || objeto.value.length == 5)  
		 	objeto.value = objeto.value + "/"; 
	 
		 if (objeto.value.length == 3 || objeto.value.length == 6){

		 	if (objeto.value.substr(objeto.value.length-2,objeto.value.length) == "//") 
	 			objeto.value = objeto.value.substr(0,objeto.value.length-2); 		 
		 	
		 } 
		 
}

function ValidaCampoNumerico(form, campo) {
		
	if (form[campo].length == null)
		var oCampo = form[campo]
	else
		var oCampo = event.srcElement; // event.srcElement = objeto que disparou o evento

	var valor = TrocaVirgulaPorPonto(oCampo.value)
	
	if (valor != "")
		if (isNaN(valor)) {
			alert("Não é um número válido.");
			return(false);
		}
		else {
			oCampo.value = FormatNumber(valor,2,true,false,true);
		}
	return(true);
}

function TrocaVirgulaPorPonto(strValor) {
	// Tirando os pontos de milhares.
	valor = strValor.replace(".","");
	valor = valor.replace(".","");
	valor = valor.replace(".","");
	// Trocando a vírgula por ponto para poder fazer calculos no js
	valor = new Number(valor.replace(",","."));
	return(valor);
}


function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas) {
	/**********************************************************************
	IN:
	NUM - the number to format
	decimalNum - the number of decimal places to format 
	
	the number to
	bolLeadingZero - true / false - display a leading zero for
	
	
	numbers between -1 and 1
	bolParens - true / false - use parenthesis around 
	
	negative numbers
	bolCommas - put commas as number separators.
	 
	RETVAL:
	The formatted number!
	**********************************************************************/
	
	if (isNaN(parseInt(num))) return "NaN";
	
	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1; // Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum));
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign; // Readjust for sign
	
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);
	
	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
	
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;
	
		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length);
			iStart -= 3;
		} 
	}
	
	// See if we need to use parenthesis
	if (bolParens && num < 0)
	tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";
	
	
	
	// Trocando o ponto por virgula e a virgula por ponto
	tmpNumStr = tmpNumStr.replace(".","$");
	// tem que colocar 3, porq pode ir até bilhoes. ex: 1.102.234,01
	tmpNumStr = tmpNumStr.replace(",",".");
	tmpNumStr = tmpNumStr.replace(",",".");
	tmpNumStr = tmpNumStr.replace(",",".");
	
	tmpNumStr = tmpNumStr.replace("$",",");
	
	// Para colocar o decimal sempre com 2 digitos. ex: 23,4 ---> 23,40
	var pos = tmpNumStr.indexOf(",");
	var temp = tmpNumStr.substring(pos+1,tmpNumStr.length);
	if (temp.length == 1 && pos != -1)
		tmpNumStr = tmpNumStr + "0";
	
	var teste = tmpNumStr.search(",");
	
	if (teste == -1 && decimalNum > 0)
		tmpNumStr = tmpNumStr + ",00";
	
	
	return tmpNumStr; // Return our formatted string!
}

//ajuda('fornecedor','Input_Fornecedor','Dados do Colaborador')
function ajuda(modulo,pagina,campo,tela){
	var	cortitulo = "FF9A31";
	var corlinha = "FFE7B3";

	switch (modulo.toUpperCase()) {
		case "CADASTRO": {
			cortitulo = "003366";
			corlinha = "CADDEC";
			break;
		}
		case "PLANEST": {
			cortitulo = "BEB5A1";
			corlinha = "E4E1DA";
			break;
		}
		case "PRESTCONT": {
			cortitulo = "546B32";
			corlinha = "EDF3E4";
			break;
		}
		case "ORCAMENTO": {
			cortitulo = "4E8D6F";
			corlinha = "ACCCB9";
			break;
		}
		case "IMPORTACAO": {
			cortitulo = "AE8D0B";
			corlinha = "FDF5D7";
			break;
		}
		case "CADIN": {
			cortitulo = "546B32";
			corlinha = "D5DFC8";
			break;
		}
		case "INSTRUMENTO": {
			cortitulo = "008080";
			corlinha = "E6FFFF";
			break;
		}
		break;
	}

	//alert (corlinha + " " + cortitulo);
	var url="/portalrbmlq/ajuda/interface_ajuda.asp?modulo=" + modulo + "&pagina=" + pagina + "&campo=" + campo + "&tela=" + tela + "&cortitulo=" + cortitulo +  "&corlinha=" + corlinha + "#go";
	//alert (url);
	var wnd=window.open(url,null, "left=250,top=170,width=350,height=250,channelmode=no,status=no,toolbar=no,menubar=no,location=no,scrollbars=1,resizable=no");
	wnd.focus();
}


/*
// Janela que não deixa clicar fora dela.
function AbrirJanelaModal(pagina){
   var sFeatures="dialogHeight:250px,dialogWidth:250px,center:yes,resizable:no,scroll:yes";
   window.showModalDialog(pagina, "",sFeatures);
   
}
*/


/*	
	var Data1 = new Date(customDateString(document.forms[0].dtip));
	var Data2 = new Date(customDateString(document.forms[0].dttp));
	if(Data1.valueOf() >= Data2.valueOf()){
    	alert("");
    }
*/

//função que retorna uma string data formatada para comparação
function MakeArray(n) {
	this.length = n
	return this
};
monthNames = new MakeArray(12)
monthNames[1] = "January"
monthNames[2] = "February"
monthNames[3] = "March"
monthNames[4] = "April"
monthNames[5] = "May"
monthNames[6] = "June"
monthNames[7] = "July"
monthNames[8] = "August"
monthNames[9] = "September"
monthNames[10] = "October"
monthNames[11] = "November"
monthNames[12] = "December"
dayNames = new MakeArray(7)
dayNames[1] = "Sunday"
dayNames[2] = "Monday"
dayNames[3] = "Tuesday"
dayNames[4] = "Wednesday"
dayNames[5] = "Thursday"
dayNames[6] = "Friday"
dayNames[7] = "Saturday";



function customDateString(campo) {
 	var dt1 = campo.value.substring(3,5)
	if (dt1.substring(0,1) == '0'){
	    var dt2 = dt1.substring(1,2)
	}else{
	    var dt2 = dt1
	};
	var theMonth = monthNames[parseInt(dt2)]
	var theYear = campo.value.substring(6,10)
	return  theMonth + " " + campo.value.substring(0,2) + ", " + theYear
};



// Completa Zeros a esquerda
function Completa_Zeros(campo) {
	if (campo.value != "") {
		var cont, zeros="";
		cont = 4 - campo.value.length;
		while (cont > 0) {
			zeros = zeros + "0";
			cont = cont - 1;
		}
		campo.value = zeros + campo.value;
	}
}

function Completa_Zeros_A_Esquerda(campo, qtde) {
	if (campo.value != "") {
		var cont, zeros="";
		cont = qtde - campo.value.length;
		while (cont > 0) {
			zeros = zeros + "0";
			cont = cont - 1;
		}
		campo.value = zeros + campo.value;
	}
}

function AnulaEnter(e) {
		var IE = (document.all) // Internet Explorer
	
		if (IE)
			var tecla = event.keyCode
		else
			var tecla = e.which;
	
		if (tecla == 13){
				if (IE){
					event.keyCode = 0;
				}
				else{
					return false;
				}
		}
}


// onkeypress="return Valor();"
// Só aceita numeros positivos, negativos e virgulas
function ValorNegativo(e){

		var IE = (document.all) // Internet Explorer
	
		if (IE)
			var tecla = event.keyCode
		else
			var tecla = e.which;
	
		if (tecla > 47 && tecla < 58) // numeros de 0 a 9
				return true
		else{
				if (tecla != 8 && tecla != 44 && tecla != 13 && tecla != 45  && tecla != 0) // backspace e Virgula e Enter e Sinal Negativo
						if (IE){
							event.keyCode = 0;
						}
						else{
							return false;
						}
				else
					return true;
		}
}

// onkeypress="return Valor();"
// Só aceita numero e virgulas
function Valor(e, el){
	var IE = (document.all) // Internet Explorer

	if (IE)
		var tecla = event.keyCode
	else
		var tecla = e.which;
		
		if (tecla > 47 && tecla < 58) // numeros de 0 a 9
					return true
		else{
				if (tecla != 8 && tecla != 44 && tecla != 13 && tecla != 0) // backspace e Virgula e Enter
						if (IE){
							event.keyCode = 0;
						}
						else{
							return false;
						}
				else
						if (tecla = 44){
								if (IE){
										if (event.srcElement.value.indexOf(",")>=0){event.keyCode = 0}
								}
								else{
										if (el.value.indexOf(",")>=0){return false}
								}
						}
						else
							return true;
					}
}

// onKeyPress="return Numero();"
//So aceita Numeros
function Numero(e){

	var IE = (document.all) // Internet Explorer


	if (IE) 
		var tecla = event.keyCode
	else 
		var tecla = e.which;

	if (tecla > 47 && tecla < 58) // numeros de 0 a 9
			return true
	else{
			// backspace e Enter
			if (tecla != 8 && tecla != 13 && tecla != 0){
				if (IE){
					event.keyCode = 0;
				}
				else{
					return false;
				}
			} 
			else
				return true;
	}
}


// onkeypress="return MaxLength(this.form, this.name,255);"
function MaxLength(form, nome, num) {
	if (form[nome].value.length >= num) {
		event.keyCode = 0;
	}
}

// onblur="ValidaData(this.form, this.name);"
function ValidaData(form, nome)
{
	if (typeof nome != "object"){
	 	obj = form.elements[nome];
	}
	else{
		obj = nome;
	}

 	strinput = obj.value
	
	if (trim(strinput) == ""){
		return true;
	}
	
	if (!CriticaData(strinput)) {
		alert("Data Inválida! Preencha uma data válida no formato: dd/mm/aaaa");
		try{ obj.focus(); }
		catch(e){};
	   return false;
	}
		
  if (obj.value.length < 10) {
		alert("Por favor preencha a data no formato: dd/mm/aaaa");
		try{ obj.focus(); }
		catch(e){};
		return false;
  }
		
  return true;
}


// onkeypress="Hora();"
//Só aceita numero e dois pontos
function Hora(e){

		var IE = (document.all) // Internet Explorer
	
		if (IE) 
			var tecla = event.keyCode
		else 
			var tecla = e.which;
	
		if (tecla > 47 && tecla < 58) // numeros de 0 a 9
			return true
		else {
					if (tecla != 8 && tecla != 13 && tecla != 58 && tecla != 0) // BackSpace e Enter e dois pontos
							if (IE){
								event.keyCode = 0;
							}
							else{
								return false;
							}
				   else
						return true;
		}
}

// onkeypress="HoraSemPonto();"
//Só aceita numero
function HoraSemPonto(e){
	var IE = (document.all) // Internet Explorer

	if (IE) 
		var tecla = event.keyCode
	else 
		var tecla = e.which;


	if (tecla > 47 && tecla < 58) // numeros de 0 a 9
		return true
	else {
				if (tecla != 8 && tecla != 13 && tecla != 0) // BackSpace e Enter
					if (IE){
						event.keyCode = 0;
					}
					else{
						return false;
					}
   			else
						return true;
	}
}

// onkeypress="Data();"
//Só aceita numero e barra
function Data(e){

	var IE = (document.all) // Internet Explorer

	if (IE) 
		var tecla = event.keyCode
	else 
		var tecla = e.which;
	
	if (tecla > 47 && tecla < 58) // numeros de 0 a 9
		return true
	else {
				if (tecla != 8 && tecla != 13 && tecla != 47 && tecla != 0) // BackSpace, Enter e Barra
						if (IE){
							event.keyCode = 0;
						}
						else{
							return false;
						}
			   else
						return true;
	}
}

// onkeypress="DataSemBarra();"
//Só aceita numero
function DataSemBarra(e){

	var IE = (document.all) // Internet Explorer

	if (IE) 
		var tecla = event.keyCode
	else 
		var tecla = e.which;


	if (tecla > 47 && tecla < 58) // numeros de 0 a 9
		return true
	else {
				if (tecla != 8 && tecla != 13 && tecla != 0) // BackSpace, Enter
					if (IE){
						event.keyCode = 0;
					}
					else{
						return false;
					}
			   else
					return true;
	}
}


//OnKeyUp="mascara_data(this)"
function mascara_data(mydata){ 
              
    if (event.keyCode!=8){ //BackSpace
  	//trata barra do dia
  	if (mydata.value.length == 2){ 
  	    mydata.value = mydata.value + '/'; 
  	} 
	if (mydata.value.length == 3 && mydata.value.substring(2,3) != '/'){
	    mydata.value = mydata.value.substring(0,2) + '/' + mydata.value.substring(2,3); 
	} 

  	//trata barra do mês
  	if (mydata.value.length == 5){ 
  	    mydata.value = mydata.value + '/'; 
  	} 
  	if (mydata.value.length == 6 && mydata.value.substring(5,6) != '/'){
  	    mydata.value = mydata.value.substring(0,5) + '/' + mydata.value.substring(5,6); 
  	} 

  	if (mydata.value.length == 10){ 
  	    verifica_data(mydata); 
  	} 
    }
} 

function verifica_data (mydata) { 

  dia = (mydata.value.substring(0,2)); 
  mes = (mydata.value.substring(3,5)); 
  ano = (mydata.value.substring(6,10)); 

  situacao = ""; 
  // verifica o dia valido para cada mes 
  if ((dia < 01)||(dia < 01 || dia > 30) && (  mes == 04 || mes == 06 || mes == 09 || mes == 11 ) || dia > 31) { 
      situacao = "falsa"; 
  } 

  // verifica se o mes e valido 
  if (mes < 01 || mes > 12 ) { 
      situacao = "falsa"; 
  } 

  // verifica se e ano bissexto 
  if (mes == 2 && ( dia < 01 || dia > 29 || ( dia > 28 && (parseInt(ano / 4) != ano / 4)))) { 
      situacao = "falsa"; 
  } 
    
  if (mydata.value == "") { 
      situacao = "falsa"; 
  } 
    
  if (situacao == "falsa") { 
      alert("Data inválida!"); 
      mydata.focus(); 
  } 
} 

//OnKeyUp="mascara_hora(this)"
function mascara_hora(myhora){ 
    if (event.keyCode!=8){ //BackSpace

  	if (myhora.value.length == 2){ 
  	    myhora.value = myhora.value + ':'; 
  	} 

  	if (myhora.value.length == 3  && myhora.value.substring(2,3) != ':'){ 
  	    //myhora.value = myhora.value + ':'; 
  	    myhora.value = myhora.value.substring(0,2) + ':' + myhora.value.substring(2,3);
  	} 

  	if (myhora.value.length == 5){ 
  	    verifica_hora(myhora); 
  	} 
    }
} 

           
function verifica_hora(myhora){ 
    hrs = (myhora.value.substring(0,2)); 
    min = (myhora.value.substring(3,5)); 
    situacao = ""; 
    // verifica data e hora 
    if ((hrs < 00 ) || (hrs > 23) || ( min < 00) ||( min > 59)){ 
        situacao = "falsa"; 
    } 
               
  	if (myhora.value.indexOf(':', 0) == -1) {
  		situacao = "falsa"; 
  	}

    if (myhora.value == "") { 
        situacao = "falsa"; 
    } 

    if (situacao == "falsa") { 
        alert("Hora inválida!"); 
        myhora.focus(); 
    } 
} 

//Retorna a data com 4 digitos para o ano
function DataCompleta(strDate){

		if (strDate.length != 8){ return(strDate)	}
		
		var today			= new Date(); 												// Data Atual
		var userdata		= new Date(strDate);										// Transforma em Data a string passada no parametro
		var strResult  	= strDate;													// Variavel que será retornada
		var strYearAtual	= today.getFullYear().toString().substr(2,2);	//	pega os 2 ultimos digitos. Ex: 2006 -> 06
		var strYear			= strDate.substr(6,2)									// pega os 2 ultimos digitos. Ex: 14/12/95 -> 95
		
		strResult = strDate.substr(0,6)	// pega os 5 primeiros digitos Ex: 20/12/67 -> 14/12/

		
		// Compara se o ano passado eh maior do que o ano corrente. Caso seja maior,
		//	considera dentro do mesmo seculo somente se estiver dentro do prazo ate
		// 5 à frente. Ex: ano atual = 2006 / ano param = 07 -> ano atual + 5 = 11 -> 2007
		//						 ano atual = 2006 / ano param = 45 -> ano atual + 5 = 11 -> 1907	   
		// Senao, o ano atual eh maior. entao considera dentro do mesmo seculo.
		// 				Ex: ano atual = 2006 / ano param = 02 -> 2002
		
  		if (strYearAtual < strYear){
				if ((parseInt(strYearAtual) + 5) > parseInt(strYear)){
					strResult = strResult + (today.getFullYear() + Math.abs(strYear - strYearAtual))
				}
				else{
					strResult = strResult + ((today.getFullYear()-100) + Math.abs(strYearAtual - strYear))
				}
		}
		else{
				strResult = strResult + (today.getFullYear() - Math.abs(strYearAtual - strYear))
		}
		
		return(strResult)
}


function CompletaAno(nome) //Completa o Ano de dois dígitos para 4 dígitos
{
	form = document.forms[0];
	
	if(form[nome].value.length == 2) {
		if (parseInt(form[nome].value) < 90){
			form[nome].value = '20' + form[nome].value;
		} else {
			form[nome].value = '19' + form[nome].value;
		}
	}	

}


function DesmarcarLinha(linha){
	linha.bgColor = "<%=CorDesmarcarLinha%>";
}

function MarcarLinha(linha){
	linha.bgColor = "<%=CorMarcarLinha%>";
}

function Mouseout(linha){
	linha.bgColor = "<%=CorMouseOut%>";
}

function Mouseover(linha,tipotabela){
	if (tipotabela == "") 
		linha.bgColor = "<%=CorMouseOver%>"; 
	else 
		linha.bgColor = "<%=CorLinhaFixa%>"; 
}

function Foco(campo) {
	form = document.forms[0];
	form[campo].focus();
}



/*
<APPLET WIDTH="22" HEIGHT="20" CODEBASE="/funcoes" CODE="CalendarWidget.class" ALT="DatePicker" MAYSCRIPT ARCHIVE="DatePicker.jar">
	<PARAM NAME="field" VALUE="nome_do_campo_data">
	<PARAM NAME="datemask" VALUE="">
	<PARAM NAME="title" VALUE="Data Inicial">
</APPLET>
*/
function jsDatePicker(szField, szDate, szAction){ 
	var form = document.forms[0];
	var field = form.elements[szField];
	if(szAction == "1"){
		field.value=szDate;
	}
	return field.value;
}



// onkeypress="return Enter();"
function Enter(e) {
	if (document.all) // Internet Explorer
		var tecla = event.keyCode;
	else if(document.layers) // Nestcape
		var tecla = e.which;
		
		if (tecla == 13)
			Executar('Logar');
}


// Para maximizar a janela ao abrir //
function maximizar_tela() {
	top.window.moveTo(0,0);
	if (document.all) {
 		top.window.resizeTo(screen.availWidth,screen.availHeight);
	} else if (document.layers||document.getElementById) {
 		if (top.window.outerHeight<screen.availHeight||top.window.outerWidth<screen.availWidth){
  			top.window.outerHeight = screen.availHeight;
  			top.window.outerWidth = screen.availWidth;
 		}
	}
}

//Informa através de a janela popup o erro encontrado
function InformaErro(nmPag,numErro,descrErro,scErro){
	window.showModalDialog(nmPag+'?numErro='+numErro+'&descrErro='+descrErro+'&scErro='+scErro,'strXML','help:no;status:no;resizeable:no;scroll:no;dialogHeight:300px;dialogWidth:500px;dialogLeft:300px;dialogTop:120px');
}


// Faz o trim: remove espaços a esquerda e a direita do texto
function trim(palavra) {
	return(lTrim(rTrim(palavra)));
}

// Remove espaços a esquerda do texto
function lTrim(palavra) {
  try {
  	if(palavra.length == 0) {
  		return(palavra);
  	} else {
  		if(palavra.substr(0, 1) == ' ') {
  			return(lTrim(palavra.substr(1, palavra.length - 1)));
  		} else {
  			return(palavra);		
  		}
  	}
  }
  catch (e) {
    return palavra;
  }
}

// Remove espaços a direita do texto
function rTrim(palavra) {
  try {
  	if(palavra.length == 0) {
  		return(palavra);
  	} else {
  		if(palavra.substr(palavra.length - 1, 1) == ' ') {
  			return(rTrim(palavra.substr(0, palavra.length - 1)));
  		} else {
  			return(palavra);
  		}
  	}
  }
  catch(e) {
    return palavra;
  }
}

// ******************************************************************
// INICIO DAS FUNCOES DE VALIDACAO DE CPF E CNPJ
// ******************************************************************

// FUNCAO "PUBLICA" QUE VALIDA CPFs OU CNPJs
function ValidaCPF_CNPJ(strTipoValidacao, strCPF_CNPJ){
  var strCPF_CNPJTemp;
  var intNumMaxDigitos;
  var blnValido;

  if ((strTipoValidacao != 'CPF') && (strTipoValidacao != 'CNPJ')){
    window.alert('Tipo de validação incorreto.\nDeve ser CPF ou CNPJ');
    return false;
  } else {
    if (strTipoValidacao == 'CPF'){
		intNumMaxDigitos = 11;
	} else {
		intNumMaxDigitos = 14;
	}
  }

  //ELIMINANDO ESPACOS DESNECESSARIOS
  strCPF_CNPJTemp = trim(strCPF_CNPJ);
 
  //EM AMBOS OS CASOS DEVEMOS TER SOMENTE DIGITOS
  if (!(isNumeric(strCPF_CNPJTemp))) {
    window.alert(strTipoValidacao + ' deve conter apenas dígitos.');
    return false;
  } else {
    if (strCPF_CNPJTemp.length == intNumMaxDigitos) {
       if (strTipoValidacao == 'CPF') {
         strCPF_CNPJTemp = '000' + strCPF_CNPJTemp;
         blnValido = VerificaCPF(strCPF_CNPJTemp);
       } else {
         blnValido = VerificaCNPJ(strCPF_CNPJTemp);
       }
       if (!blnValido) {
		 window.alert(strTipoValidacao + ' inválido');
	   }
	   return blnValido;
    } else {
      window.alert(strTipoValidacao + ' deve ter ' + intNumMaxDigitos + ' dígitos.');
      return false;
    }
  }
}

// FUNCAO AUXILIAR PARA VALIDACAO DO CNPJ
function VerificaCNPJ(strCNPJ){
  var intDigitoVerificador = 0;
  var intValorDigitos = 0;
	
  intValorDigitos = (parseInt(strCNPJ.charAt(0)) * 5);
  intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(1)) * 4);
  intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(2)) * 3);
  intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(3)) * 2);
  intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(4)) * 9);
  intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(5)) * 8);
  intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(6)) * 7);
  intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(7)) * 6);
  intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(8)) * 5);
  intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(9)) * 4);
  intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(10)) * 3);
  intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(11)) * 2);

  intDigitoVerificador = CalculoAuxiliar(intValorDigitos);

  if (parseInt(strCNPJ.charAt(12)) != intDigitoVerificador) {
	return false;
  } else {
    intValorDigitos = (parseInt(strCNPJ.charAt(0)) * 6);
    intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(1)) * 5);
    intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(2)) * 4);
    intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(3)) * 3);
    intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(4)) * 2);
    intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(5)) * 9);
    intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(6)) * 8);
    intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(7)) * 7);
    intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(8)) * 6);
    intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(9)) * 5);
    intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(10)) * 4);
    intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(11)) * 3);
    intValorDigitos = intValorDigitos + (parseInt(strCNPJ.charAt(12)) * 2);
    
    intDigitoVerificador = CalculoAuxiliar(intValorDigitos);

    if (parseInt(strCNPJ.charAt(13)) != intDigitoVerificador) {
      return false;
    }
  }
  
  return true;
}


// FUNCAO AUXILIAR PARA VALIDACAO DO CPF
function VerificaCPF(strCPF){
  var intDigitoVerificador = 0;
  var intValorDigitos = 0;
  var blnNrRepetido = true;
  
  intValorDigitos = (parseInt(strCPF.charAt(3)) * 10);
  intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(4)) * 9);
  intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(5)) * 8);
  intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(6)) * 7);
  intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(7)) * 6);
  intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(8)) * 5);
  intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(9)) * 4);
  intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(10)) * 3);
  intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(11)) * 2);

  intDigitoVerificador = CalculoAuxiliar(intValorDigitos);

  if (parseInt(strCPF.charAt(12)) != intDigitoVerificador) {
    return false;
  } else {
    intValorDigitos = (parseInt(strCPF.charAt(3)) * 11);
    intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(4)) * 10);
    intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(5)) * 9);
    intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(6)) * 8);
    intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(7)) * 7);
    intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(8)) * 6);
    intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(9)) * 5);
    intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(10)) * 4);
    intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(11)) * 3);
    intValorDigitos = intValorDigitos + (parseInt(strCPF.charAt(12)) * 2);

    intDigitoVerificador = CalculoAuxiliar(intValorDigitos);
    
	if (parseInt(strCPF.charAt(13)) != intDigitoVerificador){
      return false;
    }
  }
  
  /* Verifica se todos os números do CPF são iguais excluindo 
     os 3 zeros que são concatenados na chamada da rotina */
 for(i=4;i<14;i++)
  {
	  if(strCPF.charAt(i-1) != strCPF.charAt(i)) {
	  	blnNrRepetido=false;
		break;
	  }
  }

  return (!blnNrRepetido); 

}

// FUNCAO AUXILIAR PARA VALIDACAO DO CPF E CNPJ
function CalculoAuxiliar(intValorDigitos){
  var intDigitoVerificador = 0;
  var intResultadoDivisao = 0;
  var intValorResto = 0;

  if (intValorDigitos == 0) {
    return 0;
  } else {
    intResultadoDivisao = (intValorDigitos / 11);
    intValorResto = (intValorDigitos % 11);
    intDigitoVerificador = (11 - intValorResto);

	if (intDigitoVerificador > 9){
	  return 0;
	} else {
	  return intDigitoVerificador;
	}
  }
}

// ******************************************************************
// FIM DAS FUNCOES DE VALIDACAO DE CPF E CNPJ
// ******************************************************************


//Verifica a validade de um endereco de e-mail.
//Retorna True se o e-mail for valido,e
//False se o e-mail nao for valido.
function ValidaEmail (strEmail) {
	/* A sentença descrita abaixo é usada para validar se o endereço de e-mail informado
	   obedece ao formato usuario@dominio. É tambem utilizado para separar o nome do usuário
       do dominio.*/
	
	var strEmailPadrao=/^(.+)@(.+)$/

	/* A sentença descrita abaixo define a maáscara para filtrar todos os caracteres especiais.
	   Nós não queremos permitir esses caracteres nos endereços de e-mail.
	   Caracteres especiais incluem: ( ) < > @ , ; : \ " . [ ] */

	var strCharsEspeciais="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"

	/* A sentença seguinte representa o grupo de caracteres permitidos no nome do usuário
       ou domínio. Definindo quais caracteres não são permitidos. */

	var strCharsValidos="\[^\\s" + strCharsEspeciais + "\]"

	/* A sentença seguinte verifica se o "usuário" é quoted string (e-mail entre Aspas).
       Caso em que não existe nenhuma regra definindo quais são os caracteres permitidos ou 
       não permitidos. Qualquer caracter passa. Ex.: "jiminy cricket@disney.com" eh um e-mail
       válido. */

	var quotedUser="(\"[^\"]*\")"

	/* A sentença seguinte se aplica para domínios que são Endereços IP, ao invés de nomes
       simbólicos. Ex.: joe@[123.124.233.4] é um endereço de e-mail válido.
       ATENÇÃO: Os colchetes sao obrigatórios.  */

	var strDominioIP=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/

	/* A sentença seguinte representa uma série de caracteres não especiais. */

	var atom=strCharsValidos + '+'

	/* The following string represents one word in the typical username.
	   For example, in john.doe@somewhere.com, john and doe are words.
       Basically, a word is either an atom or quoted string.*/ // <----- TRADUZIR 

	var strPalavra="(" + atom + "|" + quotedUser + ")"

    // A sentença seguinte descreve a estrutura para o nome do usuário.

	var strFormatoUser=new RegExp("^" + strPalavra + "(\\." + strPalavra + ")*$")

	/* A sentença seguinte descreve a estrutura para um domínio simbólico, ao invés do
       domínio utilizando Endereco IP, demonstrado acima. */

	var strFormatoDominio=new RegExp("^" + atom + "(\\." + atom +")*$")

	/* Finalmente, vamos iniciar a verificação se o e-mail fornecido é válido.*/

	var VetorValidacao=strEmail.match(strEmailPadrao)

	if (VetorValidacao==null) {
		/* Muito/Poucos @'s ou outra coisa, como pontos; basicamente, esse endereço 
		   não apresenta o formato de um endereço válido de e-mail. */
	
		//alert("Endereço de Email incorreto! (Verifique @ e .'s)")
		
		window.alert("Endereço eletrônico inválido.")
		return false
	}

	var strUsuario=VetorValidacao[1]
	var strDominio=VetorValidacao[2]

	// Verificando se o "usuário" é válido.

	if (strUsuario.match(strFormatoUser)==null){
        //alert("O nome do usuário não é válido.")
		
		window.alert("Endereço eletrônico inválido.")
		return false
	}

	/* Se o endereço de e-mail é um Endereço IP (oposto ao nome do domínio simbólico)
       verifique se o Endereço IP é válido.*/   
	
	var VetorIP=strDominio.match(strDominioIP)
	
	if (VetorIP!=null){
		// É um Endereço IP.
		
		for (var i=1;i<=4;i++) {
			if (VetorIP[i]>255) {
				//alert("Endereço IP inválido!") 
				window.alert("Endereço eletrônico inválido.")
				return false
			}
		}
		return true
	}

	// O Domínio é um nome simbólico.
	
	var VetorDominio=strDominio.match(strFormatoDominio)
	
	if (VetorDominio==null) {
		//alert("O nome do domínio não é válido!")
		
		window.alert("Endereço eletrônico inválido.")
		return false
	}
	
	/* O nome do domínio parece válido, mas agora certifique-se que termine em uma palavra com
       três caracteres (como: com, edu, gov,...) ou uma palavra de dois caracteres, representando 
       o país (como: br, uk, nl,...), e se o domínio ou o país é precedido por um host name. */

	/* Agora precisamos desmembrar o dominio para validadarmos as partes.*/
	
	var atomPat=new RegExp(atom,"g")
	var DomVet=strDominio.match(atomPat)
	var tam=DomVet.length
	if (DomVet[DomVet.length-1].length<2 || DomVet[DomVet.length-1].length>3) {
		// O endereço tem que terminar em uma palavra de dois ou três caracteres.
		//alert("O endereço deve terminar em um domínio com três caracteres ou em um país com dois caracteres.")
		
		window.alert("Endereço eletrônico inválido.")
		return false
	}

	// Certificando que o domínio é precedido por um hostname.
	if (tam<2) {
		var errStr="Este endereço não possui hostname!"
		//alert(errStr)
		window.alert("Endereço eletrônico inválido.")
		return false
	}

	// Se vc chegou até aqui, todo o resto é válido!
	
	return true;
}


// VERIFICA SE A STRING PASSADA EH UM NUMERO (EM PORTUGUES)
function isNumeric(strValor){
  var blnCorreto;
  var blnVirgulaAchada;
  var intTamanho;
  var cont;

  cont = 0;
  if(strValor.length == 0) {
	blnCorreto = false;
  } else {
    blnCorreto = true;
  }
  blnVirgulaAchada = false;
  intTamanho = strValor.length;
  while ((cont <= (intTamanho - 1)) && (blnCorreto == true)) {
    if (strValor.charAt(cont) == ',') {
      if (blnVirgulaAchada == false) {
        blnVirgulaAchada = true;
      } else {
        blnCorreto = false;
      }
    } else {
		if ((strValor.charAt(cont) < '0') || (strValor.charAt(cont) > '9')){
			blnCorreto = false; 
		}
    }
    cont++;
  }
  if ((intTamanho == 1) && (blnVirgulaAchada == true)) {
	blnCorreto = false;
  }

  return blnCorreto;
}

//Valida Data "dd/mm/yyyy"
function valida_data(strData){
	
	return(true);
}



//Valida Data - Format dd/mm/yyyy
function CriticaData(strinput){
	var barra1;
	var barra2;
	var parte1;
	var parte2;
	var partedia;
	var partemes;
	var parteano;
	var retorno;
	var restobisexto;
	var arrayultimodia;
	var datagerada;
	parte1=strinput.substr(0,3);
	barra1 = parte1.search("/");
	
	
	if (barra1 > 0 ){
			if (barra1 == 1){	
				partedia = "0" + parte1.substr(0,barra1);
			} else {
				partedia =  parte1.substr(0,barra1);
			}
			parte2=strinput.substr(barra1 + 1,3);
			barra2 = parte2.search("/");
			if (barra2 > 0){
				if (barra2 == 1){	
					partemes = "0" + parte2.substr(0,barra2);
				} else {
					partemes =  parte2.substr(0,barra2);
				}
				parteano = strinput.substr(1 + barra1 + barra2 + 1);
				
				if (parteano.length == 2){
					
					if (parseInt(parteano) > 50){
						parteano = 19 + parteano;
					} else {
						parteano = 20 + parteano;
					}
					restobisexto = parteano % 4;
					if (restobisexto != 0){
						arrayultimodia = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
					} else {
						arrayultimodia = new Array(31,29,31,30,31,30,31,31,30,31,30,31);
					}
					if (partemes > 0) {
						if (partemes <= 12)	{
							if (partedia > 0){
								if (partedia <= arrayultimodia[partemes-1])								{
									datagerada = new Date(parseInt(parteano),parseInt(partemes), parseInt(partedia));
									if (datagerada)									{
										retorno = true;
									}
								} else {
									retorno = false;
								}
							} else {
								retorno = false;
							}
						} else {
							retorno = false;
						}
					} else {
						retorno = false;
					}							
				} else {
					if (parteano.length == 4) {	
						restobisexto = parteano % 4;
						if (restobisexto != 0) {
							arrayultimodia = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
						} else {
							arrayultimodia = new Array(31,29,31,30,31,30,31,31,30,31,30,31);
						}
						if (partemes > 0) {
							if (partemes <= 12) {
								if (partedia > 0) {
									if (partedia <= arrayultimodia[partemes-1]){
										datagerada = new Date(parseInt(parteano),parseInt(partemes), parseInt(partedia));
										if (datagerada)	{
											retorno = true;
										}										
									} else {
										retorno = false;
									}
								} else {
									retorno = false;
								}
							} else {
								retorno = false;
							}
						} else {
							retorno = false;
						}
					} else {
						// ano com tamanho diferente de 2 e 4
							retorno = false;
					}
				}
			} else {
				// nao achou a segunda barra ou está na terceira posicao
				retorno = false;
			}
	} else {
		// nao achou a primeira barra ou está na primeira posicao
		retorno = false;
	}
	return retorno;
}

function Mensagem(strMsg) {
	//Verifica se existe alguma mensagem
	if(strMsg != ''){
		window.alert(strMsg);
	}
}




// Aqui inicia as funções de teste do CNPJ

function TestaCNPJ(form,nome) {
//	if (form[nome].value == "")
//		return true;
	if(!VerifyCNPJ(form[nome].value))
	{
		alert("Este CNPJ não é válido!");
		form[nome].focus();
		return false;
	}
	
	return true;
}



function isNUMB(c)
	{
	if((cx=c.indexOf(","))!=-1)
		{		
		c = c.substring(0,cx)+"."+c.substring(cx+1);
		}
	if((parseFloat(c) / c != 1))
		{
		if(parseFloat(c) * c == 0)
			{
			return(1);
			}
		else
			{
			return(0);
			}
		}
	else
		{
		return(1);
		}
	}

function LIMP(c)
	{
	while((cx=c.indexOf("-"))!=-1)
		{		
		c = c.substring(0,cx)+c.substring(cx+1);
		}
	while((cx=c.indexOf("/"))!=-1)
		{		
		c = c.substring(0,cx)+c.substring(cx+1);
		}
	while((cx=c.indexOf(","))!=-1)
		{		
		c = c.substring(0,cx)+c.substring(cx+1);
		}
	while((cx=c.indexOf("."))!=-1)
		{		
		c = c.substring(0,cx)+c.substring(cx+1);
		}
	while((cx=c.indexOf("("))!=-1)
		{		
		c = c.substring(0,cx)+c.substring(cx+1);
		}
	while((cx=c.indexOf(")"))!=-1)
		{		
		c = c.substring(0,cx)+c.substring(cx+1);
		}
	while((cx=c.indexOf(" "))!=-1)
		{		
		c = c.substring(0,cx)+c.substring(cx+1);
		}
	return(c);
	}

function VerifyCNPJ(CNPJ)
	{
	CNPJ = LIMP(CNPJ);
	if(isNUMB(CNPJ) != 1)
		{
		return(0);
		}
	else
		{
		if(CNPJ == 0)
			{
			return(0);
			}
		else
			{
			g=CNPJ.length-2;
			if(RealTestaCNPJ(CNPJ,g) == 1)
				{
				g=CNPJ.length-1;
				if(RealTestaCNPJ(CNPJ,g) == 1)
					{	
					return(1);
					}
				else
					{
					return(0);
					}
				}
			else
				{
				return(0);
				}
			}
		}
	}
function RealTestaCNPJ(CNPJ,g)
	{
	var VerCNPJ=0;
	var ind=2;
	var tam;
	for(f=g;f>0;f--)
		{
		VerCNPJ+=parseInt(CNPJ.charAt(f-1))*ind;
		if(ind>8)
			{
			ind=2;
			}
		else
			{
			ind++;
			}
		}
		VerCNPJ%=11;
		if(VerCNPJ==0 || VerCNPJ==1)
			{
			VerCNPJ=0;
			}
		else
			{
			VerCNPJ=11-VerCNPJ;
			}
	if(VerCNPJ!=parseInt(CNPJ.charAt(g)))
		{
		return(0);
		}
	else
		{
		return(1);
		}
	}
// Aqui Finaliza as Funcoes de CNPJ 

function MM_openBrWindow(theURL,winName,features) { 
  window.open(theURL,winName,features);
}

// formatar numeros para moeda
// ex: entrada - 123      saida - 123,00
// 	 entrada - 123.4    saida - 123,40
// 	 entrada - 123,4    saida - 123,40
// 	 entrada - 2123.4   saida - 2.123,40
// 	 entrada - 2123,4   saida - 2.123,40
function FormatCurrency(xValue){

		 xValue = xValue.toString()
		 
		 var decimal = "0000000000000000000"
		 var nDec = 2;
		 	
		 //Retornar zero se valor vazio
		 if (xValue=="")return("0,00");

		while (xValue.indexOf(".") != -1){xValue=xValue.replace(".","")};

		 if (xValue.indexOf(",") < 0 && xValue.indexOf(".") >= 0){
		 		xValue = xValue.replace(".", ",")
		 }
		 
		 var Cents;
		 if (xValue.indexOf(",") >= 0){
		 		Cents = xValue.slice(xValue.indexOf(","))
				if (Cents.length < 3){
					Cents = Cents + "0"
				}
				else
				if (Cents.length > 3){
					Cents = Cents.slice(0,3)
				}
				xValue = xValue.slice(0, xValue.indexOf(","))
		 }
		 else{
		 		Cents = ",00"		
		 }

		 if(xValue=='') {xValue=0};
		 
		 var onlyNumbers = xValue;

		 //Retirar Zeros a esquerda
		 onlyNumbers=parseInt(onlyNumbers,10)
		 
		 onlyNumbers = onlyNumbers.toString();
		 
	 	 var lenN = onlyNumbers.length;		 
		 var tChar=0;
		 var s="";

		 //Formata o valor 
		 for (var i=lenN-(1); i>=0; i--){
		 
			 tChar++; 
			 s = onlyNumbers.substring(i,i+1) + s;

			 if (tChar == 3 && i != 0){
			 	s= "." + s;  tChar=0;
			 }
		 }		 
		 
		 s = s + Cents
		 
		 return(s);
}

function replace(originalString,searchText,replaceText){

		 var strReturn = originalString.toString()
		 while (strReturn.indexOf(searchText) != -1){strReturn=strReturn.replace(searchText,replaceText)};
		 return strReturn;
} 

//Valida se o Conteudo do ClipBoad colado
//esta de acordo com o tipo de dado do controle: usar no onbeforepaste="validaPaste(this, 'N')"
function validaPaste(oControl,dataType){
		
		var strPaste = clipboardData.getData("Text");

		if (trim(strPaste) == ""){
			event.returnValue=true; 
		}

		
		switch(dataType.toUpperCase()){
			case "N":{ /*		Numeros		*/
				if (!isNumeric(strPaste)){
					alert("Este campo só permite números");
					event.returnValue = false; 
				}
				break;
			}
			case "D":{ /*		Datas		*/
				if (!verifica_data(oControl)){
					event.returnValue = false; 
				}
				break;
			}
			case "H":{  /*		Horas		*/
				if (!verifica_hora(oControl)){
					event.returnValue = false; 
				}
				break;
			}
			case "E":{ /*		Emails		*/
				if (!ValidaEmail(strPaste)){
					alert("Entre com um email válido");
					event.returnValue = false; 
				}
				break;
			}
			
			default:{ break; }

		}
	
}

function usarMascara(oControl, Mask){
	var s, lM;
	var valid = "0123456789";

	if (oControl.style.textAlign.toUpperCase() == "RIGHT"){
			for (i=oControl.value.length-1; i >= 0; i--){
					if(valid.indexOf(oControl.value.charAt(i)) != "-1"){

							lM = Mask.lastIndexOf("#")
							s = Mask.substr(0,lM) + oControl.value.charAt(i) +  Mask.substr(lM+1)
							Mask = s;
					}
			}
	}
	else{
			for (i=0; i < oControl.value.length; i++){
					if(valid.indexOf(oControl.value.charAt(i)) != "-1"){
							lM = Mask.indexOf("#")
							s = Mask.substr(0,lM) + oControl.value.charAt(i) +  Mask.substr(lM+1)
							Mask = s;
					}
			}
	}

	while (valid.indexOf(Mask.charAt(0)) == "-1"){Mask = Mask.replace(Mask.charAt(0),'');}
	oControl.value = Mask
}

function UltimoDiaMes(pMes, pAno){
	var Dia;
	if ((pMes == 1) || (pMes == 3) || (pMes == 5) ||
		(pMes == 7) || (pMes == 8) || (pMes == 10) ||
		(pMes == 12)){
		Dia = '31';
	}
	else {
		if ((pMes == 4) || (pMes == 6) ||
			(pMes == 9) || (pMes == 11)){
			Dia = '30';
		}
		else {
			if ((pMes == 2) && ((pAno % 4) == 0)){
				Dia = '29';
			}
			else{
				Dia = '28';
			}	
		}
	}
	return Dia;
}

function ValidaFisico_ItemServ_Deslocamento(intQtd) {
	//Utilizada para os itens 1318 e 1323
	if (intQtd < 100) {
		return false;
	}
	else 	{
		return true;
	}
}


