// JavaScript Document


function janela(jan){
window.open(jan,"_blank","width=400,height=400,top=0,left=0,status=1,scrollbars=1,resizable=1");
}







function centralizaScreen(larg,altu){

var screenW = 800, screenH = 600;
if (parseInt(navigator.appVersion)>3)
{
 screenW = screen.width;
 screenH = screen.height;
}
else if (navigator.appName == "Netscape" && parseInt(navigator.appVersion)==3  && navigator.javaEnabled()
   ) 
{
 var jToolkit = java.awt.Toolkit.getDefaultToolkit();
 var jScreenSize = jToolkit.getScreenSize();
 screenW = jScreenSize.width;
 screenH = jScreenSize.height;
}

var alturaJanela = parseInt( (screenH / 2) - (altu/2) );
var larguraJanela= parseInt( (screenW / 2) - (larg/2) );

window.moveTo(larguraJanela,alturaJanela);
}







function apagar_registro(PagIr,msgAlerta){
if(confirm(msgAlerta)) {
window.location.href=(PagIr);
}
}




function marcaTudo(campo) 
{ 
   for (var i=0;i<document.form1.elements.length;i++) 
   {
     var x = document.form1.elements[i];
     if (x.name == 'UIDL[]') 
	 { 
		x.checked = document.form1.selall.checked;
	 } 
  } 
}






function hidErro(id){
	var baseErros = document.getElementById(id);
		baseErros.style.display="none";
	return false;
}






function erros(erros,id){
	var baseErr = document.getElementById(id);
	baseErr.style.left = "50px";
	baseErr.style.top =  "10px";
	baseErr.style.display = 'block';
		
	baseErro ='<div id="erroBase">';
	baseErro+='<div id="erroLinha">';
	baseErro+='<div id="erroFecha">';
	baseErro+='<a href="javascript:void(fechar)" onClick="hidErro(\'erroBase\'); return false">';
	baseErro+='Fechar [ x ]</a></div>';
	baseErro+='</div>';
	baseErro+='<div id="erroTexto">';
	baseErro+='<b>ALERTA! Foram encontrados os seguinte erros:</b> <br>';
	baseErro+=erros;
	baseErro+='</div>';
	baseErro+='</div>';
	
	baseErr.innerHTML=baseErro;

return false;
}







function curso_tipo_troca_curso(campo)
{
	
	curso_tipo = campo.value;
	var divs = document.getElementsByTagName("tr");
	for (var i=0; i<divs.length; i++)
	{
		if (divs[i].getAttribute("id")){
			if (divs[i].getAttribute("id").substring(0,11) == 'curso_tr['+curso_tipo+']'){
			divs[i].style.display = "table-row";
			}else{
			divs[i].style.display = "none";
			}
		}	
	}
}















//onkeypress="return ajustar_tel(this , event)"
function ajustar_tel(input, evento)
{
         var BACKSPACE=  8; 
         var DEL=  46; 
         var FRENTE=  39; 
         var TRAS=  37; 
         var TAB=  9; 
         var F5=  116; 
         var ENTER=  13; 
         var tecla= (evento.keyCode ? evento.keyCode: evento.which ? evento.which : evento.charCode)
         
         if ( (tecla == BACKSPACE) || (tecla == DEL) || (tecla == FRENTE) || (tecla == TRAS) || (tecla==TAB) || (tecla==F5) || (tecla==ENTER) ) {
             return true; 
             }
         if ( tecla == 13 )     return false; 


		if ((tecla<48)||(tecla>57)) {
			evento.returnValue = false; 
			return false;
			} else { 
				if ((input.value.length==1)) {
				   input.value='('+input.value;
				   }
				if ((input.value.length==3)) {
				   input.value=input.value+")";
				   }
				if ((input.value.length==8)) {
				   input.value=input.value+"-";
				   }
			}
			//
			//
  return true;			
};







//onkeypress='return SomenteNumero(event)'
function SomenteNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;   
    if((tecla>47 && tecla<58)) return true;
    else{
    	if (tecla==8 || tecla==0) return true;
	else  return false;
    }
}






//onkeypress="return ajustar_cep(this , event)"
function ajustar_cep(input, evento)
{
         var BACKSPACE=  8; 
         var DEL=  46; 
         var FRENTE=  39; 
         var TRAS=  37; 
         var TAB=  9; 
         var F5=  116; 
         var ENTER=  13; 
         var tecla= (evento.keyCode ? evento.keyCode: evento.which ? evento.which : evento.charCode)
         
         if ( (tecla == BACKSPACE) || (tecla == DEL) || (tecla == FRENTE) || (tecla == TRAS) || (tecla==TAB) || (tecla==F5) || (tecla==ENTER) ) {
             return true; 
             }
         if ( tecla == 13 )     return false; 


		if ((tecla<48)||(tecla>57)) {
			evento.returnValue = false; 
			return false;
			} else { 
				if ((input.value.length==5)) {
				   input.value=input.value + "-" ;
				   }
			}
			//
			//
  return true;			
};







//onkeypress="return ajustar_cpf(this , event)"
function ajustar_cpf(input, evento)
{
         var BACKSPACE=  8; 
         var DEL=  46; 
         var FRENTE=  39; 
         var TRAS=  37;          
         var TAB=  9; 
         var F5=  116; 
         var ENTER=  13; 
         var tecla= (evento.keyCode ? evento.keyCode: evento.which ? evento.which : evento.charCode)
         
         if ( (tecla == BACKSPACE) || (tecla == DEL) || (tecla == FRENTE) || (tecla == TRAS) || (tecla==TAB) || (tecla==F5) || (tecla==ENTER) ) {
             return true; 
             }
			 
         if ( tecla == 13 )     return false; 

		if ((tecla<48)||(tecla>57)){
			evento.returnValue =false;
			return false;
		} else 
		{ 

					/*
					str = input.value;
					if(tecla==42){
					   i = 0;
					   while(i< str.length){
						   if(str.substr(i,1) == ".")
							  input.value = str.replace(".","");
							  i++;
					   }
					}
					*/

					if(input.value.length==3)
					{
					input.value = input.value + ".";
					} 
					
					if(input.value.length==7)
					{
					input.value = input.value + ".";
					} 
					
					if(input.value.length==11) 
					{
					input.value = input.value + "-";
					}

		}
		 return true;		
  		
}






//onkeypress="return ajustar_data(this , event)"
function ajustar_data(input, evento)
{
         var BACKSPACE=  8; 
         var DEL=  46; 
         var FRENTE=  39; 
         var TRAS=  37; 
         var TAB=  9; 
         var F5=  116; 
         var ENTER=  13; 
         var tecla= (evento.keyCode ? evento.keyCode: evento.which ? evento.which : evento.charCode)
		 
         if ( (tecla == BACKSPACE) || (tecla == DEL) || (tecla == FRENTE) || (tecla == TRAS) || (tecla==TAB) || (tecla==F5) || (tecla==ENTER) ) {
             return true; 
             }
         if ( tecla == 13 )     return false; 


		if ((tecla<48)||(tecla>57)) {
			evento.returnValue = false; 
			return false;
			} else { 

					if ((input.value.length==2)||(input.value.length==5)) {
				   input.value = input.value + "/";
				   }
				   
			}
			//
			//
  return true;			
};





//onkeypress="return ajustar_moeda(this , event)"
function ajustar_moeda(input, evento)
{
         var BACKSPACE=  8; 
         //var DEL=  46; 
         var FRENTE=  39; 
         var TRAS=  37; 
         var TAB=  9; 
         var F5=  116; 
         var ENTER=  13; 
         var tecla= (evento.keyCode ? evento.keyCode: evento.which ? evento.which : evento.charCode)
         
		if ( ((tecla>=48) && (tecla<=57)) || (tecla==BACKSPACE) || (tecla==FRENTE) || (tecla==TRAS) || (tecla==TAB) || (tecla==F5) ){
			
			       
					if ( (tecla>=48) && (tecla<=57) ){
					recuo = 1;
					}else if( (tecla==BACKSPACE) ){
					recuo = 3;	
					}else if( (tecla==FRENTE) || (tecla==TRAS) || (tecla==TAB) || (tecla==F5) ){
					return true;	
					}
				   
				   
				   str = input.value;
					
				   i = 0;
				   while(i< str.length){
					   if(str.substr(i,1) == ".")
						  str = str.replace(".","");
						  i++;
				   }
			
				   part1 = str.substr(0,str.length - recuo);
				   while(part1.search(" ") != -1)
					   part1 = part1.replace(" ","");
			
					   part2 = str.substr(str.length - recuo,3);
					   res = "";
					   i = part1.length;
					   sob = i % 3;
					   if((sob != 0) && (i > 2))
						  res = part1.substr(0,sob);
					   else
						  res = part1.substr(0,sob);
					   j = 1;
					   part1 = part1.substr(sob);
					   i = 0;
					   while(i < part1.length){
						  if(j == 3){
							 if(i + 1 == part1.length)
								res = res + part1.substr(i-2,3);
							 else res = res + part1.substr(i-2,3);
						  }
						  i++;
						  j = j<3?j+1:1;
					   }
						
						
						/*
						alert('res-----'+res);
						alert('part2-----'+part2);
						*/
						if( res!='' ){
						input.value = res + "." + part2;
						}else{
						input.value = part2;
						}

					  //alert('numero --- '+tecla)
					  return true;
					  

			} else { 


			  	//alert('letra --- '+tecla)
				evento.returnValue = false; 
				return false;
			
			}
};




//onkeypress="return ajustar_porcentagem(this , event)"
function ajustar_porcentagem(input, evento)
{
         var BACKSPACE=  8; 
         //var DEL=  46; 
         var FRENTE=  39; 
         var TRAS=  37; 
         var TAB=  9; 
         var F5=  116; 
         var ENTER=  13; 
         var tecla= (evento.keyCode ? evento.keyCode: evento.which ? evento.which : evento.charCode)
         
		 
		if ( ((tecla>=48) && (tecla<=57)) || (tecla==BACKSPACE) || (tecla==FRENTE) || (tecla==TRAS) || (tecla==TAB) || (tecla==F5) || (tecla==ENTER) ){
			
			       
					if ( (tecla>=48) && (tecla<=57) ){
					recuo = 0;
					}else if( (tecla==BACKSPACE) ){
					recuo = 2;	
					}else if( (tecla==FRENTE) || (tecla==TRAS) || (tecla==TAB) || (tecla==F5) ){
					return true;	
					}
				   
				   
				   str = input.value;
					
				   i = 0;
				   while(i< str.length){
					   if(str.substr(i,1) == ".")
						  str = str.replace(".","");
						  i++;
				   }
			
				   part1 = str.substr(0,str.length - recuo);
				   while(part1.search(" ") != -1)
					   part1 = part1.replace(" ","");
			
					   part2 = str.substr(str.length - recuo,3);
					   res = "";
					   i = part1.length;
					   sob = i % 3;
					   if((sob != 0) && (i > 2))
						  res = part1.substr(0,sob);
					   else
						  res = part1.substr(0,sob);
					   j = 1;
					   part1 = part1.substr(sob);
					   i = 0;
					   while(i < part1.length){
						  if(j == 3){
							 if(i + 1 == part1.length)
								res = res + part1.substr(i-2,3);
							 else res = res + part1.substr(i-2,3);
						  }
						  i++;
						  j = j<3?j+1:1;
					   }
						
						
						/*
						alert('res-----'+res);
						alert('part2-----'+part2);
						*/
						if( res!='' ){
						input.value = res + "." + part2;
						}else{
						input.value = part2;
						}

					  //alert('numero --- '+tecla)
					  return true;
					  

			} else { 


			  	//alert('letra --- '+tecla)
				evento.returnValue = false; 
				return false;
			
			}
};










function converteMoeda(str){

	str = new String(str);


	partes = str.split('.'); 
	parte_1_2 = partes[0];
	parte_3   = partes[1];

	// redefine a parte_3
	tem_ponto = 0;
	i = 0;
	while(i< str.length){
	   if(str.substr(i,1) == ".")
		  tem_ponto = 1;
		  i++;
	}
	
	if(tem_ponto==0){
	parte_3 = new String('00');
	}
	/////////////////////
	

	if(parte_1_2.length >= 4){
		parte_1 = str.substr(0,parte_1_2.length-3) + '.';
		parte_2 = str.substr(parte_1_2.length-3,parte_1_2.length-1) + ',';
	}else{
		parte_1 = '';
		parte_2 = parte_1_2 + ',';
	}
	
	if(parte_3.length == 1){
		parte_3 = parte_3 + '0';
	}else if(parte_3.length > 2){
		parte_3 = parte_3.substr(0,2);
	}

/*
alert(str)
alert(parte_1_2)
alert(parte_1)
alert(parte_2)
alert(parte_3)
*/

	return parte_1 + parte_2 + parte_3;
}









//Contar caracteres de campoTexto
// onKeyUp='contaCaracteres(this,car,500);
function contaCaracteres(texto,subtrair,total)
{ 
	var campoTexto = texto;
	var contar = subtrair;
	var caracteres = total;
	
	intCaracteres = caracteres - campoTexto.value.length; 
	if (intCaracteres > 0)
	{ 
	contar.value = intCaracteres; 
	return true; 
	} 
	else 
	{ 
	contar.value = 0; 
	campoTexto.value = campoTexto.value.substr(0,caracteres) 
	return false; 
	} 
} 








function number_format( number, decimals, dec_point, thousands_sep ) {
    // %        nota 1: Para 1000.55 retorna com precisão 1 no FF/Opera é 1,000.5, mas no IE é 1,000.6
    // *     exemplo 1: number_format(1234.56);
    // *     retorno 1: '1,235'
    // *     exemplo 2: number_format(1234.56, 2, ',', ' ');
    // *     retorno 2: '1 234,56'
    // *     exemplo 3: number_format(1234.5678, 2, '.', '');
    // *     retorno 3: '1234.57'
    // *     exemplo 4: number_format(67, 2, ',', '.');
    // *     retorno 4: '67,00'
    // *     exemplo 5: number_format(1000);
    // *     retorno 5: '1,000'
    // *     exemplo 6: number_format(67.311, 2);
    // *     retorno 6: '67.31'
 
    var n = number, prec = decimals;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
    var dec = (typeof dec_point == "undefined") ? '.' : dec_point;
 
    var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = Math.abs(n).toFixed(prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
 
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    return s;
}







function matriculas_listar_cursos(campo){
	
	curso_tipo = campo.value;
	var divs = document.getElementsByTagName("tr");
	for (var i=0; i<divs.length; i++)
	{
		if (divs[i].getAttribute("id")){
			if (divs[i].getAttribute("id").substring(0,1) == curso_tipo){
			divs[i].style.display = "table-row";
			}else{
			divs[i].style.display = "none";
			}
		}	
	}
	
	var divs = document.getElementsByTagName("input");
	for (var i=0; i<divs.length; i++)
	{
		if (divs[i].getAttribute("id")){
			if (divs[i].getAttribute("id").substring(0,5) == 'curso'){
			divs[i].checked = false;
			}
		}	
	}
	
}








function somar_cursos(id){
	valor = new Number(document.getElementById('valor_curso['+id+']').value);
	if(document.getElementById('curso['+id+']').checked == true){
		valor_inicial = new Number(document.getElementById('valor_inicial').value) + valor;
	}else{
		valor_inicial = new Number(document.getElementById('valor_inicial').value) - valor;
	}
	
	document.getElementById('valor_inicial').value = number_format(valor_inicial, 2, '.', '');
	document.getElementById('hidden_valor_inicial').value = number_format(valor_inicial, 2, '.', '');
	
	valor_final = valor_inicial - new Number(document.getElementById('valor_desconto').value);
	document.getElementById('valor_final').value = number_format(valor_final, 2, '.', '');
	
	valor_parcela = valor_final - new Number(document.getElementById('somatorio_parcelas').value);
	document.getElementById('valor_parcela').value = number_format(valor_parcela, 2, '.', '');
}





function descontar_cursos(campo){
	valor_final = new Number(document.getElementById('valor_inicial').value) - campo.value;
	document.getElementById('valor_final').value = number_format(valor_final, 2, '.', '');
	
	valor_parcela = valor_final - new Number(document.getElementById('somatorio_parcelas').value);
	document.getElementById('valor_parcela').value = number_format(valor_parcela, 2, '.', '');
	
	if(valor_parcela==0){
		document.getElementById('faltam').innerHTML = '<i>(concluído)</i>';
	}else if(valor_parcela>0){
		document.getElementById('faltam').innerHTML = '<i>(faltam R$ '+number_format(valor_parcela, 2, ',', '.')+')</i>';
	}else if(valor_parcela<0){
		document.getElementById('faltam').innerHTML = '';
	}
}




function valor_final_cursos(campo){
	valor_desconto = new Number(document.getElementById('valor_inicial').value) - campo.value;
	document.getElementById('valor_desconto').value = number_format(valor_desconto, 2, '.', '');
	
	valor_parcela = campo.value - new Number(document.getElementById('somatorio_parcelas').value);
	document.getElementById('valor_parcela').value = number_format(valor_parcela, 2, '.', '');
	
	if(valor_parcela==0){
		document.getElementById('faltam').innerHTML = '<i>(concluído)</i>';
	}else if(valor_parcela>0){
		document.getElementById('faltam').innerHTML = '<i>(faltam R$ '+number_format(valor_parcela, 2, ',', '.')+')</i>';
	}else if(valor_parcela<0){
		document.getElementById('faltam').innerHTML = '';
	}
}




function inserir_parcela(){
	
	vlr_parcelas = document.getElementById("parcelas").value;
	vlr_tipo = document.getElementById("tipo").value;
	vlr_valor = document.getElementById("valor_parcela").value;
	vlr_vencimento = document.getElementById("vencimento").value;
	
	//if(    (vlr_parcelas!='' && (vlr_tipo=='Cartão (Crédito)' || vlr_tipo=='Cartão (Débito)') && vlr_valor!='')    ||    (vlr_parcelas!='' && (vlr_tipo!='' && vlr_tipo!='Cartão (Crédito)' && vlr_tipo!='Cartão (Débito)') && vlr_valor!='' && vlr_vencimento!='')    ){
	if(vlr_parcelas!='' && vlr_tipo!='' && vlr_valor!='' && vlr_vencimento!=''){
		
		inserirLinhaTabela(vlr_parcelas, vlr_tipo, vlr_valor, vlr_vencimento);
		
		valor_somatorio = new Number(document.getElementById('somatorio_parcelas').value) + new Number(vlr_valor);
		document.getElementById('somatorio_parcelas').value = number_format(valor_somatorio, 2, '.', '')
		document.getElementById('hidden_somatorio_parcelas').value = number_format(valor_somatorio, 2, '.', '')
		
		document.getElementById("parcelas").value = '1';
		document.getElementById("tipo").value = '';
		valor_parcela = document.getElementById('valor_final').value - document.getElementById('somatorio_parcelas').value;
		document.getElementById('valor_parcela').value = number_format(valor_parcela, 2, '.', '');
		document.getElementById("vencimento").value = '';
		
		if(valor_parcela==0){
			document.getElementById('faltam').innerHTML = '<i>(concluído)</i>';
		}else if(valor_parcela>0){
			document.getElementById('faltam').innerHTML = '<i>(faltam R$ '+number_format(valor_parcela, 2, ',', '.')+')</i>';
		}
	}
}

	

// Função responsável por inserir linhas na tabela
function inserirLinhaTabela(vlr_parcelas, vlr_tipo, vlr_valor, vlr_vencimento) {

	// Captura a referência da tabela com id “minhaTabela”
	var table = document.getElementById("tabela_pagamentos");
	
	if(vlr_parcelas==1){
		
			// Captura a quantidade de linhas já existentes na tabela
			var numOfRows = table.rows.length;
			
			// Captura a quantidade de colunas da última linha da tabela
			var numOfCols = table.rows[numOfRows-1].cells.length;
			
			// Insere uma linha no fim da tabela.
			var newRow = table.insertRow(numOfRows);
			
			// define os valores que serão inseridos
			valor = new Array();
			valor[0] = numOfRows;
			valor[1] = vlr_tipo+"<input type='hidden' name='hidden_IDtipo_pagamento[]' value='"+vlr_tipo+"'>";
			valor[2] = vlr_valor+"<input type='hidden' name='hidden_valor_parcela[]' value='"+vlr_valor+"'>";
			//valor[3] = vlr_vencimento+"<input type='hidden' name='hidden_data_vencimento[]' value='"+vlr_vencimento+"'>&nbsp;";
			valor[3] = "<input type='text' name='text_data_vencimento[]' value='"+vlr_vencimento+"' size='10' maxlength='10' onKeyPress='return ajustar_data(this , event)'>&nbsp;";
			valor[4] = "<div style='text-align:center;'><a href=\"javascript:void('deletar')\" onclick='deletarLinhaTabela("+numOfRows+","+vlr_valor+")'>X</a></div>";
			
			// Faz um loop para criar as colunas
			for (var j=0; j<numOfCols; j++) {
				// Insere uma coluna na nova linha 
				newCell = newRow.insertCell(j);
				// Insere um conteúdo na coluna
				// newCell.innerHTML = "Linha "+ numOfRows + " – Coluna "+ j;
				newCell.innerHTML = valor[j];
			}
		
	}else{
		
		vlr_valor = vlr_valor / vlr_parcelas;
		
		for(iii=1; iii<=vlr_parcelas; iii++){
			
				
				// Captura a quantidade de linhas já existentes na tabela
				var numOfRows = table.rows.length;
				
				// Captura a quantidade de colunas da última linha da tabela
				var numOfCols = table.rows[numOfRows-1].cells.length;
				
				// Insere uma linha no fim da tabela.
				var newRow = table.insertRow(numOfRows);
			
				// define os valores que serão inseridos
				valor = new Array();
				valor[0] = numOfRows;
				valor[1] = vlr_tipo+"<input type='hidden' name='hidden_IDtipo_pagamento[]' value='"+vlr_tipo+"'>";
				valor[2] = number_format(vlr_valor, 2, '.', '')+"<input type='hidden' name='hidden_valor_parcela[]' value='"+number_format(vlr_valor, 2, '.', '')+"'>";
				if(iii>1 && vlr_vencimento!=''){
						/*
						explode_vencimento = vlr_vencimento.split('/');
						vlr_vencimento_dia = explode_vencimento[0];
						vlr_vencimento_mes = new Number(explode_vencimento[1]) + iii -1;
						vlr_vencimento_ano = explode_vencimento[2];
						if(vlr_vencimento_mes >= 13){
							vlr_vencimento_mes = vlr_vencimento_mes - 12;
							vlr_vencimento_ano = new Number(vlr_vencimento_ano) + 1;
						}
						vlr_vencimento_mes = '0'+vlr_vencimento_mes;
						vlr_vencimento_mes = vlr_vencimento_mes.slice(-2);
						valor[3] = vlr_vencimento_dia+'/'+vlr_vencimento_mes+'/'+vlr_vencimento_ano+"<input type='hidden' name='hidden_data_vencimento[]' value='"+vlr_vencimento_dia+'/'+vlr_vencimento_mes+'/'+vlr_vencimento_ano+"'>";
						*/
						
						explode_vencimento = vlr_vencimento.split('/');
						proximo_vencimento = somar_dias((30*(iii-1)), explode_vencimento[0], explode_vencimento[1], explode_vencimento[2])
						//valor[3] = proximo_vencimento+"<input type='hidden' name='hidden_data_vencimento[]' value='"+proximo_vencimento+"'>";
						valor[3] = "<input type='text' name='text_data_vencimento[]' value='"+proximo_vencimento+"' size='10' maxlength='10' onKeyPress='return ajustar_data(this , event)'>&nbsp;";
						
				}else{
						//valor[3] = vlr_vencimento+"<input type='hidden' name='hidden_data_vencimento[]' value='"+vlr_vencimento+"'>&nbsp;";
						valor[3] = "<input type='text' name='text_data_vencimento[]' value='"+vlr_vencimento+"' size='10' maxlength='10' onKeyPress='return ajustar_data(this , event)'>&nbsp;";
				}
				valor[4] = "<div style='text-align:center;'><a href=\"javascript:void('deletar')\" onclick='deletarLinhaTabela("+numOfRows+","+number_format(vlr_valor, 2, '.', '')+")'>X</a></div>";
				
				// Faz um loop para criar as colunas
				for (var j=0; j<numOfCols; j++) {
					// Insere uma coluna na nova linha 
					newCell = newRow.insertCell(j);
					// Insere um conteúdo na coluna
					// newCell.innerHTML = "Linha "+ numOfRows + " – Coluna "+ j;
					newCell.innerHTML = valor[j];
				}
				
		}
		
	}
	/*
	// define os valores que serão inseridos
	valor = new Array();
	valor[0] = numOfRows;
	valor[1] = vlr_tipo;
	valor[2] = vlr_valor;
	valor[3] = vlr_vencimento;
	valor[4] = "<div style='text-align:center;'><a href=\"javascript:void('deletar')\" onclick='deletarLinhaTabela("+numOfRows+","+vlr_valor+")'>X</a></div>";
	
	// Faz um loop para criar as colunas
	for (var j=0; j<numOfCols; j++) {
		// Insere uma coluna na nova linha 
		newCell = newRow.insertCell(j);
		// Insere um conteúdo na coluna
		// newCell.innerHTML = "Linha "+ numOfRows + " – Coluna "+ j;
		newCell.innerHTML = valor[j];
	}
	*/

}



function deletarLinhaTabela(linha, valor) {
	// Captura a referência da tabela com id “minhaTabela”
	var table = document.getElementById("tabela_pagamentos");
	table.deleteRow(linha);	
	
	valor_somatorio = new Number(document.getElementById('somatorio_parcelas').value) - new Number(valor);
	document.getElementById('somatorio_parcelas').value = number_format(valor_somatorio, 2, '.', '');
	document.getElementById('hidden_somatorio_parcelas').value = number_format(valor_somatorio, 2, '.', '');
	
	valor_parcela = new Number(document.getElementById('valor_parcela').value) + new Number(valor);
	document.getElementById('valor_parcela').value = number_format(valor_parcela, 2, '.', '');
	
	if(valor_parcela==0){
		document.getElementById('faltam').innerHTML = '<i>(concluído)</i>';
	}else if(valor_parcela>0){
		document.getElementById('faltam').innerHTML = '<i>(faltam R$ '+number_format(valor_parcela, 2, ',', '.')+')</i>';
	}
	atualizarLinhaTabela(linha);
}







// Função responsável por inserir linhas na tabela
function atualizarLinhaTabela(linha) {

	// Captura a referência da tabela com id “minhaTabela”
	var table = document.getElementById("tabela_pagamentos");
	
	// Captura a quantidade de linhas já existentes na tabela
	var numOfRows = table.rows.length;
	
	// Captura a quantidade de colunas da última linha da tabela
	var numOfCols = table.rows[numOfRows-1].cells.length;

	// Faz um loop para ordenar o numero da parcela
	for (var i=0; i<numOfRows; i++) {
		for (var ii=0; ii<numOfCols; ii++) {  
			if(i>0){
				table.rows[i].cells[0].innerHTML = i;
				
				if(i>=linha && ii==3){
					/*
					vlr_vencimento = table.rows[i].cells[3].innerHTML;
					explode_vencimento = vlr_vencimento.split('/');
					vlr_vencimento_dia = explode_vencimento[0];
					vlr_vencimento_mes = new Number(explode_vencimento[1]) - 1;
					vlr_vencimento_ano = explode_vencimento[2];
					if(vlr_vencimento_mes == 0){
						vlr_vencimento_mes = 12;
						vlr_vencimento_ano = new Number(vlr_vencimento_ano) - 1;
					}
					vlr_vencimento_mes = '0'+vlr_vencimento_mes;
					vlr_vencimento_mes = vlr_vencimento_mes.slice(-2);
					vlr_vencimento = vlr_vencimento_dia+'/'+vlr_vencimento_mes+'/'+vlr_vencimento_ano;
					table.rows[i].cells[3].innerHTML = vlr_vencimento+"<input type='hidden' name='hidden_data_vencimento[]' value='"+vlr_vencimento+"'>"
					*/
					vlr_vencimento = table.rows[i].cells[3].innerHTML;
					explode_vencimento1 = vlr_vencimento.split('value="');
					explode_vencimento2 = explode_vencimento1[1].split('"');
					explode_vencimento = explode_vencimento2[0].split("/");
					explode_vencimento_ano = explode_vencimento[2].split('<');
					proximo_vencimento = subtrair_dias(30, explode_vencimento[0], explode_vencimento[1], explode_vencimento_ano[0])
					//table.rows[i].cells[3].innerHTML = proximo_vencimento+"<input type='hidden' name='hidden_data_vencimento[]' value='"+proximo_vencimento+"'>"
					table.rows[i].cells[3].innerHTML = "<input type='text' name='text_data_vencimento[]' value='"+proximo_vencimento+"' size='10' maxlength='10' onKeyPress='return ajustar_data(this , event)'>&nbsp;";
				}
				
				
				if(i>=linha && ii==4){
					separa_valor = table.rows[i].cells[2].innerHTML.split('<input');
					table.rows[i].cells[4].innerHTML = "<div style='text-align:center;'><a href=\"javascript:void('deletar')\" onclick='deletarLinhaTabela("+i+","+separa_valor[0]+")'>X</a></div>";
				}
				
			}
		} 
	}
	
}






function tipopg_vencimento(tipopg){
	
	vlr_tipopg = tipopg.value;

	data = new Date();
	dia = data.getDate();
	mes = data.getMonth() + 1;
	ano = data.getFullYear();
	
	if(vlr_tipopg == 'À vista'){
		document.getElementById('vencimento').value = somar_dias(0, dia, mes, ano);
	}else if(vlr_tipopg == 'Cartão (Crédito)'){
		document.getElementById('vencimento').value = somar_dias(30, dia, mes, ano);
	}else if(vlr_tipopg == 'Promissória'){
		document.getElementById('vencimento').value = somar_dias(30, dia, mes, ano);
	}else if(vlr_tipopg == 'Cheque'){
		document.getElementById('vencimento').value = somar_dias(30, dia, mes, ano);
	}else if(vlr_tipopg == 'Cartão (Débito)'){
		document.getElementById('vencimento').value = somar_dias(1, dia, mes, ano);
	}
	
}




function somar_dias(soma, dia, mes, ano){
	
	data1 = new Date(ano,mes-1,dia);
	data2 = new Date( data1.getFullYear(), data1.getMonth(), data1.getDate() + soma );
	
	dia2 = data2.getDate();
	dia2 = '0'+dia2;
	dia2 = dia2.slice(-2);
	
	mes2 = data2.getMonth() + 1;
	mes2 = '0'+mes2;
	mes2 = mes2.slice(-2);
	
	ano2 = data2.getFullYear();
	
	return dia2+'/'+mes2+'/'+ano2;
	
}




function subtrair_dias(soma, dia, mes, ano){
	
	data1 = new Date(ano,mes-1,dia);
	data2 = new Date( data1.getFullYear(), data1.getMonth(), data1.getDate() - soma );
	
	dia2 = data2.getDate();
	dia2 = '0'+dia2;
	dia2 = dia2.slice(-2);
	
	mes2 = data2.getMonth() + 1;
	mes2 = '0'+mes2;
	mes2 = mes2.slice(-2);
	
	ano2 = data2.getFullYear();
	
	return dia2+'/'+mes2+'/'+ano2;
	
}







function utf8_encode(argString) {
    // Encodes an ISO-8859-1 string to UTF-8  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/utf8_encode    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // +   bugfixed by: Rafal Kukawski
    // *     example 1: utf8_encode('Kevin van Zonneveld');    // *     returns 1: 'Kevin van Zonneveld'
    if (argString === null || typeof argString === "undefined") {
        return "";
    }
     var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
    var utftext = "",
        start, end, stringl = 0;
 
    start = end = 0;    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
         if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.slice(start, end);            }
            utftext += enc;
            start = end = n + 1;
        }
    } 
    if (end > start) {
        utftext += string.slice(start, stringl);
    }
     return utftext;
}




function utf8_decode(str_data) {
    // Converts a UTF-8 encoded string to ISO-8859-1  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/utf8_decode    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Norman "zEh" Fuchs
    // +   bugfixed by: hitwork    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'    var tmp_arr = [],
        i = 0,
        ac = 0,
        c1 = 0,
        c2 = 0,        c3 = 0;
 
    str_data += '';
 	tmp_arr = new Array();
	
    while (i < str_data.length) {        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if (c1 > 191 && c1 < 224) {            c2 = str_data.charCodeAt(i + 1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i + 1);            c3 = str_data.charCodeAt(i + 2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    } 
    return tmp_arr.join('');
}







