//import deLocale from '@fullcalendar/core/locales/de';
var calendarElement = document.getElementById('calendar');
var conf = JSON.parse(calendarElement.dataset.calendarFullcalendarSettings);
conf.searchDate = calendarElement.dataset.searchDate;
conf.isAdmin = calendarElement.dataset.isAdmin;
conf.eventSourceUrl = calendarElement.dataset.eventSourceUrl;
conf.calendarHasPermissionRead = calendarElement.dataset.calendarHasPermissionRead;
conf.calendarHasPermissionTeam = calendarElement.dataset.calendarHasPermissionTeam;
conf.calendarHasPermissionUser = calendarElement.dataset.calendarHasPermissionUser;
conf.calendarUid = calendarElement.dataset.calendarUid;
conf.calendarConf = JSON.parse(calendarElement.dataset.calendarConf);//decodeURIComponent(
conf.calendarAcl = JSON.parse(calendarElement.dataset.calendarAcl);//decodeURIComponent(
var cal = conf.calendarConf;
if($(window).width() < 601) {
    cal.defaultView = 'timeGridDay';
}






// FZBE
function handlePurposes($content) {
    var activePurposes = [];
    var $checkedBookingType = $("#reservation-bookingtype input:checked", $content);
    var $selectedUser = $("#reservation-user option:selected", $content);

        if($checkedBookingType.length) {
            var bookingTypePurposesStr = $checkedBookingType.data('purposes');
            if(bookingTypePurposes) {
                var bookingTypePurposes = bookingTypePurposesStr.split(',');

                for(var i = 0; i < bookingTypePurposes.length; i++) {
                    if(!activePurposes.includes(bookingTypePurposes[i]) && bookingTypePurposes[i] != '') {
                        activePurposes.push(bookingTypePurposes[i]);
                    }
                }
            }
        }

    if($selectedUser.length) {
        var userPurposesStr = $selectedUser.data("purposes");

        if(userPurposesStr) {
            var userPurposes = userPurposesStr.split(",");

            for(var i = 0; i < userPurposes.length; i++) {
                if(!activePurposes.includes(userPurposes[i]) && userPurposes[i] != '') {
                    activePurposes.push(userPurposes[i]);
                }
            }
        }
    }
        var $allOptions = $("#reservation-purpose option", $content);
    $allOptions.each(function(i) {
        var $option = $($allOptions[i]);
        var uid = $option.val();

        $option.show();
        if(uid && !activePurposes.includes(uid)) {
            $option.hide();
        }
    });

    $("#reservation-purpose", $content).parents(".fancyInput").show();
    if(!activePurposes.length) {
        $("#reservation-purpose", $content).parents(".fancyInput").hide();
    }
}

function checkReservationType($content) {
    var $checkboxes = $('.ig-radio input[name="tx_igreservations_ajax[reservation][event][reservationTypes][]"]', $content);
    if($checkboxes.is(':checked')) {
        $checkboxes.attr('required', false);
        $checkboxes.prop('required', false);
    } else {
        $checkboxes.attr('required', true);
        $checkboxes.prop('required', true);
    }
}






var calendarConfig = {
    //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',
    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
    selectOverlap: true,
    selectMirror: true,
    select: function(arg) {
	var calendar = conf.calendarUid;
	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');
	    if (conf.calendarAcl && conf.calendarAcl.minimumBlockDuration) {
                var minimumBlockDuration = 60 * 60 * 1000 * conf.calendarAcl.minimumBlockDuration;
		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;
		}
	    }
	    if (conf.calendarAcl && conf.calendarAcl.maximumBlockDuration) {
                var maximumBlockDuration = 60 * 60 * 1000 * conf.calendarAcl.maximumBlockDuration;
		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;
		}
	    }
	    $.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');
			    $('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();
					    }
					    if (conf.calendarHasPermissionTeam || conf.calendarHasPermissionRead) {
						if($(calendarElement).data('afterBookingRedirectUrl')) {
						    window.location.href = $(calendarElement).data('afterBookingRedirectUrl');
						}
					    }
					    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.unselect()
				}
			    );

			    //	  self.fancyboxAfterShow(instance, current, '#timeslot-' + command.args.calendar + '-' + command.args.date + '-' + command.args.timeslot)
			}
		    });
		}
	    });
	}
    },
    eventLimit: true, // allow "more" link when too many events
    eventSources: [
        {
            id: 1,
            url: conf.eventSourceUrl,
            startParam: 'tx_igreservations_ajax[search][startDateAndTime]',
            endParam: 'tx_igreservations_ajax[search][endDateAndTime]',
            method: 'POST',
            extraParams: function() {
                return {
                    'tx_igreservations_ajax[calendar]': conf.calendarUid,
                    '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() : '',
                };
            }
        }
    ],
};
if (conf.searchDate) {
    calendarConfig.defaultDate = conf.searchDate;
}

/* default nicht FZBE
if (conf.calendarHasPermissionRead) {
    calendarConfig.selectable =  false;
    calendarConfig.editable = false;
} else {
    calendarConfig.selectable = true;
    calendarConfig.editable = true;
}
*/

if (conf.isAdmin) {
    calendarConfig.selectable = true;
    calendarConfig.editable = true;
} else {
    calendarConfig.selectable =  false;
    calendarConfig.editable = false;
}



if (conf.calendarHasPermissionTeam || conf.calendarHasPermissionRead || conf.calendarHasPermissionUser) {
    calendarConfig.eventClick = function(info) {
        if(conf.isAdmin || info.event.extendedProps.hasReservationForUser) {
            var calendar = conf.calendarUid;
            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 );
            		}
            	    });
        	}
            });
	};
	// FZBE: Frauenzentrale bis ende
	if (!conf.isAdmin) {
	    if(!info.event.extendedProps.hasReservationForUser && info.event.extendedProps.openReservationForm) {
		var calendar = conf.calendarUid;
		var $calendar = $('.calendar-' + calendar);
    		var commandUrl = $calendar.data('url');
    		$.ajax({
		    url: commandUrl,
		    method: 'post',
		    dataType: "json",
		    data: {
        		"tx_igreservations_ajax": {
            		    controller: 'Ajax',
            		    action: 'reservationCreateFormStartEnd',
            		    calendar: calendar,
            		    eventStart: info.event.start.toISOString(),
            		    eventEnd: info.event.end.toISOString(),
			    event: info.event.id
        		}
		    },
		    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) {
				//$('.dp-form', current.$content).initDPForm();
				IGDATAPOOLFE.addForm($('.dp-form', current.$content).get(0), 'lightbox');

				handlePurposes(current.$content);
				$("#reservation-bookingtype input", current.$content).on("change", function (e) {
				    handlePurposes(current.$content);
				});
				$("#reservation-bookingtype input", current.$content).on("change", function (e) {
				    handlePurposes(current.$content);
				});
				checkReservationType(current.$content);
				$('.ig-radio input[name="tx_igreservations_ajax[reservation][event][reservationTypes][]"]', current.$content).on('change', function(e) {
				    checkReservationType(current.$content);
				});
				var selectedLocation = '';
				if($('[name="tx_igreservations_publiccalendar[search][location]"] option:selected').length) {
				    selectedLocation = $('[name="tx_igreservations_publiccalendar[search][location]"] option:selected').val();
				}
				if(selectedLocation && selectedLocation.includes('r')) {
				    selectedLocation = selectedLocation.split('_')[1];
				    if($('input[type="radio"][name^="tx_igreservations_ajax[reservation][reservationType]"][value="' + selectedLocation + '"]').length) {
					$('input[type="radio"][name^="tx_igreservations_ajax[reservation][reservationType]"][value="' + selectedLocation + '"]').attr('checked', true);
					$('input[type="radio"][name^="tx_igreservations_ajax[reservation][reservationType]"][value="' + selectedLocation + '"]').prop('checked', true);
				    }
				} else if(selectedLocation) {
				    if($('input[type="radio"][name^="tx_igreservations_ajax[reservation][reservationType]"][value="1"]').length) {
					$('input[type="radio"][name^="tx_igreservations_ajax[reservation][reservationType]"][value="1"]').attr('checked', true);
					$('input[type="radio"][name^="tx_igreservations_ajax[reservation][reservationType]"][value="1"]').prop('checked', true);
				    }
				}

            			//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) {
            				event.preventDefault();
					var noErrors = window.validateReservationForm(this);
					if (!noErrors) {
					    return false;
					}
            				var $form = $(this);
            				//console.log('todo cal');
            				parent.jQuery.fancybox.getInstance().close();
            				$.ajax({
            				    url: $form.attr('action'),
            				    method: 'post',
            				    dataType: "json",
            				    data: $form.serialize(),
					    success: function(data) {
                                		if (conf.calendarHasPermissionTeam || conf.calendarHasPermissionRead) {
						    if($(calendarEl).data('afterBookingRedirectUrl')) {
							window.location.href = $(calendarEl).data('afterBookingRedirectUrl');
						    }
						}
						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(':');

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

            				window.fullCalendar.unselect();
            			    });
				//	  self.fancyboxAfterShow(instance, current, '#timeslot-' + command.args.calendar + '-' + command.args.date + '-' + command.args.timeslot)
    			    }
			});
		    }
		});
	    }
	}
    }
}

// FZBE
if (conf.isAdmin) {
    calendarConfig.selectOverlap = true;
} else {
    calendarConfig.selectOverlap = false;
}

if (conf.isAdmin) {
    calendarConfig.eventDrop = eventMove;
    calendarConfig.eventResize = eventMove;
    function eventMove(eventInfo) {
        var calendar = conf.calendarUid;
        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) {
                window.fullCalendar.refetchEvents();
            }
        });
    }
}













window.fullCalendar = new FullCalendar.Calendar(calendarElement,calendarConfig);



//Meeting

window.fullCalendar.render();

