//Funções JavaScript
function $(id) {
	return document.getElementById(id);
}

function carregado(x) {
	if($('carregando')) {
		if(x) $('carregando').style.display = 'none';
		else $('carregando').style.display = 'block';
	}
}
setTimeout("carregado(true)", 2000);


function buscaCep(x) {
	ajax1('com=buscaCEP&cep='+ x.value);
}
function cepBuscado(x) {
	campos = new Array('estado', 'cidade', 'bairro', 'endereco');
	for(k in campos) $(campos[k]).value = x[campos[k]];
}


//Limitador de Caracteres
//Tem como função limitar que as pessoas só possam digitar os caracteres permitidos pelo programador.
//por Vini L.Azev. (www.lazev.kit.net) - favor manter os créditos
function limitachars(z, y) {
    x = z.value;
    y = y.toUpperCase();
    y = y.replace('A-Z', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
    y = y.replace('0-9', '1234567890');
    var chars_permitidos = y;
    var resposta = '';
    for(ii=0; ii<x.length; ii++) {
        if ((chars_permitidos.indexOf(x.charAt(ii).toUpperCase()) > -1) || (chars_permitidos.indexOf(x.charAt(ii).toLowerCase()) > -1)) {
            resposta += x.charAt(ii);
        }
    }
    z.value = resposta;
}

//Auxiliar no preenchimento de datas
//Completa o restante da data, bastando digitar apenas o dia, ou o dia e mês juntos, com 2 casas cada e sem a barra (ex 1604)
//por Vini L.Azev. (www.lazev.kit.net) - favor manter os créditos
function completadata(z) {
	x = z.value;
	if ((x.length == 1) || (x.length == 2)) {
		hoje = new Date();
		var mes = (hoje.getMonth()+1);
		if(mes < 10) mes = "0" + mes;
		z.value = x + "/" + mes + "/" + hoje.getFullYear();
	} else if((x.length == 4) && (x.indexOf("/") == -1)) {
		hoje = new Date();
		var dia = x.substring(0, 2);
		var mes = x.substring(2, 4);
		z.value = dia + "/" + mes + "/" + hoje.getFullYear();
	} else if((x.length >= 6) && (x.indexOf("/") == -1)) {
		var dia = x.substring(0, 2);
		var mes = x.substring(2, 4);
		var ano = x.substring(4, x.length);
		z.value = dia + "/" + mes + "/" + ano;
	}
}

//Muda ponto para vírgula
//Após digitar o valor, muda qualquer ponto para vírgula e padroniza o numero para xxxx,xx
//por Vini L.Azev. (www.lazev.kit.net) - favor manter os créditos
function pontovirgula(x) {
	var conta = 0;
	while(x.value.indexOf(".") != -1) {	x.value = x.value.replace(".", ","); conta++; }
	for(ii=0; ii<conta; ii++) {
		if(x.value.indexOf(",", x.value.indexOf(",")+1) != -1) { x.value = x.value.replace(",", ""); }
	}
}

//Muda hífem para barra
//Após digitar a data, muda qualquer hífem para barra e padroniza a data para 00/00/0000;
//por Vini L.Azev. (www.lazev.kit.net) - favor manter os créditos
function hifembarra(x) {
	while(x.value.indexOf("-") != -1) {	x.value = x.value.replace("-", "/"); }
	//if(x.value.indexOf(",", x.value.indexOf(",")+1) != -1) { x.value = x.value.replace(",", ""); }
}

function ocultaWaitBox() {
	$('waitBox').style.display = 'none';
}

function waitAct1Box() {
	$('tapume').style.display = 'block';
	setTimeout(function() {
		$('tapume').style.display = 'none';
	}, 5000);
}

function dicamano(x) {
	if(x.alt != "") {
		if(x.value == "") x.value = x.alt;
		else if(x.value == x.alt) x.value = "";
	}
}

function vericpf(x) {
	var CPF = x.value;
	if(CPF=='') var faiado = true;
	else {
		if(CPF == "00000000000" || CPF == "11111111111" ||
			CPF == "22222222222" ||	CPF == "33333333333" || CPF == "44444444444" ||
			CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
			CPF == "88888888888" || CPF == "99999999999" || CPF == "00000000000") {
			var faiado = true;
		}
		soma = 0;
		for(i=0; i<9; i++) soma += parseInt(CPF.charAt(i)) * (10-i);
		resto = 11 - (soma % 11);
		if (resto == 10 || resto == 11) resto = 0;
		if (resto != parseInt(CPF.charAt(9))) var faiado = true;
		soma = 0;
		for(i=0; i<10; i++) soma += parseInt(CPF.charAt(i)) * (11-i);
		resto = 11-(soma % 11);
		if (resto == 10 || resto == 11) resto = 0;
		if (resto != parseInt(CPF.charAt(10))) var faiado = true;
	}
	if(faiado) {
		aviso("CPF inválido, favor verificar.");
		return false;
	} else {
		$('quadroMensagem').innerHTML = '';
		return true;
	}
}

function vericgc(x) {
	var s = x.value;
	var i;
	if(s.length == "15") s = s.substr(1,14);
	if(s != '00000000000000') {
		var c = s.substr(0,12);
		var dv = s.substr(12,2);
		var d1 = 0;
		for (i = 0; i < 12; i++) d1 += c.charAt(11-i)*(2+(i % 8));
		if (d1 == 0) var faiado = true;
		d1 = 11 - (d1 % 11);
		if (d1 > 9) d1 = 0;
		if(dv.charAt(0) != d1) var faiado = true;
		d1 *= 2;
		for (i = 0; i < 12; i++) d1 += c.charAt(11-i)*(2+((i+1) % 8));
		d1 = 11 - (d1 % 11);
		if (d1 > 9) d1 = 0;
		if (dv.charAt(1) != d1) var faiado = true;
	}
	if(faiado) {
		aviso("CNPJ inválido, favor verificar.");
		return false;
	} else {
		$('quadroMensagem').innerHTML = '';
		return true;
	}
}


function vericpfcgc(x) {
	if (x.value.length < 13) return vericpf(x);
	else return vericgc(x);
}


function veriemail(x) {
	if ((x.indexOf("@") < 1) ||
		(x.indexOf(".") < 1) ||
		(x.indexOf("@.") > -1) ||
		(x.indexOf(".@") > -1) ||
		(x.indexOf(" ") > -1) ||
		(x.indexOf(",") > -1)) {
		return false;
	} else {
		return true;
	}
}

function ponto(valor) {
	valor = valor.replace(".","");
	valor = parseFloat(valor.replace(",","."));
	if(!isNaN(valor)) return valor;
	else return 0.00;
}

if(!window.imprimir) {
	function imprimir(x) {
		pulatela('print_tabela.php');
	}
}

function navegar(x) {
	window.location = x;
}

function aviso(x) {
	document.getElementById('quadroMensagem').className = 'inicio';
	document.getElementById('quadroMensagem').innerHTML = '<span><div>'+ x +'</div></span>';
	setTimeout('desaviso()', 500);
	setTimeout('reaviso()', 1000);
	setTimeout('desaviso()', 1500);
}

function desaviso() {
	document.getElementById('quadroMensagem').className = 'fim';
}

function reaviso() {
	document.getElementById('quadroMensagem').className = 'inicio';
}

function contasel() {
	var selecionado = 0;
	for (var ii=0; ii<document.formulario.elements.length; ii++) {
		if((document.formulario.elements[ii].type == 'checkbox') && (document.formulario.elements[ii].id != 'idseltodos')) {
			if(document.formulario.elements[ii].checked) selecionado++;
		}
	}
	return selecionado;
}

function primasel() {
	var selecionado = 0;
	for (var ii=0; ii<document.formulario.elements.length; ii++) {
		if((document.formulario.elements[ii].type == 'checkbox') && (document.formulario.elements[ii].id != 'idseltodos')) {
			if(document.formulario.elements[ii].checked) {
				selecionado = document.formulario.elements[ii].value;
				break;
			}
		}
	}
	return selecionado;
}

function seltodos(x) {
	for (var ii=0; ii<document.formulario.elements.length; ii++) {
		if(document.formulario.elements[ii].type == 'checkbox') document.formulario.elements[ii].checked = x.checked;
	}
}

function pulatela(url, w, h) {
	if(isNaN(w)) var w=750;
	if(isNaN(h)) var h=600;
	var y = screen.availHeight/2-h/2;
	var x = screen.availWidth/2-w/2;
	var aleatorio = Math.random();
	aleatorio = "a" + aleatorio;
	var ultimo = aleatorio.charAt(aleatorio.length-1);
	ultimo = ultimo + aleatorio.charAt(aleatorio.length-2);
	telapopup = window.open(url, 'tela'+ ultimo, 'width='+ w +', height='+ h +', left='+ x +', top='+ y +', scrollbars=1, resizable=1');
	if(!telapopup) alert('Atenção, o seu navegador está bloqueando as janelas popups, é necessário que você habilite a visualização de Popups.');
}

function popupform(formulario, w, h) {
	if(!window.focus) return true;

	if(isNaN(w)) var w=750;
	if(isNaN(h)) var h=600;
	var y = screen.availHeight/2-h/2;
	var x = screen.availWidth/2-w/2;
	var aleatorio = Math.random();
	aleatorio = "a" + aleatorio;
	var ultimo = aleatorio.charAt(aleatorio.length-1);
	ultimo = ultimo + aleatorio.charAt(aleatorio.length-2);
	window.open('', 'tela'+ ultimo, 'width='+ w +', height='+ h +', left='+ x +', top='+ y +', scrollbars=1, resizable=1');

	formulario.target = 'tela'+ ultimo;
	return true;
}

function veridata(x) {
	if (x != "") {
		if (x.indexOf('/') == -1) { alert('A data não se encontra no formato correto: dd/mm/aaaa'); return false; }
		else if (x.indexOf('/') == x.lastIndexOf('/')) {
			if (confirm('A data não possui ano, deseja prosseguir?') == true) {
				dia = x.substring(0,x.indexOf('/'));
				mes = x.substring(x.indexOf('/')+1, x.length);
				if ((mes>12) || (mes < 1) || (((mes==4) || (mes==6) || (mes==9) || (mes==11)) && (dia > 30)) || ((mes==2) && (dia>29)) || ((mes==1) || (mes==3) || (mes==5) || (mes==7) || (mes==8) || (mes==10) || (mes==12)) && (dia > 31)) {
					aviso('Data inválida!');
					return false;
				} else return true;
			}
			else return false;
		} else {
			dia = x.substring(0,x.indexOf('/'));
			mes = x.substring(x.indexOf('/')+1, x.lastIndexOf('/'));
			ano = x.substring(x.lastIndexOf('/')+1, x.length);
			if (((ano%4!=0) && (mes==2) && (dia==29)) || (mes>12) || (mes < 1) || (((mes==4) || (mes==6) || (mes==9) || (mes==11)) && (dia > 30)) || ((mes==2) && (dia>29)) || ((mes==1) || (mes==3) || (mes==5) || (mes==7) || (mes==8) || (mes==10) || (mes==12)) && (dia > 31)) {
				aviso('Data inválida!');
				return false;
			} else return true;
		}
	} else return true;
}

function virgula(x, casas) {

	if(casas == null) casas = 2;
	var num   = new Number(x);
	var temp  = num.toFixed(casas);
	var valor = temp.split('.');
	var deci  = valor[1];

	while(deci.length > 2) {
		if(deci.charAt(deci.length-1) == '0') deci = deci.substr(0, deci.length-1);
		else break;
	}
	return valor[0] +','+ deci;
}



function ativar(x, y) {
	if(y) {
		document.getElementById(x).className = 'caixa';
		document.getElementById(x).disabled = false;
	} else {
		document.getElementById(x).className = 'caixainativa';
		document.getElementById(x).disabled = true;
	}
}

/*Busca tags*/
function buscatag(x, e, tipo, nome) {
	if(e==40) { //Seta pra baixo seleciona a lista
		document.getElementById("lista_"+ nome).focus();
		document.getElementById("lista_"+ nome).selectedIndex = 0;
	}
	else if(e==9) return false;
	else if(e==27) sometagselecao(nome); //ESC some a busca
	else {
		var lista = document.getElementById('lista_'+ nome);
		if(x.value.length >= 2) {
			document.getElementById('ajax').src = 'ajax.php?com=buscaTags&nome='+ nome +'&tipo='+ tipo +'&busca='+ x.value;
		} else {
			for(a=lista.length; a>=0; a--) lista.options[a]=null;
			sometagselecao(nome);
		}
	}
}

function selecionatag(x, nome) {
	if(x.value) document.getElementById(nome).value = x.options[x.selectedIndex].value;
	sometagselecao(nome);
}

function eventotag(elemento, e, nome) {
	if((e==13) || (e==9)) selecionatag(elemento, nome);
	else if(e==27) {
		document.getElementById(nome).value = document.getElementById("texto_temp_"+ nome).value;
		somelistaselecao(nome);
	}
}

function sometagselecao(nome) {
	document.getElementById('lista_'+ nome).style.visibility = 'hidden';
	document.getElementById(nome).focus();
	return false;
}


/*Busca lista*/
function eventobusca(elemento, e, nome) {
	if(e==13) buscalista(elemento, document.getElementById("tipolista_"+ nome).value, 1, nome);
	else if(e==40) {
		document.getElementById("lista_"+ nome).focus();
		document.getElementById("lista_"+ nome).selectedIndex = 0;
	}
	else if(e==9) return false;
	else if(e==27) {
		document.getElementById("cod_"+ nome).value = document.getElementById("cod_temp_"+ nome).value;
		document.getElementById("texto_"+ nome).value = document.getElementById("texto_temp_"+ nome).value;
		somelistaselecao(nome);
	}
	else buscalista(elemento, document.getElementById("tipolista_"+ nome).value, 0, nome);
}

function eventoseleciona(elemento, e, nome, temevento) {
	if((e==13) || (e==9)) selecionalista(elemento, nome, temevento);
	else if(e==27) {
		document.getElementById("cod_"+ nome).value = document.getElementById("cod_temp_"+ nome).value;
		document.getElementById("texto_"+ nome).value = document.getElementById("texto_temp_"+ nome).value;
		somelistaselecao(nome);
	}
}

function buscalista(x, tipo, porcod, nome) {
	if(document.getElementById('editarcadastro_'+ nome)) {
		document.getElementById('editarcadastro_'+ nome).style.visibility = 'hidden';
	}
	document.getElementById('cod_'+ nome).value = 0;
	var lista = document.getElementById('lista_'+ nome);
	if((x.value.length >= 2) || ((porcod==1) && (x.value.length >= 1))) {
		document.getElementById('ajax').src = 'ajax.php?com=buscaLista&nome='+ nome +'&porcod='+ porcod +'&tipo='+ tipo +'&busca='+ x.value;
	} else {
		for(a=lista.length; a>=0; a--) lista.options[a]=null;
		somelistaselecao(nome);
	}
}

function selecionalista(x, nome, temevento) {
	if(x.value) {
		document.getElementById('cod_'+ nome).value = x.value;
		document.getElementById('texto_'+ nome).value = x.options[x.selectedIndex].text;
		document.getElementById('cod_temp_'+ nome).value = x.value;
		document.getElementById('texto_temp_'+ nome).value = x.options[x.selectedIndex].text;
	}
	if(temevento) eval("aoselecionar_"+ nome +"();");
	somelistaselecao(nome);
}

function somelistaselecao(nome) {
	document.getElementById('lista_'+ nome).style.visibility = 'hidden';
	if((document.getElementById('cod_'+ nome).value != '0') && (document.getElementById('editarcadastro_'+ nome))) {
		document.getElementById('editarcadastro_'+ nome).style.visibility = 'visible';
	}
}


function inserircadastro(x, nome) {
	if((x==1) || (x==2) || (x==5) || (x==6)) {
		if(x == 5) x = 1;
		else if(x == 6) x = 2;
		pulatela("agenda.php?com=inserir&pop=true&nome_lista="+ nome +"&ct="+ x);
	}
	else if(x==3) pulatela("produtos.php?com=inserir&pop=true&nome_lista="+ nome);
}

function editarcadastro(x, nome) {
	var codlista = document.getElementById('cod_'+ nome).value;
	if((x==1) || (x==2) || (x==5) || (x==6)) {
		if(x == 5) x = 1;
		else if(x == 6) x = 2;
		pulatela("agenda.php?com=alterar&nome_lista="+ nome +"&pop=true&ct="+ x +"&cod="+ codlista);
	}
	else if(x==3) pulatela("produtos.php?com=alterar&nome_lista="+ nome +"&pop=true&cod="+ codlista);
}

function limpalista(nome) {
	document.getElementById('cod_'+ nome).value = 0;
	document.getElementById('texto_'+ nome).value = '';
	document.getElementById('editarcadastro_'+ nome).style.visibility = 'hidden';
}

function aoselecionar_produtoEspecialNF() {
	completaDadosProduto();
}


/*QUADRINHO ETIQUETAS*/
function selecionaQuadrinhoEtiqueta(x) {
	document.getElementById('quadroInicioEtiqueta').value = x;
	for(ii=0; ii<=document.getElementById('totalQuadrinhos').value; ii++) {
		if(ii < x) document.getElementById('quadrinho'+ii).style.background = '#FFFFFF';
		else document.getElementById('quadrinho'+ii).style.background = '#6699FF';
	}
}

function msg(texto, titulo) {
	if((titulo==undefined) || (titulo=='')) titulo = 'Mensagem';
	document.getElementById('caixa_msg').innerHTML = '<fieldset><legend>'+ titulo +'</legend>'+ texto +'</fieldset>';
	openDivUp('caixa_msg');
}

function mudaTipoDoc(campo, x) {
	for(ii=x; ii<50; ii++) {
		if($('tipodoc'+ ii)) $('tipodoc'+ ii).value = campo.value;
		else break;
	}
}

function RecalcEntrada(campo, x, total) {
	var conta = 0;
	var passado = 0;
	var parc = 0;

	for(ii=(x+1); ii<50; ii++) {
		if($('valor'+ ii)) conta = conta+1;
		else break;
	}

	for(ii=1; ii<=x; ii++) {
//		alert(passado);
		passado += ponto($('valor'+ ii).value);
	}

	parc = (total - passado) / conta;
	for(ii=(x+1); ii<50; ii++) {
		if($('valor'+ ii)) $('valor'+ ii).value = virgula(parc);
		else break;
	}
}

function listarSerial(venda) {
	ajax0('subLista', 'com=listarSerial&venda='+ venda);
}

function addSerial(campo, evento, venda) {
	if(evento == 13) {
		ajax0('subLista', 'com=addSerial&venda='+ venda +'&serial='+ campo.value);
		campo.value = '';
	}
}

function remSerial(prod, chave, venda) {
	ajax0('subLista', 'com=remSerial&venda='+ venda +'&prod='+ prod +'&chave='+ chave);
}

function selProxCampo(nome, cod) {
	cod++;
	if(document.getElementById(nome + cod)) document.getElementById(nome + cod).select();
}

/*AJAX*/
var fila=[];
var ifila=0;

function formajax(x) {
	ajax0(x.destino.value, "com="+ x.com.value);
}

function ajax0(destino, comando, pagina) { //ajax que retorna informação em algum lugar
	document.getElementById(destino).innerHTML = "<div class='centro'>Carregando...</div>";
	if((pagina != "") && (pagina != undefined)) var url = pagina +"?ajax=true&"+ comando;
	else var url = "ajax.php?"+ comando;
	fila[fila.length]=[destino, url];
	if((ifila+1)==fila.length) ajax2();
}

function ajax1(comando, pagina) { //ajax sem retorno de dados
	if((pagina != "") && (pagina != undefined)) var url = pagina +"?ajax=true&"+ comando;
	else var url = "ajax.php?"+ comando;
	fila[fila.length]=['-semdestino-', url];
	if((ifila+1)==fila.length) ajax2();
}

function ajax2() { document.getElementById('ajax').src = fila[ifila][1]; }

function ajaxretorno() {
	if(ifila<fila.length) {
		if(fila[ifila][0] != '-semdestino-') {
			var resposta = window.frames['ajax'].document.getElementById('quadroresposta').innerHTML;
			document.getElementById(fila[ifila][0]).innerHTML = resposta;
		}
		ifila++;
		if(ifila<fila.length) setTimeout("ajax2();",20);
	}
}

/*Formas de pagamento*/
function atualizarFormaPgto() {
	ajax0('quadroPgto', 'com=atualizarFormaPgto');
}

function mostra_formas_pgto() {
	if(document.getElementById('quadroParcelas')) document.getElementById('quadroParcelas').innerHTML = '';
	ajax0('quadro_muda_forma', 'com=formaPgto');
	ajax1('com=formaPgtoCom');
	openDivUp('quadro_muda_forma');
}

function pgtoforma(naogerar) {
	formaselecionada = document.getElementById('forma_pgto');
	var x = formaselecionada;
	if(!naogerar) {
		var listaparcelas = document.getElementById('parcelas');
		for(a=listaparcelas.length; a>=0; a--) listaparcelas.options[a]=null;
		listaparcelas.options[listaparcelas.length] = new Option('A Vista',0);
		for(ii=1; ii<=banco[x.value]['parcelas']; ii++) listaparcelas.options[listaparcelas.length] = new Option(ii,ii);
	}
	if(banco[x.value]['taxa'] != 0) {
		document.getElementById('taxafixa').innerHTML = "<label for='taxa'>Taxa fixa (R$ "+ virgula(banco[x.value]['taxa']) +"):</label>";
		document.getElementById('taxa').value = banco[x.value]['taxa'];
		if(!naogerar) document.getElementById('taxa').checked = true;

	} else {
		document.getElementById('taxafixa').innerHTML = "<label for='taxa'>Taxa fixa (R$ 0,00):</label>";
		document.getElementById('taxa').value = 0;
		if(!naogerar) document.getElementById('taxa').checked = false;
	}
	pgtoparcelas(naogerar);
}

function pgtoparcelas(naogerar) {
	var x = document.getElementById('parcelas');

	//Se tem desconto a vista
	if(banco[formaselecionada.value]['descontoavista'] != 0) {
		document.getElementById('labeldesc').innerHTML = "<label for='descontoavista'>Desconto a vista ("+ virgula(banco[formaselecionada.value]['descontoavista']) +"%):</label>";
		document.getElementById('descontoavista').value = banco[formaselecionada.value]['descontoavista'];
	} else {
		document.getElementById('labeldesc').innerHTML = "<label for='descontoavista'>Desconto a vista (0,00%):</label>";
		document.getElementById('descontoavista').value = 0;
	}

	//Se tem juros
	if(banco[formaselecionada.value]['juros'] != 0) {
		document.getElementById('labeljuros').innerHTML = "<label for='juros'>Com juros ("+ virgula(banco[formaselecionada.value]['juros']) +"%):</label>";
		document.getElementById('juros').value = banco[formaselecionada.value]['juros'];
	} else {
		document.getElementById('labeljuros').innerHTML = "<label for='juros'>Com juros (0,00%):</label>";
		document.getElementById('juros').value = 0;
	}

	//Se for a vista, marca o desconto
	if(x.value == 0) {
		//Tipo de entrada
		document.getElementById('labeltipo1').className = 'labelOff';
		document.getElementById('tipoentrada').className = 'campoOff';
		document.getElementById('tipoentrada').disabled = true;
		document.getElementById('tipoentrada').selectedIndex = 0;
		//Valor da entrada
		document.getElementById('valorentrada1').className = 'labelOff';
		document.getElementById('entrada').className = 'campoOff';
		document.getElementById('entrada').disabled = true;
		document.getElementById('entrada').value = 0;
		document.getElementById('juros').checked = false;

		if(banco[formaselecionada.value]['descontoavista'] != 0) {
			if(!naogerar) document.getElementById('descontoavista').checked = true;
		}
	} else { //Se não, marca o juros
		document.getElementById('labeltipo1').className = 'labelOn';
		document.getElementById('tipoentrada').className = 'caixa';
		document.getElementById('tipoentrada').disabled = false;

		if(!naogerar) {
			document.getElementById('descontoavista').checked = false;
			if(x.value > banco[formaselecionada.value]['parcsemjuros']) document.getElementById('juros').checked = true;
			else document.getElementById('juros').checked = false;
		}
	}
	pgtoentrada(naogerar);
}

function pgtoentrada(naogerar) {
	var x = document.getElementById('tipoentrada');
	if(x.value == 3) { //COM ENTRADA DIFERENTE
		document.getElementById('valorentrada1').className = 'labelOn';
		document.getElementById('entrada').className = 'caixa';
		document.getElementById('entrada').disabled = false;

	} else {
		document.getElementById('valorentrada1').className = 'labelOff';
		document.getElementById('entrada').className = 'campoOff';
		document.getElementById('entrada').disabled = true;
		document.getElementById('entrada').value = 0;
	}
	pgtocalcula();
}

function pgtocalcula() {
	var cforma = formaselecionada.value;
	var cvalor = parseFloat(document.getElementById('valor').value);
	var ctipo = parseFloat(document.getElementById('tipoentrada').value);
	var centrada = parseFloat(ponto(document.getElementById('entrada').value));
	var cparcelas = parseFloat(document.getElementById('parcelas').value);
	var cdescvista = document.getElementById('descontoavista');
	var cjuros = document.getElementById('juros');
	var ctaxa = document.getElementById('taxa');
	var cfrete = 0;
	var cseguro = 0;
	var cdespesas = 0;
	var cdesconto_dado = 0;
	if(document.getElementById('frete')) cfrete = parseFloat(ponto(document.getElementById('frete').value));
	if(document.getElementById('seguro')) cseguro = parseFloat(ponto(document.getElementById('seguro').value));
	if(document.getElementById('despesas')) cdespesas = parseFloat(ponto(document.getElementById('despesas').value));
	if(document.getElementById('desconto_dado')) cdesconto_dado = parseFloat(ponto(document.getElementById('desconto_dado').value));
	var cdespesasgeral = cfrete+cseguro+cdespesas-cdesconto_dado;
	if(isNaN(centrada)) centrada = 0;
	if(isNaN(cdespesasgeral)) cdespesasgeral = 0;
	if(cdescvista.checked) cdescvista = banco[cforma]['descontoavista']; else cdescvista = 0;
	if(cjuros.checked) cjuros = banco[cforma]['juros']; else cjuros = 0;
	if(ctaxa.checked) ctaxa = banco[cforma]['taxa']; else ctaxa = 0;
	var t = '<b>Forma: '+ banco[cforma]['nome'] +'</b><br/>';

	retorno = parcelamento(cvalor, cparcelas, cjuros, cdescvista, centrada, ctaxa, cdespesasgeral, ctipo);
	//parcelamento volta: retorno['entrada']; retorno['parcela']; retorno['total'];

	if(cparcelas == 0) {
		t += 'A vista, no valor total de '+ virgula(retorno['total']);
	} else {
		if(ctipo == 1) {
			t += '0+'+ cparcelas +'x de R$ '+ virgula(retorno['parcela']);
		} else if(ctipo == 2) {
			t += '1+'+ cparcelas +'x de R$ '+ virgula(retorno['parcela']);
		} else if(ctipo == 3) {
			t += 'Entrada de R$ '+ virgula(retorno['entrada']) +' + '+ cparcelas +'x de R$ '+ virgula(retorno['parcela']);
		}
	}
	if(cdescvista != 0) t += ', já com desconto de '+ virgula(cdescvista) +'%';
	if(ctaxa != 0) t += ', já com taxa fixa de R$ '+ virgula(ctaxa);
	if(cjuros != 0) t += ', já com juros de '+ virgula(cjuros) +'% ao período';

	t += '.<br/>Total: R$ '+ virgula(retorno['total']);

	document.getElementById('total').value = retorno['total'];
	if(ctipo == 2) document.getElementById('entrada').value = virgula(retorno['parcela']);
	document.getElementById('parcela').value = retorno['parcela'];
	document.getElementById('resultadopgto').innerHTML = t;
}

function parcelamento(valor, prests, juros, descontoavista, entrada, taxa, despesas, tipo) {
	resposta = new Array();
	var soma = valor;
	if(descontoavista*1!=0) soma = soma-(soma*descontoavista/100); //desconto
	soma = soma+taxa; //taxa fixa
	soma = soma+despesas; //despesas, frete e seguro;
	juros = juros/100; //juros

	if(prests == 0) { //a vista
		resposta['entrada'] = 0;
		resposta['parcela'] = 0;
		resposta['total'] = soma;
	} else { //parcelado
		if(tipo==2) { //com entrada igual
			if(juros*1!=0) { //com juros
				parcela = soma * (juros /((1+juros)-Math.pow((1+juros), -prests)));
				entrada = parcela;
			} else { //sem juros
				parcela = (soma) / (parseFloat(prests)+1);
				entrada = parcela;
			}

		} else { //sem entrada ou entrada diferente
			if(entrada*1!=0) soma = soma-entrada; //se tem entrada, tira do valor a parcelar

			if(juros*1!=0) { //com juros
				parte = Math.pow((1 + juros), prests);
				parcela = (soma * ((juros * parte) / (parte - 1)));
			} else { //sem juros
				parcela = (soma) / prests;
			}
		}
		resposta['entrada'] = entrada;
		resposta['parcela'] = parcela;
		resposta['total'] = (parcela*prests)+entrada;
	}
	return resposta;
}

/*Outras despesas de venda*/
function mudar_outras_despesas() {
	ajax0('quadroDespesas', 'com=outrasDespesasVenda');
}

function agenda() {
	pulatela('agenda.php?pop=true');
}

function ajuda(ajudanfe) {
	if(ajudanfe == 1) pulatela('ajudanfe.php');
	else pulatela('ajuda.php');
}

function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else begin += 2;
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}

function pega_ref() {
	document.formulario.afiliado.value = getCookie("egestorref");
}


/*IMPEDIR ATUALIZAR POR F5*/
function showKeyCode(e) {
	var keycode = (window.event) ? event.keyCode : e.keyCode;
	if((version.indexOf('MSIE') != -1)) {
		if(keycode == 116) {
			event.keyCode = 0;
			event.returnValue = false;
			return false;
		}
	}
	else if(keycode == 116) return false;
}
var version = navigator.appVersion;
document.onkeydown = showKeyCode;