﻿// JScript File

var OnSubmit = false;

function checkSubmit() {
    if (!OnSubmit) {
        OnSubmit = true;
        return true;
    } else {
        //alert('O formulário esta sendo enviado…');
        return false; 
    }
}

function tryResizeIframe()
{
    try { 
        window.parent.resizeIfrmPrincipal();
        window.parent.parent.resizeIfrmISS();
    } catch(e) {        
       //alert(e);
    }
}

function inicializaPagina()
{        
        OnSubmit=false;
        tryResizeIframe();
}

function MostraObjeto(objeto)
{

    var divObj = document.getElementById(objeto);
    divObj.style.display="";
    tryResizeIframe();
}

function ConverteMaiusculo(objeto)
{
    var upperCaseVersion = objeto.value.toUpperCase();
    objeto.value = upperCaseVersion;
} 

function ConverteMinusculo(objeto)
{
    var lowerCaseVersion = objeto.value.toLowerCase();
    objeto.value = lowerCaseVersion;
} 

 function OcultaObjeto(objeto)
 {

    var divObj = document.getElementById(objeto);
    divObj.style.display="none";
    tryResizeIframe();

 }

function hideSelects(status)
{
	var xsels = document.getElementsByTagName("SELECT");
	
	if(xsels.length > 0)
	{
		for(i=0;i<xsels.length;i++)
		{
			xsels[i].style.visibility = status;
		}
	}
}

function travaTela()
{

    try {
    var testaTravaTela = document.getElementById('divTravaTela');
	var xdivTrava
	var xheight;
	var xwidth;
	
	if (testaTravaTela) return;

	if(document.all)
	{
		xheight = document.body.offsetHeight + 'px';
		xwidth = document.body.offsetWidth + 'px';
	}
	else
	{
		xheight = document.body.clientHeight + 'px';
		xwidth = document.body.clientWidth + 'px';
	}

	xdivTrava = document.createElement('DIV');
	
	with(xdivTrava){
	    id = 'divTravaTela';
	    style.position = 'absolute';
	    style.top = '0px';
	    style.left = '0px';
		style.zIndex = '101';
	    style.width = xwidth; 
	    style.height = xheight;
	    style.backgroundColor = '#FFFFFF';
	    style.opacity = '.55';
	    style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=0, xray=0, mirror=0, invert=0, opacity=0.55, rotation=0)';
	}
	
	hideSel = (document.all) ? hideSelects('hidden') : '';

	document.body.appendChild(xdivTrava);

    } catch(e) {
        //alert(e);
    }

}

function destravaTela()
{
	
    try {
	    var xTrava = document.getElementById('divTravaTela');
	    hideSelects('visible');
	    document.body.removeChild(xTrava);
    } catch(e) {
        //alert(e);
    }
	
}

function SelecaoObjeto(objMenu)
{
	//objMenu.bgColor='#A92929'
	//objMenu.style.color='#FFFFFF'
	objMenu.style.color='#267C7D'
	objMenu.style.cursor='pointer'
}

function TiraSelecaoObjeto(objMenu)
{
	//objMenu.bgColor='#FFFFFF'
	objMenu.style.color=''
	objMenu.style.cursor='default'
}

function SetarFocus(xobj) {
    document.getElementById(xobj).focus();
}

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 validaTeclaAlfaNum(event)
{
    if(navigator.appName == 'Microsoft Internet Explorer')
    {
        tecla = event.keyCode;
    }
    else
    {
        tecla = objEvent.which;
    }
    
    if ((tecla >= 16 && tecla <= 20) || tecla == 27 || (tecla >= 32 && tecla <= 40) || tecla == 45 || (tecla >= 91 && tecla <= 93) || (tecla >= 111 && tecla <= 123) || (tecla >= 144 && tecla <= 145))
    {
        return false
    }
    else
    {
        return true
    }
}

function SoNumeros(evnt){
 	if (evnt.keyCode < 48 || evnt.keyCode > 57){
 	    return false
 	}
 }

function Ajusta_Data(input, evnt){

 	if (input.value.length == 2 || input.value.length == 5){
        input.value += "/";
 	}
 
 	return SoNumeros(evnt);
 }

function Verifica_Data(data, obrigatorio, mostraMsg){
//Se o parâmetro obrigatorio for igual à zero, significa que elepode estar vazio, caso contrário, não
//Se o parâmetro mostraMsg for igual à zero, significa que mostra o alert, caso contrario, não

    //var xdata = document.getElementById(data);
 	var strdata = data.value;

 	if((obrigatorio == 1) || (obrigatorio == 0 && strdata != "")){

 		//Verifica a quantidade de digitos informada esta correta.
 		if (strdata.length != 10){
			if(mostraMsg==0)
			{
	 			alert("Formato da data não é válido. Formato correto: - dd/mm/aaaa.");
			}
			
 			return false
 		}

 		//Verifica máscara da data
 		if ("/" != strdata.substr(2,1) || "/" != strdata.substr(5,1)){
 			if(mostraMsg==0)
			{
				alert("Formato da data não é válido. Formato correto: - dd/mm/aaaa.");
			}
 			return false
 		}

 		dia = strdata.substr(0,2)
 		mes = strdata.substr(3,2);
 		ano = strdata.substr(6,4);
 		
 		//Verifica o dia
 		if (isNaN(dia) || dia > 31 || dia < 1){
 			if(mostraMsg==0)
			{
				alert("Formato do dia não é válido.");
			}
 			return false
 		}

 		if (mes == 4 || mes == 6 || mes == 9 || mes == 11){
 			
 			if (dia == "31"){
 				if(mostraMsg==0)
				{
					alert("O mês informado não possui 31 dias.");
				}
 				return false
 			}

 		}
 		if (mes == "02"){

 			bissexto = ano % 4;

 			if (bissexto == 0){

 				if (dia > 29){
 					if(mostraMsg==0)
					{
						alert("O mês informado possui somente 29 dias.");
					}
 					return false
 				}

 			}else{

 				if (dia > 28){
					if(mostraMsg==0)
					{
 					alert("O mês informado possui somente 28 dias.");
					}
 					return false

 				}
 			}
 		}
 	    
 	    //Verifica o mês
 		if (isNaN(mes) || mes > 12 || mes < 1){
			if(mostraMsg==0)
			{
 				alert("Formato do mês não é válido.");
			}
 			return false
 		}
 		
 		//Verifica o ano
 		if (isNaN(ano)){
			if(mostraMsg==0)
			{
	 			alert("Formato do ano não é válido.");
			}
 			return false
 		}
 	}
 	return true
 }
 
function VerificaPeriodoDt(cdata1, cdata2) {

    var data1 = cdata1.value
    var data2 = cdata2.value

    var TotalData1 = parseInt(data1.split( "/" )[2].toString() + data1.split( "/" )[1].toString() + data1.split( "/" )[0].toString()) 
    var TotalData2 = parseInt(data2.split( "/" )[2].toString() + data2.split( "/" )[1].toString() + data2.split( "/" )[0].toString())

    if (TotalData1>TotalData2)
    {
      return false
    }
    else
    {
      return true
    }
}

function SelecionaItemGrid(row) {

    for (i=0; i<row.cells[row.cells.length-1].childNodes.length; i++)
    {
    
        if (row.cells[row.cells.length-1].childNodes[i].nodeName=='INPUT')
        {
            xSubmit = row.cells[row.cells.length-1].childNodes[i]
            break
        }
    }

    if (xSubmit) {
        xSubmit.click()
    }

}


function maskCEP(objId)
{
	var xobj = document.getElementById(objId);
	var str = xobj.value;
	if(str.length == 5)
	{
		str = str + "-";
	}
	xobj.value = str;
}

function atualizaImgSeguranca(){
	alert(document.getElementById('imgSeguranca').src);
    document.getElementById('imgSeguranca').src = 'imgSeguranca.aspx';
}


function resizeIfrmPrincipal() {    
    
	try{	
		if(document.all)
		{
			var xbody	= ifrmPrincipal.document.body;
			var xMenuLeft = document.getElementById('linkLeftMenu');
			var xframe	= document.all("ifrmPrincipal");
			var xTam    = xbody.scrollHeight + xbody.offsetHeight - xbody.clientHeight;
				
			xframe.style.height = ( xTam < xMenuLeft.offsetHeight ) ? xMenuLeft.offsetHeight : xTam;
//			alert('NF ' + xTam);
			
		}
		else
		{
			var xifrmPrincipal = document.getElementById('ifrmPrincipal');
			var xMenuLeft = document.getElementById('linkLeftMenu');
			if (xifrmPrincipal)
			{
				var xheight = ifrmPrincipal.document.documentElement.offsetHeight;
				var xMenuLeftHeight = xMenuLeft.offsetHeight;
				xifrmPrincipal.style.height = ( xheight < xMenuLeftHeight ) ? xMenuLeftHeight + 'px' : xheight + 'px';
//				alert('NF ' + xheight);
            }
		}		
	}
	catch(e)
	{
//		alert(e.description);
	}
}

function useEnter(objEvent, objClick)
{
    if(navigator.appName == 'Microsoft Internet Explorer')
    {
        tecla = event.keyCode;
    }
    else
    {
        tecla = objEvent.which;
    }
	
	if(tecla == 13)
	{
		document.getElementById(objClick).click();
	}

}

function configuraValidatorSummary()
{
	travaTela();
	var xParent = window.parent;
	var divVal = document.getElementById('valSummary');

	if(xParent)
	{
		posTop = window.parent.document.body.scrollTop + 200;
	}
	else
	{
		posTop = document.body.scrollTop + 200;
	}
	
	divVal.style.top = posTop.toString() + 'px';
	
	setTimeout("adicionaBtFechar();", 200);
	
	/*divVal.style.height = divVal.clientHeight + 135;*/
	
	return false;
}

function adicionaBtFechar()
{
	var divVal = document.getElementById('valSummary');
	var btnFechar = "<div align='center'><input type='button' style='width:60px;height:25px;' class='botaoForm' value='Ok' onclick='fecharValidator();'/><br/><br/></div>";
	var contAnterior = divVal.innerHTML;
	divVal.innerHTML = contAnterior + btnFechar;
}

function fecharValidator()
{
	var divVal = document.getElementById('valSummary');
	/*divVal.style.height = divVal.clientHeight - 135;*/
	divVal.style.display = "none";
	destravaTela();

}

function BlockKeybord()
{
    if((event.keyCode < 48) || (event.keyCode > 57))
    {
    event.returnValue = false;
    }
}

function troca(str,strsai,strentra)
{
    while(str.indexOf(strsai)>-1)
    {
    str = str.replace(strsai,strentra);
    }
    return str;
}

function FormataMoeda(campo,tammax,teclapres,caracter)
{
    if(teclapres == null || teclapres == "undefined")
    {
    var tecla = -1;
    }
    else
    {
    var tecla = teclapres.keyCode;
    }

    if(caracter == null || caracter == "undefined")
    {
    caracter = ".";
    }

    vr = campo.value;
    if(caracter != "")
    {
    vr = troca(vr,caracter,"");
    }
    vr = troca(vr,"/","");
    vr = troca(vr,",","");
    vr = troca(vr,".","");

    tam = vr.length;
    if(tecla > 0)
    {
    if(tam < tammax && tecla != 8)
    {
    tam = vr.length + 1;
    }

    if(tecla == 8)
    {
    tam = tam - 1;
    }
    }
    if(tecla == -1 || tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)
    {
    if(tam <= 2)
    { 
    campo.value = vr;
    }
    if((tam > 2) && (tam <= 5))
    {
    campo.value = vr.substr(0, tam - 2) + ',' + vr.substr(tam - 2, tam);
    }
    if((tam >= 6) && (tam <= 8))
    {
    campo.value = vr.substr(0, tam - 5) + caracter + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam);
    }
    if((tam >= 9) && (tam <= 11))
    {
    campo.value = vr.substr(0, tam - 8) + caracter + vr.substr(tam - 8, 3) + caracter + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam);
    }
    if((tam >= 12) && (tam <= 14))
    {
    campo.value = vr.substr(0, tam - 11) + caracter + vr.substr(tam - 11, 3) + caracter + vr.substr(tam - 8, 3) + caracter + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam);
    }
    if((tam >= 15) && (tam <= 17))
    {
    campo.value = vr.substr(0, tam - 14) + caracter + vr.substr(tam - 14, 3) + caracter + vr.substr(tam - 11, 3) + caracter + vr.substr(tam - 8, 3) + caracter + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam);
    }
    }
}

function maskKeyPress(objEvent) 
{
    var iKeyCode; 
    iKeyCode = objEvent.keyCode; 
    if(iKeyCode>=48 && iKeyCode<=57) return true;
    return false;
}

function autoFormatarData(obj)
{
	var totalNum = obj.value.length;
	if(totalNum == 2 || totalNum == 5)
	{
		obj.value = obj.value + "/";
	}
}
/*Validações Flash*/
function getFlashMovieObject(movieName)	{
	if (window.document[movieName]) 
	{
	  return window.document[movieName];
	}
	if (navigator.appName.indexOf("Microsoft Internet")==-1)
	{
	if (document.embeds && document.embeds[movieName])
	  return document.embeds[movieName]; 
	}
	else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
	{
	return document.getElementById(movieName);
	}
}

function mostrarMsgSplash(pstrTipo, pstrMsg) {

	var xdivMsgSplash = document.getElementById('divMsgSplash')
	var xarquivoFlash
	
	if (xdivMsgSplash) {
		return
	}

 	if (pstrTipo=='salvo') {
		xarquivoFlash = '_msg_confirm.swf'
	}

 	if (pstrTipo=='erro') {
		xarquivoFlash = '_msg_erro.swf'
	}

    if (pstrTipo=='atencao') {
		xarquivoFlash = '_msg_atencao.swf'
	}
    
    /*xarquivoFlash = 'sample.swf'*/
    
	xdivMsgSplash = document.createElement('DIV')
	xdivMsgSplash.id = 'divMsgSplash'
	xdivMsgSplash.style.position = 'absolute'

	xhtml = ''
    xhtml = xhtml + '<object id="objMsgSplash" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="343" height="145">'
    xhtml = xhtml + '<param name="movie" value="/notafiscaleletronica/img/' + xarquivoFlash + '" />'
    xhtml = xhtml + '<param name="quality" value="high" />'
    xhtml = xhtml + '<param name="menu" value="false" />'
    xhtml = xhtml + '<embed src="/notafiscaleletronica/img/' + xarquivoFlash + '" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" swliveconnect="true" name="objMsgSplash" width="343" height="145"></embed>'
    xhtml = xhtml + '</object>	'
	xdivMsgSplash.innerHTML = xhtml
	
	document.body.appendChild(xdivMsgSplash)
	xdivMsgSplash.style.top = (document.body.offsetHeight/2) - (xdivMsgSplash.offsetHeight/2) - 80 + 'px'
	xdivMsgSplash.style.left = (document.documentElement.clientWidth/2) - (xdivMsgSplash.offsetWidth/2) + 'px'

	if(window.objMsgSplash) window.document["objMsgSplash"].SetVariable("myText", pstrMsg);
	if(document.objMsgSplash) document.objMsgSplash.SetVariable("myText", pstrMsg);

	/*if (pstrMsg) {
		if (pstrMsg!='') {
			xobjTmp = getFlashMovieObject('objMsgSplash')
			if (xobjTmp) {
				window.setTimeout("objMsgSplash.SetVariable('mensagem',  '" + pstrMsg + "')", 1000)
			}
		}
	}*/
}

function fecharMsg() {
	
	var xdivMsgSplash = document.getElementById('divMsgSplash')
	
	if (xdivMsgSplash) {
		document.body.removeChild(xdivMsgSplash)
		destravaTela()
	}
}

function showAlert(mensagem, redirect)
{
	if(document.getElementById('divAlert')){return false};
	//var xdivAlert = document.createElement('DIV');
	var xmostraAlert = document.getElementById('mostraAlert');
	var xmensagemAlert;

	var xTravaTela = document.getElementById('divTravaTela');
	if(!(xTravaTela)) { travaTela() };

	var xParent = window.parent.ifrmPrincipal;

	if(xParent)
	{
		divHeight = window.parent.document.body.scrollTop + 120 + "px";
	}
	else
	{
		divHeight = document.body.scrollTop + 200 + "px";
	}
	
	//xdivAlert.style.
	
    xmensagemAlert = 	"<div id=divAlert style='top = " + divHeight + "; position = absolute; left = 50%; marginLeft = -150px; zIndex = 115;'>"
	xmensagemAlert += 	"<table width='335' height='108' border='0' cellpadding='0' cellspacing='0'>";
	xmensagemAlert += 	"<tr>";
	xmensagemAlert += 	"<td width='11' height='12'><img src='img/box_top_left.gif' width='11' height='12' /></td>";
	xmensagemAlert += 	"<td background='img/box_top.gif'></td>";
	xmensagemAlert += 	"<td width='11'><img src='img/box_top_right.gif' width='11' height='12' /></td>";
	xmensagemAlert += 	"</tr>";
	xmensagemAlert += 	"<tr>";
	xmensagemAlert += 	"<td background='img/box_left.gif'>&nbsp;</td>";
	xmensagemAlert += 	"<td bgColor='#FFFFFF'>";
	xmensagemAlert += 	"<table width='100%' border='0' cellspacing='0' cellpadding='0'>";
	xmensagemAlert += 	"<tr>";
	xmensagemAlert += 	"<td colspan='2'><table width='90%' border='0' cellspacing='0' cellpadding='0'>";
	xmensagemAlert += 	"<tr>";
	xmensagemAlert += 	"<td width='50'><img src='img/ico_alert.gif' width='45' height='45' /></td>";
	xmensagemAlert += 	"<td align='center'>" + mensagem + "</td>";
	xmensagemAlert += 	"</tr>";
	xmensagemAlert += 	"</table></td>";
	xmensagemAlert += 	"</tr>";
	xmensagemAlert += 	"<tr>";
	xmensagemAlert += 	"<td width='53%' align='center' style='padding:4px 0px 0px 6px;'>";

	//AC O DO BOTO OK
	if(redirect)
	{
		xmensagemAlert += 	"<img src='img/alert_bt_ok.gif' style='cursor:pointer;' id='closeAlert' onClick='document.location.href = \"" + redirect + "\";' width='103' height='32' />";
	}
	else
	{
		xmensagemAlert += 	"<img src='img/alert_bt_ok.gif' style='cursor:pointer;' id='closeAlert' onClick='ocultarAlert();' width='103' height='32' />";
	}

	xmensagemAlert += 	"</td>";
	xmensagemAlert += 	"</tr>";
	xmensagemAlert += 	"</table></td>";
	xmensagemAlert += 	"<td background='img/box_right.gif'>&nbsp;</td>";
	xmensagemAlert += 	"</tr>";
	xmensagemAlert += 	"<tr>";
	xmensagemAlert += 	"<td height='12'><img src='img/box_bottom_left.gif' width='11' height='12' /></td>";
	xmensagemAlert += 	"<td background='img/box_bottom.gif'>&nbsp;</td>";
	xmensagemAlert += 	"<td><img src='img/box_bottom_right.gif' width='11' height='12' /></td>";
	xmensagemAlert += 	"</tr>";
	xmensagemAlert += 	"</table>";

	xmensagemAlert += 	"</div>";

    

    try {
	    //var xdivAlert = document.createElement("<div id=divAlert style='top = 120px; position = absolute; left = 50%; marginLeft = -150px; zIndex = 115;'><table width='335' height='108' border='0' cellpadding='0' cellspacing='0'><tr><td width='11' height='12'><img src='img/box_top_left.gif' width='11' height='12' /></td><td background='img/box_top.gif'></td><td width='11'><img src='img/box_top_right.gif' width='11' height='12' /></td></tr><tr><td background='img/box_left.gif'>&nbsp;</td><td bgColor='#FFFFFF'><table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td colspan='2'><table width='90%' border='0' cellspacing='0' cellpadding='0'><tr><td width='50'><img src='img/ico_alert.gif' width='45' height='45' /></td><td align='center'>Contribuinte Inválido!</td></tr></table></td></tr><tr><td width='53%' align='center' style='padding:4px 0px 0px 6px;'><img src='img/alert_bt_ok.gif' style='cursor:pointer;' id='closeAlert' onClick='ocultarAlert();' width='103' height='32' /></td></tr></table></td><td background='img/box_right.gif'>&nbsp;</td></tr><tr><td height='12'><img src='img/box_bottom_left.gif' width='11' height='12' /></td><td background='img/box_bottom.gif'>&nbsp;</td><td><img src='img/box_bottom_right.gif' width='11' height='12' /></td></tr></table></div>");
	    var xdivAlert = document.createElement ("<input type='radio' name='primeiro' value='1'>")
    } catch(e) {
        alert(e);
    }


	document.body.appendChild(xdivAlert);
	document.getElementById('closeAlert').focus();
	
}

function ocultarAlert()
{
	var xDiv = document.getElementById('divAlert');
	document.body.removeChild(xDiv);

	var xTravaTela = document.getElementById('divTravaTela');
	if(xTravaTela) { destravaTela() };
}

function validaCamposConsulta()
{	
	var chkSelPeriodo = document.getElementById('chkSelPeriodo')
    var chkNumEspecifica = document.getElementById('chkNumEspecifica')
    var chkSelTomador = document.getElementById('chkSelTomador')
    var chkNumCTS = document.getElementById('chkNumCTS')

    if(chkSelPeriodo.checked==true)
    {
        var txtIniPeriodo = document.getElementById('txtIniPeriodo')

        if(Verifica_Data(txtIniPeriodo,1,1)!=true)
        {
            travaTela()
            showAlert('Início de Período Inválido');
            //mostrarMsgSplash('atencao','Início de Período Inválido')

            return false
        }
        else
        {
            var txtFimPeriodo = document.getElementById('txtFimPeriodo')

            if(Verifica_Data(txtFimPeriodo,1,1)!=true)
            {

                travaTela()
                showAlert('Término de Período Inválido');
                //mostrarMsgSplash('atencao','Término de Período Inválido')

                return false
            }
            else
            {
                if(VerificaPeriodoDt(txtIniPeriodo,txtFimPeriodo)!=true)
                {
                    travaTela()
                    showAlert('Período Inválido');
                    //mostrarMsgSplash('atencao','Período Inválido')

                    return false
                }
            }
        }
    }

    if(chkNumEspecifica.checked==true)
    {
        var txtIniNum = document.getElementById("txtIniNum").value
        var txtFimNum = document.getElementById('txtFimNum').value

        if(Trim(txtIniNum)=='' || Trim(txtFimNum)=='')
        {
            travaTela()
            showAlert('Número de Notas Inválidas');
            //mostrarMsgSplash('atencao','Número de Notas Inválidas')
            
            return false
        }
        else
        {
            if(txtFimNum<txtIniNum)
            {
                travaTela()
                showAlert('Notas Inválidas');
                //mostrarMsgSplash('atencao','Notas Inválidas')

                return false
            }
        }

    }

    if(chkSelTomador.checked==true)
    {
        var txtIdPessoa = document.getElementById("txtIdPessoa").value

        if(txtIdPessoa=='')
        {
            travaTela()
            showAlert('Tomador deve ser Selecionado');
            //mostrarMsgSplash('atencao','Tomador deve ser Selecionado')

            return false
        }
    }

    if(chkNumCTS.checked==true)
    {
        var txtIniNumCTS = document.getElementById("txtIniNumCTS").value
        var txtFimNumCTS = document.getElementById('txtFimNumCTS').value

        if(Trim(txtIniNumCTS)=='' || Trim(txtFimNumCTS)=='')
        {
            travaTela()
            showAlert('Número de RPS Inválido');
            //mostrarMsgSplash('atencao','Número de RPS Inválido')

            return false
        }
        else
        {
            if(txtFimNumCTS<txtIniNumCTS)
            {
                travaTela()
                showAlert('RPS Inválido');
                //mostrarMsgSplash('atencao','RPS Inválido')

                return false
            }
        }

    }

    return true
}

function validaCamposConsulta()
{
   showAlert('RPS Inválido');
}

function checkMail(mail){

    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);

    if(typeof(mail) == "string"){
        if(er.test(mail)){ return true; }
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){ 
                    return true; 
                }
    }else{
        return false;
        }
}


function alertaComRedirect(strMensagem, strUrlDestino) {

    alert(strMensagem)

    window.location = strUrlDestino

}

function novaJanelaRedirect(url_boleto, strUrlDestino) {

    window.open(url_boleto, 'boleto','top=0,left=0,toolbar=1,location=0,diretories=0,resizable=0,status=0,menubar=1,scrollbars=1,width=680, height=400');

    window.location = strUrlDestino

}

function limpaCampo(objCampo) {

    objCampo.value = ""

}

function LimpaCampoDefault(objCampo) {

        if (objCampo.value == objCampo.defaultValue)
        objCampo.value="";

        }
        
function LimpaConteudoCampo(objCampo) {
        
        objCampo.value="";

        }
        
        
function RetornaValorDefault(objCampo) 
{

        if (objCampo.value == "")
        objCampo.value=objCampo.defaultValue;


}        
        
function calculaValorDeducaoTotal()
{
	var xgrid = document.getElementById('gdvDeducoes');
	var xinputs = xgrid.getElementsByTagName('INPUT');
	var lblResultado = document.getElementById('gdvDeducoes_ctl07_lblValorTotalDeducao');
	var xtotal = 0.00;	
	
	for(i=0;i<xinputs.length;i++)
	{
	      var txtDeducao = parseFloat(retornavalor(xinputs[i].value));
          if ( isNaN(txtDeducao) == true )
            txtDeducao = 0;	      		    
		    xtotal +=txtDeducao;
	}	
	
	var innerSoma = formataValor(xtotal,2);
	document.getElementById("gdvDeducoes_ctl07_lblValorTotalDeducao").innerText = innerSoma;  
	lblResultado.innerHTML = "R$ " + innerSoma;	
	
}

function calculaValorDeducaoTotalAnexo()
{
	var xgrid = document.getElementById('gdvDeducoes');
	var xinputs = xgrid.getElementsByTagName('INPUT');
	var lblResultado = document.getElementById('lblTotalDeducaoTribFederal');	
	var txtCredtoRemTribFederal = document.getElementById('txtCredtoRemTribFederal');
	var lblReceitasServico = document.getElementById('lblReceitasServico').innerHTML;
	var lblResultadoSaldoTF = document.getElementById("lblSaldoTribFederal");
	
	var xtotal = 0.00;
	var xsoma =  0.00;
	var xlimitededucao = 0.00;
	var xvalortransferir = 0.00;
	
	for(i=0;i<xinputs.length;i++)
	{
	      
	      var txtDeducao = parseFloat(retornavalor(xinputs[i].value));
          if ( isNaN(txtDeducao) == true )
            txtDeducao = 0;	      		    
		    xtotal +=txtDeducao;
	}	
	
	var vlrCredtoRemTribFederal = parseFloat(retornavalor(txtCredtoRemTribFederal.value));
	var vlrTotalReceita = parseFloat(retornavalor(lblReceitasServico));	
		
	var innerSoma = formataValor(xtotal,2);
	document.getElementById("lblTotalDeducaoTribFederal").innerText = innerSoma;  
	lblResultado.innerHTML = "R$ " + innerSoma;
	
	xlimitededucao = vlrTotalReceita*0.5;
	xsoma = xtotal + vlrCredtoRemTribFederal;
	
    if ( xsoma > xlimitededucao )
        xvalortransferir   = xsoma - xlimitededucao;
        var innerSaldoTransferir =  formataValor(xvalortransferir,2); 
        document.getElementById("lblSaldoTribFederal").innerText = innerSaldoTransferir;
        lblResultadoSaldoTF.innerHTML = "R$ " + innerSaldoTransferir;	
		
}

function replaceAll(string, de, para)
{
    var pos = string.indexOf(de);
    while (pos > -1){
		string = string.replace(de, para);
		pos = string.indexOf(de);
	}
    return (string);
}

function retornavalor(string)
{
    string = string.replace('R$','');
    string = replaceAll(string,'.','');
    string = string.replace(',','.');
        
    return (string);
} 

function formataValor(valor, decimais){ 
 var vlr = parseFloat(valor).toFixed(decimais).toString();
 var pos = vlr.indexOf('.');
 var vlrInt = vlr;
 
 if(pos > 0){vlrInt = vlrInt.substring(0, pos);}
 
 var vlrF = '';
 var pt='';
 
 for(i=vlrInt.length; i>0; i=i-3){
  vlrF = vlrInt.substring(i-3, i) + pt + vlrF ;
  pt='.'
 } 
 
 if(pos > 0){vlrF = vlrF + ',' + vlr.substring(pos + 1, vlr.length)}
 return vlrF;    
}

function CalculoDeducao185() 
{	
	var txtValorDeducaoLei185 = document.getElementById('txtDeducaoLei185');
	var txtCredtoRemanescente = document.getElementById('txtCredtoRemaLei185');
	var lblReceitasServico = document.getElementById('lblReceitaServLei185').innerHTML;
	var lblResultadoSaldo185 = document.getElementById("lblSaldoLei185");
	
	var xtotal = 0.00;
	var xsoma =  0.00;
	var xvalortransferir = 0.00;
	
	var vlrCredtoRemanescente = parseFloat(txtCredtoRemanescente.value.replace('R$','').replace('.','').replace(',','.'));
	
	var vlrTotalReceita = parseFloat(lblReceitasServico.replace('R$','').replace('.','').replace(',','.'));
	
	var txtDeducao185 = parseFloat(txtValorDeducaoLei185.value.replace('R$','').replace('.','').replace(',','.'));
	if ( isNaN(txtDeducao185) == true )
            txtDeducao185 = 0;
            
    xtotal +=txtDeducao185;		
	
	xsoma = xtotal + vlrCredtoRemanescente;
	
    if ( xsoma > vlrTotalReceita )
        xvalortransferir   = xsoma - vlrTotalReceita;
        var innerSaldoTransferir = xvalortransferir.toFixed(2).toString().replace(".", ",");
        document.getElementById("lblSaldoLei185").innerText = innerSaldoTransferir;
        lblResultadoSaldo185.innerHTML = "R$ " + innerSaldoTransferir;
}
        

function ExibeTalonario(strListaNF)
{
    window.open('wfExibeTalonario.aspx?strListaNF=' + strListaNF,'_blank');
}

function validaEmail(idcampo){
    
    var campo = document.getElementById(idcampo)
    
    if(!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(campo))) {

		campo.focus();
		return false;

	}

    return true

}

function popUpsBlocked(msg) {

     var mine = window.open('','','width=1,height=1,left=5000,top=5000,scrollbars=no');
     var bloqueio;

     if (mine)
        bloqueio = false;
     else
        bloqueio = true;

	try {
       mine.close();
	} catch (e) {}
    
     if (msg && bloqueio) {
		alert('Atenção, foi detectado que seu navegador está com bloquador de pop-up ativo. Para o correto funcionamento do site desative seu bloquador de pop-up ou configure-o para permitir pop-up do site www.barueri.sp.gov.br');
     }

     return bloqueio

}

function abreRelatorio()
 {
    window.open('relat/verRelatorio.aspx','blank','width=' + (screen.width - 40) +', height=' + (screen.height - 90) +', top=10, left=10, status=yes, scrollbars=yes');
    return false;
 }
 
   function noCopyMouse(e) {
        var isRight = (e.button) ? (e.button == 2) : (e.which == 3);
        
        if(isRight) {
            alert('Para este tipo de campo não é permitido colar o conteúdo!');
            return false;
        }
        return true;
    }

    function noCopyKey(e) {
        var forbiddenKeys = new Array('c','x','v');
        var keyCode = (e.keyCode) ? e.keyCode : e.which;
        var isCtrl;

        if(window.event)
            isCtrl = e.ctrlKey
        else
            isCtrl = (window.Event) ? ((e.modifiers & Event.CTRL_MASK) == Event.CTRL_MASK) : false;
    
        if(isCtrl) {
            for(i = 0; i < forbiddenKeys.length; i++) {
                if(forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
                    alert('Para este tipo de campo não é permitido colar o conteúdo!');
                    return false;
                }
            }
        }
        return true;
    }


function ConfirmaCancelNF() { 

    return confirm("Nota Fiscal vinculada a uma guia. Confirma o cancelamento?");
  
}


function ConfirmaExcluirEmailFoneComercial() { 

    return confirm("Confirma a exclusão das informaçõess de Telefone e Email Comerciais \n do Cadastro do Contribuinte?");
  
}

function AtribuiZeroBaseCalculo(){

    var Vlr = document.getElementById('txtBaseCalculo').value;
    
    if(Vlr == '')
    {
        document.getElementById('txtBaseCalculo').value = '0,00';
    }

}


function validaTomadorConsultaNFe()
{
	var objCPFCNPJTomador = document.getElementById('txtDocumento');
			
  	if(objCPFCNPJTomador.value == "")
    {
	   alert('CPF/CNPJ inválido !');
       return false;
    }      
    
    if(isCpfCnpj(objCPFCNPJTomador.value,false) == false )
    {
        alert('CPF/CNPJ inválido (' + objCPFCNPJTomador.value + ') !');
        return false;   
    }	
}
