var onpro = 0;

function clearElement(id) {
    $('.ctext').remove();
    var node = document.getElementById(id);
    while (node.hasChildNodes()) {
        node.removeChild(node.firstChild);
    }
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}
 
function savedata() {
    catchchange().then(() => {
        if (onpro == 1) {
            ga('send', 'event', "File", "save data skip", "another task on progress");
            return false;
        }
        $('.tprogress').show('slow');
        $('.pstatus').text('Collecting Data...');
        $(".btn-save").prop("disabled", true);
        onpro = 1;
        tstart = Date.now();
        tmp_id = '';
        tmp_txt = '';
        var bigdata = document.getElementsByClassName('txt-edited');
        var aid = new Array();
        var avalue = new Array();
        var section_list = [];
        var section;
        var data_id = [];
        var data_val = [];
        var dataLength = bigdata.length;
        for (var i = 0; i < dataLength; i++) {
            let parts = bigdata[i].id.split("_");
            section = parts[1];
            if (data_id[section] == null) {
                section_list.push(section);
                data_id[section] = new Array();
                data_val[section] = new Array();
            }
            data_id[section].push(parts[2]);
            data_val[section].push(bigdata[i].textContent.replace(/\u00a0/g, " "));
        }
        // remove text
        for (var i = 0; i < removedId.length; i++) {
            let parts = removedId[i].split("_");
            section = parts[1];
            if (data_id[section] == null) {
                section_list.push(section);
                data_id[section] = new Array();
                data_val[section] = new Array();
            }
            data_id[section].push(parts[2]);
            data_val[section].push("");
        }
        removedId = [];
        // style change
        let attribute_id = [];
        let attribute_style = [];
        var styleChange = $("[italic],[bold]");
        var styleLength = styleChange.length;
        var allStyle;
        console.log("total element change", styleChange.length);
        for (var idx = 0; idx < styleLength; idx++) {
            allStyle = [];
            let parts = styleChange[idx].id.split("_");
            section = parts[1];
            if (data_id[section] == null && attribute_id[section] == null) {
              section_list.push(section);
            }
            if (attribute_id[section] == null) {
              attribute_id[section] = new Array();
              attribute_style[section] = new Array();
            }
            if (styleChange[idx].getAttribute("origin-italic") == "italic" && styleChange[idx].getAttribute("italic") == "false") {
                allStyle.push("ri");
            } else if (styleChange[idx].getAttribute("origin-italic") != "italic" && styleChange[idx].getAttribute("italic") == "true") {
                allStyle.push("ai");
            }
            if (styleChange[idx].getAttribute("origin-bold") == "bold" && styleChange[idx].getAttribute("bold") == "false") {
                allStyle.push("rb");
            } else if (styleChange[idx].getAttribute("origin-bold") != "bold" && styleChange[idx].getAttribute("bold") == "true") {
                allStyle.push("ab");
            }
            if (allStyle.length > 0) {
                attribute_id[section].push(parts[2]);
                attribute_style[section].push(allStyle.join("*"));
            }
        }

        if (section_list.length == 0) {
            $('.tprogress').hide('slow');
            $('.pstatus').text('');
            return false;
        }
        $.ajax({
            type: "POST",
            url: homeUrl + "upload/prepare_save",
            data: {
                recheck: 1,
                key: document.getElementById("key").value,
                sections: section_list.join("*"),
                a3g4d21h4k: readCookie('k55b1n5f8')
            },
            cache: false,
            success: function(res) {
                if (res == "success") {
                    send_change_to_server(0, section_list, data_id, data_val, attribute_id, attribute_style);
                    ga('send', 'event', "File", "prepare save finish", document.getElementById("key").value);
                } else {
                    ga('send', 'event', "File", "prepare save failed", document.getElementById("key").value);
                }
            }
        });
    });
    // $('#warningGradientOuterBarG').show();
}             

function send_change_to_server(idx, section_list, data_id, data_val, attribute_id, attribute_style) {
    $('.pstatus').text('Saving data...');
    let section = section_list[idx];
    if (section == null) {
        console.log("section is null", section_list);
        ga('send', 'event', "File", "save finished!", document.getElementById("key").value);
        if (idx == 0) {
            onpro = 0;
            $(".tprogress").hide("slow");
            $(".pstatus").text("");
        } else {
            onpro = 0;
            $('.tprogress').hide('slow');
            $('.pstatus').text("Selesai dalam " + ((Date.now() - tstart) / 1000) + " detik");
            settime = setTimeout(function () {
                $(".pstatus").text("");
            }, 5000);
        }
        return true;
    }
    let key = document.getElementById("key").value;
    var nid = JSON.stringify(data_id[section]);
    var nvalue = JSON.stringify(data_val[section]);
    var aid = JSON.stringify(attribute_id[section]);
    var avalue = JSON.stringify(attribute_style[section]);
    $.ajax({
        type: "POST",
        url: serverurl + `req2/save_data/${ext}?key=${key}_${section}&section=${section}`,
        data: {
            json_index: nid,
            json_value: nvalue,
            attribute_index: aid,
            attribute_value: avalue
        },
        cache: false,
        success: function(res) {
            // if (section == 1) reloaddata(section_list);
            document.getElementById(
                "section_" + section
            ).innerHTML = res;
            $(".btn-download").prop("disabled", false);
            $(".btn-save").prop("disabled", true);
            setTimeout(() => {
                send_change_to_server(++idx, section_list, data_id, data_val);
            }, 500);
        },
        error: function(e) {
            alert("Gagal! Server tidak merespon permintaan anda.. \nJika kendala terulang kembali, laporkan kepada teknisi kami.\nTerima kasih");
        }
    });
}

function do_recheck() {
    if (onpro == 1) {
        ga('send', 'event', "File", "recheck skip", "another task on progress");
        return false;
    }
    onpro = 1;
    ga('send', 'event', "File", "recheck start", document.getElementById("key").value);
    tstart = Date.now();
    $('#warningGradientOuterBarG').show();
    $.ajax({
        type: "POST",
        url: homeUrl + "upload/do_recheck",
        data: {
            recheck: 1,
            key: document.getElementById("key").value,
            sections: servers.join("*"),
            a3g4d21h4k: readCookie('k55b1n5f8')
        },
        cache: false,
        success: function(res) {
            ga('send', 'event', "File", "recheck finish", document.getElementById("key").value);
            getdata(2);
            $('#warningGradientOuterBarG').hide();
        }
    });
}

function do_dl() {
    if (onpro == 1){
        ga('send', 'event', "File", "download skip", "another task on progress");
        return false;
    }
    onpro = 1;
    $('.tprogress').show('slow');
    clearTimeout(settime);
    $('.pstatus').text('Menunggu dokumen...');
    ga('send', 'event', "File", "download start", document.getElementById("key").value);
    $.ajax({
        type: "POST",
        url: homeUrl + "upload/do_dl/"+ext,
        data: {
            dl: 1,
            key: document.getElementById("key").value,
            sections: servers.join("*"),
            a3g4d21h4k: readCookie('k55b1n5f8')
        },
        cache: false,
        success: function(res) {
            setTimeout(function(){ 
                // $("#popup-feedback").modal("show"); 
                // if (readCookie('review_status') != 1) {
                //     $('.review-form').addClass('active');
                // }
                $('#popup-feedback').modal('show');
            }, 4000);
            window.location.replace(res);
            ga('send', 'event', "File", "download finish", document.getElementById("key").value);
            $('.tprogress').hide('slow');
            $('.pstatus').text('');
            onpro = 0;
        }
    });
}