/** * Client UI Javascript for the Calendar plugin * * @author Lazlo Westerhof * @author Thomas Bruederli * * @licstart The following is the entire license notice for the * JavaScript code in this file. * * Copyright (C) 2010, Lazlo Westerhof * Copyright (C) 2014-2015, Kolab Systems AG * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . * * @licend The above is the entire license notice * for the JavaScript code in this file. */ // Roundcube calendar UI client class function rcube_calendar_ui(settings) { // extend base class rcube_calendar.call(this, settings); /*** member vars ***/ this.is_loading = false; this.selected_event = null; this.selected_calendar = null; this.search_request = null; this.saving_lock = null; this.calendars = {}; this.quickview_sources = []; /*** private vars ***/ var DAY_MS = 86400000; var HOUR_MS = 3600000; var me = this; var day_clicked = day_clicked_ts = 0; var ignore_click = false; var event_defaults = { free_busy:'busy', alarms:'' }; var event_attendees = []; var calendars_list; var calenders_search_list; var calenders_search_container; var search_calendars = {}; var attendees_list; var resources_list; var resources_treelist; var resources_data = {}; var resources_index = []; var resource_owners = {}; var resources_events_source = { url:null, editable:false }; var freebusy_ui = { workinhoursonly:false, needsupdate:false }; var freebusy_data = {}; var current_view = null; var count_sources = []; var event_sources = []; var exec_deferred = 1; var sensitivitylabels = { 'public':rcmail.gettext('public','calendar'), 'private':rcmail.gettext('private','calendar'), 'confidential':rcmail.gettext('confidential','calendar') }; var ui_loading = rcmail.set_busy(true, 'loading'); // global fullcalendar settings var fullcalendar_defaults = { theme: false, aspectRatio: 1, timezone: false, // will treat the given date strings as in local (browser's) timezone monthNames: settings.months, monthNamesShort: settings.months_short, dayNames: settings.days, dayNamesShort: settings.days_short, weekNumbers: settings.show_weekno > 0, weekNumberTitle: rcmail.gettext('weekshort', 'calendar') + ' ', firstDay: settings.first_day, firstHour: settings.first_hour, slotDuration: {minutes: 60/settings.timeslots}, businessHours: { start: settings.work_start + ':00', end: settings.work_end + ':00' }, scrollTime: settings.work_start + ':00', views: { list: { titleFormat: settings.dates_long, listDayFormat: settings.date_long, visibleRange: function(currentDate) { return { start: currentDate.clone(), end: currentDate.clone().add(settings.agenda_range, 'days') } } }, month: { columnFormat: 'ddd', // Mon titleFormat: 'MMMM YYYY', eventLimit: 4 }, week: { columnFormat: 'ddd ' + settings.date_short, // Mon 9/7 titleFormat: settings.dates_long }, day: { columnFormat: 'dddd ' + settings.date_short, // Monday 9/7 titleFormat: 'dddd ' + settings.date_long } }, timeFormat: settings.time_format, slotLabelFormat: settings.time_format, defaultView: rcmail.env.view || settings.default_view, allDayText: rcmail.gettext('all-day', 'calendar'), buttonText: { today: settings['today'], day: rcmail.gettext('day', 'calendar'), week: rcmail.gettext('week', 'calendar'), month: rcmail.gettext('month', 'calendar'), list: rcmail.gettext('agenda', 'calendar') }, buttonIcons: { prev: 'left-single-arrow', next: 'right-single-arrow' }, nowIndicator: settings.time_indicator, eventLimitText: function(num) { return rcmail.gettext('andnmore', 'calendar').replace('$nr', num); }, // event rendering eventRender: function(event, element, view) { if (view.name != 'list') { var prefix = event.sensitivity && event.sensitivity != 'public' ? String(sensitivitylabels[event.sensitivity]).toUpperCase()+': ' : ''; element.attr('title', prefix + event.title); } if (view.name != 'month') { if (view.name == 'list') { var loc = $('').attr('class', 'fc-event-location'); if (event.location) loc.text(event.location); element.find('.fc-list-item-title').after(loc); } else if (event.location) { element.find('div.fc-title').after($('
').html('@ ' + Q(event.location))); } var time_element = element.find('div.fc-time'); if (event.sensitivity && event.sensitivity != 'public') time_element.append(''); if (event.recurrence) time_element.append(''); if (event.alarms || (event.valarms && event.valarms.length)) time_element.append(''); } if (event.status) { element.addClass('cal-event-status-' + String(event.status).toLowerCase()); } set_event_colors(element, event, view.name); element.attr('aria-label', event.title + ', ' + me.event_date_text(event, true)); }, // callback when a specific event is clicked eventClick: function(event, ev, view) { if (!event.temp && (!event.className || event.className.indexOf('fc-type-freebusy') < 0)) event_show_dialog(event, ev); } }; /*** imports ***/ var Q = this.quote_html; var text2html = this.text2html; var event_date_text = this.event_date_text; var date2unixtime = this.date2unixtime; var fromunixtime = this.fromunixtime; var parseISO8601 = this.parseISO8601; var date2servertime = this.date2ISO8601; var render_message_links = this.render_message_links; /*** private methods ***/ // same as str.split(delimiter) but it ignores delimiters within quoted strings var explode_quoted_string = function(str, delimiter) { var result = [], strlen = str.length, q, p, i, chr, last; for (q = p = i = 0; i < strlen; i++) { chr = str.charAt(i); if (chr == '"' && last != '\\') { q = !q; } else if (!q && chr == delimiter) { result.push(str.substring(p, i)); p = i + 1; } last = chr; } result.push(str.substr(p)); return result; }; // Change the first charcter to uppercase var ucfirst = function(str) { return str.charAt(0).toUpperCase() + str.substr(1); }; // clone the given date object and optionally adjust time var clone_date = function(date, adjust) { var d = 'toDate' in date ? date.toDate() : new Date(date.getTime()); // set time to 00:00 if (adjust == 1) { d.setHours(0); d.setMinutes(0); } // set time to 23:59 else if (adjust == 2) { d.setHours(23); d.setMinutes(59); } return d; }; // fix date if jumped over a DST change var fix_date = function(date) { if (date.getHours() == 23) date.setTime(date.getTime() + HOUR_MS); else if (date.getHours() > 0) date.setHours(0); }; var date2timestring = function(date, dateonly) { return date2servertime(date).replace(/[^0-9]/g, '').substr(0, (dateonly ? 8 : 14)); } var format_date = function(date, format) { return $.fullCalendar.formatDate('toDate' in date ? date : moment(date), format); }; var format_datetime = function(date, mode, voice) { return me.format_datetime(date, mode, voice); } var render_link = function(url) { var islink = false, href = url; if (url.match(/^[fhtpsmailo]+?:\/\//i)) { islink = true; } else if (url.match(/^[a-z0-9.-:]+(\/|$)/i)) { islink = true; href = 'http://' + url; } return islink ? '' + Q(url) + '' : Q(url); } // determine whether the given date is on a weekend var is_weekend = function(date) { return date.getDay() == 0 || date.getDay() == 6; }; var is_workinghour = function(date) { if (settings['work_start'] > settings['work_end']) return date.getHours() >= settings['work_start'] || date.getHours() < settings['work_end']; else return date.getHours() >= settings['work_start'] && date.getHours() < settings['work_end']; }; var set_event_colors = function(element, event, mode) { var bg_color = '', border_color = '', cat = String(event.categories), color = event.calendar && me.calendars[event.calendar] ? me.calendars[event.calendar].color : '', cat_color = rcmail.env.calendar_categories[cat] ? rcmail.env.calendar_categories[cat] : color; switch (settings.event_coloring) { case 1: bg_color = border_color = cat_color; break; case 2: border_color = color; bg_color = cat_color; break; case 3: border_color = cat_color; bg_color = color; break; default: bg_color = border_color = color; break; } var css = { 'border-color': border_color, 'background-color': bg_color, 'color': me.text_color(bg_color) }; if (String(css['border-color']).match(/^#?f+$/i)) delete css['border-color']; $.each(css, function(i, v) { if (!v) delete css[i]; else if (v.charAt(0) != '#') css[i] = '#' + v; }); if (mode == 'list') { bg_color = css['background-color']; if (bg_color && !bg_color.match(/^#?f+$/i)) $(element).find('.fc-event-dot').css('background-color', bg_color); } else $(element).css(css); }; var load_attachment = function(data) { var event = data.record, query = {_id: data.attachment.id, _event: event.recurrence_id || event.id, _cal: event.calendar}; if (event.rev) query._rev = event.rev; if (event.calendar == "--invitation--itip") $.extend(query, {_uid: event._uid, _part: event._part, _mbox: event._mbox}); libkolab.load_attachment(query, data.attachment); }; // build event attachments list var event_show_attachments = function(list, container, event, edit) { libkolab.list_attachments(list, container, edit, event, function(id) { remove_attachment(id); }, function(data) { load_attachment(data); } ); }; var remove_attachment = function(id) { rcmail.env.deleted_attachments.push(id); }; // event details dialog (show only) var event_show_dialog = function(event, ev, temp) { var $dialog = $("#eventshow"); var calendar = event.calendar && me.calendars[event.calendar] ? me.calendars[event.calendar] : { editable:false, rights:'lrs' }; if (!temp) me.selected_event = event; if ($dialog.is(':ui-dialog')) $dialog.dialog('close'); // remove status-* and sensitivity-* classes $dialog.removeClass(function(i, oldclass) { var oldies = String(oldclass).split(' '); return $.grep(oldies, function(cls) { return cls.indexOf('status-') === 0 || cls.indexOf('sensitivity-') === 0 }).join(' '); }); // convert start/end dates if not done yet by fullcalendar if (typeof event.start == 'string') event.start = parseISO8601(event.start); if (typeof event.end == 'string') event.end = parseISO8601(event.end); // allow other plugins to do actions when event form is opened rcmail.triggerEvent('calendar-event-init', {o: event}); $dialog.find('div.event-section, div.event-line, .form-group').hide(); $('#event-title').html(Q(event.title)).show(); if (event.location) $('#event-location').html('@ ' + text2html(event.location)).show(); if (event.description) $('#event-description').show().find('.event-text').html(text2html(event.description, 300, 6)); if (event.vurl) $('#event-url').show().find('.event-text').html(render_link(event.vurl)); if (event.recurrence && event.recurrence_text) $('#event-repeat').show().find('.event-text').html(Q(event.recurrence_text)); if (event.valarms && event.alarms_text) $('#event-alarm').show().find('.event-text').html(Q(event.alarms_text).replace(',', ',
')); if (calendar.name) $('#event-calendar').show().find('.event-text').html(Q(calendar.name)).addClass('cal-'+calendar.id); if (event.categories) $('#event-category').show().find('.event-text').text(event.categories).addClass('cat-'+String(event.categories).toLowerCase().replace(rcmail.identifier_expr, '')); if (event.free_busy) $('#event-free-busy').show().find('.event-text').text(rcmail.gettext(event.free_busy, 'calendar')); if (event.priority > 0) { var priolabels = [ '', rcmail.gettext('highest'), rcmail.gettext('high'), '', '', rcmail.gettext('normal'), '', '', rcmail.gettext('low'), rcmail.gettext('lowest') ]; $('#event-priority').show().find('.event-text').text(event.priority+' '+priolabels[event.priority]); } if (event.status) { var status_lc = String(event.status).toLowerCase(); $('#event-status').show().find('.event-text').text(rcmail.gettext('status-'+status_lc,'calendar')); $('#event-status-badge > span').text(rcmail.gettext('status-'+status_lc,'calendar')); $dialog.addClass('status-'+status_lc); } if (event.sensitivity && event.sensitivity != 'public') { $('#event-sensitivity').show().find('.event-text').text(sensitivitylabels[event.sensitivity]); $('#event-status-badge > span').text(sensitivitylabels[event.sensitivity]); $dialog.addClass('sensitivity-'+event.sensitivity); } if (event.created || event.changed) { var created = parseISO8601(event.created), changed = parseISO8601(event.changed); $('.event-created', $dialog).text(created ? format_datetime(created) : rcmail.gettext('unknown','calendar')); $('.event-changed', $dialog).text(changed ? format_datetime(changed) : rcmail.gettext('unknown','calendar')); $('#event-created,#event-changed,#event-created-changed').show() } // create attachments list if ($.isArray(event.attachments)) { event_show_attachments(event.attachments, $('#event-attachments').find('.event-text'), event); if (event.attachments.length > 0) { $('#event-attachments').show(); } } else if (calendar.attachments) { // fetch attachments, some drivers doesn't set 'attachments' prop of the event? } // build attachments list $('#event-links').hide(); if ($.isArray(event.links) && event.links.length) { render_message_links(event.links || [], $('#event-links').find('.event-text'), false, 'calendar'); $('#event-links').show(); } // list event attendees if (calendar.attendees && event.attendees) { // sort resources to the end event.attendees.sort(function(a,b) { var j = a.cutype == 'RESOURCE' ? 1 : 0, k = b.cutype == 'RESOURCE' ? 1 : 0; return (j - k); }); var data, mystatus = null, rsvp, line, morelink, html = '', overflow = '', organizer = me.is_organizer(event), num_attendees = event.attendees.length; for (var j=0; j < num_attendees; j++) { data = event.attendees[j]; if (data.email) { if (data.role != 'ORGANIZER' && is_this_me(data.email)) { mystatus = (data.status || 'UNKNOWN').toLowerCase(); if (data.status == 'NEEDS-ACTION' || data.status == 'TENTATIVE' || data.rsvp) rsvp = mystatus; } } line = rcube_libcalendaring.attendee_html(data); if (morelink) overflow += ' ' + line; else html += ' ' + line; // stop listing attendees if (j == 7 && num_attendees > 8) { morelink = $('').html(rcmail.gettext('andnmore', 'calendar').replace('$nr', num_attendees - j - 1)); } } if (html && (num_attendees > 1 || !organizer)) { $('#event-attendees').show() .find('.event-text') .html(html) .find('a.mailtolink').click(event_attendee_click); // display all attendees in a popup when clicking the "more" link if (morelink) { $('#event-attendees .event-text').append(morelink); morelink.click(function(e){ rcmail.simple_dialog( '
' + html + overflow + '
', rcmail.gettext('tabattendees','calendar'), null, {width: 450, cancel_button: 'close'}); $('#all-event-attendees a.mailtolink').click(event_attendee_click); return false; }); } } if (mystatus && !rsvp) { $('#event-partstat').show().find('.changersvp, .event-text') .removeClass('accepted tentative declined delegated needs-action unknown') .addClass(mystatus); $('#event-partstat').find('.event-text') .text(rcmail.gettext('status' + mystatus, 'libcalendaring')); } var show_rsvp = rsvp && !organizer && event.status != 'CANCELLED' && me.has_permission(calendar, 'v'); $('#event-rsvp')[(show_rsvp ? 'show' : 'hide')](); $('#event-rsvp .rsvp-buttons input').prop('disabled', false).filter('input[rel="'+(mystatus || '')+'"]').prop('disabled', true); if (show_rsvp && event.comment) $('#event-rsvp-comment').show().find('.event-text').html(Q(event.comment)); $('#event-rsvp a.reply-comment-toggle').show(); $('#event-rsvp .itip-reply-comment textarea').hide().val(''); if (event.recurrence && event.id) { var sel = event._savemode || (event.thisandfuture ? 'future' : (event.isexception ? 'current' : 'all')); $('#event-rsvp .rsvp-buttons').addClass('recurring'); } else { $('#event-rsvp .rsvp-buttons').removeClass('recurring'); } } var buttons = [], is_removable_event = function(event, calendar) { // for invitation calendars check permissions of the original folder if (event._folder_id) calendar = me.calendars[event._folder_id]; return calendar && me.has_permission(calendar, 'td'); }; if (!temp && calendar.editable && event.editable !== false) { buttons.push({ text: rcmail.gettext('edit', 'calendar'), 'class': 'edit mainaction', click: function() { event_edit_dialog('edit', event); } }); } if (!temp && is_removable_event(event, calendar) && event.editable !== false) { buttons.push({ text: rcmail.gettext('delete', 'calendar'), 'class': 'delete', click: function() { me.delete_event(event); $dialog.dialog('close'); } }); } buttons.push({ text: rcmail.gettext('close', 'calendar'), 'class': 'cancel', click: function() { $dialog.dialog('close'); } }); var close_func = function(e) { rcmail.command('menu-close', 'eventoptionsmenu', null, e); $('.libcal-rsvp-replymode').hide(); }; // open jquery UI dialog $dialog.dialog({ modal: true, resizable: true, closeOnEscape: true, title: me.event_date_text(event), open: function() { $dialog.attr('aria-hidden', 'false'); setTimeout(function(){ $dialog.parent().find('button:not(.ui-dialog-titlebar-close,.delete)').first().focus(); }, 5); }, close: function(e) { close_func(e); $dialog.dialog('close'); }, dragStart: close_func, resizeStart: close_func, buttons: buttons, minWidth: 320, width: 420 }).show(); // remember opener element (to be focused on close) $dialog.data('opener', ev && rcube_event.is_keyboard(ev) ? ev.target : null); // set voice title on dialog widget $dialog.dialog('widget').removeAttr('aria-labelledby') .attr('aria-label', me.event_date_text(event, true) + ', ', event.title); // set dialog size according to content me.dialog_resize($dialog.get(0), $dialog.height(), 420); // add link for "more options" drop-down if (!temp && !event.temporary && event.calendar != '_resource') { $('') .attr({href: '#', 'class': 'dropdown-link btn btn-link options', 'data-popup-pos': 'top'}) .text(rcmail.gettext('eventoptions','calendar')) .click(function(e) { return rcmail.command('menu-open','eventoptionsmenu', this, e); }) .appendTo($dialog.parent().find('.ui-dialog-buttonset')); } rcmail.enable_command('event-history', calendar.history); rcmail.triggerEvent('calendar-event-dialog', {dialog: $dialog}); }; // event handler for clicks on an attendee link var event_attendee_click = function(e) { var cutype = $(this).attr('data-cutype'), mailto = this.href.substr(7); if (rcmail.env.calendar_resources && cutype == 'RESOURCE') { event_resources_dialog(mailto); } else { rcmail.command('compose', mailto, e ? e.target : null, e); } return false; }; // bring up the event dialog (jquery-ui popup) var event_edit_dialog = function(action, event) { // copy opener element from show dialog var op_elem = $("#eventshow:ui-dialog").data('opener'); // close show dialog first $("#eventshow:ui-dialog").data('opener', null).dialog('close'); var $dialog = $('
'); var calendar = event.calendar && me.calendars[event.calendar] ? me.calendars[event.calendar] : { editable:true, rights: action=='new' ? 'lrwitd' : 'lrs' }; me.selected_event = $.extend($.extend({}, event_defaults), event); // clone event object (with defaults) event = me.selected_event; // change reference to clone freebusy_ui.needsupdate = false; if (rcmail.env.action == 'dialog-ui') calendar.attendees = false; // TODO: allow Attendees tab in Save-as-event dialog // reset dialog first $('#eventedit form').trigger('reset'); $('#event-panel-recurrence input, #event-panel-recurrence select, #event-panel-attachments input').prop('disabled', false); $('#event-panel-recurrence, #event-panel-attachments').removeClass('disabled'); // allow other plugins to do actions when event form is opened rcmail.triggerEvent('calendar-event-init', {o: event}); // event details var title = $('#edit-title').val(event.title || ''); var location = $('#edit-location').val(event.location || ''); var description = $('#edit-description').text(event.description || ''); var vurl = $('#edit-url').val(event.vurl || ''); var categories = $('#edit-categories').val(event.categories); var calendars = $('#edit-calendar').val(event.calendar); var eventstatus = $('#edit-event-status').val(event.status); var freebusy = $('#edit-free-busy').val(event.free_busy); var priority = $('#edit-priority').val(event.priority); var sensitivity = $('#edit-sensitivity').val(event.sensitivity); var syncstart = $('#edit-recurrence-syncstart input'); var end = 'toDate' in event.end ? event.end : moment(event.end); var start = 'toDate' in event.start ? event.start : moment(event.start); var duration = Math.round((end.format('x') - start.format('x')) / 1000); // Correct the fullCalendar end date for all-day events if (!end.hasTime()) { end.subtract(1, 'days'); } var startdate = $('#edit-startdate').val(format_date(start, settings.date_format)).data('duration', duration); var starttime = $('#edit-starttime').val(format_date(start, settings.time_format)).show(); var enddate = $('#edit-enddate').val(format_date(end, settings.date_format)); var endtime = $('#edit-endtime').val(format_date(end, settings.time_format)).show(); var allday = $('#edit-allday').get(0); var notify = $('#edit-attendees-donotify').get(0); var invite = $('#edit-attendees-invite').get(0); var comment = $('#edit-attendees-comment'); // make sure any calendar is selected if (!calendars.val()) calendars.val($('option:first', calendars).attr('value')); invite.checked = settings.itip_notify & 1 > 0; notify.checked = me.has_attendees(event) && invite.checked; if (event.allDay) { starttime.val("12:00").hide(); endtime.val("13:00").hide(); allday.checked = true; } else { allday.checked = false; } // set calendar selection according to permissions calendars.find('option').each(function(i, opt) { var cal = me.calendars[opt.value] || {}; $(opt).prop('disabled', !(cal.editable || (action == 'new' && me.has_permission(cal, 'i')))) }); // set alarm(s) me.set_alarms_edit('#edit-alarms', action != 'new' && event.valarms && calendar.alarms ? event.valarms : []); // enable/disable alarm property according to backend support $('#edit-alarms')[(calendar.alarms ? 'show' : 'hide')](); // check categories drop-down: add value if not exists if (event.categories && !categories.find("option[value='"+event.categories+"']").length) { $(' '; list_html += '
' + role_html + dispname + '
'; // clone attendees data for local modifications freebusy_ui.attendees[i] = freebusy_ui.attendees[domid] = $.extend({}, data); } // add total row list_html += '
 
'; list_html += '
' + rcmail.gettext('reqallattendees','calendar') + '
'; $('#schedule-attendees-list').html(list_html) .unbind('click.roleicons') .bind('click.roleicons', function(e){ // toggle attendee status upon click on icon if (e.target.id && e.target.id.match(/rcmlia(.+)/)) { var attendee, domid = RegExp.$1, roles = [ 'REQ-PARTICIPANT', 'OPT-PARTICIPANT', 'NON-PARTICIPANT', 'CHAIR' ]; if ((attendee = freebusy_ui.attendees[domid]) && attendee.role != 'ORGANIZER') { var req = attendee.role != 'OPT-PARTICIPANT' && attendee.role != 'NON-PARTICIPANT'; var j = $.inArray(attendee.role, roles); j = (j+1) % roles.length; attendee.role = roles[j]; $(e.target).parent().attr('class', 'attendee '+String(attendee.role).toLowerCase()); // update total display if required-status changed if (req != (roles[j] != 'OPT-PARTICIPANT' && roles[j] != 'NON-PARTICIPANT')) { compute_freebusy_totals(); update_freebusy_display(attendee.email); } } } return false; }); // enable/disable buttons $('#schedule-find-prev').prop('disabled', fb_start.getTime() < now.getTime()); // dialog buttons var buttons = [ { text: rcmail.gettext('select', 'calendar'), 'class': 'save mainaction', click: function() { $('#edit-startdate').val(freebusy_ui.startdate.val()); $('#edit-starttime').val(freebusy_ui.starttime.val()); $('#edit-enddate').val(freebusy_ui.enddate.val()); $('#edit-endtime').val(freebusy_ui.endtime.val()); // write role changes back to main dialog $('select.edit-attendee-role').each(function(i, elem){ if (event_attendees[i] && freebusy_ui.attendees[i]) { event_attendees[i].role = freebusy_ui.attendees[i].role; $(elem).val(event_attendees[i].role); } }); if (freebusy_ui.needsupdate) update_freebusy_status(me.selected_event); freebusy_ui.needsupdate = false; $dialog.dialog("close"); } }, { text: rcmail.gettext('cancel', 'calendar'), 'class': 'cancel', click: function() { $dialog.dialog("close"); } } ]; $dialog.dialog({ modal: true, resizable: true, closeOnEscape: true, title: rcmail.gettext('scheduletime', 'calendar'), open: function() { rcmail.ksearch_blur(); $dialog.attr('aria-hidden', 'false').find('#schedule-find-next, #schedule-find-prev').not(':disabled').first().focus(); }, close: function() { $dialog.dialog("destroy").attr('aria-hidden', 'true').hide(); // TODO: focus opener button }, resizeStop: function() { render_freebusy_overlay(); }, buttons: buttons, minWidth: 640, width: 850 }).show(); // adjust dialog size to fit grid without scrolling var gridw = $('#schedule-freebusy-times').width(); var overflow = gridw - $('#attendees-freebusy-table td.times').width(); me.dialog_resize($dialog.get(0), $dialog.height() + (bw.ie ? 20 : 0), 800 + Math.max(0, overflow)); // fetch data from server freebusy_ui.loading = 0; load_freebusy_data(freebusy_ui.start, freebusy_ui.interval); }; // render an HTML table showing free-busy status for all the event attendees var render_freebusy_grid = function(delta) { if (delta) { freebusy_ui.start.setTime(freebusy_ui.start.getTime() + DAY_MS * delta); fix_date(freebusy_ui.start); // skip weekends if in workinhoursonly-mode if (Math.abs(delta) == 1 && freebusy_ui.workinhoursonly) { while (is_weekend(freebusy_ui.start)) freebusy_ui.start.setTime(freebusy_ui.start.getTime() + DAY_MS * delta); fix_date(freebusy_ui.start); } freebusy_ui.end = new Date(freebusy_ui.start.getTime() + DAY_MS * freebusy_ui.numdays); } var dayslots = Math.floor(1440 / freebusy_ui.interval); var date_format = 'ddd '+ (dayslots <= 2 ? settings.date_short : settings.date_format); var lastdate, datestr, css, curdate = new Date(), allday = (freebusy_ui.interval == 1440), interval = allday ? 1440 : (freebusy_ui.interval * (settings.timeslots || 1)); times_css = (allday ? 'allday ' : ''), dates_row = '', times_row = '', slots_row = ''; for (var s = 0, t = freebusy_ui.start.getTime(); t < freebusy_ui.end.getTime(); s++) { curdate.setTime(t); datestr = format_date(curdate, date_format); if (datestr != lastdate) { if (lastdate && !allday) break; dates_row += '' + Q(datestr) + ''; lastdate = datestr; } // set css class according to working hours css = is_weekend(curdate) || (freebusy_ui.interval <= 60 && !is_workinghour(curdate)) ? 'offhours' : 'workinghours'; times_row += '' + Q(allday ? rcmail.gettext('all-day','calendar') : format_date(curdate, settings.time_format)) + ''; slots_row += ' '; t += interval * 60000; } dates_row += ''; times_row += ''; // render list of attendees var domid, data, list_html = '', times_html = ''; for (var i=0; i < event_attendees.length; i++) { data = event_attendees[i]; domid = String(data.email).replace(rcmail.identifier_expr, ''); times_html += '' + slots_row + ''; } // add line for all/required attendees times_html += ''; times_html += '' + slots_row + ''; var table = $('#schedule-freebusy-times'); table.children('thead').html(dates_row + times_row); table.children('tbody').html(times_html); // initialize event handlers on grid if (!freebusy_ui.grid_events) { freebusy_ui.grid_events = true; table.children('thead').click(function(e){ // move event to the clicked date/time if (e.target.id && e.target.id.match(/t-(\d+)/)) { var newstart = new Date(RegExp.$1 * 1000); // set time to 00:00 if (me.selected_event.allDay) { newstart.setMinutes(0); newstart.setHours(0); } update_freebusy_dates(newstart, new Date(newstart.getTime() + freebusy_ui.startdate.data('duration') * 1000)); render_freebusy_overlay(); } }); } // if we have loaded free-busy data, show it if (!freebusy_ui.loading) { if (freebusy_ui.start < freebusy_data.start || freebusy_ui.end > freebusy_data.end || freebusy_ui.interval != freebusy_data.interval) { load_freebusy_data(freebusy_ui.start, freebusy_ui.interval); } else { for (var email, i=0; i < event_attendees.length; i++) { if ((email = event_attendees[i].email)) update_freebusy_display(email); } } } // render current event date/time selection over grid table // use timeout to let the dom attributes (width/height/offset) be set first window.setTimeout(function(){ render_freebusy_overlay(); }, 10); }; // render overlay element over the grid to visiualize the current event date/time var render_freebusy_overlay = function() { var overlay = $('#schedule-event-time'), event_start = 'toDate' in me.selected_event.start ? me.selected_event.start.toDate() : me.selected_event.start; event_end = 'toDate' in me.selected_event.end ? me.selected_event.end.toDate() : me.selected_event.end; if (event_end.getTime() <= freebusy_ui.start.getTime() || event_start.getTime() >= freebusy_ui.end.getTime()) { overlay.hide(); if (overlay.data('isdraggable')) overlay.draggable('disable'); } else { var i, n, table = $('#schedule-freebusy-times'), width = 0, pos = { top:table.children('thead').height(), left:0 }, eventstart = date2unixtime(clone_date(me.selected_event.start, me.selected_event.allDay?1:0)), eventend = date2unixtime(clone_date(me.selected_event.end, me.selected_event.allDay?2:0)) - 60, slotstart = date2unixtime(freebusy_ui.start), slotsize = freebusy_ui.interval * 60, slotnum = freebusy_ui.interval > 60 ? 1 : (60 / freebusy_ui.interval), cells = table.children('thead').find('td'), cell_width = cells.first().get(0).offsetWidth, h_margin = table.parents('table').data('h-margin'), v_margin = table.parents('table').data('v-margin'), slotend; if (h_margin === undefined) h_margin = 4; if (v_margin === undefined) v_margin = 4; // iterate through slots to determine position and size of the overlay for (i=0; i < cells.length; i++) { for (n=0; n < slotnum; n++) { slotend = slotstart + slotsize - 1; // event starts in this slot: compute left if (eventstart >= slotstart && eventstart <= slotend) { pos.left = Math.round(i * cell_width + (cell_width / slotnum) * n); } // event ends in this slot: compute width if (eventend >= slotstart && eventend <= slotend) { width = Math.round(i * cell_width + (cell_width / slotnum) * (n + 1)) - pos.left; } slotstart += slotsize; } } if (!width) width = table.width() - pos.left; // overlay is visible if (width > 0) { overlay.css({ width: (width - h_margin) + 'px', height: (table.children('tbody').height() - v_margin) + 'px', left: pos.left + 'px', top: pos.top + 'px' }).show(); // configure draggable if (!overlay.data('isdraggable')) { overlay.draggable({ axis: 'x', scroll: true, stop: function(e, ui){ // convert pixels to time var px = ui.position.left; var range_p = $('#schedule-freebusy-times').width(); var range_t = freebusy_ui.end.getTime() - freebusy_ui.start.getTime(); var newstart = new Date(freebusy_ui.start.getTime() + px * (range_t / range_p)); newstart.setSeconds(0); newstart.setMilliseconds(0); // snap to day boundaries if (me.selected_event.allDay) { if (newstart.getHours() >= 12) // snap to next day newstart.setTime(newstart.getTime() + DAY_MS); newstart.setMinutes(0); newstart.setHours(0); } else { // round to 5 minutes // @TODO: round to timeslots? var round = newstart.getMinutes() % 5; if (round > 2.5) newstart.setTime(newstart.getTime() + (5 - round) * 60000); else if (round > 0) newstart.setTime(newstart.getTime() - round * 60000); } // update event times and display update_freebusy_dates(newstart, new Date(newstart.getTime() + freebusy_ui.startdate.data('duration') * 1000)); if (me.selected_event.allDay) render_freebusy_overlay(); } }).data('isdraggable', true); } else overlay.draggable('enable'); } else overlay.draggable('disable').hide(); } }; // fetch free-busy information for each attendee from server var load_freebusy_data = function(from, interval) { var start = new Date(from.getTime() - DAY_MS * 2); // start 2 days before event fix_date(start); var end = new Date(start.getTime() + DAY_MS * Math.max(14, freebusy_ui.numdays + 7)); // load min. 14 days freebusy_ui.numrequired = 0; freebusy_data.all = []; freebusy_data.required = []; // load free-busy information for every attendee var domid, email; for (var i=0; i < event_attendees.length; i++) { if ((email = event_attendees[i].email)) { domid = String(email).replace(rcmail.identifier_expr, ''); $('#rcmli' + domid).addClass('loading'); freebusy_ui.loading++; $.ajax({ type: 'GET', dataType: 'json', url: rcmail.url('freebusy-times'), data: { email:email, start:date2servertime(clone_date(start, 1)), end:date2servertime(clone_date(end, 2)), interval:interval, _remote:1 }, success: function(data) { freebusy_ui.loading--; // find attendee var i, attendee = null; for (i=0; i < event_attendees.length; i++) { if (freebusy_ui.attendees[i].email == data.email) { attendee = freebusy_ui.attendees[i]; break; } } // copy data to member var var ts, status, req = attendee.role != 'OPT-PARTICIPANT', start = parseISO8601(data.start); freebusy_data.start = new Date(start); freebusy_data.end = parseISO8601(data.end); freebusy_data.interval = data.interval; freebusy_data[data.email] = {}; for (i=0; i < data.slots.length; i++) { ts = date2timestring(start, data.interval > 60); status = data.slots.charAt(i); freebusy_data[data.email][ts] = status start = new Date(start.getTime() + data.interval * 60000); // set totals if (!freebusy_data.required[ts]) freebusy_data.required[ts] = [0,0,0,0]; if (req) freebusy_data.required[ts][status]++; if (!freebusy_data.all[ts]) freebusy_data.all[ts] = [0,0,0,0]; freebusy_data.all[ts][status]++; } // hide loading indicator var domid = String(data.email).replace(rcmail.identifier_expr, ''); $('#rcmli' + domid).removeClass('loading'); // update display update_freebusy_display(data.email); } }); // count required attendees if (freebusy_ui.attendees[i].role != 'OPT-PARTICIPANT') freebusy_ui.numrequired++; } } }; // re-calculate total status after role change var compute_freebusy_totals = function() { freebusy_ui.numrequired = 0; freebusy_data.all = []; freebusy_data.required = []; var email, req, status; for (var i=0; i < event_attendees.length; i++) { if (!(email = event_attendees[i].email)) continue; req = freebusy_ui.attendees[i].role != 'OPT-PARTICIPANT'; if (req) freebusy_ui.numrequired++; for (var ts in freebusy_data[email]) { if (!freebusy_data.required[ts]) freebusy_data.required[ts] = [0,0,0,0]; if (!freebusy_data.all[ts]) freebusy_data.all[ts] = [0,0,0,0]; status = freebusy_data[email][ts]; freebusy_data.all[ts][status]++; if (req) freebusy_data.required[ts][status]++; } } }; // update free-busy grid with status loaded from server var update_freebusy_display = function(email) { var status_classes = ['unknown','free','busy','tentative','out-of-office']; var domid = String(email).replace(rcmail.identifier_expr, ''); var row = $('#fbrow' + domid); var rowall = $('#fbrowall').children(); var dateonly = freebusy_ui.interval > 60, t, ts = date2timestring(freebusy_ui.start, dateonly), curdate = new Date(), fbdata = freebusy_data[email]; if (fbdata && fbdata[ts] !== undefined && row.length) { t = freebusy_ui.start.getTime(); row.children().each(function(i, cell) { var j, n, attr, last, all_slots = [], slots = [], all_cell = rowall.get(i), cnt = dateonly ? 1 : (60 / freebusy_ui.interval), percent = (100 / cnt); for (n=0; n < cnt; n++) { curdate.setTime(t); ts = date2timestring(curdate, dateonly); attr = { 'style': 'float:left; width:' + percent.toFixed(2) + '%', 'class': fbdata[ts] ? status_classes[fbdata[ts]] : 'unknown' }; slots.push($('
').attr(attr)); // also update total row if all data was loaded if (!freebusy_ui.loading && freebusy_data.all[ts] && all_cell) { var w, all_status = freebusy_data.all[ts][2] ? 'busy' : 'unknown', req_status = freebusy_data.required[ts][2] ? 'busy' : 'free'; for (j=1; j < status_classes.length; j++) { if (freebusy_ui.numrequired && freebusy_data.required[ts][j] >= freebusy_ui.numrequired) req_status = status_classes[j]; if (freebusy_data.all[ts][j] == event_attendees.length) all_status = status_classes[j]; } attr['class'] = req_status + ' all-' + all_status; // these elements use some specific styling, so we want to minimize their number if (last && last.attr('class').startsWith(attr['class'])) { w = percent + parseFloat(last.css('width').replace('%', '')); last.css('width', w.toFixed(2) + '%').attr('class', attr['class'] + ' w' + w.toFixed(0)); } else { last = $('
').attr(attr).addClass('w' + percent.toFixed(0)).append(''); all_slots.push(last); } } t += freebusy_ui.interval * 60000; } $(cell).html('').append(slots); if (all_slots.length) $(all_cell).html('').append(all_slots); }); } }; // write changed event date/times back to form fields var update_freebusy_dates = function(start, end) { // fix all-day evebt times if (me.selected_event.allDay) { var numdays = Math.floor((me.selected_event.end.getTime() - me.selected_event.start.getTime()) / DAY_MS); start.setHours(12); start.setMinutes(0); end.setTime(start.getTime() + numdays * DAY_MS); end.setHours(13); end.setMinutes(0); } me.selected_event.start = start; me.selected_event.end = end; freebusy_ui.startdate.val(format_date(start, settings.date_format)); freebusy_ui.starttime.val(format_date(start, settings.time_format)); freebusy_ui.enddate.val(format_date(end, settings.date_format)); freebusy_ui.endtime.val(format_date(end, settings.time_format)); freebusy_ui.needsupdate = true; }; // attempt to find a time slot where all attemdees are available var freebusy_find_slot = function(dir) { // exit if free-busy data isn't available yet if (!freebusy_data || !freebusy_data.start) return false; var event = me.selected_event, eventstart = clone_date(event.start, event.allDay ? 1 : 0).getTime(), // calculate with integers eventend = clone_date(event.end, event.allDay ? 2 : 0).getTime(), duration = eventend - eventstart - (event.allDay ? HOUR_MS : 0), /* make sure we don't cross day borders on DST change */ sinterval = freebusy_data.interval * 60000, intvlslots = 1, numslots = Math.ceil(duration / sinterval), fb_start = freebusy_data.start.getTime(), fb_end = freebusy_data.end.getTime(), checkdate, slotend, email, ts, slot, slotdate = new Date(), candidatecount = 0, candidatestart = false, success = false; // shift event times to next possible slot eventstart += sinterval * intvlslots * dir; eventend += sinterval * intvlslots * dir; // iterate through free-busy slots and find candidates for (slot = dir > 0 ? fb_start : fb_end - sinterval; (dir > 0 && slot < fb_end) || (dir < 0 && slot >= fb_start); slot += sinterval * dir ) { slotdate.setTime(slot); // fix slot if just crossed a DST change if (event.allDay) { fix_date(slotdate); slot = slotdate.getTime(); } slotend = slot + sinterval; if ((dir > 0 && slotend <= eventstart) || (dir < 0 && slot >= eventend)) // skip continue; // respect workinghours setting if (freebusy_ui.workinhoursonly) { if (is_weekend(slotdate) || (freebusy_data.interval <= 60 && !is_workinghour(slotdate))) { // skip off-hours candidatestart = false; candidatecount = 0; continue; } } if (!candidatestart) candidatestart = slot; ts = date2timestring(slotdate, freebusy_data.interval > 60); // check freebusy data for all attendees for (var i=0; i < event_attendees.length; i++) { if (freebusy_ui.attendees[i].role != 'OPT-PARTICIPANT' && (email = freebusy_ui.attendees[i].email) && freebusy_data[email] && freebusy_data[email][ts] > 1) { candidatestart = false; break; } } // occupied slot if (!candidatestart) { slot += Math.max(0, intvlslots - candidatecount - 1) * sinterval * dir; candidatecount = 0; continue; } else if (dir < 0) candidatestart = slot; candidatecount++; // if candidate is big enough, this is it! if (candidatecount == numslots) { 'toDate' in event.start ? (event.start = new Date(candidatestart)) : event.start.setTime(candidatestart); 'toDate' in event.end ? (event.end = new Date(candidatestart + duration)) : event.end.setTime(candidatestart + duration); success = true; break; } } // update event date/time display if (success) { update_freebusy_dates(event.start, event.end); // move freebusy grid if necessary var event_start = 'toDate' in event.start ? event.start.toDate() : event.start, event_end = 'toDate' in event.end ? event.end.toDate() : event.end, offset = Math.ceil((event_start.getTime() - freebusy_ui.end.getTime()) / DAY_MS), now = new Date(); if (event_start.getTime() >= freebusy_ui.end.getTime()) render_freebusy_grid(Math.max(1, offset)); else if (event_end.getTime() <= freebusy_ui.start.getTime()) render_freebusy_grid(Math.min(-1, offset)); else render_freebusy_overlay(); $('#schedule-find-prev').prop('disabled', event_start.getTime() < now.getTime()); // speak new selection rcmail.display_message(rcmail.gettext('suggestedslot', 'calendar') + ': ' + me.event_date_text(event, true), 'voice'); } else { rcmail.alert_dialog(rcmail.gettext('noslotfound','calendar')); } }; // update event properties and attendees availability if event times have changed var event_times_changed = function() { if (me.selected_event) { var allday = $('#edit-allday').get(0); me.selected_event.allDay = allday.checked; me.selected_event.start = me.parse_datetime(allday.checked ? '12:00' : $('#edit-starttime').val(), $('#edit-startdate').val()); me.selected_event.end = me.parse_datetime(allday.checked ? '13:00' : $('#edit-endtime').val(), $('#edit-enddate').val()); if (event_attendees) freebusy_ui.needsupdate = true; $('#edit-startdate').data('duration', Math.round((me.selected_event.end.getTime() - me.selected_event.start.getTime()) / 1000)); } }; // add the given list of participants var add_attendees = function(names, params) { names = explode_quoted_string(names.replace(/,\s*$/, ''), ','); // parse name/email pairs var item, email, name, success = false; for (var i=0; i < names.length; i++) { email = name = ''; item = $.trim(names[i]); if (!item.length) { continue; } // address in brackets without name (do nothing) else if (item.match(/^<[^@]+@[^>]+>$/)) { email = item.replace(/[<>]/g, ''); } // address without brackets and without name (add brackets) else if (rcube_check_email(item)) { email = item; } // address with name else if (item.match(/([^\s<@]+@[^>]+)>*$/)) { email = RegExp.$1; name = item.replace(email, '').replace(/^["\s<>]+/, '').replace(/["\s<>]+$/, ''); } if (email) { add_attendee($.extend({ email:email, name:name }, params)); success = true; } else { rcmail.alert_dialog(rcmail.gettext('noemailwarning')); } } return success; }; // add the given attendee to the list var add_attendee = function(data, readonly, before) { if (!me.selected_event) return false; // check for dupes... var exists = false; $.each(event_attendees, function(i, v){ exists |= (v.email == data.email); }); if (exists) return false; var calendar = me.selected_event && me.calendars[me.selected_event.calendar] ? me.calendars[me.selected_event.calendar] : me.calendars[me.selected_calendar]; var dispname = Q(data.name || data.email); dispname = '' + dispname + ''; // role selection var organizer = data.role == 'ORGANIZER'; var opts = {}; if (organizer) opts.ORGANIZER = rcmail.gettext('calendar.roleorganizer'); opts['REQ-PARTICIPANT'] = rcmail.gettext('calendar.rolerequired'); opts['OPT-PARTICIPANT'] = rcmail.gettext('calendar.roleoptional'); opts['NON-PARTICIPANT'] = rcmail.gettext('calendar.rolenonparticipant'); if (data.cutype != 'RESOURCE') opts['CHAIR'] = rcmail.gettext('calendar.rolechair'); if (organizer && !readonly) dispname = rcmail.env['identities-selector']; var select = ''; // delete icon var icon = rcmail.env.deleteicon ? '' : '' + Q(rcmail.gettext('delete')) + ''; var dellink = '' + icon + ''; var tooltip = '', status = (data.status || '').toLowerCase(), status_label = rcmail.gettext('status' + status, 'libcalendaring'); // send invitation checkbox var invbox = ''; if (data['delegated-to']) tooltip = rcmail.gettext('libcalendaring.delegatedto') + ' ' + data['delegated-to']; else if (data['delegated-from']) tooltip = rcmail.gettext('libcalendaring.delegatedfrom') + ' ' + data['delegated-from']; else if (!status && organizer) tooltip = rcmail.gettext('statusorganizer', 'libcalendaring'); else if (status) tooltip = status_label; // add expand button for groups if (data.cutype == 'GROUP') { dispname += ' ' + rcmail.gettext('expandattendeegroup','libcalendaring') + ''; } var avail = data.email ? 'loading' : 'unknown'; var table = rcmail.env.calendar_resources && data.cutype == 'RESOURCE' ? resources_list : attendees_list; var img_src = rcmail.assets_path('program/resources/blank.gif'); var elastic = $(table).parents('.no-img').length > 0; var avail_tag = elastic ? ('' + '' + dispname + '' + '' + avail_tag + ' data-email="' + data.email + '" />' + '' + Q(status && !elastic ? status_label : '') + '' + (data.cutype != 'RESOURCE' ? '' + (organizer || readonly || !invbox ? '' : invbox) + '' : '') + '' + (organizer || readonly ? '' : dellink) + ''; var tr = $('') .addClass(String(data.role).toLowerCase()) .html(html); if (before) tr.insertBefore(before) else tr.appendTo(table); tr.find('a.deletelink').click({ id:(data.email || data.name) }, function(e) { remove_attendee(this, e.data.id); return false; }); tr.find('a.expandlink').click(data, function(e) { me.expand_attendee_group(e, add_attendee, remove_attendee); return false; }); tr.find('input.edit-attendee-reply').click(function() { var enabled = $('#edit-attendees-invite:checked').length || $('input.edit-attendee-reply:checked').length; $('#eventedit .attendees-commentbox')[enabled ? 'show' : 'hide'](); }); // select organizer identity if (data.identity_id) $('#edit-identities-list').val(data.identity_id); // check free-busy status if (avail == 'loading') { check_freebusy_status(tr.find('.availability > *:first'), data.email, me.selected_event); } // Make Elastic checkboxes pretty if (window.UI && UI.pretty_checkbox) { $(tr).find('input[type=checkbox]').each(function() { UI.pretty_checkbox(this); }); $(tr).find('select').each(function() { UI.pretty_select(this); }); } event_attendees.push(data); return true; }; // iterate over all attendees and update their free-busy status display var update_freebusy_status = function(event) { attendees_list.find('.availability > *').each(function(i,v) { var email, icon = $(this); if (email = icon.attr('data-email')) check_freebusy_status(icon, email, event); }); freebusy_ui.needsupdate = false; }; // load free-busy status from server and update icon accordingly var check_freebusy_status = function(icon, email, event) { var calendar = event.calendar && me.calendars[event.calendar] ? me.calendars[event.calendar] : { freebusy:false }; if (!calendar.freebusy) { $(icon).attr('class', 'availabilityicon unknown'); return; } icon = $(icon).attr('class', 'availabilityicon loading'); $.ajax({ type: 'GET', dataType: 'html', url: rcmail.url('freebusy-status'), data: { email:email, start:date2servertime(clone_date(event.start, event.allDay?1:0)), end:date2servertime(clone_date(event.end, event.allDay?2:0)), _remote: 1 }, success: function(status){ var avail = String(status).toLowerCase(); icon.removeClass('loading').addClass(avail).attr('title', rcmail.gettext('avail' + avail, 'calendar')); }, error: function(){ icon.removeClass('loading').addClass('unknown').attr('title', rcmail.gettext('availunknown', 'calendar')); } }); }; // remove an attendee from the list var remove_attendee = function(elem, id) { $(elem).closest('tr').remove(); event_attendees = $.grep(event_attendees, function(data){ return (data.name != id && data.email != id) }); }; // open a dialog to display detailed free-busy information and to find free slots var event_resources_dialog = function(search) { var $dialog = $('#eventresourcesdialog'); if ($dialog.is(':ui-dialog')) $dialog.dialog('close'); // dialog buttons var buttons = [ { text: rcmail.gettext('addresource', 'calendar'), 'class': 'mainaction save', click: function() { rcmail.command('add-resource'); $dialog.dialog("close"); } }, { text: rcmail.gettext('close'), 'class': 'cancel', click: function() { $dialog.dialog("close"); } } ]; var resize = function() { var container = $(rcmail.gui_objects.resourceinfocalendar); container.fullCalendar('option', 'height', container.height() + 1); }; // open jquery UI dialog $dialog.dialog({ modal: true, resizable: false, // prevents from Availability tab reflow bugs on resize closeOnEscape: true, title: rcmail.gettext('findresources', 'calendar'), classes: {'ui-dialog': 'selection-dialog resources-dialog'}, open: function() { rcmail.ksearch_blur(); $dialog.attr('aria-hidden', 'false'); // for Elastic if ($('html.layout-small,html.layout-phone').length) { $('#eventresourcesdialog .resource-selection').css('display', 'flex'); $('#eventresourcesdialog .resource-content').css('display', 'none'); } setTimeout(resize, 50); }, close: function() { $dialog.dialog('destroy').attr('aria-hidden', 'true').hide(); }, resize: resize, buttons: buttons, width: 900, height: 500 }).show(); $('.ui-dialog-buttonset button', $dialog.parent()).first().attr('id', 'rcmbtncalresadd'); me.dialog_resize($dialog.get(0), 540, Math.min(1000, $(window).width() - 50)); // set search query $('#resourcesearchbox').val(search || ''); // initialize the treelist widget if (!resources_treelist) { resources_treelist = new rcube_treelist_widget(rcmail.gui_objects.resourceslist, { id_prefix: 'rcres', id_encode: rcmail.html_identifier_encode, id_decode: rcmail.html_identifier_decode, selectable: true, save_state: true }); resources_treelist.addEventListener('select', function(node) { if (resources_data[node.id]) { resource_showinfo(resources_data[node.id]); rcmail.enable_command('add-resource', me.selected_event && $("#eventedit").is(':visible')); // on elastic mobile display resource info box if ($('html.layout-small,html.layout-phone').length) { $('#eventresourcesdialog .resource-selection').css('display', 'none'); $('#eventresourcesdialog .resource-content').css('display', 'flex'); $(window).resize(); resize(); } } else { rcmail.enable_command('add-resource', false); $(rcmail.gui_objects.resourceinfo).hide(); $(rcmail.gui_objects.resourceownerinfo).hide(); $(rcmail.gui_objects.resourceinfocalendar).fullCalendar('removeEventSources'); } }); // fetch (all) resource data from server me.loading_lock = rcmail.set_busy(true, 'loading', me.loading_lock); rcmail.http_request('resources-list', {}, me.loading_lock); // register button rcmail.register_button('add-resource', 'rcmbtncalresadd', 'button'); // initialize resource calendar display var resource_cal = $(rcmail.gui_objects.resourceinfocalendar); resource_cal.fullCalendar($.extend({}, fullcalendar_defaults, { header: { left: '', center: '', right: '' }, height: resource_cal.height() + 4, defaultView: 'agendaWeek', eventSources: [], slotMinutes: 60, allDaySlot: false, eventRender: function(event, element, view) { var title = rcmail.get_label(event.status, 'calendar'); element.addClass('status-' + event.status); element.find('.fc-title').text(title); element.attr('aria-label', me.event_date_text(event, true) + ': ' + title); } })); $('#resource-calendar-prev').click(function(){ resource_cal.fullCalendar('prev'); return false; }); $('#resource-calendar-next').click(function(){ resource_cal.fullCalendar('next'); return false; }); } else if (search) { resource_search(); } else { resource_render_list(resources_index); } if (me.selected_event && me.selected_event.start) { $(rcmail.gui_objects.resourceinfocalendar).fullCalendar('gotoDate', me.selected_event.start); } }; // render the resource details UI box var resource_showinfo = function(resource) { // inline function to render a resource attribute function render_attrib(value) { if (typeof value == 'boolean') { return value ? rcmail.get_label('yes') : rcmail.get_label('no'); } return value; } if (rcmail.gui_objects.resourceinfo) { var tr, table = $(rcmail.gui_objects.resourceinfo).show().find('tbody').html(''), attribs = $.extend({ name:resource.name }, resource.attributes||{}) attribs.description = resource.description; for (var k in attribs) { if (typeof attribs[k] == 'undefined') continue; table.append($('').addClass(k + ' form-group row') .append('') .append('' + text2html(render_attrib(attribs[k])) + '') ); } $(rcmail.gui_objects.resourceownerinfo).hide(); $(rcmail.gui_objects.resourceinfocalendar).fullCalendar('removeEventSources'); if (resource.owner) { // display cached data if (resource_owners[resource.owner]) { resource_owner_load(resource_owners[resource.owner]); } else { // fetch owner data from server me.loading_lock = rcmail.set_busy(true, 'loading', me.loading_lock); rcmail.http_request('resources-owner', { _id: resource.owner }, me.loading_lock); } } // load resource calendar resources_events_source.url = "./?_task=calendar&_action=resources-calendar&_id="+urlencode(resource.ID); $(rcmail.gui_objects.resourceinfocalendar).fullCalendar('addEventSource', resources_events_source); } }; // callback from server for resource listing var resource_data_load = function(data) { var resources_tree = {}; // store data by ID $.each(data, function(i, rec) { resources_data[rec.ID] = rec; // assign parent-relations if (rec.members) { $.each(rec.members, function(j, m){ resources_tree[m] = rec.ID; }); } }); // walk the parent-child tree to determine the depth of each node $.each(data, function(i, rec) { rec._depth = 0; if (resources_tree[rec.ID]) rec.parent_id = resources_tree[rec.ID]; var parent_id = resources_tree[rec.ID]; while (parent_id) { rec._depth++; parent_id = resources_tree[parent_id]; } }); // sort by depth, collection and name data.sort(function(a,b) { var j = a._type == 'collection' ? 1 : 0, k = b._type == 'collection' ? 1 : 0, d = a._depth - b._depth; if (!d) d = (k - j); if (!d) d = b.name < a.name ? 1 : -1; return d; }); $.each(data, function(i, rec) { resources_index.push(rec.ID); }); // apply search filter... if ($('#resourcesearchbox').val() != '') resource_search(); else // ...or render full list resource_render_list(resources_index); rcmail.set_busy(false, null, me.loading_lock); }; // renders the given list of resource records into the treelist var resource_render_list = function(index) { var rec, link; resources_treelist.reset(); $.each(index, function(i, dn) { if (rec = resources_data[dn]) { link = $('').attr('href', '#') .attr('rel', rec.ID) .html(Q(rec.name)); resources_treelist.insert({ id:rec.ID, html:link, classes:[rec._type], collapsed:true }, rec.parent_id, false); } }); }; // callback from server for owner information display var resource_owner_load = function(data) { if (data) { // cache this! resource_owners[data.ID] = data; var table = $(rcmail.gui_objects.resourceownerinfo).find('tbody').html(''); for (var k in data) { if (k == 'event' || k == 'ID') continue; table.append($('').addClass(k) .append('' + Q(ucfirst(rcmail.get_label(k, 'calendar'))) + '') .append('' + text2html(data[k]) + '') ); } table.parent().show(); } } // quick-filter the loaded resource data var resource_search = function() { var dn, rec, dataset = [], q = $('#resourcesearchbox').val().toLowerCase(); if (q.length && resources_data) { // search by iterating over all resource records for (dn in resources_data) { rec = resources_data[dn]; if ((rec.name && String(rec.name).toLowerCase().indexOf(q) >= 0) || (rec.email && String(rec.email).toLowerCase().indexOf(q) >= 0) || (rec.description && String(rec.description).toLowerCase().indexOf(q) >= 0) ) { dataset.push(rec.ID); } } resource_render_list(dataset); // select single match if (dataset.length == 1) { resources_treelist.select(dataset[0]); } } else { $('#resourcesearchbox').val(''); } }; // var reset_resource_search = function() { $('#resourcesearchbox').val('').focus(); resource_render_list(resources_index); }; // var add_resource2event = function() { var resource = resources_data[resources_treelist.get_selection()]; if (resource) add_attendee($.extend({ role:'REQ-PARTICIPANT', status:'NEEDS-ACTION', cutype:'RESOURCE' }, resource)); } var is_this_me = function(email) { if (settings.identity.emails.indexOf(';'+email) >= 0 || settings.identity.ownedResources.indexOf(';'+email) >= 0) { return true; } return false; }; // when the user accepts or declines an event invitation var event_rsvp = function(response, delegate, replymode, event) { var btn; if (typeof response == 'object') { btn = $(response); response = btn.attr('rel') } else { btn = $('#event-rsvp input.button[rel='+response+']'); } // show menu to select rsvp reply mode (current or all) if (me.selected_event && me.selected_event.recurrence && !replymode) { rcube_libcalendaring.itip_rsvp_recurring(btn, function(resp, mode) { event_rsvp(resp, null, mode, event); }, event); return; } if (me.selected_event && me.selected_event.attendees && response) { // bring up delegation dialog if (response == 'delegated' && !delegate) { rcube_libcalendaring.itip_delegate_dialog(function(data) { data.rsvp = data.rsvp ? 1 : ''; event_rsvp('delegated', data, replymode, event); }); return; } // update attendee status attendees = []; for (var data, i=0; i < me.selected_event.attendees.length; i++) { data = me.selected_event.attendees[i]; //FIXME this can only work if there is a single resource per invitation if (is_this_me(String(data.email).toLowerCase())) { data.status = response.toUpperCase(); data.rsvp = 0; // unset RSVP flag if (data.status == 'DELEGATED') { data['delegated-to'] = delegate.to; data.rsvp = delegate.rsvp } else { if (data['delegated-to']) { delete data['delegated-to']; if (data.role == 'NON-PARTICIPANT' && data.status != 'DECLINED') data.role = 'REQ-PARTICIPANT'; } } attendees.push(i) } else if (response != 'DELEGATED' && data['delegated-from'] && settings.identity.emails.indexOf(';'+String(data['delegated-from']).toLowerCase()) >= 0) { delete data['delegated-from']; } // set free_busy status to transparent if declined (#4425) if (data.status == 'DECLINED' || data.role == 'NON-PARTICIPANT') { me.selected_event.free_busy = 'free'; } else { me.selected_event.free_busy = 'busy'; } } // submit status change to server var submit_data = $.extend({}, { source:null, comment:$('#reply-comment-event-rsvp').val(), _savemode: replymode || 'all' }, (delegate || {})), submit_items = 'id,uid,_instance,calendar,_mbox,_uid,_part,attendees,free_busy,allDay', noreply = $('#noreply-event-rsvp:checked').length ? 1 : 0; // Submit only that data we really need $.each(submit_items.split(','), function() { if (this in me.selected_event) submit_data[this] = me.selected_event[this]; }); // import event from mail (temporary iTip event) if (submit_data._mbox && submit_data._uid) { me.saving_lock = rcmail.set_busy(true, 'calendar.savingdata'); rcmail.http_post('mailimportitip', { _mbox: submit_data._mbox, _uid: submit_data._uid, _part: submit_data._part, _status: response, _to: (delegate ? delegate.to : null), _rsvp: (delegate && delegate.rsvp) ? 1 : 0, _noreply: noreply, _comment: submit_data.comment, _instance: submit_data._instance, _savemode: submit_data._savemode }); } else if (settings.invitation_calendars) { update_event('rsvp', submit_data, { status:response, noreply:noreply, attendees:attendees }); } else { me.saving_lock = rcmail.set_busy(true, 'calendar.savingdata'); rcmail.http_post('calendar/event', { action:'rsvp', e:submit_data, status:response, attendees:attendees, noreply:noreply }); } event_show_dialog(me.selected_event); } }; // add the given date to the RDATE list var add_rdate = function(date) { var li = $('
  • ') .attr('data-value', date2servertime(date)) .append($('').text(format_date(date, settings.date_format))) .appendTo('#edit-recurrence-rdates'); $('').attr('href', '#del') .addClass('iconbutton delete') .html(rcmail.get_label('delete', 'calendar')) .attr('title', rcmail.get_label('delete', 'calendar')) .appendTo(li); }; // re-sort the list items by their 'data-value' attribute var sort_rdates = function() { var mylist = $('#edit-recurrence-rdates'), listitems = mylist.children('li').get(); listitems.sort(function(a, b) { var compA = $(a).attr('data-value'); var compB = $(b).attr('data-value'); return (compA < compB) ? -1 : (compA > compB) ? 1 : 0; }) $.each(listitems, function(idx, item) { mylist.append(item); }); } // remove the link reference matching the given uri function remove_link(elem) { var $elem = $(elem), uri = $elem.attr('data-uri'); me.selected_event.links = $.grep(me.selected_event.links, function(link) { return link.uri != uri; }); // remove UI list item $elem.hide().closest('li').addClass('deleted'); } // post the given event data to server var update_event = function(action, data, add) { me.saving_lock = rcmail.set_busy(true, 'calendar.savingdata'); rcmail.http_post('calendar/event', $.extend({ action:action, e:data }, (add || {}))); // render event temporarily into the calendar if ((data.start && data.end) || data.id) { var tmp, event = data.id ? $.extend(fc.fullCalendar('clientEvents', data.id)[0], data) : data; if (data.start) event.start = data.start; if (data.end) event.end = data.end; if (data.allDay !== undefined) event.allDay = !!data.allDay; // must be boolean for fullcalendar // For fullCalendar all-day event's end date must be exclusive if (event.allDay && data.end && (tmp = moment(data.end)) && tmp.format('Hms') !== '000') { event.end = moment().year(tmp.year()).month(tmp.month()).date(tmp.date()).hour(0).minute(0).second(0).add(1, 'days'); } event.editable = false; event.temp = true; event.className = ['fc-event-temp']; fc.fullCalendar(data.id ? 'updateEvent' : 'renderEvent', event); // mark all recurring instances as temp if (event.recurrence || event.recurrence_id) { var base_id = event.recurrence_id ? event.recurrence_id : String(event.id).replace(/-\d+(T\d{6})?$/, ''); $.each(fc.fullCalendar('clientEvents', function(e){ return e.id == base_id || e.recurrence_id == base_id; }), function(i,ev) { ev.temp = true; ev.editable = false; event.className.push('fc-event-temp'); fc.fullCalendar('updateEvent', ev); }); } } }; // mouse-click handler to check if the show dialog is still open and prevent default action var dialog_check = function(e) { var showd = $("#eventshow"); if (showd.is(':visible') && !$(e.target).closest('.ui-dialog').length && !$(e.target).closest('.popupmenu').length) { showd.dialog('close'); e.stopImmediatePropagation(); ignore_click = true; return false; } else if (ignore_click) { window.setTimeout(function(){ ignore_click = false; }, 20); return false; } return true; }; // display confirm dialog when modifying/deleting an event var update_event_confirm = function(action, event, data) { // Allow other plugins to do actions here // E.g. when you move/resize the event init wasn't called // but we need it as some plugins may modify user identities // we depend on here (kolab_delegation) rcmail.triggerEvent('calendar-event-init', {o: event}); if (!data) data = event; var decline = false, notify = false, html = '', cal = me.calendars[event.calendar], _is_invitation = String(event.calendar).match(/^--invitation--(declined|pending)/) && RegExp.$1, _has_attendees = me.has_attendees(event), _is_attendee = _has_attendees && me.is_attendee(event), _is_organizer = me.is_organizer(event); // event has attendees, ask whether to notify them if (_has_attendees) { var checked = (settings.itip_notify & 1 ? ' checked="checked"' : ''); if (action == 'remove' && cal.group != 'shared' && !_is_organizer && _is_attendee && _is_invitation != 'declined') { decline = true; checked = event.status != 'CANCELLED' ? checked : ''; html += '
    ' + '
    '; } else if (_is_organizer) { notify = true; if (settings.itip_notify & 2) { html += '
    ' + '
    '; } else { data._notify = settings.itip_notify; } } else if (cal.group != 'shared' && !_is_invitation) { html += '
    ' + $('#edit-localchanges-warning').html() + '
    '; data._notify = 0; } } // recurring event: user needs to select the savemode if (event.recurrence) { var future_disabled = '', message_label = (action == 'remove' ? 'removerecurringeventwarning' : 'changerecurringeventwarning'); // disable the 'future' savemode if I'm an attendee // reason: no calendaring system supports the thisandfuture range parameter in iTip REPLY if (action == 'remove' && !_is_organizer && _is_attendee) { future_disabled = ' disabled'; } html += '
    ' + rcmail.gettext(message_label, 'calendar') + '
    ' + '
    '; } // show dialog if (html) { var $dialog = $('
    ').html(html); $dialog.find('a.button').filter(':not(.disabled)').click(function(e) { data._savemode = String(this.href).replace(/.+#/, ''); // open event edit dialog when saving as new if (data._savemode == 'new') { event._savemode = 'new'; event_edit_dialog('edit', event); fc.fullCalendar('refetchEvents'); } else { if ($dialog.find('input.confirm-attendees-donotify').length) data._notify = $dialog.find('input.confirm-attendees-donotify').get(0).checked ? 1 : 0; if (decline) { data._decline = $dialog.find('input.confirm-attendees-decline:checked').length; data._notify = 0; } update_event(action, data); } $dialog.dialog("close"); return false; }); var buttons = []; if (!event.recurrence) { buttons.push({ text: rcmail.gettext((action == 'remove' ? 'delete' : 'save'), 'calendar'), 'class': action == 'remove' ? 'delete mainaction' : 'save mainaction', click: function() { data._notify = notify && $dialog.find('input.confirm-attendees-donotify:checked').length ? 1 : 0; data._decline = decline && $dialog.find('input.confirm-attendees-decline:checked').length ? 1 : 0; update_event(action, data); $(this).dialog("close"); } }); } buttons.push({ text: rcmail.gettext('cancel', 'calendar'), 'class': 'cancel', click: function() { $(this).dialog("close"); } }); $dialog.dialog({ modal: true, width: 460, dialogClass: 'warning', title: rcmail.gettext((action == 'remove' ? 'removeeventconfirm' : 'changeeventconfirm'), 'calendar'), buttons: buttons, open: function() { setTimeout(function(){ $dialog.parent().find('button:not(.ui-dialog-titlebar-close)').first().focus(); }, 5); }, close: function(){ $dialog.dialog("destroy").remove(); if (!rcmail.busy) fc.fullCalendar('refetchEvents'); } }).addClass('event-update-confirm').show(); return false; } // show regular confirm box when deleting else if (action == 'remove' && !cal.undelete) { if (!confirm(rcmail.gettext('deleteventconfirm', 'calendar'))) return false; } // do update update_event(action, data); return true; }; /*** public methods ***/ /** * Remove saving lock and free the UI for new input */ this.unlock_saving = function() { if (me.saving_lock) rcmail.set_busy(false, null, me.saving_lock); }; // opens the given calendar in a popup dialog this.quickview = function(id, shift) { var src, in_quickview = false; $.each(this.quickview_sources, function(i,cal) { if (cal.id == id) { in_quickview = true; src = cal; } }); // remove source from quickview if (in_quickview && shift) { this.quickview_sources = $.grep(this.quickview_sources, function(src) { return src.id != id; }); } else { if (!shift) { // remove all current quickview event sources if (this.quickview_active) { fc.fullCalendar('removeEventSources'); } this.quickview_sources = []; // uncheck all active quickview icons calendars_list.container.find('div.focusview') .add('#calendars .searchresults div.focusview') .removeClass('focusview') .find('a.quickview').attr('aria-checked', 'false'); } if (!in_quickview) { // clone and modify calendar properties src = $.extend({}, this.calendars[id]); src.url += '&_quickview=1'; this.quickview_sources.push(src); } } // disable quickview if (this.quickview_active && !this.quickview_sources.length) { // register regular calendar event sources $.each(this.calendars, function(k, cal) { if (cal.active) fc.fullCalendar('addEventSource', cal); }); this.quickview_active = false; $('body').removeClass('quickview-active'); // uncheck all active quickview icons calendars_list.container.find('div.focusview') .add('#calendars .searchresults div.focusview') .removeClass('focusview') .find('a.quickview').attr('aria-checked', 'false'); } // activate quickview else if (!this.quickview_active) { // remove regular calendar event sources fc.fullCalendar('removeEventSources'); // register quickview event sources $.each(this.quickview_sources, function(i, src) { fc.fullCalendar('addEventSource', src); }); this.quickview_active = true; $('body').addClass('quickview-active'); } // update quickview sources else if (in_quickview) { fc.fullCalendar('removeEventSource', src); } else if (src) { fc.fullCalendar('addEventSource', src); } // activate quickview icon if (this.quickview_active) { $(calendars_list.get_item(id)).find('.calendar').first() .add('#calendars .searchresults .cal-' + id) [in_quickview ? 'removeClass' : 'addClass']('focusview') .find('a.quickview').attr('aria-checked', in_quickview ? 'false' : 'true'); } }; // disable quickview mode function reset_quickview() { // remove all current quickview event sources if (me.quickview_active) { fc.fullCalendar('removeEventSources'); me.quickview_sources = []; } // register regular calendar event sources $.each(me.calendars, function(k, cal) { if (cal.active) fc.fullCalendar('addEventSource', cal); }); // uncheck all active quickview icons calendars_list.container.find('div.focusview') .add('#calendars .searchresults div.focusview') .removeClass('focusview') .find('a.quickview').attr('aria-checked', 'false'); me.quickview_active = false; $('body').removeClass('quickview-active'); }; //public method to show the print dialog. this.print_calendars = function(view) { if (!view) view = fc.fullCalendar('getView').name; var date = fc.fullCalendar('getDate').toDate(); rcmail.open_window(rcmail.url('print', { view: view, date: date2unixtime(date), range: settings.agenda_range, search: this.search_query }), true, true); }; // public method to bring up the new event dialog this.add_event = function(templ) { if (this.selected_calendar) { var now = new Date(); var date = fc.fullCalendar('getDate').toDate(); date.setHours(now.getHours()+1); date.setMinutes(0); var end = new Date(date.getTime()); end.setHours(date.getHours()+1); event_edit_dialog('new', $.extend({ start:date, end:end, allDay:false, calendar:this.selected_calendar }, templ || {})); } }; // delete the given event after showing a confirmation dialog this.delete_event = function(event) { // show confirm dialog for recurring events, use jquery UI dialog return update_event_confirm('remove', event, { id:event.id, calendar:event.calendar, attendees:event.attendees }); }; //opens a dialog to add caldav sources this.calendar_new_source = function() { var title = rcmail.gettext('addsources', 'calendar'), params = {action: 'form-source-new', _framed: 1}, $dialog = $('