function checkIsMobile() {
    return window.matchMedia('only screen and (max-width: 760px)').matches;
}

jQuery(function($) {
    // Get the calendar data from localized script
    const calendarData = window.dacdbCalendarData || {};
    
    $.getJSON(calendarData.eventIdJson, function(data) {
        console.log(data);
        showColorKey(data);
    });

    var calendarEl = document.getElementById('Calendar');
    var calendar = new FullCalendar.Calendar(calendarEl, {
        timeZone: 'UTC',
        eventTimeFormat: {
            hour: '2-digit',
            minute: '2-digit',
            meridiem: 'narrow'
        },
        height: 'auto',
        handleWindowResize: true,
        slotMinTime: '06:00',
        slotMaxTime: '20:00',
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: calendarData.views
        },

        views: {
            listDay: { buttonText: 'list day' },
            listWeek: { buttonText: 'list week' }
        },

        initialView: checkIsMobile() ? 'listMonth' : calendarData.view,
        navLinks: true,
        businessHours: true,
        editable: false,
        selectable: true,
        dayMaxEvents: false,
        eventDisplay: 'block',

        eventDidMount: function(info) {
            var tooltip = new Tooltip(info.el, {
                title: info.event.title,
                placement: 'top',
                trigger: 'hover',
                container: 'body'
            });
        },

        eventSources: [{
            url: calendarData.dataPath + 'R_GetEventsV2.cfm',
            method: 'GET',
            extraParams: function() {
                return {
                    AccountID: calendarData.accountId,
                    ClubID: calendarData.clubId || '0',
                    EventCategoryIDs: calendarData.eids,
                    Sector: calendarData.sector || '',
                    r: Math.random()
                };
            }
        }],

        eventClick: function(info) {
            if (!checkIsMobile()) {
                info.jsEvent.preventDefault();
                $.colorbox({ width:'90%', height:'905', iframe:true, href:info.event.url });
            }
        }
    });
    calendar.render();
});

function showColorKey(json) {
    var statusHTML = [];
    console.log(json.length);
    for (var i = 0; i < json.length; i++) {
        var p = json[i];
        console.log(p);
        var catDisplay = p.EVENTCATEGORY.trim();
        console.log(catDisplay);
        statusHTML.push('<div style="display:inline-block;margin-right:10px;"><span class="dac-label" style="background-color:' + p.BGCOLOR + ';color:' + p.FGCOLOR + ';font-weight:normal;border: 1px solid #3a87ad;">' + catDisplay + '</span></div>');
    }
    console.log(statusHTML);
    if ($('#colorKey').length) {
        document.getElementById('colorKey').innerHTML = statusHTML.join('');
    }
} 