
//Ready Function
$(document).ready(function () {
    $('.calendarlistaction').hide();
    $('.calendarlists_details').hide();
    $('.calendarshow').hide();
    $('.currentdate').text(formatDate(currentDate, { year: 'numeric', month: 'long', day: 'numeric' }));
    LoadBranchCalender();
})

//VariableDeclarations
var currentDate = new Date();
var branchid = '0';
var startTime = 8; // 8 A.M.
var endTime = 23;  // 8 P.M.
var interval = 30; // 30 minutes
var timeHeaderRowlength = '';
var headerRowLength = '';
var formattedDateForInput = formatDateForInput(currentDate);
//var activeTab = '';
var activeTab = 0;
//var startOfWeek = '';
var startOfWeek = new Date(currentDate);
var currentMonth = '';
var currentYear = '';
var startOfMonth = '';
var endOfMonth = '';
var filteredDetails = '';
let displayDate = '';
let openCollapses = [7];
var FilteredTypeDatalistName = [];
var checkedNames = [];
var hiddendoctorid=''
var checkedObject = {
    DoctorId: null,
    OtId: null,
    Schedule_Type: null,
    WardNo: null
};
function clearFilters() {
    checkedNames = [''];
    openCollapses = [7];
    if (activeTab) {
        LoadCalendar(activeTab);
    } else {
        LoadCalendar(0);
    }
}



//BranchOnchange
$('#selbranch').change(function () {
    debugger;
    if ($('#selbranch').val()) {
        $('.calendarshow').show();
        branchid = $('#selbranch').val()
        if (activeTab == 0) {
            LoadAccordion('Day', branchid, currentDate)
        }
        else if (activeTab == 1) {
            LoadAccordion('Week', branchid, currentDate)
        }
        else if (activeTab == 2) {
            LoadAccordion('Month', branchid, currentDate)
        }
    }

})

//ForamtCurrentDate
function formatDateForInput(date) {
    debugger;
    var year = date.getFullYear();
    var month = ('0' + (date.getMonth() + 1)).slice(-2);
    var day = ('0' + date.getDate()).slice(-2);
    return `${month}/${day}/${year}`;
}

//FormatTime
function formatTime(hour, minutes) {
    var ampm = hour >= 12 ? 'PM' : 'AM';
    hour = hour % 12;
    hour = hour ? hour : 12;
    var minutesStr = minutes < 10 ? '0' + minutes : minutes;
    return hour + ':' + minutesStr + ' ' + ampm;
}

function parseTimeString(timeStr) {
    debugger;
    let [time, modifier] = timeStr.split(' ');
    let [hours, minutes] = time.split(':');
    minutes = minutes || '00';

    if (modifier === 'PM' && hours !== '12') {
        hours = parseInt(hours, 10) + 12;
    } else if (modifier === 'AM' && hours === '12') {
        hours = '00';
    }

    let today = new Date();
    today.setHours(hours);
    today.setMinutes(minutes);
    today.setSeconds(0);
    today.setMilliseconds(0);
    return today;
}
// calculate the column span
function calculateColspan(startTimeStr, endTimeStr, intervalMinutes) {
    debugger;
    let startTime = parseTimeString(startTimeStr);
    let endTime = parseTimeString(endTimeStr);
    if (isNaN(startTime) || isNaN(endTime)) {
        console.error('Invalid Date:', startTimeStr, endTimeStr);
        return 0;
    }
    let timeDifferenceInMinutes = (endTime - startTime) / (1000 * 60);
    let colspan = timeDifferenceInMinutes / intervalMinutes;

    return colspan;
}


//Helper function to parse time in HH:MM AM/PM format
function parseTime(time) {
    var parts = time.match(/(\d+):(\d+)\s*(AM|PM)/i);
    var hours = parseInt(parts[1], 10);
    var minutes = parseInt(parts[2], 10);
    var ampm = parts[3].toUpperCase();

    if (ampm === 'PM' && hours < 12) {
        hours += 12;
    } else if (ampm === 'AM' && hours === 12) {
        hours = 0;
    }

    return new Date(0, 0, 0, hours, minutes, 0, 0);
}

//LoadingBranch
function LoadBranchCalender() {
    debugger;
    $('#selbranch').val('');
    var subdepartment = {
        Dml_Indicator: "LBRAN",
        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) {
            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">--Select--</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').attr('disabled', true);
                        $('#selbranch').append(SubDepartment);
                        $('.calendarshow').show();
                        LoadAccordion('Day', $('#selbranch').val(), currentDate);
                    }
                    else {
                        $('#selbranch').append(default_opt + SubDepartment);
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

// Tabonclickfunction
function LoadCalendar(tab) {
    activeTab = tab;
    console.log(activeTab);
    branchid = $('#selbranch').val();

    if (tab == 1) {
        startOfWeek = new Date(currentDate);
        // startOfWeek.setDate(startOfWeek.getDate() - startOfWeek.getDay());
    }

    updateDisplayDate();

    switch (tab) {
        case 0:
            LoadAccordion('Day', branchid, currentDate);
            break;
        case 1:
            LoadAccordion('Week', branchid, currentDate);
            break;
        case 2:
            LoadAccordion('Month', branchid, currentDate);
            break;
        default:
            console.error("Invalid tab number");
    }
}

//LoadAccordion
function LoadAccordion(calendartype, branchid, currentDate) {
    debugger;
    getHeaderRows(calendartype);
    let typelistdata = {
        DmlIndicator: "OTSTM"
    };
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/CalendarScheduleView',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(typelistdata),
        success: function (data) {
            debugger;
            var accordiontypes = JSON.parse(data).data.Table;
            var overalldatacollapse_row = "";
            const dateObject = new Date(currentDate);
            const formattedDateForInput = formatDateForInput(dateObject);
            let accordioncountdata = {
                DmlIndicator: "CDCOUNT",
                fromDate: formattedDateForInput,
                UserId: $('#hiddenUser_id').val(),
                HospitalId: $('#HospitalIdInt').val(),
                BranchId: branchid,
                calender_type: calendartype
            };


            $.ajax({
                async: true,
                type: 'POST',
                url: '/Calender/CalendarDayView',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(accordioncountdata),
                success: function (data) {
                    debugger;
                    var accordioncountlist = JSON.parse(data).data.Table;
                    console.log(accordioncountlist)

                   
                    // Initialize scheduleCounts with current counts from accordioncountlist
                    let scheduleCounts = {};
                    accordioncountlist.forEach(schedule => {
                        scheduleCounts[schedule.ScheduleType] = {
                            currentCount: schedule.Currentcount,
                            totalCount: schedule.Totalcount
                        };
                    });

                    // Update the current counts based on checkedNames if not empty
                    if (checkedNames.length > 0) {
                        // Reset the current counts for the Schedule_Type present in checkedNames
                        checkedNames.forEach(checkedName => {
                            let scheduleType = checkedName.Schedule_Type;
                            if (scheduleCounts.hasOwnProperty(scheduleType)) {
                                scheduleCounts[scheduleType].currentCount = 0;
                            }
                        });

                        // Increment the counts based on checkedNames
                        checkedNames.forEach(checkedName => {
                            let scheduleType = checkedName.Schedule_Type;
                            if (scheduleCounts.hasOwnProperty(scheduleType)) {
                                scheduleCounts[scheduleType].currentCount++;
                            }
                        });
                    }

            var popupdatatarget = '', popupid = '', popupdataheading = '', popuptitle = '';
            var popupDataMap = {
                1: { datatarget: '#otcreationpop', id: 'otpop', dataheading: '', title: '' },
                2: { datatarget: '#bookingpop', id: '', dataheading: 'daycare', title: 'Book a Day Care Schedule' },
                3: { datatarget: '#bookingpop', id: '', dataheading: 'massage', title: 'Book a Therapy Schedule' },
                4: { datatarget: '#bookingpop', id: '', dataheading: 'Technician', title: 'Book a Technician Schedule' },
                5: { datatarget: '#nursepop', id: 'nurse_addnew', dataheading: 'Nurse', title: '' },
                6: { datatarget: '#wardpop', id: 'ward_addnew', dataheading: 'Ward', title: '' },
                7: { datatarget: '#', id: '', dataheading: '', title: '' }
            };
            for (var i = 0; i < accordiontypes.length; i++) {
               
                var schId = accordiontypes[i].SchId;
                var currentCount = 0;
                var totalCount = 0;

                // Find the corresponding schedule in accordioncountlist
                let schedule = accordioncountlist.find(item => item.ScheduleId == schId);
                if (schedule) {
                    let scheduleType = schedule.ScheduleType;
                    currentCount = scheduleCounts[scheduleType].currentCount;
                    totalCount = scheduleCounts[scheduleType].totalCount;
                }

                //Add Id and target for open add new popup
                if (popupDataMap.hasOwnProperty(schId)) {
                    popupdatatarget = popupDataMap[schId].datatarget;
                    popupid = popupDataMap[schId].id;
                    popupdataheading = popupDataMap[schId].dataheading;
                    popuptitle = popupDataMap[schId].title;
                }
                let hiddenRoleId = $('#hiddenRole_id').val();
                if ((hiddenRoleId == "1" && schId == 7) || (hiddenRoleId == "19" && schId == 4) || hiddenRoleId != "1") {
                    var datatoggle_row = '<tr><td class="typetd" ><div><div class="opencollapseclick" data-toggle="collapse"  data-schId="' + accordiontypes[i].SchId + '" data-target="#row_' + calendartype + '' + accordiontypes[i].SchId + '"  onclick="opencollapselist(' + accordiontypes[i].SchId + ', ' + branchid + ', \'' + currentDate + '\',\'' + calendartype + '\', \'' + hiddendoctorid + '\')"><i class="fa fa-angle-double-up arrow-icon rotate-calarrow"></i><a>' + accordiontypes[i].ScheduleName + '</a></div><div><span>' + currentCount + '/' + totalCount + '</span><span class="typeaddnew" data-toggle="modal" data-target="' + popupdatatarget + '" data-heading="' + popupdataheading + '" id="' + popupid +'"><i class="fa fa-plus"></i></span></div></div></td><td colspan="' + headerRowLength + '"></td></tr>';
                var datacollapse_row = '<tr class="collapse" id="row_' + calendartype + '' + accordiontypes[i].SchId + '"><td colspan="' + (headerRowLength) + '"><table class="new_calendar newcalendar_subtable"><tbody id="subtable_' + calendartype + '' + accordiontypes[i].SchId + '"></tbody></table></td></tr>';
                overalldatacollapse_row += datatoggle_row + datacollapse_row;
                }
            }
            if (calendartype == 'Day') {
                $('#daywisetable_tbody').html(overalldatacollapse_row);
            } else if (calendartype == 'Week') {
                $('#weekwisetable_tbody').html(overalldatacollapse_row);
            } else if (calendartype == 'Month') {
                $('#monthwisetable_tbody').html(overalldatacollapse_row);
                    }
                    
            for (let i = 0; i < openCollapses.length; i++) {
                opencollapselist(openCollapses[i], branchid, currentDate, calendartype, hiddendoctorid);
                $('#row_' + calendartype + '' + openCollapses[i] + '').collapse('show');
            }
                }
            });

        }
    });
}

function opencollapselist(SchId, branchid, currentDate, calendartype, hiddendoctorid) {
   
    switch (calendartype) {
        case 'Day':
            opentypelist(SchId, branchid, currentDate, calendartype, hiddendoctorid);
            break;
        case 'Week':
            opentypelistweekwise(SchId, branchid, currentDate, calendartype, hiddendoctorid);
            break;
        case 'Month':
            opentypelistmonthwise(SchId, branchid, currentDate, calendartype, hiddendoctorid);
            break;
        default:
            console.error("Invalid calandar Type");
    }
}

function formatDate(date, options) {
    return date.toLocaleDateString('en-US', options);
}
// Function to get header rows based on the calendar type
function getHeaderRows(calendartype) {
    debugger;
    var headerRow;
    if (calendartype == 'Day') {
        headerRow = $('#daywisetable_header');
        headerRow.empty();
        headerRow.append('<th>Type</th>');
        for (var hour = startTime; hour <= endTime; hour++) {
            for (var minutes = 0; minutes < 60; minutes += interval) {
                if (hour === endTime && minutes > 0) break;
                var time = formatTime(hour, minutes);
                headerRow.append('<th>' + time + '</th>');
            }
        }
    } else if (calendartype == 'Week') {
        headerRow = $('#weekwisetable_header');
        headerRow.empty();
        headerRow.append('<th>Type</th>');
        debugger;
        //currentDate = new Date();
        // startOfWeek = new Date(currentDate);
        startOfWeek.setDate(currentDate.getDate() - currentDate.getDay());
        for (var i = 0; i < 7; i++) {
            var currentDay = new Date(startOfWeek);
            currentDay.setDate(startOfWeek.getDate() + i);
            headerRow.append('<th>' + formatDate(currentDay, { weekday: 'short', day: 'numeric' }) + '</th>');
        }
    } else if (calendartype == 'Month') {
        headerRow = $('#monthwisetable_header');
        headerRow.empty();
        headerRow.append('<th>Type</th>');
        debugger;
        //currentDate = new Date();
        currentMonth = currentDate.getMonth();
        currentYear = currentDate.getFullYear();
        startOfMonth = new Date(currentYear, currentMonth, 1);
        endOfMonth = new Date(currentYear, currentMonth + 1, 0);
        for (var date = new Date(startOfMonth); date <= endOfMonth; date.setDate(date.getDate() + 1)) {
            headerRow.append('<th>' + formatDate(date, { weekday: 'short', day: 'numeric' }) + '</th>');
        }
    }
    headerRowLength = headerRow.find('th').length;
}


/// Daywise typelist function
function opentypelist(SchId, branchid, currentDate, calendartype, hiddendoctorid) {
    const dateObject = new Date(currentDate);
    if (isNaN(dateObject)) {
        console.error("Invalid date:", currentDate);
        return;
    }
    const formattedDateForInput = formatDateForInput(dateObject);
    // const formattedDateForInput = formatDateForInput(currentDate);
    var filterkey = '';
    var sheduletypelist = checkedNames.filter((item) => item.Schedule_Type == SchId.toString());
    if (SchId == 7) {
        filterkey = sheduletypelist.map(item => item.DoctorId).filter(id => id !== 0).join(',');
        if (hiddendoctorid) {
            filterkey = [filterkey, hiddendoctorid].join(',');
            hiddendoctorid = '';
        }
       
    } else {
        filterkey = sheduletypelist.map(item => item.WardNo).filter(id => id !== 0).join(',');
    }
    let OTdata = {
        DmlIndicator: "CDVD",
        ScheduleType: SchId,
        fromDate: formattedDateForInput,
        //: "03/31/2024",
        UserId: $('#hiddenUser_id').val(),
        HospitalId: $('#HospitalIdInt').val(),
        BranchId: branchid,
        Id: filterkey
    };
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/CalendarDayView',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(OTdata),
        success: function (data) {
            
            var scheduleDetails = JSON.parse(data).data.Table;
            if (scheduleDetails) {
                var tbody = $('#subtable_' + calendartype + SchId);
                tbody.empty();
                var timeHeaderRowlength = $('#daywisetable_header th').length - 1;
                if ($('#hiddenRole_id').val() == "2") {
                    var dayviewlistfilterrow = '';
                    if (SchId == 7) {
                        dayviewlistfilterrow = '<tr><td><div class="typeliaddsearch"><div><span class="mar0"><input id="doctorsearch_' + calendartype + '" type="checkbox"></span><input type="text"  class="forms_field ui-autocomplete-input search-input calendarsearchfield" name="text" id="searchtype_' + SchId + '' + calendartype + '" placeholder="Search" autocomplete="off"><input type="text"  class="forms_field ui-autocomplete-input search-input calendarsearchfield hideadd" name="text" id="autosearchtype_' + SchId + '' + calendartype + '" placeholder="Search" autocomplete="off"><span id="addButton_' + calendartype +'" class="hideadd"><i class="fa fa-plus"></i></span></div></div></td><td colspan="' + timeHeaderRowlength + '"></td></tr>';
                    } else {
                        dayviewlistfilterrow = '<tr><td><div class="typeliaddsearch"><div><input type="text"  class="forms_field ui-autocomplete-input search-input calendarsearchfield" name="text" id="searchtype_' + SchId + '' + calendartype + '" placeholder="Search" autocomplete="off"></div></div></td><td colspan="' + timeHeaderRowlength + '"></td></tr>';
                    }
                    tbody.append(dayviewlistfilterrow);
                }

                 
                var rowMap = {};
                var i = 0;
                scheduleDetails.forEach(item => {
                   
                    if (!rowMap[item.Type_DatalistName]) {
                        var row = $('<tr class="uisortabletable"></tr>');
                        row.append('<td data-doctorid="' + item.DoctorId + '" data-sheduletype="' + item.Schedule_Type + '" data-wardno="' + item.WardNo + '"> <div class="typelisttd"><div> <i class="fas fa-grip-vertical"></i> <input id="dayviewlistcheck' + i + '" type="checkbox" checked class="clearcheckbox" /></div><div><label for="dayviewlistcheck' + i + '" title="' + item.Type_DatalistName + '">' + item.Type_DatalistName + '</label></div></div></td>');
                        i++;
                        for (var hour = startTime; hour <= endTime; hour++) {
                            for (var minutes = 0; minutes < 60; minutes += interval) {
                                if (hour === endTime && minutes > 0) break;
                                row.append('<td></td>');
                            }
                        }
                        rowMap[item.Type_DatalistName] = row;
                        tbody.append(row);
                    }

                    PushCheckedObjToArry(item);  //Push the  checked Object into an Array 
                    if (item.ScheduleDate) {
                    var row = rowMap[item.Type_DatalistName];
                    var timeSlots = $('#daywisetable_header th');
                    console.log(timeSlots);

                    //get previous time slot index 
                    var indexSlot = [];
                    let scheduleStart = parseTimeString(item.ScheduleFromTime1);
                    let scheduleEnd = parseTimeString(item.ScheduleToTime1);

                    timeSlots.each(function (index, timeSlot) {
                        if (index === 0) return;
                        let timeSlotText = $(timeSlot).text();
                        let timeSlotStart = parseTimeString(timeSlotText);

                        if (timeSlotStart <= scheduleStart) {
                            indexSlot.push(timeSlotText);
                        }
                    });

                    //Start time margin calculation
                    let lastIndex = indexSlot.length - 1;
                    let lastTime = indexSlot[lastIndex];
                    var marginstart = (parseTimeString(lastTime).getTime() - scheduleStart.getTime());
                    marginstart = Math.abs(marginstart / (1000 * 60)) * 2

                    let intervalMinutes = 30;
                    let index = indexSlot.length;

                    var colspan = calculateColspan(item.ScheduleFromTime1, item.ScheduleToTime1, intervalMinutes);
                    var cell = row.find('td').eq(index);
                        var divElement = $('<div style="width:' + colspan * 100 + 'px;omargin-left:' + marginstart + 'px" data-title="' + item.Schedule_TypeName + '" class="eventlist popover-btn" data-content-id="popover-content-' + item.OtId + '" data-otid="' + item.OtId + '" data-schedulefromtime="' + item.ScheduleFromTime1 + '" data-scheduletotime="' + item.ScheduleToTime1 + '" data-patientid="' + item.Patient_Id + '" data-patientname="' + item.PatientName + '" data-scheduletype="' + item.Schedule_Type + '" data-scheduledate="' + item.ScheduleDate + '" data-totimeformatted="' + item.ScheduleToTime + '" data-branchid="' + item.Branch_id + '" data-appointmenttype="' + item.Appointment_type + '" onclick="initializePopovers()"> ' + item.ServiceType + '</div>');
                    cell.append(divElement);
                    }
                    });

                if (SchId == 7) {
                    $('#doctorsearch_' + calendartype).on('change', function () {
                        const isChecked = $(this).is(':checked');
                        const addIcon = $('#addButton_' + calendartype + '');
                        const autosearch = $('#autosearchtype_' + SchId + '' + calendartype + '');
                        const localsearch = $('#searchtype_' + SchId + '' + calendartype + '');
                        if (isChecked) {
                            addIcon.removeClass('hideadd');
                            autosearch.removeClass('hideadd');
                            localsearch.addClass('hideadd');
                            CalendarAutoCompleteSearch(SchId, calendartype, currentDate, branchid); //For CalendarAutoCompleteSearch
                        } else {
                            addIcon.addClass('hideadd');
                            autosearch.addClass('hideadd');
                            localsearch.removeClass('hideadd');
                            CalendarLocalSearch(SchId, calendartype); //For CalendarLocalSearch
                        }
                    })
                } 
                CalendarLocalSearch(SchId, calendartype); //For CalendarLocalSearch

            } else {
               
                $('#row_' + calendartype + '' + SchId + '').collapse('hide');
            }

        }

    });

}

/// showing popovers and edit click open popup
function initializePopovers() {
    debugger;
    $('.popover-btn').each(function () {
        if (!$(this).data('popover-initialized')) {
            $(this).popover({
                html: true,
                trigger: 'manual',
                content: function () {
                    debugger;
                    var dynamiccontent = '';
                    var $this = $(this);
                    var otId = $this.data('otid');
                    var scheduleFromTime = $this.data('schedulefromtime');
                    var scheduleToTime = $this.data('scheduletotime');
                    var totimeformatted = $this.data('totimeformatted');
                    var PatientId = $this.data('patientid');
                    var PatientName = $this.data('patientname');
                    var scheduletype = $this.data('scheduletype');
                    var scheduledate = $this.data('scheduledate');
                    var datatitle = $this.data('title');
                    var databranchid = $this.data('branchid');
                    var dataapptype = $this.data('appointmenttype');
                    var appedit = '';
                    appedit = "'" + PatientId + "','" + PatientName + "'," + otId + ',' + databranchid + ',' + dataapptype;
                    // Parse the scheduledate and scheduleToTime
                    var [day, month, year] = scheduledate.split('/');
                    var [hours, minutes] = totimeformatted.split(':');
                    hours = parseInt(hours);
                    minutes = parseInt(minutes);

                    var scheduleDateTime = new Date(year, month - 1, day, hours, minutes);

                    var currentDate = new Date();

                    // Check if the scheduled date and time are greater than or equal to the current date and time
                    var isFutureDateTime = scheduleDateTime >= currentDate;

                    var editFunction, deleteFunction, modalTarget, modalTitle;
                    if (scheduletype == 1) {
                        editFunction = 'OTEdit';
                        deleteFunction = 'OTDelete';
                        modalTarget = '#otcreationpop';
                    } else if (scheduletype == 2) {
                        editFunction = 'DCEdit';
                        deleteFunction = 'DCDelete';
                        modalTarget = '#bookingpop';
                        modalTitle = 'Book a Day Care Schedule';
                    } else if (scheduletype == 3) {
                        editFunction = 'MEdit';
                        deleteFunction = 'MDelete';
                        modalTarget = '#bookingpop';
                        modalTitle = 'Book a Therapy Schedule';
                    } else if (scheduletype == 4) {
                        editFunction = 'TechnicianEdit';
                        deleteFunction = 'TechnicianDelete';
                        modalTarget = '#bookingpop';
                        modalTitle = 'Book a Technician Schedule';
                    } else if (scheduletype == 7 && datatitle == 'Appointment Booking') {
                        editFunction = 'AppointmentEdit';
                        deleteFunction = 'AppointmentDelete';
                    } else {
                        editFunction = 'OTEdit';
                        deleteFunction = 'OTDelete';
                        modalTarget = '#otcreationpop';
                    }
                    $(modalTarget + ' .modal-title').text(modalTitle);
                    dynamiccontent = '<div id="popover-content-' + otId + '" class="daywise_popovercontent">'
                        + '<p><span>OT ID:</span> ' + otId + '</p>'
                        + '<p><span>Patient Name:</span> ' + PatientName + '</p>'
                        + '<p><span>Patient ID: </span>' + PatientId + '</p>'
                        + '<p><span>Schedule:</span> ' + scheduleFromTime + ' - ' + scheduleToTime + '</p>'
                        + (isFutureDateTime ?
                            (scheduletype == 7 && datatitle == 'Appointment Booking' ?
                             '<button class="cal_edit hideaction" id="edit_' + otId + '" onclick="' + editFunction + '(' + appedit + ')"><i class="fa fa-pencil"></i> Edit</button>'
                                :
                                '<button class="cal_delete hideaction" id="delete_' + otId + '" onclick="' + deleteFunction + '(' + otId + ')"><i class="fa fa-trash-o"></i> Delete</button>'
                                + '<button class="cal_edit hideaction" id="edit_' + otId + '" onclick="' + editFunction + '(' + otId + ')" data-toggle="modal" data-target="' + modalTarget + '"><i class="fa fa-pencil"></i> Edit</button>'
                            )
                            : '')
                        + '</div>';
                    return dynamiccontent;
                }
            });

            $(this).data('popover-initialized', true);

            $(this).on('click', function (e) {
                $('.popover-btn').not(this).popover('hide');
                $(this).popover('toggle');
                e.stopPropagation();
            });
        }
    });

    $(document).on('click', function (e) {
        if (!$(e.target).closest('.popover').length && !$(e.target).closest('.popover-btn').length) {
            $('.popover-btn').popover('hide');
        }
    });
}


function AppointmentEdit(PatientId, PatientName, otId, databranchid, dataapptype) {

    //const url = `/DirectPatientEnroll?patient_id=${PatientId}&PName=${PatientName}&slotId=${otId}&BId=${databranchid}&r_type=${dataapptype}&showDiv1='false'&showDiv2='true'`;
    const url = `/DirectPatientEnroll/AppointmentSlot?patient_id=${PatientId}&PName=${PatientName}&slotId=${otId}&BId=${databranchid}&r_type=${dataapptype}`;
    window.location.href = url;
}



function opentypelistweekwise(SchId, branchid, currentDate, calendartype, hiddendoctorid) {

    const dateObject = new Date(currentDate);
    const formattedDateForInput = formatDateForInput(dateObject);
    var filterkey = '';
    var sheduletypelist = checkedNames.filter((item) => item.Schedule_Type == SchId.toString());
    if (SchId == 7) {
        filterkey = sheduletypelist.map(item => item.DoctorId).filter(id => id !== 0).join(',');
        if (hiddendoctorid) {
            filterkey = [filterkey, hiddendoctorid].join(',');
            hiddendoctorid = '';
        }
    } else {
        filterkey = sheduletypelist.map(item => item.WardNo).filter(id => id !== 0).join(',');
    }
    console.log(startOfWeek);
    let OTWeekdata = {
        DmlIndicator: "CDVW",
        ScheduleType: SchId,
        fromDate: formattedDateForInput,
        /* fromDate: '07/19/2024',*/
        UserId: $('#hiddenUser_id').val(),
        HospitalId: $('#HospitalIdInt').val(),
        BranchId: branchid,
        Id: filterkey
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/CalendarWeekView',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(OTWeekdata),
        success: function (data) {
           
            var weekDataList = JSON.parse(data).data.Table;
            if (weekDataList) {
                var tbody = $('#subtable_' + calendartype + '' + SchId);
                var dayviewlistrow = "";
                const arraylist = {};
                tbody.empty();
                var timeHeaderRowlength = $('#weekwisetable_header th').length - 1;
                if ($('#hiddenRole_id').val() == "2") {
                    var weekviewlistfilterrow = '';
                    if (SchId == 7) {
                        weekviewlistfilterrow = '<tr><td><div class="typeliaddsearch"><div><span class="mar0"><input id="doctorsearch_' + calendartype + '" type="checkbox"></span><input type="text"  class="forms_field ui-autocomplete-input search-input calendarsearchfield" name="text" id="searchtype_' + SchId + '' + calendartype + '" placeholder="Search" autocomplete="off"><input type="text"  class="forms_field ui-autocomplete-input search-input calendarsearchfield hideadd" name="text" id="autosearchtype_' + SchId + '' + calendartype + '" placeholder="Search" autocomplete="off"><span id="addButton_' + calendartype + '" class="hideadd"><i class="fa fa-plus"></i></span></div></div></td><td colspan="' + timeHeaderRowlength + '"></td></tr>';
                    } else {
                        weekviewlistfilterrow = '<tr><td><div class="typeliaddsearch"><div><input type="text"  class="forms_field ui-autocomplete-input search-input calendarsearchfield" name="text" id="searchtype_' + SchId + '' + calendartype + '" placeholder="Search" autocomplete="off"></div></div></td><td colspan="' + timeHeaderRowlength + '"></td></tr>';
                    }
                    tbody.append(weekviewlistfilterrow);
                }
                //var weekviewlistfilterrow = '<tr><td><div class="typeliaddsearch"><a class="hideadd">Add</a><div><input type="text" class="forms_field ui-autocomplete-input search-input calendarsearchfield" name="text" id="searchtype_' + SchId + '' + calendartype + '" placeholder="Search" autocomplete="off"></div></div></td><td colspan="' + timeHeaderRowlength + '"></td></tr>';
                //tbody.append(weekviewlistfilterrow);

                var i = 0;
                weekDataList.forEach(item => {
                    if (!arraylist[item.Type_DatalistName]) {
                        var row = $('<tr class="uisortabletable"></tr>');
                        row.append('<td data-doctorid="' + item.DoctorId + '" data-sheduletype="' + item.Schedule_Type + '" data-wardno="' + item.WardNo + '"> <div class="typelisttd"><div> <i class="fas fa-grip-vertical"></i> <input id="weekviewlistcheck' + i + '" type="checkbox" checked class="clearcheckbox" /></div><div><label for="weekviewlistcheck' + i + '" title="' + item.Type_DatalistName + '">' + item.Type_DatalistName + '</label></div></div></td>');
                        i++;
                        for (var j = 0; j < 7; j++) {
                            row.append('<td></td>');
                        }
                        arraylist[item.Type_DatalistName] = row;
                        tbody.append(row);
                    }
                    PushCheckedObjToArry(item);  //Push the  checked Object into an Array 
                    if (item.ScheduleDay) {
                        var row = arraylist[item.Type_DatalistName];
                        var dayIndex = getDayIndex(item.ScheduleDay);
                        var cell = $(row).find('td').eq(dayIndex + 1);
                        var displayName;
                        //var openparameters = `'${item.Schedule_Type}', ${item.ScheduleDay}, '${item.Type_DatalistName}'`;
                        var openparameters = `'${item.Schedule_Type}', '${item.ScheduleDay}', '${item.Type_DatalistName}'`;
                        if (item.ScheduleCount > 1) {
                            displayName = ' <div class="cursorclass" onclick="opendetailssidebar(' + openparameters + ')"><p>' + item.ServiceType + ' <span  class="new_badge">' + item.ScheduleCount + '</span></p></div>';
                        } else {
                            displayName = ' <div class="cursorclass" onclick="opendetailssidebar(' + openparameters + ')"><p>' + item.ServiceType + '</p></div>';
                        }
                        cell.html(displayName);
                    }
                });
                if (SchId == 7) {
                    $('#doctorsearch_' + calendartype).on('change', function () {
                        const isChecked = $(this).is(':checked');
                        const addIcon = $('#addButton_' + calendartype + '');
                        const autosearch = $('#autosearchtype_' + SchId + '' + calendartype + '');
                        const localsearch = $('#searchtype_' + SchId + '' + calendartype + '');
                        if (isChecked) {
                            addIcon.removeClass('hideadd');
                            autosearch.removeClass('hideadd');
                            localsearch.addClass('hideadd');
                            CalendarAutoCompleteSearch(SchId, calendartype, currentDate); //For CalendarAutoCompleteSearch
                        } else {
                            addIcon.addClass('hideadd');
                            autosearch.addClass('hideadd');
                            localsearch.removeClass('hideadd');
                            CalendarLocalSearch(SchId, calendartype); //For CalendarLocalSearch
                        }
                    })
                }
                CalendarLocalSearch(SchId, calendartype); //For CalendarLocalSearch
                console.log(arraylist);
            } else {
                 
                $('#row_' + calendartype + '' + SchId + '').collapse('hide');
            }
        },
        error: function (error) {
            console.error('Error fetching week data:', error);
        }
    });
}

function getDayIndex(dateString) {
    var date = new Date(dateString);
    var day = date.getDay();
    return day;
}


function opentypelistmonthwise(SchId, branchid, currentDate, calendartype, hiddendoctorid) {

    const dateObject = new Date(currentDate);
    const formattedDateForInput = formatDateForInput(dateObject);
    debugger;
    var filterkey = '';
    var sheduletypelist = checkedNames.filter((item) => item.Schedule_Type == SchId.toString());
    if (SchId == 7) {
        filterkey = sheduletypelist.map(item => item.DoctorId).filter(id => id !== 0).join(',');
        if (hiddendoctorid) {
            filterkey = [filterkey, hiddendoctorid].join(',');
            hiddendoctorid = '';
        }
    } else {
        filterkey = sheduletypelist.map(item => item.WardNo).filter(id => id !== 0).join(',');
    }
    let OTMonthData = {
        DmlIndicator: "CDVM",
        ScheduleType: SchId,
        fromDate: formattedDateForInput,
        UserId: $('#hiddenUser_id').val(),
        HospitalId: $('#HospitalIdInt').val(),
        BranchId: branchid,
        Id: filterkey
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/CalendarMonthView',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(OTMonthData),
        success: function (data) {

            var monthDataList = JSON.parse(data).data.Table;
            if (monthDataList) {
                var tbody = $('#subtable_' + calendartype + '' + SchId);
                tbody.empty();
                tbody.empty();
                var arraylists = {};
               
                var timeHeaderRowLength = $('#monthwisetable_header th').length - 1;
                if ($('#hiddenRole_id').val() == "2") {
                    var monthViewListFilterRow = '';
                    if (SchId == 7) {
                        monthViewListFilterRow = '<tr><td><div class="typeliaddsearch"><div><span class="mar0"><input id="doctorsearch_' + calendartype + '" type="checkbox"></span><input type="text"  class="forms_field ui-autocomplete-input search-input calendarsearchfield" name="text" id="searchtype_' + SchId + '' + calendartype + '" placeholder="Search" autocomplete="off"><input type="text"  class="forms_field ui-autocomplete-input search-input calendarsearchfield hideadd" name="text" id="autosearchtype_' + SchId + '' + calendartype + '" placeholder="Search" autocomplete="off"><span id="addButton_' + calendartype + '" class="hideadd"><i class="fa fa-plus"></i></span></div></div></td><td colspan="' + timeHeaderRowLength + '"></td></tr>';
                    } else {
                        monthViewListFilterRow = '<tr><td><div class="typeliaddsearch"><div><input type="text"  class="forms_field ui-autocomplete-input search-input calendarsearchfield" name="text" id="searchtype_' + SchId + '' + calendartype + '" placeholder="Search" autocomplete="off"></div></div></td><td colspan="' + timeHeaderRowLength + '"></td></tr>';
                    }
                    tbody.append(monthViewListFilterRow);
                }
               //var monthViewListFilterRow = '<tr><td><div class="typeliaddsearch"><a class="hideadd">Add</a><div><input type="text" class="forms_field ui-autocomplete-input search-input calendarsearchfield" name="text" id="searchtype_' + SchId + '' + calendartype + '" placeholder="Search" autocomplete="off"></div></div></td><td colspan="' + timeHeaderRowLength + '"></td></tr>';
                //tbody.append(monthViewListFilterRow);

                var i = 0;
                monthDataList.forEach(item => {
                    if (!arraylists[item.Type_DatalistName]) {
                        var row = $('<tr class="uisortabletable"></tr>');
                        row.append('<td data-doctorid="' + item.DoctorId + '" data-sheduletype="' + item.Schedule_Type + '" data-wardno="' + item.WardNo + '"> <div class="typelisttd"><div> <i class="fas fa-grip-vertical"></i> <input id="monthviewlistcheck' + i + '" type="checkbox" checked class="clearcheckbox" /></div><div><label for="monthviewlistcheck' + i + '" title="' + item.Type_DatalistName + '">' + item.Type_DatalistName + '</label></div></div></td>');
                        i++;
                        for (var j = 0; j < timeHeaderRowLength; j++) {
                            row.append('<td></td>');
                        }
                        arraylists[item.Type_DatalistName] = row;
                        tbody.append(row);
                    }
                    PushCheckedObjToArry(item);  //Push the  checked Object into an Array 
                    if (item.ScheduleDay) {
                        var openparameters = `'${item.Schedule_Type}', '${item.ScheduleDay}', '${item.Type_DatalistName}'`;

                        var row = arraylists[item.Type_DatalistName];
                        var dayIndex = new Date(item.ScheduleDay).getDate();
                        var cell = $(row).find('td').eq(dayIndex);
                        cell.html(`<span class="new_badge cursorclass" onclick="opendetailssidebar(${openparameters})">${item.ScheduleCount}</span>`);
                    }
                    });
                if (SchId == 7) {
                    $('#doctorsearch_' + calendartype).on('change', function () {
                        const isChecked = $(this).is(':checked');
                        const addIcon = $('#addButton_' + calendartype + '');
                        const autosearch = $('#autosearchtype_' + SchId + '' + calendartype + '');
                        const localsearch = $('#searchtype_' + SchId + '' + calendartype + '');
                        if (isChecked) {
                            addIcon.removeClass('hideadd');
                            autosearch.removeClass('hideadd');
                            localsearch.addClass('hideadd');
                            CalendarAutoCompleteSearch(SchId, calendartype, currentDate); //For CalendarAutoCompleteSearch
                        } else {
                            addIcon.addClass('hideadd');
                            autosearch.addClass('hideadd');
                            localsearch.removeClass('hideadd');
                            CalendarLocalSearch(SchId, calendartype); //For CalendarLocalSearch
                        }
                    })
                }
                CalendarLocalSearch(SchId, calendartype); //For CalendarLocalSearch
                console.log(arraylists);
            } else {
                
                $('#row_' + calendartype + '' + SchId + '').collapse('hide');
            }

        },
        error: function (error) {
            console.error('Error fetching month data:', error);
        }
    });
}

//PreviousButtonClick
function previousday() {
    debugger;

    if (activeTab == 0) {
        calendartype = 'Day';
        currentDate.setDate(currentDate.getDate() - 1);
    } else if (activeTab == 1) {
        calendartype = 'Week';
        currentDate.setDate(currentDate.getDate() - 7);
        startOfWeek = new Date(currentDate);
        // startOfWeek.setDate(startOfWeek.getDate() - startOfWeek.getDay());
    } else if (activeTab == 2) {
        calendartype = 'Month';
        currentDate.setMonth(currentDate.getMonth() - 1);
    }
    updateDisplayDate();
    LoadAccordion(calendartype, $('#selbranch').val(), currentDate);
}

//NextButtonClick
function nextday() {
    debugger;

    if (activeTab == 0) {
        calendartype = 'Day';
        currentDate.setDate(currentDate.getDate() + 1);
    } else if (activeTab == 1) {
        calendartype = 'Week';
        currentDate.setDate(currentDate.getDate() + 7);
        startOfWeek = new Date(currentDate);
        // startOfWeek.setDate(startOfWeek.getDate() - startOfWeek.getDay());
    } else if (activeTab == 2) {
        calendartype = 'Month';
        currentDate.setMonth(currentDate.getMonth() + 1);
    }
    updateDisplayDate();
    LoadAccordion(calendartype, $('#selbranch').val(), currentDate);
}

//UpdateDisplayDate
function updateDisplayDate() {
    if (activeTab == 0) {
        displayDate = formatDate(currentDate, { year: 'numeric', month: 'long', day: 'numeric' });
    } else if (activeTab == 1) {
        displayDate = formatDate(startOfWeek, { year: 'numeric', month: 'long', day: 'numeric' });
    } else if (activeTab == 2) {
        displayDate = formatDate(currentDate, { year: 'numeric', month: 'long' });
    }
    $('.currentdate').text(displayDate);
}
//ConvertDateFormat
function convertDateFormat(dateString) {
    const date = new Date(dateString);
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const year = date.getFullYear();
    return `${month}/${day}/${year}`;
}

//For Open DetailsSidebar
function opendetailssidebar(sheduleid, fromdate, Type_DatalistName) {
    
    if (sheduleid && fromdate != 'null' && Type_DatalistName != '') {
        $('.calendarlistaction').toggle();
        $('.calendarlistaction').css('display', 'flex');
        const formattedDate = convertDateFormat(fromdate);

        let OTdata = {
            DmlIndicator: "CDVD",
            ScheduleType: sheduleid,
            fromDate: formattedDate,
            UserId: $('#hiddenUser_id').val(),
            HospitalId: $('#HospitalIdInt').val(),
            BranchId: branchid,
        };
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Calender/CalendarDayView',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(OTdata),
            success: function (data) {
                debugger;
                var details = JSON.parse(data).data.Table;
                
                //filteredDetails = details.filter(item => item.Type_DatalistName == Type_DatalistName);
                 filteredDetails = details.filter(item =>
                    item.Type_DatalistName.toLowerCase() === Type_DatalistName.toLowerCase()
                );
                console.log(filteredDetails);
                // Assuming you have a container element with class 'calendarlists'
                var calendarList = $('.calendarlists ul');
                calendarList.empty(); // Clear the current list
                if (filteredDetails.length >= 0) {
                    $('.currentdateinlist').text(filteredDetails[0].ScheduleDate);
                }
                filteredDetails.forEach((item, index) => {
                    var listItem = '<li class="openinnerdetailssider" onclick="openinnerdetailsider(' + item.OtId + ')">' +
                        '<span class="typebadge">' + item.Schedule_TypeName + '</span>' +
                        '<h4>' + item.PatientName + '</h4>' +
                        '<p><span>' + item.ScheduleDate + '</span><span class="mr-10 ml-10">' + item.ScheduleFromTime1 + '</span><span>' + item.ScheduleToTime1 + '</span></p>' +
                        '<p>' + item.Type_DatalistName + '</p>' +
                        '<p>' + item.PatientName + '</p>' +
                        '</li>';
                    calendarList.append(listItem);
                });
            }
        })
    }
}
//For Closing InnerDetailsSidebar
function openinnerdetailsider(otid) {
    debugger;
    $('.calendarlists_details').show();
    
    var filteredinnerDetails = filteredDetails.filter(item => item.OtId == otid);

    if (filteredinnerDetails.length > 0) {
        var details = filteredinnerDetails[0];
        var appedit = '';
        appedit = "'" + details.Patient_Id + "','" + details.PatientName + "'," + details.OtId + ',' + details.Branch_id + ',' + details.Appointment_type;
        // Parse the scheduledate and scheduleToTime
        var [day, month, year] = details.ScheduleDate.split('/');
        var [hours, minutes] = details.ScheduleToTime.split(':');
        hours = parseInt(hours);
        minutes = parseInt(minutes);

        var scheduleDateTime = new Date(year, month - 1, day, hours, minutes);

        var currentDate = new Date();

        // Check if the scheduled date and time are greater than or equal to the current date and time
        var isFutureDateTime = scheduleDateTime >= currentDate;

        var initials = getInitials(details.PatientName);
        
        var editFunction, deleteFunction, modalTarget, modalTitle;
        if (details.Schedule_Type == 1) {
            editFunction = 'OTEdit';
            deleteFunction = 'OTDelete';
            modalTarget = '#otcreationpop';

        } else if (details.Schedule_Type == 2) {
            editFunction = 'DCEdit';
            deleteFunction = 'DCDelete';
            modalTarget = '#bookingpop';
            modalTitle = 'Book a Day Care Schedule';
        } else if (details.Schedule_Type == 3) {
            editFunction = 'MEdit';
            deleteFunction = 'MDelete';
            modalTarget = '#bookingpop';
            modalTitle = 'Book a Therapy Schedule';

        } else if (details.Schedule_Type == 4) {
            editFunction = 'TechnicianEdit';
            deleteFunction = 'TechnicianDelete';
            modalTarget = '#bookingpop';
            modalTitle = 'Book a Technician Schedule';
        } else if (details.Schedule_Type == 7 && details.ServiceType == 'Appointment Booking') {
            editFunction = 'AppointmentEdit';
            deleteFunction = 'AppointmentDelete';
        }else {
            editFunction = '';
            deleteFunction = '';
            modalTarget = '';
        }
        $(modalTarget + ' .modal-title').text(modalTitle);
        // Common HTML structure
        var detailHtml = `
         ${isFutureDateTime ? `
    <div class="details_action">
        ${details.Schedule_Type == 7 && details.ServiceType == 'Appointment Booking' ? `
            <button id="edit_${otid}" onclick="${editFunction}(${appedit})">
                <i class="fa fa-pencil mr-5"></i>Edit
            </button>
        ` : `
            <button id="edit_${otid}" onclick="${editFunction}('${otid}')" data-toggle="modal" data-target="${modalTarget}">
                <i class="fa fa-pencil mr-5"></i>Edit
            </button>
            <button id="delete_${otid}" onclick="${deleteFunction}('${otid}')" data-toggle="modal" data-target="${modalTarget}">
                <i class="fa fa-trash-o mr-5"></i>Delete
            </button>
        `}
        <i class="fa fa-times closeinnerdetailsidebar" onclick="closeinnerdetailsidebar()"></i>
    </div>` : ''}
            <div>
                <p>${details.Branch_Name}/ <span>${details.OtId}</span></p>
                <div class="patnamebg">
                    <div class="patshortname">
                        <p>${initials}</p>
                    </div>
                    <div>
                        <p class="patid">${details.Patient_Id}</p>
                        <p class="patname">${details.PatientName}</p>
                    </div>
                </div>
                <div class="diseasebg">
                    <p class="diseasename">${details.Schedule_TypeName}</p> 
                    <p class="diseasename">${details.Type_DatalistName}</p> 
                    <p class="scheduledetails"><span>${details.ScheduleDate}</span><span class="mr-10 ml-10">${details.ScheduleFromTime1}</span><span>${details.ScheduleToTime1}</span></p>
                </div>
        `;

        // Conditional HTML based on Schedule_Type
        if (details.Schedule_Type == 1) {
            detailHtml += `
                <div class="doctorslist">
                    <div class="doctordiv">
                        <div>
                            <p class="patname">${details.Surgeon_Name}</p>
                            <p class="scheduledetails">Surgeon</p>
                        </div>
                        <div class="headdoctorbg">
                            <i class="fa fa-star"></i>
                        </div>
                    </div>
                    <div class="doctordiv">
                        <div>
                            <p class="patname">${details.AssistantSurgeon_Name}</p>
                            <p class="scheduledetails">Assistant Surgeon</p>
                        </div>
                    </div>
                    <div class="doctordiv">
                        <div>
                            <p class="patname">${details.Anaesthesian_Name}</p>
                            <p class="scheduledetails">Anaesthesian</p>
                        </div>
                    </div>
                </div>
                <div class="diagnosisdiv">
                    <p class="scheduledetails">Diagnosis</p>
                    <div class="diagnosisbg">
                        <p>${details.Diagnosis}</p>
                    </div>
                </div>
            `;
        } else {
            detailHtml += `
                <div class="doctorslist">
                    <div class="doctordiv">
                        <div>
                            <p class="patname">${details.Type_DatalistName}</p>
                            <p class="scheduledetails"></p>
                        </div>
                        <div class="headdoctorbg">
                            <i class="fa fa-star"></i>
                        </div>
                    </div>
                    <div class="doctordiv">
                        <div>
                            <p class="patname"></p>
                            <p class="scheduledetails"></p>
                        </div>
                    </div>
                </div>
            `;
        }

        detailHtml += `</div>`;

        // Insert the HTML into the .calendarlists_details div
        document.querySelector('.calendarlists_details').innerHTML = detailHtml;
    }
}

//GetInitial of the Name(FirstLetter)
function getInitials(name) {
    let initials = name.split(' ').map(part => part.charAt(0)).join('');
    if (initials.length > 2) {
        initials = initials.charAt(0) + initials.charAt(1);
    }
    return initials.toUpperCase();
}
//For Closing DetailsSidebar
$('.closedetailssidebar').click(function () {
    $('.calendarlistaction').toggle();
    $('.calendarlists_details').hide();
});
//For Closing InnerDetailsSidebar
function closeinnerdetailsidebar() {
    $('.calendarlists_details').hide();
}

$(document).off('change', '.clearcheckbox').on('change', '.clearcheckbox', function () {
    console.log('Checkbox changed:', this.checked);
    var tr = $(this).closest('tr');
    var doctorId = $(this).closest('td').data('doctorid');
    debugger;
    debugger;
    if (!this.checked) {
        // Remove the row if the checkbox is unchecked
        checkedNames = checkedNames.filter(obj => obj.DoctorId !== doctorId);
        //tr.remove();
        tr.addClass('hideuncheckrow');
    } else {
        tr.removeClass('hideuncheckrow');
    }
});

function PushCheckedObjToArry(item) {
    checkedObject.DoctorId = item.DoctorId ? item.DoctorId : 0;
    checkedObject.OtId = item.OtId ? item.OtId : 0;
    checkedObject.Schedule_Type = item.Schedule_Type ? item.Schedule_Type : 0;
    checkedObject.WardNo = item.WardNo ? item.WardNo : 0;

    // Check if any property of checkedObject has a value other than 0
    const hasValue = checkedObject.DoctorId || checkedObject.OtId || checkedObject.Schedule_Type || checkedObject.WardNo;
    if (hasValue) {
    var isDuplicate = checkedNames.some(function (existingItem) {
        if (checkedObject.DoctorId) {
            return existingItem.DoctorId === checkedObject.DoctorId;
        } else if (checkedObject.WardNo) {
            return existingItem.WardNo === checkedObject.WardNo;
        }
        return false;
    });
    if (!isDuplicate) {
        checkedNames.push({ ...checkedObject });
    }
    }

    console.log(checkedNames);
}


//CalendarNormalLocalSearch
function CalendarLocalSearch(SchId, calendartype) {
   
    const tbodyId = `#subtable_${calendartype}${SchId}`;
    const tbody = $(tbodyId);

    $('#searchtype_' + SchId + calendartype).on('input', function () {
        const searchQuery = this.value.toLowerCase();
        tbody.find('.uisortabletable').each(function () {
            const doctorName = $(this).find('label').text().toLowerCase();
            if (doctorName.includes(searchQuery)) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });
}

//CalendarAutoCompleteSearch
function CalendarAutoCompleteSearch(SchId, calendartype, currentDate, branchid) {

    const dateObject = new Date(currentDate);
    const formattedDateForInput = formatDateForInput(dateObject);

    $('.calendarsearchfield').autocomplete({
        source: function (request, response) {
            $.ajax({
                async: true,
                url: "/Calender/DoctorAutoCompletelist",
                type: "POST",
                dataType: "json",
                data: {
                 TypeName: request.term,
                  // Prefix: request.term,
                    DmlIndicator: 'CDAUTO',
                    ScheduleType: 7,
                   // fromDate: '07/31/2024',
                    fromDate: formattedDateForInput,
                    UserId: $('#hiddenUser_id').val(),
                    HospitalId: $('#HospitalIdInt').val(),
                    BranchId: branchid,
                    calender_type: calendartype,

                },
                success: function (data) {
                    debugger;
                    var responsedata = JSON.parse(data).data.Table;
                    //var data2 = data.Table;
                    response($.map(responsedata, function (item) {
                        return { label: item.Type_DatalistName, value: item.Type_DatalistName, id: item.DoctorId };
                    }))
                }
            })
        },
        minLength: 1,
        select: function (event, ui) {
          
            $('#Hdndoctor_id').val(ui.item.id);
        },
        html: true,
    });
    $('#addButton_' + calendartype + '').on('click', function () {
        
         hiddendoctorid = $('#Hdndoctor_id').val();
        if (hiddendoctorid) {
            opencollapselist(SchId, branchid, currentDate, calendartype, hiddendoctorid)
        }
    });
}



//Onclick Function for adding SchId to openCollapses for opening Collapses
$(document).on('click', '.opencollapseclick', function () {

    const schId = Number($(this).attr('data-schId'));
    const targetCollapse = $(this).attr('data-target');

    // Delay to allow transition
    setTimeout(function () {
        const isCollapseShown = $(targetCollapse).hasClass('in'); // Check if the target is open

        if (isCollapseShown) {
            // Collapse is open
            if (!openCollapses.includes(schId) && schId !== null) {
                openCollapses.push(schId);
            }
        } else {
            // Collapse is closed
            const index = openCollapses.indexOf(schId);
            if (index > -1) {
                openCollapses.splice(index, 1);
            }
        }

        console.log("Opened:", openCollapses);
    }, 500); // Adjust delay if necessary
});