<!--

// JavaScript Document
/***********************************************
* Switch Menu script- by Martial B of http://getElementById.com/
* Modified by Dynamic Drive for format & NS4/IE4 compatibility
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

var persistmenu="yes" //"yes" or "no". Make sure each SPAN content contains an incrementing ID starting at 1 (id="sub1", id="sub2", etc)
var persisttype="sitewide" //enter "sitewide" for menu to persist across site, "local" for this page only

if (document.getElementById){ //DynamicDrive.com change
document.write('<style type="text/css">\n')
document.write('.submenu{display: none;}\n')
document.write('</style>\n')
}

function SwitchMenu(obj){
	if(document.getElementById){
	var el = document.getElementById(obj);
	var ar = document.getElementById("masterdiv").getElementsByTagName("span"); //DynamicDrive.com change
		if(el.style.display != "block"){ //DynamicDrive.com change
			for (var i=0; i<ar.length; i++){
				if (ar[i].className=="submenu") //DynamicDrive.com change
				ar[i].style.display = "none";
			}
			el.style.display = "block";
		}else{
			el.style.display = "none";
		}
	}
}


function get_cookie(Name) { 
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) { 
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

function onloadfunction(){
if (persistmenu=="yes"){
var cookiename=(persisttype=="sitewide")? "switchmenu" : window.location.pathname
var cookievalue=get_cookie(cookiename)
if (cookievalue!="")
document.getElementById(cookievalue).style.display="block"
}
}

function savemenustate(){
var inc=1, blockid=""
while (document.getElementById("sub"+inc)){
if (document.getElementById("sub"+inc).style.display=="block"){
blockid="sub"+inc
break
}
inc++
}
var cookiename=(persisttype=="sitewide")? "switchmenu" : window.location.pathname
var cookievalue=(persisttype=="sitewide")? blockid+";path=/" : blockid
document.cookie=cookiename+"="+cookievalue
}

if (window.addEventListener)
window.addEventListener("load", onloadfunction, false)
else if (window.attachEvent)
window.attachEvent("onload", onloadfunction)
else if (document.getElementById)
window.onload=onloadfunction

if (persistmenu=="yes" && document.getElementById)
window.onunload=savemenustate
//FIM

//COMEÇO
//Rich HTML Balloon Tooltip: http://www.dynamicdrive.com/dynamicindex5/balloontooltip.htm
//Created: September 10th, 2006

var disappeardelay=250  //tooltip disappear delay (in miliseconds)
var verticaloffset=0 //vertical offset of tooltip FROM anchor link, if any
var enablearrowhead=0 //0 or 1, to disable or enable the arrow image
var arrowheadimg=["", ""] //path to down and up arrow images
var arrowheadheight=11 //height of arrow image (amount to reveal)

/////No further editting needed

var ie=document.all
var ns6=document.getElementById&&!document.all
verticaloffset=(enablearrowhead)? verticaloffset+arrowheadheight : verticaloffset

function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

function showhide(obj, e){
dropmenuobj.style.left=dropmenuobj.style.top="-500px"
if (e.type=="mouseover")
obj.visibility="visible"
}

function iecompattest(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
if (whichedge=="rightedge"){
edgeoffsetx=0
var windowedge=ie && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
edgeoffsetx=dropmenuobj.contentmeasure-obj.offsetWidth
return edgeoffsetx
}
else{
edgeoffsety=0
var topedge=ie && !window.opera? iecompattest().scrollTop : window.pageYOffset
var windowedge=ie && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure) //move up?
edgeoffsety=dropmenuobj.contentmeasure+obj.offsetHeight+(verticaloffset*2)
return edgeoffsety
}
}

function displayballoontip(obj, e){ //main ballooon tooltip function
if (window.event) event.cancelBubble=true
else if (e.stopPropagation) e.stopPropagation()
if (typeof dropmenuobj!="undefined") //hide previous tooltip?
dropmenuobj.style.visibility="hidden"
clearhidemenu()
//obj.onmouseout=delayhidemenu
dropmenuobj=document.getElementById(obj.getAttribute("rel"))
showhide(dropmenuobj.style, e)
dropmenuobj.x=getposOffset(obj, "left")
dropmenuobj.y=getposOffset(obj, "top")+verticaloffset
dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+"px"
dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+"px"
if (enablearrowhead)
displaytiparrow()
}

function displaytiparrow(){ //function to display optional arrow image associated with tooltip
tiparrow=document.getElementById("arrowhead")
tiparrow.src=(edgeoffsety!=0)? arrowheadimg[0] : arrowheadimg[1]
var ieshadowwidth=(dropmenuobj.filters && dropmenuobj.filters[0])? dropmenuobj.filters[0].Strength-1 : 0
//modify "left" value depending on whether there's no room on right edge of browser to display it, respectively
tiparrow.style.left=(edgeoffsetx!=0)? parseInt(dropmenuobj.style.left)+dropmenuobj.offsetWidth-tiparrow.offsetWidth-10+"px" : parseInt(dropmenuobj.style.left)+5+"px"
//modify "top" value depending on whether there's no room on right edge of browser to display it, respectively
tiparrow.style.top=(edgeoffsety!=0)? parseInt(dropmenuobj.style.top)+dropmenuobj.offsetHeight-tiparrow.offsetHeight-ieshadowwidth+arrowheadheight+"px" : parseInt(dropmenuobj.style.top)-arrowheadheight+"px"
tiparrow.style.visibility="visible"
}

function delayhidemenu(){
delayhide=setTimeout("dropmenuobj.style.visibility='hidden'; dropmenuobj.style.left=0; if (enablearrowhead) tiparrow.style.visibility='hidden'",disappeardelay)
}

function clearhidemenu(){
if (typeof delayhide!="undefined")
clearTimeout(delayhide)
}

function reltoelement(linkobj){ //tests if a link has "rel" defined and it's the ID of an element on page
var relvalue=linkobj.getAttribute("rel")
return (relvalue!=null && relvalue!="" && document.getElementById(relvalue)!=null && document.getElementById(relvalue).className=="balloonstyle")? true : false
}

function initalizetooltip(){
var all_links=document.getElementsByTagName("a")
if (enablearrowhead){
tiparrow=document.createElement("img")
tiparrow.setAttribute("src", arrowheadimg[0])
tiparrow.setAttribute("id", "arrowhead")
document.body.appendChild(tiparrow)
}
for (var i=0; i<all_links.length; i++){
if (reltoelement(all_links[i])){ //if link has "rel" defined and it's the ID of an element on page
all_links[i].onmouseover=function(e){
var evtobj=window.event? window.event : e
displayballoontip(this, evtobj)
}
all_links[i].onmouseout=delayhidemenu
}
}
}

if (window.addEventListener)
window.addEventListener("load", initalizetooltip, false)
else if (window.attachEvent)
window.attachEvent("onload", initalizetooltip)
else if (document.getElementById)
window.onload=initalizetooltip



function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
//-->
function selecionaCod(codSolicitacao,codEmpresa,codCliente,form){
	document.getElementById('cod').value = codSolicitacao;
		document.getElementById('codEmpresa').value = codEmpresa;
			document.getElementById('codCliente').value = codCliente;
				document.getElementById('Visualiza').value = "S";
	form.submit();
	
}

function selecionaElemento(codElemento,form){
	document.getElementById('cod').value = codElemento;
		document.getElementById('Visualiza').value = "S";
	form.submit();
}


function selecionaUsu(codUsuario,form){
	document.getElementById('cod').value = codUsuario;
				document.getElementById('Visualiza').value = "S";
	form.submit();
	
}


function testeabc(a, b){
    alert ("teste");
}

function contador(campo){
	if(fraseSemEspaco(campo) == 'S'){
		alert('Existe ao menos uma palavra muito grande nesse texto! Utilize a barra de espa?os.')
		document.getElementById(campo.id).value = '';
	}
	else{
		if((2000-campo.value.length) <= 0){
		   alert('Limite de caracteres atingido!');
		   campo.value = campo.value.substr(0,2000);
		}
	}
	document.getElementById("qtd").value = 2000-campo.value.length
}

function validaTamanho(obj){
	if(fraseSemEspaco(obj) == 'S'){
		alert('Existe ao menos uma palavra muito grande nesse texto! Utilize a barra de espacos.')
		document.getElementById(obj.id).value = '';
	}
	else{
		if(obj.value.length > obj.maxlength){
			alert('Limite de caracteres atingido!');
			document.getElementById(obj.id).value = obj.value.substr(0,obj.maxlength);
		}
	}
}

function fraseSemEspaco(campo){
	var erro = 'N';
	var vet = campo.value.split(" ");
	for(i=0;i<vet.length;i++){
		if(vet[i].length > 50){
			erro = 'S';
		}
	}
	
	return erro;
}

function confirmacao231(visualizarNota, id_nota_fiscal, op){
    if (confirm("Deseja realmente cancelar esta nota fiscal?"))
		top.rodape.document.location='action/notaFiscal/consultarNotaFiscalResult.php?verNota='+visualizarNota+'&id_nota_fiscal='+id_nota_fiscal+'&op='+op; 
    else
        return false;
}

function confirmaCancelamento(id){
    if (confirm("Deseja realmente cancelar esta guia?"))
		top.principal.document.location='action/emitirGuiaNota.php?btnCancelarGuia=Cancelar%20Guia&id_guia='+id; 
    else
        return false;
}

function trocaPeriodoExportacao() {
	if (document.getElementsByName("rPeriodoEN")[1].checked == true) {
	 	document.getElementsByName("rMesCompetenciaEN")[0].disabled = true;	
	 	document.getElementsByName("rAnoCompetenciaEN")[0].disabled = true;	 	
		document.getElementsByName("rDataInicioEN")[0].disabled = false;
		document.getElementsByName("rDataFimEN")[0].disabled = false;			
	} else {
	 	document.getElementsByName("rMesCompetenciaEN")[0].disabled = false;	
	 	document.getElementsByName("rAnoCompetenciaEN")[0].disabled = false;	 	
		document.getElementsByName("rDataInicioEN")[0].disabled = true;
		document.getElementsByName("rDataFimEN")[0].disabled = true;			
	}
}


function trocaPeriodoCredito() {
	if (document.getElementsByName("rPeriodoCC")[1].checked == true) {
	 	document.getElementsByName("rMesCompetenciaCC")[0].disabled = true;	
	 	document.getElementsByName("rAnoCompetenciaCC")[0].disabled = true;	 	
		document.getElementsByName("rDataInicioCC")[0].disabled = false;
		document.getElementsByName("rDataFimCC")[0].disabled = false;			
	} else {
	 	document.getElementsByName("rMesCompetenciaCC")[0].disabled = false;	
	 	document.getElementsByName("rAnoCompetenciaCC")[0].disabled = false;	 	
		document.getElementsByName("rDataInicioCC")[0].disabled = true;
		document.getElementsByName("rDataFimCC")[0].disabled = true;			
	}
}


function controlaSelecaoTomador(valor){
	if(valor==""){
		document.getElementById("rTomCpfCnpj").readOnly = false;
		document.getElementById("rTomCpfCnpj").className = "campo";
		document.getElementById("rTomCpfCnpj").value = '';
		document.getElementById("rTomCpfCnpj").focus();
	}
	else{
		document.getElementById("rTomCpfCnpj").readOnly = true;
		document.getElementById("rTomCpfCnpj").className = "campo disabled";
		document.getElementById("rTomCpfCnpj").value = '';
	}
}

function trocaUf(f,obj){
	document.getElementById("rAntesGravar").value = 'S';
	document.getElementById("rAntesGravarCidade").value = 'N';
	document.getElementById(obj.id).value = obj.value;
	f.submit();
}

function trocaCidade(f,obj){
	document.getElementById("rAntesGravar").value = 'S';
	document.getElementById("rAntesGravarCidade").value = 'S';
	document.getElementById(obj.id).value = obj.value;
	f.submit();
}

function trocaRecolhimento(f,obj){
	document.getElementById("rAntesGravar").value = 'S';
	document.getElementById("rAntesGravarRecolhimento").value = 'S';

	document.getElementById(obj.id).value = obj.value;
	f.submit();
}

function trocaTributacao(f,obj){
	document.getElementById("rAntesGravar").value = 'S';
	document.getElementById("rAntesGravarTributacao").value = 'S';
	document.getElementById(obj.id).value = obj.value;
	f.submit();
}

function controlaSelecaoAtividade(valor,page){
	if(valor != ""){
		if(valor == "0"){
			document.location=page+'?todasAtividades=S';
		}
		else{
			if(page == 'prestador/configurarPerfil.php'){
				document.getElementById("rAntesGravar").value = 'S';
				document.getElementById("valor").value = valor;
				document.forms["configurarPerfil"].submit();
			}
			else
				parent.rodape.location='action/'+page+'?achaAliquota=S&valor='+valor;
		}
	}
	else{
		document.getElementById("rAliquota").value = '';
		document.getElementById("rAliquota").readOnly = false;
		document.getElementById("rAliquota").className = "campo";
		document.getElementById("rDescrServ").value = '';
		document.getElementById("rCodServ").value = '';
	}
}

function exibirDescricao(rowName){
	var estado = document.getElementById("rItemDeducao").checked;
	var table = document.getElementById("item");

	for (var i = 0; i < table.rows.length; i++) {
		if(table.rows[i].id == rowName){
			if(estado == true){
				table.rows[i].cells[1].innerHTML = '<select name="rItemDescricao" id="rItemDescricao" class="campo" style="width:330px;"><option value="Despesas com Materiais">Despesas com Materiais</option><option value="Despesas com Subempreitada">Despesas com Subempreitada</option></select>';
			}
			else{
				table.rows[i].cells[1].innerHTML = '<textarea name="rItemDescricao" cols="62" rows="1" id="rItemDescricao" class="campo"></textarea>';
			}
		}
	}

}

function calculaValorTotal(){
	qtd = this.trocaDecimal(document.getElementById("rItemQtd").value,',','');
	qtd = this.trocaDecimal(qtd,'.','');
	document.getElementById("rItemQtd").value = qtd;
	
	//val = this.trocaDecimal(document.getElementById("rItemValUnit").value,',','.');
	val = this.moeda2float(document.getElementById("rItemValUnit").value);

	if((qtd != "") && (val != "")){
		tot = qtd * val;
		if(tot.toString() != "NaN")
			document.getElementById("rItemValTotal").value = this.float2moeda(tot);
			//document.getElementById("rItemValTotal").value = this.number_format(tot,2,",","");
			
			//VALOR DO ISS B?SICO
			/*aliq = this.trocaDecimal(document.getElementById("rAliquota").value,',','.');
			if(aliq != ""){
				iss = tot * (aliq / 100); 
				document.getElementById("rItemValIss").value = this.number_format(iss,2,",","");
			}
			else{
				document.getElementById("rItemValIss").value = "0,00";
			}*/
	}
	
	document.getElementById("rItemValUnit").value = this.float2moeda(val);
	//document.getElementById("rItemValUnit").value = this.trocaDecimal(val,'.',',');
}

function recalculaValoresIss(){
	totNota = this.trocaDecimal(document.getElementById("rValTotNota").value,',','.');
	totDed = this.trocaDecimal(document.getElementById("rValTotDed").value,',','.');
	aliq = this.trocaDecimal(document.getElementById("rAliquota").value,',','.');

	if((totNota != "") && (totDed != "") && (aliq != "")){
		tot = (totNota - totDed) * (aliq / 100);
		if(tot < 0)
			tot = 0;
		if(tot.toString() != "NaN")
			document.getElementById("rValTotIss").value = this.number_format(tot,2,",","");
	}
}

function excluirItem(itemId,f){
	document.getElementById("itemId").value = itemId;
	document.getElementById("botaoApagar").value = 'S';
	f.submit();
	//parent.rodape.location='action/notaFiscal/emitirNotaFiscalPasso6.php?btnExcluir=S&itemId='+itemId;
}

function excluirDeducao(deducaoId){
	parent.rodape.location='action/notaFiscal/emitirNotaFiscalPasso5.php?btnExcluir=S&deducaoId='+deducaoId;
}
/*
function mudaDeducoes(tela){
	document.getElementById("telaDeducao").value = tela;
}*/

function editarSubUsuario(subUsuarioId){
	parent.rodape.location='action/usuario/cadastrarSubUsuario.php?btnEditar=S&subUsuarioId='+subUsuarioId;
}

function limpar(){
	document.getElementById("rSubUsuarioNome").value = "";
}

function marcaImposto(imposto,marcacao){
	aliquota = this.trocaDecimal(document.getElementById("rAliq"+imposto).value,',','.');
	if(marcacao == true){
		this.recalculaAliquota(imposto,aliquota);
	}
	else{
		document.getElementById("rVal"+imposto).value = "0,00";
	}
}

function recalculaAliquota(imposto,aliquota){
	//valorBase = this.trocaDecimal(document.getElementById("rValTotServ").value,',','.');
	//aliquota = this.trocaDecimal(aliquota,',','.');
	valorBase = this.moeda2float(document.getElementById("rValTotServ").value);
	aliquota = this.moeda2float(aliquota);
	
	valor = valorBase * (aliquota / 100);
	if(valor < 0)
		valor = 0;
	if(valor.toString() != "NaN"){
		if(document.getElementById("rTem"+imposto).checked == true)
			document.getElementById("rVal"+imposto).value = this.float2moeda(valor);
			//document.getElementById("rVal"+imposto).value = this.number_format(valor,2,",","");
		else
			document.getElementById("rVal"+imposto).value = "0,00";
	}
}

function trocaDecimal(valor,sai,entra){
	if(valor != ""){
		return valor.replace(sai,entra);
	}
	else
		return '';
}

function number_format (number, decimals, dec_point, thousands_sep)
{
  var exponent = "";
  var numberstr = number.toString ();
  var eindex = numberstr.indexOf ("e");
  if (eindex > -1)
  {
    exponent = numberstr.substring (eindex);
    number = parseFloat (numberstr.substring (0, eindex));
  }
  
  if (decimals != null)
  {
    var temp = Math.pow (10, decimals);
    number = Math.round (number * temp) / temp;
  }
  var sign = number < 0 ? "-" : "";
  var integer = (number > 0 ? 
      Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
  
  var fractional = number.toString ().substring (integer.length + sign.length);
  dec_point = dec_point != null ? dec_point : ".";
  fractional = decimals != null && decimals > 0 || fractional.length > 1 ? 
               (dec_point + fractional.substring (1)) : "";
  if (decimals != null && decimals > 0)
  {
    for (i = fractional.length - 1, z = decimals; i < z; ++i)
      fractional += "0";
  }
  
  thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
                  thousands_sep : null;
  if (thousands_sep != null && thousands_sep != "")
  {
	for (i = integer.length - 3; i > 0; i -= 3)
      integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
  }
  
  return sign + integer + fractional + exponent;
}

function checkCompetencia(field) {
	DateValue = field.value; 
	
	/* Deletando todos os caracteres exceto o 0..9 */ 
	DateValue = DateValue.replace(/[^0-9]/gi, '');
	var modificado = true;
	
	if(DateValue.length == 6)
		DateValue = DateValue.substr(0,2)+"/"+DateValue.substr(2, 5);

	else if(DateValue.length == 5)
		DateValue = "0"+DateValue.substr(0,1)+"/"+DateValue.substr(1, 4);

	else if(DateValue.length == 4)
		DateValue = DateValue.substr(0,2) + "/20" + DateValue.substr(2,4);

	else if(DateValue.length == 3)
		DateValue = "0" + DateValue.substr(0,1) + "/20" + DateValue.substr(1,2);

	else
		modificado = false;
	
	if(modificado == true){
		field.value = DateValue;
		
		/*separado = DateValue.split('/');
		
		hoje = new Date();
		if((separado[0] < 1) || (separado[0]) > 12)
			alert("Verifique Mes de Competencia");
		else if((separado[1] < 1980) || (separado[1] > hoje.getFullYear()))
			alert("Verifique Mes de Competencia");*/
	}
}


function marcaItens(){
    var status="";
    for (i=0; i < document.forms[0].elements.length; i++){ 
    	if (document.forms[0].elements[i].checked == true) {
	    	document.forms[0].elements[i].checked = false;
	    } else {
		    document.forms[0].elements[i].checked = true;
	    }
        //document.emitirGuiaNota.elements[i].checked=true;
    } 
}

function desmarcaGrupo(){
    for (i=0; i < document.forms[0].elements.length; i++){ 
		document.forms[0].elements[i].checked=false;
    }
}

function checkDate(field) {
	var checkstr = "0123456789"; 
	var DateField = field; 
	var Datevalue = ""; 
	var DateTemp = ""; 
	var seperator = "/"; 
	var day; 
	var month; 
	var year; 
	var leap = 0; 
	var err = 0; 
	var i; 
	err = 0; 
	DateValue = DateField.value; 
	
	/* Deletando todos os caracteres exceto o 0..9 */ 
	for (i = 0; i < DateValue.length; i++){ 
		if (checkstr.indexOf(DateValue.substr(i,1)) >= 0)
			DateTemp = DateTemp + DateValue.substr(i,1); 
	}
	DateValue = DateTemp; 
	
	if(DateValue.length == 0)
		err = 20;
	
	if (DateValue.length > 8)
		err = 19;
	
	/* Exectutando a data para 8 digitos - string*/ 
	/* if entrada do ano com 2-digitos / exemplo 20xx */ 
	if (DateValue.length == 6)
		DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); 
		
		
	/* Se o ano for errado = 0000 */ 
	year = DateValue.substr(4,4); 
	if (year == 0)
		year = 2007;
	
	/* Validando o mes*/ 
	month = DateValue.substr(2,2); 
	if (month < 1)
		month = "01";

	if (month > 12)
		month = 12;
	
	/* Validando o dia*/ 
	day = DateValue.substr(0,2); 
	if (day < 1)
		day = "01";
	
	/* Validando ano Bissexto / fevereiro / dia */
	if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0))
		leap = 1;
	if ((month == 2) && (leap == 1) && (day > 29))
		day = 29;
	if ((month == 2) && (leap != 1) && (day > 28))
		day = 28;
	
	
	/* Validando o mes */ 
	if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12")))
		day = 31; 
	if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) 
		day = 30; 
		
	/* if 00 houvendo entrada, com erros */ 
	if ((day == 0) && (month == 0) && (year == 00)){
		err = 18;
		day = ""; 
		month = ""; 
		year = ""; 
		seperator = "";
	}
	

/* if sem erros, escrevo a data completa no Input-Field (e.x. 13/12/2001) */ 
	if (err == 0) 
		DateField.value = day + seperator + month + seperator + year; 
	else
		DateField.value = "";
}


function trocaPeriodo() {
	if (document.getElementsByName("rPeriodoCN")[1].checked == true) {
	 	document.getElementsByName("rMesCompetenciaCN")[0].disabled = true;	
	 	document.getElementsByName("rAnoCompetenciaCN")[0].disabled = true;	 	
		document.getElementsByName("rDataInicioCN")[0].disabled = false;
		document.getElementsByName("rDataFimCN")[0].disabled = false;			
	} else {
	 	document.getElementsByName("rMesCompetenciaCN")[0].disabled = false;	
	 	document.getElementsByName("rAnoCompetenciaCN")[0].disabled = false;	 	
		document.getElementsByName("rDataInicioCN")[0].disabled = true;
		document.getElementsByName("rDataFimCN")[0].disabled = true;			
	}
}

function pegaPos(obj){
  var topo = obj.offsetTop + obj.offsetHeight;
  objY=obj;
  while((objY = objY.offsetParent) != null) topo += objY.offsetTop;
  
  var esquerda = obj.offsetLeft + obj.offsetWidth;
  objX=obj;
  while((objX = objX.offsetParent) != null) esquerda += objX.offsetLeft;
  var retorno = Array(topo,esquerda);
  return retorno;
}


var timerID = null;
function abreFecha(bloco){
	
	if(document.getElementById(bloco).style.position == 'absolute'){
	    document.getElementById(bloco).style.visibility = 'visible';
	    document.getElementById(bloco).style.display = 'inline';
	    //alert(document.getElementById(bloco).style);
	    //window.clearTimeout(timerID);
    	document.getElementById(bloco).style.position = 'relative';
	    document.getElementById(bloco+"Seta").src = "../NotaFiscal/imagens/setas_up.gif";
	}else{
	    document.getElementById(bloco).style.visibility = 'hidden';
	    document.getElementById(bloco).style.display = 'none';
	    document.getElementById(bloco).style.position = 'absolute';
	    document.getElementById(bloco+"Seta").src = "../NotaFiscal/imagens/setas_down.gif";
	}
	
	if(bloco == "dadosItemNota"){
		bloco2 = "valoresNota";
		abreFecha(bloco2);
	}

}

function buscarCep(cep) {
	parent.rodape.location='action/notaFiscal/consultarCep.php?cep='+cep.value;
}





function validaCNPJ(cnpj){
	digito =  (parseInt(cnpj.charAt(0)) * 5);
	digito += (parseInt(cnpj.charAt(1)) * 4);
	digito += (parseInt(cnpj.charAt(2)) * 3);
	digito += (parseInt(cnpj.charAt(3)) * 2);
	digito += (parseInt(cnpj.charAt(4)) * 9);
	digito += (parseInt(cnpj.charAt(5)) * 8);
	digito += (parseInt(cnpj.charAt(6)) * 7);
	digito += (parseInt(cnpj.charAt(7)) * 6);
	digito += (parseInt(cnpj.charAt(8)) * 5);
	digito += (parseInt(cnpj.charAt(9)) * 4);
	digito += (parseInt(cnpj.charAt(10))* 3);
	digito += (parseInt(cnpj.charAt(11))* 2);
		digito = (digito*10) % 11;
	if(digito == 10)
		digito = 0;
		if(digito == cnpj.charAt(12)){
		digito =  (parseInt(cnpj.charAt(0)) * 6);
		digito += (parseInt(cnpj.charAt(1)) * 5);
		digito += (parseInt(cnpj.charAt(2)) * 4);
		digito += (parseInt(cnpj.charAt(3)) * 3);
		digito += (parseInt(cnpj.charAt(4)) * 2);
		digito += (parseInt(cnpj.charAt(5)) * 9);
		digito += (parseInt(cnpj.charAt(6)) * 8);
		digito += (parseInt(cnpj.charAt(7)) * 7);
		digito += (parseInt(cnpj.charAt(8)) * 6);
		digito += (parseInt(cnpj.charAt(9)) * 5);
		digito += (parseInt(cnpj.charAt(10))* 4);
		digito += (parseInt(cnpj.charAt(11))* 3);
		digito += (parseInt(cnpj.charAt(12))* 2);
			digito = (digito*10) % 11;
		if(digito == 10)
			digito = 0;
			if(digito == cnpj.charAt(13)){
			return "";
		}
		else{
			return "CNPJ Invalido";
		}
	}
	else{
		return "CNPJ Invalido";
	}
}

function validaCPF(cpf){
	digito =  (parseInt(cpf.charAt(0)) * 10);
	digito += (parseInt(cpf.charAt(1)) * 9);
	digito += (parseInt(cpf.charAt(2)) * 8);
	digito += (parseInt(cpf.charAt(3)) * 7);
	digito += (parseInt(cpf.charAt(4)) * 6);
	digito += (parseInt(cpf.charAt(5)) * 5);
	digito += (parseInt(cpf.charAt(6)) * 4);
	digito += (parseInt(cpf.charAt(7)) * 3);
	digito += (parseInt(cpf.charAt(8)) * 2);

	digito = (digito*10) % 11;

	if(digito == 10)
		digito = 0;
		if(digito == cpf.charAt(9)){
		digito =  (parseInt(cpf.charAt(0)) * 11);
		digito += (parseInt(cpf.charAt(1)) * 10);
		digito += (parseInt(cpf.charAt(2)) * 9);
		digito += (parseInt(cpf.charAt(3)) * 8);
		digito += (parseInt(cpf.charAt(4)) * 7);
		digito += (parseInt(cpf.charAt(5)) * 6);
		digito += (parseInt(cpf.charAt(6)) * 5);
		digito += (parseInt(cpf.charAt(7)) * 4);
		digito += (parseInt(cpf.charAt(8)) * 3);
		digito += (parseInt(cpf.charAt(9)) * 2);

		digito = (digito*10) % 11;
		if(digito == 10)
			digito = 0;


		if(digito == cpf.charAt(10)){
			return "";
		}else{
			return "CPF Inválido";
		}
	}else{
		return "CPF Inválido";
	}

}


function FormataCPFDSF(objeto, evento){
	evita_letra2(evento);
	cpf = objeto.value.replace(/[^0-9]/gi, '');
	tamanho = cpf.length;
	
	if(tamanho >= 9)
		cpf = cpf.substr(0, 3)+"."+cpf.substr(3, 3)+"."+cpf.substr(6, 3)+"-"+cpf.substr(9, 3);
	else if(tamanho >= 6)
		cpf = cpf.substr(0, 3)+"."+cpf.substr(3, 3)+"."+cpf.substr(6, 3);
	else if(tamanho >= 3)
		cpf = cpf.substr(0, 3)+"."+cpf.substr(3, 3);
	else 
		cpf = cpf;
		
	objeto.value = cpf;
}


function FormataCNPJDSF(objeto, evento){
	evita_letra2(evento);
	
	cnpj = objeto.value.replace(/[^0-9]/gi, '');
	tamanho = cnpj.length;
	
	if(tamanho >= 12)
		objeto.value = cnpj.substr(0, 2)+"."+cnpj.substr(2, 3)+"."+cnpj.substr(5, 3)+"/"+cnpj.substr(8, 4)+"-"+cnpj.substr(12, 2);
	else if(tamanho >= 8)
		objeto.value = cnpj.substr(0, 2)+"."+cnpj.substr(2, 3)+"."+cnpj.substr(5, 3)+"/"+cnpj.substr(8, 4);
	else if(tamanho >= 5)
		objeto.value = cnpj.substr(0, 2)+"."+cnpj.substr(2, 3)+"."+cnpj.substr(5, 3);
	else if(tamanho >= 2)
		objeto.value = cnpj.substr(0, 2)+"."+cnpj.substr(2, 3);
	else
		objeto.value = cnpj;
}



function cpfcnpj(obj, evento){
	var valida;
	soNumero(obj);
	if(obj.value.replace(/[^0-9]/gi, '').length == 11){
		valida = validaCPF(obj.value);
		if(valida){
			alert(valida);
			obj.value='';
		}else{
			FormataCPFDSF(obj, evento);
            return 'OK';
		}
	}
	else {
		if(obj.value.replace(/[^0-9]/gi, '').length == 14){
			valida = validaCNPJ(obj.value);
			if(valida){
				alert(valida);
				obj.value='';
			}else{
				FormataCNPJDSF(obj, evento);
                return 'OK';
			}
		}
		else {
			if(obj.value.replace(/[^0-9]/gi, '').length > 0){
				alert("CPF/CNPJ com formato inválido.");
				obj.focus();
			}
			obj.value = '';
		}
	}
}




function soNumero(obj){
	qtd = obj.value.length;
	valor = obj.value.replace(/[^0-9$]/gi, '');
	if(qtd > 0 && valor == ""){
		alert('Digite um valor válido.');
		obj.value = '';
		obj.focus();
		return (false);
	}
	else{
		obj.value = valor;
	}
}


function soMoeda(obj){
	qtd = obj.value.length;
	valor = obj.value.replace(/[^0-9.,$]/gi, '');
	if(qtd > 0 && valor == ""){
		alert('Digite um valor válido.');
		obj.value = '';
		obj.focus();
		return (false);
	}
	else{
		//obj.value = valor;
		return (true);
		
	}
}


function evita_letra2(tecla) {
	if (tecla.keyCode < 48 || tecla.keyCode > 57) 
		tecla.returnValue = false;
}

function cpf(obj, evento){
	var valida;
	soNumero(obj);
	if(obj.value.replace(/[^0-9]/gi, '').length == 11){
		valida = validaCPF(obj.value);
		if(valida){
			alert(valida);
			obj.value='';
		}else{
			FormataCPFDSF(obj, evento);
            return 'OK';
		}
	}
	else
		obj.value = '';
}	

//USADO NO FORMATAPARAMOEDA
function LimparMoeda(valor, validos) {
	// retira caracteres invalidos da string
	var result = "";
	var aux;
	for (var i=0; i < valor.length; i++) {
		aux = validos.indexOf(valor.substring(i, i+1));
		if (aux>=0) {
			result += aux;
		}
	}
	return result;
}


//FORMATA??O NO ONKEYDOWN
function FormataParaMoeda(campo,tammax,teclapres,decimal) {
	var tecla = teclapres.keyCode;
	vr = LimparMoeda(campo.value,"0123456789");
	tam = vr.length;
	dec = decimal;
	
	if (tam < tammax && tecla != 8){ 
		tam = vr.length + 1 ; 
	}
	
	if (tecla == 8 ){ 
		tam = tam - 1 ; 
	}
 	
	if ( tecla == 8 || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105)){
	
		if ( tam <= dec ){ 
			campo.value = vr ; 
		}
		
		if ( (tam > dec) && (tam <= 5) ){
			campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; 
		}
		
		if ( (tam >= 6) && (tam <= 8) ){
			campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
		}

		if ( (tam >= 9) && (tam <= 11) ){
			campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
		}
		
		if ( (tam >= 12) && (tam <= 14) ){
			campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
		}
		
		if ( (tam >= 15) && (tam <= 17) ){
			campo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;
		}
	} 
}


function float2moeda(num) {
   x = 0;

   if(num<0) {
      num = Math.abs(num);
      x = 1;
   }   
   
   if(isNaN(num)) 
      num = "0";
   
   cents = Math.floor((num*100+0.5)%100);
   num = Math.floor((num*100+0.5)/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)) + '.' + num.substring(num.length-(4*i+3));   
   
   ret = num + ',' + cents;   
               
   if (x == 1) 
      ret = ' - ' + ret;
      
   return ret;

}

function moeda2float(moeda){

   moeda = moeda.replace(".","");

   moeda = moeda.replace(",",".");

   return parseFloat(moeda);

}


function blNumero(event){
    if (navigator.appName == "Microsoft Internet Explorer")
        var tecla = window.event.keyCode;
    else
        var tecla = event.which;

    if ( (tecla < 48 || tecla > 57) && tecla != 8 && tecla != 0) 
        return false;
    return true;
}

function Trim(str){
	while (str.charAt(0) == " ")
	str = str.substr(1,str.length -1);
	
	while (str.charAt(str.length-1) == " ")
	str = str.substr(0,str.length-1);
	
	return str;
}

function alteraLabel(check){
    if (check == 'adm'){
        document.getElementById("labelUsuario").value='Login:';
    }else if (check == 'web'){
        document.getElementById("labelUsuario").value='Login:';
    }else if (check == 'telefone'){
        document.getElementById("labelUsuario").value='Login:';
    }else if (check == 'solicitante'){
        document.getElementById("labelUsuario").value='CPF/CNPJ:';
        document.getElementById("usuario").value='';
    }
}


function validasenha () {
	if (document.frm.atend_senha.value == ""){
		alert('Atenção: Senha - Campo Obrigatório!');
		document.frm.atend_senha.focus();
		return false;
	}
	if (document.frm.atend_senha.value != document.frm.conf_senha.value){
		alert('Atenção: Confirmação da senha não confere!');
		document.frm.atend_senha.focus();
		return false;
	}
}


function inscMunicipal(insMun){
	if(insMun.length < 7)
		return false;
	else
		return true;
}


function formataInsMun(inscMun){
	inscMun = inscMun.replace(/[^0-9]/gi, '');
	while(inscMun.length < 7){
		inscMun = '0'+inscMun;
	}
	
	inscMun = inscMun.substring(0, 6)+"-"+inscMun.substring(6,7);
	return inscMun;
}

function certidaoPMS(num){
	num = num.replace(/[^0-9]/gi, '');
	while(num.length < 5){
		num = '0'+num;
	}
	
	num = num.substring(0, 5)+""+num.substring(5,5);
	return num;
}


function processoConstrucao(num){
	num = num.replace(/[^a-z]/gi, '');
	while(num.length < 4){
		num = '0'+num;
	}
	
	num = num.substring(0, 4)+""+num.substring(4,4);
	return num;
}




function mostraCarregando(){
    top.principal.document.getElementById("carregando").style.visibility = 'visible'; 
}


function mostraCarregandoPesquisaGrafica(){
    document.getElementById("carregando").style.visibility = "visible";
}


			function check_date(field) {
				var checkstr = "0123456789"; 
				var DateField = field; 
				var Datevalue = ""; 
				var DateTemp = ""; 
				var seperator = "/"; 
				var day; 
				var month; 
				var year; 
				var leap = 0; 
				var err = 0; 
				var i; 
				err = 0; 
				DateValue = DateField.value; 
				
				/* Deletando todos os caracteres exceto o 0..9 */ 
				for (i = 0; i < DateValue.length; i++){ 
					if (checkstr.indexOf(DateValue.substr(i,1)) >= 0)
						DateTemp = DateTemp + DateValue.substr(i,1); 
				}
				DateValue = DateTemp; 
				
				/* Exectutando a data para 8 digitos - string*/ 
				/* if entrada do ano com 2-digitos / exemplo 20xx */ 
				if (DateValue.length == 6)
					DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); 
				
				if (DateValue.length != 8)
					err = 19;
					
				/* Se o ano for errado = 0000 */ 
				year = DateValue.substr(4,4); 
				if (year == 0)
					year = 2001;
				
				/* Validando o mês*/ 
				month = DateValue.substr(2,2); 
				if (month < 1)
					month = "01";

				if (month > 12)
					month = 12;
				
				/* Validando o dia*/ 
				day = DateValue.substr(0,2); 
				if (day < 1)
					day = "01";
				
				/* Validando ano Bissexto / fevereiro / dia */
				if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0))
					leap = 1;
				if ((month == 2) && (leap == 1) && (day > 29))
					day = 29;
				if ((month == 2) && (leap != 1) && (day > 28))
					day = 28;
				
				
				/* Validando o mês */ 
				if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12")))
					day = 31; 
				if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) 
					day = 30; 
					
				/* if 00 houvendo entrada, com erros */ 
				if ((day == 0) && (month == 0) && (year == 00)){
					err = 18;
					day = ""; 
					month = ""; 
					year = ""; 
					seperator = "";
				}
				
		/* if sem erros, escrevo a data completa no Input-Field (e.x. 13/12/2001) */ 
			if (err == 0) 
				DateField.value = day + seperator + month + seperator + year; 
			else
				DateField.value = "";
	}

function validaData(e){
  // Definimos o divisor de nossa nova data
  var divisor = '/'
  // Recebemos a data digitada pelo usuario
  var data = e.value
  // Setamos a nova data para vazia
  var dataAtual = ''
  // Verificamos se o camarada digitou uma data válida
  if (data.match (/^(0[1-9]|[12][0-9]|3[01]).?(0[1-9]|1[012]).?([12][0-9]{3}|[0-9]{2})$/)) {
    // Precisamos trabalhar apenas com numeros
    data = data.replace (/[^0-9]/g, '')
    // adicionamos os dois primeiros pares
    dataAtual = data.substr(0,2)+divisor+data.substr(2,2)+divisor
    // Agora, os quatro ultimos
    // Se o usuário entrar com quatro caracteres, então ele entrou com uma data inteira
    if ( data.substr (4).length == 4 ) dataAtual += data.substr (4)
    // Senão, verificamos se os dois caracteres finais baseiam-se em 30 (lembrem-se do que disse no post)
    else dataAtual += (data.substr (4) > 30 ? '19' : '20') + data.substr (4)
  }
  // Por ultimo, reescrevemos o campo
  e.value = dataAtual
}	


// calendario
function ValidaRel(theForm)
{

if (Trim(theForm.de.value) == "")
 {
  alert("Por favor, digite o período De.")
  theForm.de.focus();
    return (false);
  }

if (Trim(theForm.ate.value) == "")
 {
  alert("Por favor, digite o período Até.")
  theForm.ate.focus();
    return (false);
  }

  return (true);
}

function Trim(s) 
{
  // Remove leading spaces and carriage returns
  while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
  {
    s = s.substring(1,s.length);
  }

  // Remove trailing spaces and carriage returns
  while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
  {
    s = s.substring(0,s.length-1);
  }
  return s;
}

function semLetras(e){
	navegador = /msie/i.test(navigator.userAgent);
	if (navegador)
	var tecla = event.keyCode;
	else
	var tecla = e.which;
	
	if(tecla > 47 && tecla < 58) // numeros de 0 a 9
	return true;
	else
	{
		if ((tecla != 8) && (tecla != 09)  && (tecla != 27)){
			alert('Digite um valor válido!');
		}
		
		if ((tecla != 8) && (tecla != 09)  && (tecla != 27)) // backspace
		return false;
		else
		return true;
	}
}

function somenteNumero(e,retorno) {
	//retorno = true para campo numeros e false para campo letras
	var ctrl = e.ctrlKey;
    var tecla = e.keyCode ? e.keyCode : e.which;
    var teclasPermitidas = new Array('47','46','8','0','45', '9');
    var teclasNaoPermitidas = new Array('17');
    var permitido = false;
    var textoPermitido = true;
    
    for(teclaPermitida in teclasPermitidas) {
    	if(tecla == teclasPermitidas[teclaPermitida]) {
    		permitido = true;
    	}
    }
    
    for(teclaNaoPermitida in teclasNaoPermitidas) {
    	if(tecla == teclasNaoPermitidas[teclaNaoPermitida]) {
    		textoPermitido = false;
    	}
    }
    if((tecla>47 && tecla<58) ||(tecla>95 && tecla<106)) {
    	if(ctrl == 1)
    		return false;
    	else if(retorno)
    		return true;
    	else
    		return false;
    } else {
    	if(retorno) {
    		if(permitido)
    			return true;
    		else
    			return false;
    	} else {
    		if(!textoPermitido)
    			return false;
    		else if(ctrl == 1)
    			return false;
    		else
    			return true;
    	}
    }
}

function pulaCampo(input,proximoInput,qtdeCaracteres) {
	if(input.value.length >= qtdeCaracteres) {
		document.getElementById(proximoInput).focus();
	}
}
