$("#upload_image").change(function() {
    loaderPage(true)
    readURL(this);

    const fileupload1 = $(this).prop('files')[0];

    var formData = new FormData();

    formData.append("id", $("#iduseredt").val());
    formData.append("inifile", fileupload1)

    $.ajax({
        url: "editpp",
        data: formData,
        dataType: 'json',
        type: 'POST',
        processData: false,
        contentType: false,
        success: function(data) {
            let response = data
            if (response.code == 0) {
                swal({
                    title: response.info,
                    text: response.data,
                    type: "success",
                    icon: "success",
                    confirmButtonColor: "#00BCD4"
                }).then((isConfirm) => {
                    location.reload()
                })
            } else {
                swal({
                    title: 'Error',
                    text: 'Hubungi Developer',
                    type: "warning",
                    icon: "error",
                    confirmButtonColor: "#00BCD4"
                })
            }

        }
    })
});

// perbaikan jalan
function getdetailper(id) {
    $(".map_detail_p_p").html(``)
    // console.log(id)
    $.ajax({
        url: "get-detail-perbaikan",
        data: {
            'id': id
        },
        dataType: 'json',

        success: function(data) {

            $(".map_detail_p_p").html(`<div id="map_detail_perbaikan_dash" style=" position: relative; height: 220px; width: 90%; border-radius: 5px; ">`)

            var map_detail_perbaikan = L.map('map_detail_perbaikan_dash', {
                editable: false,
                zoomControl: false,
                drawControl: false
            }).setView([-4.125826277307029, 104.1881561279297], 10);

            L.tileLayer('https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}&s=Gal&apistyle=s.t:0|s.e:l|p.v:off', {
                maxZoom: 21,
                minZoom: 4,
            }).addTo(map_detail_perbaikan);

            setTimeout(function() {
                map_detail_perbaikan.invalidateSize();
            }, 500);


            if (data.length === 0) {
                
                $(".nama_detail_dash").text("Null");
                $(".type_detail_dash").html("Null");
                $(".tanggal_perbaikan_detail_dash").html("Null")
                $(".anggaran_detail_dash").html("Null")
                $(".penanggung_jawab_detail_dash").html("Null")
                $(".penanggung_jawab_lapangan_detail_dash").html("Null")
                $(".kontraktor_detail_dash").html("Null")
                $(".panjang_jalan_detail_dash").html("Null")
                $(".lebar_jalan_detail_dash").html("Null")

                $(".proposal_detail_dash").html(`
                        <a href="media/proposal/null" id="downloadproposal ">
                            <img src="{% static 'img/icon-1/proposal.svg' %} " alt=" " style="height: 65px;width: 65px; ">
                        </a>`);


                $(".bukti_detail_perbaikan_dash").html(`
                        <a href="media/bukti_penyelesaian/null" onclick="viewBukti() " id="view-bukti ">
                            <img src="{% static 'img/icon-1/bukti.svg' %} " alt=" " style="height: 70px;
                            width: 50px;">
                        </a>`);

            } else {

                $(".nama_detail_dash").html(data[0]['name']);
                $(".type_detail_dash").html(data[0]['type'])
                $(".tanggal_perbaikan_detail_dash").text(data[0]['tgl_perbaikan'])
                // $(".anggaran_detail_dash").html(data[0]['anggaran'])
                // $(".penanggung_jawab_detail_dash").html(data[0]['pj'])
                // $(".penanggung_jawab_lapangan_detail_dash").html(data[0]['pj_lapangan'])
                // $(".kontraktor_detail_dash").html(data[0]['kontraktor'])
                $(".panjang_jalan_detail_dash").html(data[0]['panjang'])
                $(".lebar_jalan_detail_dash").html(data[0]['lbr_jln_reno'])
                $(".proposal_detail_dash").html(`
                        <a href="static/media/proposal/` + data[0]['proposal'] + `" target="_blank" "id="downloadproposal">
                            <img src="static/img/icon-1/proposal.svg" alt=" " style="height: 65px;width: 65px; ">
                        </a>`);


                $(".bukti_detail_perbaikan_dash").html(`
                        <a href="static/media/bukti_penyelesaian/` + data[0].bukti_selesai + `" target="_blank" id="view-bukti">
                            <img src="static/img/icon-1/bukti.svg" alt=" " style="height: 70px;
                            width: 50px;">
                        </a>`);

                //hide ngaco
                // $("#bkt_ang").html(``)
                // $("#bkt_peja").html(``)
                // $("#bkt_pjlap").html(``)
                // $("#bkt_kont").html(``)
                // $("#bkt_lbrjln").html(``)
                // $("#bkt_prop").html(``)
                // $("#bkt_bukti").html(``)
                //end hide ngaco

                $('.map_detail_p_jalan').show()
                
                map_detail_perbaikan.setView([data[0]['geometry']['coordinates'][0][0][1], data[0]['geometry']['coordinates'][0][0][0]], 18)

                var myLines = [data[0]['geometry']];
                // var myLines = data;
                // console.log(myLines)

                var geo_jalan_perbaikan = L.geoJson(data[0]['geometry'], {
                    style: function(feature) {
                        return {
                            color: "#FAFA00",
                            weight: 10,
                            opacity: 2,
                            zIndex: 1001
                        };
                    }
                }).addTo(map_detail_perbaikan);
            }



        }
    });
};

function load_manage() {
    // $("#pengaturan_btn").click(function() {
    $(".datatable-show-all.list_user").dataTable().fnDestroy();
    $(".datatable-show-all.list_group").dataTable().fnDestroy();
    $(".datatable-show-all.list_point").dataTable().fnDestroy();
    $("#list_point").removeClass('list_point')
    $("#list_user").removeClass('list_user')
    $("#list_group").removeClass('list_group')

    $.ajax({
        url: "api/user-data",
        dataType: 'json',

        success: function(data) {
            var data_user = []
            var number = 0;
            var all_id = []
            var all_stat = []

            for (var i = 0; i < data['data'].length; i++) {
                $("#list_point").addClass('list_point')
                $("#list_user").addClass('list_user')
                $("#list_group").addClass('list_group')

                number += 1;
                var id = data['data'][i]['id'];
                var name = data['data'][i]['name'];
                var username = data['data'][i]['username'];
                var group = data['data'][i]['group'];
                var email = data['data'][i]['email'];
                var last = data['data'][i]['last'];
                var isactive = data['data'][i]['isactive'];

                var no_telp = data['data'][i]['phone'];
                var jabatan = data['data'][i]['jabatan'];

                if (isactive == true) {
                    var isac = 'checked'
                } else {
                    var isac = ''
                }

                var data_gab = `<tr>
                        <td>` + number + `</td>
                        <td>` + username + `</td>
                        <td>` + email + `</td>
                        <td>` + no_telp + `</td>
                        <td>` + jabatan + `</td>
                        <td>` + last + `</td>
                        <td class="text-center" style='padding:0px;'>
                        <div class='row'>
                        <div class='col-md-6 text-right' style='margin-top:8px'>
                            <a onclick="loaduserbyid('` + id + `')"><i class=" icon-pencil7"></i>Edit</a>
                        </div>
                        <div class='col-md-6 text-left'>
                            <div class="checkbox switch_custom">
                                <label>
                                    <input type="checkbox" class="slider round" id="checkbox` + id + `" onclick="switchuserstatus('` + id + `, ` + isactive + `','` + id + `')" ` + isac + ` >
                                    <span class="slider round"></span>
                                </label>
                            </div>
                        </div>  
                    </div>
                        </td>

                    </tr>`;

                data_user.push(data_gab)
                all_id.push(id)
                all_stat.push(isactive)
            };

            $("#tbody_user_list").html(data_user)

            if (Array.prototype.forEach) {
                var elems = Array.prototype.slice.call(document.querySelectorAll('.switchery'));
                elems.forEach(function(html) {
                    var switchery = new Switchery(html);
                });
            } else {
                var elems = document.querySelectorAll('.switchery');
                for (var i = 0; i < elems.length; i++) {
                    var switchery = new Switchery(elems[i]);
                }
            }
            $(".switch").bootstrapSwitch();
            var primary_s = document.querySelectorAll("[class^=switchery-custom-x");

            for (var z = 0; z < primary_s.length; z++) {
                var switchery = new Switchery(primary_s[z], { color: '#5A9AFB', secondaryColor: '#3B3E47', jackColor: '#fff', jackSecondaryColor: '#fff' });
            }

            //group
            var data_group = []
            var number = 0;
            var all_id = []
            var all_stat = []

            // console.log(data['group'])

            for (var i = 0; i < data['group'].length; i++) {

                number += 1;
                var id = data['group'][i]['id'];
                var name = data['group'][i]['name'];

                var data_gab = `<tr>
                        <td>` + number + `</td>
                        <td>` + name + `</td>
                        <td class="text-center" style='padding:0px;'>
                            <div class='row'>
                                <div class='col-md-6 text-right' style='margin-top:8px'>
                                    <a onclick="loadgroupbyid('` + id + `')"><i class=" icon-pencil7"></i>Edit</a>
                                </div>
                            </div>
                        </td>
                    </tr>`;

                data_group.push(data_gab)
                all_id.push(id)
                all_stat.push(isactive)
            };

            $("#tbody_group_list").html(data_group)

            if (Array.prototype.forEach) {
                var elems = Array.prototype.slice.call(document.querySelectorAll('.switchery'));
                elems.forEach(function(html) {
                    var switchery = new Switchery(html);
                });
            } else {
                var elems = document.querySelectorAll('.switchery');
                for (var i = 0; i < elems.length; i++) {
                    var switchery = new Switchery(elems[i]);
                }
            }
            $(".switch").bootstrapSwitch();
            var primary_s = document.querySelectorAll("[class^=switchery-custom-x");

            for (var z = 0; z < primary_s.length; z++) {
                var switchery = new Switchery(primary_s[z], { color: '#5A9AFB', secondaryColor: '#3B3E47', jackColor: '#fff', jackSecondaryColor: '#fff' });
            }
            //endgroup

            var data_point = []
            var number2 = 0;

            for (var i = 0; i < data['point'].length; i++) {

                number2 += 1;
                var id = data['point'][i]['id'];
                var nama_tempat = data['point'][i]['nama_tempat'];
                var alamat = data['point'][i]['alamat'];
                var luas = data['point'][i]['luas'];
                var pj = data['point'][i]['pj']
                var db = data['point'][i]['table']

                var data_gab = `<tr>
                        <td>` + number2 + `</td>
                        <td>` + nama_tempat + `</td>
                        <td>` + alamat + `</td>
                        <td>` + luas + `</td>
                        <td>` + pj + `</td>
                        <td class="text-center " style="padding: 0px;">
                            <div class="row">
                                    <a class="btn mdlFire " data-toggle="modal" onclick="modal_detail_point_pengaturan('` + id + `','` + db + `')" style="padding: 10px 12px 10px 12px;">
                                        <div>
                                            <img src="static/img/icon-1/detailpoi.svg" alt="" style="margin-top: -4px;"><span>&nbsp;Detail</span>
                                        </div>
                                        
                                    </a>
    
                            </div>
                        </td>
                    </tr>`;
                data_point.push(data_gab)
            };

            $("#tbody_point_list").html(data_point)

            //input_search
            $('.datatable-show-all.list_user').DataTable({
                autoWidth: false,
                columnDefs: [{
                    orderable: false,
                    width: '10%',
                    targets: [0],
                }, ],
                dom: '<"float-left "B>frtip',
                buttons: [{
                    text: 'Add new button',
                    action: function(e, dt, node, config) {
                        dt.button().add(1, {
                            text: 'Button ' + (counter++),
                            action: function() {
                                this.remove();
                            }
                        });
                    }
                }],
                language: {
                    search: ' _INPUT_',
                    searchPlaceholder: 'Data User...',
                    lengthMenu: '<span>Show:</span><hr> _MENU_',
                    paginate: {
                        'first': 'First',
                        'last': 'Last',
                        'next': '&rarr;',
                        'previous': '&larr;'
                    }
                },

                drawCallback: function() {
                    $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
                },
                preDrawCallback: function() {
                    $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
                }
            });

            $('.datatable-show-all.list_group').DataTable({
                autoWidth: false,
                columnDefs: [{
                    orderable: false,
                    width: '10%',
                    targets: [0],
                }, ],
                dom: '<"float-left "B>frtip',
                buttons: [{
                    text: 'Add new button',
                    action: function(e, dt, node, config) {
                        dt.button().add(1, {
                            text: 'Button ' + (counter++),
                            action: function() {
                                this.remove();
                            }
                        });
                    }
                }],
                language: {
                    search: ' _INPUT_',
                    searchPlaceholder: 'Data Group...',
                    lengthMenu: '<span>Show:</span><hr> _MENU_',
                    paginate: {
                        'first': 'First',
                        'last': 'Last',
                        'next': '&rarr;',
                        'previous': '&larr;'
                    }
                },

                drawCallback: function() {
                    $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
                },
                preDrawCallback: function() {
                    $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
                }
            });

            $('.datatable-show-all.list_point').DataTable({
                autoWidth: false,
                columnDefs: [{
                    orderable: false,
                    width: '10%',
                    targets: [0],

                }, {
                    orderable: false,
                    width: '10%',
                    targets: [3],

                }, {
                    orderable: false,
                    width: '10%',
                    targets: [5],

                }, ],
                dom: '<"float-left "B>frtip',
                language: {
                    search: ' _INPUT_',
                    searchPlaceholder: 'Data Tempat Penting...',
                    lengthMenu: '<span>Show:</span><hr> _MENU_',
                    paginate: {
                        'first': 'First',
                        'last': 'Last',
                        'next': '&rarr;',
                        'previous': '&larr;'
                    }
                },
                drawCallback: function() {
                    $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
                },
                preDrawCallback: function() {
                    $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
                }
            });
            //
        }
    });
};


function btnuserclick(evt) {
    var i, tabcontent, tablinks;

    tablinks = document.getElementsByClassName("tab-user");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    evt.currentTarget.className += " active";
}

function download_user_list(type, fn, dl) {
    $.ajax({
        url: "api/user-data",
        dataType: 'json',

        success: function(data) {

            var thead = `<thead>
                            <tr>
                                <th>No.</th>
                                <th>Id user</th>
                                <th>Username</th>
                                <th>Nama</th>
                                <th>Email</th>
                                <th>Last Login</th>
                                <th>Status</th>
                            </tr>
                        </thead>`
            var data_user = []
            var number = 0;

            for (var i = 0; i < data['data'].length; i++) {

                number += 1;
                var id = data['data'][i]['id'];
                var name = data['data'][i]['name'];
                var username = data['data'][i]['username'];
                var group = data['data'][i]['group'];
                var email = data['data'][i]['email'];
                var last = data['data'][i]['last'];
                var isactive = data['data'][i]['isactive'];


                var data_gab = `<tr>
                    <td>` + number + `</td>
                    <td>` + id + `</td>
                    <td>` + username + `</td>
                    <td>` + name + `</td>
                    <td>` + email + `</td>
                    <td>` + last + `</td>
                    <td>` + isactive + `</td>
                </tr>`;
                data_user.push(data_gab)
            }

            var tbody = `<tbody>
                            ` + data_user + `
                        </tbody>`;

            $("#table_downloader").html(thead + tbody)

            var elt = document.getElementById('table_downloader');

            var wb = XLSX.utils.table_to_book(elt, {
                sheet: "sheet1"
            });
            return dl ?
                XLSX.write(wb, {
                    bookType: type,
                    bookSST: true,
                    type: 'base64'
                }) :
                XLSX.writeFile(wb, fn || ('data_user.' + (type || 'xlsx')));


        }
    })
}

function download_point_list(type, fn, dl) {
    $.ajax({
        url: "api/user-data",
        dataType: 'json',

        success: function(data) {

            var thead = `<thead>
                            <tr>
                                <th>No.</th>
                                <th>Nama Tempat</th>
                                <th>Alamat</th>
                                <th>Luas Bangunan</th>
                                <th>Penanggung Jawab</th>
                            </tr>
                        </thead>`


            var data_point = []
            var number2 = 0;

            for (var i = 0; i < data['point'].length; i++) {

                number2 += 1;
                var id = data['point'][i]['id'];
                var nama_tempat = data['point'][i]['nama_tempat'];
                var alamat = data['point'][i]['alamat'];
                var luas = data['point'][i]['luas'];
                var pj = data['point'][i]['pj']

                var data_gab = `<tr>
                        <td>` + number2 + `</td>
                        <td>` + nama_tempat + `</td>
                        <td>` + alamat + `</td>
                        <td>` + luas + `</td>
                        <td>` + pj + `</td>
                    </tr>`;
                data_point.push(data_gab)
            };

            var tbody = `<tbody>
                            ` + data_point + `
                        </tbody>`;

            $("#table_downloader").html(thead + tbody)

            var elt = document.getElementById('table_downloader');

            var wb = XLSX.utils.table_to_book(elt, {
                sheet: "sheet1"
            });
            return dl ?
                XLSX.write(wb, {
                    bookType: type,
                    bookSST: true,
                    type: 'base64'
                }) :
                XLSX.writeFile(wb, fn || ('data_point.' + (type || 'xlsx')));


        }
    })
}

function loadGroups(isSelect) {
    var isObject = {}

    isObject.func_name = "loadGroups";

    $.ajax({
        url: "/getallGroups/",
        data: isObject,
        dataType: 'json',
        type: 'post',
        success: function(data) {

            let response = data;

            if (response.code == 0) {
                var groups = response.data;
                var html = `<option value="null" selected disabled>-- Pilih Group --</option>`;
                for (i in groups) {
                    if (isSelect) {
                        if (isSelect.length >= 1) {
                            for (j in isSelect) {
                                if (isSelect[j] == groups[i]) {
                                    html += `<option value="` + groups[i] + `" selected>` + groups[i] + `</option>`;

                                } else {
                                    html += `<option value="` + groups[i] + `">` + groups[i] + `</option>`;
                                }
                            }
                        } else {
                            html += `<option value="` + groups[i] + `">` + groups[i] + `</option>`;
                        }



                    } else {
                        html += `<option value="` + groups[i] + `">` + groups[i] + `</option>`;
                    }

                }

                $("#select_group").html(html);
                $("#select_group_parent").html(html);

            } else {
                $("#select_group").html("group tidak tersedia");
                $("#select_group_parent").html("group tidak tersedia");
            }

        }
    });
}

function loadparent(isSelect) {
    var isObject = {}

    isObject.func_name = "loadparent";

    $.ajax({
        url: "/getallGroups/",
        data: isObject,
        dataType: 'json',
        type: 'post',
        success: function(data) {
            // console.log(data)
            let response = data;

            if (response.code == 0) {
                var groups = response.data;
                var html = `<option value="" selected>-- Pilih Parent --</option>`;
                for (i in groups) {
                    if (isSelect) {
                        if (isSelect.length >= 1) {
                            for (j in isSelect) {
                                if (isSelect[j] == groups[i]) {
                                    html += `<option value="` + groups[i] + `" selected>` + groups[i] + `</option>`;
                                } else {
                                    html += `<option value="` + groups[i] + `">` + groups[i] + `</option>`;
                                }
                            }
                        } else {
                            html += `<option value="` + groups[i] + `">` + groups[i] + `</option>`;
                        }
                    } else {
                        html += `<option value="` + groups[i] + `">` + groups[i] + `</option>`;
                    }
                }

                $("#select_parent").html(html);
                // $("#select_group_parent").html(html);

            } else {
                $("#select_parent").html("group tidak tersedia");
                // $("#select_group_parent").html("group tidak tersedia");
            }

        }
    });
}

function swal_switch(isConfirm, c, isObject) {
    var checkbox = document.getElementById("checkbox" + c);

    if (isConfirm == true) {
        if (checkbox.checked == true) {
            checkbox.checked = true
        } else {
            checkbox.checked = false
        }

        $.ajax({
            url: "/switchStatus/",
            data: isObject,
            dataType: 'json',
            type: 'post',
            success: function(data) {

                let response = data;

                if (isObject.stat == "true") {
                    var inf = "dinonaktifkan"
                } else {
                    var inf = "diaktifkan"
                }
                if (response.code == 0) {
                    swal({
                        title: "sukses",
                        text: "User berhasil " + inf,
                        type: "success",
                        icon: "success",
                        confirmButtonColor: "#00BCD4"
                    }, function(isok) {

                        if (inf == "diaktifkan") {
                            $(this).checked = true;
                        } else {
                            $(this).checked = false;
                        }
                    })
                } else {
                    alert("no data in database")
                }

            }
        });
    } else {
        if (checkbox.checked == true) {
            checkbox.checked = false
        } else {
            checkbox.checked = true
        }
        swal("Dibatalkan", "User status tidak berubah", "error");
    }
}

function switchuserstatus(id, c) {
    var isObject = {}
    var params = id.split(",");


    isObject.id = params[0];
    isObject.stat = params[1].replace(" ", "");


    if (isObject.stat == "true") {
        var title = "Nonaktifkan";
        var text = "User tidak akan bisa login jika dinonaktifkan!";
    } else {
        var title = "Aktifkan";
        var text = "User dapat kembali login jika diaktifkan!";
    }

    swal({
        title: title + " user?",
        text: text,
        type: "warning",
        showCancelButton: true,
        confirmButtonClass: "btn-danger",
        confirmButtonText: "Ya!",
        cancelButtonText: "Tidak!",
        closeOnConfirm: false,
        closeOnCancel: false
    }, function(isConfirm) {
        swal_switch(isConfirm, c, isObject)
    });

}

function loaduserbyid(id) {
    var isObject = {};

    isObject.id = id;
    $("#iduser").val(id)

    $.ajax({
        url: "/loadUserbyId/",
        data: isObject,
        dataType: 'json',
        type: 'post',
        success: function(data) {
            $("#modal_edit_user").css('display', 'block');
            $("#modal_edit_user").modal("show")
            $(".modstit").html("Update User")
            $("#inUsername").attr("disabled", true)


            let response = data;

            if (response.code == 0) {
                var user = response.data;

                $("#inUsername").val(user.username);
                $("#inNameF").val(user.firstname);
                $("#inNameL").val(user.lastname);
                $("#inEmail").val(user.email);
                $("#phone").val(user.phone)
                if (user.is_staff) {
                    $('input[name=isStaff][value=true]').attr('checked', true)
                } else {
                    $('input[name=isStaff][value=false]').attr('checked', true)
                }
                loadGroups(user.group)
                $("#modalAddButton").click()
            } else {

            }

        }
    });
}

function loadgroupbyid(id) {
    var isObject = {};

    isObject.id = id;
    $("#idgroup").val(id)
    $("input[name='chekbox'][name='chekbox']").attr('checked', false)

    $.ajax({
        url: "/loadgroup/",
        data: isObject,
        dataType: 'json',
        type: 'post',
        success: function(data) {
            $("#modal_edit_group").css('display', 'block');
            $("#modal_edit_group").modal("show")
            $(".modstit").html("Update Group")
                // $("#ingroup").attr("disabled", true)

            let response = data;

            if (response.code == 0) {
                for (i in data.perm_group) {
                    $("input[name='chekbox'][value=" + data.perm_group[i] + "]").prop('checked', 'checked')
                }

                var grup = response.data;

                $("#ingroup").val(grup.name);
                var gays = []
                gays.push(grup.parent)
                if (grup.parent == null) {
                    loadparent()
                } else {
                    loadparent(gays)
                }

                // if (user.is_staff) {
                //     $('input[name=isStaff][value=true]').attr('checked', true)
                // } else {
                //     $('input[name=isStaff][value=false]').attr('checked', true)
                // }
                // loadparent(grup.have_parent)
                $("#modalAddButton").click()
            } else {

            }
        }
    });
}

function gas_point_perm() {
    var checkBox = document.getElementById("point_perm");
    if (checkBox.checked == true) {
        document.getElementById("k_adm_perm").checked = true;
        document.getElementById("add_k_adm_perm").checked = true;
        document.getElementById("edit_k_adm_perm").checked = true;
        document.getElementById("delete_k_adm_perm").checked = true;
        document.getElementById("rs_perm").checked = true;
        document.getElementById("add_rs_perm").checked = true;
        document.getElementById("edit_rs_perm").checked = true;
        document.getElementById("delete_rs_perm").checked = true;
        document.getElementById("puskes_perm").checked = true;
        document.getElementById("add_puskes_perm").checked = true;
        document.getElementById("edit_puskes_perm").checked = true;
        document.getElementById("delete_puskes_perm").checked = true;
        document.getElementById("lakes_perm").checked = true;
        document.getElementById("add_lakes_perm").checked = true;
        document.getElementById("edit_lakes_perm").checked = true;
        document.getElementById("delete_lakes_perm").checked = true;
        document.getElementById("si_perm").checked = true;
        document.getElementById("add_si_perm").checked = true;
        document.getElementById("edit_si_perm").checked = true;
        document.getElementById("delete_si_perm").checked = true;
        document.getElementById("skul_perm").checked = true;
        document.getElementById("add_skul_perm").checked = true;
        document.getElementById("edit_skul_perm").checked = true;
        document.getElementById("delete_skul_perm").checked = true;
        document.getElementById("st_perm").checked = true;
        document.getElementById("add_st_perm").checked = true;
        document.getElementById("edit_st_perm").checked = true;
        document.getElementById("delete_st_perm").checked = true;
        document.getElementById("term_perm").checked = true;
        document.getElementById("add_term_perm").checked = true;
        document.getElementById("edit_term_perm").checked = true;
        document.getElementById("delete_term_perm").checked = true;
        document.getElementById("cb_perm").checked = true;
        document.getElementById("add_cb_perm").checked = true;
        document.getElementById("edit_cb_perm").checked = true;
        document.getElementById("delete_cb_perm").checked = true;
        document.getElementById("gl_perm").checked = true;
        document.getElementById("add_gl_perm").checked = true;
        document.getElementById("edit_gl_perm").checked = true;
        document.getElementById("delete_gl_perm").checked = true;

    } else if (checkBox.checked == false) {
        document.getElementById("k_adm_perm").checked = false;
        document.getElementById("add_k_adm_perm").checked = false;
        document.getElementById("edit_k_adm_perm").checked = false;
        document.getElementById("delete_k_adm_perm").checked = false;
        document.getElementById("rs_perm").checked = false;
        document.getElementById("add_rs_perm").checked = false;
        document.getElementById("edit_rs_perm").checked = false;
        document.getElementById("delete_rs_perm").checked = false;
        document.getElementById("puskes_perm").checked = false;
        document.getElementById("add_puskes_perm").checked = false;
        document.getElementById("edit_puskes_perm").checked = false;
        document.getElementById("delete_puskes_perm").checked = false;
        document.getElementById("lakes_perm").checked = false;
        document.getElementById("add_lakes_perm").checked = false;
        document.getElementById("edit_lakes_perm").checked = false;
        document.getElementById("delete_lakes_perm").checked = false;
        document.getElementById("si_perm").checked = false;
        document.getElementById("add_si_perm").checked = false;
        document.getElementById("edit_si_perm").checked = false;
        document.getElementById("delete_si_perm").checked = false;
        document.getElementById("skul_perm").checked = false;
        document.getElementById("add_skul_perm").checked = false;
        document.getElementById("edit_skul_perm").checked = false;
        document.getElementById("delete_skul_perm").checked = false;
        document.getElementById("st_perm").checked = false;
        document.getElementById("add_st_perm").checked = false;
        document.getElementById("edit_st_perm").checked = false;
        document.getElementById("delete_st_perm").checked = false;
        document.getElementById("term_perm").checked = false;
        document.getElementById("add_term_perm").checked = false;
        document.getElementById("edit_term_perm").checked = false;
        document.getElementById("delete_term_perm").checked = false;
        document.getElementById("cb_perm").checked = false;
        document.getElementById("add_cb_perm").checked = false;
        document.getElementById("edit_cb_perm").checked = false;
        document.getElementById("delete_cb_perm").checked = false;
        document.getElementById("gl_perm").checked = false;
        document.getElementById("add_gl_perm").checked = false;
        document.getElementById("edit_gl_perm").checked = false;
        document.getElementById("delete_gl_perm").checked = false;

    }
}

function gas_k_adm_perm() {
    var checkBox = document.getElementById("k_adm_perm");
    if (checkBox.checked == true) {
        document.getElementById("add_k_adm_perm").checked = true;
        document.getElementById("edit_k_adm_perm").checked = true;
        document.getElementById("delete_k_adm_perm").checked = true;

    } else if (checkBox.checked == false) {
        document.getElementById("add_k_adm_perm").checked = false;
        document.getElementById("edit_k_adm_perm").checked = false;
        document.getElementById("delete_k_adm_perm").checked = false;
    }
}

function gas_rs_perm() {
    var checkBox = document.getElementById("rs_perm");
    if (checkBox.checked == true) {
        document.getElementById("add_rs_perm").checked = true;
        document.getElementById("edit_rs_perm").checked = true;
        document.getElementById("delete_rs_perm").checked = true;

    } else if (checkBox.checked == false) {
        document.getElementById("add_rs_perm").checked = false;
        document.getElementById("edit_rs_perm").checked = false;
        document.getElementById("delete_rs_perm").checked = false;
    }
}

function gas_puskes_perm() {
    var checkBox = document.getElementById("puskes_perm");
    if (checkBox.checked == true) {
        document.getElementById("add_puskes_perm").checked = true;
        document.getElementById("edit_puskes_perm").checked = true;
        document.getElementById("delete_puskes_perm").checked = true;

    } else if (checkBox.checked == false) {
        document.getElementById("add_puskes_perm").checked = false;
        document.getElementById("edit_puskes_perm").checked = false;
        document.getElementById("delete_puskes_perm").checked = false;
    }
}

function gas_lakes_perm() {
    var checkBox = document.getElementById("lakes_perm");
    if (checkBox.checked == true) {
        document.getElementById("add_lakes_perm").checked = true;
        document.getElementById("edit_lakes_perm").checked = true;
        document.getElementById("delete_lakes_perm").checked = true;

    } else if (checkBox.checked == false) {
        document.getElementById("add_lakes_perm").checked = false;
        document.getElementById("edit_lakes_perm").checked = false;
        document.getElementById("delete_lakes_perm").checked = false;
    }
}

function gas_si_perm() {
    var checkBox = document.getElementById("si_perm");
    if (checkBox.checked == true) {
        document.getElementById("add_si_perm").checked = true;
        document.getElementById("edit_si_perm").checked = true;
        document.getElementById("delete_si_perm").checked = true;

    } else if (checkBox.checked == false) {
        document.getElementById("add_si_perm").checked = false;
        document.getElementById("edit_si_perm").checked = false;
        document.getElementById("delete_si_perm").checked = false;
    }
}

function gas_skul_perm() {
    var checkBox = document.getElementById("skul_perm");
    if (checkBox.checked == true) {
        document.getElementById("add_skul_perm").checked = true;
        document.getElementById("edit_skul_perm").checked = true;
        document.getElementById("delete_skul_perm").checked = true;

    } else if (checkBox.checked == false) {
        document.getElementById("add_skul_perm").checked = false;
        document.getElementById("edit_skul_perm").checked = false;
        document.getElementById("delete_skul_perm").checked = false;
    }
}

function gas_st_perm() {
    var checkBox = document.getElementById("st_perm");
    if (checkBox.checked == true) {
        document.getElementById("add_st_perm").checked = true;
        document.getElementById("edit_st_perm").checked = true;
        document.getElementById("delete_st_perm").checked = true;

    } else if (checkBox.checked == false) {
        document.getElementById("add_st_perm").checked = false;
        document.getElementById("edit_st_perm").checked = false;
        document.getElementById("delete_st_perm").checked = false;
    }
}

function gas_term_perm() {
    var checkBox = document.getElementById("term_perm");
    if (checkBox.checked == true) {
        document.getElementById("add_term_perm").checked = true;
        document.getElementById("edit_term_perm").checked = true;
        document.getElementById("delete_term_perm").checked = true;

    } else if (checkBox.checked == false) {
        document.getElementById("add_term_perm").checked = false;
        document.getElementById("edit_term_perm").checked = false;
        document.getElementById("delete_term_perm").checked = false;
    }
}

function gas_cb_perm() {
    var checkBox = document.getElementById("cb_perm");
    if (checkBox.checked == true) {
        document.getElementById("add_cb_perm").checked = true;
        document.getElementById("edit_cb_perm").checked = true;
        document.getElementById("delete_cb_perm").checked = true;

    } else if (checkBox.checked == false) {
        document.getElementById("add_cb_perm").checked = false;
        document.getElementById("edit_cb_perm").checked = false;
        document.getElementById("delete_cb_perm").checked = false;
    }
}

function gas_gl_perm() {
    var checkBox = document.getElementById("gl_perm");
    if (checkBox.checked == true) {
        document.getElementById("add_gl_perm").checked = true;
        document.getElementById("edit_gl_perm").checked = true;
        document.getElementById("delete_gl_perm").checked = true;

    } else if (checkBox.checked == false) {
        document.getElementById("add_gl_perm").checked = false;
        document.getElementById("edit_gl_perm").checked = false;
        document.getElementById("delete_gl_perm").checked = false;
    }
}

function gas_bangunan_perm() {
    var checkBox = document.getElementById("bangunan_perm");
    if (checkBox.checked == true) {
        document.getElementById("add_bangunan_perm").checked = true;
        document.getElementById("edit_bangunan_perm").checked = true;
        document.getElementById("delete_bangunan_perm").checked = true;
        document.getElementById("perbaikan_bangunan_perm").checked = true;
        document.getElementById("tampak_3d_perm").checked = true;

    } else if (checkBox.checked == false) {
        document.getElementById("add_bangunan_perm").checked = false;
        document.getElementById("edit_bangunan_perm").checked = false;
        document.getElementById("delete_bangunan_perm").checked = false;
        document.getElementById("perbaikan_bangunan_perm").checked = false;
        document.getElementById("tampak_3d_perm").checked = false;
    }
}

function gas_jalan_perm() {
    var checkBox = document.getElementById("jalan_perm");
    if (checkBox.checked == true) {
        document.getElementById("add_jalan_perm").checked = true;
        document.getElementById("edit_jalan_perm").checked = true;
        document.getElementById("delete_jalan_perm").checked = true;
        document.getElementById("perbaikan_jalan_perm").checked = true;
    } else if (checkBox.checked == false) {
        document.getElementById("add_jalan_perm").checked = false;
        document.getElementById("edit_jalan_perm").checked = false;
        document.getElementById("delete_jalan_perm").checked = false;
        document.getElementById("perbaikan_jalan_perm").checked = false;
    }
}

function gas_lahan_perm() {
    var checkBox = document.getElementById("lahan_perm");
    if (checkBox.checked == true) {
        document.getElementById("edit_lahan_perm").checked = true;
    } else if (checkBox.checked == false) {
        document.getElementById("edit_lahan_perm").checked = false;
    }
}

function gas_teritori_perm() {
    var checkBox = document.getElementById("teritori_perm");
    if (checkBox.checked == true) {
        document.getElementById("kelurahan_perm").checked = true;
        document.getElementById("kecamatan_perm").checked = true;
        document.getElementById("edit_kelurahan_perm").checked = true;
        document.getElementById("edit_kecamatan_perm").checked = true;
    } else if (checkBox.checked == false) {
        document.getElementById("kelurahan_perm").checked = false;
        document.getElementById("kecamatan_perm").checked = false;
        document.getElementById("edit_kelurahan_perm").checked = false;
        document.getElementById("edit_kecamatan_perm").checked = false;
    }
}

function gas_kelurahan_perm() {
    var checkBox = document.getElementById("kelurahan_perm");
    if (checkBox.checked == true) {
        document.getElementById("edit_kelurahan_perm").checked = true;
    } else if (checkBox.checked == false) {
        document.getElementById("edit_kelurahan_perm").checked = false;
    }
}

function gas_kecamatan_perm() {
    var checkBox = document.getElementById("kecamatan_perm");
    if (checkBox.checked == true) {
        document.getElementById("edit_kecamatan_perm").checked = true;
    } else if (checkBox.checked == false) {
        document.getElementById("edit_kecamatan_perm").checked = false;
    }
}

function gas_all_perm() {
    var checkBox = document.getElementById("all_perm");
    if (checkBox.checked == true) {

        document.getElementById("point_perm").checked = true;
        document.getElementById("k_adm_perm").checked = true;
        document.getElementById("add_k_adm_perm").checked = true;
        document.getElementById("edit_k_adm_perm").checked = true;
        document.getElementById("delete_k_adm_perm").checked = true;
        document.getElementById("rs_perm").checked = true;
        document.getElementById("add_rs_perm").checked = true;
        document.getElementById("edit_rs_perm").checked = true;
        document.getElementById("delete_rs_perm").checked = true;
        document.getElementById("puskes_perm").checked = true;
        document.getElementById("add_puskes_perm").checked = true;
        document.getElementById("edit_puskes_perm").checked = true;
        document.getElementById("delete_puskes_perm").checked = true;
        document.getElementById("lakes_perm").checked = true;
        document.getElementById("add_lakes_perm").checked = true;
        document.getElementById("edit_lakes_perm").checked = true;
        document.getElementById("delete_lakes_perm").checked = true;
        document.getElementById("si_perm").checked = true;
        document.getElementById("add_si_perm").checked = true;
        document.getElementById("edit_si_perm").checked = true;
        document.getElementById("delete_si_perm").checked = true;
        document.getElementById("skul_perm").checked = true;
        document.getElementById("add_skul_perm").checked = true;
        document.getElementById("edit_skul_perm").checked = true;
        document.getElementById("delete_skul_perm").checked = true;
        document.getElementById("st_perm").checked = true;
        document.getElementById("add_st_perm").checked = true;
        document.getElementById("edit_st_perm").checked = true;
        document.getElementById("delete_st_perm").checked = true;
        document.getElementById("term_perm").checked = true;
        document.getElementById("add_term_perm").checked = true;
        document.getElementById("edit_term_perm").checked = true;
        document.getElementById("delete_term_perm").checked = true;
        document.getElementById("cb_perm").checked = true;
        document.getElementById("add_cb_perm").checked = true;
        document.getElementById("edit_cb_perm").checked = true;
        document.getElementById("delete_cb_perm").checked = true;
        document.getElementById("gl_perm").checked = true;
        document.getElementById("add_gl_perm").checked = true;
        document.getElementById("edit_gl_perm").checked = true;
        document.getElementById("delete_gl_perm").checked = true;

        document.getElementById("bangunan_perm").checked = true;
        document.getElementById("add_bangunan_perm").checked = true;
        document.getElementById("edit_bangunan_perm").checked = true;
        document.getElementById("delete_bangunan_perm").checked = true;
        document.getElementById("perbaikan_bangunan_perm").checked = true;
        document.getElementById("tampak_3d_perm").checked = true;

        document.getElementById("jalan_perm").checked = true;
        document.getElementById("add_jalan_perm").checked = true;
        document.getElementById("edit_jalan_perm").checked = true;
        document.getElementById("delete_jalan_perm").checked = true;
        document.getElementById("perbaikan_jalan_perm").checked = true;

        document.getElementById("teritori_perm").checked = true;
        document.getElementById("kelurahan_perm").checked = true;
        document.getElementById("kecamatan_perm").checked = true;
        document.getElementById("edit_kelurahan_perm").checked = true;
        document.getElementById("edit_kecamatan_perm").checked = true;

        document.getElementById("lahan_perm").checked = true;
        document.getElementById("edit_lahan_perm").checked = true;


    } else if (checkBox.checked == false) {
        document.getElementById("point_perm").checked = false;
        document.getElementById("k_adm_perm").checked = false;
        document.getElementById("add_k_adm_perm").checked = false;
        document.getElementById("edit_k_adm_perm").checked = false;
        document.getElementById("delete_k_adm_perm").checked = false;
        document.getElementById("rs_perm").checked = false;
        document.getElementById("add_rs_perm").checked = false;
        document.getElementById("edit_rs_perm").checked = false;
        document.getElementById("delete_rs_perm").checked = false;
        document.getElementById("puskes_perm").checked = false;
        document.getElementById("add_puskes_perm").checked = false;
        document.getElementById("edit_puskes_perm").checked = false;
        document.getElementById("delete_puskes_perm").checked = false;
        document.getElementById("lakes_perm").checked = false;
        document.getElementById("add_lakes_perm").checked = false;
        document.getElementById("edit_lakes_perm").checked = false;
        document.getElementById("delete_lakes_perm").checked = false;
        document.getElementById("si_perm").checked = false;
        document.getElementById("add_si_perm").checked = false;
        document.getElementById("edit_si_perm").checked = false;
        document.getElementById("delete_si_perm").checked = false;
        document.getElementById("skul_perm").checked = false;
        document.getElementById("add_skul_perm").checked = false;
        document.getElementById("edit_skul_perm").checked = false;
        document.getElementById("delete_skul_perm").checked = false;
        document.getElementById("st_perm").checked = false;
        document.getElementById("add_st_perm").checked = false;
        document.getElementById("edit_st_perm").checked = false;
        document.getElementById("delete_st_perm").checked = false;
        document.getElementById("term_perm").checked = false;
        document.getElementById("add_term_perm").checked = false;
        document.getElementById("edit_term_perm").checked = false;
        document.getElementById("delete_term_perm").checked = false;
        document.getElementById("cb_perm").checked = false;
        document.getElementById("add_cb_perm").checked = false;
        document.getElementById("edit_cb_perm").checked = false;
        document.getElementById("delete_cb_perm").checked = false;
        document.getElementById("gl_perm").checked = false;
        document.getElementById("add_gl_perm").checked = false;
        document.getElementById("edit_gl_perm").checked = false;
        document.getElementById("delete_gl_perm").checked = false;

        document.getElementById("bangunan_perm").checked = false;
        document.getElementById("add_bangunan_perm").checked = false;
        document.getElementById("edit_bangunan_perm").checked = false;
        document.getElementById("delete_bangunan_perm").checked = false;
        document.getElementById("perbaikan_bangunan_perm").checked = false;
        document.getElementById("tampak_3d_perm").checked = false;

        document.getElementById("jalan_perm").checked = false;
        document.getElementById("add_jalan_perm").checked = false;
        document.getElementById("edit_jalan_perm").checked = false;
        document.getElementById("delete_jalan_perm").checked = false;
        document.getElementById("perbaikan_jalan_perm").checked = false;

        document.getElementById("teritori_perm").checked = false;
        document.getElementById("kelurahan_perm").checked = false;
        document.getElementById("kecamatan_perm").checked = false;
        document.getElementById("edit_kelurahan_perm").checked = false;
        document.getElementById("edit_kecamatan_perm").checked = false;

        document.getElementById("lahan_perm").checked = false;
        document.getElementById("edit_lahan_perm").checked = false;

    }
}

var map_poin_det = L.map('maps_detail_p', {
    editable: true,
    zoomControl: false,
    drawControl: true
});

mapss = L.tileLayer('https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}&s=Gal&apistyle=s.t:0|s.e:l|p.v:off', {
    maxZoom: 22,
    minZoom: 4,
}).addTo(map_poin_det);

var map_edit_p = L.map('map-for-edit', {
    editable: true,
    zoomControl: false,
    drawControl: true
}).setView([-2, 118], 5);

mapss_p = L.tileLayer('https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}&s=Gal&apistyle=s.t:0|s.e:l|p.v:off', {
    maxZoom: 22,
    minZoom: 4,
}).addTo(map_edit_p);

var mark_l = null
var mark_p = null

function modal_detail_point_pengaturan(id, db) {

    $("#modal_detail_point_pengaturan").modal("show")

    if (map_poin_det.hasLayer(mark_l)) {
        // marker.clearLayers()
        mark_l.remove()
    }

    if (map_edit_p.hasLayer(mark_p)) {
        // poinin.clearLayers()
        mark_p.remove()
    }

    $.ajax({
        url: "/api/load_point_id",
        data: {
            'idx': id,
            'db': db
        },
        dataType: 'json',
        success: function(data) {
            setTimeout(function() {
                map_poin_det.invalidateSize();
            }, 1000);
            $("#id_adm_edit").val(id)



            $(".nama_point").html(data['result'][0][0]['properties']['f2'])
            $(".pj_bangunan").html(data['result'][0][0]['properties']['f5'])
            $(".luas_bangunan").html(data['result'][0][0]['properties']['f4'])


            $(".gambar_point").html(`<img src="/static/img/image/` + data['result'][0][0]['properties']['f6'] + `" alt="" style="width:100%;height:240px;border-top-left-radius: 10px;">`)

            $("#namobj_adm_edit").val(data['result'][0][0]['properties']['f2'])
            $("#alamat_adm_edit").val(data['result'][0][0]['properties']['f3'])
            $("#luas_tanah_adm_edit").val(data['result'][0][0]['properties']['f4'])
            $("#perangkat_adm_edit").val(data['result'][0][0]['properties']['f5'])
            $("#db_p").val(db)

            var marker = L.marker([data['result'][0][0]['geometry']['coordinates'][1], data['result'][0][0]['geometry']['coordinates'][0]]).addTo(map_poin_det);
            map_poin_det.setView([data['result'][0][0]['geometry']['coordinates'][1], data['result'][0][0]['geometry']['coordinates'][0]], 17)

            mark_l = marker

            map_edit_p.setView([data['result'][0][0]['geometry']['coordinates'][1], data['result'][0][0]['geometry']['coordinates'][0]], 17);
            let dapoin = [data['result'][0][0]['geometry']['coordinates'][1], data['result'][0][0]['geometry']['coordinates'][0]]
            var poinin = L.marker(dapoin).addTo(map_edit_p)
            mark_p = poinin
            poinin.enableEdit();
            $('#saveedit_p').click(function() {
                var hasil = (JSON.stringify(poinin.toGeoJSON()))
                $("#coordinateZoneedit_p").val(hasil);
            })
        }
    });
}


$("#edit_point_p").click(function() {
    $("#koordinat_cek_p").addClass("active")
    $("#info_umum_p").removeClass("active")
    $("#left-tab1-feas-upli").addClass("active")
    $("#right-tab2-feas-upli").removeClass("active")

    setTimeout(function() {
        map_edit_p.invalidateSize();
    }, 1000);
})


$("#saveuser").on("click", function() {
    var isObject = {};
    var ars = ''
    var group = $("#select_group").val();
    var iduser = $("#iduser").val();

    if (iduser) {
        isObject.id = iduser;
    }

    isObject['username'] = $("#inUsername").val();
    isObject['first_name'] = $("#inNameF").val();
    isObject['last_name'] = $("#inNameL").val();
    isObject['email'] = $("#inEmail").val();
    isObject['phone'] = $("#phone").val();
    isObject.group = group
    isObject.isStaff = $('input[name="isStaff"]:checked').val();
    // console.log(group)

    $.ajax({
        url: "adduser/",
        data: isObject,
        dataType: 'json',
        type: 'post',
        success: function(data) {
            let response = data;

            if (response.code == 0) {
                $("#modal_edit_user").css('display', 'none');
                swal({
                    title: response.info,
                    text: response.data + "reload untuk mendapatkan update",
                    type: "success",
                    icon: "success",
                    confirmButtonColor: "#00BCD4"
                })
            } else {
                swal({
                    title: response.info,
                    text: response.data,
                    type: "alert",
                    icon: "error",
                    confirmButtonColor: "#00BCD4"
                })

            }
        }
    });
})



$("#savegroup").on("click", function() {
    var all_perm = []
    $.each($("input[name='chekbox']:checked"), function() {
        all_perm.push($(this).val())
    });
    var isObject = {};
    var ars = ''
    var idgroup = $("#idgroup").val();
    var group = $("#select_parent").val();

    if (idgroup) {
        isObject.id = idgroup;
    }

    isObject['name'] = $("#ingroup").val();
    isObject['parent'] = $("#select_parent").val();
    isObject['all_perm'] = JSON.stringify(all_perm)
    isObject.group = group

    // console.log(group)
    // console.log(isObject)
    $.ajax({
        url: "addGroup/",
        data: isObject,
        dataType: 'json',
        type: 'post',
        success: function(data) {
            let response = data;

            if (response.code == 0) {
                $("#modal_edit_group").css('display', 'none');
                swal({
                    title: response.info,
                    text: response.data + "reload untuk mendapatkan update",
                    type: "success",
                    icon: "success",
                    confirmButtonColor: "#00BCD4"
                })
            } else {
                swal({
                    title: response.info,
                    text: response.data,
                    type: "alert",
                    icon: "error",
                    confirmButtonColor: "#00BCD4"
                })

            }
        }
    });
})


$("#add_user").click(function() {
    $("#modal_edit_user").css('display', 'block');
    $("#modal_edit_user").modal("show")
    $(".modstit").html("Tambah User")
    $("#inUsername").attr("disabled", false)
    $("#group_use").css("display", "none")

    $("#inUsername").val("")
    $("#inNameF").val("")
    $("#inNameL").val("")
    $("#inEmail").val("")
    $("#phone").val("")
    $("#iduser").val("")
    loadGroups()
})

$("#add_group").click(function() {
    $("#modal_edit_group").css('display', 'block');
    $("#modal_edit_group").modal("show")
    $(".modstit").html("Tambah Group")
    $("#ingroup").attr("disabled", false)
    $("#ingroup").val("")
    $("#idgroup").val("")
    loadparent()
})

$("#saveedit_p").click(function() {
    var idka = $('#id_adm_edit').val();
    var poi = $('#coordinateZoneedit_p').val();
    var data = new FormData();
    data.append("file", $("input[id^='fileadm']")[0].files[0]);

    data.append('id', idka)
    data.append('namobj', $('#namobj_adm_edit').val())
    data.append('luastanah', $('#luas_tanah_adm_edit').val())
    data.append('alamat', $('#alamat_adm_edit').val())
    data.append('perangkat', $('#perangkat_adm_edit').val())
    data.append('point', poi)
    data.append('db', $("#db_p").val())
    data.append('gambar', $('#gambar_adm_edit').val())

    $.ajax({
        url: "/api/edit_detail_poin",
        data: data,
        dataType: 'json',
        type: 'POST',
        processData: false,
        contentType: false,
        success: function(data) {
            let response = data
            if (response.status == 0) {
                swal({
                    title: response.info,
                    text: response.data,
                    type: "success",
                    icon: "success",
                    confirmButtonColor: "#00BCD4"
                }, function() {
                    $("#modal_adm").css('display', 'none');
                })
            } else {
                swal({
                    title: 'Error',
                    text: 'Hubungi Developer',
                    type: "warning",
                    icon: "error",
                    confirmButtonColor: "#00BCD4"
                })
            }
        }
    });
})

function changepassword() {
    var isObject = {};

    isObject.id = $("#iduseredt").val();
    isObject.currPass = $('#currentPass').val();
    isObject.newPass = $("#newPass").val();
    isObject.renewPass = $("#renewPass").val();
    isObject.username = $("#usernameedt").val();

    if (isObject.currPass == "" || isObject.newPass == "" || isObject.renewPass == "") {
        $("#notifications").css("display", "block")
        $("#notifications").html("Inputan tidak boleh kosong")

        return false;
    }

    $.ajax({
        url: "changepassword/",
        data: isObject,
        dataType: 'json',
        type: 'post',
        success: function(data) {
            let response = data;

            if (response.code == 0) {
                var datas = response.data
                swal({
                    title: response.info,
                    text: response.data,
                    type: "success",
                    icon: "success",
                    confirmButtonColor: "#00BCD4"
                }, function() {
                    $("#notifications").css("display", "none")
                })
            } else {
                $("#notifications").html(response.data)
                $("#notifications").css("display", "block")
            }
        }
    });



}



function editprofile() {
    var isObject = {}

    isObject.id = $("#iduseredt").val();
    isObject.first_name = $("#firstnameedt").val();
    isObject.last_name = $("#lastnameedt").val();
    isObject.email = $("#emailedts").val()

    if (isObject.first_name == "" || isObject.last_name == "" || isObject.email == "") {
        $("#notificationsprop").css("display", "block");
        $("#notificationsprop").html("Inputan tidak boleh kosong")
        return false
    } else {
        var mail_format = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/;

        if (!isObject.email.match(mail_format)) {
            $("#notificationsprop").css("display", "block");
            $("#notificationsprop").html("Format email tidak valid, silahkan coba kembali.")
            return false
        }
    }

    $.ajax({
        url: "editprofile/",
        data: isObject,
        dataType: 'json',
        type: 'post',
        success: function(data) {
            let response = data;

            if (response.code == 0) {
                var datas = response.data
                swal({
                    title: response.info,
                    text: response.data,
                    type: "success",
                    icon: "success",
                    confirmButtonColor: "#00BCD4"
                }, function() {
                    $("#notificationsprop").css("display", "none")
                })

            } else {
                $("#notificationsprop").html(response.data)
                $("#notificationsprop").css("display", "block");
            }
        }
    });

}

function changecur() {
    var checkBox = document.getElementById("passcur");
    var typ = document.getElementById("currentPass");
    if (checkBox.checked == true) {

        $("#matachange").html(`<i class="icon-eye"></i>`)
        typ.type = 'text';
    } else {
        $("#matachange").html(`<i class="icon-eye-blocked"></i>`)
        typ.type = 'password';
    }
}

function changecur1() {
    var checkBox = document.getElementById("passcur1");
    var typ = document.getElementById("newPass");
    if (checkBox.checked == true) {

        $("#matachange1").html(`<i class="icon-eye"></i>`)
        typ.type = 'text';
    } else {
        $("#matachange1").html(`<i class="icon-eye-blocked"></i>`)
        typ.type = 'password';
    }
}

function changecur2() {
    var checkBox = document.getElementById("passcur2");
    var typ = document.getElementById("renewPass");
    if (checkBox.checked == true) {

        $("#matachange2").html(`<i class="icon-eye"></i>`)
        typ.type = 'text';
    } else {
        $("#matachange2").html(`<i class="icon-eye-blocked"></i>`)
        typ.type = 'password';
    }
}


$("#btnsaveuser").click(function() {
    editprofile()
    changepassword()
})

// function switchuserstatuss(id, isactive) {
//     var checkbox = $(this);

//     if (checkbox.is(":checked")) {
//         e.preventDefault();
//         return false;
//     }else{

//     }
// }

$(".send_pesan").click(function() {
    var pengirimh = $("#nama_pengirimh").val();
    var emailh = $("#email_pengirimh").val();
    var pesan_pengirimh = $("#pesan_pengirimh").val();

    var pengirim = $("#nama_pengirim").val();
    var email = $("#email_pengirim").val();
    var pesan_pengirim = $("#pesan_pengirim").val();

    $.ajax({
        url: "sendmail",
        data: { 'pengirimh': pengirimh, 'emailh': emailh, 'pesanh': pesan_pengirimh, 'pengirim': pengirim, 'email': email, 'pesan': pesan_pengirim },
        dataType: 'json',
        type: 'post',
        success: function(data) {
            let response = data
            if (response.code == 0) {

                swal({
                    title: response.info,
                    text: response.data,
                    type: "success",
                    icon: "success",
                    confirmButtonColor: "#00BCD4"
                }, function() {
                    $("#nama_pengirimh").values('');
                    $("#email_pengirimh").values('');
                    $("#pesan_pengirimh").values('');
                    $("#nama_pengirim").values('');
                    $("#email_pengirim").values('');
                    $("#pesan_pengirim").values('');
                })

            }
        }
    });

})






document.querySelector("#map-create-all > div.leaflet-control-container > div.leaflet-bottom.leaflet-right > div").html(`Powered by <a href="https://khansia.co.id" target="_blank">Khansia</a> with <a href="https://leafletjs.com" target="_blank">Leaflet</a>`)
document.querySelector("#map-create-all > div.leaflet-control-container > div.leaflet-bottom.leaflet-right > div").css("right", "50px")