function botaoOutrasOpcoes(btnOpcao) {
    for (let i = 0; i < btnOpcao.length; i++) {
        btnOpcao[i].addEventListener("click", function () {
            for (let j = 0; j < btnOpcao.length; j++) {
                btnOpcao[j].classList.remove("botao-activo");
            }
            btnOpcao[i].classList.add("botao-activo");
        });
    }
}

function insertLinhaDocumento(id, success, error, done) {
    $.ajax({
        url: "includes/read/queryDocumento.inc.php",
        type: "post",
        dataType: "json",
        data: {
            idDocumento: id,
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoLogin(url, type, dataType, tabela, dados, success, error, done) {
    $.ajax({
        url: url,
        type: type,
        dataType: dataType,
        data: {
            tabela: tabela,
            dados: dados
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoReadModoPagamento(success, error, done) {
    $.ajax({
        url: "includes/read/modoPagamento.inc.php",
        type: "post",
        dataType: "json",
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoQueryEntidade(id, tipoEntidade, success, error, done) {
    $.ajax({
        url: "includes/read/searchEntidade.inc.php",
        type: "post",
        dataType: "json",
        data: {
            idEntidade: id,
            idTipoEntidade: tipoEntidade
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function createDoc(idUsuario, idTipoDoc, idEntidade, idPrazoPagamento, entregue, total, troco, totalLiquido, totalImposto, descontoGlobal, success, error, done) {
    $.ajax({
        url: "includes/create/doc.inc.php",
        type: "post",
        dataType: "json",
        data: {
            idUsuario: idUsuario,
            idTipoDoc: idTipoDoc,
            idEntidade: idEntidade,
            idPrazoPagamento: idPrazoPagamento,
            entregue: entregue,
            total: total,
            troco: troco,
            totalLiquido: totalLiquido,
            totalImposto: totalImposto,
            descontoGlobal: descontoGlobal == "" ? 0 : descontoGlobal
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function createArtigoDocumento(idDocumento, idArtigo, descricao, qtd, preco, desconto, idImposto, imposto, total, success, error, done) {
    $.ajax({
        url: "includes/create/artigoDocumento.inc.php",
        type: "post",
        dataType: "json",
        data: {
            idDocumento: idDocumento,
            idArtigo: idArtigo,
            descricao: descricao,
            qtd: qtd,
            preco: preco,
            desconto: desconto,
            idImposto: idImposto,
            imposto: imposto,
            total: total,
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function createModoPagamento(idModoPagamento, idDocumento, valor, success, error, done) {
    $.ajax({
        url: "includes/create/modoPagamentoDocumento.inc.php",
        type: "post",
        dataType: "json",
        data: {
            idModoPagamento: idModoPagamento,
            idDocumento: idDocumento,
            valor: valor,
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function separadorMilhares(parametro) {
    for (let i = 0; i < parametro.length; i++) {
        parametro[i].addEventListener('keyup', function () {
            var removeChar = parametro[i].value.replace(/[^0-9,\.]/g, '');
            var removeDot = removeChar.replace(/\./g, '');
            parametro[i].value = removeDot;

            var formatedNumber = parametro[i].value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
            parametro[i].value = formatedNumber;
        });
    }
}

function sumCampoTotal(parametro, entregue, entregueText, total, totalText, totalDocumento, moeda) {
    let totalAbsoluto = 0;
    for (let i = 0; i < parametro.length; i++) {
        if (parametro[i].value != "") {
            totalAbsoluto += parseFloat(parametro[i].value.replace(/\ /g, '').replace(/\,/g, '.'));
        }
    }

    entregue.innerText = parseFloat(totalAbsoluto).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;

    if (totalAbsoluto < totalDocumento) {
        totalText.innerText = "VALOR PENDENTE";
        totalText.classList.add("text-danger");
        total.classList.add("text-danger");
        total.innerText = parseFloat(totalDocumento - totalAbsoluto).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
    } else if (totalAbsoluto == totalDocumento && totalAbsoluto != 0) {
        totalText.classList.remove("text-danger");
        total.classList.remove("text-danger");
        entregueText.innerText = "ENTREGUE";
        totalText.innerText = "SEM TROCO";
        totalText.classList.add("text-success");
        total.classList.add("text-success");
        total.innerText = parseFloat(totalDocumento - totalAbsoluto).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
    } else if (totalAbsoluto > totalDocumento) {
        totalText.classList.remove("text-danger");
        total.classList.remove("text-danger");
        entregueText.innerText = "ENTREGUE";
        totalText.innerText = "TROCO";
        totalText.classList.add("text-success");
        total.classList.add("text-success");
        total.innerText = parseFloat(totalAbsoluto - totalDocumento).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
    }
}

function sumModoPagamento(modoPagamento, entregueSpan, totalSpan, totalText, totalEntregue, totalDocumento) {
    let all = 0;
    for (let i = 0; i < modoPagamento.length; i++) {
        if (modoPagamento[i].value != "") {
            all += parseFloat(modoPagamento[i].value.replace(/\ /g, '').replace(/\,/g, '.'));
        }
    }
    entregueSpan.innerText = parseFloat(all);
    entregueSpan.innerText = parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
    if (parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) < totalDocumento) {
        totalText.innerText = "VALOR PENDENTE";
        totalText.className = "text-danger";
        totalSpan.className = "text-danger";
        totalSpan.innerText = totalDocumento - parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        totalSpan.innerText = parseFloat(totalSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
        recalcular();
    } else if (parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) == totalDocumento && parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) != 0) {
        entregueSpan.className = "";
        totalEntregue.className = "";
        totalEntregue.innerText = "ENTREGUE";
        totalText.innerText = "SEM TROCO";
        totalText.className = "text-success";
        totalSpan.className = "text-success";
        totalSpan.innerText = totalDocumento - parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        totalSpan.innerText = parseFloat(totalSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
        recalcular();
    } else if (parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) > totalDocumento) {
        entregueSpan.className = "";
        totalEntregue.className = "";
        totalEntregue.innerText = "ENTREGUE";
        totalText.innerText = "TROCO";
        totalText.className = "text-success";
        totalSpan.className = "text-success";
        totalSpan.innerText = parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) - totalDocumento;
        totalSpan.innerText = parseFloat(totalSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
    }
    recalcular();
}

function recalcular() {
    let total = 0;
    let tabela = document.getElementById("tabelaArtigo");
    for (i = 1; i < tabela.rows.length; i++) {
        if (tabela.rows[i].querySelector('.total').value != "") {
            total += parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.'));
        }
    }
}

function funcaoQueryArtigo(id, linhaPreco, success, error, done) {
    $.ajax({
        url: "includes/read/queryArtigoList.inc.php",
        type: "post",
        dataType: "json",
        data: {
            idArtigo: id,
            linhaPreco: linhaPreco
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoQueryImposto(id, success, error, done) {
    $.ajax({
        url: "includes/read/queryImposto.inc.php",
        type: "post",
        dataType: "json",
        data: {
            idImposto: id
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function outrasOpcoes(total, preco, qtd, desconto, imposto, opcaoTotalBruto, opcaoDescontoLinha, opcaoTotalLiquido, opcaoTotalImposto, opcaoTotalDocumento, opcaoValorPagar, arredondamento, descontoGlobalValor, descontoGlobalPorcentagem, impostoOpcao, impostoOpcaoTr) {
    let totalOpcao = 0;
    let descontoOpcao = 0;
    let totalLiquidoOpcao = 0;
    let totalImpostoOpcao = 0;

    for (let i = 0; i < total.length; i++) {
        if (total[i].value != "") {
            totalOpcao += (parseFloat(preco[i].value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(qtd[i].value.replace(/\ /g, '').replace(/\,/g, '.')));

            totalLiquidoOpcao += parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.'));

            totalImpostoOpcao += (parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.')) * (parseFloat(imposto[i].value.replace(/\ /g, '').replace(/\,/g, '.')) / 100));
        }

        if (total[i].value != "" && preco[i].value != "") {
            descontoOpcao += ((parseFloat(preco[i].value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(qtd[i].value.replace(/\ /g, '').replace(/\,/g, '.'))) - parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.')));
        }
    }
    opcaoTotalBruto.innerText = parseFloat(totalOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoDescontoLinha.innerText = parseFloat(descontoOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoTotalLiquido.innerText = parseFloat(totalLiquidoOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoTotalImposto.innerText = parseFloat(totalImpostoOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoTotalDocumento.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

    let dados = "";
    let tabela = document.getElementById("tabelaArtigo");

    for (i = 1; i < tabela.rows.length; i++) {
        if (tabela.rows[i].querySelector('.inputSearchArtigo').value != "") {
            dados += `
        <tr>
          <td class="tdTaxa"><small>${parseFloat(tabela.rows[i].querySelector('.imposto').value).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + "%"}</small></td>
          <td class="tdIncidencia"><small>${parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</small></td>
          <td class="tdImposto"><small>${(parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')) * (parseFloat(tabela.rows[i].querySelector('.imposto').value.replace(/\ /g, '').replace(/\,/g, '.')) / 100)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</small></td>
          <td class="tdValor"><small>${(parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')) + (parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')) * (parseFloat(tabela.rows[i].querySelector('.imposto').value.replace(/\ /g, '').replace(/\,/g, '.')) / 100))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</small></td>
        </tr>
      `;
        }
    }
    $("#impostoOpcao").html(dados);

    let taxaSet = new Set();

    for (let i = 0; i < $("#impostoOpcao tr").length; i++) {
        let td = $("#impostoOpcao tr")[i].querySelector('.tdTaxa');
        let tr = $("#impostoOpcao tr")[i];

        if (taxaSet.has(td.innerText)) {
            let incidenciaAtual = parseFloat(tr.querySelector('.tdIncidencia').innerText.replace(/\ /g, '').replace(/\,/g, '.'));
            let novoValorIncidencia = incidenciaAtual + parseFloat(td.parentElement.querySelector('.tdIncidencia').innerText.replace(/\ /g, '').replace(/\,/g, '.'));
            tr.querySelector('.tdIncidencia').innerHTML = `<small>${novoValorIncidencia.toFixed(2)}</small>`;
            td.parentElement.remove();
        } else {
            taxaSet.add(td.innerText);
        }
    }

    opcaoValorPagar.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

    $(document).on('keyup', arredondamento, function (e) {
        if (arredondamento.value != "") {
            opcaoValorPagar.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao) + parseFloat(arredondamento.value.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        } else {
            opcaoValorPagar.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        }
    });

    $(document).on('keyup', descontoGlobalValor, function (e) {
        if (descontoGlobalValor.value != "") {
            opcaoTotalLiquido.innerText = (parseFloat(totalLiquidoOpcao) - parseFloat(descontoGlobalValor.value.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

            descontoGlobalPorcentagem.value = ((parseFloat(descontoGlobalValor.value.replace(/\ /g, '').replace(/\,/g, '.')) / parseFloat(totalOpcao)) * 100).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        }
    });

    $(document).on('keyup', descontoGlobalPorcentagem, function (e) {
        if (descontoGlobalPorcentagem.value != "") {
            opcaoTotalLiquido.innerText = (parseFloat(totalLiquidoOpcao) - parseFloat(descontoGlobalPorcentagem.value.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

            descontoGlobalValor.value = ((parseFloat(descontoGlobalPorcentagem.value.replace(/\ /g, '').replace(/\,/g, '.')) / 100) * parseFloat(totalOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        }
    });
}

function funcaoReadCodigoTaxa(success, error, done) {
    $.ajax({
        url: "includes/read/codigoTaxa.inc.php",
        type: "post",
        dataType: "json",
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoReadTipoTaxa(success, error, done) {
    $.ajax({
        url: "includes/read/tipoTaxa.inc.php",
        type: "post",
        dataType: "json",
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoReadRegiao(success, error, done) {
    $.ajax({
        url: "includes/read/regiao.inc.php",
        type: "post",
        dataType: "json",
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoReadTaxa(success, error, done) {
    $.ajax({
        url: "includes/read/taxa.inc.php",
        type: "post",
        dataType: "json",
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoReadTaxaEstado(estado, success, error, done) {
    $.ajax({
        url: "includes/read/taxaEstado.inc.php",
        type: "post",
        dataType: "json",
        data: {
            estado: estado
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoReadPais(success, error, done) {
    $.ajax({
        url: "includes/read/pais.inc.php",
        type: "post",
        dataType: "json",
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

let urlToFile = (url) => {
    let arr = url.split(",");
    let mime = arr[0].match(/:(.*?);/)[1];
    let data = arr[1];

    let dataString = atob(data);
    let n = dataString.length;
    let dataArr = new Uint8Array(n);
    while (n--) {
        dataArr[n] = dataString.charCodeAt(n);
    }
    let file = new File([dataArr], 'File.jpg', {
        type: mime
    });
    return file;
}

function resizeImagem(imagem, containerImagem) {
    imagem.addEventListener("change", function () {
        const reader = new FileReader();
        reader.addEventListener("load", () => {
            const imgElement = document.createElement("img");
            imgElement.src = reader.result;
            imgElement.onload = function (e) {
                const canvas = document.createElement("canvas");
                const MAX_WIDTH = 400;
                const scaleSize = MAX_WIDTH / e.target.width;
                canvas.width = MAX_WIDTH;
                canvas.height = e.target.height * scaleSize;
                const ctx = canvas.getContext("2d");
                ctx.drawImage(e.target, 0, 0, canvas.width, canvas.height);

                const srcEncoded = ctx.canvas.toDataURL(e.target, "image/jpeg");
                resizedImage = urlToFile(srcEncoded);
            }

            const uploaded_image = reader.result;
            containerImagem.style.backgroundImage = `url(${uploaded_image})`;
        });
        reader.readAsDataURL(this.files[0]);
        containerImagem.querySelector("i").style.display = "none";
    });
}

function linhaSelecionada(tabela, btn) {
    $(document).on('click', '#' + tabela + ' tbody tr', function () {
        var isSelected = $(this).hasClass('selected');
        $('#' + tabela + ' tbody tr').removeClass('selected');
        if (!isSelected) {
            $(this).addClass('selected');
            if (btn != null) {
                btn.removeAttribute("disabled");
            }
        } else {
            if (btn != null) {
                btn.setAttribute("disabled", "disabled");
                btn.classList.remove("botao-activo");
            }
        }
    });
}

function funcaoQueryObjecto(parametro, id, url, success, error, done) {
    var requestData = {};
    if (Array.isArray(parametro)) {
        for (let i = 0; i < parametro.length; i++) {
            requestData[parametro[i]] = id[i];
        }
    } else {
        requestData[parametro] = id;
    }
    $.ajax({
        url: url,
        type: "post",
        dataType: "json",
        data: requestData,
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoGetTabela(url, success, error, done) {
    $.ajax({
        url: url,
        type: "post",
        dataType: "json",
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoSelect(url, type, dataType, tabela, success, error, done) {
    $.ajax({
        url: url,
        type: type,
        dataType: dataType,
        data: {
            tabela: tabela
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoQuerySelect(url, type, dataType, id, tabela, success, error, done) {
    $.ajax({
        url: url,
        type: type,
        dataType: dataType,
        data: {
            id: id,
            tabela: tabela
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoAutoIncrement(url, type, dataType, database, tabela, alias, success, error, done) {
    $.ajax({
        url: url,
        type: type,
        dataType: dataType,
        data: {
            database: database,
            tabela: tabela,
            alias: alias
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}


function funcaoImport(url, type, data, cache, contentType, processData, success, error, done) {
    $.ajax({
        url: url,
        type: type,
        data: data,
        cache: cache,
        contentType: contentType,
        processData: processData,
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoImagem(url, type, data, cache, contentType, processData, success, error, done) {
    $.ajax({
        url: url,
        type: type,
        data: data,
        cache: cache,
        contentType: contentType,
        processData: processData,
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoAutoIncrementUpdate(url, type, dataType, tabela, dados, success, error, done) {
    $.ajax({
        url: url,
        type: type,
        dataType: dataType,
        data: {
            tabela: tabela,
            dados: dados
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoInsert(url, type, dataType, tabela, dados, success, error, done) {
    $.ajax({
        url: url,
        type: type,
        dataType: dataType,
        data: {
            tabela: tabela,
            dados: dados
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}



function funcaoUpdate(url, type, dataType, tabela, dados, id, success, error, done) {
    $.ajax({
        url: url,
        type: type,
        dataType: dataType,
        data: {
            id: id,
            tabela: tabela,
            dados: dados
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoDelete(url, type, dataType, tabela, id, success, error, done) {
    $.ajax({
        url: url,
        type: type,
        dataType: dataType,
        data: {
            id: id,
            tabela: tabela
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoCount(url, type, dataType, tabela, id, success, error, done) {
    $.ajax({
        url: url,
        type: type,
        dataType: dataType,
        data: {
            id: id,
            tabela: tabela
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function resetForm(slidePage) {
    slidePage.style.marginLeft = "0%";
    current = 1;
}

function resetFormStep(slidePage, progressText, bullet, progressCheck) {
    slidePage.style.marginLeft = "0%";
    for (let i = 0; i < progressText.length; i++) {
        bullet[i].classList.remove("active");
        progressText[i].classList.remove("active");
        progressCheck[i].classList.remove("active");
    }
    current = 1;
}

function funcaoResetAutoIncrement(url, type, dataType, tabela, success, error, done) {
    $.ajax({
        url: url,
        type: type,
        dataType: dataType,
        data: {
            tabela: tabela
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            error(data);
        }
    }).done(function (data) {
        done(data);
    });
}

function funcaoReload(btn) {
    $('#modal-documento').modal('hide');
    let elemento = document.querySelectorAll('.formulario .form-control');
    for (let i = 0; i < elemento.length; i++) {
        elemento[i].value = "";
        if (elemento[i].parentElement.querySelectorAll("small")[1] !== undefined) {
            elemento[i].parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
        }
        console.log("Elementos: ", elemento[i].tagName.toLowerCase());
        if (elemento[i].tagName.toLowerCase() == 'input' || elemento[i].tagName.toLowerCase() == 'textarea') {
            elemento[i].className = "form-control";
        } else if (elemento[i].tagName.toLowerCase() == 'select') {
            //elemento[i].className = "form-control select2";
        }
    }
    loadNovoId();
    btn.removeAttribute('disabled');
}

var idiomaPortugues = {
    buttons: {
        copy: "Copiar",
        print: "Imprimir",
        colvis: "Visibilidade"
    },
    "sProcessing": "A processar...",
    "sLengthMenu": "Mostrar _MENU_ dos registros",
    "sZeroRecords": "Sem resultados!",
    "sEmptyTable": "Tabela sem dados disponíveis",
    "sInfo": "De _START_ à _END_ de um total de _TOTAL_ registros",
    "sInfoEmpty": "De 0 à 0 de um total de 0 registros",
    "sInfoFiltered": "(filtrado de um total de _MAX_ registros)",
    "sInfoPostFix": "",
    "sSearch": "Pesquisar:",
    "sUrl": "",
    "sInfoThousands": ",",
    "sLoadingRecords": "A carregar...",
    "oPaginate": {
        "sFirst": "Primeira",
        "sLast": "Última",
        "sNext": "Seguinte",
        "sPrevious": "Anterior"
    },
    "oAria": {
        "sSortAscending": ": Activar para ordenar a coluna de forma ascendente",
        "sSortDescending": ": Activar para ordenar a coluna de forma descendente"
    }
}

img_input = document.querySelector("#file");
imagem = document.getElementById("foto");

img_input.addEventListener("change", function () {
    const reader = new FileReader();
    reader.addEventListener("load", () => {
        const uploaded_image = reader.result;
        document.querySelector(".image-container").style.backgroundImage = `url(${uploaded_image})`;
    });
    reader.readAsDataURL(this.files[0]);
    document.querySelector(".image-container").querySelector("i").style.display = "none";
});



