document.addEventListener('DOMContentLoaded', function () {
    let calendarEl = document.querySelector('#appointments');
    let host_url = document.querySelector('#hosturl').value;

    let date = new Date();
    let d = date.getDate();
    let m = date.getMonth();
    let y = date.getFullYear();

    let calendar = new FullCalendar.Calendar(calendarEl, {
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
        },
        initialDate: new Date(y, m, d),
        navLinks: true, // can click day/week names to navigate views
        businessHours: true, // display business hours
        editable: false,
        selectable: true,
        eventMaxStack: 3,
        eventSources: [
            {
                events: function (info, successCallback, failureCallback) {
                    $.ajax({
                        url: host_url + '/controllers/appointments.php?ac=events',
                        method: 'POST',
                        data: {
                            start: info.startStr,
                            end: info.endStr
                        }, success: function (result) {
                            successCallback(JSON.parse(result));
                        }, error: function (error) {
                            failureCallback(error);
                        }
                    })
                },
                color: '#30a030',   // a non-ajax option
                textColor: 'white' // a non-ajax option
            }
        ]
        , loading: function (bool) {
            document.getElementById('loading').style.display =
                bool ? 'block' : 'none';
        },
        eventDidMount: function (info) {
            let element;
            if (info.view.type !== 'listMonth') {
                element = info.el.querySelector('.fc-event-title');
            } else {
                element = info.el.querySelector('.fc-list-event-title');
            }
            if (info.event.extendedProps.description !== undefined) {
                element.innerHTML = '<strong>' + info.event.title + '</strong><br><span style="font-size: 11px;">' + info.event.extendedProps.description + '</span>';
            }
        },
    });

    calendar.render();
});