
      <script>

      //import deLocale from '@fullcalendar/core/locales/de';
      document.addEventListener('DOMContentLoaded', function() {
	  var calendarEl = document.getElementById('calendar');
	  var cal = <f:format.raw>{calendar.rawFullCalendar->f:format.json()}</f:format.raw>;

      if($(window).width() < 601) {
          cal.defaultView = 'timeGridDay';
      }

	  window.fullCalendar = new FullCalendar.Calendar(calendarEl, {
          //timeZone: 'UTC',
	      plugins: [ 'interaction', 'dayGrid', 'timeGrid', 'moment' ],
          views: {
              week: {
                  titleFormat: 'D. MMM YYYY',
              }
          },
	      header: {
		  left: 'prev,next today',
		  center: 'title',
		  right: 'dayGridMonth,timeGridWeek,timeGridDay'
	      },
	      contentHeight: 'auto',
	      allDaySlot: false,
	      locale: 'de', // the initial locale. of not specified, uses the first one
	      //eventTextColor: 'rgb(0, 0, 0)',
              //eventBackgroundColor: 'rgb(255, 158, 129)',
	      //eventBorderColor: 'rgb(255, 79, 64)',
	      //defaultView: 'timeGridWeek',
		  <f:if condition="{search.date}">
		  defaultDate: '{search.date}',
	      </f:if>
	      defaultView: cal.defaultView,
	      slotDuration: cal.slotDuration,
	      minTime: cal.minTime,
	      maxTime: cal.maxTime,
	      validRange: {
		  start: cal.validRange.start,
		  end: cal.validRange.end,
	      },
	      selectConstraint: {
		  start: cal.selectConstraint.start,
		  end: cal.selectConstraint.end,
	      },
	      navLinks: true, // can click day/week names to navigate views
		  <cal:calendar.hasPermission calendar="{calendar}" permission="read">
          <f:then>
	      selectable: false,
          editable: false,
          </f:then>
          <f:else>
	      selectable: true,
          editable: true,
          </f:else>
          </cal:calendar.hasPermission>
	      selectOverlap: true,
	      selectMirror: true,
		  <cal:calendar.hasPermission calendar="{calendar}" permission="team,read,user">
	      eventClick: function(info) {
              <cal:calendar.isAdmin calendar="{calendar}">
                <f:else>
                    if(info.event.extendedProps.hasReservationForUser) {
                </f:else>
              </cal:calendar.isAdmin>
        		  var calendar = "<f:format.raw>{calendar.uid}</f:format.raw>";
        		  var $calendar = $('.calendar-' + calendar);
        		  var commandUrl = $calendar.data('url');
        		  //console.log('Event: ' + info.event.title);
        		  $.ajax({
                      url: commandUrl,
                      method: 'post',
                      dataType: "json",
                      data: {
            			  "tx_igreservations_ajax": {
            			      controller: 'Ajax',
            			      action: 'eventShow',
            			      event: info.event.id
            			      //date: '2020-06-19',
            			      //timeslot: 2
            			  }
                      },
        		      success: function(data) {
            			  // on success, post (preview) returned data in fancybox	    //context: document.body
            			  $.fancybox.open(data.html, {
                              // fancybox API options
                              fitToView: true,
                              afterShow: function(instance, current) {
				                  $('.calendar-confirm', current.$content).on('click', window.initDeleteConfirm );
            			      }
            			  });
        		      }
        		  });
              <cal:calendar.isAdmin calendar="{calendar}">
                <f:else>
                }
                </f:else>
              </cal:calendar.isAdmin>
		  //    alert('Coordinates: ' + info.jsEvent.pageX + ',' + info.jsEvent.pageY);
		  //alert('View: ' + info.view.type);

		  // change the border color just for fun
		  //info.el.style.borderColor = 'red';
	      },
		  </cal:calendar.hasPermission>
	      select: function(arg) {
		  var calendar = "<f:format.raw>{calendar.uid}</f:format.raw>";
		  var $calendar = $('.calendar-' + calendar);

		  if(window.fullCalendar.view.type=='dayGridMonth')
		  {
		      // Monat Ansicht select verbieten
		      window.fullCalendar.unselect();
		      return false;
		      // nono
		  } else {
		      var commandUrl = $calendar.data('url');
              <f:if condition="{calendar.acl} && {calendar.acl.minimumBlockDuration}">
                  var minimumBlockDuration = 60 * 60 * 1000 * <f:format.raw>{calendar.acl.minimumBlockDuration}</f:format.raw>;
                  if(arg.end - arg.start < minimumBlockDuration) {
                      toastr.options = {
                          "closeButton": true
                      };
                          //$newContent.hasClass('ajax-error')
                      toastr.options.timeOut = 0; // Show errors forever
                      toastr['error']('<f:translate key="toastr.minimum_block_duration.message" arguments="{0: calendar.acl.minimumBlockDuration}" />', '<f:translate key="toastr.minimum_block_duration.title" />');
                      window.fullCalendar.unselect();
                      return false;
                  }
              </f:if>
              <f:if condition="{calendar.acl} && {calendar.acl.maximumBlockDuration}">
                  var maximumBlockDuration = 60 * 60 * 1000 * <f:format.raw>{calendar.acl.maximumBlockDuration}</f:format.raw>;
                  if(arg.end - arg.start > maximumBlockDuration) {
                      toastr.options = {
                          "closeButton": true
                      };
                          //$newContent.hasClass('ajax-error')
                      toastr.options.timeOut = 0; // Show errors forever
                      toastr['error']('<f:translate key="toastr.maximum_block_duration.message" arguments="{0: calendar.acl.maximumBlockDuration}" />', '<f:translate key="toastr.maximum_block_duration.title" />');
                      window.fullCalendar.unselect();
                      return false;
                  }
              </f:if>
		      $.ajax({
			  url: commandUrl,
			  method: 'post',
			  dataType: "json",
			  data: {
			      "tx_igreservations_ajax": {
				  controller: 'Ajax',
				  action: 'reservationCreateFormStartEnd',
				  calendar: calendar,
				  eventStart: arg.start.toUTCString(),
				  eventEnd: arg.end.toUTCString(),
			      }
			  },
			  success: function(data) {
			      // on success, post (preview) returned data in fancybox	    //context: document.body
			      $.fancybox.open(data.html, {
                    touch: false,
                    keyboard: false,
				  // fancybox API options
				  fitToView: true,
				  afterShow: function(instance, current) {
                        IGDATAPOOLFE.addForm($('.dp-form', current.$content).get(0), 'lightbox');
                      /*if($('#dp-field-ckeditor-description', ).length) {
                        ClassicEditor
                            .create(document.getElementById('dp-field-ckeditor-description'));
                          //CKEDITOR.replace( 'dp-field-ckeditor-description' );
                      } else if($('#dp-field-ckeditor-event-description', current.$content).length) {
                          ClassicEditor
                              .create(document.querySelector('#dp-field-ckeditor-event-description'));
                          //CKEDITOR.replace( 'dp-field-ckeditor-event.description' );
                      }*/
				      //console.log('ok');
                      $('form .repetition-select select', current.$content).change(
                          function(event) {
                              if($(this).val() != 'None') {
                                  $('.rooms-checkboxes').hide();
                              } else {
                                  $('.rooms-checkboxes').show();
                              }
                          }
                      );
                      $('form .rooms-checkboxes input[type="checkbox"]', current.$content).click(
                          function(event) {
                              var isChecked = false;
                              $('form .rooms-checkboxes input[type="checkbox"]').each(function() {
                                  if($(this).is(':checked')) {
                                      isChecked = true;
                                  }
                              });
                              if(isChecked) {
                                  $('.repetition-select').hide();
                              } else {
                                  $('.repetition-select').show();
                              }
                          }
                      );
                      if($('form #reservations-hasBillAddress', current.$content).length) {
                          var $billAddressField = $('form #reservations-hasBillAddress', current.$content);
                          if($billAddressField.is(':checked')) {
                              $('form .bill-field', current.$content).addClass('show');
                              $('form .bill-field input[type="text"]', current.$content).attr('required', true);
                              $('form .bill-field input[type="text"]', current.$content).prop('required', true);
                          }
                          $billAddressField.on('change', function(e) {
                              $('form .bill-field', current.$content).removeClass('show');
                              $('form .bill-field input[type="text"]', current.$content).attr('required', false);
                              $('form .bill-field input[type="text"]', current.$content).prop('required', false);

                              if($(this).is(':checked')) {
                                  $('form .bill-field', current.$content).addClass('show');
                                  $('form .bill-field input[type="text"]', current.$content).attr('required', true);
                                  $('form .bill-field input[type="text"]', current.$content).prop('required', true);
                              }
                          });
                      }
				      $('form', current.$content).unbind('submit');
				      $('form', current.$content).submit(
					  function(event) {
                          $('.reservation-form input[type="submit"]').attr('disabled', true);
                          $('.reservation-form input[type="submit"]').prop('disabled', true);
					      event.preventDefault();
					      var noErrors = window.validateReservationForm(this);
					      if (!noErrors) {
						  return false;
					      }					      
					      var $form = $(this);
					      //console.log('todo cal');
					      $.ajax({
						  url: $form.attr('action'),
						  method: 'post',
						  dataType: "json",
						  data: $form.serialize(),
                          success: function(data) {
                              if(typeof data.errors != 'undefined' && data.errors.length) {
                                  $('.reservation-form .error').removeClass('error');
                                  for(var i = 0; i < data.errors.length; i++) {
                                      $('.reservation-form [name="tx_igreservations_ajax' + data.errors[i] + '"]').addClass('error');
                                  }
                                  $('.reservation-form input[type="submit"]').attr('disabled', false);
                                  $('.reservation-form input[type="submit"]').prop('disabled', false);
                              } else {
                                  parent.jQuery.fancybox.getInstance().close();
                              }
                    		  <cal:calendar.hasPermission calendar="{calendar}" permission="team,read">
                                if($(calendarEl).data('afterBookingRedirectUrl')) {
                                    window.location.href = $(calendarEl).data('afterBookingRedirectUrl');
                                }
                              </cal:calendar.hasPermission>
                              window.fullCalendar.refetchEvents();
                          }
					      });
					      var title = 'Reserviert';

                          var $select = $form.find('select[name="tx_igreservations_ajax[reservation][event][endTime]"]');

                          if($select.length) {
                              var selectedTime = $form.find('select[name="tx_igreservations_ajax[reservation][event][endTime]"]').val();
                              var selectedTimeArray = selectedTime.split(':');

                              arg.end.setHours(selectedTimeArray[0]);
                              arg.end.setMinutes(selectedTimeArray[1]);
                              arg.end.setSeconds(selectedTimeArray[2]);
                          }

					      /*window.fullCalendar.addEvent({
						  title: title,
						  start: arg.start,
						  end: arg.end,
						  classNames: ["event-status-red","event-status-new"],
						  allDay: false
                          });*/
					      window.fullCalendar.unselect()
					  }
				      );

				      //	  self.fancyboxAfterShow(instance, current, '#timeslot-' + command.args.calendar + '-' + command.args.date + '-' + command.args.timeslot)
				  }
			      });
			  }
		      });
		  }
	      },
          <cal:calendar.isAdmin calendar="{calendar}">
            eventDrop: eventMove,
            eventResize: eventMove,
          </cal:calendar.isAdmin>
	      eventLimit: true, // allow "more" link when too many events
          eventSources: [
              {
                  id: 1,
                  url: "<f:format.raw>{f:uri.action(pageType: 9190501, action: 'getEvents', pluginName: 'Ajax', controller: 'Ajax', pageUid: settings.calendarAjaxPageUid)}</f:format.raw>",
                  startParam: 'tx_igreservations_ajax[search][startDateAndTime]',
                  endParam: 'tx_igreservations_ajax[search][endDateAndTime]',
                  method: 'POST',
                  extraParams: function() {
                      return {
                          'tx_igreservations_ajax[calendar]': <f:format.raw>{calendar.uid}</f:format.raw>,
                          'tx_igreservations_ajax[search][location]': $('[name="tx_igreservations_publiccalendar[search][location]"]').length ? $('[name="tx_igreservations_publiccalendar[search][location]"]').val() : '',
                          'tx_igreservations_ajax[search][bookingType]': $('[name="tx_igreservations_publiccalendar[search][bookingType]"]').length ? $('[name="tx_igreservations_publiccalendar[search][bookingType]"]').val() : '',
                          'tx_igreservations_ajax[search][owner]': $('[name="tx_igreservations_publiccalendar[search][owner]"]').length ? $('[name="tx_igreservations_publiccalendar[search][owner]"]').val() : '',
                          'tx_igreservations_ajax[search][status]': $('[name="tx_igreservations_publiccalendar[search][status]"]').length ? $('[name="tx_igreservations_publiccalendar[search][status]"]').val() : '',
                      };
                  }
              }
          ],
	  });
      function eventMove(eventInfo) {
            var calendar = "<f:format.raw>{calendar.uid}</f:format.raw>";
            var $calendar = $('.calendar-' + calendar);
            var event = eventInfo.event;
            var eventId = event.id;
            var commandUrl = $calendar.data('url');
            $.ajax({
                url: commandUrl,
                method: 'post',
                dataType: "json",
                data: {
                    "tx_igreservations_ajax": {
                        controller: 'Ajax',
                        action: 'updateEvent',
                        calendar: calendar,
                        event: eventId,
                        eventStart: event.start.toISOString(),
                        eventEnd: event.end.toISOString(),
                    }
                },
                success: function(data) {
                }
            });
      }
      
      //Meeting

	  window.fullCalendar.render();
      });

    </script>
