// var parambot = loadparambobot();
$("body").addClass("sidebar-xs");

$('.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'
});
$("#genpopup").on("click", function(){
    $("#modal-generate").modal("show");
})

$("#generatenilai").on("click", function(){
    loaderPage(true);
    generatenilai();
})

$("#hitung").on('click', function(e){
    // e.preventDefault();
    loaderPage(true);
    
    // console.log(loadparambobot());
    var objbobotperusahaan = loadparambobot(81);
    var objbobotpenguji    = loadparambobot(82);
    
    var nilai_perusahaan       = document.querySelectorAll('[id^="valperusahaan"]');
    var nama_nilai_perusahaan  = document.querySelectorAll('[id^="nperusahaan"]');
    var objperusahaan    = {};
    
    for(var i = 0; i < nilai_perusahaan.length; i++){
        objperusahaan[nama_nilai_perusahaan[i].innerHTML] = nilai_perusahaan[i].value;
    }

    var sumperusahaan = {};
    if(objperusahaan.length == objbobotperusahaan.length){
        for(var n in objperusahaan){
            sumperusahaan[n] = parseFloat(objperusahaan[n]) * parseFloat(objbobotperusahaan[n]);
            
        }
    }
    
    var nilai_penguji      = document.querySelectorAll('[id^="valpenguji"]');
    var nama_nilai_penguji  = document.querySelectorAll('[id^="npenguji"]');
    var objpenguji    = {};
    
    for(var i = 0; i < nilai_penguji.length; i++){
        
        objpenguji[nama_nilai_penguji[i].innerHTML] = nilai_penguji[i].value;
    }
    // console.log(nilai_penguji);
    // var nilai_pembimbing      = document.querySelectorAll('[id^="valpembimbing"]');
    // var nama_nilai_pembimbing  = document.querySelectorAll('[id^="npembimbing"]');
    // var objpembimbing    = {};
    
    // for(var i = 0; i < nilai_pembimbing.length; i++){
        
    //     objpembimbing[nama_nilai_pembimbing[i].innerHTML] = nilai_pembimbing[i].value;
    // }

    var sumpenguji ={};
    // if(objpembimbing.length == objpenguji.length){
        for(var key in objpenguji){
            sumpenguji[key] = parseFloat(objpenguji[key]);
        }
    // }

    if(sumpenguji.length == objbobotpenguji.length){
        for(var n in sumpenguji){
            sumpenguji[n] = (parseFloat(sumpenguji[n]) * parseFloat(objbobotpenguji[n]));
        }
    }

    var jumpenguji = 0;
    for(const key of Object.values(sumpenguji)){
        jumpenguji = jumpenguji + key;
    }
    // console.log(jumpenguji);

    var jumperusahaan = 0;
    for(const keys of Object.values(sumperusahaan)){
        jumperusahaan = jumperusahaan + keys;
    }

    var nilai_akhir = jumpenguji + jumperusahaan;
    var nilai_mutu;

    console.log(nilai_akhir);
    // return false;
    hitungnilaiakhir(nilai_akhir);
    
})

$("#btn-note").on('click', function(){
    saveKeterangan();
});



function hitungnilaiakhir(nilai_akhir){
    var isObject = {};
    isObject.nilai_akhir = nilai_akhir;
    isObject.idkp = $("#idkp").val();
    isObject.nim  = $("#nim").val();  

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/savenilaiakhir',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            if(response.code == CODE_SUCCESS){
                
                swal({
                    title: "Alert",
                    text: "Nilai Akhir telah dihitung",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){
                    
                    location.reload();  
                });
                
                
                
            } else {
                swal({
                    title: "Alert",
                    text:  response.info+ " 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"
                });                        
            }
        }
    });
}

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

    var dtpr = $('#penilaianpenguji').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/datanilaiakhir',
            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)
                    // callendars(data);
                    return data;
                }else{
                    return response;
                }
               
            }
        },	
        columns: [
            { 'data': 'nim', 'sClass':'','sWidth':'10px'},
            { 'data': 'nim', 'sClass':''},
            // { 'data': 'jurusan', 'sClass':''},
            { 'data': 'nama', 'sClass':''},
            { 'data': 'dosen_pembimbing', 'sClass':''},
            { 'data': 'dosen_penguji', 'sClass':''},
            { 'data': 'dosen_penguji2', 'sClass':''},
            { 'data': 'mulai_kp', 'sClass':''},
            { 'data': 'tanggal', 'sClass':'text-center'},
            { 'data': 'semester', 'sClass':'text-center'},
            { 'data': 'nilai_akhir', 'sClass':'text-center'},
            { 'data': 'nilai_mutu', 'sClass':'text-center'},
            { 'data': 'isnilaicount', 'sClass':'text-center'},
            { 'data': 'keterangan', 'sWidth':'200px'},
            { 'data': '', 'sClass':'text-center','sWidth':'10px'}
        ],
        // buttons: {            
        //     buttons: [
        //         {
        //             extend: 'colvis',
        //             className: 'btn btn-default'
        //         },
        //     ]
        // },
        processing: true,
        stateSave: false,
        autoWidth: false,
        dom: '<"datatable-header"fl><"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_nilai_pembimbing != 1){
                //         $rowData ='<span style="min-width: 70px" class="label label-danger">Nilai Belum Diinput</span>';
                //     }else {
                //         $rowData ='<span style="min-width: 70px" class="label label-success">Nilai Sudah Diinput</span>';
                //     }
                //     return $rowData;
                // },
                // visible: true,
                // targets: 4,
            }, 
            {   
                render: function (data, type, row){
                    // console.log(row);
                    var $rowData = row.mulai_kp+" sampai "+row.akhir_kp;
                    
                    return $rowData;
                },
                visible: true,
                targets: 6,
            },
            {   
                render: function (data, type, row){
                    // console.log(row);
                    var $rowData = "";
                    let sem = 'GENAP';
                    if(row.semester == 1){
                        sem = "GANJIL";
                    }
                    $rowData = sem+' '+row.tahun_ajaran;
                    return $rowData;
                },
                visible: true,
                targets: 8,
            },
            {   
                render: function (data, type, row){
                    // console.log(row);
                    var $rowData = ``;
                    if(row.isnilaicount == 1){
                        $rowData ='<span style="min-width: 70px" class="label label-success">Nilai Sudah Dihitung</span>';
                    } else {
                        $rowData ='<span style="min-width: 70px" class="label label-danger">Nilai Belum Dihitung</span>';
                    }
                    
                    return $rowData;
                },
                visible: true,
                targets: 11,
            },
            {   
                render: function (data, type, row){
                    var $rowData = '';
                    var $actpembimbing, $actpenguji;

                    if(row.isnilaicount == 1){
                        $actpembimbing = `<li class=""><a onclick="lihatnilai(`+row.id_kp+`,'`+row.nim+`','`+row.nama+`','`+row.file_foto+`','`+row.dosen_penguji+`','`+row.dosen_pembimbing+`','`+row.nama_prodi+`','`+row.pembimbinggd+`','`+row.pembimbinggb+`','`+row.pengujigd+`','`+row.pengujigb+`','`+row.nilai_akhir+`','`+row.nilai_mutu+`','`+row.dosen_penguji2+`','`+row.nopegpenguji+`','`+row.nopegpenguji2+`')" class=""><i class=" icon-users"></i> Lihat Nilai</a></li>
                                          <li class=""><a onclick="addNotes(`+row.id_kp+`,'`+row.keterangan+`')" class=""><i class=" icon-notebook"></i> Tambah Keterangan</a></li>`;
                        
                    } else {
                        $actpembimbing = `<li class=""><a onclick="modalnilai(`+row.id_kp+`,'`+row.nim+`','`+row.nama+`','`+row.file_foto+`','`+row.dosen_penguji+`','`+row.dosen_pembimbing+`','`+row.nama_prodi+`','`+row.dosen_penguji2+`','`+row.nopegpenguji+`','`+row.nopegpenguji2+`')" class=""><i class=" icon-users"></i> Hitung Nilai</a></li>`;
                       
                    }

                    $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">
                                               
                                                `+$actpembimbing+`
                                            </ul>

                                             
                                         </li>
                                     </ul>`

                    return $rowData;
                },
                visible: true,
                targets: 13,
                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();

        }
    });

}

function alreadyinputalert(){
    swal({
        title: "Alert",
        text:  "Nilai akhir telah dihitung, tidak dapat menghitung kembali nilai akhir!",
        confirmButtonColor: "#2196F3",
        type: "warning",
        icon: "warning"
    });
}

function modalnilai(idkp, nim, nama, foto, penguji, pembimbing, prodi, penguji2, nopeg_peng1, nopeg_peng2){
    $('#idkp').val(idkp);
    $("#nim").val(nim);
    
    if(!fileExists(foto)){
        $(".normpoint > img").attr('src', baseURL+'/data/profilepicture/defaultpics.png');
    }else{
        $(".normpoint > img").attr('src', baseURL+'/data/profilepicture/'+foto);
    }

    $("#nopeg_peng_1").val(nopeg_peng1);
    $("#nopeg_peng_2").val(nopeg_peng2);
    // console.log(foto);
    // alert(nama+foto+penguji+pembimbing+prodi)
    // $(".normpoint > img").attr('src', '/data/profilepicture/'+foto);
    $("#identitasNama").html(': '+nama);
    $("#identitasNim").html(': '+nim);
    $("#identitasProdi").html(': '+prodi);
    $("#identitasPembimbing").html(': '+pembimbing);
    $("#identitasPenguji").html(': '+penguji);
    $("#identitasPenguji2").html(': '+penguji2);


    loadnilaiperusahaan(idkp);
    loadnilaipenguji(idkp);
    loadnilaipembimbing(idkp);
    $("#modal-nilai").modal('show');
}

function setgelardosen(depan, belakang, nama){
    $namagelar = nama;
    
    if(depan == 'null'){
        //noact
    }else{
        $namagelar = depan+" "+$namagelar;
    }

    if(belakang == 'null'){
        //noact
    }else{
        $namagelar = $namagelar+", "+belakang;
    }

    return $namagelar;
}

function lihatnilai(idkp, nim, nama, foto, penguji, pembimbing, prodi, pembimbinggd, pembimbinggb,pengujigd, pengujigb, totalnilai, nilaiakhir, penguji2, nopeg_peng1, nopeg_peng2){
    
    console.log(foto);
    console.log('null')

    if(foto == null || foto == "" || foto == "null"){
        $(".normpoint > img").attr('src', '/data/profilepicture/notupload.png');
    }else{
        $(".normpoint > img").attr('src', '/data/profilepicture/'+foto);
    }
    // $(".normpoint > img").attr('src', '/data/profilepicture/'+foto);
    $namapenguji = setgelardosen(pengujigd, pengujigb, penguji);
    $namapenguji2 = penguji2
    $namapembimbing = setgelardosen(pembimbinggd, pembimbinggb, pembimbing);
    $("#nopeg_peng_1").val(nopeg_peng1);
    $("#nopeg_peng_2").val(nopeg_peng2);
    $("#identitasNaman").html(': '+nama);
    $("#identitasNimn").html(': '+nim);
    $("#identitasProdin").html(': '+prodi);
    $("#identitasPembimbingn").html(': '+$namapembimbing);
    $("#identitasPengujin").html(': '+$namapenguji);
    $("#identitasPengujin2").html(': '+$namapenguji2);
    $("#totalnilai").html(': '+totalnilai);
    $("#nilaiakhir").html(': '+nilaiakhir);
    
    loadnilaiperusahaan(idkp);
    loadnilaipenguji(idkp);
    loadnilaipembimbing(idkp);
    $("#lihat-nilai").modal('show');
}

function loadnilaiperusahaan(idkp){
    loaderPage(true)
    var isObject = {};
    isObject.idkp = idkp;
    
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/nilaiperusahaan',
        // async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            var x = 1;
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                let data    = result.data;
                // console.log(data)
                $res = ``;
                for(i in data){
                    $res += `<div class="form-group">
                                <label id="nperusahaan`+x+`"class="col-lg-4 control-label text-semibold">`+data[i].nama_nilai_perusahaan+`</label>
                                <div class="col-lg-8">
                                    <div class="input-group">
                                        <span class="input-group-addon"></span>
                                        <input id="valperusahaan`+x+`"type="url" class="form-control" placeholder="Url ruang&hellip;" value="`+data[i].nilai_perusahaan+`"disabled>
                                    </div>
                                </div>
                            </div>`;
                    x++;
                }

                $("#nilaiperusahaan").html($res);
                $("#nilaiperusahaanl").html($res);
                
                
            } else {
                // $("#btn-add").attr('disabled', true)
                // $("#updateberkas").hide();
                // swal({
                //     title: "Alert",
                //     text:  response.info+ " 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"
                });                        
            }
        }
    });
    
    
}

function loadnilaipenguji(idkp){
 
    var isObject = {};
    isObject.idkp  = idkp;
    isObject.nopeg = 'generate'; 
    
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/nilaipenguji',
        // async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            var x = 1;
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                let data    = result.data;
                // console.log(data)
                $res = ``;
                for(i in data){
                    $res += `<div class="form-group">
                                <label id="npenguji`+x+`"class="col-lg-4 control-label text-semibold">`+data[i].nama_nilai_penguji+`</label>
                                <div class="col-lg-8">
                                    <div class="input-group">
                                        <span class="input-group-addon"></span>
                                        <input id="valpenguji`+x+`"type="url" class="form-control" placeholder="Url ruang&hellip;" value="`+data[i].nilai_penguji+`"disabled>
                                    </div>
                                </div>
                            </div>`;
                            x++;
                }

                $("#nilaipenguji").html($res);
                $("#nilaipengujil").html($res);
                

                if(isObject.nopeg == 'generate'){ // untuk modal generate aja
                    
                    let penguji_1 = $("#nopeg_peng_1").val();
                    let penguji_2 = $("#nopeg_peng_2").val();
                    let xz = 1;
                    $resPenguji_1 = '';
                    $resPenguji_2 = '';
                    for($i in data){
                        
                        if(penguji_1 == data[$i].nopeg){
                            $resPenguji_1 += `<div class="form-group">
                                    <label id="npengujipertama`+xz+`"class="col-lg-4 control-label text-semibold">`+data[$i].nama_nilai_penguji+`</label>
                                    <div class="col-lg-8">
                                        <div class="input-group">
                                            <span class="input-group-addon"><i class="icon-pencil4"></i></span>
                                            <input id="valpengujipertama`+xz+`"type="url" class="form-control" placeholder="Url ruang&hellip;" value="`+data[$i].nilai_penguji+`" disabled>
                                        </div>
                                    </div>
                                </div>`;
                            xz++;
                        }else{
                            $resPenguji_2 += `<div class="form-group">
                                    <label id="npengujikedua`+xz+`"class="col-lg-4 control-label text-semibold">`+data[$i].nama_nilai_penguji+`</label>
                                    <div class="col-lg-8">
                                        <div class="input-group">
                                            <span class="input-group-addon"><i class="icon-pencil4"></i></span>
                                            <input id="valpengujikedua`+xz+`"type="url" class="form-control" placeholder="Url ruang&hellip;" value="`+data[$i].nilai_penguji+`" disabled>
                                        </div>
                                    </div>
                                </div>`;
                            xz++;
                        }
                    }

                    $("#nilaipengujil").html($resPenguji_1);
                    $("#nilaipengujil2").html($resPenguji_2);
                    $("#nilaipenguji").html($resPenguji_1);
                    $("#nilaipenguji2").html($resPenguji_2);
                }
                
            } else {
                // $("#btn-add").attr('disabled', true)
                // $("#updateberkas").hide();
                // swal({
                //     title: "Alert",
                //     text:  response.info+ " Silahkan coba kembali :)",
                //     confirmButtonColor: "#2196F3",
                //     type: "error"
                // });
            }

            
            
        },
        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 loadnilaipembimbing(idkp){
 
    var isObject = {};
    isObject.idkp = idkp;
    
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/nilaipembimbing',
        // async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            var x = 1;
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                let data    = result.data;
                // console.log(data)
                $res = ``;
                for(i in data){
                    $res += `<div class="form-group">
                                <label id="npembimbing`+x+`"class="col-lg-4 control-label text-semibold">`+data[i].nama_nilai_pembimbing+`</label>
                                <div class="col-lg-8">
                                    <div class="input-group">
                                        <span class="input-group-addon"></span>
                                        <input id="valpembimbing`+x+`"type="url" class="form-control" placeholder="Url ruang&hellip;" value="`+data[i].nilai_pembimbing+`"disabled>
                                    </div>
                                </div>
                            </div>`;
                            x++;
                }

                $("#nilaipembimbing").html($res);
                $("#nilaipembimbingl").html($res);
                
                
            } else {
                // $("#btn-add").attr('disabled', true)
                // $("#updateberkas").hide();
                // swal({
                //     title: "Alert",
                //     text:  response.info+ " Silahkan coba kembali :)",
                //     confirmButtonColor: "#2196F3",
                //     type: "error"
                // });
            }

            
            
        },
        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 loadparambobot(param){
    var isObject = {}
    isObject.code = param;
    var objekbobot = {};

    // console.log(pembimbing);
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loadparambobots',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            // console.log(response.code)
            // $("tbody").empty();
            
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                // console.log(result.data);
                let data    = result.data;
                // console.log(data);

                for(i in data){
                    objekbobot[data[i].nama_bobot] = data[i].bobot;
                    
                }
                
                // console.log(objekbobot);
            } else {
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            }
            
        },
        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 objekbobot;
}

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

    isObject.kodeprodi      = $("#kodeprodi").val();
    // isObject.jenis_bobot    = $("#jenisBobot").val();
    // isObject.status = $('input[name="stat"]:checked').val();
    isObject.tglawal   = dateformats($("#tglawal").val());
    isObject.tglakhir   = dateformats($("#tglakhir").val());
    isObject.semester   = $("#selecSemester").val();
    
    console.log(isObject);
    
    if(isObject.kodeprodi == null || isObject.kode == ""){
        loaderPage(false);  
        swal({
            title: "Alert",
            text:  " Program Studi tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "error"
        });  
        return false;
    }

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

    if(!daterangeCheck(isObject.tglawal, isObject.tglakhir)){
        loaderPage(false);  
        swal({
            title: "Peringatan!",
            text:" Tanggal akhir tidak boleh kurang dari tanggal awal",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        return false;
        
    }

    
    loaderPage(true);
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/reportingnilai',
        // async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            if(response.code == CODE_SUCCESS){
                console.log(baseURL+"/data/pengumuman/"+response.data);
                swal({
                    title: "Alert",
                    text: "Report Nilai telah Digenerate!",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){
                    window.open(baseURL+'/data/reporting/'+response.data)
                    $("#modal-generate").modal("hide");  
                });
                
                
                
            } else {
                swal({
                    title: "Warning",
                    text:  response.info+ " 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"
                });                        
            }
        }
    });

}


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

    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 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);
    return (today - idate) < 0;
}

function daterangeCheck(idateAW, 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()
    return (idateAW - idateAK) < 0;
}

function addNotes(id,ket){
    var isObject = {};
    isObject.idkp = id;
    console.log(isObject.idkp)
    $("#idkps").val(id);
    $("#keterangans").val(ket);
    $('#modal-note').modal('show');
}

function saveKeterangan(){
    var isObject = {};
    isObject.idkp       =  $("#idkps").val();
    isObject.keterangan =  $("#keterangans").val();
    loaderPage(true);

    if(isObject.keterangan == null || isObject.keterangan == ""){
        swal({
            title: "Alert",
            text: "Keterangan tidak boleh kosong",
            confirmButtonColor: "#66BB6A",
            type: "alert"
        });
    }
    // return isObject.keterangan;
    
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: baseURL + '/jsondata/saveket',
            // async: false,
            data: {
                iparam	    : cryptoEncrypt(PHRASE, isObject),
            },
            success: function(response){
                
                if(response.code == CODE_SUCCESS){
                    
                    swal({
                        title: "Alert",
                        text: "Keterangan telah ditambahkan",
                        confirmButtonColor: "#66BB6A",
                        type: "success"
                    }, function(){
                        loaderPage(false)
                        // loadElementsnilai();
                        location.reload();
                    });
                    
                    
                    loaderPage(false)
                } else {
                    swal({
                        title: "Alert",
                        text:  response.info+ " 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"
                    });                        
                }
            }
        });
        loaderPage(false)
}


/* 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(); 
}); 

$('#genexcel').on('click', function(){
    $("#modal-generate-excel").modal('show');
})

$("#generatexcel").on("click", function(){
    loaderPage(true);
    generatexcel();
})

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

    isObject.kodeprodi      = $("#kodeprodiex").val();
    isObject.tglawal        = dateformats($("#tglawalex").val());
    isObject.tglakhir       = dateformats($("#tglakhirex").val());
    isObject.semester       = $("#selecSemesterex").val();
    
    console.log(isObject);
    
    if(isObject.kodeprodi == null || isObject.kode == ""){
        loaderPage(false);  
        swal({
            title: "Alert",
            text:  " Program Studi tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "error"
        });  
        return false;
    }

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

    if(!daterangeCheck(isObject.tglawal, isObject.tglakhir)){
        loaderPage(false);  
        swal({
            title: "Peringatan!",
            text:" Tanggal akhir tidak boleh kurang dari tanggal awal",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        return false;
        
    }

    
    loaderPage(true);
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/reportingnilaiexcel',
        // async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            if(response.code == CODE_SUCCESS){
                console.log(baseURL+"/data/pengumuman/"+response.data);
                swal({
                    title: "Alert",
                    text: "Report Nilai telah Digenerate!",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){
                    window.open(baseURL+'/data/reporting/'+response.data)
                    $("#modal-generate-excel").modal("hide");  
                });
                
                
                
            } else {
                swal({
                    title: "Warning",
                    text:  response.info+ " 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"
                });                        
            }
        }
    });

}

loadSelectSemester();
function loadSelectSemester(){
    var isObject = {};
    isObject.idkp       =  null;
    
    loaderPage(true);

    
    // return isObject.keterangan;
    
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/selectsemester',
        // async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            if(response.code == CODE_SUCCESS){
                
                let data = response.data;

                let opt  = `<option> --- Pilih Semester ---</option>`;
                for(i in data){
                    let sem = 'GENAP';
                    if(data[i].semester == 1){
                        sem = 'GANJIL';
                    }

                    opt += `<option value="`+data[i].semester+`~`+data[i].tahun_ajaran+`">`+sem+` `+data[i].tahun_ajaran+`</option>`;
                }

                console.log(opt)
                
                $("#selecSemester").html(opt);
                $("#selecSemesterex").html(opt);
                
                loaderPage(false)
            }
            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"
                });                        
            }
        }
    });
    loaderPage(false)
}