/* GLOBAL VAR */

var objLoad = {};
$(document).ready(function(){
    
    var modalTemplate = '<div class="modal-dialog modal-lg" role="document">\n' +
    '  <div class="modal-content">\n' +
    '    <div class="modal-header">\n' +
    '      <div class="kv-zoom-actions btn-group">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
    '      <h6 class="modal-title">{heading} <small><span class="kv-zoom-title"></span></small></h6>\n' +
    '    </div>\n' +
    '    <div class="modal-body">\n' +
    '      <div class="floating-buttons btn-group"></div>\n' +
    '      <div class="kv-zoom-body file-zoom-content"></div>\n' + '{prev} {next}\n' +
    '    </div>\n' +
    '  </div>\n' +
    '</div>\n';

    // Buttons inside zoom modal
    var previewZoomButtonClasses = {
    toggleheader: 'btn btn-default btn-icon btn-xs btn-header-toggle',
    fullscreen: 'btn btn-default btn-icon btn-xs',
    borderless: 'btn btn-default btn-icon btn-xs',
    close: 'btn btn-default btn-icon btn-xs'
    };

    // Icons inside zoom modal classes
    var previewZoomButtonIcons = {
    prev: '<i class="icon-arrow-left32"></i>',
    next: '<i class="icon-arrow-right32"></i>',
    toggleheader: '<i class="icon-menu-open"></i>',
    fullscreen: '<i class="icon-screen-full"></i>',
    borderless: '<i class="icon-alignment-unalign"></i>',
    close: '<i class="icon-cross3"></i>'
    };

    // File actions
    var fileActionSettings = {
    zoomClass: 'btn btn-link btn-xs btn-icon',
    zoomIcon: '<i class="icon-zoomin3"></i>',
    dragClass: 'btn btn-link btn-xs btn-icon',
    dragIcon: '<i class="icon-three-bars"></i>',
    removeClass: 'btn btn-link btn-icon btn-xs',
    removeIcon: '<i class="icon-trash"></i>',
    indicatorNew: '<i class="icon-file-plus text-slate"></i>',
    indicatorSuccess: '<i class="icon-checkmark3 file-icon-large text-success"></i>',
    indicatorError: '<i class="icon-cross2 text-danger"></i>',
    indicatorLoading: '<i class="icon-spinner2 spinner text-muted"></i>'
    };

    $('.file-input').fileinput({
        browseLabel: 'Browse',
        browseIcon: '<i class="icon-file-plus"></i>',
        uploadLabel: '',
        uploadClass: 'hidden',
        uploadIcon: '',
        removeIcon: '<i class="icon-cross3"></i>',
        layoutTemplates: {
            icon: '<i class="icon-file-check"></i>',
            modal: modalTemplate
        },
        initialCaption: "No file selected",
        previewZoomButtonClasses: previewZoomButtonClasses,
        previewZoomButtonIcons: previewZoomButtonIcons,
        fileActionSettings: fileActionSettings
    });

    $('.pickatime-disabled').pickatime({
        // format: 'yyyy, mm dd',
        disable: [
           [12,0],
           [12,30]
        ],
        min: [13,0],
        max: [17,0],
       
    });
    $(".select2-hidden-accessible").on('click', function(){
            
    });

    var arraydata = [
        {id: 'ininilai', text: "hohohihek", value: 13},
        {id: 1, text: "ckaaks", value: 11},
    ]
    
    
    
    loadselectmhs();
    function loadselectmhs(){
        var isObject = {};
        var kdprodi  = $("#nim_mhs").val();
        
        isObject.kodeprodi = kdprodi.substr(0, 3);

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: baseURL + '/jsondata/loadmhsbyprodi',
            data: {
                iparam	    : cryptoEncrypt(PHRASE, isObject),
            },
            success: function (response) {
                // $('#modal-add').modal("hide");
                if(response.code == CODE_SUCCESS){
                    response = cryptoDecrypt(PHRASE, response.data);
                    var data = response.data;
                    var arraydata = [];
                    // var obj = {};
                    // console.log(kdprodi)
                    for(i in data){
                        
                        if(kdprodi != data[i].nim){
                            var obj = {};
                            obj['id']    = data[i].nim;
                            obj['text']  = data[i].nim+" / "+data[i].nama;
                            arraydata[i] = obj;
                        } 
                        
                    }

                    var filtered = arraydata.filter(function (el) {
                        return el != null;
                      });

                    $(".select2-hidden-accessible").select2({
                        minimumResultsForSearch: Infinity,
                        allowClear: true,
                        // containerCssClass: 'select-xs',
                        // tags: true,
                        maximumSelectionLength: 5,
                        placeholder: " Pilih Mahasiswa...",
                        data: filtered
                    });
                        // console.log(filtered);
                }else{
                    // swal({
                    //     title: "Alert",
                    //     text:  response.info+ " Silahkan coba kembali :)",
                    //     confirmButtonColor: "#2196F3",
                    //     type: "error"
                    // });  
                };
    
                loaderPage(false);
                
            },
            error: function () {
                loaderPage(false);
                if(xhr.status != 200){
                    swal({
                        title: "Alert",
                        text:  xhr.status+"-"+xhr.statusText+" Silahkan coba kembali :)",
                        confirmButtonColor: "#2196F3",
                        type: "error"
                    });                        
                }
            }
        });
    }



    $('.pickadate').pickadate({
        // Escape any “rule” characters with an exclamation mark (!).
        // minDate: new Date.now(),
        // minDate: '22/10/2020',
        format: 'dd mmmm yyyy',
        formatSubmit: 'yyyy/mm/dd',
        // monthsFull: ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'],
        hiddenPrefix: 'prefix__',
        hiddenSuffix: '__suffix'
    });

    $("#tanggalAwaledt").change(function(){
        //// console.log($("#tanggalAwaledt").val());
    })

    $('.daterange-basic').daterangepicker({
        applyClass: 'bg-slate-600',
        cancelClass: 'btn-default'
    });

    $(".btn-modal").on("click", function(){
        $("#modal-add").modal("show");
    })

    $(".btn-modalupdate").on("click", function(){
        $("#modal-update").modal("show");
    })

    $(".btn-conf").on("click", function(){
        $("#modal-conf").modal("show");
    })
    

    $("#submitpengajuan").on("click", function(){
        var $ckaaks = $(".select2-hidden-accessible").val();
        var jmlpengajuan = $("#jmlpengajuan").val();

        $(this).attr('disabled',true);
        savepengajuan();
    })

    $("#submitupdate").on("click", function(){
        // // console.log($("#tanggalAwaledt").val())
        // isFutureDateupd($("#tanggalAwaledt").val())
        $(this).attr('disabled',true);
        updatepengajuan();
    })

    $(".alertno").hide()
    $('input[name="konfirmasi"]').change(function(){
        var isconf = $('input[name="konfirmasi"]:checked').val();
        
        if(isconf == 101){
            $(".panel-body > fieldset").show();
            $(".alertno").hide()
        }else {
            $(".panel-body > fieldset").hide();
            $(".alertno").show()
        }
    })

    $("#submitconf").on("click",function(e){
        e.preventDefault();
        requestconfirmation();
    })

    // // console.log(nim);

    

    // $("#download").on('click', function(){
    //     alert('jaw')
    // })

    
});



$(".btn-download").on('click', function(){
    var id  = $("#id_pengajuan").val();
    var nim = $("#nim_mhs").val();
    var dir = $("#file_name").val();
    var exploded = dir.split('/');
    // // console.log(nim)
    // // console.log(id)
    window.open(baseURL+'/data/surat/'+exploded[4]);
})

function requestconfirmation(){
    const file = $('#file').prop('files')[0];
    var isObject = {};
    let formdata = new FormData();
    
    isObject.status     = $('input[name="konfirmasi"]:checked').val();
    isObject.nim        = $("#nim_mhsconf").val();
    isObject.perusahaan = $("#namaper").val();
    

   
    if(isObject.status == 102){ //ditolak

        


        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: baseURL + '/jsondata/konfirmasiperusahaan',
            data: {
                iparam	    : cryptoEncrypt(PHRASE, isObject),
            },
            success: function (response) {
                // $('#modal-add').modal("hide");
                if(response.code == CODE_SUCCESS){
    
                    // document.getElementById("form-data").reset();
                    var object2 = isObject.nimmhs;
                    swal({
                        title: "Alert",
                        text: "Surat permohonan ditolak, silahkan buat surat permohonan kembali",
                        confirmButtonColor: "#66BB6A",
                        type: "success"
                    }, function(){ 
                        // $("tbody").empty();
                        // loadElementsMhs();
                        location.reload()
                        
                    });
    
                }else{
                    swal({
                        title: "Alert",
                        text:  response.info+ " Silahkan coba kembali :)",
                        confirmButtonColor: "#2196F3",
                        type: "error"
                    });  
                };
    
                loaderPage(false);
                
            },
            error: function () {
                loaderPage(false);
                if(xhr.status != 200){
                    swal({
                        title: "Alert",
                        text:  xhr.status+"-"+xhr.statusText+" Silahkan coba kembali :)",
                        confirmButtonColor: "#2196F3",
                        type: "error"
                    });                        
                }
            }
        });

        
    } else if (isObject.status == 101){ //diterima
        
        
        isObject.perusahaan         = $("#namaper").val();
        isObject.staff              = $("#staff").val();
        isObject.staffkontak        = $("#kontak").val();
        isObject.alamat_perusahaan  = $("#alamatper").val();
        isObject.syarat             = $("#syarat").val();
        isObject.jumlahmhsw         = $("#jmlmhsw").val();
        isObject.transport          = $('input[name="transport"]:checked').val();
        isObject.penginapan         = $('input[name="penginapan"]:checked').val();
        isObject.makan              = $("#makan").val();
        isObject.asuransi           = $("#asuransi").val();
        isObject.lainnya            = $("#lain").val();
        isObject.bukti              = file;
        isObject.tanggalAwal        = dateformats($("#tanggalAwalconf").val());
        isObject.tanggalAkhir       = dateformats($("#tanggalAkhirconf").val());
        // console.log(isObject);  


        // if(isObject.noref == null || isObject.noref == ""){
        //     wrongvalidation("No Referensi Tidak Boleh Kosong");
        //     return false;
        // }

        if(isObject.perusahaan == null || isObject.perusahaan ==""){
            wrongvalidation("Nama Perusahaan Tidak Boleh Kosong");
            return false;
        }

        // if(isObject.staff == null || isObject.staff ==""){
        //     wrongvalidation("Staff Perusahaan Tidak Boleh Kosong");
        //     return false;
        // }

        // if(isObject.staffkontak == null || isObject.staffkontak ==""){
        //     wrongvalidation("Kontak Perusahaan Tidak Boleh Kosong");
        //     return false;
        // }

        // if(isObject.alamat_perusahaan == null || isObject.alamat_perusahaan ==""){
        //     wrongvalidation("Alamat Perusahaan Tidak Boleh Kosong");
        //     return false;
        // }

        // if(isObject.transport == null || isObject.transport ==""){
        //     wrongvalidation("Transport Perusahaan Tidak Boleh Kosong");
        //     return false;
        // }

        // if(isObject.penginapan == null || isObject.penginapan ==""){
        //     wrongvalidation("Penginapan Perusahaan Tidak Boleh Kosong");
        //     return false;
        // }

        // if(isObject.makan == null || isObject.makan ==""){
        //     wrongvalidation("Uang Makan Perusahaan Tidak Boleh Kosong");
        //     return false;
        // }

        // if(isObject.asuransi == null || isObject.asuransi ==""){
        //     wrongvalidation("Asuransi Perusahaan Tidak Boleh Kosong");
        //     return false;
        // }

            // if(isObject.asuransi == null || isObject.asuransi ==""){
            //     wrongvalidation("Nama Perusahaan Tidak Boleh Kosong");
            //     return false;
            // }

        if(document.getElementById("file").files.length == 0 ){
            wrongvalidation("File Tidak Boleh Kosong");
            return false;
        } else {

            var regexpattern = /[\/.](pdf)$/i;
            // let nimMhs = nim;
            let namefile = isObject.bukti.name;
            // console.log(namefile)
            if(!regexpattern.test(namefile)){
                wrongvalidation('File Harus Berupa PDF!');
                return false;
            } 
        }

        if(!isFutureDate(isObject.tanggalAwal)){
            // // console.log(isFutureDateupd(isObject.tanggalAwal));
            swal({
                title: "Peringatan!",
                text:" Tanggal tidak valid",
                confirmButtonColor: "#2196F3",
                type: "warning"
            });
            return false;
        } else if(!daterangeCheck(isObject.tanggalAwal, isObject.tanggalAkhir)){
            swal({
                title: "Peringatan!",
                text:" Tanggal akhir tidak boleh kurang dari tanggal awal",
                confirmButtonColor: "#2196F3",
                type: "warning"
            });
            return false;
        }

        formdata.append('file', isObject.bukti);
        // formdata.append('noref', isObject.noref);
        formdata.append('namaper', isObject.perusahaan);
        formdata.append('staff', isObject.staff);
        formdata.append('kontakstaff', isObject.staffkontak);
        formdata.append('alamat', isObject.alamat_perusahaan);
        formdata.append('syarat', isObject.syarat);
        formdata.append('jumlahmhsw', isObject.jumlahmhsw);
        formdata.append('transpot', isObject.transport);
        formdata.append('penginapan', isObject.penginapan);
        formdata.append('makan', isObject.makan);
        formdata.append('asuransi', isObject.asuransi);
        formdata.append('lainnya', isObject.lainnya);
        formdata.append('tglawal', isObject.tanggalAwal);
        formdata.append('tglakhir', isObject. tanggalAkhir);
        formdata.append('nim', isObject.nim);
        formdata.append('status', isObject.status);

        $.ajax({
            type        : 'POST',
            url         : baseURL + '/jsondata/konfirmasivalid',
            data        : formdata,
            cache       : false,
            processData : false,
            contentType : false,
            success: function (response) {
    
                if(response.code == CODE_SUCCESS){
                    loaderPage(false)
                    // document.getElementById("form-data").reset();
    
                    swal({
                        title:"Alert",
                        text: "Data konfirmasi telah di upload, hubungi TU untuk memvalidasi ",
                        confirmButtonColor: "#66BB6A",
                        type: "success"
                    },function(){ 
                        // $("#file1").prop("disabled", true);
                        // $("#file1").prop("disabled", true);
                        // $("#file1").prop("disabled", true);
                        // $("#file1").prop("disabled", true);
                        window.location.reload();
                    });
    
                }else{
                    swal({
                        title: "Alert",
                        text:  response.info+ " Silahkan coba kembali :)",
                        confirmButtonColor: "#2196F3",
                        type: "error"
                    });  
                };
    
                loaderPage(false);
                
            },
            error: function () {
                loaderPage(false);
                if(xhr.status != 200){
                    swal({
                        title: "Alert",
                        text:  xhr.status+"-"+xhr.statusText+" Silahkan coba kembali :)",
                        confirmButtonColor: "#2196F3",
                        type: "error"
                    });                        
                }
            }
        });
    }
}

async function savepengajuan(){


    var isObject = {};
    loaderPage(true);
    var telppattern             = /\+?([ -]?\d+)+|\(\d+\)([ -]\d+)/;

    isObject.nama_perusahaan    = $("#nama_perusahaan").val();
    isObject.penerima_surat     = $("#penerima_surat").val();
    isObject.telp_perusahaan    = $("#telp_perusahaan").val();
    isObject.tanggalAwal        = dateformats($("#tanggalAwal").val());
    isObject.tanggalAkhir       = dateformats($("#tanggalAkhir").val());
    isObject.alamat_perusahaan  = $("#alamat_perusahaan").val();
    isObject.nim                = $("#nim_mhs").val();
    isObject.pos                = $("#pos_perusahaan").val();
    isObject.divisi             = $("#divisi_penerima").val();
    isObject.kodeprodi          = isObject.nim.substr(0, 3);
    isObject.jmlpengajuan       = $("#jmlpengajuan").val();
    
    console.log(isObject);
    const respeng = await isPengajuanExist(isObject.jmlpengajuan, isObject.nim);
    let datasss   = cryptoDecrypt(PHRASE, respeng.data);
    let validatedM = datasss.data;
    // console.log(validatedM);return false;
    if(validatedM > 0){
        $("#submitpengajuan").attr('disabled',false);
        var txtd = "Mahasiswa dengan NIM:\n";
        for(i in validatedM){
            txtd += (parseInt(i+1))+". "+validatedM[i].nim+" / "+validatedM[i].nama
        }
        txtd += "\nTidak dapat melakukan pengajuan karena terdapat pengajuan aktif.";
        swal({
            title: "Alert",
            text:  txtd,
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    }
    // console.log(datasss);
    // return false;
    
    if(isObject.nama_perusahaan == "" || isObject.nama_perusahaan == null){
        $("#submitpengajuan").attr('disabled',false);
        swal({
            title: "Alert",
            text:  "Nama perusahaan tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    }

    if(isObject.penerima_surat == "" || isObject.penerima_surat == null){
        $("#submitpengajuan").attr('disabled',false);
        swal({
            title: "Alert",
            text:  "Penerima tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    }

    if(!telppattern.test(isObject.telp_perusahaan)){
        $("#submitpengajuan").attr('disabled',false);
        swal({
            title: "Alert",
            text:  "Telepon perusahaan kosong/tidak valid",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
     } 

    if(isObject.tanggalAwal == "" || isObject.tanggalAwal == null){
        $("#submitpengajuan").attr('disabled',false);
        swal({
            title: "Alert",
            text:  "Tanggal Mulai tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    }

    if(isObject.tanggalAkhir == "" || isObject.tanggalAkhir == null){
        $("#submitpengajuan").attr('disabled',false);
        swal({
            title: "Alert",
            text:  "Tanggal Berhenti tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    }

    if(isObject.alamat_perusahaan == "" || isObject.alamat_perusahaan == null){
        $("#submitpengajuan").attr('disabled',false);
        swal({
            title: "Alert",
            text:  "Tanggal Berhenti tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    }

    if(isObject.pos.length < 1){
        $("#submitpengajuan").attr('disabled',false);
        swal({
            title: "Alert",
            text:  "Kode pos tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    } else if(isObject.pos.length > 5){
        $("#submitpengajuan").attr('disabled',false);
        swal({
            title: "Alert",
            text:  "Kode pos tidak boleh lebih dari 5 digit",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    } else if(isObject.pos.length < 5 && isObject.pos.length > 1){
        $("#submitpengajuan").attr('disabled',false);
        swal({
            title: "Alert",
            text:  "Kode pos tidak boleh kurang dari 5 digit",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    }


    // if(!isFutureDate(isObject.tanggalAwal)){
    //     $("#submitpengajuan").attr('disabled',false);
    //     swal({
    //         title: "Peringatan!",
    //         text:" Tanggal tidak valid",
    //         confirmButtonColor: "#2196F3",
    //         type: "warning"
    //     });loaderPage(false);
    //     return false;
    // } else 
    if(!daterangeCheck(isObject.tanggalAwal, isObject.tanggalAkhir)){
        $("#submitpengajuan").attr('disabled',false);
        swal({
            title: "Peringatan!",
            text:" Tanggal akhir tidak boleh kurang dari tanggal awal",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    } else if(minimalkp(isObject.tanggalAwal, isObject.tanggalAkhir) < 21){
        $("#submitpengajuan").attr('disabled',false);
        swal({
            title: "Peringatan!",
            text:   "Waktu pelaksanaan kerja praktik minimal 21 hari, silahkan ubah tanggal",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    }

    

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/savepengajuan',
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function (response) {
            $('#modal-add').modal("toggle");
            $("#submitpengajuan").attr('disabled',false);
            if(response.code == CODE_SUCCESS){

                // document.getElementById("form-data").reset();
                var object2 = isObject.nimmhs;
                swal({
                    title: "Alert",
                    text: "Surat pengantar KP telah diajukan ",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){ 
                    // $("tbody").empty();
                    // loadElementsMhs();
                    location.reload()
                    
                });
                location.reload()
            }else{
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            };
            // $("#submitpengajuan").attr('disabled',false);
            loaderPage(false);
            
        },
        error: function () {
            loaderPage(false);
            $("#submitpengajuan").attr('disabled',false);
            if(xhr.status != 200){
                swal({
                    title: "Alert",
                    text:  xhr.status+"-"+xhr.statusText+" Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });

}

function updatepengajuan(){
    loaderPage(true);
    var isObject = {};

    isObject.nama_perusahaan    = $("#nama_perusahaanedt").val();
    isObject.penerima_surat     = $("#penerima_suratedt").val();
    isObject.telp_perusahaan    = $("#telp_perusahaanedt").val();
    isObject.tanggalAwal        = dateformats($("#tanggalAwaledt").val());
    isObject.tanggalAkhir       = dateformats($("#tanggalAkhiredt").val());
    isObject.alamat_perusahaan  = $("#alamat_perusahaanedt").val();
    isObject.nim                = $("#nim_mhsedt").val();
    isObject.pos                = $("#pos_perusahaanedt").val()
    isObject.divisi             = $("#divisi_penerimaedt").val();
    
    // console.log(isObject);
    
    if(isObject.nama_perusahaan == "" || isObject.nama_perusahaan == null){
        swal({
            title: "Alert",
            text:  "Nama perusahaan tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    }

    if(isObject.penerima_surat == "" || isObject.penerima_surat == null){
        swal({
            title: "Alert",
            text:  "Penerima tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    }

    if(isObject.telp_perusahaan == "" || isObject.telp_perusahaan == null){
        swal({
            title: "Alert",
            text:  "Telepon perusahaan tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    }

    if(isObject.tanggalAwal == "" || isObject.tanggalAwal == null){
        swal({
            title: "Alert",
            text:  "Tanggal Mulai tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    }

    if(isObject.tanggalAkhir == "" || isObject.tanggalAkhir == null){
        swal({
            title: "Alert",
            text:  "Tanggal Berhenti tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    }

    if(isObject.alamat_perusahaan == "" || isObject.alamat_perusahaan == null){
        swal({
            title: "Alert",
            text:  "Tanggal Berhenti tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    }

    if(!isFutureDate(isObject.tanggalAwal)){
        // // console.log(isFutureDateupd(isObject.tanggalAwal));
        swal({
            title: "Peringatan!",
            text:" Tanggal tidak valid",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    } else if(!daterangeCheck(isObject.tanggalAwal, isObject.tanggalAkhir)){
        swal({
            title: "Peringatan!",
            text:" Tanggal akhir tidak boleh kurang dari tanggal awal",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });loaderPage(false);
        return false;
    }

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/updatepengajuan',
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function (response) {
            $('#modal-update').modal("toggle");
            if(response.code == CODE_SUCCESS){

                // document.getElementById("form-data").reset();
                var object2 = isObject.nimmhs;
                swal({
                    title: "Alert",
                    text: "Surat pengantar KP telah diubah",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){ 
                    // $("tbody").empty();
                    // loadElementsMhs();
                    location.reload()
                });

            }else{
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            };

            loaderPage(false);
            
        },
        error: function () {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Alert",
                    text:  xhr.status+"-"+xhr.statusText+" Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });

}

function dateformats(date){
    var months    = {
        'January': 1,
        'February': 2,
        'March': 3,
        'April': 4,
        'May': 5,
        'June': 6,
        'July': 7,
        'August': 8,
        'September': 9,
        'October': 10,
        'November': 11,
        'December': 12
    };
    // console.log(date);
    var datesplit = date.split(' ')
    var tanggal   = datesplit[0];
    var bulan     = months[datesplit[1]];
    var tahun     = datesplit[2];

    var datestring = tanggal +"-"+bulan+"-"+tahun;
    // console.log(datestring)
    // var dateNew     = new Date(date);
    // var dateString  = 
    //     ("0" + (dateNew.getUTCDate()+1)).slice(-2) + "-" +
    //     ("0" + (dateNew.getUTCMonth()+1)).slice(-2) + "-" +
    //     dateNew.getUTCFullYear();

    return datestring;
}

function dateformatss(date){
    var dateNew     = new Date(date);
    var dateString  = 
        ("0" + (1 + dateNew.getUTCDate())).slice(-2) + "-" +
        ("0" + (dateNew.getUTCMonth()+1)).slice(-2) + "-" +
        dateNew.getUTCFullYear();

    return dateString;
}

function isFutureDate(idate){
    var today = new Date().getTime();
    var idate = idate.split("-");

    idate = new Date(idate[2], idate[1] - 1, idate[0]).getTime();
    console.log("idate: "+idate);
    return (today - idate) < 0;
}

function isFutureDateupd(idate){
    var today = new Date().getTime();
    var idate = idate.split("-");

    idate = new Date(idate[2], idate[1] - 1, idate[0]).getTime();
    // console.log(idate);
    return (today - idate) < 0;
}

function daterangeCheck(idateAW, idateAK){
    console.log(idateAW);
    console.log(idateAK)
    var idateAK = idateAK.split("-");
    var idateAW = idateAW.split("-");

    idateAW = new Date(idateAW[2], idateAW[1] - 1, idateAW[0]).getTime();
    idateAK = new Date(idateAK[2], idateAK[1] - 1, idateAK[0]).getTime();

    console.log(idateAW - idateAK);
    return (idateAW - idateAK) < 0;
}

function datefordetail(date1){
    let date_aw = new Date(date1);

    let date = ("0" + date_aw.getDate()).slice(-2);
    let month = ("0" + (date_aw.getMonth() + 1)).slice(-2);
    let year = date_aw.getFullYear();

    return date + " / " + month + " / " + year ;
}

loadElementspengajuan();
function loadElementspengajuan(clicksc){
    loaderPage(true)
    let isObject     = {}; 
    isObject.ipoly   = 1;

    var dtpr = $('#list_pengajuan').DataTable({
        serverSide	: true,
        destroy		: true,
        bFilter		: true,
        responsive	: true,
        searching   : true,
        pagingType  : 'full',
        lengthMenu  : [[1, 25, 50, -1], [1, 25, 50, "All"]],
        pageLength  : 25,
        ajax		: {
            url: baseURL + '/jsondata/listpengajuan',
            type: 'POST',
            // async: false,
            data : function (d) {         
                return $.extend( {}, d, {
                    iparam	    : cryptoEncrypt(PHRASE, isObject),
                });
            },
            dataSrc: function(response) {
                
                if(response.code == CODE_SUCCESS){
                    response = cryptoDecrypt(PHRASE, response.data);
                    // // console.log(response.data.data);
                    var data = response.data.data;
                    // var datas;
                    // var dataada=[];
                    // // datas.push(data[0])
                    // // // console.log(datas);
                    // for(i in data){
                    //     datas = {
                    //         "id_mhs": data[i].id_mhs,
                    //         "nim": data[i].nim,
                    //         "nama": data[i].nama,
                    //         "jurusan": data[i].jurusan,
                    //         "jeniskelamin": data[i].jeniskelamin,
                    //         "fakultas": data[i].fakultas,
                    //         "create_date": data[i].create_date,
                    //         // "status": statusberkas(data[i].nim)
                    //     }
                    //     dataada.push(datas)
                    // }
                    // console.log(data)
                    return data;
                }else{
                    return response;
                }
               
            }
        },	
        columns: [
            { 'data': 'id_pengajuan', 'sClass':'','sWidth':'10px'},
            { 'data': 'nama_perusahaan', 'sClass':''},
            { 'data': 'alamat_perusahaan', 'sClass':''},
            { 'data': 'nama_penerima_perusahaan', 'sClass':''},
            { 'data': 'status', 'sClass':'text-center'},
            // { 'data': '', 'sClass':'text-center','sWidth':'10px'}
        ],
        buttons: {            
            buttons: [
                {
                    extend: 'colvis',
                    className: 'btn btn-default'
                },
            ]
        },
        processing: true,
        stateSave: false,
        autoWidth: false,
        dom: '<"datatable-header"fBl><"datatable-scroll-wrap"t><"datatable-footer"ip>',
        language: {
            search: '<span>Filter:</span> _INPUT_',
            lengthMenu: '<span>Show:</span> _MENU_',
            processing: "<div class='table-loading'><img src='../../img/loadingtwo.gif' /></div>",

            paginate: { 'first': 'First', 'last': 'Last', 'next': '&rarr;', 'previous': '&larr;' }
        },
        columnDefs: [
            {
                width: '20px',
                targets: 0,
                visible: true
            },
            {   


                // render: function (data, type, row){
                //     // var $rowData = '<img src="/distro/assets/images/placeholder.jpg" alt="" class="img-rounded img-preview showAtt" style="cursor: pointer;">';
                //     let isIcon = ' icon-file-download2';

                //     var $rowData = '<div class="thumb img-rounded img-preview showAtt" style="width: 70px;">'+
                //         '<img src="/distro/assets/images/placeholder.jpg" alt="" class="img-rounded img-preview showAtt">'+
                //         '<div class="caption-overflow">'+
                //             '<span>'+
                //                 '<p  class="btn showAtt bg-success-400 btn-icon btn-lg" style="font-variant: all-petite-caps;background-color: #0e0e0e33 !important;border-color: #25252591 !important;">'+
                //                     '<i class="'+isIcon+'"></i> '
                //                 '</p>'+
                //             '</span>'+
                //         '</div>'+
                //     '</div>';

                //     return $rowData;
                // },
                // visible: true,
                // targets: 1,
            },  
            {   
                render: function (data, type, row){
                    // // console.log(row);
                    var $rowData = ``;
                    if(row.status_pengajuan == 91){
                        $rowData ='<span style="min-width: 70px" class="label bg-grey-400">'+row.status+'</span>';
                    }else if(row.status_pengajuan == 92){
                        $rowData = '<span style="min-width: 70px" class="label label-success">'+row.status+'</span>';
                    }else if(row.status_pengajuan == 102){
                        $rowData ='<span style="min-width: 70px" class="label label-danger">'+row.status+'</span>';
                    }else if(row.status_pengajuan == 103){
                        $rowData ='<span style="min-width: 70px" class="label label-primary">'+row.status+'</span>';
                    }else if(row.status_pengajuan == 101){
                        $rowData = '<span style="min-width: 70px" class="label label-success">'+row.status+'</span>';
                    }
                    else if(row.status_pengajuan == 104){
                        $rowData = '<span style="min-width: 70px" class="label label-success">'+row.status+'</span>';
                    }
                    else if(row.status_pengajuan == 105){
                        $rowData = '<span style="min-width: 70px" class="label label-danger">'+row.status+'</span>';
                    }
                    return $rowData;
                },
                visible: true,
                targets: 4,
            }, 
            // {   
            //     render: function (data, type, row){
            //         // // console.log(row);
            //         var $rowData = ``;

                    
            //             $rowData = `<ul class="icons-list">
            //                             <li class="dropdown">
            //                                 <a href="#" class="dropdown-toggle" data-toggle="dropdown">
            //                                     <i class="icon-menu9"></i>
            //                                 </a>

            //                                 <ul class="dropdown-menu dropdown-menu-right">
                                            
            //                                     <li class=""><a "><i class=" icon-file-eye2"></i> Lihat Surat</a></li>                                              
            //                                     <li><a><i class="icon-user-cancel"></i> Delete Pengajuan</a></li>
            //                                 </ul>
            //                             </li>
            //                         </ul>`;
                    

            //         return $rowData;
            //     },
            //     visible: true,
            //     targets: 5,
            //     className: 'dt-center'
            // }, 
        ],
        fnRowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull){ 
            var index = iDisplayIndexFull + 1; 
            $('td:eq(0)', nRow).html('#'+index); 
            return  index;
        },
        drawCallback: function (settings) {
            // // console.log(settings.json);
            
            var api  = this.api();
            var rows = api.rows({page:'current'}).nodes();
            var last = null;

            // // console.log(rows)
            // Reverse last 3 dropdowns orientation
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');

            var that = this;
            var td ;
            var tr ;

            this.$('td').click( function () {
                td = this;
            });
            this.$('tr').click( function () {
                tr = this;
            });

            this.$('.showAtt').on('click', function(){

                var tr      = $(this).parents('tr')
                var aData   = dtpr.row( tr ).data();

                // loadAttachments(aData);

            });

            
        },
        fnInitComplete: function (oSettings, json) {
            var that = this;
            var td ;
            var tr ;

            this.$('td').click( function () {
                td = this;
            });
            this.$('tr').click( function () {
                tr = this;
            });

            

            $('#mahasiswalist input').bind('keyup', function (e) {
                return this.value;
            });

            setIFrameSize();

        }
    });

}
var statuskp = loadstatuskp(nim);
pengajuannow(nim, statuskp);
function pengajuannow(nim, statuskp){
    let isObject = {};
    isObject.param = nim;

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/detailpengajuan',
        // async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            // // console.log(response.code)
            
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                let data    = result.data[0];
                console.log(data);
                // console.log(data.id_pengajuan);
                $("#id_pengajuan").val(data.id_pengajuan);
                $("#file_name").val(data.file_name);
                $(".btn-download").attr("disabled", false)

                $("#nama").html(data.nama_perusahaan);
                $("#alamat").html(data.alamat_perusahaan);
                $("#telepon").html(data.no_telp);
                $("#penerima").html(data.nama_penerima_perusahaan);
                $("#bagian").html(data.divisi_penerima);
                $("#tanggal").html(hereys2(data.tanggal_kerja_praktik_awal) + " Sampai " + hereys2(data.tanggal_kerja_praktik_akhir));
                
                if(data.status_pengajuan == 91){
                    $(".btn-modal").hide()
                    $(".btn-download").attr("disabled", true)
                    $(".btn-conf").attr("disabled", true)
                    $(".btn-kirimperusahaan").attr("disabled", true)
                    $(".btn-modaltopik").attr("disabled", true)
                    $("#status").html("Menunggu Surat Dibuat");
                } else if(data.status_pengajuan == 92){
                    $(".btn-modal").hide()
                    $(".btn-download").attr("disabled", false)
                    $(".btn-modalupdate").attr("disabled", true)
                    $(".btn-kirimperusahaan").attr("disabled", false)
                    $(".btn-conf").attr("disabled", false)
                    $(".btn-modaltopik").attr("disabled", true)
                    $("#status").html("Surat Telah Dibuat");
                } else if(data.status_pengajuan == 102){
                    $(".btn-modal").show();
                    $(".btn-modalupdate").attr("disabled", true)
                    $(".btn-download").attr("disabled", true)
                    $(".btn-kirimperusahaan").attr("disabled", true)
                    $(".btn-conf").attr("disabled", true)
                    $(".btn-modaltopik").attr("disabled", true)
                    $("#status").html("Ditolak oleh perusahaan");
                } else if(data.status_pengajuan == 101){
                    $(".btn-modal").hide()
                    $(".btn-modalupdate").attr("disabled", true)
                    $(".btn-download").attr("disabled", true)
                    $(".btn-kirimperusahaan").attr("disabled", true)
                    $(".btn-conf").attr("disabled", true)
                    $(".btn-modaltopik").attr("disabled", false)
                    $("#status").html("Diterima oleh perusahaan");
                } else if(data.status_pengajuan == 103){
                    $(".btn-modal").hide()
                    $(".btn-modalupdate").attr("disabled", true)
                    $(".btn-download").attr("disabled", true)
                    $(".btn-kirimperusahaan").attr("disabled", true)
                    $(".btn-conf").attr("disabled", true)
                    $(".btn-modaltopik").attr("disabled", true)
                    $("#status").html("Menunggu Review Akademik");
                } 
                else if(data.status_pengajuan == 104){
                    $(".btn-modal").hide()
                    $(".btn-modalupdate").attr("disabled", true)
                    $(".btn-download").attr("disabled", true)
                    $(".btn-kirimperusahaan").attr("disabled", true)
                    $(".btn-conf").attr("disabled", true)
                    $(".btn-modaltopik").attr("disabled", false)
                    $("#status").html("Konfirmasi Pengajuan Valid");
                } 
                else if(data.status_pengajuan == 105){
                    $(".btn-modal").attr("disabled", false)
                    $(".btn-modalupdate").attr("disabled", true)
                    $(".btn-download").attr("disabled", true)
                    $(".btn-kirimperusahaan").attr("disabled", true)
                    $(".btn-conf").attr("disabled", true)
                    $(".btn-modaltopik").attr("disabled", true)
                    $("#status").html("Konfirmasi tidak valid");
                }

                //dom modal update
                $("#nama_perusahaanedt").val(data.nama_perusahaan);
                $("#penerima_suratedt").val(data.nama_penerima_perusahaan);
                $("#telp_perusahaanedt").val(data.no_telp);
                $("#tanggalAwaledt").val(herey(data.tanggal_kerja_praktik_awal));
                $("#tanggalAkhiredt").val(herey(data.tanggal_kerja_praktik_akhir))
                $("#alamat_perusahaanedt").val(data.alamat_perusahaan);
                // $("#nim_mhs").val();
                $("#pos_perusahaanedt").val(data.kode_pos)
                $("#divisi_penerimaedt").val(data.divisi_penerima);

                //dom modal conf
                $("#namaper").val(data.nama_perusahaan);
                $("#alamatper").val(data.alamat_perusahaan+" "+data.kode_pos);

                if(statuskp == 123 && data.status_pengajuan == 104){
                    $(".btn-modal").attr("disabled", false);
                    $("#status").html("Kerja Praktik Gagal, silahkan membuat pengajuan kembali");
                    
                }

            } else {
                $(".btn-modalupdate").attr("disabled", true)
                $(".btn-download").attr("disabled", true)
                $(".btn-conf").attr("disabled", true)
                // // console.log("data")
            }
            
        },
        error: function(xhr) {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });
}


function loadstatuskp(nim){
    let isObject = {};
    isObject.param = nim;
    var status;

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loadstatuskp',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            // // console.log(response.code)
            
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                let data    = result.data[0];
                console.log(data)
                status      = data.status_kp;
                objLoad     = data;
                // console.log('disini gan')
                // console.log(data.status_kp);
            } else {
               // belum pernah kp
            }
            
        },
        error: function(xhr) {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });
    return status;
}

//untuktanggal
function hereys2(dates){
        var tgl = dates.split(' ');
        // console.log(tgl);
        var tanggal = tgl[0].split('-');
        var tahun = tanggal[0];
        var bulan = tanggal[1];
        var hari  = tanggal[2];
        // // console.log(hari+"-"+bulan+"-"+tahun)
        var datestring = hari+"-"+bulan+"-"+tahun;
        return datestring;
}

function herey(dates){
    var tgl = dates.split(' ');
    // console.log(tgl);
    var tanggal = tgl[0].split('-');
    var tahun = tanggal[0];
    var bulan = tanggal[1];
    var hari  = tanggal[2];
    var date = new Date(dates);
     let monthNames =["January","February","March","April",
    "May","June","July","August",
    "September", "October","November","December"];
    var month = monthNames[parseInt(bulan)-1]
    // console.log(bulan);
    // console.log(parseInt(bulan))
    
    var datestring = hari+" "+month+" "+tahun;
    return datestring;
    // let monthNames =["January","February","March","April",
    // "May","June","July","August",
    // "September", "October","November","December"];

    // let day = date.getDate();

    // let monthIndex = date.getMonth();
    // let monthName = monthNames[monthIndex];
    // let year = date.getFullYear();

    // // console.log(day)
    // return `${day} ${monthName} ${year}`; 
    
    
    // return moment(date).format('D MMMM Y');
    
}

function wrongvalidation(msg){
    swal({
        title: "Alert",
        text:  msg,
        confirmButtonColor: "#2196F3",
        type: "warning"
    }); 

    return false;
}

function minimalkp(tglawal, tglakhir){
    // var tgl1 = tglawal.replaceAll("-", "/"); 
    // var tgl2 = tglakhir.replaceAll("-", "/");
    var tgl1 = convertime(tglawal);
    var tgl2 = convertime(tglakhir);
    
    // console.log(tgl1);
    // var date1 = new Date(tgl1); 
    // var date2 = new Date(tgl2); 
    // // console.log(date1);
    
    // To calculate the time difference of two dates 
    var Difference_In_Time = tgl2 - tgl1; 
    
    // To calculate the no. of days between two dates 
    var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24); 
    // console.log(Difference_In_Days);
    return Difference_In_Days;
}

function convertime(idate){
   
    var idate = idate.split("-");

    idate = new Date(idate[2], idate[1] - 1, idate[0]).getTime();
    // console.log(idate);
    return idate;
}

loadperusahaan();
function loadperusahaan(clicksc){
    loaderPage(true)
    let isObject     = {}; 
    isObject.ipoly   = 1;

    var dtpr = $('#list_perusahaan').DataTable({
        serverSide	: true,
        destroy		: true,
        bFilter		: true,
        responsive	: true,
        searching   : true,
        pagingType  : 'full',
        lengthMenu  : [[1, 25, 50, -1], [1, 25, 50, "All"]],
        pageLength  : 25,
        ajax		: {
            url: baseURL + '/jsondata/listperusahaan',
            type: 'POST',
            // async: false,
            data : function (d) {         
                return $.extend( {}, d, {
                    iparam	    : cryptoEncrypt(PHRASE, isObject),
                });
            },
            dataSrc: function(response) {
                
                if(response.code == CODE_SUCCESS){
                    response = cryptoDecrypt(PHRASE, response.data);
                    // // console.log(response.data.data);
                    var data = response.data.data;
                    // console.log(response)
                    return data;
                }else{
                    return response;
                }
               
            }
        },	
        columns: [
            { 'data': 'nama_perusahaan_kp', 'sClass':'','sWidth':'10px'},
            { 'data': 'nama_perusahaan_kp', 'sClass':''},
            { 'data': 'alamat', 'sClass':''},
            { 'data': 'no_telp', 'sClass':''},
            { 'data': 'jumlah_mahasiswa', 'sClass':'text-center'},
            // { 'data': '', 'sClass':'text-center','sWidth':'10px'}
        ],
        buttons: {            
            buttons: [
                {
                    extend: 'colvis',
                    className: 'btn btn-default'
                },
            ]
        },
        processing: true,
        stateSave: false,
        autoWidth: false,
        dom: '<"datatable-header"fBl><"datatable-scroll-wrap"t><"datatable-footer"ip>',
        language: {
            search: '<span>Filter:</span> _INPUT_',
            lengthMenu: '<span>Show:</span> _MENU_',
            processing: "<div class='table-loading'><img src='../../img/loadingtwo.gif' /></div>",

            paginate: { 'first': 'First', 'last': 'Last', 'next': '&rarr;', 'previous': '&larr;' }
        },
        columnDefs: [
            {
                width: '20px',
                targets: 0,
                visible: true
            },
            {   


                render: function (data, type, row){
                    let $rowData = row.alamat + ", " +row.kode_pos;
                    // console.log(row);

                    return $rowData;
                },
                visible: true,
                targets: 2,
            },  
            {   
                // render: function (data, type, row){
                //     // // console.log(row);
                //     var $rowData = ``;
                //     if(row.status_pengajuan == 91){
                //         $rowData ='<span style="min-width: 70px" class="label bg-grey-400">'+row.status+'</span>';
                //     }else if(row.status_pengajuan == 92){
                //         $rowData = '<span style="min-width: 70px" class="label label-success">'+row.status+'</span>';
                //     }else if(row.status_pengajuan == 102){
                //         $rowData ='<span style="min-width: 70px" class="label label-danger">'+row.status+'</span>';
                //     }else if(row.status_pengajuan == 103){
                //         $rowData ='<span style="min-width: 70px" class="label label-primary">'+row.status+'</span>';
                //     }else if(row.status_pengajuan == 101){
                //         $rowData = '<span style="min-width: 70px" class="label label-success">'+row.status+'</span>';
                //     }
                //     else if(row.status_pengajuan == 104){
                //         $rowData = '<span style="min-width: 70px" class="label label-success">'+row.status+'</span>';
                //     }
                //     else if(row.status_pengajuan == 105){
                //         $rowData = '<span style="min-width: 70px" class="label label-danger">'+row.status+'</span>';
                //     }
                //     return $rowData;
                // },
                // visible: true,
                // targets: 4,
            }, 
            // {   
            //     render: function (data, type, row){
            //         // // console.log(row);
            //         var $rowData = ``;

                    
            //             $rowData = `<ul class="icons-list">
            //                             <li class="dropdown">
            //                                 <a href="#" class="dropdown-toggle" data-toggle="dropdown">
            //                                     <i class="icon-menu9"></i>
            //                                 </a>

            //                                 <ul class="dropdown-menu dropdown-menu-right">
                                            
            //                                     <li class=""><a "><i class=" icon-file-eye2"></i> Lihat Surat</a></li>                                              
            //                                     <li><a><i class="icon-user-cancel"></i> Delete Pengajuan</a></li>
            //                                 </ul>
            //                             </li>
            //                         </ul>`;
                    

            //         return $rowData;
            //     },
            //     visible: true,
            //     targets: 5,
            //     className: 'dt-center'
            // }, 
        ],
        fnRowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull){ 
            var index = iDisplayIndexFull + 1; 
            $('td:eq(0)', nRow).html('#'+index); 
            return  index;
        },
        drawCallback: function (settings) {
            // // console.log(settings.json);
            
            var api  = this.api();
            var rows = api.rows({page:'current'}).nodes();
            var last = null;

            // // console.log(rows)
            // Reverse last 3 dropdowns orientation
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');

            var that = this;
            var td ;
            var tr ;

            this.$('td').click( function () {
                td = this;
            });
            this.$('tr').click( function () {
                tr = this;
            });

            this.$('.showAtt').on('click', function(){

                var tr      = $(this).parents('tr')
                var aData   = dtpr.row( tr ).data();

                // loadAttachments(aData);

            });

            
        },
        fnInitComplete: function (oSettings, json) {
            var that = this;
            var td ;
            var tr ;

            this.$('td').click( function () {
                td = this;
            });
            this.$('tr').click( function () {
                tr = this;
            });

            

            $('#list_perusahaan input').bind('keyup', function (e) {
                return this.value;
            });

            setIFrameSize();

        }
    });

}

/* disabling scroll input number */
$('.form-group').on('focus', 'input[type=number]', function (e) {
    $(this).off('wheel.disableScroll')
})

$('.form-group').on('blur', 'input[type=number]', function (e) {
    $(this).off('wheel.disableScroll')
})

/* only numbweer */
$(function() {
    $('.form-group').on('keydown', 'input[type=number]', function(e){
        -1!==$
        .inArray(e.keyCode,[46,8,9,27,13,110,190]) || /65|67|86|88/
        .test(e.keyCode) && (!0 === e.ctrlKey || !0 === e.metaKey)
        || 35 <= e.keyCode && 40 >= e.keyCode || (e.shiftKey|| 48 > e.keyCode || 57 < e.keyCode)
        && (96 > e.keyCode || 105 < e.keyCode) && e.preventDefault()
    });
})

$('input[type=number]').on("wheel", function (e) { 
    $(this).blur(); 
}); 

$(".btn-fnilai").on("click", function(){
    $("#download-fnilai")[0].click();
})

$(".btn-fhadir").on("click", function(){
    $("#download-fhadir")[0].click();
})

$(".btn-modaltopik").on("click", function(){
    
    $("#modal-topik").modal("show");
})

$("#subtopic").on("click", function(){
    
    submitTopic(objLoad.id_kp);
})

function submitTopic(id){
    loaderPage(true);
    var isObject = {};
    
    isObject.topik = $("#topik").val();
    isObject.id_kp = id;

    if(isObject.topik == null || isObject.topi == ''){
        swal({
            title: "Alert",
            text:  "Topik tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        loaderPage(false);
        return false;
    }

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/savetopik',
        
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            loaderPage(false);
            if(response.code == CODE_SUCCESS){
                swal({
                    title: "Alert",
                    text: "Topik berhasil diinput, silahkan hubungi TU untuk memilihkan pembimbing",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){ 
                    location.reload()
                });
               
            } else {
                swal({
                    title: "Alert",
                    text: "Input topik gagal, silahkan coba kembali!",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });
            }
            loaderPage(false);
        },
        error: function(xhr) {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });
    
}

async function isPengajuanExist(arrNim, nim){

    let isObject = {};

    isObject.arrNim = arrNim;
    isObject.nim    = nim;

    const result = await $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/validatepengajuan',
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function (response) {
            // $('#modal-add').modal("toggle");
            // $("#submitpengajuan").attr('disabled',false);
            
            let data = cryptoDecrypt(PHRASE, response.data);
            // console.log(data);
            // if(response.code == CODE_SUCCESS){

            //     // document.getElementById("form-data").reset();
            //     // var object2 = isObject.nimmhs;
            //     // swal({
            //     //     title: "Alert",
            //     //     text: "Surat pengantar KP telah diajukan ",
            //     //     confirmButtonColor: "#66BB6A",
            //     //     type: "success"
            //     // }, function(){ 
            //     //     // $("tbody").empty();
            //     //     // loadElementsMhs();
            //     //     location.reload()
                    
            //     // });
            //     // location.reload()
            // }else{
            //     swal({
            //         title: "Alert",
            //         text:  response.info+ " Silahkan coba kembali :)",
            //         confirmButtonColor: "#2196F3",
            //         type: "error"
            //     });  
            // };
            // $("#submitpengajuan").attr('disabled',false);
            loaderPage(false);
            
        },
        error: function () {
            loaderPage(false);
            $("#submitpengajuan").attr('disabled',false);
            if(xhr.status != 200){
                swal({
                    title: "Alert",
                    text:  xhr.status+"-"+xhr.statusText+" Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });

    return result;
}