function f_Alerta(msg, campo)
{
	campo.focus();
	$.growlUI("Alerta", msg, 5000, function(){},"growlUIAlerta");
}

/*
Funcoes:

carregaValor (comboBox)
	seleciona todos os valores do comboBox para pegar valores via REQUEST.FORM

move (campo1, campo2)
	move valores do campo1 para o campo2 e vice-versa

fPopPaletaCor(campo)
		Abre popup do calendário
		
fPopData(campo)
		Abre popup do calendário
		
fAbrePopup(endereco)
		Abre popup
		
destacaLinha
		Coloca em destaque a linha da tabela na cor cinza

normalizaLinha
		Devolve a cor da tabela para branco
		
ConsisteCampoBranco(valor)
		Consiste se foi preenchido o campo
		
LimpaEspacoBranco(valor)
		Limpa os espaços em branco na string tanto inicial quanto final

LimpaEspacoBrancoAll(valor)
		Limpa os espaços em branco, caracter de return e quebar de linha
		
ConsisteNumero(valor)
      Recebe um valor e verifica se é numero ou nao

ConsisteIntreiro(valor)
      Recebe um valor e verifica se é numero ou nao considerando número negativo

ConsisteString(valor)
      Recebe um valor e verifica se é string ou nao

ConsisteTelefone(valor)
      Recebe uma string no formato de telefone (XX [X]XXX-XXXX) e valida

ConsisteDecimal(valor)
			Recebe um valor e verifica se é um decimal ou não
			
ConsisteData(valor)
			Recebe uma string no format dd/mm/yyyy e verifica se é uma data válida ou não
		
ConsisteEmail(valor)
      Recebe uma string e valida se é email ou não

ConsiteCGCCPF(valor)
      Recebe uma string e valida se é CPF ou CNPJ

ConsisteCEP(valor)
      Recebe um valor com 8 digitos e valida

Arredonda(valor)
      Arredonda um valor no formato #####.##### para baixo e 2 casas

RetornaData()
			Retorna a data corrente no formato dd/mm/yyyy
			
SomaData(Campo,Soma)
			Retorna a data passada no formato dd/mm/yyyy acrescentado da quantidade de dias a serem somados			

SubtraiData(Campo,Valor)
			Retorna a data passada no formato dd/mm/yyyy diminuindo a quantidade de dias a serem subtraidos

ComparaData(DataIni,DataFin)
			Retorna true se a data inicial for menor que a data final, caso contrario, retorna false

ConsisteHora(Valor)
			Retorna true se a hora for válida

FormataHora(Valor, teclapress)
			Retorna a hora formatada hh:mm

FormataData(Valor, teclapress)
	Retorna a data formatada dd/MM/yyyy


FormataCep(Valor, teclapress)
	Retorna a data formatada dd/MM/yyyy

FormataPeriodo(Valor, teclapress)
	Retorna o periodo formatado MM/yyyy

ComparaHora(HoraIni,HoraFim)
			Retorna true se a hora inicial for menor que a hora final

ComparaHoraIgual(HoraIni,HoraFim)
			Retorna true se a hora inicial for menor ou igual que a hora final

ConsisteValorDigitado(Valor)
			Verifica se exite algum dos carecters não permitidos no campo ".,-_/ "

FormataTelaBanco(Valor)
			Formata valor para ser enviado ao banco de dados, troca a virgula por ponto

FormataBancoTela(Balor)
			Formata valor para ser enviado a tela, troca ponto por virgula
			
FormataValor(tam, fld,milSep, decSep, e)
			Formata o valor digitado para decimal

FormataStr(str, tam)
			Limita o numero de caracteres digitados (Usado em campos textarea)

TirarZerosEsquerda(STR)

FormataVlr(OBJ,tammax,teclapres)
			Formata o valor digitado, colocando , e .

DateFormat(vDateName, vDateValue, e, dateCheck, dateType)
			Formata a data digitada, coloca as barras automaticamente.

fDesabilitarEnter()
                                        Desabilita o enter para envio de formulário


autoTab()
	Funcao para pular de campos

Utf8.encode()
    Funcao para codificar valores da URL igual ao server.URLEncode
Utf8.decode()
    Funcao para decodificar valores da URL
*/

var Utf8 = {
 // public method for url encoding
 encode : function (string) {
 string = string.replace(/\r\n/g,"\n");
 var utftext = "";
 
 for (var n = 0; n < string.length; n++) {
  var c = string.charCodeAt(n);
  if (c < 128) {
   utftext += String.fromCharCode(c);
  }
  else if((c > 127) && (c < 2048)) {
   utftext += String.fromCharCode((c >> 6) | 192);
   utftext += String.fromCharCode((c & 63) | 128);
  }
  else {
   utftext += String.fromCharCode((c >> 12) | 224);
   utftext += String.fromCharCode(((c >> 6) & 63) | 128);
   utftext += String.fromCharCode((c & 63) | 128);
  }
 }
 return utftext;
},

 // public method for url decoding
 decode : function (utftext) {
  var string = "";
  var i = 0;
  var c = c1 = c2 = 0;
  
  while ( i < utftext.length ) {
   c = utftext.charCodeAt(i);
   if (c < 128) {
    string += String.fromCharCode(c);
    i++;
   }
   else if((c > 191) && (c < 224)) {
    c2 = utftext.charCodeAt(i+1);
    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
    i += 2;
   }
   else {
    c2 = utftext.charCodeAt(i+1);
    c3 = utftext.charCodeAt(i+2);
    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
    i += 3;
   }
  }
  return string;
 }
}

function modalWin(pUrl, pWidth, pHeight) {
	if (window.showModalDialog) {
		window.showModalDialog(pUrl, window,  "dialogWidth:" + pWidth + "px;dialogHeight:" + pHeight + "px; status:no; center:yes; help:no; minimize:no; maximize:no; border:no; statusbar:no; scrool: no; unadorned: no; resizable: no;");
	} else {
		window.open(pUrl, "wndModal", "width=" + pWidth  + ",height=" + pHeight + ",resizable=no,modal=yes");
	}
}
 

function fArredonda( valor , casas )
{	
  var novo = Math.round( valor * Math.pow( 10 , casas ) ) / Math.pow( 10 , casas );
  return( novo.toString());
}

//função que retorna a diferença de dias entre duas datas.
function DateDiff(date1, date2){
    var dat1 = date1.split("/");
    var dat2 = date2.split("/");
    //converte a data para MM/DD/AAAA HH:MM
    var data1 = dat1[1]+"/"+dat1[0]+"/"+dat1[2]+" 00:00";
    var data2 = dat2[1]+"/"+dat2[0]+"/"+dat2[2]+" 00:00";
	var objDate1=new Date(data1);
	var objDate2=new Date(data2);
	return ((((objDate1.getTime()-objDate2.getTime())/1000)/60)/60)/24;
}


function fPopAgenda(idSolicitacao, idFornecedor, idCliente, idServico, idUnidade, NomeServico, idRecurso, dta_ini, hra_ini, dta_fim, hra_fim)
{
window.open("Agenda.asp?idSolicitacao="+idSolicitacao+"&idFornecedor="+idFornecedor+"&idCliente="+idCliente+"&idServico="+idServico+"&idUnidade="+idUnidade+"&NomeServico="+NomeServico+"&idRecurso="+idRecurso+"&A821_dta_ini="+dta_ini+"&A821_hra_ini="+hra_ini+"&A821_dta_fim="+dta_fim+"&A821_hra_fim="+hra_fim,"Agenda","height=500,width=730,left=10,screenX=10,top=10,screenY=10");
}


function MascaraValor(Valor)
{
	 var Aux = "";

	 if (Valor >= 0) {
	 Valor     = Valor.toString();

	 if (Valor.length == 1)
		 Aux = "0,0" + Valor.substr(0,1);
	 if (Valor.length == 2)
		 Aux = "0," + Valor.substr(0,2);
		 if (Valor.length == 3)
		 Aux = Valor.substr(0,1) + "," + Valor.substr(1,2);
	 if (Valor.length == 4)
		 Aux = Valor.substr(0,2) + "," + Valor.substr(2,2);
	 if (Valor.length == 5)
		 Aux = Valor.substr(0,3) + "," + Valor.substr(3,2);
	 if (Valor.length == 6)
		 Aux = Valor.substr(0,1) + "." + Valor.substr(1,3) + "," + Valor.substr(4,2);
	 if (Valor.length == 7)
		 Aux = Valor.substr(0,2) + "." + Valor.substr(2,3) + "," + Valor.substr(5,2);
	 if (Valor.length == 8)
		 Aux = Valor.substr(0,3) + "." + Valor.substr(3,3) + "," + Valor.substr(6,2);
	}
else {
	 Valor = Valor.toString();

	 if (Valor.length == 2)
		 Aux = "-0,0" + Valor.substr(1,1);
		 if (Valor.length == 3)
		 Aux = "-0," + Valor.substr(1,2) ;
	 if (Valor.length == 4)
		 Aux = "-" + Valor.substr(1,1) + "," + Valor.substr(2,2);
	 if (Valor.length == 5)
		 Aux = "-" + Valor.substr(1,2) + "," + Valor.substr(3,2);
	 if (Valor.length == 6)
		 Aux = "-" + Valor.substr(1,3) + "," + Valor.substr(4,2);
	 if (Valor.length == 7)
		 Aux = "-" + Valor.substr(1,1) + "." + Valor.substr(2,3) + "," + Valor.substr(5,2);
	 if (Valor.length == 8)
		 Aux = "-" + Valor.substr(1,2) + "." + Valor.substr(3,3) + "," + Valor.substr(6,2);
	 if (Valor.length == 9)
		 Aux = "-" + Valor.substr(1,3) + "." + Valor.substr(4,3) + "," + Valor.substr(7,2);
}

 return Aux;	

}

// Funcao para formatar um número com 4 casas decimais
function MascaraValor4(Valor)
{
	 var Aux = "";

	 if (Valor >= 0) {
	 Valor     = Valor.toString();

	 if (Valor.length == 1)
		 Aux = "0,0" + Valor.substr(0,1);
	 if (Valor.length == 2)
		 Aux = "0," + Valor.substr(0,2);
	 if (Valor.length == 3)
		 Aux = "0," + Valor.substr(0,3);
	 if (Valor.length == 4)
		 Aux = "0," + Valor.substr(0,4);
	 if (Valor.length == 5)
	 Aux = Valor.substr(0,1) + "," + Valor.substr(1,4);
	 if (Valor.length == 6)
		 Aux = Valor.substr(0,2) + "," + Valor.substr(2,4);
	 if (Valor.length == 7)
		 Aux = Valor.substr(0,3) + "," + Valor.substr(3,4);
	 if (Valor.length == 8)
		 Aux = Valor.substr(0,1) + "." + Valor.substr(1,3) + "," + Valor.substr(4,4);
	 if (Valor.length == 9)
		 Aux = Valor.substr(0,2) + "." + Valor.substr(2,3) + "," + Valor.substr(5,4);
	 if (Valor.length == 10)
		 Aux = Valor.substr(0,3) + "." + Valor.substr(3,3) + "," + Valor.substr(6,4);
	}
else {
	 Valor = Valor.toString();

	 if (Valor.length == 1)
		 Aux = "-0,0" + Valor.substr(0,1);
	 if (Valor.length == 2)
		 Aux = "-0," + Valor.substr(0,2);
	 if (Valor.length == 3)
		 Aux = "-0," + Valor.substr(0,3);
	 if (Valor.length == 4)
		 Aux = "-0," + Valor.substr(0,4);
	 if (Valor.length == 5)
		 Aux = "-" + Valor.substr(0,1) + "," + Valor.substr(1,4);
	 if (Valor.length == 6)
		 Aux = "-" + Valor.substr(0,2) + "," + Valor.substr(2,4);
	 if (Valor.length == 7)
		 Aux = "-" + Valor.substr(0,3) + "," + Valor.substr(3,4);
	 if (Valor.length == 8)
		 Aux = "-" + Valor.substr(0,1) + "." + Valor.substr(1,3) + "," + Valor.substr(4,4);
	 if (Valor.length == 9)
		 Aux = "-" + Valor.substr(0,2) + "." + Valor.substr(2,3) + "," + Valor.substr(5,4);
	 if (Valor.length == 10)
		 Aux = "-" + Valor.substr(0,3) + "." + Valor.substr(3,3) + "," + Valor.substr(6,4);
}

 return Aux;	

}


// Funcao para pular para o proximo campo
function autoTab(input, len, e)
{
	var isNN = (navigator.appName.indexOf("Netscape") != -1); 
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46]; 

	if (input.value.length >= len && !containsElement(filter, keyCode))
	{
		input.value = input.value.slice(0, len); 
		var i=1;
		while ((input.form[(getIndex(input)+i) % input.form.length].disabled) || (input.form[(getIndex(input)+i) % input.form.length].type == 'hidden'))
		{
			i++;
		}
		input.form[(getIndex(input)+i) % input.form.length].focus(); 
	} 

	// Função auxiliar do autoTab Para contar os elementos da tela
	function containsElement(arr, ele) 
	{ 
		var found = false, index = 0; 
		while (!found && index < arr.length)
		{
			if (arr[index] == ele) 
				found = true; 
			else 
				index++; 
		}		
		return found; 
	} 

	// Função auxiliar do autoTab Para pular de campo
	function getIndex(input) 
	{ 
		var index = -1, i = 0, found = false; 
		while (i < input.form.length && index == -1) 
			if (input.form[i] == input)
				index = i; 
			else 
				i++; 
			return index; 
	} 
	return true; 
} 

// Calcula o Tamanho do iframe
  function calcHeight(AuxFrame)
  {
    document.getElementById(AuxFrame).style.filter = "blendTrans(duration=1.0)";
	  document.getElementById(AuxFrame).filters.blendTrans.apply();
	  document.getElementById(AuxFrame).filters.blendTrans.play();
	
	  var the_height = parseInt(document.frames[AuxFrame].document.body.scrollHeight);
    document.getElementById(AuxFrame).style.height = the_height;

  }





// Check browser version
var isNav4 = false, isNav5 = false, isIE4 = false
var strSeperator = "/"; 
var vDateType = 3; 
var vYearType = 4; 
var vYearLength = 2; 
var err = 0; 
if(navigator.appName == "Netscape") {
	if (navigator.appVersion < "5") {
		isNav4 = true;
		isNav5 = false;
	}
	else
		if (navigator.appVersion > "4") {
			isNav4 = false;
			isNav5 = true;
   	}
}
else {
	isIE4 = true;
}

function formataValor(num,separadorMil,separadorDec) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3)) +separadorMil+ num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + num + separadorDec + cents);
}

function DateFormat(vDateName, vDateValue, e, dateCheck, dateType) {
vDateType = 3;
if (vDateValue == "~") {
	alert("AppVersion = "+navigator.appVersion+" \nNav. 4 Version = "+isNav4+" \nNav. 5 Version = "+isNav5+" \nIE Version = "+isIE4+" \nYear Type = "+vYearType+" \nDate Type = "+vDateType+" \nSeparator = "+strSeperator);
	vDateName.value = "";
	vDateName.focus();
	return true;
}
var whichCode = (window.Event) ? e.which : e.keyCode;
if (vDateValue.length > 8 && isNav4) {
	if ((vDateValue.indexOf("-") >= 1) || (vDateValue.indexOf("/") >= 1))
		return true;
}
var alphaCheck = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/-";
if (alphaCheck.indexOf(vDateValue) >= 1) {
	if (isNav4) {
		vDateName.value = "";
		vDateName.focus();
		vDateName.select();
		return false;
	}
	else {
		vDateName.value = vDateName.value.substr(0, (vDateValue.length-1));
		return false;
  }
}
if (whichCode == 8)
	return false;
else {
	var strCheck = '47,48,49,50,51,52,53,54,55,56,57,58,59,95,96,97,98,99,100,101,102,103,104,105';
	if (strCheck.indexOf(whichCode) != -1) {
		if (isNav4) {
			if (((vDateValue.length < 6 && dateCheck) || (vDateValue.length == 7 && dateCheck)) && (vDateValue.length >=1)) {
				alert("Data Inválida\nFavor entrar com uma data válida");
				vDateName.value = "";
				vDateName.focus();
				vDateName.select();
				return false;
			}
			if (vDateValue.length == 6 && dateCheck) {
				var mDay = vDateName.value.substr(2,2);
				var mMonth = vDateName.value.substr(0,2);
				var mYear = vDateName.value.substr(4,4)
				if (mYear.length == 2 && vYearType == 4) {
					var mToday = new Date();
					var checkYear = mToday.getFullYear() + 30; 
					var mCheckYear = '20' + mYear;
					if (mCheckYear >= checkYear)
						mYear = '19' + mYear;
					else
						mYear = '20' + mYear;
				}
				var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
				if (!dateValid(vDateValueCheck)) {
					alert("Data Inválida\nFavor entrar com uma data válida");
					vDateName.value = "";
					vDateName.focus();
					vDateName.select();
					return false;
				}
				return true;
			}
			else {
				if (vDateValue.length >= 8  && dateCheck) {
					if (vDateType == 1){
						var mDay = vDateName.value.substr(2,2);
						var mMonth = vDateName.value.substr(0,2);
						var mYear = vDateName.value.substr(4,4)
						vDateName.value = mMonth+strSeperator+mDay+strSeperator+mYear;
					}
					if (vDateType == 2){
						var mYear = vDateName.value.substr(0,4)
						var mMonth = vDateName.value.substr(4,2);
						var mDay = vDateName.value.substr(6,2);
						vDateName.value = mYear+strSeperator+mMonth+strSeperator+mDay;
					}
					if (vDateType == 3){
						var mMonth = vDateName.value.substr(2,2);
						var mDay = vDateName.value.substr(0,2);
						var mYear = vDateName.value.substr(4,4)
						vDateName.value = mDay+strSeperator+mMonth+strSeperator+mYear;
					}
					var vDateTypeTemp = vDateType;
					vDateType = 1;
					var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
					if (!dateValid(vDateValueCheck)) {
						alert("Data Inválida\nFavor entrar com uma data válida");
						vDateType = vDateTypeTemp;
						vDateName.value = "";
						vDateName.focus();
						vDateName.select();
						return false;
					}
					vDateType = vDateTypeTemp;
					return true;
				}
				else {
				if (((vDateValue.length < 8 && dateCheck) || (vDateValue.length == 9 && dateCheck)) && (vDateValue.length >=1)) {
					alert("Data Inválida\nFavor entrar com uma data válida");
					vDateName.value = "";
					vDateName.focus();
					vDateName.select();
					return false;
        }
			}
		}
	}
	else {
		if (((vDateValue.length < 8 && dateCheck) || (vDateValue.length == 9 && dateCheck)) && (vDateValue.length >=1)) {
			alert("Data Inválida\nFavor entrar com uma data válida");
			vDateName.value = "";
			vDateName.focus();
			return true;
		}
		if (vDateValue.length >= 8 && dateCheck) {
			if (vDateType == 1){
				var mMonth = vDateName.value.substr(0,2);
				var mDay = vDateName.value.substr(3,2);
				var mYear = vDateName.value.substr(6,4)
			}
			if (vDateType == 2){
				var mYear = vDateName.value.substr(0,4)
				var mMonth = vDateName.value.substr(5,2);
				var mDay = vDateName.value.substr(8,2);
			}
			if (vDateType == 3){
				var mDay = vDateName.value.substr(0,2);
				var mMonth = vDateName.value.substr(3,2);
				var mYear = vDateName.value.substr(6,4)
			}
			if (vYearLength == 4) {
				if (mYear.length < 4) {
					alert("Data Inválida\nFavor entrar com uma data válida");
					vDateName.value = "";
					vDateName.focus();
					return true;
   			}
			}
			var vDateTypeTemp = vDateType;
			vDateType = 1;
			var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
			if (mYear.length == 2 && vYearType == 4 && dateCheck) {
				var mToday = new Date();
				var checkYear = mToday.getFullYear() + 30; 
				var mCheckYear = '20' + mYear;
				if (mCheckYear >= checkYear)
					mYear = '19' + mYear;
				else
					mYear = '20' + mYear;
				vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
				if (vDateTypeTemp == 1) // mm/dd/yyyy
					vDateName.value = mMonth+strSeperator+mDay+strSeperator+mYear;
				if (vDateTypeTemp == 3) // dd/mm/yyyy
					vDateName.value = mDay+strSeperator+mMonth+strSeperator+mYear;
			} 
			if (!dateValid(vDateValueCheck)) {
				alert("Data Inválida\nFavor entrar com uma data válida");
				vDateType = vDateTypeTemp;
				vDateName.value = "";
				vDateName.focus();
				return true;
			}
			vDateType = vDateTypeTemp;
			return true;
		}
		else {
			if (vDateType == 1) {
				if (vDateValue.length == 2) {
					vDateName.value = vDateValue+strSeperator;
				}
				if (vDateValue.length == 5) {
					vDateName.value = vDateValue+strSeperator;
   			}
			}
			if (vDateType == 2) {
				if (vDateValue.length == 4) {
					vDateName.value = vDateValue+strSeperator;
				}
				if (vDateValue.length == 7) {
					vDateName.value = vDateValue+strSeperator;
   			}
			} 
			if (vDateType == 3) {
				if (vDateValue.length == 2) {
					vDateName.value = vDateValue+strSeperator;
				}
				if (vDateValue.length == 5) {
					vDateName.value = vDateValue+strSeperator;
   			}
			}
			return true;
		}
	}
	if (vDateValue.length == 10&& dateCheck) {
		if (!dateValid(vDateName)) {
			alert("Data Inválida\nFavor entrar com uma data válida");
			vDateName.focus();
			vDateName.select();
   	}
	}
	return false;
}
else {
	if (isNav4) {
		vDateName.value = "";
		vDateName.focus();
		vDateName.select();
		return false;
	}
	else{
		vDateName.value = vDateName.value.substr(0, (vDateValue.length-1));
		return false;
	}
}
}
}

function dateValid(objName) {
var strDate;
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var booFound = false;
var datefield = objName;
var strSeparatorArray = new Array("-"," ","/",".");
var intElementNr;
// var err = 0;
var strMonthArray = new Array(12);
strMonthArray[0] = "Jan";
strMonthArray[1] = "Feb";
strMonthArray[2] = "Mar";
strMonthArray[3] = "Apr";
strMonthArray[4] = "May";
strMonthArray[5] = "Jun";
strMonthArray[6] = "Jul";
strMonthArray[7] = "Aug";
strMonthArray[8] = "Sep";
strMonthArray[9] = "Oct";
strMonthArray[10] = "Nov";
strMonthArray[11] = "Dec";
//strDate = datefield.value;
strDate = objName;
if (strDate.length < 1) {
return true;
}
for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
strDateArray = strDate.split(strSeparatorArray[intElementNr]);
if (strDateArray.length != 3) {
err = 1;
return false;
}
else {
strDay = strDateArray[0];
strMonth = strDateArray[1];
strYear = strDateArray[2];
}
booFound = true;
   }
}
if (booFound == false) {
if (strDate.length>5) {
strDay = strDate.substr(0, 2);
strMonth = strDate.substr(2, 2);
strYear = strDate.substr(4);
   }
}
//Adjustment for short years entered
if (strYear.length == 2) {
strYear = '20' + strYear;
}
strTemp = strDay;
strDay = strMonth;
strMonth = strTemp;
intday = parseInt(strDay, 10);
if (isNaN(intday)) {
err = 2;
return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth)) {
for (i = 0;i<12;i++) {
if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
intMonth = i+1;
strMonth = strMonthArray[i];
i = 12;
   }
}
if (isNaN(intMonth)) {
err = 3;
return false;
   }
}
intYear = parseInt(strYear, 10);
if (isNaN(intYear)) {
err = 4;
return false;
}
if (intMonth>12 || intMonth<1) {
err = 5;
return false;
}
if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
err = 6;
return false;
}
if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
err = 7;
return false;
}
if (intMonth == 2) {
if (intday < 1) {
err = 8;
return false;
}
if (LeapYear(intYear) == true) {
if (intday > 29) {
err = 9;
return false;
   }
}
else {
if (intday > 28) {
err = 10;
return false;
      }
   }
}
return true;
}

function LeapYear(intYear) {
	if (intYear % 100 == 0) {
		if (intYear % 400 == 0) { return true; }
	}else {
		if ((intYear % 4) == 0) { return true; }
	}
	return false;
}


//muda o src da imagem
function moveover(p_Over,p_Name)
{
document.images[p_Name].src = p_Over;
}

function moveback(p_Out,p_Name)
{
document.images[p_Name].src = p_Out;
}

function trocaVirgulaPonto(valor)
{
  var sStr=valor;
//  sStr = sStr.replace(".","")
  while(sStr.indexOf(".") != -1)
	  sStr = sStr.replace(".","")
  sStr = sStr.replace(",",".")
  return sStr;
}

function trocaPontoVirgula(valor)
{
	var sStr=valor;
  sStr = sStr.replace(".",",")
  return sStr;
}


function TirarZerosEsquerda(STR)
{
  var sAux='';
  var i=0;
  STR=new String(STR);
  while (i < STR.length )
  {
    if ((STR.charAt(i)!='.') && (STR.charAt(i)!=','))
    {
	  	sAux += STR.charAt(i);
    }
		i++
  }
  STR = new String(sAux);
  sAux = '';
  i=0;
  while (i < STR.length )
  {
    if (STR.charAt(i) != '0')
    {
      sAux = STR.substring(i,STR.length)
	  	i = STR.length;
		}
    i++;
  }
  return  sAux;
}

function FormataVlr(OBJ,tammax,teclapres){
  var decimal,inteiro;
  var i,count;
  STR = new String(OBJ.value);

  inteiro='';
		if (isIE4) {
			if (OBJ.maxLength > STR.length){
				STR = TirarZerosEsquerda(STR); //ESTA FUNCAO TIRA TAMBEM PONTO E VIRGULA
				if ( ((event.keyCode > 47) && (event.keyCode < 59)) || ((event.keyCode > 95) && (event.keyCode < 106))   ){
	
					if (STR.length == 0){
						inteiro  = '0';
						decimal = '0' + STR;
					}else {
						if (STR.length == 1){
							inteiro  = '0';
							decimal = STR;
						}else{
							decimal = STR.substring(STR.length-1,STR.length);
							i=2;
							count=0;
							while (i<=STR.length){
								if (count==3) {
									inteiro = '.' + inteiro;
									count = 0;
								}
								inteiro = STR.charAt(STR.length-i) + inteiro;
								count++;
								i++;
							}
						}
					}
				}else{
					if (event.keyCode == 8){
						if (STR.length == 0){
							inteiro  = '0';
							decimal = '000';
						} else {
							if (STR.length == 1){
								inteiro  = '0';
								decimal = '00' + STR;
							} else {
								if (STR.length == 2){
									inteiro  = '0';
									decimal = '0' + STR;
								}else{
									decimal = STR.substring(STR.length-3,STR.length);
									i=4;
									count=0;
									while (i<=STR.length){
										if (count==3) {
											inteiro = '.' + inteiro;
											count = 0;
										}
										inteiro = STR.charAt(STR.length-i) + inteiro;
										count++;
										i++;
									}
								}
							}
						}
					}	else {
						if (STR.length == 1){
							inteiro  = '0';
							decimal = '0' + STR;
					} else {
						if (STR.length == 2){
							inteiro  = '0';
							decimal = STR;
						}else{
							decimal = STR.substring(STR.length-2,STR.length);
							i=3;
							count=0;
							while (i<=STR.length){
								if (count==3) {
									inteiro = '.' + inteiro;
									count = 0;
								}
								inteiro = STR.charAt(STR.length-i) + inteiro;
								count++;
								i++;
							}
						}
					}
				}
			}
				if (inteiro == '') {
					inteiro = '0';
				}
				if (decimal == '') {
					decimal = '00';
				}
				OBJ.value = inteiro+','+decimal;
			}
		}else{
			var tecla = teclapres.keyCode;
			valorSemFormato = OBJ.value;
			valorSemFormato = valorSemFormato.replace( ",", "" );
			valorSemFormato = valorSemFormato.replace( ".", "" );
			valorSemFormato = valorSemFormato.replace( ".", "" );
			valorSemFormato = valorSemFormato.replace( ".", "" );
			valorSemFormato = valorSemFormato.replace( ".", "" );
			tamanho = valorSemFormato.length;
	
			if (tecla == 46) {
				OBJ.value = OBJ.value;
			}
			if (tamanho < tammax && tecla != 8) {
				tamanho = valorSemFormato.length + 1;
			}
			if (tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
				if (tecla == 8) {
					tamanho = tamanho - 1;
				}
				if (tamanho <= 2) {
					OBJ.value = valorSemFormato;
				} else if ((tamanho > 2) && (tamanho <= 5)) {
					OBJ.value = valorSemFormato.substr(0, tamanho - 2) + ',' +
					valorSemFormato.substr(tamanho - 2, tamanho);
				}else if ((tamanho >= 6) && (tamanho <= 8)) {
					OBJ.value = valorSemFormato.substr(0, tamanho - 5) + '.' +
					valorSemFormato.substr(tamanho - 5, 3) + ',' +
					valorSemFormato.substr(tamanho - 2, tamanho);
				}else if ((tamanho >= 9) && (tamanho <= 11)) {
					OBJ.value = valorSemFormato.substr(0, tamanho - 8) + '.' +
					valorSemFormato.substr(tamanho - 8, 3) + '.' +
					valorSemFormato.substr(tamanho - 5, 3) + ',' +
					valorSemFormato.substr(tamanho - 2, tamanho);
				}else if ((tamanho >= 12) && (tamanho <= 14)) {
					OBJ.value = valorSemFormato.substr(0, tamanho - 11) + '.' +
					valorSemFormato.substr(tamanho - 11, 3) + '.' +
					valorSemFormato.substr(tamanho - 8, 3)  + '.' +
					valorSemFormato.substr(tamanho - 5, 3)  + ',' +
					valorSemFormato.substr(tamanho - 2, tamanho);
				}else if ((tamanho >= 15) && (tamanho <= 17)) {
					OBJ.value = valorSemFormato.substr(0, tamanho - 14) + '.' +
					valorSemFormato.substr(tamanho - 14, 3) + '.' +
					valorSemFormato.substr(tamanho - 11, 3) + '.' +
					valorSemFormato.substr(tamanho - 8, 3)  + '.' +
					valorSemFormato.substr(tamanho - 5, 3)  + ',' +
					valorSemFormato.substr(tamanho - 2, tamanho);
				}
			}
		}
}

function FormataVlr2(OBJ,tammax,teclapres){
	var decimal,inteiro;
	var i,count;
	STR = new String(OBJ.value);
	
	inteiro='';
	if (isIE4) {
		if (OBJ.maxLength > STR.length){
			STR = TirarZerosEsquerda(STR); //ESTA FUNCAO TIRA TAMBEM PONTO E VIRGULA
			if (((event.keyCode > 47) && (event.keyCode < 59)) || ((event.keyCode > 95) && (event.keyCode < 106))   ){
			
				if (STR.length == 0){
					inteiro  = '0';
					decimal = '0' + STR;
				}else {
					if (STR.length == 1){
						inteiro  = '0';
						decimal = STR;
					}else{
						decimal = STR.substring(STR.length-1,STR.length);
						i=2;
						count=0;
						while (i<=STR.length){
							if (count==3) {
								inteiro = '.' + inteiro;
								count = 0;
							}
							inteiro = STR.charAt(STR.length-i) + inteiro;
							count++;
							i++;
						}
					}
				}
			}else{
				if (event.keyCode == 8){
					if (STR.length == 0){
						inteiro  = '0';
						decimal = '000';
					} else {
						if (STR.length == 1){
							inteiro  = '0';
							decimal = '00' + STR;
						} else {
							if (STR.length == 2){
								inteiro  = '0';
								decimal = '0' + STR;
							}else{
								decimal = STR.substring(STR.length-3,STR.length);
								i=4;
								count=0;
								while (i<=STR.length){
									if (count==3) {
										inteiro = '.' + inteiro;
										count = 0;
									}
									inteiro = STR.charAt(STR.length-i) + inteiro;
									count++;
									i++;
								}
							}
						}
					}
				}	else {
					if (STR.length == 1){
						inteiro  = '0';
						decimal = '0' + STR;
					} else {
						if (STR.length == 2){
							inteiro  = '0';
							decimal = STR;
						}else{
							decimal = STR.substring(STR.length-2,STR.length);
							i=3;
							count=0;
							while (i<=STR.length){
								if (count==3) {
									inteiro = '.' + inteiro;
									count = 0;
								}
								inteiro = STR.charAt(STR.length-i) + inteiro;
								count++;
								i++;
							}
						}
					}
				}
			}
			if (inteiro == '') {
				inteiro = '0';
			}
			if (decimal == '') {
				decimal = '00';
			}
			if ((inteiro == '0') && (decimal == '0')) {
				OBJ.value = '';
			}else{	
				OBJ.value = inteiro+','+decimal;
			}
		}
	}else{
		var tecla = teclapres.keyCode;
		valorSemFormato = OBJ.value;
		valorSemFormato = valorSemFormato.replace( ",", "" );
		valorSemFormato = valorSemFormato.replace( ".", "" );
		valorSemFormato = valorSemFormato.replace( ".", "" );
		valorSemFormato = valorSemFormato.replace( ".", "" );
		valorSemFormato = valorSemFormato.replace( ".", "" );
		tamanho = valorSemFormato.length;

		if (tecla == 46) {
			OBJ.value = OBJ.value;
		}
		if (tamanho < tammax && tecla != 8) {
			tamanho = valorSemFormato.length + 1;
		}
		if (tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
			if (tecla == 8) {
				tamanho = tamanho - 1;
			}
			if (tamanho <= 2) {
				OBJ.value = valorSemFormato;
			} else if ((tamanho > 2) && (tamanho <= 5)) {
				OBJ.value = valorSemFormato.substr(0, tamanho - 2) + ',' +
				valorSemFormato.substr(tamanho - 2, tamanho);
			}else if ((tamanho >= 6) && (tamanho <= 8)) {
				OBJ.value = valorSemFormato.substr(0, tamanho - 5) + '.' +
				valorSemFormato.substr(tamanho - 5, 3) + ',' +
				valorSemFormato.substr(tamanho - 2, tamanho);
			}else if ((tamanho >= 9) && (tamanho <= 11)) {
				OBJ.value = valorSemFormato.substr(0, tamanho - 8) + '.' +
				valorSemFormato.substr(tamanho - 8, 3) + '.' +
				valorSemFormato.substr(tamanho - 5, 3) + ',' +
				valorSemFormato.substr(tamanho - 2, tamanho);
			}else if ((tamanho >= 12) && (tamanho <= 14)) {
				OBJ.value = valorSemFormato.substr(0, tamanho - 11) + '.' +
				valorSemFormato.substr(tamanho - 11, 3) + '.' +
				valorSemFormato.substr(tamanho - 8, 3)  + '.' +
				valorSemFormato.substr(tamanho - 5, 3)  + ',' +
				valorSemFormato.substr(tamanho - 2, tamanho);
			}else if ((tamanho >= 15) && (tamanho <= 17)) {
				OBJ.value = valorSemFormato.substr(0, tamanho - 14) + '.' +
				valorSemFormato.substr(tamanho - 14, 3) + '.' +
				valorSemFormato.substr(tamanho - 11, 3) + '.' +
				valorSemFormato.substr(tamanho - 8, 3)  + '.' +
				valorSemFormato.substr(tamanho - 5, 3)  + ',' +
				valorSemFormato.substr(tamanho - 2, tamanho);
			}
		}
	}
}



function FormataValor(tam, fld, milSep, decSep, e) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode == 13) return true;  // Enter
key = String.fromCharCode(whichCode);  // Get key value from key code
if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
//len = fld.value.length;
len = tam;
for(i = 0; i < len; i++)
if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
aux = '';
for(; i < len; i++)
if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
aux += key;
len = aux.length;
if (len == 0) fld.value = '';
if (len == 1) fld.value = '0'+ decSep + '0' + aux;
if (len == 2) fld.value = '0'+ decSep + aux;
if (len > 2) {
aux2 = '';
for (j = 0, i = len - 3; i >= 0; i--) {
if (j == 3) {
aux2 += milSep;
j = 0;
}
aux2 += aux.charAt(i);
j++;
}
fld.value = '';
len2 = aux2.length;
for (i = len2 - 1; i >= 0; i--)
fld.value += aux2.charAt(i);
fld.value += decSep + aux.substr(len - 2, len);
}
return false;
}

function FormataStr(c_str, tam, textocont){
	var str_tam = c_str.value.substr(0,tam);
	var c_str_tam= c_str.value.length;
	
	if (c_str_tam > tam){
		alert("Campo limitado em "+tam+" caracteres.")
		c_str.value = str_tam;
		textocont.innerText = 0;
	}
	else
	textocont.innerText = tam-c_str_tam;	
}

function destacaLinha(){
	var tr,td;
	tr = event.srcElement.parentElement;
	for(i=0;i<tr.children.length;i++){
		td = tr.children[i];
		td.style.backgroundColor='#C0C0C0';
		td.style.cursor='hand';
		td.title='Clique aqui para visualizar este item';
	}
}

function normalizaLinha(){
	var tr,td;
	tr = event.srcElement.parentElement;
	for(i=0;i<tr.children.length;i++){
		td = tr.children[i];
		td.style.backgroundColor='white';
	}
}

function ConsisteCampoBranco(str) {
	str = LimpaEspacoBrancoAll(str);
  if (str==null || str=="")
    return true;
  return false;
}

function LimpaEspacoBranco(str) {
  if (str!=null) {
    while (str.charAt(str.length - 1)==" ")
      str = str.substring(0, str.length - 1);
    while (str.charAt(0)==" ")
      str = str.substring(1, str.length);
  }
  return str;
}

function LimpaEspacoBrancoAll(str) {
  if (str!=null) {
    while (str.length > 0 &&
      "\n\r\t ".indexOf(str.charAt(str.length - 1)) != -1)
      str = str.substring(0, str.length - 1);
    while (str.length > 0 &&
      "\n\r\t ".indexOf(str.charAt(0)) != -1)
      str = str.substring(1, str.length);
  }
  return str;
}

function ConsisteNumero(str) {
  var pattern = "0123456789"
  var i = 0;
  do {
    var pos = 0;
    for (var j=0; j<pattern.length; j++)
      if (str.charAt(i)==pattern.charAt(j)) {
        pos = 1;
        break;
      }
    i++;
  } while (pos==1 && i<str.length)  
  if (pos==0) 
    return true;
  return false;
} 


function ConsisteFuso(str) {
  var pattern1 = "-+"
	var pattern2 = "0123456789"
  var i = 0;
  do {
    var pos = 0;
    for (var j=0; j<pattern2.length; j++)
			if ( i == 0){
				if (str.charAt(i)==pattern1.charAt(j)) {
						pos = 1;
						break;
					}
			}else{
				if (str.charAt(i)==pattern2.charAt(j)) {
					pos = 1;
					break;
				}
			}
		i++;
  } while (pos==1 && i<str.length)  
  if (pos==0)
    return true;
  return false;
} 



function ConsisteString(str) {
  var pattern = "ABCDEFGHIJKLMNOPQRSTUYXWZabcdefghijklmnopqrstuyxwz"
  var i = 0;
  do {
    var pos = 0;
    for (var j=0; j<pattern.length; j++)
      if (str.charAt(i)==pattern.charAt(j)) {
        pos = 1;
        break;
      }
    i++;
  } while (pos==1 && i<str.length)  
  if (pos==0) 
    return true;
  return false;
} 

function ConsisteTelefone(str) {
  var pattern = "0123456789( )-"
  var i = 0;
  do {
    var pos = 0;
    for (var j=0; j<pattern.length; j++)
      if (str.charAt(i)==pattern.charAt(j)) {
				pos = 1;
      	break;
      }
    	i++;
  } 	
  while (pos==1 && i<str.length)  
  if (pos==0) 
    return true;
  return false;
}

function ConsisteCep(str) {
  var pattern = "0123456789-"
  var i = 0;
  do {
    var pos = 0;
    for (var j=0; j<pattern.length; j++)
      if (str.charAt(i)==pattern.charAt(j)) {
				pos = 1;
      	break;
      }
    	i++;
  } 	
  while (pos==1 && i<str.length)  
  if (pos==0) 
    return true;
  return false;
}

function ConsisteDecimal(str) {
  for (var i = 0; i < str.length; i++) 
  {
    var ch = str.substring(i, i + 1)
    if ((ch < "0" || "9" < ch) && (ch != ',') && ( ch != '.')) 
    {
    	return false;
    }
  }
  return true;
}




function ConsisteData(str) {

  if (str.length!=10 || str.charAt(2)!="/" || str.charAt(5)!="/" )
    return false;
  if (ConsisteNumero(str.substring(0,2) + str.substring(3,5) + str.substring(6,10))==true)
    return false;


  var d = str.substring(0,2);
  var m = str.substring(3,5);
  var y = str.substring(6,10);
  
  if (d==0 || m==0 || y==0)
    return false;

  if (m>12) return false;
  if (m==1 || m==3 || m==5 || m==7 || m==8 || m==10 || m==12) 
    var dmax = 31;
  else
    if (m==4 || m==6 || m==9 || m==11) dmax = 30;
    else 
      if ((y%400==0) || (y%4==0 && y%100!=0)) dmax = 29;
      else dmax = 28;
  if (d>dmax) return false;
  if (y<1900) return false;
  return true;
}

function ConsisteEmail(valor) {
    var reg = /\w{1,}[@]\w{1,}[.]\w{1,}/
    return reg.test(valor);
}

function Arredonda(valor) {
    var s = new String(valor);
    var a,b,c,result;
    if (s.indexOf('.') >= 0)
	{
        a = parseInt(s.substring(0,s.indexOf('.')));
	}
    else
        return s;
    b = s.substr(s.indexOf('.') + 1,2);
    c = parseInt(s.substr(s.indexOf('.') + 3));
    if (!isNaN(b) && !isNaN(c)) {
        if ((parseInt(b) + 1) >= 100) {
            a = a + 1;
            b = 0;
            c = 0;
        } else {
            b = b + 1;
            c = 0;
        }
    }
    result = a;
    if (b != 0) result = result + '.' + b;
    return result;
}

function RetornaData(){
	dt = new Date();
	dd = dt.getDate();
	mm = dt.getMonth() + 1;
	yy = dt.getYear();
	
	if (dd < 10) dd = '0' + dd;
	if (mm < 10) mm = '0' + mm;

	dtFinal = dd + '/' + mm + '/' + yy
	
	return  dtFinal;
}

function SomaData(Campo, Soma){
  var dia = '', mes = '', ano = '';
	var dtInicial = '';
	var dtFinal = '';
	var str = Campo;
	var soma = Soma;
  i = 0;
  while (i < str.length && str.charAt(i) != '/') dia = dia + str.charAt(i++);
  if (dia.length == 1) dia = '0' + dia;
  i++;
  while (i < str.length && str.charAt(i) != '/') mes = mes+str.charAt(i++);
	if (mes.length == 1) mes = '0' + mes;
	ano = str.substring(i+1,str.length);
	dtInicial = mes + '/' + dia + '/' + ano;
	dt = new Date(dtInicial);
	dt.setDate(dt.getDate()+parseInt(soma));
	dd = dt.getDate();
	mm = dt.getMonth() + 1;
	yy = dt.getYear();

	if (dd < 10) dd = '0' + dd;
	if (mm < 10) mm = '0' + mm;

	dtFinal = dd + '/' + mm + '/' + yy
  return  dtFinal;
}

function SubtraiData(Campo, Soma){
  var dia = '', mes = '', ano = '';
	var dtInicial = '';
	var dtFinal = '';
	var str = Campo;
	var soma = Soma;

  i = 0;
  while (i < str.length && str.charAt(i) != '/') dia = dia + str.charAt(i++);
  if (dia.length == 1) dia = '0' + dia;
  i++;
  while (i < str.length && str.charAt(i) != '/') mes = mes+str.charAt(i++);
	if (mes.length == 1) mes = '0' + mes;
	ano = str.substring(i+1,str.length);
	dtInicial = mes + '/' + dia + '/' + ano;

	dt = new Date(dtInicial);
	dt.setDate(dt.getDate()-parseInt(soma));
	dd = dt.getDate();
	mm = dt.getMonth() + 1;
	yy = dt.getYear();
	
	if (dd < 10) dd = '0' + dd;
	if (mm < 10) mm = '0' + mm;

	dtFinal = dd + '/' + mm + '/' + yy
	
	return  dtFinal;
}

function ComparaData(sDataIni,sDataFim){
	var DataIni = '';
  var DataFim = '';
  DataIni = sDataIni.substring(6,10)+sDataIni.substring(3,5)+sDataIni.substring(0,2);
  DataFim = sDataFim.substring(6,10)+sDataFim.substring(3,5)+sDataFim.substring(0,2);
  if (parseInt(DataIni)>parseInt(DataFim)){
  	return false;
  }
  else{  
    return true;
  }
}

function ConsisteHora(campo){
	tam = campo.value.length;
	HoraInvalida = false;
	if (tam < 5 ){
		HoraInvalida = true;
	  alert('Hora inválida, digite no formato hh:mm.');	
  }
	else{ 
		for (var x = 0 ; x < 5 ; x++){
			teste = campo.value.substr(x, 1);
			if ((teste != '0')&&(teste != '1')&&(teste != '2')&&(teste != '3')&&(teste != '4')&&(teste != '5')&&(teste != '6')&&(teste != '7')&&(teste != '8')&&(teste != '9')&&(teste != ':')){
				HoraInvalida = true;
			}
		}
		if  ( (parseInt(campo.value.substring(0,2)) > 23) || (parseInt(campo.value.substring(3,5))>59) ){
			HoraInvalida = true;
	    alert('As horas devem ser digitadas entre 00:00 e 23:59.');	
		 return false;
     }

  }

	if (HoraInvalida){
		campo.value = '';
	  campo.focus();
	  return false;
	}
	else{
	  return true;
  }
}

function FormataHora(Campo, teclapres){
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace("", "");
	tam = vr.length + 1;
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 5)
			Campo.value = vr.substr(0, 2) + ':' + vr.substr(2, tam);
	}
}

function FormataMesAno(Campo,teclapres)
{
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace("/", "");
	vr = vr.replace("/", "");
	tam = vr.length + 1;
	if (tecla != 9 && tecla != 8) 
	{
		if (tam > 2 && tam < 5)
			Campo.value = vr.substr(0, 2) + '/' + vr.substr(2, tam);
	}
}

function FormataData(Campo, teclapres)
{
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace("/", "");
	vr = vr.replace("/", "");
	tam = vr.length + 1;
	if (tecla != 9 && tecla != 8 && tecla != 46) 
	{
		if (tam > 2 && tam < 5)
			Campo.value = vr.substr(0, 2) + '/' + vr.substr(2, tam);
		if (tam >= 5 && tam <=10)
			Campo.value = vr.substr(0,2) + '/' + vr.substr(2,2) + '/' + vr.substr(4,4);
	}
}


function FormataCEP(Campo, teclapres)
{
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace("-", "");
	tam = vr.length + 1;
		
	if (tecla != 9 && tecla != 8) 
	{
		if (tam > 6)
			Campo.value = vr.substr(0, 5) + '-' + vr.substr(5, tam);	
	}
}


function FormataPeriodo(Campo, teclapres)
{
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace("/", "");
	tam = vr.length + 1;
	if (tecla != 9 && tecla != 8) 
	{
		if (tam > 2 && tam < 5)
			Campo.value = vr.substr(0, 2) + '/' + vr.substr(2, tam);
		if (tam >= 5 && tam <=10)
			Campo.value = vr.substr(0,2) + '/'  + vr.substr(2,4);
	
	}
}

function ValidaHora(valor)
{
	var hora = valor.substring(0,2);
	var min  = valor.substring(3,5);
	
	if (valor.length < 5)
	{
	 return false;
	}

	if ((parseInt(min) > 59) || (parseInt(min) < 0))
	{
	 return false;
	}

	if ((parseInt(hora) > 24) || (parseInt(hora) < 0))
	{
	 return false;
	}
	
	if ((parseInt(hora) > 23) && (parseInt(min) > 0))
	{
	 return false;
	}
	
return true;	
}

function ComparaHora(sHoraIni,sHoraFim){
	var HoraIni = '';
  var HoraFim = '';
	HoraIni = sHoraIni.substring(0,2)+sHoraIni.substring(3,5);
  HoraFim = sHoraFim.substring(0,2)+sHoraFim.substring(3,5);
  if (sHoraIni.substring(0,2) == sHoraFim.substring(0,2)){
    if (parseInt(sHoraIni.substring(3,5))>=parseInt(sHoraFim.substring(3,5))){
    	return false;
    }
    else{  
      return true;
    }
  }
  else{
    if ((eval(HoraIni)-(HoraFim))>0){
    	return false;
    }
    else{  
      return true;
    }
  }
}

function ComparaHoraIgual(sHoraIni,sHoraFim){
	var HoraIni = '';
  var HoraFim = '';
	HoraIni = sHoraIni.substring(0,2)+sHoraIni.substring(3,5);
  HoraFim = sHoraFim.substring(0,2)+sHoraFim.substring(3,5);
  if (sHoraIni.substring(0,2) == sHoraFim.substring(0,2)){
    if (parseInt(sHoraIni.substring(3,5))>parseInt(sHoraFim.substring(3,5))){
    	return false;
    }
    else{  
      return true;
    }
  }
  else{
    if ((eval(HoraIni)-(HoraFim))>0){
    	return false;
    }
    else{  
      return true;
    }
  }
}

function ConsisteValorDigitado(str) {
  var pattern = ".,-_/"
  var i = 0;
  do {
    var pos = 0;
    for (var j=0; j<pattern.length; j++)
      if (str.charAt(i)==pattern.charAt(j)) {
        pos = 1;
        break;
      }
    i++;
  } while (pos==1 && i<str.length)  
  if (pos==0) 
    return false;
  return true;
} 

function FormataTelaBanco(valor)
{
	out = "."; // replace this
	add = ""; // with this
	temp = "" + valor; // temporary holder
	while (temp.indexOf(out)>-1) {
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + 
		temp.substring((pos + out.length), temp.length));
	}

	out = ","; // replace this
	add = "."; // with this
	valor = "" + temp; // temporary holder
	while (valor.indexOf(out)>-1) {
		pos= valor.indexOf(out);
		valor = "" + (valor.substring(0, pos) + add + 
		valor.substring((pos + out.length), valor.length));
	}
  return valor;
}

function FormataBancoTela(valor)
{
	out = "."; // replace this
	add = ","; // with this
	temp = "" + valor; // temporary holder
	while (temp.indexOf(out)>-1) {
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + 
		temp.substring((pos + out.length), temp.length));
	}
	return temp;
}

function ConsiteCGCCPF(p_NomeCampo){
  BASE = p_NomeCampo.value;
  if (BASE.length > 11){
	return ConsiteCGC(p_NomeCampo)
  }
  else{
    return ValidaCPF(p_NomeCampo)
  }
}

function ValidaCPF(p_NomeCampo)
{	
sNumCPF = p_NomeCampo.value;
if ((sNumCPF == "00000000000") || (sNumCPF == "11111111111")||(sNumCPF == "22222222222")||(sNumCPF == "33333333333")||(sNumCPF == "44444444444")||(sNumCPF == "55555555555")||(sNumCPF == "66666666666")||(sNumCPF == "77777777777")||(sNumCPF == "88888888888")||(sNumCPF == "99999999999")){
		return false;
}
if (sNumCPF == "") { return true;}

	var nAux = 0;
	var nResto = 0;
	var nDigito1 = 0;
	var nDigito2 = 0;
	var sCharCpf = new Array(11);

	sCharCpf[0] = sNumCPF.charAt(0);
	sCharCpf[1] = sNumCPF.charAt(1);
	sCharCpf[2] = sNumCPF.charAt(2);
	sCharCpf[3] = sNumCPF.charAt(3);
	sCharCpf[4] = sNumCPF.charAt(4);
	sCharCpf[5] = sNumCPF.charAt(5);
	sCharCpf[6] = sNumCPF.charAt(6);
	sCharCpf[7] = sNumCPF.charAt(7);
	sCharCpf[8] = sNumCPF.charAt(8);
	sCharCpf[9] = sNumCPF.charAt(9);
	sCharCpf[10] = sNumCPF.charAt(10);

	// Define o primeiro dígito do dígito verificador
	nAux =	10*parseInt(sCharCpf[0]) + 9*parseInt(sCharCpf[1]) + 8*parseInt(sCharCpf[2]) + 7*parseInt(sCharCpf[3]) + 6*parseInt(sCharCpf[4]) + 5*parseInt(sCharCpf[5]) + 4*parseInt(sCharCpf[6]) + 3*parseInt(sCharCpf[7]) + 2*parseInt(sCharCpf[8]) ;
	nResto = nAux - ( parseInt(nAux/11)*11);
	nDigito1 = 11 - nResto;
	if (nDigito1 >= 10)
	{	nDigito1 = 0;
	}
	
	// Define o segundo dígito do dígito verificador

	nAux =	11*parseInt(sCharCpf[0]) + 10*parseInt(sCharCpf[1]) + 9*parseInt(sCharCpf[2]) + 8*parseInt(sCharCpf[3]) + 7*parseInt(sCharCpf[4]) + 6*parseInt(sCharCpf[5]) + 5*parseInt(sCharCpf[6]) + 4*parseInt(sCharCpf[7]) + 3*parseInt(sCharCpf[8]) + 2*nDigito1;
	nResto = nAux -  (parseInt(nAux/11)*11);
	nDigito2 = 11 - nResto;

	if (nDigito2 >= 10){
		nDigito2 = 0;
	}

	if ( nDigito1 != sCharCpf[9] || nDigito2 != sCharCpf[10])
		return false;
	else
		return true;
}

function ConsiteCGC(p_NomeCampo){

 BASE = p_NomeCampo.value;
  if (BASE.length < 12){
	p_NomeCampo.value="";
	p_NomeCampo.focus();
	return false;
 }
 
 		BASE = BASE.replace( ".", "" );
		BASE = BASE.replace( ".", "" );
		BASE = BASE.replace( "-", "" );
		BASE = BASE.replace( "/", "" );
        var start_format = " +-0123456789";
        var number_format = "  0123456789";
        var check_char;
        var decimal = false;
        var trailing_blank = false;
        var digits = false;
		var verify = false;

        check_char = start_format.indexOf(BASE.charAt(0))
        if (check_char == 1)
            	decimal = true;
        else if (check_char < 1)
                return false;
        for (var i = 1; i < BASE.length; i++)
        {
                check_char = number_format.indexOf(BASE.charAt(i))
                if (check_char < 0)
                        return false;
                else if (check_char == 1)
                {
                        if (decimal)            // Second decimal.
                                return false;
                        else
                                decimal = true;
                }
                else if (check_char == 0)
                {
                        if (decimal || digits)  
                                trailing_blank = true;

                }
                else if (trailing_blank)
                        return false;
                else
                        digits = true;
						//return false;
        }       
    verify = true;

if (verify) {
	if (BASE.length > 11) {
	
        var CGC = BASE.substring(0,12);
		var DAC = BASE.substring(12,14);
		digito = "0";
		var DF1 = 0;
		var DF2 = 0;
		var DF3 = 0;
		var DF4 = 0;
		var DF5 = 0;
		var DF6 = 0;
		var resto1 = 0;
		var resto2 = 0;
		var DIG1 = 0;
		var DIG2 = 0;
		var n1=  BASE.substring(0,1);
		var n2=  BASE.substring(1,2);
		var n3=  BASE.substring(2,3);
		var n4=  BASE.substring(3,4);
		var n5=  BASE.substring(4,5);
		var n6=  BASE.substring(5,6);
		var n7=  BASE.substring(6,7);
		var n8=  BASE.substring(7,8);
		var n9=  BASE.substring(8,9);
		var n10= BASE.substring(9,10);
		var n11= BASE.substring(10,11);
		var n12= BASE.substring(11,12);
		DF1 = eval((5 * n1) + (4 * n2) + (3 * n3) + (2 * n4) + (9 * n5) + (8 * n6) + (7 * n7) + (6 * n8) + (5 * n9) + (4 * n10) + (3 * n11) + (2 * n12));
		DF2 = eval(DF1 / 11);
		DF3 = eval(parseInt(DF2) * 11);
		resto1 = eval(DF1 - DF3);
		if ((resto1 == 0) || (resto1 == 1))	{
				DIG1 = 0}
		else {
		        DIG1 = eval(11 - resto1)};
		DF4 = eval((6 * n1) + (5 * n2) + (4 * n3) + (3 * n4) + (2 * n5) + (9 * n6) + (8 * n7) + (7 * n8) + (6 * n9) + (5 * n10) + (4 * n11) + (3 * n12) + (2 * DIG1));
		DF5 = eval(DF4 / 11);
		DF6 = eval(parseInt(DF5) * 11);
		resto2 = eval(DF4 - DF6);
		if ((resto2 == 0) || (resto2 == 1))	{
		        DIG2 = 0}
		else {
		        DIG2 = eval(11 - resto2)};
				
		digito = eval((DIG1*10) + DIG2);
			
		if  (digito != DAC ) {
				//p_NomeCampo.value="";
				p_NomeCampo.focus();
		     	return false
			}
		else{
		    	return true;
			}
			
	}
	else{		
		var CPF = BASE.substring(0,9);
		var DAC1 = BASE.substring(9,11);
		var controle  = 0;
		var controle1 = 0;
		var digito1 = 0;
        var inicio = 2;
        var fim = 10;
		var soma = 0;		
		for (j=1; j<3;j++){
             soma = 0;
			 for (i=inicio; i<=fim;i++){	 
              		soma = eval(soma + ((CPF.substring(i-1 - j,i-1-j+1)) * (fim + 1 + j - i)))
			 }
        	if (j == 2){ soma = eval(soma + (2 * digito1))}
		        digito1 = eval((soma * 10)-((parseInt((soma * 10)/11))* 11)
			)
    	    if (digito1 == 10) {
            	digito1 = 0
			}
			if (j == 1){
	        controle =  digito1
			}
			else{
			controle1 =  digito1
			}			
        	inicio = 3;
        	fim = 11;
		}			
		digito1 = eval((controle*10) + controle1);
		if  (digito1 != DAC1 ) {
			//alert("O CNPJ/CPF não é válido.")
		     	return false
			}
		else{
				return true
		}
	  }		
	}
	else{
		return false;
	}
}

//*****Validar se período(mês/ano) são válidos******

function fValidaPeriodoMes(base)
{
  Periodo = base.value;
  if (Periodo != '')
   { 
    if (!fValidaFormatoPeriodo(base.value)){
  		alert("O período deve estar no formato mm/aaaa. "+
		"Exemplo: 09/2001")
		base.value = "";
		base.focus();
       }
    else {
	pos1 = Periodo.indexOf('/');
	mes = Periodo.slice(0,pos1);
	ano = Periodo.slice(pos1+1);
	if ((ano < 1900 || ano > 9999) ||(mes < 1 || mes > 12))
	 {
           alert("Período Inválido!");
	   base.value = "";
	   base.focus();
	  }
      }
   }
}

function fValidaFormatoPeriodo(p_Data)
{
  bRetorno = true;
  if (p_Data.length != 7){
   bRetorno = false;
  }
  pos1 = p_Data.indexOf('/');
  if (pos1 != 2)
  {
	bRetorno=false;
  }
  return bRetorno;
}

function _checkeurodate(object_value)
    {
    //Returns true if value is a eurodate format or is NULL
    //otherwise returns false	

    if (object_value.length == 0)
        return true;

    //Returns true if value is a date in the dd/mm/yyyy format
	isplit = object_value.indexOf('/');

	if (isplit == -1)
	{
		isplit = object_value.indexOf('.');
	}

	if (isplit == -1 || isplit == object_value.length)
		return false;

    sDay = object_value.substring(0, isplit);

	monthSplit = isplit + 1;

	isplit = object_value.indexOf('/', monthSplit);

	if (isplit == -1)
	{
		isplit = object_value.indexOf('.', monthSplit);
	}

	if (isplit == -1 ||  (isplit + 1 )  == object_value.length)
		return false;

    sMonth = object_value.substring((sDay.length + 1), isplit);

	sYear = object_value.substring(isplit + 1);

	if (!_checkinteger(sMonth)) //check month
		return false;
	else
	if (!_checkrange(sMonth, 1, 12)) // check month
		return false;
	else
	if (!_checkyear(sYear)) //check year
		return false;
	else
	if (!_checkrange(sYear, 0, null)) //check year
		return false;
	else
	if (!_checkinteger(sDay)) //check day
		return false;
	else
	if (!_checkday(sYear, sMonth, sDay)) //check day
		return false;
	else
		return true;
    }

function _checkday(checkYear, checkMonth, checkDay)
    {

	maxDay = 31;

	if (checkMonth == 4 || checkMonth == 6 ||
			checkMonth == 9 || checkMonth == 11)
		maxDay = 30;
	else
	if (checkMonth == 2)
	{
		if (checkYear % 4 > 0)
			maxDay =28;
		else
		if (checkYear % 100 == 0 && checkYear % 400 > 0)
			maxDay = 28;
		else
			maxDay = 29;
	}

	return _checkrange(checkDay, 1, maxDay); //check day
    }

function _checkyear(object_value)
    {
    if (object_value.length == 0)
        return true;

    if (object_value.length != 4)
        return false;
		
	var decimal_format = ".";
	var check_char;

    //The first character can be + -  blank or a digit.
	check_char = object_value.indexOf(decimal_format)
    //Was it a decimal?
    if (check_char < 1)
	 return _checknumber(object_value);
    else
	 return false;
}

function _numberrange(object_value, min_value, max_value)
    {
    // check minimum
    if (min_value != null)
	{
        if (object_value < min_value)
		return false;
	}

    // check maximum
    if (max_value != null)
	{
	if (object_value > max_value)
		return false;
	}
	
    //All tests passed, so...
    return true;
}


function _checkinteger(object_value)
    {
    //Returns true if value is a number or is NULL
    //otherwise returns false	

    if (object_value.length == 0)
        return true;

    //Returns true if value is an integer defined as
    //   having an optional leading + or -.
    //   otherwise containing only the characters 0-9.
	var decimal_format = ".";
	var check_char;

    //The first character can be + -  blank or a digit.
	check_char = object_value.indexOf(decimal_format)
    //Was it a decimal?
    if (check_char < 1)
	return _checknumber(object_value);
    else
	return false;
}

function _checknumber(object_value)
    {
    //Returns true if value is a number or is NULL
    //otherwise returns false	

    if (object_value.length == 0)
        return true;

    //Returns true if value is a number defined as
    //   having an optional leading + or -.
    //   having at most 1 decimal point.
    //   otherwise containing only the characters 0-9.
	var start_format = " ,+-0123456789";
	var number_format = " .0123456789";
	var check_char;
	var decimal = false;
	var trailing_blank = false;
	var digits = false;

    //The first character can be + - .  blank or a digit.
	check_char = start_format.indexOf(object_value.charAt(0))
    //Was it a decimal?
	if (check_char == 1)
	    decimal = true;
	else if (check_char < 1)
		return false;
        
	//Remaining characters can be only . or a digit, but only one decimal.
	for (var i = 1; i < object_value.length; i++)
	{
		check_char = number_format.indexOf(object_value.charAt(i))
		if (check_char < 0)
			return false;
		else if (check_char == 1)
		{
			if (decimal)		// Second decimal.
				return false;
			else
				decimal = true;
		}
		else if (check_char == 0)
		{
			if (decimal || digits)	
				trailing_blank = true;
        // ignore leading blanks

		}
	        else if (trailing_blank)
			return false;
		else
			digits = true;
	}	
    //All tests passed, so...
    return true
    }

function _checkrange(object_value, min_value, max_value)
    {
    //if value is in range then return true else return false

    if (object_value.length == 0)
        return true;


    if (!_checknumber(object_value))
	{
	return false;
	}
    else
	{
	return (_numberrange((eval(object_value)), min_value, max_value));
	}
	
    //All tests passed, so...
    return true;
    }


//********************************************************************
function isDate(dia, mes, ano) {
// Checa se eh uma data valida
if ((isNaN(parseInt(dia)) || isNaN(parseInt(mes)) || isNaN(parseInt(ano))) 
 ||(ano < 1900 || ano > 9999) ||(mes < 1 || mes > 12) ||(dia < 1 
 || dia > 31) ||(mes == 2 && dia > 28 && (ano % 4 != 0)) 
 ||(mes == 2 && dia > 29 && (ano % 4 == 0)) ||(dia > 30 
 && (mes == 4 || mes == 6 || mes == 9 || mes== 11)))
 return false;
else
 return true;
}

function fNumDiasMes(p_nMes,p_nAno){
 if (p_nMes == 1 || p_nMes == 3 || p_nMes == 5 || p_nMes == 7 || p_nMes == 8 || p_nMes == 10 || p_nMes == 12)
  return 31;
 if (p_nMes == 4 || p_nMes == 6 || p_nMes == 9 || p_nMes == 11)
  return 30;
 if (p_nMes ==2){
  if (p_nAno % 4 != 0) return 28
  else return 29;
 }
}

function fValidaIntDt(p_DtIni,p_DtFim)
{
 if ((p_DtIni.value != '') && (p_DtFim.value != ''))
  {
  v_DiaIni = p_DtIni.value.slice(0,2);
  v_MesIni = p_DtIni.value.slice(3,5);
  v_AnoIni = p_DtIni.value.slice(6);
  v_DiaFim = p_DtFim.value.slice(0,2);
  v_MesFim = p_DtFim.value.slice(3,5);
  v_AnoFim = p_DtFim.value.slice(6);
  if (!isDate(v_DiaIni,v_MesIni,v_AnoIni))
   {
   alert('Data Inicial Inválida');
   p_DtIni.focus;
   return false;
   }
  if (!isDate(v_DiaFim,v_MesFim,v_AnoFim))
   {
   alert('Data Final Inválida');
   p_DtFim.focus;
   return false;
   }
  vDataIni = v_AnoIni + v_MesIni + v_DiaIni
  vDataFim = v_AnoFim + v_MesFim + v_DiaFim
  if (vDataIni > vDataFim)
    {
        alert("A data inicial deve ser menor que a final!");
		p_DtIni.focus;
		return false;
    }
  }
}

function fValidaPeriodo(p_DtIni,p_DtFim)
{
 if ((p_DtIni.value != '') && (p_DtFim.value != ''))
  {
  v_DiaIni = p_DtIni.value.slice(0,2);
  v_MesIni = p_DtIni.value.slice(3,5);
  v_AnoIni = p_DtIni.value.slice(6);
  v_DiaFim = p_DtFim.value.slice(0,2);
  v_MesFim = p_DtFim.value.slice(3,5);
  v_AnoFim = p_DtFim.value.slice(6);
  if (!isDate(v_DiaIni,v_MesIni,v_AnoIni))
   {
   alert('Data Inicial Inválida');
   p_DtIni.focus;
   return false;
   }
  if (!isDate(v_DiaFim,v_MesFim,v_AnoFim))
   {
   alert('Data Final Inválida');
   p_DtFim.focus;
   return false;
   }
  vDataIni = v_AnoIni + v_MesIni + v_DiaIni
  vDataFim = v_AnoFim + v_MesFim + v_DiaFim
  if (vDataIni > vDataFim)
   {
        alert("A data inicial deve ser menor que a final!");
		p_DtIni.focus;
		return false;
	}
   vbIntValido = true
   vQtdeDiasMesIni = fNumDiasMes(v_MesIni,v_AnoIni);
   vQtdeDiasPeriodo = 0;
   vDifAno = v_AnoFim - v_AnoIni;
   vDifMes = v_MesFim - v_MesIni;
   if ((vDifAno > 1) || (vDifAno == 1 && (v_MesIni != 12 || v_MesFim != 1))){
     vbIntValido = false
     
   }
   else if ((vDifAno == 0 && vDifMes == 1)||(vDifAno == 1 && v_MesIni == 12 && v_MesFim == 1)){
    vQtdeDiasPeriodo = (vQtdeDiasMesIni - v_DiaIni)+ parseInt(1) + parseInt(v_DiaFim)
    if (vQtdeDiasPeriodo > 65)
      vbIntValido = false 
   }

   if (vDifAno == 0 && vDifMes > 1)
	{
	 vDifMes_aux = 1;
	 ContaDias = vQtdeDiasMesIni - v_DiaIni;
	 if ((v_MesIni.indexOf('0') != -1) && (v_MesIni.indexOf('0') == 0))
		vMesAux = v_MesIni.slice(1);
	 else
		vMesAux = v_MesIni;
	 MesAux = parseInt(vMesAux) + parseInt(1);
	 while ((vDifMes_aux <= vDifMes) && ContaDias <= 65)
	  {
	   vNumDias = fNumDiasMes(MesAux ,v_AnoIni)
	   if (vDifMes_aux == vDifMes)
	     {
	      ContaDias = parseInt(ContaDias) + parseInt(v_DiaFim);
	     }
	   else
	     {
	      ContaDias = parseInt(ContaDias) + parseInt(vNumDias);	
	     }
	   vDifMes_aux = vDifMes_aux + 1;
	   MesAux = MesAux + 1;
	 }
	 if ( ContaDias > 65 )
	   vbIntValido = false 
	}

    if (!vbIntValido)
     {
      alert("O número de dias do período não pode ultrapassar 65 dias!")
      p_DtFim.value=""
      return false;
     }
  }
  return true;
}

function fAbrePopup(endereco)
{
	if (endereco.indexOf("http://") == -1)
		endereco = "http://"+endereco;
	window.open(endereco,"");
}



function fAtivar(NomeCheckBox,NomeCampo)
{
  if (NomeCheckBox.checked==1) 
       NomeCampo.value=1; 
  else 
       NomeCampo.value=0;
}


function fDesabilitarEnter() {
 var tecla = event.keyCode;
 if ((tecla == 13)) { 
   return false;
 }
 return tecla;
}

function MostraMenu(iMenu, iMenus)
{
	if(iMenu>0){	    
		eval('document.all.Menu' + iMenu + '.style.visibility = \'visible\'');
	}
	else{	    
	    eval('document.all.Menu2.style.visibility = \'hidden\''); 
	}
	var iContador, iContaSub;
	for(iContador=2;iContador<=iMenus;iContador++)
	{
		eval("document.all.Menu" + iContador + ".style.visibility = 'hidden'");
		for(iContaSub=1;iContaSub<=64;iContaSub++)
			if(eval('document.all.Menu' + iContador + iContaSub + '')) {
				eval('document.all.Menu' + iContador + iContaSub + '.style.visibility = \'hidden\'');
			} else {
				if (iMenu == 0) {
					document.all.ESCONDERIJO.style.display = 'none'
				} else {
					document.all.ESCONDERIJO.style.display = ''
				}
				break;
			}
	}
	if(iMenu>0){	   
		eval('document.all.Menu' + iMenu + '.style.visibility = \'visible\'');
		}
	return true;
}


function MostraSubMenu(iMenu, iSubMenu, iMenus)
{
	var iContador;
	for(iContador=1;iContador<=iMenus;iContador++)
		eval('document.all.Menu' + iMenu + iContador + '.style.visibility = \'hidden\'');
	if(iSubMenu>0)
		eval('document.all.Menu' + iMenu + iSubMenu + '.style.visibility = \'visible\'');
	return true;
}

function FormataCEP(Campo, teclapres)
{
    var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	//se não tiver o replace, depois do tracino se eu digitar qualquer tecla vai sair um tracinho no text.
	vr = vr.replace("-","");
	tam = vr.length + 1;
    // Este if do tecla!= 9 && tecla!= 8 serve para funcionar a tecla de retorno, ou seja se eu digitar um nº errado eu posso retornar na tecla backspace, se não tiver o if eu não consigo retornar, o cursor tranca no tracinho (-).
    if (tecla != 9 && tecla != 8) 
	{
	    if (tam > 5 )
	    {
	       Campo.value = vr.substr(0, 5) + '-' + vr.substr(5, tam);
	    }
    }
 			
}

function FormataHORA2(Campo, teclapres)
{
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	//se não tiver o replace, depois do tracino se eu digitar qualquer tecla vai sair um tracinho no text.
	vr = vr.replace(":","");
	tam = vr.length + 1;
    // Este if do tecla!= 9 && tecla!= 8 serve para funcionar a tecla de retorno, ou seja se eu digitar um nº errado eu posso retornar na tecla backspace, se não tiver o if eu não consigo retornar, o cursor tranca no tracinho (-).
    if (tecla != 5 && tecla != 4) 
	{
	    if (tam > 2 )
	    {
	       Campo.value = vr.substr(0, 2) + '-' + vr.substr(2, tam);
	    }
    }
}

function ValidaCEP(campo)
{   
	var val = campo.value
    var tam = val.length
	if (tam != 9)
		{
		return true;
		}
	for (var x = 0 ; x < tam ; x++)
	    {
		teste = val.substr(x, 1);
		if ((teste != '0')&&(teste != '1')&&(teste != '2')&&(teste != '3')&&(teste != '4')&&(teste != '5')&&(teste != '6')&&(teste != '7')&&(teste != '8')&&(teste != '9')&&(x!=5))
		    {
		    return true;
		    }
        }return false;
}

function fDesabilitarEnter() {
 var tecla = event.keyCode;
 //alert(tecla);
 if ((tecla == 13)) { 
   return false;
 }
 return tecla;
}

//funções para montar o calendário.
//******************************
function fValidaData(base)
{
  vAux = 0;
  if (base.value != ''){  
   if (!fValidaFormatoData(base.value)){
		base.value = "";
		base.focus();
		vAux = 1;
		return false;
   }
   else if (!_checkeurodate(base.value)){
		base.value = "";
		base.focus();
		vAux = 1;
		return false;
   }
  }
  return true;
}

//funções para montar o calendário.
//******************************
function fValidaData2(base)
{
  vAux = 0;
  if (base.value != ''){  
   if (!fValidaFormatoData(base.value)){
		base.value = "";
		//base.focus();
		vAux = 1;
		return false;
   }
   else if (!_checkeurodate(base.value)){
		base.value = "";
		//base.focus();
		vAux = 1;
		return false;
   }
  }
  return true;
}

function fPopPaletaCor(campo,campoFocus)
{
	window.open("../includes/paletadecor.asp?campo="+campo+"&campoFocus="+campoFocus,"Paleta","height=100,width=293,left=400,screenX=600,top=190,screenY=190");
}

//original
//function fPopData(campo,campoFocus){
//window.open("../includes/Calendario_popup.asp?campo="+campo+"&campoFocus="+campoFocus,"Calendario","height=120,width=130,left=600,screenX=600,top=190,screenY=190");
//}

function fPopData(campo,campoFocus){
window.open("../includes/Calendario_popup.asp?campo="+campo+"&campoFocus="+campoFocus,"Calendario","height=120,width=260,left=600,screenX=600,top=190,screenY=190");
}

// construindo o calendário
function popdate(obj,div,tam,ddd,objFocus)
{
   if (ddd) 
   {
       day = ""
       mmonth = ""
       ano = ""
       c = 1
       char = ""
       for (s=0;s<parseInt(ddd.length);s++)
       {
           char = ddd.substr(s,1)
           if (char == "/") 
           {
               c++; 
               s++; 
               char = ddd.substr(s,1);
           }
           if (c==1) day    += char
           if (c==2) mmonth += char
           if (c==3) ano    += char
       }
       ddd = mmonth + "/" + day + "/" + ano
		       
   }

   //alert(ddd);
		 
   if(!ddd) {today = new Date()} else {today = new Date(ddd)}

   //alert(today);
		   
   //today = new Date()
		   
   date_Form = eval (obj)
   //if (date_Form.value == "") {date_Form = new Date()} else {date_Form = new Date(date_Form.value)}
   date_Form = new Date()
		    
   ano = today.getFullYear();
   mmonth = today.getMonth ();
   day = today.toString ().substr (8,2)
		 
   umonth = new Array ("Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro")
   days_Feb = (!(ano % 4) ? 29 : 28)
   days = new Array (31, days_Feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

   //if ((mmonth < 0) || (mmonth > 11))  alert(mmonth)
   if ((mmonth - 1) == -1) {month_prior = 11; year_prior = ano - 1} else {month_prior = mmonth - 1; year_prior = ano}
   if ((mmonth + 1) == 12) {month_next  = 0;  year_next  = ano + 1} else {month_next  = mmonth + 1; year_next  = ano}
   txt  = "<table cellspacing='0' cellpadding='0' border='0'><tr><td>"
   txt += "<table bgcolor='#efefff' style='border:solid #006699; border-width:1' cellspacing='0' cellpadding='0' border='0' width='"+tam+"' height='"+tam*0.9 +"'>"
   txt += "<tr bgcolor='#FFFFFF'><td colspan='7' align='center'><table border='0' cellspacing='0' cellpadding='0' width='100%' bgcolor='#FFFFFF'><tr>"
   txt += "<td width=18% align=center colspan='2'><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+((mmonth+1).toString() +"/01/"+(ano-1).toString())+"','"+objFocus+"') class='Cabecalho_Calendario' title='Ano Anterior'><<</a></td>"
   txt += "<td width=18% align=center colspan='2'><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+( "01/" + (month_prior+1).toString() + "/" + year_prior.toString())+"','"+objFocus+"') class='Cabecalho_Calendario' title='Mês Anterior'><</a></td>"
   txt += "</tr></table></td></tr>"
   txt += "<tr><td colspan='7' align='right' bgcolor='#ccccff' class='mes'><a href=javascript:pop_year('"+obj+"','"+div+"','"+tam+"','" + (mmonth+1) + "') class='mes' style='FONT-SIZE: 10px'>" + ano.toString() + "</a>"
   txt += " <a href=javascript:pop_month('"+obj+"','"+div+"','"+tam+"','" + ano + "') class='mes' style='FONT-SIZE: 10px'>" + umonth[mmonth] + "</a> <div id='popd' style='position:absolute'></div></td></tr>"
   txt += "<tr bgcolor='#006699'><td width='14%' class='dia' align=center><b><font color=#ccccff>D</font></b></td><td width='14%' class='dia' align=center><b>S</b></td><td width='14%' class='dia' align=center><b>T</b></td><td width='14%' class='dia' align=center><b>Q</b></td><td width='14%' class='dia' align=center><b>Q</b></td><td width='14%' class='dia' align=center><b>S<b></td><td width='14%' class='dia' align=center><b>S</b></td></tr>"
   today1 = new Date((mmonth+1).toString() +"/01/"+ano.toString());
   diainicio = today1.getDay () + 1;
   week = d = 1
   start = false;
   var Y = 0;
   for (n=1;n<= 42;n++) 
   {
       if (week == 1)  {txt += "<tr bgcolor='#efefff' align=center>"}
       if (week==diainicio) {start = true}
       if (d > days[mmonth]) {start=false}
       if (start) 
       {
           dat = new Date((mmonth+1).toString() + "/" + d + "/" + ano.toString())
           day_dat   = dat.toString().substr(0,10)
           day_today  = date_Form.toString().substr(0,10)
           year_dat  = dat.getFullYear ()
           year_today = date_Form.getFullYear ()
           colorcell = ((day_dat == day_today) && (year_dat == year_today) ? " bgcolor='#FFCC00' " : "" )
           txt += "<td"+colorcell+" align=center><a href=javascript:block('"+  d + "/" + (mmonth+1).toString() + "/" + ano.toString() +"','"+ obj +"','" + div +"','"+objFocus+"') class='data'>"+ d.toString() + "</a></td>"
           d ++ 
       } 
       else 
       { 
           txt += "<td class='data' align=center>&nbsp;</td>"
       }
       week ++
       if (week == 8) 
       { 
           week = 1; txt += "</tr>"} 
       }
	  
       txt += "</table>"

   txt += "</td><td>"

   date_Form = eval (obj)
   //if (date_Form.value == "") {date_Form = new Date()} else {date_Form = new Date(date_Form.value)}
   date_Form = new Date()
		    
   ano = today.getFullYear();
   mmonth = today.getMonth () + 1;
   day = today.toString ().substr (8,2)
		 
   umonth = new Array ("Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro")
   days_Feb = (!(ano % 4) ? 29 : 28)
   days = new Array (31, days_Feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

   //if ((mmonth < 0) || (mmonth > 11))  alert(mmonth)
   if ((mmonth - 1) == -1) {month_prior = 11; year_prior = ano - 1} else {month_prior = mmonth; year_prior = ano}
   if ((mmonth + 1) == 12) {month_next  = -1;  year_next  = ano + 1} else {month_next  = mmonth; year_next  = ano}
   txt += "<table bgcolor='#efefff' style='border:solid #006699; border-width:1' cellspacing='0' cellpadding='0' border='0' width='"+tam+"' height='"+tam*0.9 +"'>"
   txt += "<tr bgcolor='#FFFFFF'><td colspan='7' align='center'><table border='0' cellspacing='0' cellpadding='0' width='100%' bgcolor='#FFFFFF'><tr>"
   txt += "<td width=18% align=center colspan='2'><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+( "01/" + (month_next+1).toString()  + "/" + year_next.toString())+"','"+objFocus+"') class='Cabecalho_Calendario' title='Próximo Mês'>></a></td>"
   txt += "<td width=18% align=center colspan='2'><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+((mmonth+1).toString() +"/01/"+(ano+1).toString())+"','"+objFocus+"') class='Cabecalho_Calendario' title='Próximo Ano'>>></a></td>"
   txt += "</tr></table></td></tr>"

   //alert(mmonth);
   if(mmonth==12){ var mesproxe = 0; var anoproxe = parseInt(ano) + 1; }else{ var mesproxe = parseInt(mmonth); var anoproxe = ano;}
   
   txt += "<tr><td colspan='7' align='right' bgcolor='#ccccff' class='mes'><a href=javascript:pop_year('"+obj+"','"+div+"','"+tam+"','" + (mmonth+1) + "') class='mes' style='FONT-SIZE: 10px'>" + anoproxe.toString() + "</a>"
   txt += " <a href=javascript:pop_month('"+obj+"','"+div+"','"+tam+"','" + ano + "') class='mes' style='FONT-SIZE: 10px'>" + umonth[parseInt(mesproxe)] + "</a> <div id='popd' style='position:absolute'></div></td></tr>"
   txt += "<tr bgcolor='#006699'><td width='14%' class='dia' align=center><b><font color=#ccccff>D</font></b></td><td width='14%' class='dia' align=center><b>S</b></td><td width='14%' class='dia' align=center><b>T</b></td><td width='14%' class='dia' align=center><b>Q</b></td><td width='14%' class='dia' align=center><b>Q</b></td><td width='14%' class='dia' align=center><b>S<b></td><td width='14%' class='dia' align=center><b>S</b></td></tr>"
   today1 = new Date((mmonth+1).toString() +"/01/"+ano.toString());
   diainicio = today1.getDay () + 1;
   week = d = 1
   start = false;
   var Y = 0;
   //alert(mmonth);
   for (n=1;n<= 42;n++) 
   {
       if (week == 1)  {txt += "<tr bgcolor='#efefff' align=center>"}
       if (week==diainicio) {start = true}
	   var quant = mmonth;
	   if (mmonth==12){quant = 0;}
       if (d > days[quant]) {start=false}
       if (start) 
       {
           dat = new Date((mmonth+1).toString() + "/" + d + "/" + ano.toString())
           day_dat   = dat.toString().substr(0,10)
           day_today  = date_Form.toString().substr(0,10)
           year_dat  = dat.getFullYear ()
           year_today = date_Form.getFullYear ()

		   if(mmonth==12){ var mesprox = 1; var anoprox = parseInt(ano) + 1; }else{ var mesprox = parseInt(mmonth) + 1; var anoprox = ano; }
           
           colorcell = ((day_dat == day_today) && (year_dat == year_today) ? " bgcolor='#FFCC00' " : "" )
           txt += "<td"+colorcell+" align=center><a href=javascript:block('"+  d + "/" + mesprox.toString() + "/" + anoprox.toString() +"','"+ obj +"','" + div +"','"+objFocus+"') class='data'>"+ d.toString() + "</a></td>"
           d ++ 
       } 
       else 
       { 
           txt += "<td class='data' align=center>&nbsp;</td>"
       }
       week ++
       if (week == 8) 
       { 
           week = 1; txt += "</tr>"} 
       }
	  
       txt += "</table>"
       txt += "</td></tr></table>"



       div2 = eval (div)
       div2.innerHTML = txt 

}





  /* txt += "<table bgcolor='#efefff' style='border:solid #006699; border-width:1' cellspacing='0' cellpadding='0' border='0' width='"+tam+"' height='"+tam*0.9 +"'>"
   txt += "<tr bgcolor='#FFFFFF'><td colspan='7' align='center'><table border='0' cellspacing='0' cellpadding='0' width='100%' bgcolor='#FFFFFF'><tr>"
   txt += "<td width=18% align=center colspan='2'><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+( "01/" + (month_next+1).toString()  + "/" + year_next.toString())+"','"+objFocus+"') class='Cabecalho_Calendario' title='Próximo Mês'>></a></td>"
   txt += "<td width=18% align=center colspan='2'><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+((mmonth+1).toString() +"/01/"+(ano+1).toString())+"','"+objFocus+"') class='Cabecalho_Calendario' title='Próximo Ano'>>></a></td>"
   txt += "</tr></table></td></tr>"
   
   if(mmonth+1==12){ var mesproxe = 0; var anoproxe = parseInt(ano) + 1; }else{ var mesproxe = parseInt(mmonth)+1; var anoproxe = ano;}
 
   txt += "<tr><td colspan='7' align='right' bgcolor='#ccccff' class='mes'><a href=javascript:pop_year('"+obj+"','"+div+"','"+tam+"','" + (mmonth+1) + "') class='mes' style='FONT-SIZE: 10px'>" + anoproxe.toString() + "</a>"
   txt += " <a href=javascript:pop_month('"+obj+"','"+div+"','"+tam+"','" + ano + "') class='mes' style='FONT-SIZE: 10px'>" + umonth[parseInt(mesproxe)] + "</a> <div id='popd' style='position:absolute'></div></td></tr>"
   txt += "<tr bgcolor='#006699'><td width='14%' class='dia' align=center><b><font color=#ccccff>D</font></b></td><td width='14%' class='dia' align=center><b>S</b></td><td width='14%' class='dia' align=center><b>T</b></td><td width='14%' class='dia' align=center><b>Q</b></td><td width='14%' class='dia' align=center><b>Q</b></td><td width='14%' class='dia' align=center><b>S<b></td><td width='14%' class='dia' align=center><b>S</b></td></tr>"
   today1 = new Date((mmonth+2).toString() +"/01/"+ano.toString());
   diainicio = today1.getDay () + 1;
   week = d = 1
   start = false;
   var z = 0;
   for (n=1;n<= 42;n++) 
   {
       if (week == 1)  { txt += "<tr bgcolor='#efefff' align=center>"}
       if (week==diainicio) {start = true}
       if (d > days[mmonth]) {start=false}
       if (start) 
       {
           dat = new Date((mmonth+2).toString() + "/" + d + "/" + ano.toString())
           day_dat   = dat.toString().substr(0,10)
           day_today  = date_Form.toString().substr(0,10)
           year_dat  = dat.getFullYear ()
           year_today = date_Form.getFullYear ()

		   if(mmonth+2==13){ var mesprox = 1; var anoprox = parseInt(ano) + 1; }else{ var mesprox = parseInt(mmonth)+2; var anoprox = ano; }

           colorcell = ((day_dat == day_today) && (year_dat == year_today) ? " bgcolor='#FFCC00' " : "" )
           txt += "<td"+colorcell+" align=center><a href=javascript:block('"+  d + "/" + mesprox.toString() + "/" + anoprox.toString() +"','"+ obj +"','" + div +"','"+objFocus+"') class='data'>"+ d.toString() + "</a></td>"
           d ++ 
       } 
       else 
       { 
           txt += "<td class='data' align=center>&nbsp;</td>"
       }
       week ++
       if (week == 8) 
       { 
           week = 1; txt += "</tr>"} 
       }


// construindo o calendário ORIGINAL
/*
function popdate(obj,div,tam,ddd,objFocus)
{
   if (ddd) 
   {
       day = ""
       mmonth = ""
       ano = ""
       c = 1
       char = ""
       for (s=0;s<parseInt(ddd.length);s++)
       {
           char = ddd.substr(s,1)
           if (char == "/") 
           {
               c++; 
               s++; 
               char = ddd.substr(s,1);
           }
           if (c==1) day    += char
           if (c==2) mmonth += char
           if (c==3) ano    += char
       }
       ddd = mmonth + "/" + day + "/" + ano
		       
   }
		 
   if(!ddd) {today = new Date()} else {today = new Date(ddd)}
		   
   //today = new Date()
		   
   date_Form = eval (obj)
   //if (date_Form.value == "") {date_Form = new Date()} else {date_Form = new Date(date_Form.value)}
   date_Form = new Date()
		    
   ano = today.getFullYear();
   mmonth = today.getMonth ();
   day = today.toString ().substr (8,2)
		 
   umonth = new Array ("Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro")
   days_Feb = (!(ano % 4) ? 29 : 28)
   days = new Array (31, days_Feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

   if ((mmonth < 0) || (mmonth > 11))  alert(mmonth)
   if ((mmonth - 1) == -1) {month_prior = 11; year_prior = ano - 1} else {month_prior = mmonth - 1; year_prior = ano}
   if ((mmonth + 1) == 12) {month_next  = 0;  year_next  = ano + 1} else {month_next  = mmonth + 1; year_next  = ano}
   txt  = "<table bgcolor='#efefff' style='border:solid #006699; border-width:1' cellspacing='0' cellpadding='0' border='0' width='"+tam+"' height='"+tam*0.9 +"'>"
   txt += "<tr bgcolor='#FFFFFF'><td colspan='7' align='center'><table border='0' cellspacing='0' cellpadding='0' width='100%' bgcolor='#FFFFFF'><tr>"
   txt += "<td width=18% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+((mmonth+1).toString() +"/01/"+(ano-1).toString())+"','"+objFocus+"') class='Cabecalho_Calendario' title='Ano Anterior'><<</a></td>"
   txt += "<td width=18% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+( "01/" + (month_prior+1).toString() + "/" + year_prior.toString())+"','"+objFocus+"') class='Cabecalho_Calendario' title='Mês Anterior'><</a></td>"
   txt += "<td width=18% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+( "01/" + (month_next+1).toString()  + "/" + year_next.toString())+"','"+objFocus+"') class='Cabecalho_Calendario' title='Próximo Mês'>></a></td>"
   txt += "<td width=18% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+((mmonth+1).toString() +"/01/"+(ano+1).toString())+"','"+objFocus+"') class='Cabecalho_Calendario' title='Próximo Ano'>>></a></td>"
   txt += "</tr></table></td></tr>"
   txt += "<tr><td colspan='7' align='right' bgcolor='#ccccff' class='mes'><a href=javascript:pop_year('"+obj+"','"+div+"','"+tam+"','" + (mmonth+1) + "') class='mes'>" + ano.toString() + "</a>"
   txt += " <a href=javascript:pop_month('"+obj+"','"+div+"','"+tam+"','" + ano + "') class='mes'>" + umonth[mmonth] + "</a> <div id='popd' style='position:absolute'></div></td></tr>"
   txt += "<tr bgcolor='#006699'><td width='14%' class='dia' align=center><b><font color=#ccccff>D</font></b></td><td width='14%' class='dia' align=center><b>S</b></td><td width='14%' class='dia' align=center><b>T</b></td><td width='14%' class='dia' align=center><b>Q</b></td><td width='14%' class='dia' align=center><b>Q</b></td><td width='14%' class='dia' align=center><b>S<b></td><td width='14%' class='dia' align=center><b>S</b></td></tr>"
   today1 = new Date((mmonth+1).toString() +"/01/"+ano.toString());
   diainicio = today1.getDay () + 1;
   week = d = 1
   start = false;

   for (n=1;n<= 42;n++) 
   {
       if (week == 1)  txt += "<tr bgcolor='#efefff' align=center>"
       if (week==diainicio) {start = true}
       if (d > days[mmonth]) {start=false}
       if (start) 
       {
           dat = new Date((mmonth+1).toString() + "/" + d + "/" + ano.toString())
           day_dat   = dat.toString().substr(0,10)
           day_today  = date_Form.toString().substr(0,10)
           year_dat  = dat.getFullYear ()
           year_today = date_Form.getFullYear ()
           colorcell = ((day_dat == day_today) && (year_dat == year_today) ? " bgcolor='#FFCC00' " : "" )
           txt += "<td"+colorcell+" align=center><a href=javascript:block('"+  d + "/" + (mmonth+1).toString() + "/" + ano.toString() +"','"+ obj +"','" + div +"','"+objFocus+"') class='data'>"+ d.toString() + "</a></td>"
           d ++ 
       } 
       else 
       { 
           txt += "<td class='data' align=center> </td>"
       }
       week ++
       if (week == 8) 
       { 
           week = 1; txt += "</tr>"} 
       }
       txt += "</table>"
       div2 = eval (div)
       div2.innerHTML = txt 
}
*/

// função para exibir a janela com os meses
function pop_month(obj, div, tam, ano)
{
 txt  = "<table bgcolor='#CCCCFF' border='0' width=80>"
 for (n = 0; n < 12; n++) 
	{ 
		txt += "<tr><td align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+("01/" + (n+1).toString() + "/" + ano.toString())+"')>" + umonth[n] +"</a></td></tr>" }
 txt += "</table>"
 popd.innerHTML = txt
}

// função para exibir a janela com os anos
function pop_year(obj, div, tam, umonth)
{
 txt  = "<table bgcolor='#CCCCFF' border='0' width=160>"
 l = 1
 for (n=1991; n<2012; n++)
 {  if (l == 1) txt += "<tr>"
    txt += "<td align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+(umonth.toString () +"/01/" + n) +"')>" + n + "</a></td>"
    l++
    if (l == 4) 
       {txt += "</tr>"; l = 1 } 
 }
 txt += "</tr></table>"
 popd.innerHTML = txt 
}

// função para fechar o calendário
function force_close(div) 
   { div2 = eval (div); div2.innerHTML = ''}
		   
// função para fechar o calendário e setar a data no campo de data associado
function block(data, obj, div, objFocus)
{ 
   force_close (div)
   obj2 = eval(obj)
   obj3 = eval(objFocus)
		   
   var indexBarra = data.indexOf("/")
   var BarraDia = data.slice(0, indexBarra)
   var NovoDia = ""
   if (parseInt(BarraDia) < 10) 
		NovoDia = "0"+BarraDia
   else 
		NovoDia = BarraDia 
		   
   var MesAno = data.slice(indexBarra + 1)
   var indexBarra = MesAno.indexOf("/")
   var BarraMes = MesAno.slice(0, indexBarra)
   var NovoMes = ""
   if (parseInt(BarraMes) < 10)
		NovoMes = "0"+BarraMes
   else 
		NovoMes = BarraMes
		   
   data = NovoDia + "/" + NovoMes + MesAno.slice(indexBarra)
   obj2.value = data
//   if (objFocus.length > 0)
//		obj2.focus()
	 obj3.focus()
   window.close()
}

function fValidaFormatoData(p_Data)
{
  bRetorno = true;
  if (p_Data.length != 10){
   bRetorno = false;
  }
  pos1 = p_Data.indexOf('/');
  pos2 = p_Data.indexOf("/",3); 
  if ((pos1 != 2) || (pos2 != 5))
  {
	bRetorno=false;
  }
  return bRetorno;
}

function _checkeurodate(object_value)
    {
    //Returns true if value is a eurodate format or is NULL
    //otherwise returns false	

    if (object_value.length == 0)
        return true;

    //Returns true if value is a date in the dd/mm/yyyy format
	isplit = object_value.indexOf('/');

	if (isplit == -1)
	{
		isplit = object_value.indexOf('.');
	}

	if (isplit == -1 || isplit == object_value.length)
		return false;

    sDay = object_value.substring(0, isplit);

	monthSplit = isplit + 1;

	isplit = object_value.indexOf('/', monthSplit);

	if (isplit == -1)
	{
		isplit = object_value.indexOf('.', monthSplit);
	}

	if (isplit == -1 ||  (isplit + 1 )  == object_value.length)
		return false;

    sMonth = object_value.substring((sDay.length + 1), isplit);

	sYear = object_value.substring(isplit + 1);

	if (!_checkinteger(sMonth)) //check month
		return false;
	else
	if (!_checkrange(sMonth, 1, 12)) // check month
		return false;
	else
	if (!_checkyear(sYear)) //check year
		return false;
	else
	if (!_checkrange(sYear, 0, null)) //check year
		return false;
	else
	if (!_checkinteger(sDay)) //check day
		return false;
	else
	if (!_checkday(sYear, sMonth, sDay)) //check day
		return false;
	else
		return true;
    }

function _checkday(checkYear, checkMonth, checkDay)
    {

	maxDay = 31;

	if (checkMonth == 4 || checkMonth == 6 ||
			checkMonth == 9 || checkMonth == 11)
		maxDay = 30;
	else
	if (checkMonth == 2)
	{
		if (checkYear % 4 > 0)
			maxDay =28;
		else
		if (checkYear % 100 == 0 && checkYear % 400 > 0)
			maxDay = 28;
		else
			maxDay = 29;
	}

	return _checkrange(checkDay, 1, maxDay); //check day
    }

function _checkyear(object_value)
    {
    if (object_value.length == 0)
        return true;

    if (object_value.length != 4)
        return false;
		
	var decimal_format = ".";
	var check_char;

    //The first character can be + -  blank or a digit.
	check_char = object_value.indexOf(decimal_format)
    //Was it a decimal?
    if (check_char < 1)
	 return _checknumber(object_value);
    else
	 return false;
}

function _numberrange(object_value, min_value, max_value)
    {
    // check minimum
    if (min_value != null)
	{
        if (object_value < min_value)
		return false;
	}

    // check maximum
    if (max_value != null)
	{
	if (object_value > max_value)
		return false;
	}
	
    //All tests passed, so...
    return true;
}


function _checkinteger(object_value)
    {
    //Returns true if value is a number or is NULL
    //otherwise returns false	

    if (object_value.length == 0)
        return true;

    //Returns true if value is an integer defined as
    //   having an optional leading + or -.
    //   otherwise containing only the characters 0-9.
	var decimal_format = ".";
	var check_char;

    //The first character can be + -  blank or a digit.
	check_char = object_value.indexOf(decimal_format)
    //Was it a decimal?
    if (check_char < 1)
	return _checknumber(object_value);
    else
	return false;
}

function _checknumber(object_value)
    {
    //Returns true if value is a number or is NULL
    //otherwise returns false	

    if (object_value.length == 0)
        return true;

    //Returns true if value is a number defined as
    //   having an optional leading + or -.
    //   having at most 1 decimal point.
    //   otherwise containing only the characters 0-9.
	var start_format = " ,+-0123456789";
	var number_format = " .0123456789";
	var check_char;
	var decimal = false;
	var trailing_blank = false;
	var digits = false;

    //The first character can be + - .  blank or a digit.
	check_char = start_format.indexOf(object_value.charAt(0))
    //Was it a decimal?
	if (check_char == 1)
	    decimal = true;
	else if (check_char < 1)
		return false;
        
	//Remaining characters can be only . or a digit, but only one decimal.
	for (var i = 1; i < object_value.length; i++)
	{
		check_char = number_format.indexOf(object_value.charAt(i))
		if (check_char < 0)
			return false;
		else if (check_char == 1)
		{
			if (decimal)		// Second decimal.
				return false;
			else
				decimal = true;
		}
		else if (check_char == 0)
		{
			if (decimal || digits)	
				trailing_blank = true;
        // ignore leading blanks

		}
	        else if (trailing_blank)
			return false;
		else
			digits = true;
	}	
    //All tests passed, so...
    return true
    }

function _checkrange(object_value, min_value, max_value)
    {
    //if value is in range then return true else return false

    if (object_value.length == 0)
        return true;


    if (!_checknumber(object_value))
	{
	return false;
	}
    else
	{
	return (_numberrange((eval(object_value)), min_value, max_value));
	}
	
    //All tests passed, so...
    return true;
    }


//********************************************************************
function move(fbox, tbox) {
	var arrFbox = new Array();
	var arrTbox = new Array();
	var arrLookup = new Array();
	var i;
	for (i = 0; i < tbox.options.length; i++) {
		arrLookup[tbox.options[i].text] = tbox.options[i].value;
		arrTbox[i] = tbox.options[i].text;
	}
	var fLength = 0;
	var tLength = arrTbox.length;
	for(i = 0; i < fbox.options.length; i++) {
		arrLookup[fbox.options[i].text] = fbox.options[i].value;
		if (fbox.options[i].selected && fbox.options[i].value != "") {
			arrTbox[tLength] = fbox.options[i].text;
			tLength++;
		}
		else {
			arrFbox[fLength] = fbox.options[i].text;
			fLength++;
	   }
	}
	arrFbox.sort();
	arrTbox.sort();
	fbox.length = 0;
	tbox.length = 0;
	var c;
	for(c = 0; c < arrFbox.length; c++) {
		var no = new Option();
		no.value = arrLookup[arrFbox[c]];
		no.text = arrFbox[c];
		fbox[c] = no;
	}
	for(c = 0; c < arrTbox.length; c++) {
		var no = new Option();
		no.value = arrLookup[arrTbox[c]];
		no.text = arrTbox[c];
		tbox[c] = no;
   }
}

function carregaValor(campo){
var tamanho = campo.length;
	for(i=0; i < tamanho; i++) {
		campo.options[i].selected = true;
		}
}

function setaValorComboStr(combo, campo){
	var tamanho = combo.length;
	campo.value = "";
	for(i=0; i < tamanho; i++) {
		if (combo.options[i].value != "")
		campo.value = campo.value + combo.options[i].value + ","
	}
}

function FormataSemVirgula(Campo)
{
	var vr    = new String(Campo.value);

	out = ","; // replace this
	add = "";  // with this
	temp = "" + vr; // temporary holder
	while (temp.indexOf(out)>-1) {
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + 
		temp.substring((pos + out.length), temp.length));
	}

        Campo.value = temp;
}

//Valida Mês/Ano
function validaMesAno(campo)
{
          var bVenc = false;
          var bInv = false;
          valor = campo.value;
          if (valor != ''){      	
	if (valor.length==7){
		if (valor.indexOf("/",0)==2){
			mes = valor.slice(0,2);
			ano = valor.slice(3);
			if (isNaN(mes)){                
               bInv = true;                                     
			}
			else{
				if (mes != "01" && mes != "02" && mes != "03" && mes != "04" && mes != "05" && mes != "06" && mes != "07" && mes != "08" && mes != "09" && mes != "10" && mes != "11" && mes != "12"){
                    bInv = true;
				}
			}
			if (isNaN(ano)){
				bInv = true;
			}
			else{
				var hoje = new Date();
				var anoAtual = hoje.getFullYear();
				var mesAtual = hoje.getMonth() + 1;
				anoMais = parseInt((parseInt(anoAtual)+10));
				anoMenos = parseInt(parseInt(anoAtual)-5);
				if (parseInt(ano)>anoMais || parseInt(ano)<anoMenos){
					bInv = true;
				}                                         
				if (parseInt(ano) < anoAtual	)
					bVenc = true;                                                               
					if (parseInt(ano)  == anoAtual  &&  mes < mesAtual)
							bVenc = true;
			}
		}
		else{
			alert("Validade do Cartão deve estar no formato: mm/aaaa.")
			campo.focus();
                                                return;
		}
	}
	else{
		alert("Validade do Cartão deve estar no formato: mm/aaaa.")
		campo.focus();
                                return;
	}
                if (bInv)
                       {
                         alert("Mês/Ano Inválido.")
                          campo.focus();       
                          return;
                }

                if (bVenc)
                       {
                         alert("CARTÃO VENCIDO!\nVerifique a validade digitada.")
                          campo.focus();       
                }
        }	
}


//*******************************************************************************

/*function fPreencheCEP(CEP,LOGRADOURO,BAIRRO,CIDADE,CAMPOS)
{	
	CAMPOS = CAMPOS.split(","); 

	opener.document.form1.elements[CAMPOS[0]].value = CEP;
	opener.document.form1.elements[CAMPOS[1]].value = LOGRADOURO;
	opener.document.form1.elements[CAMPOS[2]].value = BAIRRO;
	opener.document.form1.elements[CAMPOS[3]].value = CIDADE;

	window.close();	
}*/

//**************************************************************************************************************
ns4 = (document.layers)? true:false
ie4 = (document.all)? true:false

function loadSource(id,nestref,url) {
	if (ns4) {
		var lyr = (nestref)? eval('document.'+nestref+'.document.'+id) : document.layers[id]
		lyr.load(url,lyr.clip.width)
	}
	else if (ie4) {
		self.frames['bufferFrame'].document.location = url
	}
}
function loadSourceFinish(id) {
	if (ie4) document.all[id].innerHTML = self.frames['bufferFrame'].document.body.innerHTML
}

//Verifica se o Valor é Diferente de Zero
function DiferenteDZero(campo)
{
	var Valor = campo;
		Valor = Valor.replace(",","");
		Valor = Valor.replace(".","");
	if(Valor == 0)
		{return false;}
    else
		{return true;}
}

function VerificaNomeArquivo(campo){		
	if(campo.indexOf("#")>=0){return false;}
	if(campo.indexOf(".")>=0){return false;}
	if(campo.indexOf("'")>=0){return false;}
	//if(campo.indexOf("""")>=0){return false;}
	if(campo.indexOf(";")>=0){return false;}
	if(campo.indexOf(":")>=0){return false;}
	if(campo.indexOf("{")>=0){return false;}
	if(campo.indexOf("}")>=0){return false;}
	if(campo.indexOf("[")>=0){return false;}
	if(campo.indexOf("]")>=0){return false;}
	if(campo.indexOf("(")>=0){return false;}
	if(campo.indexOf(")")>=0){return false;}
	if(campo.indexOf("!")>=0){return false;}
	if(campo.indexOf("?")>=0){return false;}
	if(campo.indexOf("%")>=0){return false;}
	if(campo.indexOf("+")>=0){return false;}
	//if(campo.indexOf("\"")>=0){return false;}
	if(campo.indexOf("*")>=0){return false;}
	if(campo.indexOf("|")>=0){return false;}
	if(campo.indexOf("$")>=0){return false;}
}


function onKeyDownH(e)
{
   var output_string;
   if (emod=="IE4+"){
      e = window.event;
      alt = (e.altKey) ? true : false;
      ctrl = (e.ctrlKey) ? true : false;
      shift = (e.shiftKey) ? true : false;
      if(ctrl==true){
		  output_string = " alt: "+alt+"\n ctrl: "+ctrl+"\n shift: "+shift;

		  if ((e.keyCode<16)||(e.keyCode>18)) {
			 output_string += "\n 'keyCode' attribute: "+e.keyCode;
			 alt = false;
			 ctrl = false;
			 shift = false; }

      return false;
	  }
    }
}

//***************************************************************************************
//BuscaCEP(A018_cep,A018_nom_lograd,A018_nom_bairro,A003_cod_cidade)
function fBuscaCEP(CEP,LOGRADOURO,BAIRRO,CIDADE,CAMPOS)
{
	CEP = CEP.replace("-","");
	url = "CEPCon.asp?A056_num_cep="+CEP+"&A056_nom_logradouro="+LOGRADOURO+"&A055_nom_bairro="+BAIRRO+"&A003_cod_cidade="+CIDADE+"&CAMPOS="+CAMPOS;
	window.open(url,"","scrollbars=yes,height=300,width=600,left=100,screenX=100,top=100,screenY=100");
}


//***************************************************************************************
function fconsultaCEP(CEP,LOGRADOURO,BAIRRO,CIDADE,CAMPOS,pasta)
{
	CEP = CEP.replace("-","");
	url = pasta+"CEPCon.asp?A056_num_cep="+CEP+"&A056_nom_logradouro="+LOGRADOURO+"&A055_nom_bairro="+BAIRRO+"&A047_cod_cidade="+CIDADE+"&CAMPOS="+CAMPOS;
	window.open(url,"","scrollbars=yes,height=300,width=600,left=100,screenX=100,top=100,screenY=100");
}

//*******************************************************************************
function fPreencheCEP(CEP,LOGRADOURO,BAIRRO,CIDADE,NOM_CIDADE,ESTADO,NOM_PAIS,CAMPOS)
{	

	CAMPOS = CAMPOS.split(","); 
    if(eval(opener.document.form1.elements[CAMPOS[0]]))
	opener.document.form1.elements[CAMPOS[0]].value = CEP;

    if(eval(opener.document.form1.elements[CAMPOS[1]]))
	opener.document.form1.elements[CAMPOS[1]].value = LOGRADOURO;

    if(eval(opener.document.form1.elements[CAMPOS[2]]))
	opener.document.form1.elements[CAMPOS[2]].value = BAIRRO;

    if(eval(opener.document.form1.elements[CAMPOS[3]]))
	opener.document.form1.elements[CAMPOS[3]].value = CIDADE;

    if(eval(opener.document.form1.elements[CAMPOS[4]]))
	opener.document.form1.elements[CAMPOS[4]].value = NOM_CIDADE;

    if(eval(opener.document.form1.elements[CAMPOS[5]]))
	opener.document.form1.elements[CAMPOS[5]].value = ESTADO;

    if(eval(opener.document.form1.elements[CAMPOS[6]]))
	opener.document.form1.elements[CAMPOS[6]].value = NOM_PAIS;	

    if(eval(opener.document.form1.elements[CAMPOS[7]]))
	opener.document.form1.elements[CAMPOS[7]].value = 1;
	
	if(eval(opener.document.all["CmbRepresentante"])){
		opener.fCarregaRepres();
	}
	
	window.close();	
}

function onloadH(e)
{
   /*emod = (e) ? (e.eventPhase) ? "W3C" : "NN4" : (window.event) ? "IE4+" : "unknown";

   if (emod == "NN4") {
      document.captureEvents(Event.KEYDOWN); }

   document.onkeydown = onKeyDownH;
   return true;
   */
}

window.onload = onloadH;

var emod;
var alt = false;
var ctrl = false;
var shift = false; 

//*********************************************
//*********************************************

function ConsisteInteiro(str) {
  var pattern = "0123456789"
  var i = 0;
  do {
    var pos = 0;
    for (var j=0; j<pattern.length; j++)
      if (str.charAt(i)==pattern.charAt(j)) {
        pos = 1;
        break;
      }
	  else{
		  if(str.charAt(i)=='-' && i==0){
			pos = 1;
			break;
		  }
	  }
    i++;
  } while (pos==1 && i<str.length)  
  if (pos==0) 
    return true;
  return false;
} 

function FormataCEP(Campo, teclapres)
{
    var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);

	vr = vr.replace("-","");
	tam = vr.length + 1;
    if (tecla != 9 && tecla != 8) 
	{
	    if (tam > 5 )
	    {
	       Campo.value = vr.substr(0, 5) + '-' + vr.substr(5, tam);
	    }
    }
 			
}



//*****************************************
//função de arredondamento
function round(number,X) {
// rounds number to X decimal places, defaults to 2
X = (!X ? 2 : X);
return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}

/*******************************************************************************************/
function $id(nomeCampo) {
	return document.getElementById(nomeCampo);
}

function janelaAgenda(url, w, h, e, x, y) {
		
	if(e != null) {
		
		if (event.pageX) { // NS 4, Mozilla
			x = event.pageX;
			y = event.pageY;
		} else { // IE, Opera
			var root = document.documentElement || document.body;
			x = event.clientX - root.scrollLeft;
			y = event.clientY - root.scrollTop;
		}
	}
				
	var iframe;
	var iframeModal;
	var div;
	
	if(!eval($id('iFrameModal'))) {
		iframeModal = document.createElement("IFRAME"); 
		iframeModal.id="iFrameModal"; 
		iframeModal.frameBorder = '0';
		iframeModal.border = '0';
		iframeModal.style.display = 'none';
		iframeModal.style.zIndex = 98;
		iframeModal.style.position = 'absolute';
		iframeModal.style.border = '0px';
		iframeModal.style.backgroundcolor = 'transparent';
		iframeModal.style.overflow = 'hidden';
		iframeModal.setAttribute('allowtransparency','true');
		document.body.appendChild(iframeModal);
	}
	else iframeModal = $id('iFrameModal');
	iFrameModal.src = "../transparente.htm";

	if(!eval($id('iFrameAgenda'))) {
		iframe = document.createElement("IFRAME"); 
		iframe.id="iFrameAgenda"; 
		iframe.frameBorder = '0';
		iframe.border = '0';
		iframe.style.display = 'none';
		iframe.style.zIndex = 99;
		iframe.style.position = 'absolute';
		iframe.style.border = '0px';
		document.body.appendChild(iframe);
	}
	else iframe = $id('iFrameAgenda');
	iframe.src = url;
	iframe.style.left = (document.body.scrollWidth/2)-(w/2);
	iframe.style.top  = (document.body.scrollHeight/2)-(h/2);
	iframe.style.width = w;
	iframe.style.height = h;

	iframeModal.style.left = 0;
	iframeModal.style.top  = 0;
	iframeModal.style.width = document.body.scrollWidth;
	iframeModal.style.height = document.body.scrollHeight;

	iframe.style.display = 'inline';
	iframeModal.style.display = 'inline';
}

function janelaAgendaHidden() {
	if(eval(parent.document.getElementById('iFrameAgenda'))) parent.document.getElementById('iFrameAgenda').style.display = 'none';
	if(eval(parent.document.getElementById('iFrameModal'))) parent.document.getElementById('iFrameModal').style.display = 'none';

	if(eval(document.getElementById('iFrameAgenda'))) document.getElementById('iFrameAgenda').style.display = 'none';
	if(eval(document.getElementById('iFrameModal'))) document.getElementById('iFrameModal').style.display = 'none';

	//if(eval($id('iDivInfo'))) $id('iDivInfo').style.display = 'none';
}

function validarCampos(formulario){
			for (i=0;i<formulario.length;i++) {
				var tempobj = formulario.elements[i];
				obrigatorio = eval(tempobj.getAttribute('obrigatorio'));
				nome_campo  = tempobj.getAttribute('nome_exibicao');
				if(obrigatorio == null) { obrigatorio = false }
				if(obrigatorio==true){
					if (ConsisteCampoBranco(tempobj.value) == true){
						alert("Você esqueceu de informar o campo \""+ nome_campo +"\".");
						tempobj.focus();
						return false;
					}
				}
			}
			return true;
}

function ReplaceAll(sStr, sDe, sPara)
{
	while (sStr.indexOf(sDe) != -1)
		sStr = sStr.replace(sDe, sPara)
	return sStr;	
}

function info(titulo, texto, w, h, e, x, y) {
		
	if(e != null) {
		
		if (event.pageX) { // NS 4, Mozilla
			x = event.pageX;
			y = event.pageY;
		} else { // IE, Opera
			var root = document.documentElement || document.body;
			x = event.clientX - root.scrollLeft;
			y = event.clientY - root.scrollTop;
		}
	}
				
	var iframe;
	var div;
	
	if(!eval($id('iFrameInfo'))) {
		iframe = document.createElement("IFRAME"); 
		iframe.id="iFrameInfo"; 
		iframe.frameBorder = '0';
		iframe.border = '0';
		iframe.style.display = 'none';
		iframe.style.zIndex = 99;
		iframe.style.position = 'absolute';
		iframe.style.border = '0px'
		document.body.appendChild(iframe);
	}
	else iframe = $id('iFrameInfo');
	
	if(!eval($id('iDivInfo'))) {
		div=document.createElement("div"); 
		div.id="iDivInfo"; 
		div.style.zIndex = 100;
		div.style.display = 'none';
		div.style.position = 'absolute';
		div.className= 'divInfo';
		document.body.appendChild(div);
	}
	else div = $id('iDivInfo');
	
	iframe.style.left = x;
	iframe.style.top  = y + 18;
	iframe.style.width = w;
	iframe.style.height = h;

	div.style.left = x  + 2;
	div.style.top  = y + 21;
	div.style.width = w;
	div.style.height = h;
	
	div.innerHTML = "<h1>" + titulo + "</h1><span>" + texto + "</span>"
	iframe.style.display = '';
	div.style.display = '';
}

function infoHidden() {

	if(eval($id('iFrameInfo'))) $id('iFrameInfo').style.display = 'none';
		
	if(eval($id('iDivInfo'))) $id('iDivInfo').style.display = 'none';
}

//tabs
function initTabs(ini){
	var length = oTabs.length;
	var html = "";
	
	if (navigator.appName.indexOf('Microsoft') != -1)
		var medida = "";
	else
		var medida = "style='width:100px'";
	
	for(var i = 0; i < length; i ++) {
		html += "<li "+medida+"><a id=\"" + oTabs[i][1] + "\" href=\"javascript:void(0);\" onclick=\"select_tab(" + i + "); buscaCargaAbasAjax(document.form1.A014_cod_plano.value, document.form1.A216_cod_temporada.value, '"+oTabs[i][3]+"', document.form1.A217_ini_temp.value, document.form1.A217_fim_temp.value); \"><font color='#"+oTabs[i][4]+"'><strong>"+ oTabs[i][0] +"</strong></font></a></li>";
	}
	
	document.getElementById("data_tabs").innerHTML = "<ul style='list-style: none; margin: 0;'>"+ html +"</ul>";
	
	if(ini == "" || ini == null)
	ini = 0;
	
	select_tab(ini);
}

function limpaTabs(){
	var length = oTabs.length;
	for(var i = 0; i < length; i ++) {
		document.getElementById(oTabs[i][1]).className = "";
		document.getElementById(oTabs[i][2]).style.display = "none";
	}
}

function select_tab(i){
	var idTab = oTabs[i][1];
	var conteudoTab = oTabs[i][2];
	
	limpaTabs();

	document.getElementById(idTab).className = "tabs_selecionada";
	document.getElementById(conteudoTab).style.display = "inline";
}

//******************************************************************
/******************************************************************************************************************************/
function mascaraCampo(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}

//******************************************************************
/******************************************************************************************************************************/
function telefone(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}


//******************************************************************
//******************************************************************
//Verifica se os cookyes estão ativos no site.
//******************************************************************
//******************************************************************


function fValidaCookye(){
	var tmpcookie = new Date();
	chkcookie = (tmpcookie.getTime() + '');
	document.cookie = "chkcookie=" + chkcookie + "; path=/";
	if (document.cookie.indexOf(chkcookie,0) < 0) {
  //var nom = navigator.appVersion;   
   // var nom = window.navigator.userAgent;   
	  //alert(nom);
		if(navigator.appVersion.indexOf("MSIE")!= -1){
    var temp = navigator.appVersion.split("MSIE");
    var versao = parseFloat(temp[1]);
    var codigo = 1;
		//alert(codigo);
		//window.alert(versao);
		var msg = encodeURI("Você está usando a versão " + versao + " do IE.");
		//window.alert("Você está usando a versão " + versao + " do IE.");
    }
    if(navigator.userAgent.indexOf("Firefox")!= -1){
    var temp = navigator.userAgent.indexOf("Firefox") + 8;
    var versao = navigator.userAgent.substring(temp, temp + 6);
    var codigo = 2;
		var msg = encodeURI("Você está usando a versão " + versao + " do Firefox");
		//alert("Você está usando a versão " + versao + " do Firefox");
    }
    if(window.navigator.userAgent.indexOf("Navigator")!= -1){
    var temp = window.navigator.userAgent.indexOf("Navigator") + 8;
		var versao = window.navigator.userAgent.substring(temp, temp + 6);
    var codigo = 3;
		var msg = encodeURI("Você está usando a versão " + versao + " do Netscape Navigator");
		//alert("Você está usando a versão " + versao + " do Netscape");
    }
		document.getElementById("divHelpCookie").style.visibility = "visible";
 		var url = "../includes/buscaInstantaneaHelp.asp?versao="+versao+"&codigo="+codigo+"&msg="+msg;
		fCarregaHelpAjax(url, "divHelpCookie")
	}
}
 
//******************************************************************
//******************************************************************

function fApagahelp(){
	document.getElementById("divHelpCookie").style.visibility = "hidden";
}
	
function fJanela(cod,titulo){
	window.open(cod,titulo,'left=200,location=no, scrollbars=yes, menubar=no, resizable=yes, top=60 ,width=500, height=650');
}

//limpa os espaços a direita e a esquerda.
function Trim(str){return str.replace(/^\s+|\s+$/g,"");}


/*
* função para permitir a  digitação de números decimais e inteiros
esta função é chamada da seguinte maneira:

Para permitir a digitação de números inteiros de decimais positivos ou negativos
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric" value=""
    onkeydown="ForceNumericInput(event, this, true, true)" />
		
Para permitir a digitação de inteiros positivos ou negativos
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric"
    value="" onkeydown="ForceNumericInput(event, this, false, true)" />
		
Para permitir a digitação de inteiros e decimais positivos
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric"
    value="" onkeydown="ForceNumericInput(event, this, true, false)" />
		
Para permitir a digitação de somente inteiros positivos
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric"
    value="" onkeydown="ForceNumericInput(event, this, false, false)" />
*/
function ForceNumericInput(event, This, AllowDecimal, AllowMinus)
{
if(arguments.length == 1)
{
var s = This.value;
// garante que o sinal de "-" seja o primeiro do índice
var i = s.lastIndexOf("-");
if(i == -1)
return;
if(i != 0)
This.value = s.substring(0,i)+s.substring(i+1);
return;
}
switch(event.keyCode)
{
case 8:     // backspace
case 9:     // tab
case 37:    // left arrow
case 39:    // right arrow
case 46:    // delete
event.returnValue = true;
return;
}
if(event.keyCode == 189)     // sinal de número de negativo
{
if(AllowMinus == false)
{
CancelEventExecution(event);
return;
}
// aguarda até que o controle tenha sido atualizado
var s = "ForceNumericInput(document.getElementById('"+This.id+"'))";
setTimeout(s, 250);
return;
}
if(AllowDecimal && event.keyCode == 188)
{
if(This.value.indexOf(",") >= 0)
{
// restringe a digitação de apenas uma vírgula
CancelEventExecution(event);
return;
}
event.returnValue = true;
return;
}
// permite caracteres entre 0 e 9
if(event.keyCode >= 48 && event.keyCode <= 57)
{
event.returnValue = true;
return;
}
CancelEventExecution(event);
}
/*
* Cancela a execução de uma function mapeada por um evento
*/
function CancelEventExecution(event)
{
if (navigator.appName == "Netscape")
{
event.preventDefault();
}
else
{
event.returnValue = false;
}
}

function fIdentificaNavegador(){
	
	if(window.navigator.userAgent.indexOf("MSIE 8.0")!= -1){
		return "IE8";
  }
		
	if((window.navigator.userAgent.indexOf("MSIE")!= -1) && (window.navigator.userAgent.indexOf("MSIE 8.0")== -1)){
		return "IE";
  }
		
  if(window.navigator.userAgent.indexOf("Firefox")!= -1){
		return "FF";
	}

  if(window.navigator.userAgent.indexOf("Opera")!= -1){
		return "OP";
	}

  if(window.navigator.userAgent.indexOf("Chrome")!= -1){
		return "CH";
	}

}