define(['mootools', 'jquery', 'moment', 'domReady', '/intranet/js/calendar/cln_date.js', '/intranet/js/calendar/cln_event.js'], function ($$, jQuery, moment, domReady, ClnDate, ClnEvent) {
	var CalendarView = new Class({

		initialize: function () {
			this.windows_ids = ['seq_popup_action', 'loading_screen', 'error_screen', 'popup_main_screen'];
			this.transactions = {};

			$(document.body).addEvents({
				'mousemove': function (e) {
					var e = new Event(e);
					document.mouse = {"x": e.client.x, "y": e.client.y};
				}
			});

			domReady(function()
			{
				// Remove selection if quick add popup is closed
				jQuery('.cln_popup').on('hidden', function()
				{
					jQuery('#calendar').fullCalendar('unselect');
				});
			});

			// this.initBoxInfo();
			return true;
		},
		initBoxInfo: function () {
			var part = $('day_0_0').getCoordinates();
			var box = $('month_view_body').getCoordinates();
			this.box = {
				"x1": box.left,
				"y1": box.top,
				"x2": box.left - -box.width - -1,
				"y2": box.top - -box.height - -1,
				'part_width': part.width + 1,
				'part_height': part.height,
				'box_width': part.width * 7 + 7,
				'box_height': part.height * 5 + 5
			};
		},

		// event_controller: new ClnEventController(),

		quickAddEvent: function (start, end) {
			var start_date = new ClnDate(start);
			var end_date = new ClnDate(end);
			this.quickAddStart(
				{
					'start': start_date,
					'end': end_date
				},
				this.getQuickPopupCoordinates(),
				true
			);
		},
		quickAddEventPartial: function (start, end) {
			var start_date = new ClnDate(start.format('YYYY-MM-DD HH:mm:ss'));
			var end_date = new ClnDate(end.format('YYYY-MM-DD HH:mm:ss'));

			this.quickAddStart(
				{
					'start': start_date,
					'end': end_date
				},
				this.getQuickPopupCoordinates(),
				false
			);
		},
		quickEditEvent: function (fc_event) {
			this.quickEditStart(
				fc_event,
				this.getQuickPopupCoordinates()
			);
		},
		quickEditStart: function (fc_event, win_position) {
			var cln_event = new ClnEvent();
			cln_event.is_personal = 1;
			cln_event.confirm = 0;
			var full_day = fc_event.allDay;

			var start_date = new ClnDate(fc_event.start.format('YYYY-MM-DD HH:mm:ss'));

			if (full_day == true) {
				cln_event.full_day = 1;
				// cln_event.days_count = 1;
				var end_date = new ClnDate(moment(fc_event.end).add(-1, 'd').format('YYYY-MM-DD 23:59:59'));
			} else {
				var end_date = new ClnDate(fc_event.end.format('YYYY-MM-DD HH:mm:ss'));
			}

			cln_event.setName(fc_event.title);
			cln_event.cln_id = fc_event.cln_id;
			cln_event.setId(fc_event.id);
			cln_event.setStartDate(start_date);
			cln_event.setEndDate(end_date);
			cln_event.setDescription(fc_event.description);
			cln_event.editable = fc_event.editable;
			cln_event.color = fc_event.color;
			cln_event.text_color = fc_event.text_color;
			cln_event.reminder = fc_event.reminder;
			cln_event.seq_id = fc_event.seq_id;
			cln_event.type = fc_event.type;
			cln_event.overview = fc_event.overview;
			cln_event.confirm = fc_event.confirm;
			cln_event.is_personal = fc_event.is_personal;
			cln_event.participant = fc_event.participant;
			cln_event.cln_name = fc_event.cln_name;
			cln_event.old_cln_id = fc_event.old_cln_id;

			cln_event.setViewDetailsUrl(fc_event.details_url);

            this.configurePopupForEdit();
			this.openQuickPopup(cln_event, win_position);
			this.showDeleteLink();
			this.saveLink2UpdateLink();
		},
		quickEditDrop: function (fc_event) {

			var regular_day_format = 'YYYY-MM-DD HH:mm:ss';
			var end_of_day_format = 'YYYY-MM-DD 23:59:59';
			var cln_event = new ClnEvent();

			var start_date = fc_event.start.format(regular_day_format);
			var end_date;

			if (fc_event.end == null) {
				if (fc_event.start.hasTime()) {//from full_day to partial day
					end_date = moment(start_date).add(2, 'hours').format(regular_day_format);
				} else {//from partial day to full_day
					end_date = moment(start_date).format(end_of_day_format);
				}
			} else if (fc_event.start.hasTime()) {//from partial day to partial day
				end_date = moment(fc_event.end).format(regular_day_format);
			} else {//from full_day to full_day
				end_date = moment(fc_event.end).add(-1, 'd').format(end_of_day_format);
			}

			start_date = new ClnDate(start_date);
			end_date = new ClnDate(end_date);

			if (fc_event.allDay === true)
				cln_event.full_day = 1;
			else
				cln_event.full_day = 0;

			cln_event.setClnId(fc_event.cln_id);
			cln_event.setId(fc_event.id);
			cln_event.setStartDate(start_date);
			cln_event.setEndDate(end_date);
			cln_event.setName(fc_event.title);
			cln_event.setDescription(fc_event.description);
			cln_event.color = fc_event.color;
            cln_event.text_color = fc_event.text_color;
			cln_event.reminder = fc_event.reminder;
			cln_event.seq_id = fc_event.seq_id;
			cln_event.type = fc_event.type;
			cln_event.editable = fc_event.editable;
			cln_event.confirm = fc_event.confirm;
			cln_event.is_personal = fc_event.is_personal;
			cln_event.participant = fc_event.participant;
			cln_event.cln_name = fc_event.cln_name;
			cln_event.old_cln_id = fc_event.old_cln_id;


			return this.quickEditEnd(cln_event, 'event');

		},
		quickEditResize: function (fc_event) {

			var regular_day_format = 'YYYY-MM-DD HH:mm:ss';
			var end_of_day_format = 'YYYY-MM-DD 23:59:59';
			var cln_event = new ClnEvent();

			var start_date = moment(fc_event.start).format(regular_day_format);
			var end_date;

			if (fc_event.start.hasTime()) {
				end_date = moment(fc_event.end).format(regular_day_format);
			} else {
				end_date = moment(fc_event.end).add(-1, 'd').format(end_of_day_format);
			}

			start_date = new ClnDate(start_date);
			end_date = new ClnDate(end_date);

			if (fc_event.allDay == true)
				cln_event.full_day = 1;
			else
				cln_event.full_day = 0;

			cln_event.setClnId(fc_event.cln_id);
			cln_event.setId(fc_event.id);
			cln_event.setStartDate(start_date);
			cln_event.setEndDate(end_date);
			cln_event.setName(fc_event.title);
			cln_event.setDescription(fc_event.description);
			cln_event.reminder = fc_event.reminder;
			cln_event.seq_id = fc_event.seq_id;
			cln_event.type = fc_event.type;
			cln_event.editable = fc_event.editable;
			cln_event.confirm = fc_event.confirm;
			cln_event.is_personal = fc_event.is_personal;
			cln_event.participant = fc_event.participant;
			cln_event.cln_name = fc_event.cln_name;
			cln_event.old_cln_id = fc_event.old_cln_id;

			return this.quickEditEnd(cln_event, 'event', true);
		},

		closeQuickAddPopup: function () {
			this.getQuickAddDiv().addClass('d-none');
			this.common_event = null;
		},
		quickAddStart: function (date_range, win_position, full_day) {
			var cln_event = new ClnEvent();
			cln_event.is_personal = 1;
			cln_event.confirm = 0;
			if (full_day == true) {
				cln_event.full_day = 1;
				cln_event.days_count = 1;
			}
			cln_event.setStartDate(date_range.start);
			cln_event.editable = 1;
			cln_event.setEndDate(date_range.end);
			cln_event.setName('');
			cln_event.type = 'event';

			this.configurePopupForAdd();
			this.openQuickPopup(cln_event, win_position);
		},
		getQuickPopupCoordinates: function () {
			var pop_size = this.getQuickWindowSize();
			var pop_half_x = Math.floor(pop_size.width / 2) - -1;
			var pop_y = pop_size.height - -1;
			var x = document.mouse.x;
			var y = document.mouse.y;
			// if (x - -pop_half_x > this.box.x2)
			// 	x -= x - -pop_half_x - this.box.x2 - -5;
			//
			// if (x - pop_half_x < this.box.x1)
			// 	x += this.box.x1 - x - -pop_half_x - -5;

			//if (y - pop_y < (this.box.y1 - -window.getScrollTop()) )
			//y += this.box.y1 - y; this.box.y1 - window.getScrollTop() - y - -pop_y - -5;
			return {'x': x, 'y': y};
		},
		getQuickWindowSize: function () {
			// 330, 150 - size of popup, we can calculate it later, but first time we will only fix it
			if (this.getQuickAddDiv().getStyle('height') == 'auto') return {'width': 370, 'height': 150};
			return {
				'width': this.getQuickAddDiv().getStyle('width').toInt() - -20,
				'height': this.getQuickAddDiv().getStyle('height').toInt()
			};
		},
		openQuickPopup: function (cln_event, win_position) {

			this.common_event = cln_event;
			var that = this;
			$('save_link').onclick = function (e) {
				var event_name = jQuery('#quick_add_event_name').val();

				if (!event_name) {
					cla.showMessage(lmsg('calendar.text.name_cannot_be_empty'), "", true);
					return;
				}

				that.quickAddEnd();
			};
			$('save_view_link').onclick = function (e) {
				that.quickAddEnd();
			};
			$('delete_link').setStyle('display', 'none');
			this.fillPopupFields(cln_event);
			this.getQuickAddDiv().removeClass('d-none');
			this.getQuickAddDiv().setStyles({visibility: 'hidden'});
			var popupOffsetWidth = jQuery('.cln_popup').width() / 2;
			var popupOffsetHeight = 206;

			this.getQuickAddDiv().setStyles({
				left: window.innerWidth / 2 - popupOffsetWidth,
				top: window.innerHeight / 2 - popupOffsetHeight,
				visibility: ''
			});
			this.showWindow('popup_main_screen');
		},
		fillPopupFields: function (cln_event) {
			var that = this;
			if (cln_event.seq_id == 0) {
				$('ext_link').setProperty('href', "/intranet/calendar/calendar_edit_event.php?id=" + cln_event.getId() + '&type=event&start_date=' + cln_event.start.serialize() + '&end_date=' + cln_event.end.serialize() + '&full_day=' + cln_event.full_day);
				var href = jQuery('#ext_link').attr('href');
				$('ext_link').onclick = function () {
					$('ext_link').href += "&event_name=" + encodeURIComponent($('quick_add_event_name').value) + "&calendar_id=" + parseInt($('calendars_array').value) + "&event_description=" + encodeURIComponent($('quick_add_event_description').value);
				};
			} else {
				$('ext_link').setProperty('href', "#");
				$('ext_link').onclick = function () {
					that.showSequenceDialog('adv_edit', lmsg('calendar.what_to_edit') + '?');
					return false;
				};
			}

			var viewDetails = jQuery('.cln_popup_view_details');
			viewDetails.each(function (el) {
				jQuery(this).css('display', (cln_event.getId() > 0 || cln_event.type == 'system') ? 'inline-block' : 'none');
			});
			if (cln_event.seq_id == 0) {
				viewDetails.each(function (el) {
				    var url = "";
				    if (cln_event.getViewDetailsUrl() != undefined) {
				        url = cln_event.getViewDetailsUrl();
                    } else {
                        url = "/intranet/calendar/calendar_view_event.php?id=" + cln_event.getId() + '&type=event';
                    }
					jQuery(this).prop('href', url);
					jQuery(this).off('click');
				});
			} else {
				viewDetails.each(function (el) {
					jQuery(this).prop('href', "#");
					jQuery(this).on('click', function (evt) {
						that.showSequenceDialog('adv_view', lmsg('calendar.what_details') + '?');
						evt.preventDefault();
					});
				});
			}

			$('quick_add_event_name').setProperty('value', cln_event.getName());
			jQuery('#quick_add_event_show_name').text(cln_event.getName());
			$('quick_add_event_description').setProperty('value', cln_event.getDescription());
            jQuery('#quick_add_event_show_description').html(this.formatEventDescription(cln_event.getDescription()));

			jQuery(document).ready(function () {
				jQuery('#quick_add_event_name').focus(function () {
					if (jQuery(this).val() === lmsg('calendar.defaults.new_name'))
						jQuery(this).val('');
				});
			});
			var icons = (cln_event.seq_id > 0 ) ? '<img class="mr-1" src="/intranet/calendar/images/chain_part_icon.gif" alt="' + lmsg('calendar.text.chain_part') + '" title="' + lmsg('calendar.text.chain_part') + '"  align="absmiddle">' : '';
			if (cln_event.is_personal == 0 && cln_event.participant == 1) {
				if (cln_event.confirm == 0) var pat_alt = lmsg('calendar.text.invitation_unknown');
				if (cln_event.confirm == 1) var pat_alt = lmsg('calendar.text.invitation_accepted');
				if (cln_event.confirm == 2) var pat_alt = lmsg('calendar.text.invitation_rejected');
				icons = icons + '<img class="mr-1" src="/intranet/calendar/images/confirm_' + cln_event.confirm + '.gif" alt="' + pat_alt + '" title="' + pat_alt + '"  align="absmiddle">';
			}

			$('quick_add_event_time').setHTML(icons + lmsg('calendar.common.time') + ': ' + cln_event.getRange());
			/////////////////////////// REMINDER
			var reminder = cln_event.reminder;

			$('cln_reminder').setStyle('display', 'block');
			$('reminder_setter').setStyle('display', 'none');

			if (cln_event.reminder == '') {
				$('cln_reminder').setStyle('display', 'none');
				$('reminder_setter').setStyle('display', 'block');
				$('reminder_setter_href').setStyle('display', 'flex');
				reminder = cln_event.reminder_default;
				if ($('reminder_default').selectedIndex)
					reminder = $('reminder_default').value;
			}
			var option = $('cln_reminder').getElement('option[value=' + reminder + ']');
			$('cln_reminder').selectedIndex = option.index;
			/////////////////////////// REMINDER END

			// $('cln_a_bility_' + cln_event.a_bility).checked = true;
			if ($defined(cln_event.confirm)) $('cln_confirm_' + cln_event.confirm).checked = true;

			var clnid_changed = false;
			if (cln_event.old_cln_id > 0 && cln_event.editable)
			{
				cln_event.cln_id = cln_event.old_cln_id;
				cln_event.old_cln_id = 0;
				clnid_changed = true;
			}

			// select current calendar
			var option = $('calendars_array').getElement('option[value=' + cln_event.cln_id + ']');
			if (!$defined(option)) {
				if ($('default_calendar').selectedIndex) {
					option = $('calendars_array').options[$('default_calendar').selectedIndex];
				} else {
					var flag = true;
					for (var index = 0; index < $('calendars_array').options.length; index++) {
						el = $('calendars_array').options[index];
						if (flag && el.value > 0) {
							option = el;
							flag = false;
						}
					}
				}
			}
			if ($defined(option)) $('calendars_array').selectedIndex = option.index;
			$('calendars_array').onchange();
			/* if ($defined(option) && $defined(option.onclick)) option.onclick(); */

			var is_creator = (cln_event.creator_id == document.session_uid);
			if (cln_event.editable || !$defined(cln_event.cln_id)) {

				$('quick_add_event_name').removeProperty('disabled');
				$('quick_add_event_description').removeProperty('disabled');
				$("cln_popup_edit_controls_td").setStyle('display', 'block');
				$("cln_popup_view_controls_td").setStyle('display', 'none');

				$('cln_not_edit_wrap').setStyle('display', 'none');
				$('calendars_array').setStyle('display', 'block');
				if (!is_creator && cln_event.id > 0) {
					$('calendars_array').addClass('admin_only');
				} else {
					$('calendars_array').removeClass('admin_only');
				}
			} else {
				$('quick_add_event_name').setProperty('disabled', 'true');
				$('quick_add_event_description').setProperty('disabled', 'true');
				$("cln_popup_edit_controls_td").setStyle('display', 'none');
				$("cln_popup_view_controls_td").setStyle('display', 'block');



				$('calendars_array').setStyle('display', 'none');
				$('cln_not_edit_wrap').setStyle('display', 'block');
				if (cln_event.cln_id == -1 || clnid_changed)
					$('cln_not_edit').setHTML(cln_event.cln_name);
				else
					$('cln_not_edit').setHTML(document.calendar_info[cln_event.cln_id].name);
				$('cln_not_edit').setStyle('background-color', cln_event.color);
				$('cln_not_edit').setStyle('color', cln_event.text_color);


			}

			if ($('quick_add_event_description').value.length == 0 && $('quick_add_event_description').getProperty('disabled')) {
				$('quick_add_event_description_row').addClass('d-none');
			}
			else {
				$('quick_add_event_description_row').removeClass('d-none');
			}

			if (cln_event.type == 'system') {
				// $('cln_avail_row').addClass('d-none');
				$('cln_confirm_row').addClass('d-none');
				$('cln_overview_row').removeClass('d-none');
				$('cln_overview_body').setHTML(cln_event.overview);
			} else {
				$('cln_overview_row').addClass('d-none');
				if (cln_event.is_personal == 1 || cln_event.participant != 1) {
					// $('cln_avail_row').removeClass('d-none');
					$('cln_confirm_row').addClass('d-none');
				} else {
					// $('cln_avail_row').addClass('d-none');
					$('cln_confirm_row').removeClass('d-none');
				}
			}
			if (!$('quick_add_event_name').disabled) {
				try {
					$('quick_add_event_name').focus();
				}
				catch (e) {
					return false;
				}
				$('quick_add_event_name').select();
			}
		},
		showWindow: function (win_name) {
			this.windows_ids.each(function (id) {
				if (id == win_name) {
					$(win_name).removeClass('d-none');
				} else {
					$(id).addClass('d-none');
				}
			});
			var header = '';
			if (win_name == 'popup_main_screen')
				header = jQuery('#quick_add_event_time').html();
			else if (win_name == 'seq_popup_action')
				header = jQuery('#seq_popup_header').html();

			popup_set_header(jQuery('#quick_add_popup'), header);
		},
		showSequenceDialog: function(action, header){
			this.seq_action = action;
			$('seq_popup_header').setHTML(header);
			this.showWindow("seq_popup_action");
			return;
		},
		doSeqAction: function(event_type){
			var cln_event = this.getEditedEvent();
			switch(this.seq_action)
			{
				case 'delete':
					this.quickDelete(event_type);
					return this.showWindow('popup_main_screen');
					break;
				case 'edit':
					this.quickEditEnd(cln_event, event_type);
					return this.showWindow('popup_main_screen');
					break;
				case 'adv_edit':
					var href = (event_type == 'event' ) ?
					"/intranet/calendar/calendar_edit_event.php?id="+cln_event.getId()+'&type=event&start_date='+cln_event.start.serialize()+'&end_date='+cln_event.end.serialize()+'&full_day='+cln_event.full_day+'&event_name='+encodeURIComponent($('quick_add_event_name').value)+'&event_descsription='+encodeURIComponent($('quick_add_event_description').value) :
					"/intranet/calendar/calendar_edit_event.php?id="+cln_event.seq_id+'&type=chain&event_name='+encodeURIComponent($('quick_add_event_name').value)+'&event_descsription='+encodeURIComponent($('quick_add_event_description').value);
					document.location.href = href;
					return;
					break;
				case 'adv_view':
					var href = (event_type == 'event' ) ?
					"/intranet/calendar/calendar_view_event.php?id="+cln_event.getId()+'&type=event' :
					"/intranet/calendar/calendar_view_event.php?id="+cln_event.seq_id+'&type=chain';
					document.location.href = href;
					return;
					break;
				default:
					alert('ERROR: actions is not set!');
					return this.showWindow('popup_main_screen');
			}
		},
		quickAddEnd: function () {
			cln_event = this.getEditedEvent();
			var options = cln_event.serialize();

			this.transactions[options.trasaction_id] = cln_event;
			this.showSpinner();
			var that = this;

			var request = jQuery.ajax({
				url: '/api/calendar/v1/events',
				data: JSON.stringify(options),
				type: "POST"
			});

			request.done(function(response) {
				var calendar = jQuery('#calendar').fullCalendar();
				if(options.full_day)
				//full calendar doesn't recognize h:23 m:59 s:59 as full day
					end_date = moment(options.end_date).add(1, 'd').format('YYYY-MM-DD 00:00:00');
				else
					end_date = moment(options.end_date).format();

				calendar.fullCalendar('renderEvent',
					{
						title: options.name,
						start: moment(options.start_date).format(),
						end: end_date,
						allDay: !!options.full_day,
						color: response.color,
						text_color: response.text_color,
						id: response.id,
						cln_id: options.cln_id,
						description: options.description,
						editable: options.editable,
						reminder: options.reminder,
						type: options.type,
						seq_id: options.seq_id
					},
					true // make the event "stick"
				);

				calendar.fullCalendar('unselect');
			});

			request.fail(function() {
				cla.showMessage(lmsg('calendar.can_not_add_event'), "", true);
			});

			request.always(function(){
				that.hideSpinner();
			});

			this.closeQuickAddPopup();

		},
		getEditedEvent: function (drop) {
			if (typeof drop === 'undefined') drop = false;
			if (!$defined(this.common_event)) {
				alert("Error: havn't requested event!");
				return;
			}
			cln_event = this.common_event;


			cln_event.reminder = ($('cln_reminder').getStyle('display') == 'none') ? '' : $($('cln_reminder').options[$('cln_reminder').selectedIndex]).getProperty('value');

			if (cln_event.type == 'system') return cln_event;
			if (!drop)cln_event.setName($('quick_add_event_name').getProperty('value'));
			cln_event.setDescription($('quick_add_event_description').value);
			if ($('calendars_array').selectedIndex < 0) {
				var cln_id = false;
			} else {
				var cln_id = $($('calendars_array').options[$('calendars_array').selectedIndex]).getProperty('value');
			}
			var is_creator = (cln_event.creator_id == document.session_uid);
			if (!$defined(cln_event.cln_id) || cln_event.cln_id == 0 || (document.calendar_perms[129][cln_event.cln_id] == 1) || (is_creator && document.calendar_perms[3][cln_event.cln_id] == 1 )) cln_event.cln_id = cln_id;
			// cln_event.a_bility = $('cln_a_bility_1').checked ? 1 : 0;
			cln_event.confirm = $('cln_confirm_1').checked ? 1 : ($('cln_confirm_2').checked ? 2 : 0);
			return cln_event;
		},
		getQuickAddDiv: function () {
			return $('quick_add_popup');
		},
		showDeleteLink: function () {
			var that = this;
			$('delete_link').setHTML(lmsg('common.delete')).removeClass('deleteConfirm').setStyles({'display': 'inline-block'});
			$('delete_link').onclick = function (e) {
				var e = new Event(e);
				that.confirmDelete(e.target);
			};
		},
		saveLink2UpdateLink: function () {
			var that = this;
			$('save_link').onclick = function (e) {
				that.quickEdit();
			};
			$('save_view_link').onclick = function (e) {
				that.quickEdit();
			};
		},
		quickEdit: function () {
			var cln_event = this.getEditedEvent();
			if (cln_event.seq_id > 0) return this.showSequenceDialog('edit', lmsg('calendar.what_to_edit') + '?');
			return this.quickEditEnd(cln_event, 'event');
		},
		confirmDelete: function (target) {
			var cln_event = this.getEditedEvent();
			if (cln_event.seq_id > 0) return this.showSequenceDialog('delete', lmsg('calendar.what_to_delete') + '?');

			var that = this;
			target.setHTML(lmsg('calendar.delete_confirm')).addClass('deleteConfirm').setStyles({'display': 'inline-block'});
			target.onclick = function (e) {
				that.quickDelete('event');
				return false;
			};
		},
		quickEditEnd: function (cln_event, cln_type) {
			var options = cln_event.serialize();
			if (options.type !== 'system')
				options.type = cln_type;

			this.transactions[options.trasaction_id] = cln_event;
			var that = this;
			this.result = true;
			this.showSpinner();

			var request = jQuery.ajax({
				url: '/api/calendar/v1/events/' + options.id,
				data: JSON.stringify(options),
				type: "POST"
			});

			request.done(function(color) {
				var calendar = jQuery('#calendar').fullCalendar();
				if(cln_type == 'chain'){
					calendar.fullCalendar('removeEvents');
					calendar.fullCalendar('refetchEvents');
				}else{
					if(color == false){
						cla.showMessage(lmsg('calendar.can_not_update_event'), "", true);
					}else{
						if(options.full_day)
							end_date = moment(options.end_date).add(1, 'd').format('YYYY-MM-DD 00:00:00');
						else
							end_date = moment(options.end_date).format('YYYY-MM-DD HH:mm:ss');

						calendar.fullCalendar('removeEvents', options.id);
						calendar.fullCalendar('renderEvent',
							{
								title: options.name,
								start: moment(options.start_date).format('YYYY-MM-DD HH:mm:ss'),
								end: end_date,
								allDay: !!options.full_day,
								id: options.id,
								color: color,
								text_color: options.text_color,
								cln_id: options.cln_id,
								description: options.description,
								reminder: options.reminder,
								type: options.type,
								overview: options.overview,
								seq_id: options.seq_id,
								editable: options.editable,
								is_personal: options.is_personal,
								participant: options.participant,
								confirm: options.confirm,
								cln_name: options.cln_name,
								old_cln_id: options.old_cln_id
							},
							true // make the event "stick"
						);
						calendar.fullCalendar('unselect');
					}
				}
			});

			request.fail(function() {
				cla.showMessage(lmsg('calendar.can_not_update_event'), "", true);
			});

			request.always(function(){
				that.hideSpinner();
			});

			that.closeQuickAddPopup();
		},
		quickDelete: function (cln_type) {
			cln_event = this.getEditedEvent();
			var options = cln_event.serialize();
			options.type = cln_type;
			this.closeQuickAddPopup();
			var that = this;
			this.showSpinner();

			var request = jQuery.ajax({
				url: '/api/calendar/v1/events/' + cln_event.id,
				data: JSON.stringify(options),
				type: "DELETE"
			});

			request.done(function(result) {
				var calendar = jQuery('#calendar').fullCalendar();
				if(cln_type == 'chain'){
					calendar.fullCalendar('removeEvents');
					calendar.fullCalendar('refetchEvents');
				}else if(result == false){
					cla.showMessage(lmsg('calendar.can_not_del_event'), "", true);
				}else{
					calendar.fullCalendar('removeEvents', cln_event.id);
				}
			});

			request.fail(function() {
				cla.showMessage(lmsg('calendar.can_not_del_event'), "", true);
			});

			request.always(function(){
				that.hideSpinner();
			});

		},
		showSpinner: function(){
			//show the spinner
			var spinner = jQuery('#spinner');

			spinner.css('display', 'block');
			spinner.css("top", (jQuery(window).height() - spinner.height())/2 + jQuery(window).scrollTop() + "px");
			spinner.css("left", (jQuery(window).width() - spinner.width())/2 + jQuery(window).scrollLeft() + "px");
		},
		hideSpinner: function(){
			//show the spinner
			var spinner = jQuery('#spinner');
			spinner.css('display', 'none');

		},
		toggleCalendarsFilter: function(){
			jQuery('#calendar_filter').modal('hide');
		},
        formatEventDescription: function (text) {
            text = _.escape(text);

            //this is the same link-replacing logic as is in ClaText::ParseLinksAndEscapeText
            text = text.replace(
                /(?:(?:https?|ftp):\/\/|mailto:|www\.)[^\s]+/g,
                function (match) {
                    match = _.unescape(match);
                    var url = match;

                    if (/^www\./.test(url))
                        url = "http://" + url;

                    var elem = jQuery("<a>");
                    elem.attr('target', '_blank');
                    elem.attr('href', url);
                    elem.text(match);

                    return elem[0].outerHTML;
                });

            text = text.replace(/\n/g, "<br />\n");

            return text;
        },
        configurePopupForAdd: function() {
            jQuery("#quick_add_event_name").removeClass("d-none");
            jQuery("#quick_add_event_show_name").addClass("d-none");

            jQuery("#quick_add_event_description").removeClass("d-none");
            jQuery("#quick_add_event_show_description").addClass("d-none");
        },
        configurePopupForEdit: function() {
            jQuery("#quick_add_event_name").addClass("d-none");
            jQuery("#quick_add_event_show_name").removeClass("d-none");

            jQuery("#quick_add_event_description").addClass("d-none");
            jQuery("#quick_add_event_show_description").removeClass("d-none");
        }
	});

	return CalendarView;
});
