function initFullCalendar(authToken) {
    document.addEventListener('DOMContentLoaded', function () {
        let urlParam = new URLSearchParams(window.location.search);
        let initDate = urlParam.get("d");
        if (initDate == null) {
            initDate = moment().format("YYYY-MM-DD");
            urlParam.set("d",initDate.toString());
        }
        history.pushState({id: 'schedule'},'Horaire - C-CMS', '/admin/schedule?'+urlParam.toString());

        var calendarEl = document.getElementById('fullCalendar');

        var calendar = new FullCalendar.Calendar(calendarEl, {
            plugins: ['dayGrid','interaction','list'],
            locale: 'fr-ca',
            header: {
                left: 'title',
                center: 'dayGridMonth,listWeek',
                right: 'prev,next'
            },
            defaultDate: initDate,
            events: '/api/schedule/events/auth?api_token='+authToken,
            eventRender: function(event, element) {
                if (event.event.extendedProps.icon && event.view.type == 'dayGridMonth')
                {
                    let i = document.createElement('i');
                    i.className = event.event.extendedProps.icon+' mx-1';
                    event.el.querySelector('.fc-content').prepend(i);
                }
                else if(event.event.extendedProps.icon && event.view.type == 'listWeek')
                {
                    let i = document.createElement('i');
                    i.className = event.event.extendedProps.icon+' mr-1';
                    event.el.querySelector('.fc-list-item-title').prepend(i);
                }
            },
            eventClick: function (info) {
                $.get("/api/schedule/events/modal/full/" + info.event.id + "/"+ info.event.extendedProps.extraParams.db_type + "?api_token="+authToken, function (data) {
                    $("#modal-content").html(data);
                    let urlParams = new URLSearchParams(window.location.search);
                    urlParams.set("e",info.event.id);
                    history.pushState({id: 'schedule'},'Horaire - C-CMS', '/admin/schedule?'+urlParams.toString());
                });
                $('#schedulemodal').modal('toggle')
            },
            datesRender(arg) {
                urlParam.set("d",moment(arg.view.currentStart).format("YYYY-MM-DD"));
                history.pushState({id: 'schedule'},'Horaire - C-CMS', '/admin/schedule?'+urlParam.toString());
            },
            dateClick: function (info) {
                var date = moment(info.date).format("YYYY-MM-DD");
                Swal.fire({
                    title: 'Ajouter un événement?',
                    text: "Voulez vous ajouter un événement le "+date,
                    type: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Oui',
                    cancelButtonText: 'Non',
                  }).then((result) => {
                    if (result.value) {
                        window.location.href = '/admin/schedule/add/'+date;
                    }
                  })
            }
        });
        calendar.render();
        if (urlParam.get('e') != null) {
            $.get("/api/schedule/events/modal/full/" + urlParam.get('e')+ "/event?api_token="+authToken, function (data) {
                $("#modal-content").html(data);
                $('#schedulemodal').modal('toggle')
            });
        }
    });

}

function closeScheduleModal() {
    let urlParams = new URLSearchParams(window.location.search);
    urlParams.delete("e");
    if (urlParams.entries().next().done) {
        history.pushState({id: 'schedule'},'Horaire - C-CMS', '/admin/schedule');
    } else {
        history.pushState({id: 'schedule'},'Horaire - C-CMS', '/admin/schedule?'+urlParams.toString());
    }
    $('#schedulemodal').modal('toggle');
}

function switchType(date) {

    var selectInput = $('#type')
    $.get( "/api/schedule/events/add/modal/"+selectInput.val()+"/"+date+"?api_token="+api_token, function( data ) {
        $( "#container" ).html( data );
        console.log( "Loading defaut value for activity type ("+selectInput.val()+")" );
        $('select').selectpicker();
      });

}
function switchTypeEDIT(date) {

    var selectInput = $('#type')

    Swal.fire({
        title: 'êtes vous sur de vouloir changer le type d\'évenement ?',
        text: "Voulez vous ajouter un événement le "+date,
        type: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Oui',
        cancelButtonText: 'Non',
    }).then((result) => {
        if (result.value) {
            $.get( "/api/schedule/events/add/modal/"+selectInput.val()+"/"+date+"?api_token="+api_token, function( data ) {
                $( "#container" ).html( data );
                console.log( "Loading defaut value for activity type ("+selectInput.val()+")" );
            });
        }
    })

}
function deleteEvent(pid){
    swal({
        title: 'Êtes vous certain de vouloir supprimer l\'évenement?',
        text: "Vous ne pourrez pas annuler cette action",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Oui',
        cancelButtonText: 'Non'
    }).then((result) => {
        if (result.value) {

            (function($) {
                $.post('/api/schedule/event/delete/'+pid+'?api_token='+api_token, function(data, status, xhr) {
                    swal(
                        'Supprimé!',
                        "L'évenement a été supprimé",
                        'success'
                    ).then((result) => {
                        if (result.value) {
                            location.reload();
                        }
                    })
                }).fail(function (data, status, xhr) {
                    if (xhr == 'Forbidden') {
                        swal(
                            'Oups!',
                            "Vous n'avez pas les permissions nécessaires...",
                            'error'
                        ).then((result) => {
                            if (result.value) {
                                location.reload();
                            }
                        })
                    }
                });


            })(jQuery);
        }
    })
}
