$(document).ready(function () {
    SelectHospital();
    var redirect = 0;
});
var totdayCount = 0;

function SelectHospital() {
    debugger;
    var HospitalData = {
        Dml_Indicator: "HS",
        doctor_id: $('#HiddenDoctorID').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(HospitalData),
        success: function (data) {
            debugger;
            if (jQuery.isEmptyObject((data))) {

            }
            else {
                var data = JSON.parse(data);
                console.log(data);
                if (data.msg = "Success") {
                    var default_opt = '<option value="0">--Select--</option>';
                    var SelHospital = '';
                    $('#SelHospital').empty();
                    if (data.data.length > 0) {
                        for (var i = 0; i < data.data.length; i++) {
                            SelHospital = SelHospital + '<option value="' + data.data[i].hospital_id + '">' + data.data[i].hospital_name + '</option>';
                        }
                        $('#SelHospital').append(SelHospital);
                        $('#SelHospital').prop('disabled', true);
                        LoadBranch();
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

//on change function, call the load doctor function
$('#SelHospital').change(function () {
    $('#SelDepartment,#SelSubDepartment,#SelService').val('');
    $('#SelDepartment,#SelSubDepartment,#SelService,#SelBranch,#SelDoctor').empty();
    LoadBranch();
    //LoadDoctor();
});

$('#SelBranch').change(function () {
    debugger;
    if ($('#SelSheduleType').val() == 1) {
        LoadDoctor();
    }
    else {
        $('#SelService').empty();

        //$('#SelDepartment').val(0); // one master concept
        //$('#SelSubDepartment').empty(); // one master concept
        //load_departmentlist(); // one master concept
    }
});

function LoadBranch() {
    debugger;
    $('#SelBranch').empty();

    //Only KinderSurge
    //var dml = ''
    //if (parseInt($('#hiddenRole_id').val()) == 1) {
    //    dml = 'DLBRAN'
    //}
    //else {
    //    dml = 'LBRAN'
    //}

    var subdepartment = {
        Dml_Indicator: "LBRAN",
        //Dml_Indicator: dml,
        name: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var SubDepartment;
                    var default_opt = '<option value="0">All</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#SelBranch').append(SubDepartment);
                        $('#SelBranch').change();
                    }
                    else {
                        $('#SelBranch').append(default_opt + SubDepartment);
                    }

                    //Only KinderSurge
                    //if ($('#hiddenRole_id').val() == 1) {
                    //    $('#SelBranch').val($('#HospitalBranchID').val());
                    //    if ($('#hiddenRole_id').val() == 1) {
                    //        $('#SelSheduleType').val(1);
                    //        $('#SelSheduleType').attr('disabled', true);
                    //    }
                    //    $('#SelSheduleType').change();
                    //    $('#div_SelDoctor').show();
                    //    LoadDoctor();
                    //}
                    //else 
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#SelBranch').val($('#HospitalBranchID').val());
                        $('#SelBranch').attr('disabled', true);
                        //$('#SelSheduleType').val(1);
                        //$('#SelSheduleType').attr('disabled', true);
                        if ($('#hiddenRole_id').val() == 1) {
                            $('#SelSheduleType').val(1);
                            $('#SelSheduleType').attr('disabled', true);
                        }
                        $('#SelSheduleType').change();
                        $('#div_SelDoctor').show();
                        LoadDoctor();
                    }
                    
                }
            }
            else {
                console.log(data1);
            }

        }
    });
}

//load doctor list based on hospital id
function LoadDoctor() {
    debugger;
    var roleId = $('#hiddenRole_id').val();
    var DoctorId = $('#HiddenDoctorID').val();
    //if (roleId == "2" || roleId == "3") {     
    //    var DoctorData = {
    //        Dml_Indicator: "DL",
    //        hospital_id: $('#SelHospital').val(),
    //        branch_id: $('#SelBranch').val()
    //    }
    //}
    //else {
    //    var DoctorData = {
    //        Dml_Indicator: "DO",
    //        doctor_id: DoctorId,
    //    }
    if (roleId == "1") {
        var DoctorData = {
            Dml_Indicator: "DO",
            doctor_id: DoctorId,
        }
    }
    else {
        var DoctorData = {
            Dml_Indicator: "HDL",
            hospital_id: $('#SelHospital').val(),
            branch_id: $('#SelBranch').val()
        }
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            debugger;
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                var data1 = JSON.parse(data)
                if (data1.msg = "Success") {
                    var tr = '';
                    var SelRole = '';
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    $('#SelDoctor').empty();
                    if (data1.data.length > 0) {
                        for (var i = 0; i < data1.data.length; i++) {
                            j++;
                            /*SelRole = SelRole + '<option value="' + data1.data[i].doctor_id + '">' + data1.data[i].first_name + '</option>';*/
                            SelRole = SelRole + '<option value="' + data1.data[i].doctor_id + '" data-id="' + data1.data[i].doctoruserid + '">' + data1.data[i].first_name + '</option>';

                        }
                        $('#SelDoctor').append(default_opt + SelRole);
                        if (data1.data.length == 1) {
                            $('#SelDoctor').val(data1.data[0].first_name);
                            $('#Hdn_docid').val('');
                            $('#Hdn_docid').val($('#HiddenDoctorID').val());

                            if ($('#hiddenRole_id').val() == 1)
                            {
                                $('#SelDoctor').attr('disabled', true)
                            }        
                        }
                        else {
                            $('#SelDoctor').val($('#QSdoctor_id').val());
                            //$('#SelDoctor').attr('disabled', false)
                        }
                    }
                }
                else {
                    console.log(data1);
                }
            }
        }
    });
}

//based on shedule type, we need to show the select type
$('#SelSheduleType').change(function () {
    if ($('#SelSheduleType').val() == "1") {
        $('#div_SelDepartment,#div_SelSubDepartment,#div_SelUser').hide();
        $('#div_SelDoctor').show();
        $('#SelDepartment,#SelSubDepartment,#SelService').val('');
        $('#SelSubDepartment,#SelService').empty();
        $('.counter_addon').show();
        $('#txtPatientTime').val(00);
        $('.divPerPatientHandling').show();
        $('#divAppointmentType').show();
        LoadDoctor();
    }
    else if ($('#SelSheduleType').val() == "2") {
        $('#div_SelDepartment,#div_SelSubDepartment,#div_SelUser').show();
        $('#div_SelDoctor').hide();
        $('.counter_addon').hide();
        $('#txtPatientTime').val(00);
        $('.divPerPatientHandling').hide();
        $('#divAppointmentType').hide();
        load_departmentlist();
    }
    else {
        $('#div_SelDepartment,#div_SelSubDepartment,#div_SelUser').hide();
        $('#div_SelDoctor').hide();

    }
});


//load department list based on hospital id
function load_departmentlist() {
    var MCDTbldata = {
        Dml_Indicator: 'CDSC',
        type: 2,
       // branch_id: $('#SelBranch').val() // one master concept
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(MCDTbldata),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data)) {
            }
            else {
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var tr = '';
                    var SelRole = '';
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    $('#SelDepartment').empty();
                    if (data1['Table'].length > 0) {
                        for (var i = 0; i < data1['Table'].length; i++) {
                            j++;
                            SelRole = SelRole + '<option value="' + data1['Table'][i].master_category_department_id + '">' + data1['Table'][i].name + '</option>';
                        }
                        $('#SelDepartment').append(default_opt + SelRole);
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}


//on change function, call the load_sub_department function
$('#SelDepartment').change(function () {
    load_sub_department()
});

$('#SelSubDepartment').change(function () {
    load_user()
});

function load_user() {
    debugger;
    var UserData = {
        Dml_Indicator: 'US',
        condition: $('#SelDepartment').val(),
        subdepartment: $('#SelSubDepartment').val()
    };
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(UserData),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (!jQuery.isEmptyObject(data)) {
                if (data2.msg === "Success") {
                    var data1 = data2.data;
                    var SelRole = '';
                    var default_opt = '<option value="0">--Select--</option>';
                    $('#SelUser').empty();
                    if (data1['Table'].length > 0) {
                        for (var i = 0; i < data1['Table'].length; i++) {
                            SelRole += '<option value="' + data1['Table'][i].doctor_user_id + '">' + data1['Table'][i].doctorname + '</option>';
                        }
                        $('#SelUser').append(SelRole);
                    }
                    // Initialize Select2 for multi-select functionality
                    $('#SelUser').select2({
                        placeholder: "--Select Users--",
                        allowClear: true
                    });
                }
            } else {
                console.log(data);
            }
        }
    });
}


//load sub department list based on department id
function load_sub_department() {
    debugger;
    var SCDTbldata = {
        Dml_Indicator: 'SUDSA',
        Master_cd_id: $('#SelDepartment').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(SCDTbldata),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data)) {
            }
            else {
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var tr = '';
                    var SelRole = '';
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    $('#SelSubDepartment').empty();
                    if (data1['Table1'].length > 0) {
                        for (var i = 0; i < data1['Table1'].length; i++) {
                            j++;
                            SelRole = SelRole + '<option value="' + data1['Table1'][i].sub_category_department_id + '">' + data1['Table1'][i].sub_cd_name + '</option>';
                        }
                        $('#SelSubDepartment').append(default_opt + SelRole);
                    }          
                }
                else {
                    console.log(data);
                }
            }
        }
    });

   
}


//get no of concurrent slots based on sub department id
$('#SelSubDepartment').change(function () {
    concurrent_slot();
    //LoadService();
})
function concurrent_slot() {
    var SubDepartmentData = {
        Dml_Indicator: "GSDS",
        sub_department_id: $('#SelSubDepartment').val(),

    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(SubDepartmentData),
        success: function (data) {
            $('#Sub_Dept_Slots').val('');
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                var data1 = JSON.parse(data)
                if (data1.msg = "Success") {
                    if (data1.data.length > 0) {
                        for (var i = 0; i < data1.data.length; i++) {
                            $('#Sub_Dept_Slots').val(data1.data[i].number_of_concurrent_slots);
                        }
                    }
                }
                else {
                    console.log(data1);
                }
            }
        }
    })
}
function LoadService() {
    var service_data = {
        P_Dml_Indicator: "SL",
        branch_id: $('#SelBranch').val(),
        department_id: $('#SelDepartment').val(),
        sub_department_id: $('#SelSubDepartment').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(service_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                $('#SelService').empty();
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var Service;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        Service = Service + '<option value="' + emp.master_service_id + '">' + emp.service_name + '</option>';
                    });
                    $('#SelService').append(default_opt + Service);
                }
            }
            else {
                console.log(data1);
            }
        }
    })
}

function timeconvert(time) {
    debugger
    var time = time;
    var hours = Number(time.match(/^(\d+)/)[1]);
    var minutes = Number(time.match(/:(\d+)/)[1]);
    var AMPM = time.match(/\s(.*)$/)[1];
    if (AMPM == "PM" && hours < 12) hours = hours + 12;
    if (AMPM == "AM" && hours == 12) hours = hours - 12;
    var sHours = hours.toString();
    var sMinutes = minutes.toString();
    if (hours < 10) sHours = "0" + sHours;
    if (minutes < 10) sMinutes = "0" + sMinutes;
    time = (sHours + ":" + sMinutes);
    return time;
}


// Convert a time in hh:mm format to minutes
function timeToMins(time) {
    var b = time.split(':');
    return b[0] * 60 + +b[1];
}

// Convert minutes to a time in format hh:mm
// Returned value is in range 00  to 24 hrs
function timeFromMins(mins) {
    function z(n) { return (n < 10 ? '0' : '') + n; }
    var h = (mins / 60 | 0) % 24;
    var m = mins % 60;
    return z(h) + ':' + z(m);
}

// Add two times in hh:mm format
function addTimes(t0, t1) {
    return timeFromMins(timeToMins(t0) + timeToMins(t1));
}

function converthourstoseconds(hms) {
    var hms = hms;   // your input string
    var a = hms.split(':'); // split it at the colons

    // minutes are worth 60 seconds. Hours are worth 60 minutes.
    var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
    //console.log('sec----' + seconds);
    hms = seconds;
    return hms;
}

$("#BtnSubmit").click(function () {
    debugger;
    var Chkapplicationhidemob = '';
    if ($('#Chkapplicationhidemob').prop("checked") == true) {
        Chkapplicationhidemob = 1;
    }
    else if ($('#Chkapplicationhidemob').prop("checked") == false) {
        Chkapplicationhidemob = 0;
    }


    if ($.trim($('#SelHospital :selected').val()) == "" || $('#SelHospital :selected').val() == "0") {
        $('#PSelHospital').show();
        $('#PSelHospital').fadeOut(8000);
        $('#PSelHospital').html('Select Hospital');
        $('#SelHospital').focus();
        $('#SelHospital :selected').val('0');
        return false;
    }

    if ($.trim($('#SelBranch :selected').val()) == "" || $('#SelBranch :selected').val() == "0") {
        $('#PSelBranch').show();
        $('#PSelBranch').fadeOut(8000);
        $('#PSelBranch').html('Select Branch');
        $('#SelBranch').focus();
        $('#SelBranch :selected').val('0');
        return false;
    }

    if ($.trim($('#SelSheduleType').val()) == "0" || $.trim($('#SelSheduleType').val()) == "") {
        $('#PSelSheduleType').show();
        $('#PSelSheduleType').fadeOut(8000);
        $('#PSelSheduleType').html('Select Schedule Type');
        return false;
    }

    if ($.trim($('#SelSheduleType').val()) == "1") {
        if ($.trim($('#SelDoctor').val()) == "0" || $.trim($('#SelDoctor').val()) == "") {
            $('#PSeldocerr').show();
            $('#PSeldocerr').fadeOut(8000);
            $('#PSeldocerr').html('Select Doctor');
            return false;
        }
    }

    if ($.trim($('#SelSheduleType').val()) == "2") {
        if ($.trim($('#SelDepartment').val()) == "0" || $.trim($('#SelDepartment').val()) == "") {
            $('#PSeDepartment').show();
            $('#PSeDepartment').fadeOut(8000);
            $('#PSeDepartment').html('Select Department');
            return false;
        }
        if ($.trim($('#SelSubDepartment').val()) == "0" || $.trim($('#SelSubDepartment').val()) == "") {
            $('#PSelSubDepartment').show();
            $('#PSelSubDepartment').fadeOut(8000);
            $('#PSelSubDepartment').html('Select Sub Department');
            return false;
        }
        //if ($.trim($('#SelService').val()) == "0" || $.trim($('#SelService').val()) == "") {
        //    $('#PSelService').show();
        //    $('#PSelService').fadeOut(8000);
        //    $('#PSelService').html('Select Service');
        //    return false;
        //}
    }

    if ($.trim($('#FDate').val()) == "") {
        $('#PFDate').show();
        $('#PFDate').fadeOut(8000);
        $('#PFDate').html('Select From Date');
        $('#FDate').focus();
        $('#FDate').val('');
        return false;
    }

    if ($.trim($('#EDate').val()) == "") {
        $('#PEDate').show();
        $('#PEDate').fadeOut(8000);
        $('#PEDate').html('Select End Date');
        $('#EDate').focus();
        $('#EDate').val('');
        return false;
    }

    if ($.trim($('#SelDay').val()) == "" || $.trim($('#SelDay').val()) == null) {
        $('#PSelDay').show();
        $('#PSelDay').fadeOut(8000);
        $('#PSelDay').html('Select Days');
        $('#SelDay').focus();
        $('#SelDay :selected').val('0');
        return false;
    }

    if ($.trim($('#FTime').val()) == "") {
        $('#PFTime').show();
        $('#PFTime').fadeOut(8000);
        $('#PFTime').html('Enter From Time');
        $('#FTime').focus();
        $('#FTime').val('');
        return false;
    }

    if ($.trim($('#ETime').val()) == "") {
        $('#PETime').show();
        $('#PETime').fadeOut(8000);
        $('#PETime').html('Enter To Time');
        $('#ETime').focus();
        $('#ETime').val('');
        return false;
    }

    if ($.trim($('#SelSheduleType').val()) == "1") {
        if ($.trim($('#AppType').val()) == "" || $.trim($('#AppType').val()) == null) {
            $('#PAppType').show();
            $('#PAppType').fadeOut(8000);
            $('#PAppType').html('Select Appointment Type');
            $('#AppType').focus();
            $('#AppType :selected').val('0');
            return false;
        }
    }

    if ($('#SelSheduleType').val() == 1) {
        if ($.trim($('#txtPatientTime').val()) == "" || $('#txtPatientTime').val() == "00" || $('#txtPatientTime').val() == "0") {
            $('#PtxtPatientTime').show();
            $('#PtxtPatientTime').fadeOut(8000);
            $('#PtxtPatientTime').html('Enter Per patient handling time');
            $('#txtPatientTime').focus();
            $('#txtPatientTime').val('00');
            return false;
        }
    }
    var selecteduser = $('#SelUser').val();
    if (selecteduser && selecteduser.length > $('#Sub_Dept_Slots').val()) {
        toastr.warning('Slot not available');
        $('#PSeUser').val('');
        return false;
    }
   
    if ($.trim($('#ETime').val()) == $('#FTime').val()) {
        $('#PETime').show();
        $('#PETime').fadeOut(8000);
        $('#PETime').html('Start Time and To Time cant be same');
        $('#ETime').focus();
        $('#ETime').val('');
        return false;
    }

    var from_time = $('#FTime').val();
    from_time = timeconvert(from_time);
    var to_time = $('#ETime').val();
    to_time = timeconvert(to_time);

    if ($('#SelSheduleType').val() == 1) {
        if (from_time >= to_time) {
            $('#PETime').show();
            $('#PETime').fadeOut(8000);
            $('#PETime').html('Enter valid To Time');
            $('#ETime').focus();
            $('#ETime').val('');        
            return false;
        }
    }
    else {
        var time_diff = (moment($('#ETime').val(), ['hh:mm A']).diff(moment($('#FTime').val(), ['hh:mm A']), 'hours'));
        var handle_hour = $('#txtPatientTime').val() / 60;
        if (time_diff < handle_hour) {
            $('#PETime').show();
            $('#PETime').fadeOut(8000);
            $('#PETime').html('Enter valid To Time');
            $('#ETime').focus();
            $('#ETime').val('');
            return false;
        }


    }
    $('#shade_slot').show();

    var AppType = $('#AppType').val();
    var AppointmentType = '';
    // 1.physical, 2.video, 3.sms, 4.physical & video, 5.physical & video & sms,  6.video &sms, 7.physical & sms
    if (AppType == '1') {
        AppointmentType = 1;
    }
    else if (AppType == '2') {
        AppointmentType = 2;
    }
    else if (AppType == '3') {
        AppointmentType = 3;
    }
    else if (AppType == '1,2,3') {
        AppointmentType = 5;
    }
    else if (AppType == '1,2') {
        AppointmentType = 4;
    }
    else if (AppType == '1,3') {
        AppointmentType = 7;
    }
    else if (AppType == '2,3') {
        AppointmentType = 6;
    }

    //$(':input[type="submit"]').prop('disabled', true);
    //$('#BtnSubmit').attr('disable',true);
    $('#BtnSubmit').hide();
    //if (($.trim($('#SelHospital :selected').val()) != "" || $('#SelHospital :selected').val() != "0") && ($.trim($('#FDate').val()) != "") && ($.trim($('#EDate').val()) != "") && ($.trim($('#SelDay').val()) != "" || $('#SelDay').val() != "0") && ($.trim($('#FTime').val()) != "") && ($.trim($('#ETime').val()) != "") && ($.trim($('#txtPatientTime').val()) != "" || $('#txtPatientTime').val() != "00")) {
    var Fdate, Edate, formated_Fdate, formated_Edate, Fdate_temp;
    var FDate = $('#FDate').val();
    Fdate = FDate.split('/');
    formated_Fdate = Fdate[1] + '/' + Fdate[0] + '/' + Fdate[2];
    Fdate = new Date(formated_Fdate);
    Fdate_temp = new Date(formated_Fdate);

    var EDate = $('#EDate').val();
    Edate = EDate.split('/');
    formated_Edate = Edate[1] + '/' + Edate[0] + '/' + Edate[2];
    Edate = new Date(formated_Edate);

    var dc_id;

    if ($('#SelSheduleType').val() == "1") {
        dc_id = $('#Hdn_docid').val();
    }
    else {
        dc_id = $('#HiddenDoctorID').val();
    }


    // var tot = (Edate.getDate() - Fdate.getDate());
    var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
    //var firstDate = new Date(2008, 01, 12);
    //var secondDate = new Date(2008, 01, 22);

    var diffDays = Math.round(Math.abs((Fdate.getTime() - Edate.getTime()) / (oneDay)));
    //alert(diffDays);
    //return false;
    // var days = (Edate - Fdate) / 1000 / 60 / 60 / 24;
    var SelDay = $('#SelDay').val();
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    var check = new Date(Fdate);
    var check_temp = new Date(Fdate_temp);
    debugger;
    var diffDayss = diffDays;
    var totsolts = '';
    var b = 0, c = 0;
   // toastr.warning('Please wait while loading...');
    for (var k = 0; k <= diffDays; k++) {
        if (k > 0) {

            check_temp = new Date(Fdate_temp.setDate(Fdate_temp.getDate() + 1));
        }
        for (var l = 0; l <= diffDays ; l++) {
            if (check_temp.getDay() == SelDay[l]) {
                c++;
            }
        }
    }

    console.log('c------>' + c);
    if (c > 0) {
        for (var i = 0; i <= diffDays; i++) {


            debugger;
            if (i > 0) {

                check = new Date(Fdate.setDate(Fdate.getDate() + 1));
            }

            for (var j = 0; j <= diffDays ; j++) {
                debugger;
                console.log('diffDays------>' + diffDays);

                if (check.getDay() == SelDay[j]) {
                    var date = check.getDate();
                    var month = check.getMonth() + 1;
                    var year = check.getFullYear();

                    if (date < 10) {
                        date = '0' + date;
                    }
                    if (month < 10) {
                        month = '0' + month;
                    }
                    var convertdate = year + '-' + month + '-' + date;
                    totdayCount++;

                    var selecteduser = $('#SelUser').val();
                    var selectedUserId = "";

                    if (selecteduser && selecteduser.length >0) {
                        selectedUserId = selecteduser.join(',');
                    } else {
                        selectedUserId = $('#Hdata_id').val();
                    }
                   
                    //insert function
                    var perpatienttime = $('#txtPatientTime').val();
                    var HospitalData = {
                        Dml_Indicator: "I",
                        doctor_id: dc_id,
                        hospital_id: $('#SelHospital').val(),
                        schedule_date: convertdate,
                        from_time: convertdate + " " + from_time,
                        to_time: convertdate + " " + to_time,
                        per_patient_time: perpatienttime,
                        doctor_schedule_type: AppointmentType,
                        schedule_status: 1,
                        appointment_flag: Chkapplicationhidemob,
                        schedule_type: $('#SelSheduleType').val(),
                        department_id: $('#SelDepartment').val(),
                        sub_department_id: $('#SelSubDepartment').val(),
                        branch_id: $('#SelBranch').val(),
                        master_service_id: $('#SelService').val(),
                        doctoruserid: selectedUserId
                    }
                    //console.log(HospitalData);
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/CalendarConfiguration/CalendarConfiguration',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(HospitalData),
                        success: function (data) {
                            debugger;
                            //slotInsert(data);

                            ajaxroundcount++;
                            //var a= StringMsg

                            // $.when(slotInsert(data)).then(redirect());


                            var data1 = JSON.parse(data);
                            console.log(data1);
                            if (data1.msg = "Success") {
                                var doctorScheduleId;
                                var Rschedule_date;
                                for (var i = 0; i < data1.data.length; i++) {
                                    doctorScheduleId = data1.data[i].StringMsg;
                                    Rschedule_date = data1.data[i].Rschedule_date;
                                    //alert(doctorScheduleId);
                                }
                                debugger;
                                var from_time = $('#FTime').val();
                                from_time = timeconvert(from_time);
                                var to_time = $('#ETime').val();
                                to_time = timeconvert(to_time);
                                var SlotTime = '';
                                if ($('#SelSheduleType').val() == "2")   //added by nandhini for department level appointment slot // set per patient handling based on from and to time
                                {
                                    var tstartTime = moment(from_time, 'hh:mm');
                                    var tendTime = moment(to_time, 'hh:mm');

                                    var ttotalSec = tendTime.diff(tstartTime, 'seconds');
                                    var minutes = parseInt(ttotalSec / 60);

                                    SlotTime = minutes;
                                    var SlotConvertTime;
                                    if (SlotTime == "60") {
                                        SlotConvertTime = converthourstoseconds('01:00:00');
                                        SlotTime = "60:00"
                                    }
                                    else {
                                        SlotConvertTime = converthourstoseconds('00:' + SlotTime + ':00');
                                        SlotTime = '00:' + SlotTime;
                                    }
                                }
                                else {
                                    SlotTime = $('#txtPatientTime').val();
                                    var SlotConvertTime;
                                    if (SlotTime == "60") {
                                        SlotConvertTime = converthourstoseconds('01:00:00');
                                        SlotTime = "60:00"
                                    }
                                    else {
                                        SlotConvertTime = converthourstoseconds('00:' + SlotTime + ':00');
                                        SlotTime = '00:' + SlotTime;
                                    }
                                }

                                var startTime = moment(from_time, 'hh:mm');
                                var endTime = moment(to_time, 'hh:mm');

                                var totalSec = endTime.diff(startTime, 'seconds');

                                var hours = parseInt(totalSec / 3600) % 24;
                                var minutes = parseInt(totalSec / 60) % 60;
                                var seconds = totalSec % 60;

                                var total_fixed_time = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);

                                total_fixed_time = converthourstoseconds(total_fixed_time);
                                var totslotcount = total_fixed_time / SlotConvertTime;

                                var indiSlotETime = from_time;
                                var indiSlotSTime = from_time;
                                console.log('totslotcountb------->' + totslotcount);
                                for (i = 0; i < totslotcount; i++) {
                                    debugger;

                                    console.log('totslotcount------->' + totslotcount);
                                    var totsolts = parseInt(c) * parseInt(totslotcount);
                                    console.log(totsolts);

                                    indiSlotETime = addTimes(indiSlotETime, SlotTime);
                                    if (converthourstoseconds(indiSlotETime + ":00") <= converthourstoseconds(to_time + ":00")) {
                                        var Rschedule_date1 = Rschedule_date + " " + indiSlotSTime;
                                        var Rschedule_date2 = Rschedule_date + " " + indiSlotETime;
                                        var doctorScheduleId1 = doctorScheduleId;

                                        for (let l = 0; l < $('#Sub_Dept_Slots').val() ; l++) {

                                            var SlotData = {
                                                doctor_schedule_id: doctorScheduleId,
                                                slot_start_time: Rschedule_date + " " + indiSlotSTime + ":00",
                                                slot_end_time: Rschedule_date + " " + indiSlotETime + ":00",
                                                doctor_appointment_slot_status: "3",
                                                Dml_Indicator: "I",
                                            }
                                            var a = 0;
                                            var tot = totslotcount;
                                            $.ajax({
                                                async: true,
                                                type: 'POST',
                                                url: '/CalendarConfiguration/DoctorAppointmentSlot',
                                                contentType: 'application/json; charset=UTF-8',
                                                data: JSON.stringify(SlotData),
                                                success: function (data) {
                                                    debugger;
                                                    b++;
                                                    console.log(a);
                                                    console.log('done');
                                                    console.log('a------------' + a);
                                                    console.log('tot------------' + tot);
                                                    console.log('totdayCount------------' + totdayCount);
                                                    console.log('ajaxroundcount------------' + ajaxroundcount);
                                                    console.log('b------->' + b);
                                                    console.log('totsolts------>' + totsolts);
                                                    //if ((parseInt(a) == parseInt(tot - 1) && totdayCount == ajaxroundcount && b == totsolts)) {
                                                    //    window.location.href = '/CalendarConfigurationList/';
                                                    //}
                                                    if (b == (parseInt(totsolts) * parseInt($('#Sub_Dept_Slots').val()))) {
                                                        window.location.href = '/CalendarConfigurationList/';
                                                    }

                                                    //if ( b == totsolts) {
                                                    //    //alert('completed');
                                                    //    window.location.href = '/CalendarConfigurationList/';
                                                    //}

                                                    return a++;
                                                    //a++;

                                                }

                                            });
                                        }


                                    }
                                    indiSlotSTime = indiSlotETime;
                                    //console.log('i vali-------' + a + 'totval-----------' + totslotcount);

                                    //if (a == (totslotcount - 1)) {

                                    //    redirect = 1;
                                    //    return redirect;
                                    //    console.log('redirect enter');
                                    //}

                                }

                            }
                            else {
                                console.log(data1)
                            }
                        }


                    });



                }
                //else {
                //    diffDayss = parseInt(diffDayss) - parseInt(1);
                //    console.log(diffDayss);
                //}
                //console.log('j------------' + j);

            }

            //console.log(check);
        }
    }
    else {
        $('#BtnSubmit').show();
        $('#PEDate').show();
        $('#PEDate').fadeOut(8000);
        $('#PEDate').html('check the date');
        $('#EDate').focus();
        return false;
    }


    // }
    // redirect();
});
var ajaxroundcount = 0;
function redirectfun() {
    window.location.href = '/CalendarConfigurationList/';
}
function old_insert(date, from_time, to_time) {
    var perpatienttime = $('#txtPatientTime').val();
    console.log(perpatienttime);
    var HospitalData = {
        Dml_Indicator: "I",
        doctor_id: $('#Hdn_docid').val(),
        hospital_id: $('#SelHospital').val(),
        schedule_date: date,
        from_time: date + " " + from_time,
        to_time: date + " " + to_time,
        per_patient_time: perpatienttime,
        schedule_status: 1
    }
    //console.log(HospitalData);
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/CalendarConfiguration',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(HospitalData),
        success: function (data) {
            slotInsert(data);
            ajaxroundcount++;
            //var a= StringMsg

            // $.when(slotInsert(data)).then(redirect());
        }


    });

}

function old_slotInsert(data) {

    var data1 = JSON.parse(data);
    console.log(data1);
    var doctorScheduleId;
    var Rschedule_date;
    for (var i = 0; i < data1.data.length; i++) {
        doctorScheduleId = data1.data[i].StringMsg;
        Rschedule_date = data1.data[i].Rschedule_date;
        //alert(doctorScheduleId);
    }
    var from_time = $('#FTime').val();
    from_time = timeconvert(from_time);
    var to_time = $('#ETime').val();
    to_time = timeconvert(to_time);
    var SlotTime = $('#txtPatientTime').val();
    var SlotConvertTime;
    if (SlotTime == "60") {
        SlotConvertTime = converthourstoseconds('01:00:00');
        SlotTime = "60:00"
    }
    else {
        SlotConvertTime = converthourstoseconds('00:' + SlotTime + ':00');
        SlotTime = '00:' + SlotTime;
    }
    var startTime = moment(from_time, 'hh:mm');
    var endTime = moment(to_time, 'hh:mm');

    var totalSec = endTime.diff(startTime, 'seconds');

    var hours = parseInt(totalSec / 3600) % 24;
    var minutes = parseInt(totalSec / 60) % 60;
    var seconds = totalSec % 60;

    var total_fixed_time = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);

    total_fixed_time = converthourstoseconds(total_fixed_time);
    console.log('total_fixed_time----' + total_fixed_time)
    var totslotcount = total_fixed_time / SlotConvertTime;

    var indiSlotETime = from_time;
    var indiSlotSTime = from_time;
    console.log('totslotcount--------' + totslotcount);
    console.log('indiSlotETime------' + indiSlotETime);
    console.log((converthourstoseconds(indiSlotETime + ":00") + ' ------- ' + converthourstoseconds(to_time + ":00")));

    for (i = 0; i < totslotcount; i++) {
        console.log('(indiSlotETime, SlotTime)-----' + (indiSlotETime + '-------------' + SlotTime));
        indiSlotETime = addTimes(indiSlotETime, SlotTime);
        console.log(indiSlotETime);
        if (converthourstoseconds(indiSlotETime + ":00") <= converthourstoseconds(to_time + ":00")) {
            console.log('indiSlotETime-' + i + ' ------' + indiSlotETime);
            var Rschedule_date1 = Rschedule_date + " " + indiSlotSTime;
            var Rschedule_date2 = Rschedule_date + " " + indiSlotETime;
            var doctorScheduleId1 = doctorScheduleId;
            console.log('SlotData-' + i + ' ------' + Rschedule_date1 + ',' + Rschedule_date2 + ',' + doctorScheduleId1);
            var SlotData = {

                doctor_schedule_id: doctorScheduleId,
                slot_start_time: Rschedule_date + " " + indiSlotSTime + ":00",
                slot_end_time: Rschedule_date + " " + indiSlotETime + ":00",
                doctor_appointment_slot_status: "3",
                Dml_Indicator: "I",
            }
            console.log('SlotData-' + i + ' ------' + SlotData);
            var a = 0;
            var tot = totslotcount;
            $('#shade_slot').hide();
            $.ajax({
                async: true,
                type: 'POST',
                url: '/CalendarConfiguration/DoctorAppointmentSlot',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(SlotData),
                success: function (data) {
                    console.log(a);
                    console.log('done');
                    console.log('tot------------' + tot);
                    console.log('totdayCount------------' + totdayCount);
                    console.log('ajaxroundcount------------' + ajaxroundcount);
                    if (a == tot - 1 && totdayCount == ajaxroundcount) {
                        toastr.success('Completed');
                        //window.location.href = '/CalendarConfigurationList/';
                    }
                    return a++;

                }

            });
        }
        indiSlotSTime = indiSlotETime;
        //console.log('i vali-------' + a + 'totval-----------' + totslotcount);

        //if (a == (totslotcount - 1)) {

        //    redirect = 1;
        //    return redirect;
        //    console.log('redirect enter');
        //}

    }

}
//$("#FTime").on("change", function () {
//    debugger;
//    if ($('#ETime').val() > $('#FTime').val()) {
//        toastr.warning('Please set proper time...');
//    }
//})

$("#ETime").on("change", function () {
    debugger;
    var from_time = $('#FTime').val();
    from_time = timeconvert(from_time);
    var to_time = $('#ETime').val();
    to_time = timeconvert(to_time);
    if (to_time < from_time) {
        $('#PETime').show();
        $('#PETime').fadeOut(8000);
        $('#PETime').html('Enter valid To Time');
        $('#ETime').focus();
        $('#ETime').val('');
        toastr.warning('Please set proper time...');
        
    }
})
//commented bynandhini on 09/06/2022
//$('#SelService').change(function () {
//    var service_data = {
//        P_Dml_Indicator: "SLC",
//        master_service_id: $('#SelService').val()
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/Billing/Service_Master_Ins_upd_sel',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(service_data),
//        success: function (data) {
//            var data1 = JSON.parse(data);
//            if (data1.msg == "Success") {
//                debugger;
//                var data1 = data1.data[0];
//                console.log(data1);
//                $('#txtPatientTime').val(data1.per_patient_time);
//                var handle_hour = (parseFloat($('#txtPatientTime').val()) / 60);
//                var travelTime = moment($('#FTime').val(), ["hh:mm A"]).add(handle_hour, 'hours').format('hh:mm A');
//                $('#ETime').val(travelTime);
//                //$('#ETime').timepicker('setTime', travelTime);

//                $('.counter_addon').hide();

//            }
//            else {
//                console.log(data1);
//            }
//        }
//    })
//})


$('#SelDoctor').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/Ipmanagement/DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "HDL", branch_id: $('#SelBranch').val() },
            success: function (data) {
                debugger;
                $('#Hdn_docid').val('');
                $('#Hdata_id').val('');
                // var data2 = JSON.parse(data);
                var data2 = data;
                response($.map(data2, function (item) {
                    return { label: item.doctorname, value: item.doctorname, id: item.doctorid, dataid: item.Doctoruserid };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#Hdn_docid').val(ui.item.id);
        $('#Hdata_id').val(ui.item.dataid);
      //  $('#CalendarConfiguration').empty();
      //  CalendarConfigurationList();
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});