$(document).ready(function () {
    debugger;
    var currentDate = new Date();
    $('.currentdate').text(formatDate(currentDate, { year: 'numeric', month: 'long', day: 'numeric' }));
    bindCalendar(scheduleType, headerId, bodyId,currentDate);
  
});

function bindCalendar(scheduleType, headerId, bodyId, currentDate) {
    debugger;
    const formattedDateForInput = formatDateForInput(currentDate);
    const OTdata = {
        P_Dml_Indicator: 'OTCS1',
        fromDate: formattedDateForInput,
        Schedule_Type: scheduleType
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(OTdata),
        success: function (response) {
            const data = JSON.parse(response).data.Table;
            const doctorNames = [...new Set(data.map(item => item[scheduleType == 4 || scheduleType == 5 ? 'DoctorName' : 'Room_name']))];
            
            // Extract the date part from currentDate
            const eventDate = currentDate.toISOString().split('T')[0];
            
            // Use the extracted date part to create startTime and endTime
            const startTime = new Date(`${eventDate}T08:00:00`);
            const endTime = new Date(`${eventDate}T20:00:00`);

            const generateTimeSlots = (startTime, endTime, interval = 30) => {
                const times = [];
                let currentTime = new Date(startTime);
                while (currentTime <= endTime) {
                    times.push(new Date(currentTime));
                    currentTime.setMinutes(currentTime.getMinutes() + interval);
                }
                return times;
            };

            const times = generateTimeSlots(startTime, endTime);

            const calendarHeader = document.getElementById(headerId);
            calendarHeader.innerHTML = '';
            const calendarBody = document.getElementById(bodyId);
            calendarBody.innerHTML = '';

            // Create table header
            const headerRow = calendarBody.insertRow(0);
            const doctorHeader = document.createElement('th');
            doctorHeader.textContent = 'Ward Name';
            headerRow.appendChild(doctorHeader);
            times.forEach(timeSlot => {
                const th = document.createElement('th');
                th.textContent = timeSlot.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true });
                headerRow.appendChild(th);
            });

            doctorNames.forEach((doctor, rowIndex) => {
                const tr = calendarBody.insertRow(rowIndex + 1);
                const doctorTd = tr.insertCell(0);
                doctorTd.textContent = doctor;

                times.forEach((timeSlot, colIndex) => {
                    const td = tr.insertCell(colIndex + 1);
                    td.className = 'event-container';
                    td.style.position = 'relative';

                    const events = data.filter(item => {
                        const fromTime = new Date(`${eventDate}T${item.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
                        const toTime = new Date(`${eventDate}T${item.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
                        return fromTime <= timeSlot && toTime > timeSlot && item[scheduleType == 4 || scheduleType == 5 ? 'DoctorName' : 'Room_name'] === doctor;
                    });

                    events.forEach(event => {
                        const fromTime = new Date(`${eventDate}T${event.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
                        const toTime = new Date(`${eventDate}T${event.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
                        const duration = (toTime - fromTime) / (1000 * 60); // Duration in minutes

                        // Calculate the exact position in the timeslot
                        const startSlotMinutes = (timeSlot.getHours() * 60 + timeSlot.getMinutes());
                        const eventStartMinutes = (fromTime.getHours() * 60 + fromTime.getMinutes());
                        const offsetMinutes = eventStartMinutes - startSlotMinutes;

                        const widthPerMinute = 2; // Adjust this value as needed
                        const eventWidth = duration * widthPerMinute;
                        const leftPosition = offsetMinutes * widthPerMinute;

                        const div = document.createElement('div');
                        div.className = 'calendar_event';
                        div.style.width = `${eventWidth}px`;
                        div.style.position = 'absolute';
                        div.style.left = `${leftPosition}px`;
                        div.style.top = '0px';
                        //div.style.height = '60px'; // Set the height here
                        div.style.display = 'inline-block';

                        let spanClass = '';
                        let spanContent = '';
                        let eventContent = '';

                        switch (scheduleType) {
                            case 1:
                                spanClass = 'surgery-name';
                                spanContent = event.SurgeryName;
                                eventContent = `${event.Patientname}<br>${event.DoctorName}<br>${event.Service_Name}<br><p>${event.ScheduleFromTime1}</p><p>${event.ScheduleToTime1}</p>`;
                                break;
                            case 2:
                                spanClass = 'Patient-name';
                                spanContent = event.Patientname;
                                eventContent = `${event.DoctorName}<br>${event.Service_Name}<br>${event.Remarks}<br><p>${event.ScheduleFromTime1}</p><p>${event.ScheduleToTime1}</p>`;
                                break;
                            case 3:
                                spanClass = 'Therapy-name';
                                spanContent = event.Patientname;
                                eventContent = `${event.SurgeryName}<br>${event.Service_Name}<br>${event.Remarks}<br><p>${event.ScheduleFromTime1}</p><p>${event.ScheduleToTime1}</p>`;
                                break;
                            case 4:
                                spanClass = 'Tech-name';
                                spanContent = event.Patientname;
                                eventContent = `${event.Service}<br>${event.Remarks}<br>${event.ScheduleFromTime1}<br><p>${event.ScheduleToTime1}</p>`;
                                break;
                            case 5:
                                spanClass = 'nurse-name';
                                spanContent = event.Patientname;
                                eventContent = `${event.Service}<br>${event.Remarks}<br>${event.ScheduleFromTime1}<br><p>${event.ScheduleToTime1}</p>`;
                                break;
                            default:
                                break;
                        }

                        div.innerHTML = `<strong><span class="${spanClass}" data-id="${event.ID}">${spanContent}</span></strong><br>${eventContent}<input type="hidden" class="event-id" value="${event.ID}">`;
                        td.appendChild(div);
                    });

                    tr.appendChild(td);
                });

                calendarBody.appendChild(tr);
            });

            const colors = ['lightcoral', 'lightblue', 'lightgreen', 'lightyellow', 'lightpink'];
            document.querySelectorAll('.new_calendar .calendar_event').forEach((event, index) => {
                event.style.backgroundColor = colors[index % colors.length];
            });
        },
        error: function (xhr, status, error) {
            console.error('Error fetching calendar data:', error);
            // Add user-friendly error handling here
        }
    });
}







//function bindCalendar(scheduleType, headerId, bodyId, currentDate) {
//    debugger;
//    const formattedDateForInput = formatDateForInput(currentDate);
//    const OTdata = {
//        P_Dml_Indicator: 'OTCS1',
//        fromDate: formattedDateForInput,
//        Schedule_Type: scheduleType
//    };

//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/Calender/OTCreation',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(OTdata),
//        success: function (response) {
//            const data = JSON.parse(response).data.Table;
//            const doctorNames = [...new Set(data.map(item => item[scheduleType == 4 || scheduleType == 5 ? 'DoctorName' : 'Room_name']))];
//            const startTime = new Date('2024-01-05T08:00:00');
//            const endTime = new Date('2024-01-05T20:00:00');

//            const generateTimeSlots = (startTime, endTime, interval = 30) => {
//                const times = [];
//                let currentTime = new Date(startTime);
//                while (currentTime <= endTime) {
//                    times.push(new Date(currentTime));
//                    currentTime.setMinutes(currentTime.getMinutes() + interval);
//                }
//                return times;
//            };

//            const times = generateTimeSlots(startTime, endTime);

//            const calendarHeader = document.getElementById(headerId);
//            calendarHeader.innerHTML = '';
//            const calendarBody = document.getElementById(bodyId);
//            calendarBody.innerHTML = '';

//            // Create table header
//            const headerRow = calendarBody.insertRow(0);
//            const doctorHeader = document.createElement('th');
//            doctorHeader.textContent = 'Ward Name';
//            headerRow.appendChild(doctorHeader);
//            times.forEach(timeSlot => {
//                const th = document.createElement('th');
//                th.textContent = timeSlot.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true });
//                headerRow.appendChild(th);
//            });

//            doctorNames.forEach((doctor, rowIndex) => {
//                const tr = calendarBody.insertRow(rowIndex + 1);
//                const doctorTd = tr.insertCell(0);
//                doctorTd.textContent = doctor;

//                times.forEach((timeSlot, colIndex) => {
//                    const td = tr.insertCell(colIndex + 1);
//                    td.className = 'event-container';
//                    td.style.position = 'relative';

//                    const events = data.filter(item => {
//                        const fromTime = new Date(`2024-01-05T${item.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
//                        const toTime = new Date(`2024-01-05T${item.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
//                        return fromTime <= timeSlot && toTime > timeSlot && item[scheduleType == 4 || scheduleType == 5 ? 'DoctorName' : 'Room_name'] === doctor;
//                    });

//                    events.forEach(event => {
//                        const fromTime = new Date(`2024-01-05T${event.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
//                        const toTime = new Date(`2024-01-05T${event.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
//                        const duration = (toTime - fromTime) / (1000 * 60); // Duration in minutes

//                        // Calculate the exact position in the timeslot
//                        const startSlotMinutes = (timeSlot.getHours() * 60 + timeSlot.getMinutes());
//                        const eventStartMinutes = (fromTime.getHours() * 60 + fromTime.getMinutes());
//                        const offsetMinutes = eventStartMinutes - startSlotMinutes;

//                        const widthPerMinute = 2; // Adjust this value as needed
//                        const eventWidth = duration * widthPerMinute;
//                        const leftPosition = offsetMinutes * widthPerMinute;

//                        const div = document.createElement('div');
//                        div.className = 'calendar_event';
//                        div.style.width = `${eventWidth}px`;
//                        div.style.position = 'absolute';
//                        div.style.left = `${leftPosition}px`;
//                        div.style.top = '0px';
//                        //div.style.height = '60px'; // Set the height here
//                        div.style.display = 'inline-block';

//                        let spanClass = '';
//                        let spanContent = '';
//                        let eventContent = '';

//                        switch (scheduleType) {
//                            case 1:
//                                spanClass = 'surgery-name';
//                                spanContent = event.SurgeryName;
//                                eventContent = `${event.Patientname}<br>${event.DoctorName}<br>${event.Service_Name}<br><p>${event.ScheduleFromTime1}</p><p>${event.ScheduleToTime1}</p>`;
//                                break;
//                            case 2:
//                                spanClass = 'Patient-name';
//                                spanContent = event.Patientname;
//                                eventContent = `${event.DoctorName}<br>${event.Service_Name}<br>${event.Remarks}<br><p>${event.ScheduleFromTime1}</p><p>${event.ScheduleToTime1}</p>`;
//                                break;
//                            case 3:
//                                spanClass = 'Therapy-name';
//                                spanContent = event.Patientname;
//                                eventContent = `${event.SurgeryName}<br>${event.Service_Name}<br>${event.Remarks}<br><p>${event.ScheduleFromTime1}</p><p>${event.ScheduleToTime1}</p>`;
//                                break;
//                            case 4:
//                                spanClass = 'Tech-name';
//                                spanContent = event.Patientname;
//                                eventContent = `${event.Service}<br>${event.Remarks}<br>${event.ScheduleFromTime1}<br><p>${event.ScheduleToTime1}</p>`;
//                                break;
//                            case 5:
//                                spanClass = 'nurse-name';
//                                spanContent = event.Patientname;
//                                eventContent = `${event.Service}<br>${event.Remarks}<br>${event.ScheduleFromTime1}<br><p>${event.ScheduleToTime1}</p>`;
//                                break;
//                            default:
//                                break;
//                        }

//                        div.innerHTML = `<strong><span class="${spanClass}" data-id="${event.ID}">${spanContent}</span></strong><br>${eventContent}<input type="hidden" class="event-id" value="${event.ID}">`;
//                        td.appendChild(div);
//                    });

//                    tr.appendChild(td);
//                });

//                calendarBody.appendChild(tr);
//            });

//            const colors = ['lightcoral', 'lightblue', 'lightgreen', 'lightyellow', 'lightpink'];
//            document.querySelectorAll('.new_calendar .calendar_event').forEach((event, index) => {
//                event.style.backgroundColor = colors[index % colors.length];
//            });
//        },
//        error: function (xhr, status, error) {
//            console.error('Error fetching calendar data:', error);
//            // Add user-friendly error handling here
//        }
//    });
//}

//function bindCalendar(scheduleType, headerId, bodyId,currentDate) {
//    debugger;
//    var formattedDateForInput = formatDateForInput(currentDate);
//    var OTdata = {
//        P_Dml_Indicator: 'OTCS',
//        fromDate: formattedDateForInput,
//        Schedule_Type: scheduleType
//    };
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/Calender/OTCreation',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(OTdata),
//        success: function (data) {
//            var data1 = JSON.parse(data);
//            var data = data1.data.Table;
//            if(scheduleType==1)
//            {
//                // Extract unique doctor names for the header
//                const doctorNames = [...new Set(data.map(item => item.Room_name))];

//                // Define the start and end times for the calendar
//                const startTime = new Date('2024-01-05T08:00:00'); // Start time: 8:00 AM
//                const endTime = new Date('2024-01-05T20:00:00'); // End time: 8:00 PM

//                // Generate time slots in 30-minute intervals
//                const generateTimeSlots = (startTime, endTime, interval = 30) => {
//                    const times = [];
//                    let currentTime = new Date(startTime);

//                    while (currentTime <= endTime) {
//                        times.push(new Date(currentTime));
//                        currentTime.setMinutes(currentTime.getMinutes() + interval);
//                    }
//                    return times;
//                };

//                const times = generateTimeSlots(startTime, endTime);

//                // Clear the existing table header and body
//                const calendarHeader = document.getElementById(headerId);
//                calendarHeader.innerHTML = ''; // Clear existing headers

//                const calendarBody = document.getElementById(bodyId);
//                calendarBody.innerHTML = ''; // Clear existing rows

//                // Create table header
//                calendarHeader.appendChild(document.createElement('th')); // Empty top-left corner cell
//                doctorNames.forEach(doctor => {
//                    const th = document.createElement('th');
//                    th.textContent = doctor;
//                    calendarHeader.appendChild(th);
//                });

//                // Create table body
//                const spanMap = {};

//                // Populate the table body
//                times.forEach((timeSlot, index) => {
//                    const tr = document.createElement('tr');
//                    const timeTd = document.createElement('td');
//                    timeTd.textContent = timeSlot.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true });
//                    tr.appendChild(timeTd);

//                    doctorNames.forEach(doctor => {
//                        if (spanMap[doctor] && spanMap[doctor] > 0) {
//                            spanMap[doctor]--;
//                            return; // Skip this cell because it's spanned by a previous event
//                        }

//                        const td = document.createElement('td');
//                        td.className = 'event-container';

//                        // Filter events that fall within the current 30-minute time slot
//                        const events = data.filter(item => {
//                            const fromTime = new Date(`2024-01-05T${item.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
//                            const toTime = new Date(`2024-01-05T${item.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
//                            return fromTime <= timeSlot && toTime > timeSlot && item.Room_name === doctor;
//                        });

//                        if (events.length > 0) {
//                            const event = events[0];
//                            const fromTime = new Date(`2024-01-05T${event.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
//                            const toTime = new Date(`2024-01-05T${event.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
//                            const duration = (toTime - fromTime) / (1000 * 60); // Duration in minutes
//                            const heightPerMinute = 2;
//                            const eventHeight = duration * heightPerMinute;
//                            const div = document.createElement('div');
//                            div.className = 'calendar_event';
//                            div.innerHTML = '<strong><span class="surgery-name" data-id="' + event.ID + '">' + event.SurgeryName + '</span></strong><br>' +  event.Patientname + '<br>' + event.DoctorName + '<br>' +  event.Service_Name + '<br>' +'<p>' + event.ScheduleFromTime + '</p>' +'<p>' + event.ScheduleToTime + '</p>' +'<input type="hidden" class="event-id" value="' + event.ID + '">';
//                            div.style.height = '' + eventHeight + 'px';
//                            div.style.position = 'relative';
//                            td.appendChild(div);
//                            const rowSpan = Math.ceil(duration / 30);
//                            spanMap[doctor] = rowSpan - 1;
//                            td.rowSpan = rowSpan;
//                        } else {
//                            td.className = 'no-events';
//                        }

//                        tr.appendChild(td);
//                    });

//                    calendarBody.appendChild(tr);

//                });
//            }
//            if(scheduleType==2) 
//            {
//                // Extract unique doctor names for the header
//                const doctorNames = [...new Set(data.map(item => item.Room_name))];

//                // Define the start and end times for the calendar
//                const startTime = new Date('2024-01-05T08:00:00'); // Start time: 8:00 AM
//                const endTime = new Date('2024-01-05T20:00:00'); // End time: 8:00 PM

//                // Generate time slots in 30-minute intervals
//                const generateTimeSlots = (startTime, endTime, interval = 30) => {
//                    const times = [];
//                    let currentTime = new Date(startTime);

//                    while (currentTime <= endTime) {
//                        times.push(new Date(currentTime));
//                        currentTime.setMinutes(currentTime.getMinutes() + interval);
//                    }
//                    return times;
//                };

//                const times = generateTimeSlots(startTime, endTime);

//                // Clear the existing table header and body
//                const calendarHeader = document.getElementById(headerId);
//                calendarHeader.innerHTML = ''; // Clear existing headers

//                const calendarBody = document.getElementById(bodyId);
//                calendarBody.innerHTML = ''; // Clear existing rows

//                // Create table header
//                calendarHeader.appendChild(document.createElement('th')); // Empty top-left corner cell
//                doctorNames.forEach(doctor => {
//                    const th = document.createElement('th');
//                    th.textContent = doctor;
//                    calendarHeader.appendChild(th);
//                });

//                // Create table body
//                const spanMap = {};

//                // Populate the table body
//                times.forEach((timeSlot, index) => {
//                    const tr = document.createElement('tr');
//                    const timeTd = document.createElement('td');
//                    timeTd.textContent = timeSlot.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true });
//                    tr.appendChild(timeTd);

//                    doctorNames.forEach(doctor => {
//                        if (spanMap[doctor] && spanMap[doctor] > 0) {
//                            spanMap[doctor]--;
//                            return; // Skip this cell because it's spanned by a previous event
//                        }

//                        const td = document.createElement('td');
//                        td.className = 'event-container';

//                        // Filter events that fall within the current 30-minute time slot
//                        const events = data.filter(item => {
//                            const fromTime = new Date(`2024-01-05T${item.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
//                            const toTime = new Date(`2024-01-05T${item.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
//                            return fromTime <= timeSlot && toTime > timeSlot && item.Room_name === doctor;
//                        });

//                        if (events.length > 0) {
//                            const event = events[0];
//                            const fromTime = new Date(`2024-01-05T${event.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
//                            const toTime = new Date(`2024-01-05T${event.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
//                            const duration = (toTime - fromTime) / (1000 * 60); // Duration in minutes
//                            const heightPerMinute = 2;
//                            const eventHeight = duration * heightPerMinute;
//                            const div = document.createElement('div');
//                            div.className = 'calendar_event';
//                            div.innerHTML = '<strong><span class="Patient-name" data-id="' + event.ID + '">' + event.Patientname + '</span></strong><br>' +  event.DoctorName + '<br>' + event.Service_Name + '<br>' + event.Remarks + '<br>' +'<p>' + event.ScheduleFromTime + '</p>' + '<p>' + event.ScheduleToTime + '</p>' +'<input type="hidden" class="event-id" value="' + event.ID + '">';                        
//                            div.style.height = '' + eventHeight + 'px';
//                            div.style.position = 'relative';
//                            td.appendChild(div);
//                            const rowSpan = Math.ceil(duration / 30);
//                            spanMap[doctor] = rowSpan - 1;
//                            td.rowSpan = rowSpan;
//                        } else {
//                            td.className = 'no-events';
//                        }

//                        tr.appendChild(td);
//                    });

//                    calendarBody.appendChild(tr);

//                });
//            }
//            if(scheduleType==3)
//            {
//                // Extract unique doctor names for the header
//                const doctorNames = [...new Set(data.map(item => item.Room_name))];

//                // Define the start and end times for the calendar
//                const startTime = new Date('2024-01-05T08:00:00'); // Start time: 8:00 AM
//                const endTime = new Date('2024-01-05T20:00:00'); // End time: 8:00 PM

//                // Generate time slots in 30-minute intervals
//                const generateTimeSlots = (startTime, endTime, interval = 30) => {
//                    const times = [];
//                    let currentTime = new Date(startTime);

//                    while (currentTime <= endTime) {
//                        times.push(new Date(currentTime));
//                        currentTime.setMinutes(currentTime.getMinutes() + interval);
//                    }
//                    return times;
//                };

//                const times = generateTimeSlots(startTime, endTime);

//                // Clear the existing table header and body
//                const calendarHeader = document.getElementById(headerId);
//                calendarHeader.innerHTML = ''; // Clear existing headers

//                const calendarBody = document.getElementById(bodyId);
//                calendarBody.innerHTML = ''; // Clear existing rows

//                // Create table header
//                calendarHeader.appendChild(document.createElement('th')); // Empty top-left corner cell
//                doctorNames.forEach(doctor => {
//                    const th = document.createElement('th');
//                    th.textContent = doctor;
//                    calendarHeader.appendChild(th);
//                });

//                // Create table body
//                const spanMap = {};

//                // Populate the table body
//                times.forEach((timeSlot, index) => {
//                    const tr = document.createElement('tr');
//                    const timeTd = document.createElement('td');
//                    timeTd.textContent = timeSlot.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true });
//                    tr.appendChild(timeTd);

//                    doctorNames.forEach(doctor => {
//                        if (spanMap[doctor] && spanMap[doctor] > 0) {
//                            spanMap[doctor]--;
//                            return; // Skip this cell because it's spanned by a previous event
//                        }

//                        const td = document.createElement('td');
//                        td.className = 'event-container';

//                        // Filter events that fall within the current 30-minute time slot
//                        const events = data.filter(item => {
//                            const fromTime = new Date(`2024-01-05T${item.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
//                            const toTime = new Date(`2024-01-05T${item.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
//                            return fromTime <= timeSlot && toTime > timeSlot && item.Room_name === doctor;
//                        });

//                        if (events.length > 0) {
//                            const event = events[0];
//                            const fromTime = new Date(`2024-01-05T${event.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
//                            const toTime = new Date(`2024-01-05T${event.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
//                            const duration = (toTime - fromTime) / (1000 * 60); // Duration in minutes
//                            const heightPerMinute = 2;
//                            const eventHeight = duration * heightPerMinute;
//                            const div = document.createElement('div');
//                            div.className = 'calendar_event';
//                            div.innerHTML = '<strong><span class="Theraphy-name" data-id="' + event.ID + '">' + event.Patientname + '</span></strong><br>' + event.SurgeryName + '<br>' +  event.Service_Name + '<br>' +  event.Remarks + '<br>' + '<p>' + event.ScheduleFromTime + '</p>' + '<p>' + event.ScheduleToTime + '</p>' +'<input type="hidden" class="event-id" value="' + event.ID + '">';              
//                            div.style.height = '' + eventHeight + 'px';
//                            div.style.position = 'relative';
//                            td.appendChild(div);
//                            const rowSpan = Math.ceil(duration / 30);
//                            spanMap[doctor] = rowSpan - 1;
//                            td.rowSpan = rowSpan;
//                        } else {
//                            td.className = 'no-events';
//                        }

//                        tr.appendChild(td);
//                    });

//                    calendarBody.appendChild(tr);

//                });
//            }
//            if(scheduleType==4)
//            {
//                // Extract unique doctor names for the header
//                const doctorNames = [...new Set(data.map(item => item.DoctorName))];

//                // Define the start and end times for the calendar
//                const startTime = new Date('2024-01-05T08:00:00'); // Start time: 8:00 AM
//                const endTime = new Date('2024-01-05T20:00:00'); // End time: 8:00 PM

//                // Generate time slots in 30-minute intervals
//                const generateTimeSlots = (startTime, endTime, interval = 30) => {
//                    const times = [];
//                    let currentTime = new Date(startTime);

//                    while (currentTime <= endTime) {
//                        times.push(new Date(currentTime));
//                        currentTime.setMinutes(currentTime.getMinutes() + interval);
//                    }
//                    return times;
//                };

//                const times = generateTimeSlots(startTime, endTime);

//                // Clear the existing table header and body
//                const calendarHeader = document.getElementById(headerId);
//                calendarHeader.innerHTML = ''; // Clear existing headers

//                const calendarBody = document.getElementById(bodyId);
//                calendarBody.innerHTML = ''; // Clear existing rows

//                // Create table header
//                calendarHeader.appendChild(document.createElement('th')); // Empty top-left corner cell
//                doctorNames.forEach(doctor => {
//                    const th = document.createElement('th');
//                    th.textContent = doctor;
//                    calendarHeader.appendChild(th);
//                });

//                // Create table body
//                const spanMap = {};

//                // Populate the table body
//                times.forEach((timeSlot, index) => {
//                    const tr = document.createElement('tr');
//                    const timeTd = document.createElement('td');
//                    timeTd.textContent = timeSlot.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true });
//                    tr.appendChild(timeTd);

//                    doctorNames.forEach(doctor => {
//                        if (spanMap[doctor] && spanMap[doctor] > 0) {
//                            spanMap[doctor]--;
//                            return; // Skip this cell because it's spanned by a previous event
//                        }

//                        const td = document.createElement('td');
//                        td.className = 'event-container';

//                        // Filter events that fall within the current 30-minute time slot
//                        const events = data.filter(item => {
//                            const fromTime = new Date(`2024-01-05T${item.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
//                            const toTime = new Date(`2024-01-05T${item.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
//                            return fromTime <= timeSlot && toTime > timeSlot && item.DoctorName === doctor;
//                        });

//                        if (events.length > 0) {
//                            const event = events[0];
//                            const fromTime = new Date(`2024-01-05T${event.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
//                            const toTime = new Date(`2024-01-05T${event.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
//                            const duration = (toTime - fromTime) / (1000 * 60); // Duration in minutes
//                            const heightPerMinute = 2;
//                            const eventHeight = duration * heightPerMinute;
//                            const div = document.createElement('div');
//                            div.className = 'calendar_event';
//                            div.innerHTML = '<strong><span class="Tech-name" data-id="' + event.ID + '">' + event.Patientname + '</span></strong><br>' + event.Service + '<br>' +  event.Remarks + '<br>' +  event.ScheduleFromTime + '<br>' + '<p>' + event.ScheduleToTime + '</p>'+'<input type="hidden" class="event-id" value="' + event.ID + '">';                           
//                            div.style.height = '' + eventHeight + 'px';
//                            div.style.position = 'relative';
//                            td.appendChild(div);
//                            const rowSpan = Math.ceil(duration / 30);
//                            spanMap[doctor] = rowSpan - 1;
//                            td.rowSpan = rowSpan;
//                        } else {
//                            td.className = 'no-events';
//                        }

//                        tr.appendChild(td);
//                    });

//                    calendarBody.appendChild(tr);

//                });
//            }
//            if(scheduleType==5)
//            {
//                // Extract unique doctor names for the header
//                const doctorNames = [...new Set(data.map(item => item.DoctorName))];

//                // Define the start and end times for the calendar
//                const startTime = new Date('2024-01-05T08:00:00'); // Start time: 8:00 AM
//                const endTime = new Date('2024-01-05T20:00:00'); // End time: 8:00 PM

//                // Generate time slots in 30-minute intervals
//                const generateTimeSlots = (startTime, endTime, interval = 30) => {
//                    const times = [];
//                    let currentTime = new Date(startTime);

//                    while (currentTime <= endTime) {
//                        times.push(new Date(currentTime));
//                        currentTime.setMinutes(currentTime.getMinutes() + interval);
//                    }
//                    return times;
//                };

//                const times = generateTimeSlots(startTime, endTime);

//                // Clear the existing table header and body
//                const calendarHeader = document.getElementById(headerId);
//                calendarHeader.innerHTML = ''; // Clear existing headers

//                const calendarBody = document.getElementById(bodyId);
//                calendarBody.innerHTML = ''; // Clear existing rows

//                // Create table header
//                calendarHeader.appendChild(document.createElement('th')); // Empty top-left corner cell
//                doctorNames.forEach(doctor => {
//                    const th = document.createElement('th');
//                    th.textContent = doctor;
//                    calendarHeader.appendChild(th);
//                });

//                // Create table body
//                const spanMap = {};

//                // Populate the table body
//                times.forEach((timeSlot, index) => {
//                    const tr = document.createElement('tr');
//                    const timeTd = document.createElement('td');
//                    timeTd.textContent = timeSlot.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true });
//                    tr.appendChild(timeTd);

//                    doctorNames.forEach(doctor => {
//                        if (spanMap[doctor] && spanMap[doctor] > 0) {
//                            spanMap[doctor]--;
//                            return; // Skip this cell because it's spanned by a previous event
//                        }

//                        const td = document.createElement('td');
//                        td.className = 'event-container';

//                        // Filter events that fall within the current 30-minute time slot
//                        const events = data.filter(item => {
//                            const fromTime = new Date(`2024-01-05T${item.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
//                            const toTime = new Date(`2024-01-05T${item.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
//                            return fromTime <= timeSlot && toTime > timeSlot && item.DoctorName === doctor;
//                        });

//                        if (events.length > 0) {
//                            const event = events[0];
//                            const fromTime = new Date(`2024-01-05T${event.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
//                            const toTime = new Date(`2024-01-05T${event.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
//                            const duration = (toTime - fromTime) / (1000 * 60); // Duration in minutes
//                            const heightPerMinute = 2;
//                            const eventHeight = duration * heightPerMinute;
//                            const div = document.createElement('div');
//                            div.className = 'calendar_event';
//                            div.innerHTML = '<strong><span class="nurse-name" data-id="' + event.ID + '">' + event.Patientname + '</span></strong><br>' + event.Service + '<br>' +  event.Remarks + '<br>' +  event.ScheduleFromTime + '<br>' + '<p>' + event.ScheduleToTime + '</p>'+'<input type="hidden" class="event-id" value="' + event.ID + '">';
//                            div.style.height = '' + eventHeight + 'px';
//                            div.style.position = 'relative';
//                            td.appendChild(div);
//                            const rowSpan = Math.ceil(duration / 30);
//                            spanMap[doctor] = rowSpan - 1;
//                            td.rowSpan = rowSpan;
//                        } else {
//                            td.className = 'no-events';
//                        }

//                        tr.appendChild(td);
//                    });

//                    calendarBody.appendChild(tr);

//                });
//            }
//            var colors = ['lightcoral', 'lightblue', 'lightgreen', 'lightyellow', 'lightpink'];

//            $('.new_calendar .calendar_event').each(function (index) {
//                $(this).css('background-color', colors[index % colors.length]);
//            });
//        }
//    });
//}

//function bindCalendar(scheduleType) {
//    var OTdata = {
//        P_Dml_Indicator: 'OTCS',
//        fromDate: "2024-04-15",
//        Schedule_Type:scheduleType
//    };

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


//             Extract unique doctor names for the header
//            const doctorNames = [...new Set(data.map(item => item.DoctorName))];
//             Define the start and end times for the calendar
//             Define the start and end times for the calendar
//            const startTime = new Date('2024-01-05T08:00:00'); // Start time: 8:00 AM
//            const endTime = new Date('2024-01-05T20:00:00'); // End time: 8:00 PM

//             Generate time slots in 30-minute intervals
//            const generateTimeSlots = (startTime, endTime, interval = 30) => {
//                const times = [];
//                let currentTime = new Date(startTime);

//                while (currentTime <= endTime) {
//                    times.push(new Date(currentTime));
//                    currentTime.setMinutes(currentTime.getMinutes() + interval);
//                }
//                return times;
//            };

//            const times = generateTimeSlots(startTime, endTime);

//             Create table header
//            const calendarHeader = document.getElementById('calendar-header');
//            calendarHeader.appendChild(document.createElement('th')); // Empty top-left corner cell
//            doctorNames.forEach(doctor => {
//                const th = document.createElement('th');
//                th.textContent = doctor;
//                calendarHeader.appendChild(th);
//            });

//             Create table body
//            const calendarBody = document.getElementById('calendar-body');
//            const spanMap = {};

//             Populate the table body
//            times.forEach((timeSlot, index) => {
//                const tr = document.createElement('tr');
//                const timeTd = document.createElement('td');
//                timeTd.textContent = timeSlot.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true });
//                tr.appendChild(timeTd);

//                doctorNames.forEach(doctor => {
//                    if (spanMap[doctor] && spanMap[doctor] > 0) {
//                        spanMap[doctor]--;
//                        return; // Skip this cell because it's spanned by a previous event
//                    }

//                    const td = document.createElement('td');
//                    td.className = 'event-container';

//                     Filter events that fall within the current 30-minute time slot
//                    const events = data.filter(item => {
                       
//                        const fromTime = new Date(`2024-01-05T${item.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
//                        const toTime = new Date(`2024-01-05T${item.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
//                        return fromTime <= timeSlot && toTime > timeSlot && item.DoctorName === doctor;
//                    });
                  
//                    if (events.length > 0) {
//                        const event = events[0]; // Assuming one event per doctor per time slot
//                        const fromTime = new Date(`2024-01-05T${event.ScheduleFromTime.replace(/ (AM|PM)/, '')}`);
//                        const toTime = new Date(`2024-01-05T${event.ScheduleToTime.replace(/ (AM|PM)/, '')}`);
//                        const duration = (toTime - fromTime) / (1000 * 60); // Duration in minutes
//                        const heightPerMinute = 2; 
//                        const eventHeight = duration * heightPerMinute;
//                        const div = document.createElement('div');
//                        div.className = 'calendar_event';
//                        div.innerHTML = '<strong>' + event.Patientname + '</strong><br>' + event.Service_Name + '<br><p>' + event.ScheduleFromTime + '</p><p>' + event.ScheduleToTime +'</p>';
//                        div.style.height = ''+eventHeight+'px';
//                        div.style.position = 'relative';
//                        td.appendChild(div);
//                        const rowSpan = Math.ceil(duration / 30);
//                        spanMap[doctor] = rowSpan - 1;
//                        td.rowSpan = rowSpan;
//                    } else {
//                        td.className = 'no-events';
//                    }

//                    tr.appendChild(td);
//                });

//                calendarBody.appendChild(tr);
//            });


//            var colors = ['lightcoral', 'lightblue', 'lightgreen', 'lightyellow', 'lightpink'];

//             Select all .calendar_event elements
//            $('.new_calendar .calendar_event').each(function (index) {
//                 Apply background color from the colors array, cycling through with the modulus operator
//                $(this).css('background-color', colors[index % colors.length]);
//            });
//        }
//    })
//}