$("#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"
                })
            }

        }
    })
});

function getdetailper(id) {

    $.ajax({
        url: "get-detail-perbaikan",
        data: {
            'id': id
        },
        dataType: 'json',

        success: function(data) {

            var map_detail_perbaikan = L.map('map_detail_perbaikan_dash', {
                editable: true,
                zoomControl: false,
                drawControl: true
            }).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="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="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>`);

                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 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_point").dataTable().fnDestroy();
    $("#list_point").removeClass('list_point')
    $("#list_user").removeClass('list_user')


    $.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')

                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 = +6281234567890
                var jabatan = 'Support'

                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:5px'>
                            <a onclick="loaduserbyid('` + id + `')"><i class=" icon-pencil7"></i>Edit</a>
                        </div>
                        <div class='col-md-6 text-left'>
                            <div class="checkbox checkbox-switchery">
                                <label>
                                    <input type="checkbox" class="switchery-custom-x" id="checkbox` + id + `" onclick="switchuserstatus('` + id + `, ` + isactive + `','` + id + `')" ` + isac + ` >
                                </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' });
            }


            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)

            $('.datatable-show-all.list_user').DataTable({
                autoWidth: false,
                columnDefs: [{
                    orderable: false,
                    width: '10%',
                    targets: [0],
                }, ],
                dom: '<"float-left "B>frtip',
                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_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 = {}
    console.log(isSelect)
    isObject.func_name = "loadGroups";

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

            let response = data;
            console.log(response)
            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>`;
                                    console.log(groups[i])
                                } 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);
                console.log(html)
            } else {
                $("#select_group").html("group tidak tersedia");
                $("#select_group_parent").html("group tidak tersedia");
            }

        }
    });
}

function swal_switch(isConfirm) {
    if (isConfirm == true) {

        $.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 {
        swal("Dibatalkan", "User status tidak berubah", "error");
    }
}


function switchuserstatus(id, c) {
    var isObject = {}
    var params = id.split(",");
    var checkbox = document.getElementById("checkbox" + c);
    console.log(checkbox);

    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)

        // if (cb == 'b') {
        //     alert('b')
        //check it 
        // if (cb == true) {
        //     checkbox.checked = false;
        // } else {
        //     checkbox.checked = true
        // }

        // } else {
        //     alert('a')

        // if (cb == true) {
        //     checkbox.checked = true;
        // } else {
        //     checkbox.checked = false;
        // }
        // }
    });

}

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").modal("show")
            $(".modstit").html("Update User")
            $("#inUsername").attr("disabled", true)


            let response = data;

            if (response.code == 0) {
                var user = response.data;
                console.log(user)
                $("#inUsername").val(user.username);
                $("#inNameF").val(user.firstname);
                $("#inNameL").val(user.lastname);
                $("#inEmail").val(user.email);
                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 {

            }

        }
    });
}


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);


function modal_detail_point_pengaturan(id, db) {

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

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

    if (map_edit_p.hasLayer(marker)) {
        poinin.clearLayers()
        poinin.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)

            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)
            poinin.enableEdit();
            $('#saveedit_p').click(function() {
                var hasil = (JSON.stringify(poinin.toGeoJSON()))
                $("#coordinateZoneedit_p").val(hasil);
            })
            $("#edit_point_p").click(function() {
                setTimeout(function() {
                    map_edit_p.invalidateSize();
                }, 1000);
            })
        }
    });
}


$("#saveuser").on("click", function() {
    addUser()
})

// function destroyfade() {
//     $(".modal-backdrop").css("display", "none")
//     $(".modal-backdrop").removeClass('show');
//     $("body").css('padding-right', '0px !important')
// }

function addUser() {
    var isObject = {};
    var ars = ''
    var group = $("#select_group").val();
    var iduser = $("#iduser").val();

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

    // for(i in group){
    //     if(i < group.length-1){
    //         ars += group[i]+"~";
    //     }else{
    //         ars += group[i];
    //     }
    // }
    // return false
    isObject['username'] = $("#inUsername").val();
    isObject['first_name'] = $("#inNameF").val();
    isObject['last_name'] = $("#inNameL").val();
    isObject['email'] = $("#inEmail").val();
    isObject.group = group
    isObject.isStaff = $('input[name="isStaff"]:checked').val();

    $.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');
                // destroyfade();

                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"
                })

            }
        }
    });
}

$("#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{

//     }
// }

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")