$(document).ready(function(){
    $(".btn-submit").on("click", function(){
        savejadwal(nim);
    })

    var isdatechange;
    $("#tanggaledt").on('change', function(){
        isdatechange = true;
    })

    var isourchange;
    $("#jamedt").on("change", function(){
        isourchange = true;
    })

    $(".btn-updatejadwal").on("click", function(){
        updatejadwal(nim, isdatechange, isourchange);
    })

    $('.pickatime-disabled').pickatime({
        // format: 'yyyy, mm dd',
        interval: 45,
        disable: [
           [12,0],
           [12,30],
           [04,00]
        ],
        min: [07,0],
        max: [17,0],
       
    });

    $('.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'
    });
    
    
})
loadkerjapraktik(nim);
function loadkerjapraktik(nim){
    var isObject = {};

    isObject.param = nim;

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loadpembimbing',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                // console.log(result.data);
                let data = result.data;
                var option = '';
                for(i in data){
                    if(data[i].gelar_dpn != null && data[i].gelar_blk != null){
                        option += '<option value="'+data[i].nopeg+'">'+data[i].gelar_dpn+" "+data[i].pembimbing+", "+data[i].gelar_blk+'</option> ';
                    }else if(data[i].gelar_dpn == null && data[i].gelar_blk != null){
                        option += '<option value="'+data[i].nopeg+'">'+data[i].pembimbing+", "+data[i].gelar_blk+'</option> ';
                    }else if(data[i].gelar_dpn != null && data[i].gelar_blk == null){
                        option += '<option value="'+data[i].nopeg+'">'+data[i].gelar_dpn+" "+data[i].pembimbing+'</option> ';
                    } else {
                        option += '<option value="'+data[i].nopeg+'">'+data[i].pembimbing+'</option> ';
                    }
                    
                }
                // $("#penguji1").append(option);
                $("#penguji2").append(option);
                $("#pembimbingselect").append(option);
                
// console.log(data)
            } 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"
                });                        
            }
        }
    });


}

loadpenguji(null)
function loadpenguji(nopegparams){
    var isObject = {}
    isObject.param = iduser;

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loaddsn',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                // console.log(result.data.data);
                let data = result.data;
                // console.log(data);
                var option = '';
                for(i in data){
                    if(data[i].gelar_dpn != null && data[i].gelar_blk != null){
                        
                        if(nopegparams == data[i].nopeg){
                            option += '<option value="'+data[i].nopeg+'" selected>'+data[i].gelar_dpn+" "+data[i].nama+", "+data[i].gelar_blk+'</option> ';
                        }else{
                            option += '<option value="'+data[i].nopeg+'">'+data[i].gelar_dpn+" "+data[i].nama+", "+data[i].gelar_blk+'</option> ';
                        }
                        
                    }else if(data[i].gelar_dpn == null && data[i].gelar_blk != null){

                        if(nopegparams == data[i].nopeg){
                            option += '<option value="'+data[i].nopeg+'" selected>'+data[i].nama+", "+data[i].gelar_blk+'</option> ';
                        }else{
                            option += '<option value="'+data[i].nopeg+'">'+data[i].nama+", "+data[i].gelar_blk+'</option> ';
                        }
                        
                    }else if(data[i].gelar_dpn != null && data[i].gelar_blk == null){
                        
                        if(nopegparams == data[i].nopeg){
                            option += '<option value="'+data[i].nopeg+'" selected>'+data[i].gelar_dpn+" "+data[i].nama+'</option> ';
                        }else{
                            option += '<option value="'+data[i].nopeg+'">'+data[i].gelar_dpn+" "+data[i].nama+'</option> ';
                        }
                        
                    } else {

                        if(nopegparams == data[i].nopeg){
                            option += '<option value="'+data[i].nopeg+'" selected>'+data[i].nama+'</option> ';
                        }else{
                            option += '<option value="'+data[i].nopeg+'">'+data[i].nama+'</option> ';
                        }
                        
                    }
                    
                }
                $("#penguji1").append(option);
                $("#penguji1new").append(option);
                $("#penguji2new").append(option);
                if(nopegparams){
                    console.log(nopegparams)
                    $("#pengujis1").append(option);
                }
                
                
// console.log(data)
            } 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"
                });                        
            }
        }
    });
}

// savejadwal(nim);
function savejadwal(){
    
    loaderPage(true);
    var isObject = {};
    isObject.penguji1 = $("#penguji1").val();
    isObject.penguji2 = $("#penguji2").val();
    isObject.jam      = $("#jam").val();
    // isObject.tanggal  = $("#tanggal").val();
    isObject.tanggal  = dateformats($("#tanggal").val());
    isObject.ruang    = $("#ruang").val();
    // isObject.picm     = $("#kdpembimbing").val();
    isObject.nim      = nim;

    console.log(isObject.tanggal);
    // let urlpattern = ^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/
    
    if(isObject.penguji1 == isObject.penguji2){
        loaderPage(false);
        swal({
            title: "Peringatan!",
            text:" Penguji tidak boleh sama dengan pembimbing",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        return false;
    }


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

    if(!isFutureDate(isObject.tanggal)){
        loaderPage(false);
        swal({
            title: "Peringatan!",
            text:" Tanggal tidak valid",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        return false;
    }

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

    // if(!validURL(isObject.ruang)){
    //     loaderPage(false);
    //     swal({
    //         title: "Peringatan!",
    //         text:" URL Ruangan tidak valid!",
    //         confirmButtonColor: "#2196F3",
    //         type: "warning"
    //     });
    //     return false;
    // }

    // let arrayVal = validasijadwal();
    // console.log(arrayVal);
    // console.log()
    if(loadjadwal(isObject.tanggal, isObject.penguji1, isObject.penguji2, isObject.jam) == false){
        loaderPage(false);
        console.log(false)
        return false;
    }else {
        
        console.log(true)
    }


    // var penguji2 = $("#penguji2").val();
    // var penguji1 = $("#penguji1").val();
    // var jam      = $("#jam").val();
    // var tanggal  = $("#tanggal").val();
    // var ruang  = $("#ruang").val();

    // console.log(isObject.nim);  
    // console.log(isObject.penguji1);
    // console.log(isObject.penguji2);
    // console.log(isObject.tanggal);
    // console.log(isObject.jam);
    // console.log(isObject.ruang);
    $(".btn-submit").attr('disabled', true);
    $(".btn-submit").html('sending email...')
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/savejadwal',
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function (response) {
            // $('#modal-add').modal("hide");
            console.log(response.code);
            if(response.code == CODE_SUCCESS){
                
                swal({
                    title: "Alert",
                    text: "Jadwal telah ditambahkan ",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){ 
                    window.location = baseURL+"/jadwal/jadwalpersentasi"
                });

            }else{
                $(".btn-submit").attr('disabled', false)
                $(".btn-submit").html('submit')
                loaderPage(false);
                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 sendemail(nim){
    var isObject = {};
    isObject.param = nim;
    loaderPage(true)

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/sendemail',
        //async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            
            if(response.code == CODE_SUCCESS || response.data == null){
                loaderPage(false)
                swal({
                    title: "Alert",
                    text: "Jadwal telah ditambahkan ",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){ 
                    // $("tbody").empty();
                    // loadElementsMhs();
                    
                    window.location = baseURL+"/jadwal/jadwalpersentasi"
                });
                
            } else {
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            }
            loaderPage(false)
        },
        error: function(xhr) {
            // alert("dierror")

            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });
    // alert("adaga")

}


function loadjadwal(tgl, p1, p2, jam){

    var isObject     = {}
    isObject.param   = iduser;
    isObject.tanggal = tgl;
    // console.log(isObject);
    var validup = true;
    // loaderPage(true)
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loadcalendar',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            
            if(response.code == CODE_SUCCESS || response.data == null){
                let result  = cryptoDecrypt(PHRASE, response.data);

                let data = result.data;
                console.log(data)
                // console.log(tConvert(data[0].jam))
                // console.log(jam);
                $msg = '';
                for(i in data){
                    if(tConvert(data[i].jam) == jam){
                        
                        if(p1 == data[i].nidp1 || p1 == data[i].nidp2){
                            validup = false;
                            $msg    = "Penguji memiliki jadwal pada jam tersebut,";
                        } else if (p2 == data[i].nidp1 || p2 == data[i].nidp2){
                            validup = false;
                            $msg    = "Pembimbing memiliki jadwal pada jam tersebut,";
                        }
                        
                    }
                }

                    
                
                // else {
                //     swal({
                //         title: "Warning",
                //         text:  "Jadwal pada tanggal tersebut sudah penuh, silahkan pilih tanggal lain",
                //         confirmButtonColor: "#2196F3",
                //         type: "error"
                //     }); 
                //     validup = false;
                // }

                if(validup == false){
                    swal({
                        title: "Warning",
                        text:  $msg+" silahkan pilih jam lain",
                        confirmButtonColor: "#2196F3",
                        type: "error"
                    }); 
                }
                
                
                
            } 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"
                });                        
            }
        }
    });

    return validup;
}

function loadjadwalupdate(tgl, p1, p2, jam, id_jadwal, isourchange){
    var isObject     = {}
    isObject.param   = iduser;
    isObject.tanggal = tgl;
    console.log(isObject);
    var validup = true;
    // loaderPage(true)
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loadcalendar',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            
            if(response.code == CODE_SUCCESS || response.data == null){
                let result  = cryptoDecrypt(PHRASE, response.data);
                // console.log(result.data.data);
                let data = result.data;
                // console.log(data);
                // console.log(data[0].tanggal);
                // console.log(dateformatsdb(tgl));
                // // console.log($("#kdpembimbing").val());
                // console.log(p1);
                console.log(isourchange);
                console.log(data)
                // console.log(tConvert(data[1].jam))
                var jamform;
                $msg = '';
                
                    for(i in data){
                        console.log(data[i].id_jadwal);
                        if(isourchange == true){
                            jamform = tConvert(data[i].jam);
                        } else {
                            jamform = data[i].jam;
                        }
                        
                        if(jamform == jam){
                            if(data[i].id_jadwal != id_jadwal){
                                if(p1 == data[i].nidp1 || p2 == data[i].nidp2){
                                    validup = false;
                                    $msg = 'Peguji sudah memiliki jadwal pada jam tersebut';
                                } else if(p2 == data[i].nidp1 || p2 == data[i].nidp2){
                                    validup = false;
                                    $msg = 'Pembimbing sudah memiliki jadwal pada jam tersebut';
                                }
                                
                            }
                            
                        }
                    }

                    
                //  else {
                //     swal({
                //         title: "Warning",
                //         text:  "Jadwal pada tanggal tersebut sudah penuh, silahkan pilih tanggal lain",
                //         confirmButtonColor: "#2196F3",
                //         type: "error"
                //     }); 
                //     validup = false;
                // }

                if(validup == false){
                    swal({
                        title: "Warning",
                        text:  $msg+", silahkan pilih jam lain",
                        confirmButtonColor: "#2196F3",
                        type: "error"
                    }); 
                }
                
                
                
            } 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"
                });                        
            }
        }
    });

    return validup;
}

function formatTimeShow(h_24) {
    var h = h_24 % 12;
    return (h < 10 ? '0' : '') + h + ':00';
}

function tConvert(time) {
    console.log(time);
    // Check correct time format and split into components
    time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
    
    var am = /^[01]?[0-9]([:.][0-9]{2})([:.][0-9]{2})?(\s?[A]M)?$/;
    var pm = /^[01]?[0-9]([:.][0-9]{2})([:.][0-9]{2})?(\s?[P]M)?$/;

    if (time.length > 1) { // If time format correct
      time = time.slice (1);  // Remove full string match value
      time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
      time[0] = +time[0] % 12 || 12; // Adjust hours
    }
    var times =  time.join (''); // return adjusted time or original string
    // var trimtime = times.replace(':00AM', ' AM')
    // console.log(times);
    if(times.match(am)){
        var trimtime = times.replace(':00AM', ' AM');
    }else{
        var trimtime = times.replace(':00PM', ' PM');
    }
    console.log(trimtime);
    return trimtime;
  }
  
 

function dateformatsdb(date){
    var newdate = date.split("-").reverse().join("-");
    // var dateNew     = new Date(date,);
    // console.log(dateNew)
    // // var dateString  = 
    // //  dateNew.getUTCFullYear() + "-" +
    // // ("0" + (dateNew.getUTCMonth()+1)).slice(-2) + "-" +
    // // ("0" + (1+ dateNew.getUTCDate())).slice(-2);
    // // // console.log(dateString);
    // var dateString = ("0" + (1 + dateNew.getUTCDate())).slice(-2) + "-" + ("0" + (dateNew.getUTCMonth()+1)).slice(-2) + "-" + dateNew.getUTCFullYear();
        
    return newdate;
}

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

    return dateString;
}

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 dateformatsedt(date){
    var dates = date.split('-');
    var datestring = dates[2]+'-'+dates[1]+'-'+dates[0];
    return datestring;
}

function isFutureDate(idate){
    var today = new Date().getTime(),
        idate = idate.split("-");
    // console.log(idate);
    idate = new Date(idate[2], idate[1] - 1, idate[0]).getTime();
    // console.log(idate);
    return (today - idate) < 0;
}

function validURL(str) {
    var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
      '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
      '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
      '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
      '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
      '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
    return !!pattern.test(str);
  }
// console.log(validURL("https://s.xxx"))

console.log($("#nimMhs").val())

function validasijadwal(){
    var cars = ["Saab", "Volvo", "BMW"];
    return cars;
}
// alert(nim);
loaddatajadwal(nim)
function loaddatajadwal(nim){
    var isObject     = {}
    isObject.param   = nim;
    // isObject.tanggal = tgl;
    // console.log(isObject);
    // var validup = true;
    loaderPage(true)
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loaddatajadwal',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            
            if(response.code == CODE_SUCCESS || response.data == null){
                let result  = cryptoDecrypt(PHRASE, response.data);
                // console.log(result.data.data);
                let data = result.data;
                // console.log(data);
                var option = '';    
                if(data[0].gdpem != null && data[0].gbpem != null){
                    option += '<option value="'+data[0].nidp1+'">'+data[0].gdpem+" "+data[0].namapenguji1+", "+data[0].gbpem+'</option> ';
                }else if(data[0].gdpem == null && data[0].gbpem != null){
                    option += '<option value="'+data[0].nidp1+'">'+data[0].namapenguji1+", "+data[0].gbpem+'</option> ';
                }else if(data[0].gdpem != null && data[0].gbpem == null){
                    option += '<option value="'+data[0].nidp1+'">'+data[0].gdpem+" "+data[0].namapenguji1+'</option> ';
                } else {
                    option += '<option value="'+data[0].nidp1+'">'+data[0].namapenguji1+'</option> ';
                }
                // $("#pengujis1").append(option);
                $("#tanggaledt").val(data[0].tanggal);
                $("#jamedt").val(data[0].jam);
                $("#ruangedt").val(data[0].ruang);
                $("#idjadwal").val(data[0].id_jadwal)
                
                loadpenguji(data[0].nidp1);
                
            } 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"
                });                        
            }
        }
    });
}

function updatejadwal(abs, isdatechange, isourchange){
    loaderPage(true)
    var isObject = {};
    isObject.penguji1 = $("#pengujis1").val(); //penguji
    isObject.penguji12 = $("#pengujis2").val(); //penguji
    isObject.penguji2 = $("#penguji2").val(); //pembimbing
    isObject.jam      = $("#jamedt").val();
    isObject.idjadwal = $("#idjadwal").val();
    isObject.ruang    = $("#ruangedt").val();
    isObject.nim      = nim;
    isObject.semester = $("#semester").val();
    isObject.tahunAjaran = $("#thn_ajaran").val();

    if(isdatechange == true){
        isObject.tanggal  = dateformats($("#tanggaledt").val());
    }else{
        isObject.tanggal  = dateformatsedt($("#tanggaledt").val());
    }

    if(isObject.penguji1 == isObject.penguji2){
        swal({
            title: "Peringatan!",
            text:" Penguji tidak boleh sama dengan pembimbing",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        loaderPage(false)
        return false;
    }

    // if(isObject.picm == isObject.penguji1 || isObject.picm == isObject.penguji2){
    //     swal({
    //         title: "Peringatan!",
    //         text:" Penguji tidak boleh sama dengan pembimbing",
    //         confirmButtonColor: "#2196F3",
    //         type: "warning"
    //     });
    // }

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

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

    if(!isFutureDate(isObject.tanggal)){
        swal({
            title: "Peringatan!",
            text:" Tanggal tidak valid",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        loaderPage(false)
        return false;
    }

    if(isObject.ruang == "" || isObject.ruang == null){
        swal({
            title: "Peringatan!",
            text:" URL Ruangan tidak boleh kosong!",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        loaderPage(false)
        return false;
    }

    // if(!validURL(isObject.ruang)){
    //     swal({
    //         title: "Peringatan!",
    //         text:" URL Ruangan tidak valid!",
    //         confirmButtonColor: "#2196F3",
    //         type: "warning"
    //     });
    //     return false;
    // }

    // let arrayVal = validasijadwal();
    // console.log(arrayVal);
    // console.log()
    if(loadjadwalupdate(isObject.tanggal, isObject.penguji1, isObject.penguji2, isObject.jam, isObject.idjadwal, isourchange) == false){
        console.log(false)
        loaderPage(false)
        return false;
    }else {
        console.log(true)
    }

    $(".btn-updatejadwal").attr('disabled', true);
    $(".btn-updatejadwal").html('sending email...')
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/updatejadwal',
        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: "Jadwal telah diubah ",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){ 
                    // $("tbody").empty();
                    // loadElementsMhs();
                    // location.reload()
                    window.location = baseURL+"/jadwal/jadwalpersentasi"
                });

            }else{
                $(".btn-updatejadwal").attr('disabled', false);
                $(".btn-updatejadwal").html('update jadwal')
                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"
                });                        
            }
        }
    });
}

// load mahasiswa yang belum memiliki jadwal


// MhsFDaftar();
function MhsFDaftar(mhs, dospem){
    var isObject = {};
    var arraynim = [];
    loaderPage(true)
    arraynim.push(nim);
    isObject.nim = arrayNIMS;
    // console.log(isObject)
    $("#"+mhs).hide()
    $("#"+dospem).hide()
    // console.log(isObject);
    
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loadmforj',
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function (response) {
            // $('#modal-add').modal("hide");

            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                // console.log(result.data)
                let optionsmhs = '';
                let optionsdos = '';
                let data = result.data

                console.log("ahiwiy : "+data.length)
                for(i in data){
                    optionsmhs += '<option value="'+data[i].nim+'">'+data[i].nama+'</option>';
                    optionsdos += '<option value="'+data[i].no_peg+'">'+data[i].nama_pembimbing+'</option>';
                }

                // console.log(optionsmhs)
                var elements = `<div class="row">

                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="col-lg-2 control-label text-semibold">Mahasiswa :</label>
                                <div class="col-lg-10">
                                    <select id="`+mhs+`" class="select" onchange="changedmhs(this, `+dospem+`)">
                                        `+optionsmhs+`
                                    </select>
                                </div>
                            </div>

                        </div>

                        <div class="col-md-6">

                            <div class="form-group">
                                <label class="col-lg-2 control-label text-semibold">Pembimbing :</label>
                                <div class="col-lg-10">
                                    <select id="`+dospem+`" class="select" disabled>
                                        `+optionsdos+`
                                    </select>
                                </div>
                            </div>
                        </div>

                    </div>`;

    

                if(counter < 5){
                    $("#listmforj").append(elements)
                }else{
                    $("#addrowselect").css("display", "none")
                }

                counter++;

                $("#"+mhs).html(optionsmhs)
                $("#"+dospem).html(optionsdos)

                $("#"+mhs).select2();
                $("#"+dospem).select2();

            }else{
                $("#addrowselect").css("display", "none")
                // $(".btn-updatejadwal").attr('disabled', false);
                // $(".btn-updatejadwal").html('update jadwal')
                // 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"
                });                        
            }
        }
    });
}

var counter = 1
var arrayNIMS = [];
function addrowselect(){
    getAllniminselect();
    
    MhsFDaftar("nimselect"+counter, "pembimbingselect"+counter);
    
    // console.log(counter)

}

function getAllniminselect(){
    let allnim = document.querySelectorAll('[id^="nimselect"]');
    
    arrayNIMS = []
    for($i = 0; $i < allnim.length; $i++){
        arrayNIMS.push(allnim[$i].value)
    }

}

$("#submitnew").on("click", function(){
    savejadwalnew()
})

function savejadwalnew(){
    
    loaderPage(true);
    var isObject = {};
    isObject.penguji1       = $("#penguji1new").val();
    isObject.penguji2       = $("#penguji2new").val();
    isObject.jam            = $("#jamnew").val();
    isObject.tanggal        = dateformats($("#tanggalnew").val());
    isObject.ruang          = $("#ruangnew").val();
    isObject.nim            = nim;
    isObject.semester       = $("#semester").val();
    isObject.tahunAjaran    = $("#thn_ajaran").val();


    let allnim        = document.querySelectorAll('[id^="nimselect"]');
    let alldspen      = document.querySelectorAll('[id^="pembimbingselect"]');
    let allData       = [];

    for($i = 0; $i < allnim.length; $i++){
        let objects = {
            nim_mhs: allnim[$i].value,
            no_peg_pem: alldspen[$i].value
        }
        allData.push(objects)
    }

    isObject.allData  = allData;

    let alldspenguji  = document.querySelectorAll('[id^="pengujinew"]'); 
    let allAdditional = [];

    if(alldspenguji.length != 0){
        for($z = 0; $z < alldspenguji.length; $z++){
            let objects = {
                nopeg_peng_add: alldspenguji[$z].value
            }
            allAdditional.push(objects);
        }

        isObject.allAdditional = allAdditional;
    }

    
    // console.log(alldspenguji.length);
    // return false
    // console.log(allAdditional);
    // return false;
    console.log(isObject.tanggal);
    // let urlpattern = ^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/
    
    // validasi penguji
    if(isObject.penguji1 == isObject.penguji2){
        loaderPage(false);
        swal({
            title: "Peringatan!",
            text:" Penguji tidak boleh sama dengan pembimbing",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        return false;
    }

    if(isObject.tahunAjaran == null || isObject.tahunAjaran == ""){
        loaderPage(false);
        swal({
            title: "Peringatan!",
            text:"Tahun ajaran tidak boleh kosong",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        return false;
    }


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

    if(!isFutureDate(isObject.tanggal)){
        loaderPage(false);
        swal({
            title: "Peringatan!",
            text:" Tanggal tidak valid",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        return false;
    }

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

    // if(!validURL(isObject.ruang)){
    //     loaderPage(false);
    //     swal({
    //         title: "Peringatan!",
    //         text:" URL Ruangan tidak valid!",
    //         confirmButtonColor: "#2196F3",
    //         type: "warning"
    //     });
    //     return false;
    // }

    // let arrayVal = validasijadwal();
    // console.log(arrayVal);
    // console.log()

    // untuk validasi apakah pembibming/penguji meminili jadwal
    // if(loadjadwal(isObject.tanggal, isObject.penguji1, isObject.penguji2, isObject.jam) == false){
    //     loaderPage(false);
    //     console.log(false)
    //     return false;
    // }else {
    //     console.log(true)
    // }


    // var penguji2 = $("#penguji2").val();
    // var penguji1 = $("#penguji1").val();
    // var jam      = $("#jam").val();
    // var tanggal  = $("#tanggal").val();
    // var ruang  = $("#ruang").val();

    // console.log(isObject.nim);  
    // console.log(isObject.penguji1);
    // console.log(isObject.penguji2);
    // console.log(isObject.tanggal);
    // console.log(isObject.jam);
    // console.log(isObject.ruang);
    $(".btn-submit").attr('disabled', true);
    $(".btn-submit").html('sending email...')
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/savejadwalnew',
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function (response) {
            // $('#modal-add').modal("hide");
            // console.log(response.code);
            if(response.code == CODE_SUCCESS){
                
                swal({
                    title: "Alert",
                    text: "Jadwal telah ditambahkan ",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){ 
                    window.location = baseURL+"/jadwal/jadwalpersentasi"
                });

            }else{
                $(".btn-submit").attr('disabled', false)
                $(".btn-submit").html('submit')
                loaderPage(false);
                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 changedmhs(elemts, dospemid){
    // console.log(dospemid.id)
    // return false
    loaderPage(true)
    var isObject = {};

    isObject.param = elemts.value;

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loadpembimbing',
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            loaderPage(false)
            
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                // console.log(result.data);
                let data = result.data[0];
                var option = '';
                
                $("#"+dospemid.id).select2('destroy')

                option += `<option value="`+data.nopeg+`" selected>`+data.pembimbing+`</option>`
                $("#"+dospemid.id).html(option)
                $("#"+dospemid.id).select2()
                
                

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

var counterspenguji = 2;
var arrAdditional   = [];

function addrowpenguji(){
    if(counterspenguji <= 2){
        loadAdditionalPenguji("penguji"+counterspenguji+"new", counterspenguji);
    }else{
        swal({
            title: "Alert",
            text:  "maksimal 2 penguji!",
            confirmButtonColor: "#2196F3",
            type: "error"
        }); 
    }
    
}

function loadAdditionalPenguji(idselect, no){
    var isObject = {}
    isObject.param = iduser;
    
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loaddsn',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                // console.log(result.data.data);
                let data = result.data;
                // console.log(data);
                var option = '';
                for(i in data){
                    // if(data[i].gelar_dpn != null && data[i].gelar_blk != null){
                        
                        
                    //         option += '<option value="'+data[i].nopeg+'">'+data[i].gelar_dpn+" "+data[i].nama+", "+data[i].gelar_blk+'</option> ';
                        
                        
                    // }else if(data[i].gelar_dpn == null && data[i].gelar_blk != null){

                      
                    //         option += '<option value="'+data[i].nopeg+'">'+data[i].nama+", "+data[i].gelar_blk+'</option> ';
                        
                        
                    // }else if(data[i].gelar_dpn != null && data[i].gelar_blk == null){
                        
                       
                    //         option += '<option value="'+data[i].nopeg+'">'+data[i].gelar_dpn+" "+data[i].nama+'</option> ';
                        
                        
                    // } else {

                        
                    //         option += '<option value="'+data[i].nopeg+'">'+data[i].nama+'</option> ';
                        
                        
                    // }

                    option += '<option value="'+data[i].nopeg+'">'+data[i].nama+'</option> ';
                    
                }

                var contents = `<div class="form-group">
                                    <label class="col-lg-2 control-label text-semibold">Penguji `+no+` :</label>
                                    <div class="col-lg-9">
                                        <select id="`+idselect+`" class="select">
                                        `+option+`
                                        </select>
                                    </div>
                                    <label class="col-lg-1 control-label text-semibold" style="cursor: pointer; color: red!important;" onclick="destroyelement(this)">&#10006;</label>
                                </div>`
                // console.log(contents);
                $("#appendedPenguji").append(contents)

                $("#"+idselect).select2()
                counterspenguji++
            } 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"
                });                        
            }
        }
    });
}

selectTahunAjaran();
function getTahunAjaran(){
    let tahunNow    = new Date().getFullYear();
    let backYear    = 5
    let tahunAjaran = [];

    let asx = tahunNow + 1;
    let tahuntemp   = asx;     
    for(i = 0; i <= backYear; i++ ){
        let yString     = '';
        
        yString = tahuntemp-1+"/"+tahuntemp;
        tahuntemp = tahuntemp - 1;;

        tahunAjaran.push(yString);
    }

    return tahunAjaran;
}

function selectTahunAjaran(){
    let arrayTahun = getTahunAjaran();

    let option = "<option value='null'> --- Pilih Tahun Ajaran --- </option>"
    for(i in arrayTahun){
        option += `<option value="`+arrayTahun[i]+`">`+arrayTahun[i]+`</option>`
    }

    $("#thn_ajaran").html(option);
}

getNopegPenguji();
function getNopegPenguji(){
    let isObject = {};
    isObject.nim = nim;

    console.log(isObject);
    // return false;
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loadpengujidijadwal',
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            loaderPage(false)
            
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                // console.log(result.data);
                let data = result.data[0];

               selectloadpenguji2(data.penguji_2)
               console.log(data.penguji_2);
                
                

            } 
            
        },
        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 selectloadpenguji2(nopeg){
    var isObject = {}
    isObject.param = null;

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loaddsn',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            
            
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                // console.log(result.data.data);
                let data = result.data;
                // console.log(data);
                var option = '';
                
                for(x in data){
                    
                    if(nopeg == data[x].nopeg){
                        option += '<option value="'+data[x].nopeg+'" selected>'+data[x].nama+'</option> ';
                    }else{
                        option += '<option value="'+data[x].nopeg+'">'+data[x].nama+'</option> ';
                    }

                }
                
                $("#pengujis2").html(option);
                
// console.log(data)
            } 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"
                });                        
            }
        }
    });
}

function destroyelement(elements){
    $(elements).closest('div').remove();
    counterspenguji = counterspenguji - 1;
    // console.log($(elements).closest('div'));
}