// Funcoes DWR
dwr.engine.setErrorHandler(exibeErro);
dwr.util.useLoadingMessage('Processando...');

//Funcao chamada em todo carregamento de pagina
function carregaPaginas(){
    $j('.bt').click(function(){
        barrarMultClick($j(this));
    });
    
    $j('.botao').click(function(){
        barrarMultClick($j(this));
    });
}

function barrarMultClick(obj){
    obj.css('visibility','hidden');
    obj.oneTime(10000, function(){
        $j(this).css('visibility','visible');    
    });

    //obj.fadeOut(1).delay(5000).fadeIn(1);
}

function exibeErro(msg){
	alert(msg);
}

function useLoadingMessage(){
    dwr.engine.setAsync(true);
    
	dwr.engine.setPreHook(function(){
		var winHeight = 0; //Altura da janela do browser
		var divTop = 0;
		var tagBody = document.getElementsByTagName('body')[0];
		var divLoading = document.getElementById('divDwrLoading');
		var divAguarde = document.getElementById('divDwrTextoAguarde');
		
		if(!divLoading){
			divLoading = document.createElement('div');
			divLoading.id = 'divDwrLoading';
			
			divAguarde = document.createElement('div');
			divAguarde.id = 'divDwrTextoAguarde';
			
			tagBody.appendChild(divLoading);
			divLoading.appendChild(divAguarde);
		}
		
		if(navigator.appName.indexOf('Microsoft') > -1){
			winHeight = document.getElementsByTagName('body')[0].offsetHeight-4;
			divTop = document.body.scrollTop;
			esconderComboxes(true);
			divLoading.style.filter = 'alpha(opacity=60)';
		}
		else{
			winHeight = window.innerHeight;
			divTop = window.pageYOffset;
			divLoading.style.opacity = '0.6';
		}
		
		divLoading.id = 'divDwrLoading';
		divLoading.style.position = 'absolute';
		divLoading.style.display = 'block';
		divLoading.style.visibility = 'visible';
		divLoading.style.left = '0px';
		divLoading.style.top = divTop+'px';
		divLoading.style.width = '100%';
		divLoading.style.height = winHeight+'px';
		divLoading.style.backgroundColor = '#FFF';
		
		divAguarde.style.position = 'absolute';
		divAguarde.style.top = (winHeight/2)+'px';
		divAguarde.style.textAlign = 'center';
		divAguarde.style.width = '100%';
		divAguarde.style.fontWeight = 'bold';
		divAguarde.innerHTML = 'Aguarde...';
	});
	
	dwr.engine.setPostHook(function(){
		var divLoading = document.getElementById('divDwrLoading');
		document.getElementById('divDwrLoading').style.display = 'none';
		
		if(navigator.appName.indexOf('Microsoft') > -1){
			esconderComboxes(false);
		}
	});
}

if(window.addEventListener){
    window.addEventListener('load', useLoadingMessage, false);
}
else if(window.attachEvent){
    window.attachEvent('onload', useLoadingMessage);
}
else{
    window.onload = useLoadingMessage;
}

//Esconde (true) ou exibe (false) todos os comboxes da tela
function esconderComboxes(esconde){
	var comboBoxes = document.getElementsByTagName('select');
	
	for(i = 0; i < comboBoxes.length; i++){
		if(esconde){
			comboBoxes[i].style.visibility = 'hidden';
		}
		else{
			comboBoxes[i].style.visibility = 'visible';
		}
	}
}

/**
 * Esta funcao retorna uma caixa de confirmacao para o usuario.
 * Caso ele confirme a acao sera retornado true, senao false.
 */
function confirmarAcao(msg) {
    if (confirm(msg)) {
        return true;
    }
    return false;
}

function habilitaRG(valor) {
    var linhaRG = document.getElementById('linhaRG');
    var linhaOE = document.getElementById('linhaOE');
    
	if(valor == "CPJ") {
		linhaRG.style.display = 'none';
		linhaOE.style.display = 'none';
	} else {
		linhaRG.style.display = 'block';
		linhaOE.style.display = 'block';
	}
}

function redirecionaBanco() {
    var x = document.getElementById('combo');       
        
    if (x.options[x.options.selectedIndex].id == "" || x.options[x.options.selectedIndex].id == "undefined") {
        
        window.location = x.value;
    }
    else {  
      return false;
      open(x.value,'homebanking','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=535,height=200,left=0,top=0');               
    }
    
    return false;
}

function redirecionarPagina (url) {
	document.location=url;
}


//Submete formul?rio
/*function abreendereco(){
    document.forms[0].action='/AgenciaWeb/solicitarSegundaVia/localizarEndereco.do';
    document.forms[0].submit();
}*/

function submeterFormulario (url, form) {
	form.action=url;
	form.submit();	
}

function submitForm(numero){
	document.forms[numero].submit();
}

function enviarForm(idForm){
	document.getElementById(idForm).submit();
}

function resetForm(numero){
	limparFormulario(document.forms[numero]);
}


function limparFormulario(form){
	if(form.elements){
		var elementos = form.elements;
		for (idx = 0; idx < elementos.length; idx++){
	
			if((elementos[idx].type == "text" || elementos[idx].type == "select-one") 
				&& !elementos[idx].readOnly){
			   elementos[idx].value = "";
			}
		}
	}
}

function limparTodoForm(id){
    var form = document.forms[id];
	if(form.elements){
		var elementos = form.elements;
		for (idx = 0; idx < elementos.length; idx++){
			
			if(elementos[idx].type == "text" ||
			   elementos[idx].type == "select-one" ||
			   elementos[idx].type == "textarea" ){
				   elementos[idx].value = "";
				   elementos[idx].className = "";
				   
				   if(elementos[idx].readOnly){
				        elementos[idx].readOnly = false;
				   }
			}
		}
	}
}

/** Autoleitura */
// Update via click na figura
function updigitoclick(idElem){
    var numId = idElem.id.substring(11); 
    var vlr = document.getElementById('NM_RELOGIO' + numId).value;
    
    vlr++;
    
    if (vlr >= 10 ){
    	vlr = 0;
    }
      
    updigito(numId, vlr);
}

// update via seta
function updigitoseta(idElem){

    var numId = idElem.id.substring(10); 
    var keyId = (window.event) ? event.keyCode : e.keyCode;
    var vlr = idElem.value;
    
    //Incrementa
    if(keyId == 38) {
    	vlr++;
    // Decrementa
    } else if(keyId == 40) {
    	vlr--;
    } else {
    	return;
    }
    
    if (vlr >= 10 ) {
    	vlr = 0;
    } else if(vlr < 0){
    	vlr = 9;
    }

	updigito(numId, vlr);
}

function updigito(id, num){
	if (num == null || num == ''){
	    num = 0;
	} 
	document.getElementById('DIG_RELOGIO'+id).src = pathdir + num + '.png';
	document.getElementById('NM_RELOGIO'+id).value = num;
}


function relogio(id, rel, num, med){
	document.getElementById('IMG_RELOGIO'+id).src=pathdir +'relogio_' + rel + num + '.jpg';
	document.getElementById('NM_RELOGIO'+id).value=med;
}

function upimg(idElem, rel){
	var numId = idElem.id.substring(10); 
	var imgRelogio = document.getElementById('IMG_RELOGIO' + numId);
	var imgDigito  = document.getElementById('DIG_RELOGIO'+numId);
	
	if(imgRelogio != null){
		uprelogio(numId, rel);
	}
	
	if(imgDigito != null){
		updigito(numId, idElem.value);
	}
		
	
}

function uprelogio(id, rel){
	if(document.getElementById('NM_RELOGIO'+id).value=="" || !parseInt(document.getElementById('NM_RELOGIO'+id).value)){
    	document.getElementById('IMG_RELOGIO'+id).src=pathdir + 'relogio_' +rel+'00'+'.jpg';
    	document.getElementById('NM_RELOGIO'+id).value=0;
		return false;
	}
	var num = '0'+document.getElementById('NM_RELOGIO'+id).value;
	var med = document.getElementById('NM_RELOGIO'+id).value;
	relogio(id, rel, num, med);
}

/* FIM auto leitura*/

function desabilitaCampo() 
	{
		var the_form = window.document.forms[0];
		for (i = 0; i<the_form.tpDocumento.length; i++) 
		{
     		if (the_form.tpDocumento[i].checked)
     		{
      			valor = the_form.tpDocumento[i].value;
  				if (valor == "CPF") 
   				{
                	document.forms[0].numeroDocumentoCNPJ.value="";
                	document.forms[0].numeroDocumentoCPF.style.display = '';
  					document.forms[0].numeroDocumentoCNPJ.style.display = 'none';
  					
    			} else 
    			{
    			    document.forms[0].numeroDocumentoCPF.value="";
                	document.forms[0].numeroDocumentoCPF.style.display = 'none';
  					document.forms[0].numeroDocumentoCNPJ.style.display = '';
  					
          		}
     		} 
     	}	
	}
	
	// colocar no evento onKeyUp passando o objeto como parametro
function formataData(val) {
	var pass = val.value;
	var expr = /[0123456789]/;
			
	for(i=0; i<pass.length; i++){
		// charAt -> retorna o caractere posicionado no ?ndice especificado
		var lchar = val.value.charAt(i);
		var nchar = val.value.charAt(i+1);
	
		if(i==0){
			// search -> retorna um valor inteiro, indicando a posi??o do inicio da primeira
			// ocorr?ncia de expReg dentro de instStr. Se nenhuma ocorrencia for encontrada o m?todo retornara -1
			// instStr.search(expReg);
			if ((lchar.search(expr) != 0) || (lchar>3)) {
				val.value = "";
			}
			   
		} else if(i == 1) {
				   
			if(lchar.search(expr) != 0){
				// substring(indice1,indice2)
				// indice1, indice2 -> ser? usado para delimitar a string
				var tst1 = val.value.substring(0,(i));
				val.value = tst1;				
				continue;			
			}
					   
			if ((nchar != '/') && (nchar != '')) {
				var tst1 = val.value.substring(0, (i)+1);
					
				if(nchar.search(expr) != 0) 
					var tst2 = val.value.substring(i+2, pass.length);
				else
					var tst2 = val.value.substring(i+1, pass.length);
		
				val.value = tst1 + '/' + tst2;
			}
	
		} else if(i==4) {
				
			if(lchar.search(expr) != 0){
				var tst1 = val.value.substring(0, (i));
				val.value = tst1;
				continue;
			}
			
			if	((nchar != '/') && (nchar != '')){
				var tst1 = val.value.substring(0, (i)+1);
	
				if(nchar.search(expr) != 0) 
					var tst2 = val.value.substring(i+2, pass.length);
				else
					var tst2 = val.value.substring(i+1, pass.length);
		
				val.value = tst1 + '/' + tst2;
			}
		}
			
		if(i>=6) {
			if(lchar.search(expr) != 0) {
				var tst1 = val.value.substring(0, (i));
				val.value = tst1;			
			}
		}
	}
		
	if(pass.length>10)
		val.value = val.value.substring(0, 10);
	return true;
}


//Formata o objeto Date passado para o padrao especificado e
//retorna uma String
function formatarData(data, formato){
    var arrFrmt = formato.split('/');
    var valor = '';
    
    if(data){   
        for(itDta = 0; itDta < arrFrmt.length; itDta++){
            if(arrFrmt[itDta] == 'dd'){
                if(data.getDate() < 10){
                    valor += '0';
                }
                valor += data.getDate();
            }
            else if(arrFrmt[itDta] == 'mm'){
                // < 9 porque janeiro e mes 0 (zero)
                if(data.getMonth() < 9){
                    valor += '0';
                }
                valor += (data.getMonth() + 1);
            }
            else if(arrFrmt[itDta] == 'yy'){
                ano = ''+data.getYear();
                valor += ano.substr(ano.length -2, ano.length);
            }
            else if(arrFrmt[itDta] == 'yyyy'){
    
                valor += data.getFullYear();
            }
            
            if(itDta+1 < arrFrmt.length){
               valor += '/';
            }
        }
    }
    
    
    return valor;
}

function formatarNumero(numero,qtdeCasasDec){
    var valor = ''+numero;
    var inteiro, arrInt;
    var dec;
    if(numero != ''){
        if(valor.indexOf('.') > -1){
            inteiro = valor.substr(0,valor.indexOf('.'));
            dec = valor.substr(valor.indexOf('.')+1,valor.length);
            
            if(dec.length < qtdeCasasDec){
                for(iDecs = dec.length; iDecs < qtdeCasasDec; iDecs++){
                    dec += '0';
                }
            }
            else if(dec.length > qtdeCasasDec){
                dec = dec.substr(0,qtdeCasasDec);
            }
        }
        else{
            inteiro = valor;
            dec = '';
            for(iDecs = 0; iDecs < qtdeCasasDec; iDecs++){
                dec += '0';
            }
        }
        
        arrInt = inteiro.split('');
        inteiro = '';
        for(iInt = arrInt.length-1, casa = 1; iInt >= 0; iInt--, casa++){
            inteiro = arrInt[iInt] + inteiro;
            if(casa == 3 && iInt > 0){
                inteiro = '.' + inteiro;
            }
        }
        
        return inteiro+','+dec;
    }
    return '';
    
}


/* Auditoria */
function habilitaAuditoria(){
	var divmunicipio = document.getElementById("divmunicipio");
	var agente = document.getElementById("agente");
	var agente2 = document.getElementById("agente2");
	if(document.AuditarServicos.tipoRelatorio.value == "municipio") {
		divmunicipio.style.display='block';
		agente.style.display='none';
		agente2.style.display='none';
	}
	if(document.AuditarServicos.tipoRelatorio.value == "acesso"){
		divmunicipio.style.display='none';
		agente.style.display='none';
		agente2.style.display='none';
	}
	if(document.AuditarServicos.tipoRelatorio.value == "agente"){
		divmunicipio.style.display='none';
		agente.style.display='block';
		agente2.style.display='block';
			
	}
}
/* Auditoria */

/* Retorno o numero por extenso  */
function extenso(valor, blnmoeda){
	var intponto;
	var inteiro, decimal;
	var strmoedasingular, strmoedaplural;
	var retorno;

	if (isNaN(valor)){
		return false;
	}
				
	intponto = valor.indexOf('.');
		
	if (intponto < 0 ){
			inteiro = zeros(valor,15);
			decimal = zeros(0,15);
	} else 	{
	decimal = valor.substring(intponto + 1, valor.length)
		if (decimal.length == 1)
			decimal = decimal + '0';
			decimal = zeros(decimal,15);
			
			inteiro = zeros(valor.substring(0, intponto),15);
		}
		
		retorno = mil(inteiro,15,'trilh?o','trilh?es');
		
		if ((inteiro.substr(0,3) > 0) && (inteiro.substr(3,12) > 0))
		{
			if (inteiro.substr(3,10) == 0 || 
				(inteiro.substr(3,9) + inteiro.substr(13,2)) == 0 || 
				(inteiro.substr(3,4) + inteiro.substr(9,6)) == 0 || 
				(inteiro.substr(3,3) + inteiro.substr(7,8)) == 0 || 
				(inteiro.substr(3,6) + inteiro.substr(10,5)) == 0 || 
				(inteiro.substr(3,7) + inteiro.substr(12,3)) == 0 || 
				(inteiro.substr(3,1) + inteiro.substr(6,9)) == 0 || 
				inteiro.substr(4,11) == 0) 
				retorno = retorno + ' e ';
			else
				retorno = retorno + ', ';
		}
		
		retorno = retorno + mil(inteiro,12,'bilh?o','bilh?es');
		
		if (inteiro.substr(3,3) > 0 && inteiro.substr(6,9) > 0)
		{
			if (inteiro.substr(6,7) == 0 ||
				(inteiro.substr(6,6) + inteiro.substr(13,2)) == 0 ||
				(inteiro.substr(6,4) + inteiro.substr(12,3)) == 0 ||
				(inteiro.substr(6,3) + inteiro.substr(10,5)) == 0 ||
				(inteiro.substr(6,1) + inteiro.substr(9,6)) == 0 ||
				inteiro.substr(7,8) == 0)
				retorno = retorno + ' e ';
			else
				retorno = retorno + ', ';
		}
		
		retorno = retorno + mil(inteiro,9,'milh?o','milh?es');
		
		if (inteiro.substr(6,3) > 0 && inteiro.substr(9,6) > 0)
		{
			if (inteiro.substr(9,4) == 0 ||
				(inteiro.substr(9,3) + inteiro.substr(13,2)) == 0 ||
				(inteiro.substr(9,1) + inteiro.substr(12,3)) == 0 ||
				inteiro.substr(10,5) == 0)
				retorno = retorno + ' e ';
			else
				retorno = retorno + ', ';
		}
		
		retorno = retorno + mil(inteiro,6,'mil','mil');
		
		if (inteiro.substr(9,3) > 0 && inteiro.substr(12,3) > 0){
			if (inteiro.substr(13,2) == 0 ||
				inteiro.substr(12,2) == 0 ||
				inteiro.substr(12,1) == 0)
				retorno = retorno + ' e ';
			else
				retorno = retorno + ', ';
		}
		
		if (blnmoeda){
			strmoedasingular = 'real';
			strmoedaplural = 'reais';
		}
		else{
			strmoedasingular = '';
			strmoedaplural = '';
		}
		
		retorno = retorno + mil(inteiro,3,strmoedasingular,strmoedaplural);
		
		if (decimal > 0)	{
			if (inteiro > 0)
				retorno = retorno + ' e '
			 retorno = retorno + cem(decimal, 2, 'centavo', 'centavos');
		}
		
		return  retorno.toUpperCase();
	}
	
	function mil(numero,centena,unidadesingular,unidadeplural){
		var retorno;
	
		retorno = '';
		
		if (numero.substr(15 - centena,1) > 0){
			if (numero.substr(15 - centena,1) == 1)	{
				if (numero.substr(16 - centena,2) == 0)
					retorno = 'cem'
				else
					retorno = 'cento'
			}
			else{
				switch (numero.substr(15 - centena,1))
				{
					case '2':
						retorno = 'duzentos';
						break;
					case '3':
						retorno = 'trezentos';
						break;
					case '4':
						retorno = 'quatrocentos';
						break;
					case '5':
						retorno = 'quinhentos';
						break;
					case '6':
						retorno = 'seiscentos';
						break;
					case '7':
						retorno = 'setecentos';
						break;
					case '8':
						retorno = 'oitocentos';
						break;
					case '9':
						retorno = 'novecentos';
						break;				
				}
			}
			if (numero.substr(16 - centena,2) > 0)
				retorno = retorno + ' e ';
		}
				
		retorno = retorno + cem(numero, centena -1, unidadesingular, unidadeplural)
		
		return retorno;
	}
	
	function cem(numero, dezena, unidadesingular, unidadeplural)
	{
		var retorno;
		
		retorno = '';
		
		if (numero.substr(15 - dezena,1) > 1)
		{
			switch (numero.substr(15 - dezena,1))
			{
				case '2':
					retorno = 'vinte';
					break;
				case '3':
					retorno = 'trinta';
					break;
				case '4':
					retorno = 'quarenta';
					break;
				case '5':
					retorno = 'cinquenta';
					break;
				case '6':
					retorno = 'sessenta';
					break;
				case '7':
					retorno = 'setenta';
					break;
				case '8':
					retorno = 'oitenta';
					break;
				case '9':
					retorno = 'noventa';
					break;				
			}				
			if (numero.substr(16 - dezena,1) > 0){
				retorno = retorno + ' e ';
				switch (numero.substr(16 - dezena,1)){
					case '1':
						retorno = retorno + 'um';
						break;
					case '2':
						retorno = retorno + 'dois';
						break;
					case '3':
						retorno = retorno + 'tres';
						break;
					case '4':
						retorno = retorno + 'quatro';
						break;
					case '5':
						retorno = retorno + 'cinco';
						break;
					case '6':
						retorno = retorno + 'seis';
						break;
					case '7':
						retorno = retorno + 'sete';
						break;
					case '8':
						retorno = retorno + 'oito';
						break;
					case '9':
						retorno = retorno + 'nove';
						break;
				}
			}
		}
		else
		{
			switch (numero.substr(15 - dezena,2))
			{
				case '01':
					retorno = 'um';
					break;
				case '02':
					retorno = 'dois';
					break;
				case '03':
					retorno = 'tres';
					break;
				case '04':
					retorno = 'quatro';
					break;
				case '05':
					retorno = 'cinco';
					break;
				case '06':
					retorno = 'seis';
					break;
				case '07':
					retorno = 'sete';
					break;
				case '08':
					retorno = 'oito';
					break;
				case '09':
					retorno = 'nove';
					break;
				case '10':
					retorno = 'dez';
					break;
				case '11':
					retorno = 'onze';
					break;
				case '12':
					retorno = 'doze';
					break;
				case '13':
					retorno = 'treze';
					break;
				case '14':
					retorno = 'quatorze';
					break;
				case '15':
					retorno = 'quinze';
					break;
				case '16':
					retorno = 'dezesseis';
					break;
				case '17':
					retorno = 'dezesete';
					break;
				case '18':
					retorno = 'dezoito';
					break;
				case '19':
					retorno = 'dezenove';
					break;																																													
			}
		}
		if (dezena == 2)
		{
			if (numero > 0)
			{
				if (numero == 1)
				{
					retorno = retorno + ' ' + unidadesingular;
				}
				else
				{
					if (numero.substr(9,6) == 0 ||
						numero.substr(6,9) == 0 ||  
						numero.substr(3,12) == 0)
						retorno = retorno + ' de ' + unidadeplural;
					else
						retorno = retorno + ' ' + unidadeplural;
				}
			}
		}
		else
		{
			if (numero.substr(14 - dezena,3) > 0)
			{
				if (numero.substr(14 - dezena,3) == 1)
					retorno = retorno + ' ' + unidadesingular
				else
					retorno = retorno + ' ' + unidadeplural
			}
		}
		
		return retorno;
	}
	
	function maiusculo(textField){
		textField.value = textField.value.toUpperCase();
	}
	
	function zeros(valor, zeros)
	{
		var i, intqtde, strretorno
		
		intqtde = zeros - valor.length;
		strretorno = valor
		
		for (i=0; i < intqtde; i++)
		{
			strretorno = '0' + strretorno
		
		}
		return strretorno;
	}
		
/* Retorno o numero por extenso  */

/* Fun?ao para retirar espa?os em branco */
function trim(sString){
	while (sString.substring(0,1) == ' '){
		sString = sString.substring(1, sString.length);
	}
	
	while (sString.substring(sString.length-1, sString.length) == ' '){
		sString = sString.substring(0,sString.length-1);
	}
return sString;
}
/* Fun?ao para retirar espa?os em branco */



var tgs = new Array( 'div', 'p', 'td', 'span' );

//Specify spectrum of different font sizes:
var szs = new Array( 'xx-small','x-small','small','medium','large','x-large','xx-large' );
var startSz = 2;

function ts( trgt,inc ) {
if (!document.getElementById) return
var d = document,cEl = null,sz = startSz,i,j,cTags;
sz += inc;
if ( sz < 0 ) sz = 0;
if ( sz > 6 ) sz = 6;
startSz = sz;
if ( !( cEl = d.getElementById( trgt ) ) ) cEl = d.getElementsByTagName( trgt )[ 0 ];

cEl.style.fontSize = szs[ sz ];

for ( i = 0; i < tgs.length; i++ ) {
cTags = cEl.getElementsByTagName( tgs[ i ] );
for ( j = 0; j < cTags.length; j++ ) cTags[ j ].style.fontSize = szs[ sz ];
}
}


//Valida a adicao de cronograma
function adicionarCrono(formulario,action){
	
	var enviar = false;
	
	x = 0;
	enviarTP = false; //Indica se Ponta esta OK
	enviarFP = false; //Indica se Fora Ponta esta OK
	while(true){
		
		//Ponta/Todos
		arrInicio = document.getElementsByName('cronogramaList['+x+'].inicio');
		arrTermino = document.getElementsByName('cronogramaList['+x+'].termino');
		arrSeco = document.getElementsByName('cronogramaList['+x+'].kwPeriodoSeco');
		arrUmido = document.getElementsByName('cronogramaList['+x+'].kwPeriodoUmido');
		//Fora Ponta
		arrInicioFP = document.getElementsByName('cronogramaListFP['+x+'].inicio');
		arrTerminoFP = document.getElementsByName('cronogramaListFP['+x+'].termino');
		arrSecoFP = document.getElementsByName('cronogramaListFP['+x+'].kwPeriodoSeco');
		arrUmidoFP = document.getElementsByName('cronogramaListFP['+x+'].kwPeriodoUmido');
		
		if(!arrInicio[0] && !arrInicioFP[0]){
			break;
		}
		
		//Validando Ponta/Todos
		if(arrInicio[0]){
			inicio = arrInicio[0].value;
			termino = arrTermino[0].value;
			periSeco = arrSeco[0].value;
			periUmido = arrUmido[0].value;
			
			if(inicio != '' && termino != '' &&
				periSeco != '' && periUmido != '' &&
				!isNaN(periSeco) && !isNaN(periUmido)){
				
				compara = /[0-1]\d\/[1-2]\d{3}/;
				if(compara.exec(inicio) && compara.exec(termino)){
					enviarTP = true;
				}
				else{
					enviarTP = false;
				}
			}
			else{
				enviarTP = false;
			}
		}
		
		//Se existir, valida Fora Ponta
		if(arrInicioFP[0]){
			inicio = arrInicioFP[0].value;
			termino = arrTerminoFP[0].value;
			periSeco = arrSecoFP[0].value;
			periUmido = arrUmidoFP[0].value;
		
			if(inicio != '' && termino != '' &&
				periSeco != '' && periUmido != '' &&
				!isNaN(periSeco) && !isNaN(periUmido)){
				
				compara = /[0-1]\d\/[1-2]\d{3}/;
				if(compara.exec(inicio) && compara.exec(termino)){
					enviarFP = true;
				}
				else{
					enviarFP = false;
				}
			}
			else{
				enviarFP = false;
			}
		}
		x++;
	}
	
	formulario.action = action;
	formulario.submit();
}

function avisoMudancaTarifa(obj,tarInicial){
	if(obj.value != tarInicial){
		document.getElementById('avisoTarifa').innerHTML = 'Tarifa alterada!';
	}
	else{
		document.getElementById('avisoTarifa').innerHTML = '';
	}
}

// Ajusta o tamanho da janela
function setSize(width,height, janela) {
	if (janela.outerWidth) {
		janela.outerWidth = width;
		janela.outerHeight = height;
	}
	else if (janela.resizeTo) {
		janela.resizeTo(width,height);
	}
	else {
		alert("Not supported.");
	}
}


function redirecionarPaginaPai (url) {
	parent.window.location=url;
}

/*
* origem = campo de origem (geralmente this)
* destino = id do campo para onde vai o cursor
*/
function proximoCampo(origem, destino){
	var campoDestino = document.getElementById(destino);
 	if(origem.value.length >= origem.maxLength){
 		campoDestino.focus();
 	}
}

function foco(){
	if(document.forms.length > 0){
		var elementos = document.forms[0].elements;
		for (idx = 0; idx < elementos.length; idx++){
	
			if((elementos[idx].type == "text" || elementos[idx].type == "password") && !elementos[idx].readOnly){
			   elementos[idx].focus()
			   break;
			}
		}
	}
}
function abreJanPdfContrato(codCpu,numSeqOper,situacao,marcadagua){
	var novoIframe = document.getElementById('frmContrato');

	novoIframe.src='contratoPDF.do?codCpu='+codCpu+'&numSeqOper='+numSeqOper+'&situacao='+situacao;
	//var janela = window.open('contratoPDF.do?codCpu='+codCpu+'&numSeqOper='+numSeqOper+'&situacao='+situacao,'contratoPDF','width=350,height=250');
}

//Valida o campo retornando somente os numeros inseridos nele
function campoNumerico(objeto){
	var valor = objeto.value; 
	var len = valor.length;
	var novoCont = '';
	var caracter = '';
	var regexp = /[0-9]/;
	
	for(i = 0; i < len; i++){
		caracter = valor.substr(i, 1);
		if(regexp.test(caracter)){
			novoCont += caracter;
		}
	}
	
	if(objeto.value != novoCont){
		objeto.value = novoCont;
	}
}

function campoData(objeto, formato){
    campoNumerico(objeto);

    var valor = objeto.value 
    var caracter = '';
    var vlrFormat = '';
    var len = valor.length;
    
    var fmrt = formato.split('/');
    
    for(i = 0, x = 0, z = 0; i < len; i++, z++){
        if(z == fmrt[x].length){
           vlrFormat += '/';
           z = 0;
           x++;
        }
        vlrFormat += valor.substr(i, 1);
    }
    
    objeto.value = vlrFormat;
}

function exibirDica(e,texto){
	/*var objDica = document.getElementById('objDica');
	var curX = e.clientX+10;
	var curY = e.clientY+10;
	
	objDica.style.left = curX + 'px';
	objDica.style.top = curY + 'px';
	objDica.innerHTML = texto;
	objDica.style.visibility = 'visible';
	*/
	var x=0;
	var y=0;
	var m;
	var h;

    if(!e)
      var e = window.event;

    if(e.pageX || e.pageY){
       x = e.pageX;
       y = e.pageY;
    } else if(e.clientX || e.clientY){
       x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
       y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
    
    m = document.getElementById('objDica');

    if((y > 10) && (y < 450)){
       m.style.top = y - 4 + "px";
    } else {
       m.style.top = y + 4 + "px";
    }
    
    var messageHeigth = (texto.length / 20) * 10 + 25;

    if((e.clientY + messageHeigth) > 510){
       m.style.top = y - messageHeigth + "px";
    }
    if(x < 850){
       m.style.left = x + 20 + "px";
    } else {
       m.style.left = x - 170 + "px";
    }
    m.innerHTML = texto;
    //m.style.display="block";
    m.style.visibility = 'visible';
    m.style.zIndex = 203;
}

function ocultarDica(){
	var objDica = document.getElementById('objDica');
	objDica.style.visibility = 'hidden';
}

/* Funcao para retirar acentos */

function retirarAcentos(obj){
	tratarAcentos(obj, false)
}

function tratarAcentos(obj, email){
   palavra = String.fromCharCode(event.keyCode);
   if (obj.value != ''){
   	obj.value = obj.value.toUpperCase();
   }
  
  var caracteresInvalidos = 'àèìòùâêîôûäëïöüáéíóúãõÀÈÌÒÙÂÊÎÔÛÄËÏÖÜÁÉÍÓÚÃÕçÇ';
  var caracteresValidos =   'aeiouaeiouaeiouaeiouaoAEIOUAEIOUAEIOUAEIOUAOcC';
  var acento = "´`^¨~;#$%*[](){}:?,+=!|<>'\"\\";
  
  // Se o campo não for email não permite alguns caracteres a mais (@,.)
  if(!email){
  	acento = acento + "@._&";
  }
  
  if(acento.indexOf(palavra)!= -1){
    window.event.keyCode = 0;
  }
 
 if (caracteresInvalidos.indexOf(palavra) == -1){
       if (caracteresValidos.indexOf(palavra) != -1) {
         window.event.keyCode = 0;
         obj.value = obj.value + palavra;
       }
  } else {
           window.event.keyCode = 0;
           nova = caracteresValidos.charAt(caracteresInvalidos.indexOf(palavra));
           obj.value =  obj.value + nova;
  }
  
 }

function preencheCamposData(tpData){
	var sauxData = "";
	var qtdBarra = 0;
	var dia = "";
	var mes = "";
					
	if (tpData == "ini")
		sauxData = document.getElementById("dtaIni").value;
	else if(tpData == "fim")
		sauxData = document.getElementById("dtaFim").value;
					
	//Se campos estiverem  < 4 caracteres
	if (sauxData.length < 4){						
		var newDta = new Date();
		mes = (newDta.getMonth()+1);
		if ((newDta.getMonth()+1) < 10){
			mes = "0" + (newDta.getMonth()+1);
		}
		dia = (newDta.getDate());
		if ((newDta.getDate()) < 10){
			dia = "0" + (newDta.getDate());
		}
		
		var dateString = dia + "/" + mes + "/" + newDta.getFullYear() + " 00:00";
		sauxData = dateString;
	} else{
        //Campos não totalmente preeenchidos 
		var char = "";
		var ini = 0;
		var campo = sauxData.split(" ");
		
		//Separa Dia e Mes
		for(fim = 0; fim < campo[0].length; fim++){		
			if (campo[0].charAt(fim) == '/')
			{
				qtdBarra++;
				char = campo[0].substring(ini,fim);
				ini = fim + 1;
			
				if (qtdBarra <= 2)
				{
					if ((char.length < 2) && (parseInt(char) < 10))
						char = '0' + char;
				
					if (qtdBarra == 1) dia = char;
					if (qtdBarra == 2) mes = char;				
				}
				char = "";						 
			}	
		}
		var ano = campo[0].substring(ini,campo[0].length);
		if (ano.length == 1)
			ano = '200' + ano;
		if (ano.length == 2)
			ano = '20' + ano;
		if (ano.length == 3)
			ano = '2' + ano;
		
		//se mes.length = 0 significa que a data esta no formata mm/yy
		if (mes.length == 0){
			mes = dia;
			dia = '01';
		}	
	
		//Montando a data ja formatada DD/MM/YYYY
		sauxData = dia + "/" + mes + "/" + ano;
		
		//Se hora estiver vazia ou incompleta
		var hora = "";
		var minuto = "";
		ini = 0;
		
		if ((campo[1] == null) || (campo[1].length < 3))					
			sauxData = sauxData;
		else
		{
			for(fim = 0; fim < campo[1].length; fim++)		
				if (campo[1].charAt(fim) == ':'){				 
					hora = campo[1].substring(ini,fim);
					minuto = campo[1].substring(fim+1,campo[1].length);
					break;
				}
				
			if ((hora.length < 2) && (parseInt(hora) < 10))
				hora = '0' + hora;
			if ((minuto.length < 2) && (parseInt(minuto) < 10))
				minuto = '0' + minuto;
			
			sauxData = sauxData + " " + hora + ":" + minuto;
		}
	}
					
	if (tpData == "ini")
		document.getElementById("dtaIni").value = sauxData;					
	else if(tpData == "fim")		
		document.getElementById("dtaFim").value = sauxData;	
}

function init()
  {
  if(window.addEventListener)
    {
    AdjustDivWidth();
    window.addEventListener("resize", AdjustDivWidth, false);
    }
  else if(document.addEventListener && window.opera)
    {
    AdjustDivWidthForOpera7();
    document.addEventListener("resize", AdjustDivWidthForOpera7, false);
    };
  }

  function AdjustDivWidth()
  {
  var ScrollbarWidth = 13; var TableBorder = 1;
  if(navigator.userAgent && navigator.userAgent.indexOf("Gecko") != -1 && (navigator.userAgent.indexOf("Firefox/1.") != -1 || navigator.userAgent.indexOf("K-Meleon/1.") != -1))
    {ScrollbarWidth = 15; TableBorder = 2;}
  else if(navigator.userAgent && navigator.userAgent.indexOf("Gecko") != -1 && navigator.userAgent.indexOf("Firefox/2.") != -1)
    {ScrollbarWidth = 16;}
  else if(navigator.userAgent.indexOf("SeaMonkey/") != -1)
    {ScrollbarWidth = 9;}
  else if(navigator.userAgent && navigator.userAgent.indexOf("Opera/9.") != -1)
    {ScrollbarWidth = 13;};
  document.getElementById("idDivScrollingTBody").style.width = parseInt(document.defaultView.getComputedStyle(document.getElementById("idTableHeader"), null).getPropertyValue("width"), 10) + TableBorder + 2 + 2 + TableBorder + ScrollbarWidth + "px";
  /*
  ========================================================
  15 for Mozilla suite; 17 for FF 1.x and K-meleon 1.0+
  assuming that
  Start/Settings/Control Panel/Display/Appearance tab/Font size
  is Normal and here assuming that
  Advanced button/Item: Scrollbar/Size:
  has not been user-defined, then 17
  ========================================================
  */
  }

  function AdjustDivWidthForOpera7()
  {
  document.getElementById("idTableHeader").style.width = document.getElementById("idDivScrollingTBody").offsetWidth - 17 + "px";
  }
  
  /* Abre uma nova janela centralizada*/
  var win = null;
  function NovaJanela(pagina,nome,w,h,scroll){
		LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
		TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
		settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
		win = window.open(pagina,nome,settings);
  }
  
  function html_entity_decode(str) {
	  var ta=document.createElement("textarea");
	  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	  return ta.value;
  }
  
  function exibirEqp(rd){
    if(rd == null){
    		
        for(idx=0;idx < document.forms[0].equipamento.length;idx++){
        	if(document.forms[0].equipamento[idx].checked){
    		rd = document.forms[0].equipamento[idx];
    		break;
    		}
    	}
    }
  
  	if(rd.value == 'S'){
  		document.getElementById('trEqp').style.display = '';
  	} else {
  		document.getElementById('trEqp').style.display = 'none';
  		document.getElementById('trEqp').value = '';
  	}  	  
  }
  
function IsNumeric(e){
    var unicode= e.charCode? e.charCode : e.keyCode
	
	if (unicode!= 8){ 
		if (unicode < 48||unicode > 57){ 
			return false
		}
	}	
}

function mascaraData(objeto) {
	campo = eval (objeto);	
	caracteres = '01234567890';
	if (campo.value.length == 2)
		campo.value =  campo.value + '/';
	else if (campo.value.length == 5){
		campo.value = campo.value + '/';		
	}	
}

function validaData(data) {
	var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
	if ((data.value.match(expReg)) && (data.value!='')){
		var dia = parseInt(data.value.substring(0,2));
		var mes = parseInt(data.value.substring(3,5));
		var ano = parseInt(data.value.substring(6,10));
		if((mes == 4 && dia > 30) || (mes == 6 && dia > 30) || 
		   (mes == 9 && dia > 30) || (mes == 11 && dia > 30)){
			return false;
		} else{ //1
				if(ano % 4 != 0 && mes == 2 && dia > 28){
					return false;
				} else{ //2
						if(ano % 4 == 0 && mes == 2 && dia > 29){
								return false;
						} else{ //3
								return true;
						} //3-else
				}//2-else
		}//1-else			
	} else { //5
			return false;
	} //5-else
}

var txtLimite1 = "";
var txtLimite2 = "";
var tipoReclamacao= "";

function checalimite(e, limite, textarea) {  
    var keyPressed = e.keyCode;   
    if(keyPressed!=8){
        if (textarea.value.length > limite) {
            alert(txtLimite1 + limite + txtLimite2);
            textarea.focus();
            return false;
        }
    }
 return true;
}


