var vehicleType;
var vehicleType2;
var purpose;
var purpose2;
$(document).ready(function() {
    $('#registerDate').datepicker({
        format: 'dd/mm/yyyy',
        autoclose: true,
        language: 'th',
        orientation: 'bottom',
        startDate: new Date()
    }).datepicker("setDate", 'now');

    $('#registerDateEdit').datepicker({
        format: 'dd/mm/yyyy',
        autoclose: true,
        language: 'th',
        orientation: 'bottom'
    });

    $('#birthdate').datepicker({
        format: 'dd/mm/yyyy',
        autoclose: true,
        language: 'th',
        orientation: 'bottom'
    });

    $('#examDate').datepicker({
        format: 'dd/mm/yyyy',
        autoclose: true,
        language: 'th',
        orientation: 'bottom',
        startDate: new Date()
    });

    $('#examTime').timepicker({
        showMeridian: false,
        showSeconds: true,
        minuteStep: 1,
        secondStep: 1,
        icons: {
            up: 'fa fa-angle-up',
            down: 'fa fa-angle-down'
        }
    });

    $('#payTime').timepicker({
        showMeridian: false,
        showSeconds: true,
        minuteStep: 1,
        secondStep: 1,
        icons: {
            up: 'fa fa-angle-up',
            down: 'fa fa-angle-down'
        }
    });

    $('#birthdate').on('change', function() {
        var bdate = $('#birthdate').val();
        bdate = bdate.split("/");
        bdate = bdate[0] + '/' + bdate[1] + '/' + bdate[2];
        if (isDate(bdate)) {
            var age = calculateAge(parseDate(bdate), new Date());
            $('#age').val(age);
        } else {
            $('#age').val("");
        }
    });
    $.Thailand({
        $district: $('#district'),
        $amphoe: $('#amphoe'),
        $province: $('#province'),
    });
    // 1st course
    $('#course option').each(function() {
        if (!$(this).is(':selected')) {
            $('#drive1').prop("disabled", true);
            $('#drive2').prop("disabled", true);
            $('#drive3').prop("disabled", true);
            $('#drive4').prop("disabled", true);
            $('#drive5').prop("disabled", true);
            $('#bookingRow1').hide();
            $('#bookingRow2').hide();
            $('#bookingRow3').hide();
            $('#bookingRow4').hide();
            $('#bookingRow5').hide();
        }
    });

    $('#course').on('change', function() {
        var c = $('#course').val().split('-');
        var totalCost = c[1];
        vehicleType = c[3];
        $('#drive1').prop("disabled", false);
        $('#drive2').prop("disabled", false);
        if (vehicleType == 'รถยนต์') {
            $('#bookingRow1').show();
            $('#bookingRow2').show();
            $('#bookingRow3').show();
            $('#bookingRow4').show();
            $('#bookingRow5').show();
            $('#drive3').prop("disabled", false);
            $('#drive4').prop("disabled", false);
            $('#drive5').prop("disabled", false);

            getCourseModule('hour1', c[0]);
            getCourseModule('hour2', c[0]);
            getCourseModule('hour3', c[0]);
            getCourseModule('hour4', c[0]);
            getCourseModule('hour5', c[0]);
        } else {
            $('#bookingRow1').show();
            $('#bookingRow2').show();
            $('#bookingRow3').hide();
            $('#bookingRow4').hide();
            $('#bookingRow5').hide();
            $('#drive3').prop("disabled", true);
            $('#drive4').prop("disabled", true);
            $('#drive5').prop("disabled", true);
            getCourseModule('hour1', c[0]);
            getCourseModule('hour2', c[0]);
        }

        $('#pay').val("");
        if ($('#discountAmount').val() != "") {
            totalCost = (parseInt(totalCost) - parseInt($('#discountAmount').val())).toString();
        }
        $('#totalCost').val(totalCost);
        $('#remain').val(totalCost);
    });

    $('input[type=radio][name=purpose]').on('change', function() {
        purpose = this.value;
        if (purpose == 'เพิ่มประสบการณ์') {
            $('#examDate').prop("disabled", true);
            $('#examDate').val('');
            $('#examTime').prop("disabled", true);
            $('#examTime').val('');
        } else {
            $('#examDate').prop("disabled", false);
            $('#examTime').prop("disabled", false);
        }
    });
    $('#discountAmount').on('change', function() {
        if ($('#course').val() != "") {
            var t = $('#course').val().split('-');
            var cost = t[1];
            cost = (parseInt(cost) - parseInt($('#discountAmount').val())).toString();
            $('#totalCost').val(cost);
            $('#remain').val(cost);
        }
        if ($('#pay').val() != "") {
            $('#remain').val((parseInt($('#totalCost').val()) - parseInt($('#pay').val())).toString());
        }
    });
    $('#pay').on('change', function() {
        if ($('#course').val() != "") {
            if (parseInt($('#pay').val()) > parseInt($('#totalCost').val())) {
                $('#pay').val("");
                $('#remain').val($('#totalCost').val());
            } else {
                var remain = parseInt($('#totalCost').val()) - parseInt($('#pay').val());
                $('#remain').val(remain);
            }
        }
    });
    toggleInput('1');
    $('.selectpicker').selectpicker();

    bookingVehicle('vehicle1', 'gear1', 'date1', 'starttime1', 'endtime1', 'hour1', '1');
    bookingVehicle('vehicle2', 'gear2', 'date2', 'starttime2', 'endtime2', 'hour2', '1');
    bookingVehicle('vehicle3', 'gear3', 'date3', 'starttime3', 'endtime3', 'hour3', '1');
    bookingVehicle('vehicle4', 'gear4', 'date4', 'starttime4', 'endtime4', 'hour4', '1');
    bookingVehicle('vehicle5', 'gear5', 'date5', 'starttime5', 'endtime5', 'hour5', '1');
    // end 1st course

    $('#addRegister2').click(function() {
        $('#addRegister2').hide();
        $('#delRegister2').show();
        $('#register2Course').show();
        $('#register2Course :input').attr('disabled', false);
        //   $('#register2Course :select').attr('disabled', false);
        $('#course2').prop('disabled', false);
        disbledDate2x();

    });

    $('#delRegister2').click(function() {
        $('#addRegister2').show();
        $('#delRegister2').hide();
        $('#register2Course').hide();
        $('.check2').prop('checked', false);
        $('#course2').val('');
        $('#course2').selectpicker('refresh');
        disableDrive('21');
        disableDrive('22');
        disableDrive('23');
        disableDrive('24');
        $('#drive21').prop("disabled", true);
        $('#drive22').prop("disabled", true);
        $('#drive23').prop("disabled", true);
        $('#drive24').prop("disabled", true);
        $('#bookingRow21').hide();
        $('#bookingRow22').hide();
        $('#bookingRow23').hide();
        $('#bookingRow24').hide();
        $('#register2Course :input[type="radio"]').prop('checked', false);
        $('#register2Course :input').attr('disabled', true);
        $('#register2Course :select').attr('disabled', true);
    });

    //For 2nd course
    $('#course2 option').each(function() {
        if (!$(this).is(':selected')) {
            $('#drive21').prop("disabled", true);
            $('#drive22').prop("disabled", true);
            $('#drive23').prop("disabled", true);
            $('#drive24').prop("disabled", true);
            $('#bookingRow21').hide();
            $('#bookingRow22').hide();
            $('#bookingRow23').hide();
            $('#bookingRow24').hide();
        }
    });
    $('#course2').on('change', function() {
        $('#pay2').val("");
        var c = $('#course2').val().split('-');
        var totalCost = c[1];
        vehicleType2 = c[3];
        $('#drive21').prop("disabled", false);
        $('#drive22').prop("disabled", false);
        if (vehicleType2 == 'รถยนต์') {
            $('#bookingRow21').show();
            $('#bookingRow22').show();
            $('#bookingRow23').show();
            $('#bookingRow24').show();
            $('#drive23').prop("disabled", false);
            $('#drive24').prop("disabled", false);
        } else {
            $('#bookingRow21').show();
            $('#bookingRow22').show();
            $('#bookingRow23').hide();
            $('#bookingRow24').hide();
            $('#drive23').prop("disabled", true);
            $('#drive24').prop("disabled", true);
        }
        if ($('#discountAmount2').val() != "") {
            totalCost = (parseInt(totalCost) - parseInt($('#discountAmount2').val())).toString();
        }
        $('#totalCost2').val(totalCost);
        $('#remain2').val(totalCost);
    });
    $('#purpose2').on('change', function() {
        purpose2 = $('#purpose2').val();
    });
    $('#discountAmount2').on('change', function() {
        if ($('#course2').val() != "") {
            var t = $('#course2').val().split('-');
            var cost = t[1];
            vehicleType2 = t[3];
            cost = (parseInt(cost) - parseInt($('#discountAmount2').val())).toString();
            $('#totalCost2').val(cost);
            $('#remain2').val(cost);
        }
        if ($('#pay2').val() != "") {
            $('#remain2').val((parseInt($('#totalCost2').val()) - parseInt($('#pay2').val())).toString());
        }
    });
    $('#pay2').on('change', function() {
        if ($('#course2').val() != "") {
            if ($('#pay2').val() > $('#totalCost2').val()) {
                $('#pay2').val("");
                $('#remain2').val($('#totalCost2').val());
            } else {
                var remain = parseInt($('#totalCost2').val()) - parseInt($('#pay2').val());
                $('#remain2').val(remain);
            }
        }
    });
    $('#examDate2').datepicker({
        format: 'dd/mm/yyyy',
        autoclose: true,
        language: 'th',
        orientation: 'bottom',
        startDate: new Date()
    });
    toggleInput('2');
    bookingVehicle('vehicle21', 'gear21', 'date21', 'starttime21', 'endtime21', 'hour21', '2');
    bookingVehicle('vehicle22', 'gear22', 'date22', 'starttime22', 'endtime22', 'hour22', '2');
    bookingVehicle('vehicle23', 'gear23', 'date23', 'starttime23', 'endtime23', 'hour23', '2');
    bookingVehicle('vehicle24', 'gear24', 'date24', 'starttime24', 'endtime24', 'hour24', '2');
    // end 2nd course
});

function disableDrive(driveNo) {
    $('#gear' + driveNo).prop("disabled", true);
    $('#gear' + driveNo).val("");
    $('#gear' + driveNo).selectpicker('refresh');
    $('#date' + driveNo).prop("disabled", true);
    $('#date' + driveNo).val("");
    $('#starttime' + driveNo).prop("disabled", true);
    $('#starttime' + driveNo).val("");
    $('#starttime' + driveNo).selectpicker('refresh');
    $('#endtime' + driveNo).val("");
    $('#hour' + driveNo).prop("disabled", true);
    $('#hour' + driveNo).val("");
    $('#hour' + driveNo).selectpicker('refresh');
    $('#vehicle' + driveNo).prop("disabled", true);
    $('#vehicle' + driveNo).val("");
    $('#vehicle' + driveNo).selectpicker('refresh');
}

function enableDrive(driveNo) {
    $('#gear' + driveNo).prop("disabled", false);
    $('#gear' + driveNo).selectpicker('refresh');
    $('#date' + driveNo).prop("disabled", false);
    $('#starttime' + driveNo).prop("disabled", false);
    $('#starttime' + driveNo).selectpicker('refresh');
    $('#hour' + driveNo).prop("disabled", false);
    $('#hour' + driveNo).selectpicker('refresh');
    $('#vehicle' + driveNo).prop("disabled", false);
    $('#vehicle' + driveNo).selectpicker('refresh');
}

function toggleInput(courseNo) {
    var id;
    if (courseNo == '1') {
        id = '#drive';
    }
    if (courseNo == '2') {
        id = '#drive2';
    }
    $(id + '1').click(function() {
        if ($(this).is(':checked')) {
            enableDrive('1');
        } else {
            disableDrive('1');
        }
    });
    $(id + '2').click(function() {
        if ($(this).is(':checked')) {
            enableDrive('2');
        } else {
            disableDrive('2');
        }
    });
    $(id + '3').click(function() {
        if ($(this).is(':checked')) {
            enableDrive('3');
        } else {
            disableDrive('3');
        }
    });
    $(id + '4').click(function() {
        if ($(this).is(':checked')) {
            enableDrive('4');
        } else {
            disableDrive('4');
        }
    });
    $(id + '5').click(function() {
        if ($(this).is(':checked')) {
            enableDrive('5');
        } else {
            disableDrive('5');
        }
    });
}

function disbledDate2x() {
    $('#date21').prop("disabled", true);
    $('#date21').val("");
    $('#date22').prop("disabled", true);
    $('#date22').val("");
    $('#date23').prop("disabled", true);
    $('#date23').val("");
    $('#date24').prop("disabled", true);
    $('#date24').val("");
}

function getStopTime(startID, endID, hourID) {
    var start = $('#' + startID).val();
    start = start.split(":");
    var hour = $('#' + hourID).val().split("-"); // format hour from create is id-hour ex: 1-3
    var stop = parseInt(start[0]) + parseInt(hour[1]);
    stop = stop.toString() + ":00";
    $('#' + endID).val(stop);
}

function bookingVehicle(vehicleID, gearID, dateID, startTimeID, endTimeID, hourID, courseNo) {
    $('#' + gearID).on('change', function() {
        if ($('#' + startTimeID).val() != "") {
            fetchRecords(vehicleID, $('#' + gearID).val(), $('#' + dateID).val(), $('#' + startTimeID).val(), $('#' + endTimeID).val(), courseNo, hourID);
        }
    });
    $('#' + dateID).datepicker({
        format: 'dd/mm/yyyy',
        autoclose: true,
        language: 'th',
        orientation: 'bottom',
        startDate: new Date()
    });
    $('#' + dateID).on('change', function() {
        if ($('#' + startTimeID).val() != "" || $('#' + hourID).val() != "") {
            fetchRecords(vehicleID, $('#' + gearID).val(), $('#' + dateID).val(), $('#' + startTimeID).val(), $('#' + endTimeID).val(), courseNo, hourID);
        }
    });
    $('#' + hourID).on('change', function() {
        getStopTime(startTimeID, endTimeID, hourID);
        if ($('#' + startTimeID).val() != "") {
            fetchRecords(vehicleID, $('#' + gearID).val(), $('#' + dateID).val(), $('#' + startTimeID).val(), $('#' + endTimeID).val(), courseNo, hourID);
        }
    });
    $('#' + startTimeID).on('change', function() {
        if ($('#' + hourID).val() != "") {
            getStopTime(startTimeID, endTimeID, hourID);
            fetchRecords(vehicleID, $('#' + gearID).val(), $('#' + dateID).val(), $('#' + startTimeID).val(), $('#' + endTimeID).val(), courseNo, hourID);
        }
    });
}

function fetchRecords(selectID, gear, date, starttime, endtime, courseNo, hourID) {
    var dateParts = date.split("/");
    dateParts = dateParts[2] + "-" + dateParts[1] + "-" + dateParts[0];
    var type;
    var drive;
    var coursePurpose;
    if (courseNo == '1') {
        type = vehicleType;
        if (purpose == "เก็บชั่วโมงเพื่อสอบ") {
            drive = 'ไม่ขับ';
        } else {
            var d = $('#' + hourID).val().split("-");
            drive = d[2];
        }
        coursePurpose = purpose;
    }
    if (courseNo == '2') {
        type = vehicleType2;
        if (purpose2 == "เก็บชั่วโมงเพื่อสอบ") {
            drive = 'ไม่ขับ';
        } else {
            var d = $('#' + hourID).val().split("-");
            drive = d[2];
        }
        coursePurpose = purpose2;
    }
    $.ajax({
        url: '/getVehicles/' + type + '/' + gear + '/' + dateParts + '/' + starttime + '/' + endtime + '/' + drive + '/' + coursePurpose + '/0',
        type: 'get',
        dataType: 'json',
        success: function(response) {
            // console.log('/getVehicles/' + type + '/' + gear + '/' + dateParts + '/' + starttime + '/' + endtime + '/' + drive + '/' + coursePurpose + '/0');
            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 getCourseModule(selectID, courseID) {
    $.ajax({
        url: '/getModule/' + courseID,
        type: 'get',
        dataType: 'json',
        success: function(response) {
            console.log('/getModule/' + courseID);
            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 hour = response['data'][i].id + "-" + response['data'][i].module_hour + "-" + response['data'][i].drive;
                    var name = "[" + response['data'][i].module_hour + "] " + response['data'][i].module;
                    var opt = document.createElement('option');
                    opt.value = hour;
                    opt.innerHTML = name;
                    select.appendChild(opt);
                    $('.selectpicker').selectpicker('refresh');
                }
            }
        }
    });
}