
{% extends 'base.html.twig' %}

{% block pagewrapper %}
    {% if access=="config" %}
        <div class="pagemenu">
            <a href="{{ path('app_portal_config_calendar_view', {id:entity.id})}}">{{ entity.name }}</a>
            <a href='{{ path('app_portal_config_calendar_update', {id:entity.id}) }}' title='Modifier le card'><i class='fa fa-cog fa-fw'></i></a>
            <a href='{{ path('app_portal_config_calendar_delete', { id: entity.id }) }}' data-method='delete' data-confirm='Êtes-vous sûr de vouloir supprimer ?' title='Supprimer le card'><i class='fa fa-trash fa-fw'></i></a>
        </div>
        <br>
    {% else %}
        <div style="margin:10px 0px 10px 0px; text-align:left;height:34px;">
            {% if not idpage is empty %}
            <a href="{{path('app_portal_user_page_view',{id:idpage,usage:'group',group:idgroup})}}" class="btn btn-success">Revenir sur le Groupe</a>
            {% endif %}
        </div>

        <ul class="nav navbar-default nav-pills">
            <li id="menucalendar-0" class="nav-item py-3 {% if entity.id is not defined %}active{%endif%}" style="cursor:pointer">
                <a href="{{ path("app_portal_user_calendar_view") }}" class="p-3">
                    Tout
                </a>
            </li>

            {% for calendar in calendars %} 
                <li id="menucalendar-{{calendar.id}}" data-open="{% if calendar.canupdate %}true{%endif%}" class="nav-item  py-3 {% if entity.id is defined and entity.id==calendar.id%}active{%endif%}" style="cursor:pointer">
                    <a href="{{ path("app_portal_user_calendar_view",{'id':calendar.id}) }}" class="p-3">
                        {% if not calendar.groups is empty %}
                            <i class="fa fa-users fa-fw"></i>
                        {% elseif app.user==calendar.user %}
                            <i class="fa fa-user fa-fw"></i>
                        {%endif%}
                        {{ calendar.name }}
                        {% if calendar.canadd %}
                            <i class="fa fa-pencil-alt"></i>
                        {% else %}
                            <i class="fa fa-lock"></i>
                        {% endif %}
                    </a>                    
                </li>
            {% endfor %}


            <div class="ms-auto d-flex">
                {% if canupdate %}
                <li class="nav-item py-3">
                    <a class="px-1 py-3" id="menusubmit" style="cursor:pointer" onclick="submitCalendar()" title='Ajouter un calendrier'><i class='fa fa-plus fa-fw'></i></a>
                </li>
                {% endif %}
                <li class="nav-item py-3"><a class="px-1 py-3" id="menuupdate" style="cursor:pointer;display:none" onclick="updateCalendar()" title='Modifier un calendrier'><i class='fa fa-file fa-fw'></i></a></li>
                <li class="nav-item py-3"><a class="px-1 py-3" id="menushare" style="cursor:pointer;display:none" onclick="shareCalendar()" title='Partager un calendrier'><i class='fa fa-share-alt fa-fw'></i></a></li>
                <li class="nav-item py-3"><a class="px-1 py-3" id="menudelete" style="cursor:pointer;display:none" onclick="deleteCalendar()" title='Supprimer un calendrier'><i class='fa fa-trash fa-fw'></i></a></li>
            </div>
        </ul>
        <br>
    {% endif %}

    <div id="calendar"></div>

    <!-- CREATION EVENEMENT -->
    <div id="mymodal-event-add" class="modal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Création Evénement</h4>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>
                        <input id='vladd' name='vladd' class='btn btn-success' type='submit' onClick='submitEvent(false);' value='Valider' />
                        <input id='vladdpj' name='vladdpj' class='btn btn-success' type='submit' onClick='submitEvent(true);' value='Ajouter des PJ' />
                        <input class='btn btn-secondary' type='submit' value='Annuler' onClick='$("#mymodal-event-add").modal("hide");'>

                        <input name="calendar_id" id="calendar_id" type="hidden" class="form-control" placeholder="Nom">
                        <input name="envent_id" id="envent_id" type="hidden" class="form-control" placeholder="Nom">
                    </p>

                    <div class="form-group row mb-3">
                        <label for="event_calendar" class="col-sm-3 control-label">Calendrier*</label>
                        <div class="col-sm-9">
                            <select name="event_calendar" id="event_calendar" class="form-control">
                                {% if access=="config" %}
                                    {% for calendar in calendars %}
                                        <option value='{{ calendar.id}}'>{{ calendar.name}}</option>
                                    {% endfor %}
                                {% else %}
                                    {% for calendar in calendars %}
                                        {% if calendar.canadd %}
                                            <option value='{{ calendar.id}}'>{{ calendar.name}}</option>
                                        {% endif %}
                                    {% endfor %}
                                {% endif %}
                            </select>
                        </div>
                    </div>

                    <div class="form-group row mb-3">
                        <label for="event_title" class="col-sm-3 control-label">Titre*</label>
                        <div class="col-sm-9"><input name="event_title" id="event_title" type="titre" class="form-control focus" placeholder="Titre"></div>
                    </div>

                    <div class="form-group row mb-3">
                        <label for="event_allday" class="col-sm-3 control-label">Evènement sur la journée*</label>
                        <div class="col-sm-9"><input id="event_allday" name="event_allday" type="checkbox" class="switch" onChange="switchallDay('SUBMIT');"></div>
                    </div>

                    <div class="form-group row mb-3" id="form_event_start_time">
                        <label for="date" class="col-sm-3 control-label">Date Début*</label>
                        <div class="col-sm-9"><input name="event_start_time" id="event_start_time" type="titre" class="form-control" placeholder="Date Début" value=""></div>
                    </div>

                    <div class="form-group row mb-3" id="form_event_end_time">
                        <label for="date" class="col-sm-3 control-label">Date Fin*</label>
                        <div class="col-sm-9"><input name="event_end_time" id="event_end_time" type="titre" class="form-control" placeholder="Date Fin" value=""></div>
                    </div>

                    <div class="form-group row mb-3" id="form_event_start">
                        <label for="date" class="col-sm-3 control-label">Date Début*</label>
                        <div class="col-sm-9"><input name="event_start" id="event_start" type="titre" class="form-control" placeholder="Date Début" value=""></div>
                    </div>

                    <div class="form-group row mb-3" id="form_event_end">
                        <label for="date" class="col-sm-3 control-label">Date Fin*</label>
                        <div class="col-sm-9"><input name="event_end" id="event_end" type="titre" class="form-control" placeholder="Date Fin" value=""></div>
                    </div>

                    <div class="form-group row mb-3">
                        <div class="col-sm-12"><textarea style="height:150px" name="event_description" id="event_description-add" type="titre" class="form-control focus" placeholder="Description"></textarea></div>
                    </div>                    
                </div>
            </div>
        </div>
    </div>    


    <!-- UPDATE / DELETE EVENEMENT -->
    <div id="mymodal-event-mod" class="modal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Modification Evénement</h4>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>
                        <input id='vladd' name='vladd' class='btn btn-success' type='submit' onClick='updateEvent();' value='Valider' />
                        <input class="btn btn-primary" type='submit' value='Partager' onClick='shareEvent();' />
                        <input class="btn btn-primary" type='submit' value='Cloner' onClick='showcloneEvent();' />
                        <input class='btn btn-secondary' type='submit' value='Annuler' onClick='$("#mymodal-event-mod").modal("hide");'>

                        <input id='vldel' name='vldel' class='btn btn-danger float-end' type='submit' onClick='deleteEvent();' value='Suppression' />

                        <input name="calendar_id" id="calendar_id" type="hidden" class="form-control" placeholder="Nom">
                        <input name="event_id" id="event_id" type="hidden" class="form-control" placeholder="Nom">
                    </p>

                    <div class="form-group row mb-3">
                        <label for="event_calendar" class="col-sm-3 control-label">Calendrier*</label>
                        <div class="col-sm-9">
                            <select name="event_calendar" id="event_calendar" class="form-control">
                                {% if access=="config" %}
                                    {% for calendar in calendars %}
                                        <option value='{{ calendar.id}}'>{{ calendar.name}}</option>
                                    {% endfor %}
                                {% else %}
                                    {% for calendar in calendars %}
                                        {% if calendar.canadd %}
                                            <option value='{{ calendar.id}}'>{{ calendar.name}}</option>
                                        {% endif %}
                                    {% endfor %}
                                {% endif %}
                            </select>
                        </div>
                    </div>

                    <div class="form-group row mb-3">
                        <label for="event_title" class="col-sm-3 control-label">Titre*</label>
                        <div class="col-sm-9"><input name="event_title" id="event_title" type="titre" class="form-control focus" placeholder="Titre"></div>
                    </div>


                    <div class="form-group row mb-3">
                        <label for="event_allday" class="col-sm-3 control-label">Evènement sur la journée*</label>
                        <div class="col-sm-9"><input id="event_allday" name="event_allday" type="checkbox" class="switch" onChange="switchallDay('UPDATE');"></div>
                    </div>

                    <div class="form-group row mb-3" id="form_event_start_time">
                        <label for="date" class="col-sm-3 control-label">Date Début*</label>
                        <div class="col-sm-9"><input name="event_start_time" id="event_start_timem" type="titre" class="form-control" placeholder="Date Début" value=""></div>
                    </div>

                    <div class="form-group row mb-3" id="form_event_end_time">
                        <label for="date" class="col-sm-3 control-label">Date Fin*</label>
                        <div class="col-sm-9"><input name="event_end_time" id="event_end_timem" type="titre" class="form-control" placeholder="Date Fin" value=""></div>
                    </div>

                    <div class="form-group row mb-3" id="form_event_start">
                        <label for="date" class="col-sm-3 control-label">Date Début*</label>
                        <div class="col-sm-9"><input name="event_start" id="event_startm" type="titre" class="form-control" placeholder="Date Début" value=""></div>
                    </div>

                    <div class="form-group row mb-3" id="form_event_end">
                        <label for="date" class="col-sm-3 control-label">Date Fin*</label>
                        <div class="col-sm-9"><input name="event_end" id="event_endm" type="titre" class="form-control" placeholder="Date Fin" value=""></div>
                    </div>

                    <div class="form-group row mb-3">
                        <div class="col-sm-12"><textarea  style="height:150px" name="event_description" id="event_description-mod" type="titre" class="form-control focus" placeholder="Description"></textarea></div>
                    </div>

                    <div id="event_PJ"></div>
                </div>
            </div>
        </div>
    </div>    


    <!-- CLONE EVENEMENT -->
    <div id="mymodal-event-clone" class="modal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Cloner Evénement</h4>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>
                        <input id='vladd' name='vladd' class='btn btn-success' type='submit' onClick='cloneEvent();' value='Valider' />
                        <input class='btn btn-secondary' type='submit' value='Annuler' onClick='$("#mymodal-event-clone").modal("hide");'>

                        <input name="event_calendar" id="event_calendar" type="hidden" class="form-control" placeholder="Nom">
                        <input name="event_id" id="event_id" type="hidden" class="form-control" placeholder="Nom">
                        <input name="event_title" id="event_title" type="hidden" class="form-control" placeholder="Titre" value="">
                        <input name="event_description" id="event_description" type="hidden" class="form-control" placeholder="Titre" value="">
                        <input name="event_start_time" id="event_start_timem" type="hidden" class="form-control" placeholder="Date Début" value="">
                        <input name="event_end_time" id="event_end_timem" type="hidden" class="form-control" placeholder="Date Fin" value="">
                        <input name="event_start" id="event_startm" type="hidden" class="form-control" placeholder="Date Début" value="">
                        <input name="event_end" id="event_endm" type="hidden" class="form-control" placeholder="Date Fin" value="">
                        <input id="event_allday" name="event_allday" type="hidden" class="switch">
                    </p>

                    <div id="event_dates"></div>
                </div>
            </div>
        </div>
    </div>    
{% endblock %}

{% block localexternalscript %}
    <script type="text/javascript" src="{{ asset('ckeditor/ckeditor.js') }}"></script>
    <script type="text/javascript" src="{{ asset('ckeditor/adapters/jquery.js') }}"></script>
    <script type="text/javascript" src="{{ asset('js/jquery-ui.multidatespicker-1.6.4.js') }}"></script>
    <link href="{{ asset('css/jquery-ui.multidatespicker-1.6.4.css') }}" rel="stylesheet" media="screen" />
{% endblock %}

{% block localjavascript %}
    var idcalendar;
    var toaddPJ;
    var toaddPJevent;

    var defautView='month';
    {% if app.user %}
        {% if app.user.viewcalendar == 2 %}
            var defautView='agendaWeek';
        {% elseif app.user.viewcalendar == 3 %}
            var defautView='agendaDay';
        {% endif %}    
    {% endif %}

    $('document').ready(function(){
        CKEDITOR.config.toolbar_Basic =
        [
            { name: 'document', items : ['Bold','Italic','Underline','-', 'NumberedList','BulletedList','-', 'Link'] },
        ];
        CKEDITOR.config.toolbar = 'Basic';
        CKEDITOR.config.height = '100';
        CKEDITOR.config.removePlugins = 'elementspath,save,font, resize';

        CKEDITOR.replace( 'event_description-add' );
        CKEDITOR.replace( 'event_description-mod' );

        {% if entity.id is defined %}
            {% for calendar in calendars %} 
                {% if calendar.id==entity.id %}
                    {% if access=="config" %}
                        {% set calendarcanadd=true %}
                    {% else %}
                        {% set calendarcanadd=calendar.canadd %}
                    {% endif %}
                    showCalendar({{ calendar.id }}, {{ calendarcanadd }});
                {% endif %}
            {% endfor %}
        {% else %}
            {% set onecalendarcanupdate = false %}
            {% for calendar in calendars %} 
                {% if calendar.canadd %}
                    {% set onecalendarcanupdate = true %}
                {% endif %}
            {% endfor %}

            showCalendar(0, {{ onecalendarcanupdate }});
        {% endif %}  
    });

    function submitCalendar() {
        var url="{{ path('app_portal_'~access~'_calendar_submit') }}";
        $(location).attr('href',url);
    }  

    function updateCalendar() {
        var url="{{ path('app_portal_'~access~'_calendar_update',{id:'xx'}) }}";
        url=url.replace('xx',idcalendar);

        $(location).attr('href',url);
    }    

    function shareCalendar() {
        var url="{{ path('app_portal_'~access~'_calendar_share',{id:'xx'}) }}";
        url=url.replace('xx',idcalendar);

        $(location).attr('href',url);
    } 

    function deleteCalendar() {
        if (confirm('Êtes-vous sûr de vouloir supprimer ?')) {
            var url="{{ path('app_portal_'~access~'_calendar_delete',{id:'xx'}) }}";
            url=url.replace('xx',idcalendar);

            $(location).attr('href',url);
        }
    } 


    // Affichages des calendars
    var calendar;
    function showCalendar(id,canadd) {
        idcalendar=id;
        urltoload="{{ path('app_portal_'~access~'_calendarevent_load',{'idcalendar':'xx'}) }}";
        urltoload=urltoload.replace('xx',idcalendar);

        // Rendre actif le page en cours dans le menu
        $(".navbar-default li").removeClass("active");
        $("#menucalendar-"+id).addClass("active");

        // Cacher les actions possibles sur la page
        $("#menuupdate").hide();
        $("#menushare").hide();
        $("#menudelete").hide();

        if($("#menucalendar-"+id).data("open")) {
            $("#menuupdate").show();
            $("#menushare").show();
            $("#menudelete").show();
        }

        var calendarEl = document.getElementById('calendar');
        calendar = new FullCalendar.Calendar(calendarEl, {
            headerToolbar: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
            },
            locale: 'fr',
            buttonIcons: true,
            weekNumbers: false,
            navLinks: true, // can click day/week names to navigate views
            editable: true,
            dayMaxEvents: true, // allow "more" link when too many events

            // Source Evenement
            eventSources: [{
                'id': 1,
                'url': urltoload,
            }],

            // Render Evenement
            eventDidMount: function(info) {
                $(info.el).attr('title', info.event.extendedProps.description.replace(/<[^>]+>/g, ''));
                $(info.el).attr('id', "event-" + info.event.id);
            },

			// Creation Evenement
            selectable: canadd,
			select: function(info) {
			    {% if app.user %}
                    var start=moment(info.start);
                    var end=moment(info.end);
                    allDay=(start.format("DD/MM/YYYY") != end.format("DD/MM/YYYY"));

			        $("#mymodal-event-add #event_title").val("");
                    CKEDITOR.instances["event_description-add"].setData("")
				    $("#mymodal-event-add #event_start_time").val(moment(start).format("DD/MM/YYYY HH:mm"));
				    $("#mymodal-event-add #event_end_time").val(moment(end).format("DD/MM/YYYY HH:mm"));
				    $("#mymodal-event-add #event_start").val(moment(start).format("DD/MM/YYYY"));
				    $("#mymodal-event-add #event_end").val(moment(end).subtract("1","s").format("DD/MM/YYYY"));
					if(allDay) $("#mymodal-event-add #event_end_time").val(moment(end).subtract("1","s").format("DD/MM/YYYY HH:mm"));
                    $("#mymodal-event-add #event_calendar option[value='"+idcalendar+"']").prop('selected', true);

				    $("#mymodal-event-add #event_allday").bootstrapSwitch('state', allDay);
				    switchallDay("SUBMIT");
			        $('#mymodal-event-add').modal('show');
                {% endif %}
			},    

            // Modification Evenement
            editable: canadd,
            eventClick: function(info) {
                event=info.event;
                if(event.durationEditable) {
                    var start=moment(event.start);
                    var end=moment(event.end);

			        $("#mymodal-event-mod #event_id").val(event.id);
			        $("#mymodal-event-mod #event_title").val(event.title);
                    CKEDITOR.instances["event_description-mod"].setData(event.extendedProps.description)
				    $("#mymodal-event-mod #event_start_timem").val(start.format("DD/MM/YYYY HH:mm"));
				    $("#mymodal-event-mod #event_end_timem").val(end.format("DD/MM/YYYY HH:mm"));
				    $("#mymodal-event-mod #event_startm").val(start.format("DD/MM/YYYY"));
				    $("#mymodal-event-mod #event_endm").val(end.subtract("1","s").format("DD/MM/YYYY"));
				    $("#mymodal-event-mod #event_allday").bootstrapSwitch('state', event.allDay);
                    $("#mymodal-event-mod #event_calendar").val(event.extendedProps.calendar);

                    $("#mymodal-event-clone #event_id").val(event.id);
                    $("#mymodal-event-clone #event_title").val(event.title);
                    $("#mymodal-event-clone #event_description").val(event.extendedProps.description);
				    $("#mymodal-event-clone #event_start_timem").val(start.format("HH:mm"));
				    $("#mymodal-event-clone #event_end_timem").val(end.format("HH:mm"));
				    $("#mymodal-event-clone #event_startm").val(start.format("DD/MM/YYYY"));
				    $("#mymodal-event-clone #event_endm").val(end.format("DD/MM/YYYY"));
                    $("#mymodal-event-clone #event_allday").val(event.allDay);
                    $("#mymodal-event-clone #event_calendar").val(event.extendedProps.calendar);

                    refreshPJ();

				    switchallDay("UPDATE");
                    $('#mymodal-event-mod').modal('show');
                }
            },    

            // Resize Evenement
            eventResize: function(info) {
                event=info.event;
                start=moment(event.start);
                end=moment(event.end);
                $.ajax({
                    method: "POST",
                    url: "{{ path('app_portal_'~access~'_calendarevent_update') }}",
                    data: {
                        "id": event.id,
                        "title": event.title,
                        "description":event.extendedProps.description,
                        "start": start.format("YYYY-MM-DD HH:mm"),
                        "end": end.format("YYYY-MM-DD HH:mm"),
                        "allday": event.allDay,
                        "idcalendar": event.extendedProps.calendar
                    }
                });
            },     

            // Deplacement Evenement
            eventDrop: function(info) {
                event=info.event;
                start=moment(event.start);
                end=moment(event.end);                
                $.ajax({
                    method: "POST",
                    url: "{{ path('app_portal_'~access~'_calendarevent_update') }}",
                    data: {
                        "id": event.id,
                        "title": event.title,
                        "description":event.extendedProps.description,
                        "start": start.format("YYYY-MM-DD HH:mm"),
                        "end": end.format("YYYY-MM-DD HH:mm"),
                        "allday": event.allDay,
                        "idcalendar": event.extendedProps.calendar
                    }
                });
            },                       
        });

        calendar.render();
    }

    function switchallDay(form) {
        if(form=="SUBMIT") {
            if($("#mymodal-event-add #event_allday").bootstrapSwitch('state')) {
				$("#mymodal-event-add #form_event_start_time").hide();
				$("#mymodal-event-add #form_event_end_time").hide();
				$("#mymodal-event-add #form_event_start").show();
				$("#mymodal-event-add #form_event_end").show();
            }
            else {
				$("#mymodal-event-add #form_event_start_time").show();
				$("#mymodal-event-add #form_event_end_time").show();
				$("#mymodal-event-add #form_event_start").hide();
				$("#mymodal-event-add #form_event_end").hide();
			}
        }
        else if(form=="UPDATE") {
            if($("#mymodal-event-mod #event_allday").bootstrapSwitch('state')) {
				$("#mymodal-event-mod #form_event_start_time").hide();
				$("#mymodal-event-mod #form_event_end_time").hide();
				$("#mymodal-event-mod #form_event_start").show();
				$("#mymodal-event-mod #form_event_end").show();
            }
            else {
				$("#mymodal-event-mod #form_event_start_time").show();
				$("#mymodal-event-mod #form_event_end_time").show();
				$("#mymodal-event-mod #form_event_start").hide();
				$("#mymodal-event-mod #form_event_end").hide();
			}
        }
    }

    function submitEvent(addPJ) {
        $("#mymodal-event-add .alert").remove();
        if($("#mymodal-event-add #event_title").val()=="") {
            $("#mymodal-event-add fieldset").append("<div class='alert alert-danger' style='margin: 5px 0px'>Titre obligatoire</div>");
            return;
        }

        // Allday
        if($("#mymodal-event-add #event_allday").bootstrapSwitch('state')) {
            var start=moment($("#mymodal-event-add #event_start").val(),"DD/MM/YYYY");
            var end=moment($("#mymodal-event-add #event_end").val(),"DD/MM/YYYY").add("1","d");

            if( start.isAfter(end) ) {
                $("#mymodal-event-add fieldset").append("<div class='alert alert-danger' style='margin: 5px 0px'>Date de début supérieure à date de fin</div>");
                return;
            }

            var dstart=moment($("#mymodal-event-add #event_start").val(),"DD/MM/YYYY").format("YYYY-MM-DD 00:00");
            var dend=moment($("#mymodal-event-add #event_end").val(),"DD/MM/YYYY").add("1","d").format("YYYY-MM-DD 00:00");
        }
        else {
            var start=moment($("#mymodal-event-add #event_start_time").val(),"DD/MM/YYYY HH:mm");
            var end=moment($("#mymodal-event-add #event_end_time").val(),"DD/MM/YYYY HH:mm");

            if( start.isAfter(end) ) {
                $("#mymodal-event-add fieldset").append("<div class='alert alert-danger' style='margin: 5px 0px'>Date de début supérieure à date de fin</div>");
                return;
            }

            var dstart=moment($("#mymodal-event-add #event_start_time").val(),"DD/MM/YYYY HH:mm").format("YYYY-MM-DD HH:mm");
            var dend=moment($("#mymodal-event-add #event_end_time").val(),"DD/MM/YYYY HH:mm").format("YYYY-MM-DD HH:mm");
        }

        $.ajax({
            method: "POST",
            url: "{{ path('app_portal_'~access~'_calendarevent_submit') }}",
            data: {
                "title":$("#mymodal-event-add #event_title").val(),
                "description":CKEDITOR.instances["event_description-add"].getData(),
                "start": dstart,
                "end": dend,
                "allday": $("#mymodal-event-add #event_allday").bootstrapSwitch('state'),
                "idcalendar": $("#mymodal-event-add #event_calendar").val()
            },
            success: function(data) {
                calendar.refetchEvents();
                toaddPJ=addPJ;
                toaddPJevent=data.id;
                $("#mymodal-event-add").modal("hide");
            }
        });
    }


    function updateEvent() {
        $("#mymodal-event-mod .alert").remove();
        if($("#mymodal-event-mod #event_title").val()=="") {
            $("#mymodal-event-mod fieldset").append("<div class='alert alert-danger' style='margin: 5px 0px'>Titre obligatoire</div>");
            return;
        }

        // Allday
        if($("#mymodal-event-mod #event_allday").bootstrapSwitch('state')) {
            var start=moment($("#mymodal-event-mod #event_startm").val(),"DD/MM/YYYY");
            var end=moment($("#mymodal-event-mod #event_endm").val(),"DD/MM/YYYY").add("1","d");

            if( start.isAfter(end) ) {
                $("#mymodal-event-mod fieldset").append("<div class='alert alert-danger' style='margin: 5px 0px'>Date de début supérieure à date de fin</div>");
                return;
            }

            var dstart=moment($("#mymodal-event-mod #event_startm").val(),"DD/MM/YYYY").format("YYYY-MM-DD 00:00");
            var dend=moment($("#mymodal-event-mod #event_endm").val(),"DD/MM/YYYY").add("1","d").format("YYYY-MM-DD 00:00");
        }
        else {
            var start=moment($("#mymodal-event-mod #event_start_timem").val(),"DD/MM/YYYY HH:mm");
            var end=moment($("#mymodal-event-mod #event_end_timem").val(),"DD/MM/YYYY HH:mm");

            if( start.isAfter(end) ) {
                $("#mymodal-event-mod fieldset").append("<div class='alert alert-danger' style='margin: 5px 0px'>Date de début supérieure à date de fin</div>");
                return;
            }

            var dstart=moment($("#mymodal-event-mod #event_start_timem").val(),"DD/MM/YYYY HH:mm").format("YYYY-MM-DD HH:mm");
            var dend=moment($("#mymodal-event-mod #event_end_timem").val(),"DD/MM/YYYY HH:mm").format("YYYY-MM-DD HH:mm");
        }


        $.ajax({
            method: "POST",
            url: "{{ path('app_portal_'~access~'_calendarevent_update') }}",
            data: {
                "id": $("#mymodal-event-mod #event_id").val(),
                "title":$("#mymodal-event-mod #event_title").val(),
                "description":CKEDITOR.instances["event_description-mod"].getData(),
                "start": dstart,
                "end": dend,
                "allday": $("#mymodal-event-mod #event_allday").bootstrapSwitch('state'),
                "idcalendar": $("#mymodal-event-mod #event_calendar").val()                
            },
            success: function(data) {
                calendar.refetchEvents();
                $("#mymodal-event-mod").modal("hide");               
            }
        });
    }  

    function AddPJ() {
        $('#mymodal-event-mod').modal('hide');
        url='{{ path('app_core_'~access~'_file_upload',{'id': 'calendarevent-xxxx','type':'all','forcereload':false}) }}';
        url=url.replace('xxxx',$("#mymodal-event-mod #event_id").val());

        $("#mymodal").modal('show');
        ModalLoad('mymodal','Fichiers',url);
    }

    function shareEvent() {
        var id=$("#mymodal-event-mod #event_id").val();

        var url="{{ path('app_portal_'~access~'_calendarevent_share',{id:'xx'}) }}";
        url=url.replace('xx',id);

        $(location).attr('href',url);
    } 

    function showcloneEvent() {
        $("#mymodal-event-mod").modal("hide");
        $("#mymodal-event-clone").modal("show");


        $('#mymodal-event-clone #event_dates').multiDatesPicker({
            firstDay: 1,
            altField: "#datepicker",
            closeText: 'Fermer',
            prevText: 'Précédent',
            nextText: 'Suivant',
            currentText: 'Aujourd\'hui',
            monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
            monthNamesShort: ['Janv.', 'Févr.', 'Mars', 'Avril', 'Mai', 'Juin', 'Juil.', 'Août', 'Sept.', 'Oct.', 'Nov.', 'Déc.'],
            dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
            dayNamesShort: ['Dim.', 'Lun.', 'Mar.', 'Mer.', 'Jeu.', 'Ven.', 'Sam.'],
            dayNamesMin: ['D', 'L', 'M', 'M', 'J', 'V', 'S'],
            weekHeader: 'Sem.',
            dateFormat: 'yy-mm-dd',

        });
        $('#mymodal-event-clone #event_dates').multiDatesPicker('resetDates')
    } 

    function cloneEvent() {
        var dates = $('#mymodal-event-clone #event_dates').multiDatesPicker('value');
        dates=dates.replace(/\s/g, '');
        tbdates=dates.split(',');
        
        var dstart=moment($("#mymodal-event-clone #event_startm").val(),"DD/MM/YYYY");
        var tstart=$("#mymodal-event-clone #event_start_timem").val();
        var dend=moment($("#mymodal-event-clone #event_endm").val(),"DD/MM/YYYY");
        var tend=$("#mymodal-event-clone #event_end_timem").val();

        var nbdays=dend.diff(dstart, 'days');

        if($("#mymodal-event-clone #event_allday").val()=="true")
            allDay=true;
        else
            allDay=false;
        
        tbdates.forEach(function(date){
            var mdatestart=moment(date +' '+tstart,"YYYY-MM-DD HH:mm");
            var mdateend=moment(date +' '+tend,"YYYY-MM-DD HH:mm");
            mdateend.add(nbdays,'days');
            start=mdatestart.format("YYYY-MM-DD HH:mm");
            end=mdateend.format("YYYY-MM-DD HH:mm");

            $.ajax({
                method: "POST",
                url: "{{ path('app_portal_'~access~'_calendarevent_submit') }}",
                data: {
                    "title":$("#mymodal-event-clone #event_title").val(),
                    "description":$("#mymodal-event-clone #event_description").val(),
                    "start": start,
                    "end": end,
                    "allday": $("#mymodal-event-clone #event_allday").val(),
                    "idcalendar": $("#mymodal-event-clone #event_calendar").val()
                },
                success: function(data) {
                    calendar.refetchEvents();
                    $("#mymodal-event-clone").modal("hide");
                }
            });            
        });        
    }

    function deleteEvent() {

        $.ajax({
            method: "POST",
            url: "{{ path('app_portal_'~access~'_calendarevent_delete') }}",
            data: {
                "id": $("#mymodal-event-mod #event_id").val(),
                "idcalendar": $("#mymodal-event-mod #event_calendar").val()                
            },
            success: function(data) {
                calendar.refetchEvents();
                $("#mymodal-event-mod").modal("hide");               
            }
        });
    }      

    // Supprimer un fichier 
    function delFile(directory,filename) {
        var r = confirm("Confirmez-vous la suppression de ce fichier ?");
        if (r == true) {        
            $.ajax({
                method: "POST",
                url: "{{ path('app_core_'~access~'_file_delete') }}",
                data: {
                    directory:directory,
                    filename:filename
                },
                success: function() {
                    refreshPJ();
                }            
            });        
        }
    }

    $(document).on('mouseenter', '.grid-item-content', function(){
        $(this).children(".item-delete").show();
    });   
    $(document).on('mouseleave', '.grid-item-content', function(){
        $(this).children(".item-delete").hide();
    });     

    $('#mymodal-event-add').on('hidden.bs.modal', function() {        
        if(toaddPJ) {
            $("#mymodal-event-mod #event_id").val(toaddPJevent);
            AddPJ();     
        }
        toaddPJ=false;
    });

    $('#mymodal-event-mod').on('shown.bs.modal', function() { 
        $('body').imagesLoaded(function() {
            var optiongrid={columnWidth: '.grid-sizer',itemSelector: '.grid-item', gutter: '.grid-gutter-sizer'};
            var grid = $('.grid').masonry(optiongrid);        
        });    
    });
  
    function refreshPJ() {
        $.ajax({
            method: "POST",
            url: "{{ path('app_portal_'~access~'_calendarevent_loadpj') }}",
            data: {
                "id": $("#mymodal-event-mod #event_id").val()
            },
            success: function(data) {
                htmlPJ(data);
            }
        });        
    }

    $('#mymodal').on('hidden.bs.modal', function() { 
        $("#mymodal-event-mod").modal("show"); 
        var optiongrid={columnWidth: '.grid-sizer',itemSelector: '.grid-item', gutter: '.grid-gutter-sizer'};
        var grid = $('.grid').masonry(optiongrid);                  
    });

    function htmlPJ(files) {
        html ='<div class="grid clearfix">';
        html+='<div class="grid-sizer  grid-small"></div>';
        html+='<div class="grid-gutter-sizer"></div>';
        files.forEach(function(file) {
            url="{{ path('app_core_'~access~'_file_download',{'directory':'calendarevent-xxxx','filename':'yyyy' }) }}";
            url=url.replace("xxxx",$("#mymodal-event-mod #event_id").val());
            url=url.replace("yyyy",file.name);

            html+='<div class="grid-item grid-small">';
            html+='<div class="grid-item-content" style="background-color: #{{ color["main"]}}">';
            html+='<a  style="cursor:pointer;color: #{{color['fontcolorhover']}}" onClick="delFile(\'calendarevent-'+$("#mymodal-event-mod #event_id").val()+'\',\''+file.name+'\')" class="item-delete">';
            html+='<i class="fa fa-trash" title="Supprimer le fichier"></i>';
            html+='</a>';
            html+='<a style="cursor:pointer" href="'+url+'">';
            html+='<div class="item-link clearfix">';
            html+='<div class="grid-item-logo">';
            if(file.thumb)
                html+='<img class="grid-item-img" height="110" src="'+file.thumb+'">';
            else 
                html+='<img class="grid-item-img" height="110" src="{{ asset('images/files/_blank.png') }}">';
            html+='</div>';
            html+='<div class="grid-item-title">';
            html+='<h2>'+file.name+'</h2>';
            html+='</div>';                  
            html+='</div>';
            html+='</a>';
            html+='</div>';
            html+='</div>';
        });    

        html+='<div class="grid-item grid-small">'
        html+='<div onClick="AddPJ();" title="Ajouter des fichiers" class="grid-item-content" style="cursor:pointer;margin-top:20px;">';
        html+='<img class="grid-item-img imageshadow" height="60" src="{{ asset('uploads/icon/icon_add.png') }}">';
        html+='<br>Ajouter des fichiers';
        html+='</div>';
        html+='</div>';

        html+='</div>';                      
        html+='</div>';                        
        html+='</div>';

        // On ajoute les PJ à la modal
        $("#mymodal-event-mod #event_PJ").html("");
        $("#mymodal-event-mod #event_PJ").append(html);        
    }

{% endblock %}
