25
| <![CDATA[<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-5ND2WBQ');</script>]]>
|
478
| <![CDATA[<script>
var lang = "pt-BR";
function sendData() {
$('#loading-container').addClass('loading-container--show');
const XHR = new XMLHttpRequest();
// Bind the FormData object and the form element
var FD = new FormData( $('#ticketform')[0] );
// appendando arquivos ao FormData
for (i = 0; i < filesArray.length; i++) {
if(typeof filesArray[i]!="undefined"){
FD.append("attachment[]", filesArray[i]);
}
}
// Display the values
for (var value of FD.values()) {
console.log(value);
}
// Display the key/value pairs
for(var pair of FD.entries()) {
console.log(pair[0]+ ', '+ pair[1]);
}
// Define what happens on successful data submission
XHR.addEventListener( "load", function(event) {
console.debug( event.target.responseText );
} );
// Define what happens in case of error
XHR.addEventListener( "error", function( event ) {
console.error(event);
} );
// Set up our request
// XHR.open( "POST", "http://w3.homologacao.ibge.gov.br:8081/ticket", true );
XHR.open( "POST", "https://www.ibge.gov.br/atendimentoapi/ticket", true );
XHR.setRequestHeader("Access-Control-Allow-Origin", "*");
// XHR.setRequestHeader("Content-Type", "application/json");
// The data sent is what the user provided in the form
XHR.send(FD);
XHR.addEventListener("load", transferComplete);
XHR.addEventListener("error", transferFailed);
}
// ...and take over its submit event.
var onSubmit = function(token) {
event.preventDefault();
console.log('reCaptcha success!');
if(validateName($('#authorName')) && required($('#authorEmail')) && validateEmail($('#authorEmail')) && required($('#category')) && required($('#title')) && required($('#message')) && validateFilesField($('#ticketform .file-input')) ){
$this = $(this);
/** prevent double posting */
if ($this.data().isSubmitted) {
return false;
}
sendData();
/** mark the form as processed, so we will not process it again */
$this.data().isSubmitted = true;
// limpa o isSubmitted depois de 2 segundos para permitir envio de novo form
var checkSubmit = setInterval(function(){
if ($this.data().isSubmitted) {
clearInterval(checkSubmit);
$this.data().isSubmitted = false;
}
}, 2000);
return true;
}
};
function transferComplete(evt) {
console.log('Mensagem sendo enviada...'); console.log(evt);
$('#loading-container').removeClass('loading-container--show');
var status = JSON.parse(evt.target.status);
if(status < 300){
var protocolo = JSON.parse(evt.target.response).id;
console.log('Mensagem recebida com sucesso! Status:'+status);
$('#protocolo').text(protocolo);
$('#falha-container').removeClass('falha-container--show');
$('#sucesso-container').addClass('sucesso-container--show');
resetForm();
} else {
console.log('Erro HTTP status:'+status);
$('#sucesso-container').removeClass('sucesso-container--show');
$('#falha-container').addClass('falha-container--show');
resetForm();
}
}
function transferFailed(evt) {
var status = JSON.parse(evt.target.status);
console.log('Falha no envio da mensagem. Status:'+status);
$('#loading-container').removeClass('loading-container--show');
console.log(evt);
$('#sucesso-container').removeClass('sucesso-container--show');
$('#falha-container').addClass('falha-container--show');
resetForm();
}
function resetForm(){
$('#ticketform')[0].reset();
$('.rsform-block-file .control-label .formError').text('Entrada Inválida');
$('.rsform-block-file').removeClass('error');
$('.fileblock--child').remove();
$('.files-list-container').hide();
filesArray = [];
}
// FUNCTION PARA LISTAR CATEGORIAS NO SELECT PELA API/CATEGORIES
function getCategories(){
var url = new URL( "https://www.ibge.gov.br/atendimentoapi/categories" );
// const url = new URL( "http://api.atendimento.homolog/categories" );
var params = { "lang": "PT_BR" };
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
var headers = {
"Content-Type": "application/json",
"Accept": "application/json",
};
fetch(url, {
method: "GET",
headers,
}).then(response => response.json()).then(function(data){
Object.keys(data).forEach(key => $('#category').append($("<option />").val(key).text(data[key])));
});
}
this.getCategories();
// get user IP
var ipifyUrl = 'https://api.ipify.org?format=json';
fetch(ipifyUrl, {
method: "GET"
}).then(response => response.json()).then(function(data){
$('#authorIp').val(data.ip);
});
function required(inputtx){
if (inputtx[0].value.length == 0){
// alert("message");
inputtx.parent().parent().addClass('error');
return false;
}
inputtx.parent().parent().removeClass('error');
return true;
}
function validateName(inputtxt) {
$('.rsform-block-authorName .control-label .formError').text('');
if (inputtxt[0].value.length == 0){
inputtxt.parent().parent().addClass('error');
return false;
}
var numbers = /[0-9]/;
if(inputtxt[0].value.match(numbers)) {
$('.rsform-block-authorName .control-label .formError').text('Formato Inválido');
inputtxt.parent().parent().addClass('error');
return false;
}
else {
inputtxt.parent().parent().removeClass('error');
return true;
}
}
function validateEmail(mail){
var value = mail.value == undefined ? mail[0].value : mail.value;
if(value.length == 0){
$('.rsform-block-authorEmail .control-label .formError').text('Campo obrigatório');
$('.rsform-block-authorEmail').addClass('error');
return (false)
}
// if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(value)) {
if(/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/.test(value)) {
$('.rsform-block-authorEmail').removeClass('error');
return (true)
}
// alert("You have entered an invalid email address!")
$('.rsform-block-authorEmail .control-label .formError').text('Entrada Inválida');
$('.rsform-block-authorEmail').addClass('error');
return (false)
}
function formatPhoneNumber(phoneNumberString) {
if(phoneNumberString.length > 0){
var cleaned, match = ("" + phoneNumberString).replace(/\D/g, "").match(/^(\d{2})(\d{5})(\d{4})$/);
if(match){
$('.rsform-block-authorPhone').removeClass('error');
return "(" + match[1] + ") " + match[2] + "-" + match[3];
} else{
$('.rsform-block-authorPhone').addClass('error');
return null;
}
// return match ? "(" + match[1] + ") " + match[2] + "-" + match[3] : null;
} else {
$('.rsform-block-authorPhone').removeClass('error');
return null;
}
}
function validateFiles(file){
var fileName= file.name;
var fileIndex = filesArray.indexOf(file);
// Formato de arquivos permitidos;
// Imagem, PDF, Texto(word, ods,txt, csv), Planilhas(excel, libre office etc) e arquivos compactados
// var reg = /(.*?)\.(jpg|bmp|jpeg|png|gif|tiff|webp|heif|eps|svg|doc|docx|pdf|ods|odt|txt|csv|xls|xlsx|zip|gz|bz2|z|rar|tar)$/;
var reg = /(.*?)\.(jpg|bmp|jpeg|png|doc|docx|pdf|ods|odt|txt|csv|xls|xlsx|zip|gz|rar|tar|7z)$/;
if(!fileName.toLowerCase().match(reg)){
$('.rsform-block-file .control-label .formError').append('<span>Formato de arquivo não permitido '+fileName+'</span>');
$('.rsform-block-file').addClass('error');
filesArray.splice(fileIndex,1);
return false;
}
if(fileName.length > 50){
$('.rsform-block-file .control-label .formError').append('<span>O nome do arquivo '+fileName+ ' é muito grande. Envio limitado a 50 caracteres.</span>');
$('.rsform-block-file').addClass('error');
filesArray.splice(fileIndex,1);
return false;
}
if(file.length > 0)
sizeCheck(file.size);
}
function sizeCheck(fileSize) {
var numb = fileSize/1024/1024;
numb = numb.toFixed(2);
// Tamanho máximo permitido = 20 MB
if(numb > 20){ // 20MB
$('.rsform-block-file .control-label .formError').append('<span>Total de '+numb+'MB. Tamanho máximo para envio de arquivos é 20MB.</span>');
$('.rsform-block-file').addClass('error');
return false; // alert('to big, maximum is 2MiB. You file size is: ' + numb +' MiB');
}
}
// variavel para armazenar os arquivos concatenados
var filesArray = [];
function validateFilesField(fileFields){
// $('.rsform-block-file .controls .formError').text('Entrada Inválida');
$('.rsform-block-file .control-label .formError span').remove();
$('.rsform-block-file').removeClass('error');
$('.file-block').removeClass('error');
var totalSize = 0;
var totalFiles = 0;
var filesList = '';
var removeBtn = '<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="trash" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" class="svg-inline--fa fa-trash fa-w-14 fa-3x" style="width:14px;height:14px;"><path fill="#1351b4" d="M432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16zM53.2 467a48 48 0 0 0 47.9 45h245.8a48 48 0 0 0 47.9-45L416 128H32z"></path></svg>';
$('#files-list div').remove();
// varrendo campos tipo file
$(fileFields).each(function(fieldIdx){
var fileField = fileFields[fieldIdx];
// campo com algum arquivo selecionado
if(fileField.files.length > 0){
// concatena os arquivos de cada campo na variavel filesArray
var filesInputArray = Array.from(fileField.files);
filesArray = filesArray.concat(filesInputArray);
console.log(filesArray);
}
});
// removendo file inputs
$('.fileblock--child').remove();
// varrendo todos os arquivos para validação
$(filesArray).each(function(file){ //.name .type .size
validateFiles(this,file);
totalSize += this.size;
totalFiles++;
var fileIndex = filesArray.indexOf(this);
var actualFileSize = calcSize(this.size);//this.size/1024/1024;
if(fileIndex >= 0)
filesList += '<div id="file_'+fileIndex+'"><span class="filename">'+this.name+'</span> <span class="filesize">'+actualFileSize+'<span class="removeBtn" onclick="removeFile('+fileIndex+');">'+removeBtn+'</span></span></div>';
// filesList += '<div id="file_'+fileIndex+'"><span class="filename">'+this.name+'</span> <span class="filesize">('+actualFileSize.toFixed(2)+' MB)<span class="removeBtn" onclick="removeFile('+fileIndex+');">'+removeBtn+'</span></span></div>';
});
$('#files-list').append(filesList);
filesList == '' ? $('.files-list-container').hide() : $('.files-list-container').show();
if(sizeCheck(totalSize) == false){
return false;
}
console.log('total de arquivos:'+totalFiles);
if(totalFiles > 20){
$('.rsform-block-file .control-label .formError').append('<span>Quantidade máxima para envio é de 20 arquivos.</span>');
$('.rsform-block-file').addClass('error');
return false;
} else {
return true;
}
}
var fileCounter = 1;
function add_file() {
if($(".rsform-block-file .file-input").length <= 20){
$(".rsform-block-file .formControls").append("<div class='file-block fileblock--child fileblock-"+fileCounter+"'><div class='controls'><input id='fileblock-"+fileCounter+"' type='file' name='attachment[]' multiple hidden class='file-input rsform-input-box' onchange=\"validateFilesField($('#ticketform .file-input'));\"><button class='btn btn-remove' id='fileblock-"+fileCounter+"--remove' onclick=remove_file(this);>Remover</button> <span class='formValidation'><span class='formError'>Entrada Inválida</span></span></div></div>");
$('#fileblock-'+fileCounter).click();
fileCounter++;
}
if($(".rsform-block-file .file-input").length >= 20)
$("#btn-addFiles").hide();
}
function remove_file(ele) {
$(ele).parent().parent().remove();
if($(".rsform-block-file .file-input").length < 20)
$("#btn-addFiles").show();
validateFilesField($('#ticketform .file-input'));
}
function removeFile(idx) {
// remove item do array
filesArray.splice(idx,1);
// $(ele).parent().parent().remove();
if($(".rsform-block-file .file-input").length < 20)
$("#btn-addFiles").show();
validateFilesField($('#ticketform .file-input'));
}
function calcSize(nBytes) {
let sOutput = nBytes+'B';
for (
let aMultiples = ['KB', 'MB', 'GB', 'TB'],
nMultiple = 0,
nApprox = nBytes / 1024;
nApprox > 1;
nApprox /= 1024, nMultiple++
) {
sOutput = `${nApprox.toFixed(2)} ${aMultiples[nMultiple]}`
}
return sOutput
}
function cleanValidation(inputtx){
inputtx.parent().parent().removeClass('error');
return true;
}
$('#authorName').on("blur", function(){validateName($('#authorName'))});
$('#category').on("blur", function(){required($('#category'))});
$('#title').on("blur", function(){required($('#title'))});
$('#message').on("blur", function(){required($('#message'))});
$('#authorEmail').on("blur", function(){validateEmail(this)});
if(lang == "pt-BR") {
$('#authorPhone').on("blur", function(){ var fmt = formatPhoneNumber($("#authorPhone").val()); $("#authorPhone").val(fmt); });
}
</script>]]>
|