// JavaScript Document
//Funções JavaScript
function passa_foco(origem, destino, largura) {
	if (document.getElementById(origem).value.length == largura) {
		document.getElementById(destino).focus();
	}
}

function proximoCampo(campo) {
	var campos = document.getElementsByTagName('input');
	if (document.getElementById(campo).value.length == document.getElementById(campo).getAttribute("maxlength")) {
		for (i=0;i<campos.length;i++) {
			if (document.getElementById(campo) == campos[i]) {
				if (i < campos.length - 1) {
					campos[i+1].focus();
				}
				break;
			}
		}
	}
}
function mascara_hora(campo, digitos) {
	if (document.getElementById(campo).value.length == 2) {
		document.getElementById(campo).value += ":";
	}
	if (digitos == 8) {
		if (document.getElementById(campo).value.length == 5) {
			document.getElementById(campo).value += ":";
		}
	}
	proximoCampo(campo);
}
function mascara_cpf(campo) {
	if (document.getElementById(campo).value.length == 3) {
		document.getElementById(campo).value += ".";
	}
	if (document.getElementById(campo).value.length == 7) {
		document.getElementById(campo).value += ".";
	}
	if (document.getElementById(campo).value.length == 11) {
		document.getElementById(campo).value += "-";
	}
	proximoCampo(campo);
}

function mascara_data(campo) {
	if (document.getElementById(campo).value.length == 2) {
		document.getElementById(campo).value += "/";
	}
	if (document.getElementById(campo).value.length == 5) {
		document.getElementById(campo).value += "/";
	}
	proximoCampo(campo);
}

function mascara_cep(campo) {
	var cam = document.getElementById(campo);
	if (cam.value.length == 5) {
		cam.value += "-";
	}
	proximoCampo(campo);
}

function exibeMenu(id) {
	document.getElementById(id).style.display = "block";
}

function escondeMenu(id) {
	document.getElementById(id).style.display = "none";
}
function verifica_opcao(pagina, identificacao, tot) {
	var resultado;
	var IDop;
	for (i=1;i<=tot;i++) {
		if (document.getElementById(identificacao+String(i)).checked != false) {
			resultado = true;
			IDop = document.getElementById(identificacao+String(i)).value;
		}
	}
	if (resultado == true) {
		window.location = pagina+"&IDop="+IDop;
	} else {
		alert("Escolha uma opção de horário para realizar a inscrição");
	}
}

function mascara_preco(id) {
	var div = document.getElementById(id);
	if (div.value.length == 1) {
		div.value = '0,0'+div.value;
	} else if (div.value.length == 5 && div.value.indexOf('0,0') > -1) {
		div.value = div.value.replace('0,0', '');
		div.value = '0,'+div.value;
	} else {
		if (div.value.indexOf('0,') == 0) {
			div.value = div.value.replace('0,', '');
		}
		var str = div.value.charAt(div.value.length-2);
		str += div.value.charAt(div.value.length-1);
		var resto = div.value.charAt(0);
		for (var i=1;i<(div.value.length-2);i++) {
			if (div.value.charAt(i) != ",") {
				resto += div.value.charAt(i);
			}
		}
		
		div.value = resto + "," + str;
	}
}

function mascara_telefone(id) {
	var campo = document.getElementById(id);
	if (campo.value.length == 1) {
		campo.value = "(" + campo.value;
	}
	if (campo.value.length == 3) {
		campo.value += ") ";
	}
	if (campo.value.length == 9) {
		campo.value += "-";
	}
	proximoCampo(id);
}	

function addOpcao(numero) {
	ajax = getAjax();
	link = document.getElementById('linkAdd');
	attrLink = link.getAttribute('onclick');
	link.setAttribute('onclick', "");
	var elemento = document.getElementById('msgAjax');
	var resposta = document.getElementById('abrigaOpcoes');
	/*CAPTURAR DADOS DOS FORMULARIOS PARA SEREM RECUPERADOS POSTERIORMENTE*/
	var inputs = resposta.getElementsByTagName('input');
	var totDados = inputs.length;
	var arrDados = new Array(totDados);
	for (var i=0;i<totDados;i++) {
		arrDados[i] = inputs[i].value;
	}
	ajax.open("POST", "http://www.abrae.org.br/processa.asp?object=opcao", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.onreadystatechange = function() {
		//status carregando
		if(ajax.readyState == 1) {
			elemento.innerHTML = "<img src='../carregando.gif' alt='Carregando...'>";
		}
		//status pronto
		if(ajax.readyState == 4) {
			//pagina encontrada
			if(ajax.status == 200) {
				var numOpcoes = document.getElementById('curso_numOpcoes');
				elemento.innerHTML = "";
				link.setAttribute('onclick', "javascript:addOpcao("+(Number(numero)+1)+")");
				var resp = ajax.responseText;
				resposta.innerHTML += resp;
				resposta.innerHTML += '<a href="javascript:removeOpcao();" id="linkRemove'+numero+'">Remover opcao</a>';
				inputs = resposta.getElementsByTagName('input');
				for (i = 0; i<totDados;i++) {
					inputs[i].value = arrDados[i];
				}
				
				document.getElementById('curso_numOpcoes').value = String(Number(numOpcoes.value) + 1);
			} else {
				elemento.innerHTML = "Erro ao carregar os dados";
				link.setAttribute('onclick', attrLink);
			}
		}
	}
	ajax.send("ind="+numero);
	
}

function removeOpcao() {
	var resposta = document.getElementById('abrigaOpcoes');
	var inputs = resposta.getElementsByTagName('input');
	var link = document.getElementById('linkAdd');
	var totDados = inputs.length;
	var numOpcoes = document.getElementById('curso_numOpcoes');
	var arrDados = new Array(totDados);
	for (var i=0;i<totDados;i++) {
		arrDados[i] = inputs[i].value;
	}
	
	var div = document.getElementById('formOpcaoDeCurso'+(Number(numOpcoes.value)-1));
	resposta.removeChild(div);
	link.setAttribute('onclick', "javascript:addOpcao("+(Number(numOpcoes.value)-1)+")");
	inputs = resposta.getElementsByTagName('input');
	totDados = inputs.length;
	var linkRemove = document.getElementById('linkRemove'+(Number(numOpcoes.value)-1));
	resposta.removeChild(linkRemove);
	for (i = 0; i<totDados;i++) {
		inputs[i].value = arrDados[i];
	}
	numOpcoes.value = Number(numOpcoes.value) - 1;
	document.getElementById('curso_numOpcoes').value = numOpcoes.value;
}
var janela;

function cadastraCidade(def, ind) {
	var continua = true;
	if (janela == null) {
		janela = window.open("http://www.abrae.org.br/popup.asp?pagina=cidade", "popupCidade", "height=300, width=300, scrollbars=yes");
	} else if (janela.closed) {
		continua = false;
		carregaCidades(ind);
	} else if (janela != null && def != "set") {
		alert("A janela de cadastro já está aberta");
	}
	if (continua) {
		setTimeout(function(){cadastraCidade("set", ind);}, 2000);
	}
}

function carregaCidades(ind) {
	ajax = getAjax();
	var div = document.getElementById('cidadeSelect');
	var cidade = document.getElementById('cidade_'+ind+'_cidade');
	div.removeChild(cidade);
	var elemento = document.getElementById('cidadeSelect');
	
	ajax.open("POST", "http://www.abrae.org.br/processa.asp?object=lugar&tipo=cidade", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.onreadystatechange = function() {
		//status carregando
		if(ajax.readyState == 1) {
			elemento.innerHTML = "<img src='../carregando.gif' alt='Carregando...'>";
		}
		//status pronto
		if(ajax.readyState == 4) {
			//pagina encontrada
			if(ajax.status == 200) {
				elemento.innerHTML = "";
				div.innerHTML = ajax.responseText;
			} else {
				elemento.innerHTML = "Erro ao carregar os dados! Tente novamente";
			}
		}
	}
	var uf = document.getElementById('estado_'+ind+'_estado').value;
	ajax.send("uf="+uf);
	janela = null;
}
function passa_imagem(pag) {
	var imagens = document.getElementById('str_imagens').value;
	var sep = imagens.split(";");
	document.getElementById('imagem_interna').innerHTML = "<img src='imagens/"+sep[pag-1]+"' class='imgTag' />";
	for (i=0;i<document.getElementById('qtdImages').value;i++) {
		var d = document.getElementById('pag'+i);
		if (parseInt(i+1) == parseInt(pag)) {
			d.setAttribute("class", "numero_imagem_active");
		} else {
			d.setAttribute("class", "numero_imagem");
		}
		d.innerHTML = "<a href=\"javascript:passa_imagem('"+(i+1)+"')\">"+(i+1)+"</a>";
	}
}
function abre_janela(pagina, w, h) {
	return window.open (pagina, 'popup', "toolbar=yes,width="+w+",height="+h);
}
var pag;
var inter;
function cadAutor(pagina, set) {
	pag = abre_janela(pagina,600,600);
	pag.document.getElementsByTagName('body')[0].onunload = "window.location.href = window.location.href";
}

function carregaCategoria(id,nome) {
	var ajax = getAjax();
	if (id == 0) return false;
	var pass = false;
	var arrCatsPai = new Array();
	var limite;
	var cont = 0;
	var elemento = document.getElementById('div_categoria');
	while (document.getElementById('cat_'+cont) != null) {
		cont++;
	}
	arrCatsPai[0] = document.getElementById(nome).selectedIndex;
	for (i=0;i<cont;i++) {
		arrCatsPai[i+1] = document.getElementById('cat_'+i).selectedIndex;
	}
	ajax.open("GET","processa_categoria.php?ac=ajax&id="+id+"&acao=ver",true);
	ajax.onreadystatechange = function() {
		if (ajax.readyState == 4) {
			if (ajax.status == 200) {
				var text = ajax.responseText;
				if (text.substr(0,1) == "0") return false;
				var arr = text.split(";");
				var nivel = arr[1];
				var catPai = arr[2];
				
				ajax.open("GET","processa_categoria.php?ac=ajax&id="+id+"&nome="+nome,true);
				ajax.onreadystatechange = function() {
					//status carregando
					if(ajax.readyState == 1) {
						if (!pass) {
							elemento.innerHTML += "<img id='img_Ajax_cat' src='../imagens/carregando.gif' alt='Carregando...' />";
							pass = true;
						}
					}
					//status pronto
					if(ajax.readyState == 4) {
						//pagina encontrada
						if (document.getElementById('img_Ajax_cat')) elemento.removeChild(document.getElementById('img_Ajax_cat'));
						if(ajax.status == 200) {
							if (nivel >= cont) {
								var d = document.getElementById(nome);
								d.setAttribute("name","cat_"+cont);
								d.setAttribute("id","cat_"+cont);
								elemento.innerHTML += ajax.responseText;
								limite = nivel;
							} else {
								var d;
								for (i=cont;i>nivel;i--) {
									d = document.getElementById('cat_'+parseInt(i));
									if (d != null) elemento.removeChild(d);
								}
								d = document.getElementById(nome);
								if (d != null) elemento.removeChild(d);
								elemento.innerHTML += ajax.responseText;
								limite = cont;
							}
							for (i=0;i<=limite;i++) {
								document.getElementById('cat_'+i).selectedIndex = arrCatsPai[limite-i];
							}
						} else {
							elemento.innerHTML = "Erro ao carregar os dados! Tente novamente";
						}
					}
				}
				ajax.send(null);
			}
		}
	}
	ajax.send(null);
}
function exibeFlash(swf, width, height) {
	var cache;
	var wmode;
	noCache = cache || cache == undefined ? "" : "?" + new Date();
	wmode = wmode || wmode == undefined ? "opaque" : "transparent"; 
	monta_swf = "";
	monta_swf += "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0\" width=\""+ width +"\" height=\""+ height +"\" title=\"\">";
	monta_swf += "<param name=\"movie\" value=\""+ swf + noCache +"\" />";
	monta_swf += "<param name=\"quality\" value=\"high\" />";
	monta_swf += "<param name=\"wmode\" value=\"transparent\" />";
	monta_swf += "<param name=\"menu\" value=\"0\" />";
	monta_swf += "<param name=\"wmode\" value=\""+ wmode +"\" />";
	monta_swf += "<param name=\"scale\" value=\"exactFit\" />";
	monta_swf += "<embed src=\""+ swf + noCache +"\" quality=\"high\" wmode=\""+ wmode +"\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" width=\""+ width +"\" height=\""+ height +"\"></embed>";
	monta_swf += "</object>";

	document.write(monta_swf);
}
function number_format(num,digitosDecimais,pDec) {
	num = parseFloat(num);
	num = num.toFixed(digitosDecimais);
	resp = num.replace(/\./,pDec);
	return resp;
}

function calculaFrete(campo, area, tipo) {
	var ajax = getAjax();
	var area = document.getElementById(area);
	var c = document.getElementById(campo);
	var valor = c.value;
	padrao = /([0-9]{5}-[0-9]{3}|[0-9]{8})/;
	if (!padrao.test(valor)) {
		alert("Informe o valor correto do cep");
		return false;
	}
	var cont = 0;
	var exec = false;
	area.innerHTML = "Carregando...";
	do {
		ajax.open("GET","processa_frete.php?cep="+valor, true);
		ajax.onreadystatechange = function() {
			if (ajax.readyState == 4) {
				if (ajax.status == 200) {
					var resp = ajax.responseText;
					if (resp == "false") {
						exec = true;
						cont++;
						if (cont > 3) {
							exec = false;
							area.innerHTML = "Aparentemente o servidor que calcula o frete est&aacute; fora do ar. Ser&aacute; ent&atilde; pago um valor m&eacute;dio";
						}
					} else {
						var text = resp.split("%");
						if (text.length == 1) {
							area.innerHTML = ajax.responseText;
						} else {
							var sedex = text[0].replace(/SEDEX:/,"");
							sedex = parseFloat(sedex);
							sedex = sedex.toFixed(2);
							sedex += "";
							sedex.replace(/\./,",");
							var pac = text[1].replace(/PAC:/,"");
							pac = parseFloat(pac);
							pac = pac.toFixed(2);
							pac += "";
							pac.replace(/\./,",");
							document.getElementById('preco_frete').innerHTML = "";
							if (tipo != "none") {
								if (tipo == "SEDEX") {
									var selSed = 'checked="checked"';
									var selPac = '';
									selecionaFrete(sedex,"SEDEX");
								} else {
									var selSed = '';
									var selPac = 'checked="checked"';
									selecionaFrete(pac,"PAC");
								}
							}
							var t = "<input type='radio' name='frete' id='sedex' value='"+text[0]+"' onclick='javascript:selecionaFrete("+sedex+",\"SEDEX\")' "+selSed+" />Sedex: R$"+sedex;
							t += "<br /><input type='radio' name='frete' value='"+text[1]+"' onclick='javascript:selecionaFrete("+pac+",\"PAC\")' "+selPac+" />Pac: R$"+pac;
							area.innerHTML = t;
						}
					}
				} else {
					area.innerHTML = "Ocorreram erros na requisi&ccedil;&atilde;o no servidor. Aperte F5 para recarregar a página";
				}
			}
		}
		ajax.send(null);
	} while (exec);
}
var perm = true;
function selecionaFrete(valor, tipo) {
	var ajax = getAjax();
	perm = false;
	ajax.onreadystatechange = null;
	var v = document.getElementById("valor_total").value;
	v = v.replace(/,/,".");
	v = parseFloat(v);
	var total = v;
	document.getElementById("preco_total").innerHTML = number_format(v+parseFloat(valor),2,",");
	document.getElementById('preco_frete').innerHTML = "R$"+number_format(valor,2,",");
	ajax.open("GET","processa_frete.php?ac=guardaValor&frete="+tipo+"&valor="+valor,true);
	ajax.onreadystatechange = function() {
		if (ajax.readyState == 1) {
		
		}
		if (ajax.readyState == 4) {
			if (ajax.status == 200) {
				perm = true;
			} else {
				alert("Falha na conexao com o Servidor. Aperte F5 para atualizar a página");
			}
		}
	}
	ajax.send(null);
}
function goPagConfirm(pag) {
	if (document.getElementById('preco_frete').innerHTML == "") {
		alert("Selecione o frete");
		return false;
	}
	if (perm) {
		window.location = pag;
	} else {
		alert("Uma operação está sendo concluída. Tente novamente");
	}
}
function rodape() {
	var hP = document.getElementById('principal');
	var hW = document.getElementById('lateral');
	var h = hP.clientHeight;
	var hL = hW.clientHeight;
	if (hL < h) {
		hW.style.height = h+"px";
	} else {
		hP.style.height = hL+"px";
	}
}
function jogaRodape() {
	var rod = document.getElementById('rodape');
	var cont = document.getElementById('conteudo');
	var menu = document.getElementById('menu');
	var cab = document.getElementById('cabecalho');
	var tam = cont.clientHeight - menu.clientHeight - cab.clientHeight + rod.clientHeight;
	rod.style.position = "absolute";
	rod.style.bottom = "auto";
	rod.style.top = tam+"px";
}
function aumentaFonte(el,valor) {
	var el = document.getElementById(el);
	var valor = (parseInt(el.style.fontSize) + valor);
	if ((valor < 50)) {
		el.style.fontSize =  valor + "px";
	}
	el.style.fontSize = valor + "px";
	jogaRodape();
}
function diminuiFonte(el,valor) {
	var el = document.getElementById(el);
	var valor = (parseInt(el.style.fontSize) - valor);
	if ((valor > 4)) {
		el.style.fontSize =  valor + "px";
	}
	jogaRodape();
}
function setTamanhoFonte(el,valor) {
	var el = document.getElementById(el);
	el.style.fontSize =  valor + "px";
	jogaRodape();
}