$(document).ready(function() {

    // $('#calendar-table').DataTable({
    //     "lengthChange": false,
    //     "info": false,
    //     "ordering": false,
    //     "searching": false,
    //     "pageLength": 4,
    //     "dom": '<"top"<"row"<"col-sm-4"l><"col-sm-4 text-center"p><"col-sm-4"f>>>rt<"bottom"<"row"<"col-sm-4"l><"col-sm-4 text-center"p><"col-sm-4"f>>>'
    // });

    // $('input[type=radio][name=purpose]').on('change', function() {
    //     $('#student').prop('disabled', false);
    //     $('#student').selectpicker('refresh');
    // });

    // $('#student').on('change', function(e) {
    //     $('#module').prop('disabled', false);
    //     $("#module").val('default');
    //     $('#module').selectpicker('refresh');
    //     var sid = $("#student").val();
    //     var purpose = $('input[type=radio][name=purpose]:checked').val();
    //     var vid = $("#vehicle").val();
    //     var date = $("#vdate").val();
    //     var time = $("#time").val();
    //     getModule(sid, purpose, vid, date, time);
    // });

    // Script for week menu
    $('#date').datepicker({
        format: 'dd/mm/yyyy',
        autoclose: true,
        language: 'th',
        orientation: 'bottom',
        weekStart: 1,
        calendarWeeks: true,
        daysOfWeekDisabled: [0, 2, 3, 4, 5, 6]
    });

    $('#date').on('change', function(e) {
        var value = $("#date").val();
        var firstDate = moment(value, "dd/mm/yyyy").day(0).format("dd/mm/yyyy");
        var lastDate = moment(value, "dd/mm/yyyy").day(6).format("dd/mm/yyyy");
        $(this).val(lastDate);
        // $("#date").val(firstDate + " - " + lastDate);
    });

    $('#vehicleBookingModal').on('show.bs.modal', function(event) {
        var button = $(event.relatedTarget);
        var vehicle = button.data('vehicle');
        var vehicleType = button.data('type');
        var date = button.data('date');
        var time = button.data('time');
        var spanDate = date.split("-");
        spanDate = spanDate[2] + " / " + spanDate[1] + " / " + spanDate[0];
        var starttime = time + ":00 น.";
        var modal = $(this);
        modal.find('#vehicle').val(vehicle);
        modal.find('#type').val(vehicleType);
        modal.find('#vdate').val(date);
        modal.find('#time').val(time);
        modal.find('#spanDate').text(spanDate);
        modal.find('#spanStarttime').text(starttime);
        //modal.find('.modal-body input').val(recipient);
        // $('#student').selectpicker('liveSearch');
    });

    $('#vehicleBookingModal').on('hidden.bs.modal', function() {

        $("#vehicleBookFrm").trigger("reset");
        $('#studentBooking').prop('disabled', true);
        $('#studentBooking').selectpicker('refresh');
        $('#moduleBooking').prop('disabled', true);
        $('#moduleBooking').selectpicker('refresh');
        //$('#student').selectpicker('refresh');
    });

    $('.selectpicker').selectpicker();

    // $('.modal').on('hidden.bs.modal', function() {
    //     $(".teacherBookFrm").trigger("reset");
    //     $('.teacher').selectpicker('refresh');
    //     $('.teacherTypeDiv').hide();
    //     $('.teacherScanDiv').hide();
    //     $('.teacher-select').selectpicker('refresh');
    // });

    $('.teacherModal2').on('hidden.bs.modal', function() {
        $('form[name="teacherBookFrm2"]').trigger('reset');
        $('.teacherBookFrm2').trigger('reset');
        $('.teacher').selectpicker('refresh');
        $('.teacher-scan').selectpicker('refresh');
    });

    $('.teacherModal2').on('show.bs.modal', function() {
        var teacher = $(this).find('.teacherSelected').val();
        if (teacher) {
            $('.teacherTypeDiv').show();
            if ($(this).find('input[type=radio][name=teacherType]:checked').val() == 'false') {
                $('.teacherScanDiv').show();
            } else {
                $('.teacherScanDiv').hide();
            }
        } else {
            $('.teacherTypeDiv').hide();
            $('.teacherScanDiv').hide();
        }
    });

    $('input[type=radio][name=purposeBooking]').on('change', function(e) {
        var vehicle_type = $('#type').val();
        $('#studentBooking').prop('disabled', false);
        var purpose_booking = $('input[type=radio][name=purposeBooking]:checked').val();
        getStudents(purpose_booking, vehicle_type, 'studentBooking');
    });

    $('#studentBooking').on('change', function(e) {
        $('#moduleBooking').prop('disabled', false);
        var student = $('#studentBooking').val();
        var vtype = $('#type').val();
        var vid = $("#vehicle").val();
        var date = $("#vdate").val();
        var time = $("#time").val();
        var purpose = $('input[type=radio][name=purposeBooking]:checked').val();
        getModule(student, purpose, vtype, vid, date, time, 'moduleBooking');
    });

    $('.teacher').on('change', function(e) {
        $('.teacherTypeDiv').show();
    });

    $('input[type=radio][name=teacherType]').change(function() {
        if (this.value == 'false') {
            $('.teacher-scan').selectpicker('refresh');
            $('.teacherScanDiv').show();
        } else {
            $('.teacher-scan').selectpicker('refresh');
            $('.teacherScanDiv').hide();
        }
    });

    // $('.teacher-scan').on('change', function(e) {
    //     $('.teacherScanDiv').show();
    // });

    // Script for day menu
    $('#dateDay').datepicker({
        format: 'dd/mm/yyyy',
        autoclose: true,
        language: 'th',
        orientation: 'bottom',
    });

});


function fetchRecords(selectID, gear, date, starttime, endtime, courseNo) {
    var dateParts = date.split("/");
    dateParts = dateParts[2] + "-" + dateParts[1] + "-" + dateParts[0];
    var type;
    var drive;
    if (courseNo == '1') {
        type = vehicleType;
        if (purpose == "เก็บชั่วโมงเพื่อสอบ") {
            drive = 'ไม่ขับ';
        } else {
            drive = 'ขับ';
        }
    }
    if (courseNo == '2') {
        type = vehicleType2;
        if (purpose2 == "เก็บชั่วโมงเพื่อสอบ") {
            drive = 'ไม่ขับ';
        } else {
            drive = 'ขับ';
        }
    }
    $.ajax({
        url: '/getVehicles/' + type + '/' + gear + '/' + dateParts + '/' + starttime + '/' + endtime + '/' + drive + '/0',
        type: 'get',
        dataType: 'json',
        success: function(response) {
            var len = 0;
            if (response['data'] != null) {
                len = response['data'].length;
            }
            select = document.getElementById(selectID);
            var length = select.options.length;
            for (i = length - 1; i >= 0; i--) {
                select.options[i] = null;
            }
            if (len > 0) {

                for (var i = 0; i < len; i++) {
                    var id = response['data'][i].id;
                    var number = response['data'][i].number;
                    var brand = response['data'][i].brand;
                    var model = response['data'][i].model;
                    var registration = response['data'][i].registration_class + " " + response['data'][i].registration_number;
                    var vehicle = "คันที่ : " + number + " , " + brand + " " + model + " (" + registration + ")";

                    var opt = document.createElement('option');
                    opt.value = id;
                    opt.innerHTML = vehicle;
                    select.appendChild(opt);
                    $('.selectpicker').selectpicker('refresh');
                }
            }
        }
    });
}

function getStudents(purpose, vehicleType, selectID) {
    $.ajax({
        url: '/getStudent/' + purpose + '/' + vehicleType,
        type: 'get',
        dataType: 'json',
        success: function(response) {
            console.log('/getStudent/' + purpose + '/' + vehicleType);
            var len = 0;
            if (response['data'] != null) {
                len = response['data'].length;
            }
            select = document.getElementById(selectID);
            var length = select.options.length;
            for (i = length - 1; i >= 0; i--) {
                select.options[i] = null;
            }
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    var id = response['data'][i].id;
                    var code = response['data'][i].code_no + "/" + response['data'][i].code_month + "/" + response['data'][i].code_branch;
                    var student = "( " + code + " ) " + response['data'][i].title + response['data'][i].firstname + " " + response['data'][i].lastname;
                    var opt = document.createElement('option');
                    opt.value = id;
                    opt.innerHTML = student;
                    select.appendChild(opt);
                    $('#' + selectID).selectpicker('refresh');
                }
            }
        }
    });
}

function getModule(sid, purpose, vehicleType, vehicleID, date, time, selectID) {
    $.ajax({
        url: '/getModuleForCalendar/' + sid + '/' + purpose + '/' + vehicleType + '/' + vehicleID + '/' + date + '/' + time,
        type: 'get',
        dataType: 'json',
        success: function(response) {
            console.log('/getModuleForCalendar/' + sid + '/' + purpose + '/' + vehicleType + '/' + vehicleID + '/' + date + '/' + time);
            var len = 0;
            if (response['data'] != null) {
                len = response['data'].length;
            }
            var select = document.getElementById(selectID);
            var length = select.options.length;
            for (i = length - 1; i >= 0; i--) {
                select.options[i] = null;
            }
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    var enroll_id = response['data'][i].eid;
                    var module_id = response['data'][i].id;
                    var module_hour = response['data'][i].module_hour;
                    var detail = "[" + module_hour + "] " + response['data'][i].module;
                    var opt = document.createElement('option');
                    opt.value = enroll_id + '-' + module_id + '-' + module_hour;
                    opt.innerHTML = detail;
                    select.appendChild(opt);
                    $('#' + selectID).selectpicker('refresh');
                }
            }
        }
    });
}