
var iniciou = false;
var raiz = '';
if (location.host.replace('www.', '') == 'eleve.dev') {
	var raiz = '/' + location.pathname.split('/')[1];
}
var lazy = document.querySelectorAll(".grande");
for (var i = 0; i < lazy.length; i++) {
	let tmp = document.createElement('span');
	tmp.classList.add('carregando');
	tmp.innerHTML = '<span class="spinner-border" role="status" aria-hidden="true"></span>';
	if (lazy[i].nodeName == 'IMG') {
		lazy[i].after(tmp);
	} else {
		lazy[i].appendChild(tmp);
	}
}

function existe(qual) {
	var objetos = document.querySelectorAll(qual);
	return objetos.length > 0;
}
iniciou = true;
var to_pace = setInterval(function () {
	if (existe('#preloader')) {
		clearInterval(to_pace);
		document.querySelector('#preloader_pct').style.width = '100%!important';
		document.querySelector('#preloader_pct').style.overflow = 'visible';
		setTimeout(function () {
			let pre = document.querySelector('#preloader');
			pre.style.transform = 'scale(1.5)';
			pre.style.opacity = '0';
			setTimeout(function () {
				let style = document.createElement('style');
				document.head.appendChild(style);
				style.type = 'text/css';
				style.appendChild(document.createTextNode('#preloader{display:none!important}'));
			}, 700);
		}, 100);
	}
}, 100);
//verifica se objeto está visível
var isInViewport = function (elem) {
	let b = elem.getBoundingClientRect();
	if (b.top < 0 && b.bottom > (window.innerHeight || document.documentElement.clientHeight)) {
		return true;
	}
	if (b.top >= 0 && b.top <= (window.innerHeight || document.documentElement.clientHeight)) {
		return true;
	}
	if (b.bottom >= 0 && b.bottom <= (window.innerHeight || document.documentElement.clientHeight)) {
		return true;
	}
	return false;
};
//substitui classes animadas
var classes = ['zoomIn', 'fadeIn', 'fadeInDown', 'fadeInUp', 'fadeInLeft', 'fadeInRight', 'slideInUp', 'slideInDown'];
function anima() {
	let total = 0;
	classes.forEach((classe) => {
		var objetos = document.querySelectorAll('.' + classe);
		objetos.forEach((obj) => {
			total++;
			if (isInViewport(obj)) {
				obj.classList.add("animate__animated", "animate__" + classe);
				// obj.classList.remove(classe);
				obj.style.opacity = 1;
			} else {
				obj.classList.remove("animate__animated", "animate__" + classe);
				obj.style.opacity = 0;
			}
		});
	});
	if (total == 0) {
		document.removeEventListener('scroll', anima, false);
	}
}
document.addEventListener('scroll', anima, false);
anima(null);
setInterval(anima, 1000);
//redireciona caso idioma seja obrigatório
if (existe('#redir')) {
	history.pushState({ pageID: 'pagina' }, 'Redirecionamento de idioma', document.querySelector('#redir').getAttribute('data-redir'));
	document.querySelector('#redir').remove();
	var idioma = 'pt';
} else {
	var idioma = location.pathname.substr(raiz.length + 1, 2);
}
//duplica o menu fixed
if (existe('.menu_duplica')) {
	var elem = document.querySelector('.menu');
	var clone = elem.cloneNode(true);
	clone.classList.remove('fixed-top');
	elem.after(clone);
}
//animação nos botões
document.body.addEventListener('click', (event) => {
	let botao = null;
	if (event.target.nodeName === 'BUTTON' || event.target.classList.contains('btn')) {
		botao = event.target;
	}
	if (botao != null) {
		// var x=event.pageX - botao.offsetLeft;
		// var y=event.pageY - botao.offsetTop;
		let x = event.pageX - (botao.getBoundingClientRect().left + document.documentElement.scrollLeft);
		let y = event.pageY - (botao.getBoundingClientRect().top + document.documentElement.scrollTop);
		let duracao = 500;
		let quadros, inicio;
		let passo = function (timestamp) {
			if (!inicio) {
				inicio = timestamp;
			}
			let quadro = timestamp - inicio;
			if (quadro < duracao) {
				let easing = (quadro / duracao) * (2 - (quadro / duracao));
				let circulo = "circle at " + x + "px " + y + "px";
				let cor = botao.classList.contains('bg-white') || botao.classList.contains('btn-light') ? "rgba(0,0,0," + (0.75 * (1 - easing)) + ")" : "rgba(255,255,255," + (0.75 * (1 - easing)) + ")";
				let para = 90 * easing + '%';
				botao.style.backgroundImage = "radial-gradient(" + circulo + ", " + cor + " " + para + ", transparent " + para + ")";
				quadros = window.requestAnimationFrame(passo);
			} else {
				botao.style.backgroundImage = "none";
				window.cancelAnimationFrame(quadros);
			}
		};
		quadros = window.requestAnimationFrame(passo);
	}
});
//define se suporta webp e faz a subsituição de imagens
function support_format_webp() {
	var elem = document.createElement('canvas');
	if (!!(elem.getContext && elem.getContext('2d'))) {
		return elem.toDataURL('image/webp').indexOf('data:image/webp') == 0;
	} else {
		return false;
	}
}
//carregamento das imagens grandes
var agendados = [];
setTimeout(function () {
	var lazy = document.querySelectorAll(".grande");
	for (var i = 0; i < lazy.length; i++) {
		var id = lazy[i].getAttribute('id');
		if (lazy[i].nodeName == 'IMG') {
			var url = lazy[i].src;
		} else {
			var url = lazy[i].style.backgroundImage.replace(/["']/g, '').replace('url(', '').replace(')', '');
		}
		url = url.replace('_p.png', '_g.png').replace('_p.jpg', '_g.jpg');
		var para = lazy[i].getAttribute('data-para');
		if (para != null) {
			url = url.replace('.jpg', para + '.jpg').replace('.png', para + '.png');
		}
		if (!agendados.includes(url)) {
			agendados.push(url);
			var img = new Image();
			img.setAttribute('data-id', id);
			img.onload = function () {
				var destino = document.querySelectorAll('.' + this.getAttribute('data-id'));
				for (var j = 0; j < destino.length; j++) {
					if (destino[j].nodeName == 'IMG') {
						destino[j].nextElementSibling.classList.add('animate__fadeOut');
						destino[j].nextElementSibling.classList.add('animate__animated');
					} else {
						destino[j].lastElementChild.classList.add('animate__fadeOut');
						destino[j].lastElementChild.classList.add('animate__animated');
					}
					destino[j].classList.add('trocafoto');
					if (destino[j].nodeName == 'IMG') {
						destino[j].src = this.src;
					} else {
						destino[j].style.backgroundImage = 'url("' + this.src + '")';
					}
				}
			}
			img.src = url;
		}
	}
}, 1600);

//configura mapa do google
if (existe('#mapa')) {
	var mapa = document.querySelector('#mapa');
	function mostramapa() {
		if (mapa.hasAttribute('data-mapa')) {
			mapa.innerHTML = atob(mapa.getAttribute('data-mapa'));
			mapa.removeAttribute('data-mapa');
			if (mapa.querySelector('iframe').getAttribute('title') == null) {
				mapa.querySelector('iframe').setAttribute('title', 'Mapa');
			}
		}
	}
	window.addEventListener('scroll', function (event) { if (isInViewport(mapa)) { mostramapa(); } }, false);
	setTimeout(mostramapa, 4000);
}
//configura player do youtube
var youtube = document.querySelectorAll('.youtube');
if (youtube.length > 0) {
	function mostrayoutube() {
		Array.prototype.slice.call(youtube).forEach(function (obj) {
			if (obj.hasAttribute('data-url')) {
				obj.innerHTML = atob(obj.getAttribute('data-url'));
				obj.removeAttribute('data-url');
				if (obj.querySelector('iframe').getAttribute('title') == null) {
					obj.querySelector('iframe').setAttribute('title', 'YouTube');
				}
			}
		});
	}
	window.addEventListener('scroll', function (event) { if (isInViewport(youtube[0])) { mostrayoutube(); } }, false);
	setTimeout(mostrayoutube, 4000);
}

//validação de formulário
var forms = document.querySelectorAll('.needs-validation');
Array.prototype.slice.call(forms).forEach(function (form) {
	form.addEventListener('submit', function (event) {
		form.classList.remove('invalido');
		if (!form.checkValidity()) {
			form.classList.add('invalido');
			event.preventDefault();
			event.stopPropagation();
		}
		form.classList.add('was-validated');
	}, false);
});
var myModal = new bootstrap.Modal(document.getElementById('modal'), {});

function number_format(number, decimals, dec_point, thousands_sep) {
	number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
	var n = !isFinite(+number) ? 0 : +number,
		prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
		sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
		dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
		s = '',
		toFixedFix = function (n, prec) {
			var k = Math.pow(10, prec);
			return '' + Math.round(n * k) / k;
		};
	s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
	if (s[0].length > 3) {
		s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
	}
	if ((s[1] || '').length < prec) {
		s[1] = s[1] || '';
		s[1] += new Array(prec - s[1].length + 1).join('0');
	}
	return s.join(dec);
}
function confere(e) {
	if (this.checkValidity()) {

		let formData = new FormData(this);
		formData.append('form', this.getAttribute('id'));
		formData.append('num1', document.getElementById('num1').value);
		formData.append('num2', document.getElementById('num2').value);
		let xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function () {
			if (this.readyState == 4) {
				let data = JSON.parse(this.responseText);
				console.log(data)
				if (data.redir != undefined) {

					window.location = data.redir;
				} else {
					let form = document.getElementById(data.form);
					form.querySelector('button[type=submit]').disabled = false;
					if (data.msg == 'negado') {
						document.querySelector('.modal-body').innerHTML = '<div class="contato_retorno text-danger">' + data.erro + '</div>';
					} else if (data.msg == 'autorizado') {
						document.querySelector('.modal-body').innerHTML = '<div class="contato_retorno text-success">' + data.mensagem + '</div>';
					} else if (data.msg == 'erro') {
						let qte = 0;
						let erro = '';
						for (var tmp in data.erro) {
							qte++;
							erro += '<br>- ' + data.erro[tmp];
						}
						if (qte == 1) {
							erro = 'Por favor, corrija o seguinte erro e reenvie o formulário:' + erro;
						} else {
							erro = 'Por favor, corrija os seguintes erros e reenvie o formulário:' + erro;
						}
						document.querySelector('.modal-body').innerHTML = '<div class="contato_retorno text-danger">' + erro + '</div>';
					} else {
						document.querySelector('.modal-body').innerHTML = '<div class="contato_retorno text-success">' + data.msg + '</div>';
						form.reset();
						form.classList.remove('was-validated');
						//processa tags de conversão
						let tags = document.querySelectorAll('.modal-body .tag');
						for (var i = 0; i < tags.length; i++) {
							tags[i].innerHTML = atob(tags[i].innerHTML);
						}
						let scripts = document.querySelectorAll('.modal-body .tag script');
						for (var i = 0; i < scripts.length; i++) {
							let script = document.createElement('script');
							if (scripts[i].src != undefined) {
								script.src = scripts[i].src;
							}
							if (scripts[i].innerHTML != '') {
								eval(scripts[i].innerHTML);
							}
							scripts[i].after(script);
						}
						let trs = document.querySelectorAll('#apaga_arquivo tbody tr');
						if (trs != undefined && trs.length > 0) {
							for (var i = 0; i < trs.length; trs++) {
								trs[i].remove();
							}
						}
						if (document.getElementById('arquivo') != null) {
							document.getElementById('arquivos').classList.add('d-none');
						}
					}
					myModal.show();
					if (data.num1 != undefined && data.num2 != undefined) {
						document.getElementById('num1').value = data.num1;
						document.getElementById('num2').value = data.num2;
					}
				}
			}
		}


		xhr.open('POST', location.href, true);
		xhr.send(formData);


	}
};
if (existe('.needs-validation')) {
	var forms = document.querySelectorAll('.needs-validation');
	Array.prototype.slice.call(forms).forEach(function (form) {
		form.addEventListener('submit', confere);
	});
}
//política de privacidade
if (existe('#concordar')) {
	document.getElementById('msg-politica').style.opacity = 1;
	document.getElementById('concordar').addEventListener('click', (event) => {
		document.getElementById('msg-politica').style.opacity = 0;
		setTimeout(function () { document.getElementById('msg-politica').remove(); }, 1000);
		let xhrs = new XMLHttpRequest();
		xhrs.onreadystatechange = function () {
			if (this.readyState == 4 && this.responseText == 'S') {
				//processa tags após aceitar
				let tags = document.querySelectorAll('.tag');
				for (var i = 0; i < tags.length; i++) {
					tags[i].innerHTML = atob(tags[i].innerHTML);
				}
				let scripts = document.querySelectorAll('.tag script');
				for (var i = 0; i < scripts.length; i++) {
					let script = document.createElement('script');
					if (scripts[i].src != undefined) {
						script.src = scripts[i].src;
					}
					if (scripts[i].innerHTML != '') {
						eval(scripts[i].innerHTML);
					}
					scripts[i].after(script);
				}
			}
		}
		xhrs.open('POST', location.href, true);
		xhrs.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		xhrs.send('aceito=S');
	});
}
//processa fotos do tiny
if (existe('#tiny')) {
	setTimeout(function () {
		var xhrt = new XMLHttpRequest();
		xhrt.open('GET', location.pathname + '?processa=1');
		xhrt.send();
	}, 5000);
}
if (existe('#filtra_genero')) {
	var categorias = document.querySelectorAll('#filtra_genero a input');
	var navega = '';
	if (categorias.length > 0) {
		Array.prototype.slice.call(categorias).forEach(function (obj) {
			obj.addEventListener('change', (event) => {
				navega = event.target.parentNode.parentNode.getAttribute('href');
				setTimeout(function () { window.location = navega; }, 300);
			});
		});
	}
}
//apenas numeros
var pula = [8, 9, 13, 37, 39, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105];
var numeros = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105];
//formata campo de CEP
function formata_cep(valor) {
	valor = valor.replace(/\D/g, '');
	if (valor.length > 8) {
		valor = valor.substr(0, 8);
	}
	let tmp = '';
	tmp = valor.substr(0, 5);
	if (valor.length > 5) {
		tmp += '-' + valor.substr(5);
	}
	return tmp;
}
function mascara_cep(e) {
	this.value = formata_cep(this.value);
	atualizacep(e);
	if (!pula.includes(e.keyCode) || (numeros.includes(e.keyCode) && this.value.length == 9)) {
		// e.preventDefault();
		return;
	}
}
var objs = document.querySelectorAll('.cep');
objs.forEach((obj) => {
	obj.addEventListener('keydown', mascara_cep, false);
	obj.addEventListener('keypress', mascara_cep, false);
	obj.addEventListener('keyup', mascara_cep, false);
	obj.addEventListener('change', atualizacep, false);
	obj.value = formata_cep(obj.value);
});
//formata campo de CPF
function formata_cpf(valor) {
	valor = valor.replace(/\D/g, '');
	if (valor.length > 11) {
		valor = valor.substr(0, 11);
	}
	let tmp = '';
	tmp = valor.substr(0, 3);
	if (valor.length > 3) {
		tmp += '.' + valor.substr(3, 3);
		if (valor.length > 6) {
			tmp += '.' + valor.substr(6, 3);
			if (valor.length > 9) {
				tmp += '-' + valor.substr(9);
			}
		}
	}
	return tmp;
}
function mascara_cpf(e) {
	this.value = formata_cpf(this.value);
	if (!pula.includes(e.keyCode) || (numeros.includes(e.keyCode) && this.value.length == 14)) {
		// e.preventDefault();
		return;
	}
}
var objs = document.querySelectorAll('.cpf');
objs.forEach((obj) => {
	obj.addEventListener('keydown', mascara_cpf, false);
	obj.addEventListener('keypress', mascara_cpf, false);
	obj.addEventListener('keyup', mascara_cpf, false);
	obj.value = formata_cpf(obj.value);
});
//formata telefone de 8 ou 9 dígitos
function formata_telefone(valor) {
	valor = valor.replace(/\D/g, '');
	if (valor.length > 11) {
		valor = valor.substr(0, 11);
	}
	let tmp = '';
	if (valor.length > 0) {
		tmp = '(' + valor.substr(0, 2);
		if (valor.length > 2) {
			tmp += ') ';
			if (valor.length > 10) {
				tmp += valor.substr(2, 5) + '-' + valor.substr(7);
			} else if (valor.length > 6) {
				tmp += valor.substr(2, 4) + '-' + valor.substr(6);
			} else {
				tmp += valor.substr(2);
			}
		}
	}
	return tmp;
}
function mascara_telefone(e) {
	this.value = formata_telefone(this.value);
	if (!pula.includes(e.keyCode) || (numeros.includes(e.keyCode) && this.value.length == 15)) {
		// e.preventDefault();
		return;
	}
}
var objs = document.querySelectorAll('.telefone');
objs.forEach((obj) => {
	obj.addEventListener('keydown', mascara_telefone, false);
	obj.addEventListener('keypress', mascara_telefone, false);
	obj.addEventListener('keyup', mascara_telefone, false);
	obj.value = formata_telefone(obj.value);
});
//formata campo de telefone de 9 dígitos
function formata_celular(valor) {
	valor = valor.replace(/\D/g, '');
	if (valor.length > 11) {
		valor = valor.substr(0, 11);
	}
	let tmp = '';
	if (valor.length > 0) {
		tmp = '(' + valor.substr(0, 2);
		if (valor.length > 2) {
			tmp += ') ' + valor.substr(2, 5);
			if (valor.length > 7) {
				tmp += '-' + valor.substr(7);
			}
		}
	}
	return tmp;
}
function mascara_celular(e) {
	this.value = formata_celular(this.value);
	if (!pula.includes(e.keyCode) || (numeros.includes(e.keyCode) && this.value.length == 15)) {
		// e.preventDefault();
		return;
	}
}
var objs = document.querySelectorAll('.celular');
objs.forEach((obj) => {
	obj.addEventListener('keydown', mascara_celular, false);
	obj.addEventListener('keypress', mascara_celular, false);
	obj.addEventListener('keyup', mascara_celular, false);
	obj.value = formata_celular(obj.value);
});
if (existe('#envia_foto')) {
	document.addEventListener('dragover', function (e) {
		e.preventDefault();
		e.stopPropagation();
	});
	document.addEventListener('drop', function (e) {
		e.preventDefault();
		e.stopPropagation();
	});
	let div = document.querySelector('#envia_foto');
	div.addEventListener('dragover', function () {
		this.classList.add('drag_over');
		return false;
	});
	div.addEventListener('dragleave', function () {
		this.classList.remove('drag_over');
		return false;
	});
	var unico = -1;
	function envia(arquivo) {
		let formData = new FormData();
		formData.append('form', 'antologia_arquivo');
		formData.append('num1', document.getElementById('num1').value);
		formData.append('num2', document.getElementById('num2').value);
		formData.append('unico', unico);
		formData.append('arquivo', arquivo);
		let xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function () {
			if (this.readyState == 4) {
				try {
					let data = JSON.parse(this.responseText);
					let linha = document.getElementById('envio' + data.codigo);
					linha.querySelectorAll('td')[1].innerHTML = data.size;
					linha.setAttribute('id', 'linha' + data.arquivo);
					linha.setAttribute('class', 'nomeArq');
					linha.querySelectorAll('td')[2].innerHTML =
						'<a href="#" data-codigo="' + data.arquivo + '">' +
						'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash" viewBox="0 0 16 16"><path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z"></path><path fill-rule="evenodd" d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z"></path></svg>' +
						'</a>';
				} catch (e) {
					// document.querySelector('.modal-body').innerHTML='<div class="text-danger">Ocorreu um erro ao enviar seu formulário. Por favor, recarregue a página e tente novamente.</div>';
					// myModal.show();
				}
			}
		}
		xhr.open('POST', location.href, true);
		xhr.send(formData);
	}
	function processa(arquivos) {
		let limite_mb = document.getElementById('arquivo').getAttribute('data-limite');
		let limite = parseFloat(limite_mb.replace('M', '')) * 1024 * 1024 * 0.5;
		limite_mb = Math.round(limite / (1024 * 1024)) + 'M';
		let tbody = document.querySelector('#apaga_arquivo tbody');
		let permitido = document.getElementById('arquivo').getAttribute('accept');
		let permitidos = permitido.split(',');
		for (var i = 0; i < arquivos.length; i++) {
			let tamanho = number_format((arquivos[i].size / 1024) / 1024, 2, ',', '.') + 'M';
			if (arquivos[i].size > limite) {
				document.querySelector('.modal-body').innerHTML = '<div class="text-danger">O tamanho do arquivo escolhido "' + arquivos[i].name + '" (' + tamanho + ') é maior que o máximo permitido (' + limite_mb + '). Por favor, otimize e reduza o arquivo e tente novamente, ou entre em contato direto através do e-mail atendimento@luraeditorial.com.br.</div>';
				myModal.show();
			} else if (!permitidos.includes(arquivos[i].type)) {
				document.querySelector('.modal-body').innerHTML = '<div class="text-danger">O formato do arquivo escolhido "' + arquivos[i].name + '" (' + arquivos[i].type + ') não está entre os formatos permitidos (' + document.getElementById('arquivo').getAttribute('data-accept') + '). Por favor, selecione um arquivo válido e tente novamente.</div>';
				myModal.show();
			} else {
				unico++;
				tbody.innerHTML =
					'<tr id="envio' + unico + '" class="fadeInUp">' +
					'<td>' + arquivos[i].name + '</td>' +
					'<td>Enviando..</td>' +
					'<td width="1"></td>' +
					'</tr>';
				envia(arquivos[i]);
			}
		}
		document.getElementById('arquivos').classList.remove('d-none');
	}
	div.addEventListener('drop', function (e) {
		e.preventDefault();
		this.classList.remove('drag_over');
		processa(e.dataTransfer.files);
	});
	document.getElementById('arquivo').addEventListener('change', function (e) {
		processa(e.target.files);
	});
	document.getElementById('apaga_arquivo').addEventListener('click', function (e) {
		e.preventDefault();
		let obj = null;
		if (e.target.tagName == 'A') {
			obj = e.target;
		} else if (e.target.parentNode.tagName == 'A') {
			obj = e.target.parentNode;
		} else if (e.target.parentNode.parentNode.tagName == 'A') {
			obj = e.target.parentNode.parentNode;
		}
		if (obj) {
			let formData = new FormData();
			formData.append('form', 'antologia_apaga');
			formData.append('num1', document.getElementById('num1').value);
			formData.append('num2', document.getElementById('num2').value);
			formData.append('codigo', obj.getAttribute('data-codigo'));
			let xhr = new XMLHttpRequest();
			xhr.onreadystatechange = function () {
				if (this.readyState == 4) {
					try {
						let data = JSON.parse(this.responseText);
						if (data.codigo != undefined) {
							// document.getElementById('linha'+data.codigo).classList.add('animate__fadeOutUp');
							// document.getElementById('linha'+data.codigo).classList.add('animate__animated');
							document.getElementById('linha' + data.codigo).remove();
							if (document.querySelectorAll('#arquivos tbody tr').length == 0) {
								document.getElementById('arquivos').classList.add('d-none');
							}
						}
					} catch (e) {
						// document.querySelector('.modal-body').innerHTML='<div class="text-danger">Ocorreu um erro ao enviar seu formulário. Por favor, recarregue a página e tente novamente.</div>';
						// myModal.show();
					}
				}
			}
			xhr.open('POST', location.href, true);
			xhr.send(formData);
		}
	});
}
let leiamais = document.querySelectorAll('.leiamais');
leiamais.forEach((obj) => {
	obj.addEventListener('click', function (e) {
		document.querySelector('.modal-body').innerHTML = this.getAttribute('data-texto');
		myModal.show();
	});
});

if (existe('.asaas')) {
	let objs = document.querySelectorAll('.asaas');
	for (var i = 0; i < objs.length; i++) {
		objs[i].addEventListener('click', function (e) {
			if (this.getAttribute('data-codigo') == undefined) {
				document.querySelector('.modal-body').innerHTML = '<div class="text-danger text-center">Código não definido!<br>Por favor, recarregue a página e tente novamente</div>';
				myModal.show();
			} else if (this.getAttribute('data-valor') == undefined) {
				document.querySelector('.modal-body').innerHTML = '<div class="text-danger text-center">Valor não definido!<br>Por favor, recarregue a página e tente novamente.</div>';
				myModal.show();
			} else if (this.getAttribute('data-descricao') == undefined) {
				document.querySelector('.modal-body').innerHTML = '<div class="text-danger text-center">Código do pagamento não definido!<br>Por favor, recarregue a página e tente novamente.</div>';
				myModal.show();
			} else {
				let icones = 'bi';
				// let icones='fa';
				let txt =
					'<div id="etapa1">' +
					'<div class="text-center">' +
					'<h1 class="h5">Você está realizando o pagamento de:</h3>' +
					'<i>' + this.getAttribute('data-descricao') + '</i><br>' +
					'<br>' +
					'Escolha abaixo a forma de pagamento de sua preferência:<br>' +
					'<input type="hidden" id="pgto_codigo" value="' + this.getAttribute('data-codigo') + '">' +
					'<input type="hidden" id="pgto_valor" value="' + this.getAttribute('data-valor') + '">' +
					'<input type="hidden" id="pgto_descricao" value="' + this.getAttribute('data-descricao') + '">' +
					'</div>' +
					'<div class="row">' +
					'<div class="mt-3 d-grid"><button type="button" data-forma="credito" class="btn btn-dark btn-credito"><i class="' + (icones == 'bi' ? 'bi bi-credit-card' : 'fad fa-credit-card fa-lg') + ' me-3"></i>Cartão de Crédito</button></div>' +
					'<div class="mt-3 col-6 d-grid"><button type="button" data-forma="pix" class="btn btn-dark btn-roxo btn-pix"><i class="' + (icones == 'bi' ? 'bi bi-wallet' : 'fad fa-wallet fa-lg') + ' me-3"></i>Pix</button></div>' +
					'<div class="mt-3 col-6 d-grid"><button type="button" data-forma="boleto" class="btn btn-dark btn-roxo btn-boleto"><i class="' + (icones == 'bi' ? 'bi bi-upc' : 'fad fa-barcode fa-lg') + ' me-3"></i>Boleto</button></div>' +
					'</div>' +
					'</div>' +
					'';
				document.querySelector('.modal-dialog').classList.remove('modal-lg');
				document.querySelector('.modal-body').innerHTML = txt;
				document.querySelector('.btn-pix').addEventListener('click', pgto_escolhe, false);
				document.querySelector('.btn-credito').addEventListener('click', pgto_escolhe, false);
				// document.querySelector('.btn-debito').addEventListener('click',pgto_escolhe,false);
				document.querySelector('.btn-boleto').addEventListener('click', pgto_escolhe, false);
				myModal.show();
			}
		}, false);
	}
	function formata_cartao(valor) {
		valor = valor.replace(/\D/g, '');
		if (valor.length > 16) { valor = valor.substr(0, 16); }
		let tmp = '';
		tmp = valor.substr(0, 4);
		if (valor.length > 4) {
			tmp += ' ' + valor.substr(4, 4);
			if (valor.length > 8) {
				tmp += ' ' + valor.substr(8, 4);
				if (valor.length > 12) {
					tmp += ' ' + valor.substr(12, 4);
				}
			}
		}
		return tmp;
	}
	function mascara_cartao(e) {
		this.value = formata_cartao(this.value);
		if (!pula.includes(e.keyCode) || (numeros.includes(e.keyCode) && this.value.length == 19)) {
			e.preventDefault();
			return;
		}
	}
	function formata_validade(valor) {
		valor = valor.replace(/\D/g, '');
		if (valor.length > 7) { valor = valor.substr(0, 7); }
		let tmp = '';
		tmp = valor.substr(0, 2);
		if (valor.length > 2) {
			tmp += '/' + valor.substr(2, 4);
		}
		return tmp;
	}
	function mascara_validade(e) {
		this.value = formata_validade(this.value);
		if (!pula.includes(e.keyCode) || (numeros.includes(e.keyCode) && this.value.length == 7)) {
			e.preventDefault();
			return;
		}
	}
	function formata_codigo(valor) {
		valor = valor.replace(/\D/g, '');
		if (valor.length > 3) { valor = valor.substr(0, 3); }
		return valor;
	}
	function mascara_codigo(e) {
		this.value = formata_codigo(this.value);
		if (!pula.includes(e.keyCode) || (numeros.includes(e.keyCode) && this.value.length == 3)) {
			e.preventDefault();
			return;
		}
	}
	//formata campo de CPF / CNPJ simultaneamente
	function formata_cpfcnpj(valor) {
		valor = valor.replace(/\D/g, '');
		if (valor.length > 14) {
			valor = valor.substr(0, 14);
		}
		let tmp = '';
		if (valor.length <= 11) {
			if (valor.length > 3) {
				tmp += '.' + valor.substr(3, 3);
				if (valor.length > 6) {
					tmp += '.' + valor.substr(6, 3);
					if (valor.length > 9) {
						tmp += '-' + valor.substr(9, 2);
					}
				}
			}
		} else {
			tmp = valor.substr(0, 2) + '.' + valor.substr(2, 3) + '.' + valor.substr(5, 3) + '/' + valor.substr(8, 4);
			if (valor.length > 12) {
				tmp += '-' + valor.substr(12);
			}
		}
		return tmp;
	}
	function mascara_cpfcnpj(e) {
		this.value = formata_cpfcnpj(this.value);
		if (!pula.includes(e.keyCode) || (numeros.includes(e.keyCode) && this.value.length == 18)) {
			// e.preventDefault();
			return;
		}
	}

}
const getCookie = (name) => {
	const value = " " + document.cookie;
	const parts = value.split(" " + name + "=");
	return parts.length < 2 ? undefined : parts.pop().split(";").shift();
};

const setCookie = function (name, value, expiryDays, domain, path, secure) {
	const exdate = new Date();
	exdate.setHours(
		exdate.getHours() +
		(typeof expiryDays !== "number" ? 365 : expiryDays) * 24
	);
	document.cookie =
		name +
		"=" +
		value +
		";expires=" +
		exdate.toUTCString() +
		";path=" +
		(path || "/") +
		(domain ? ";domain=" + domain : "") +
		(secure ? ";secure" : "");
};

var cookiesBanner = document.querySelector(".cookies-eu-banner");
var cookiesBannerButton = cookiesBanner.querySelector("button");
const cookieName = "cookiesBanner";
const hasCookie = getCookie(cookieName);

if (!hasCookie) {
	cookiesBanner.classList.remove("hidden");
}

cookiesBannerButton.addEventListener("click", () => {
	setCookie(cookieName, "closed");
	cookiesBanner.remove();
});



if (document.getElementById("sucesso") != null) {
	document.querySelector('.modal-body').innerHTML = '<div class="text-success">Usuário cadastrado com sucesso.</div>';
}
var count_header_but = 0;
$(".navbar-toggler").click(function () {
	if ($(".navbar-toggler").hasClass("collapsed")) {
		$("#cadastro_header").css("display", "flex");

	} else {
		$("#cadastro_header").css("display", "none");
	}
	count_header_but++;
});



$("#perfil").mouseover(() => {
	$("#sair").css("display", "flex")
})
$("#sair").mouseover(() => {
	$("#sair").css("display", "flex")
})
$("#sair").mouseout(() => {
	$("#sair").css("display", "none")
})
$("#perfil").mouseover(() => {
	$("#ant_subscribe").css("display", "flex")
})
$("#ant_subscribe").mouseover(() => {
	$("#ant_subscribe").css("display", "flex")
})
$("#ant_subscribe").mouseout(() => {
	$("#ant_subscribe").css("display", "none")
})

// Create lazy-load function to images3
$(window).scroll(function () {
	var windowTop = $(window).scrollTop();
	var windowBottom = windowTop + $(window).height();

	$('.lazy-load').each(function () {
		var img = $(this);
		var dataSrc = img.attr('url');
		var offset = img.offset().top;

		if (offset < windowBottom && offset + img.height() > windowTop) {
			if (img.attr('session') == 'services') {
				img.attr('src', dataSrc).removeClass('lazy-load');
			} else {
				img.attr('src', dataSrc).removeAttr('width').removeAttr('height').removeClass('lazy-load');
			}
		}
	});
	$('.lazy-load-background').each(function () {
		var img = $(this);
		var dataSrc = img.attr('url');
		var offset = img.offset().top;

		if (offset < windowBottom && offset + img.height() > (windowTop - 300)) {
			if (img.attr('session') == 'services') {
				img.css('background-image', 'url(' + dataSrc + ')').removeClass('lazy-load-background');
			} else {
				img.css('background-image', 'url(' + dataSrc + ')').removeClass('lazy-load-background').removeAttr('width').removeAttr('height').removeClass('lazy-load');
			}
		}
	});
});


if (existe('#banner')) {
	var banner = new Swiper('#banner', {
		grabCursor: true,
		centeredSlides: true,
		spaceBetween: 0,
		slidesPerView: 1,
		loop: true,
		autoplay: {
			delay: 6000,
			disableOnInteraction: false,
		},
		pagination: {
			el: '.swiper-pagination',
		}
	});
}
if (existe('#banner_antologias')) {
	var antologias = new Swiper('#banner_antologias', {
		grabCursor: true,
		spaceBetween: 0,
		slidesPerView: 1,
		loop: true,
		autoHeight: true,
		autoplay: {
			delay: 6000,
			disableOnInteraction: false,
		},
		breakpoints: {
			576: { slidesPerView: 2 },
			768: { slidesPerView: 3 },
			992: { slidesPerView: 1 },
		},
		navigation: {
			nextEl: '.swiper-button-next',
			prevEl: '.swiper-button-prev',
		},
	});
}
$(document).ready(function () {
	$('#close').on('click', function () {
		$(".modal").trigger('click');
	});
});
