//compile 0a1a5a5d8ee6affa8ab79b4be4d87ea8
function calendar_callbacks(){
  this.setTimeline = function(){
    var parentDiv = $(".fc-agenda-slots:visible").parent();
    var timeline = parentDiv.children(".timeline");
    rcmail.env.calendar_timeline = timeline;
    if (timeline.length == 0) {
      timeline = $("<hr>").addClass("timeline");
      parentDiv.prepend(timeline);
    }

    var curTime = new Date();

    var curCalView = $('#calendar').fullCalendar("getView");
    if (curCalView.visStart < curTime && curCalView.visEnd > curTime) {
      timeline.show();
    }
    else {
      timeline.hide();
    }

    var curSeconds = (curTime.getHours() * 60 * 60) + (curTime.getMinutes() * 60) + curTime.getSeconds();
    var percentOfDay = curSeconds / 86400;
    var topLoc = Math.floor(parentDiv.height() * percentOfDay);

    timeline.css("top", topLoc + "px");

    if (curCalView.name == "agendaWeek" || curCalView.name == "agendaDay") {
      var fudge = 1;
      var left = 0;
      var width, dayCol;
      if(curCalView.name == "agendaWeek"){
        dayCol = $(".fc-today:visible");
        try{
          left = dayCol.position().left;
          width = dayCol.width() + 'px';
        }
        catch(e){
          timeline.hide();
        }
      }
      if(curCalView.name == "agendaDay"){
        left = 70;
        fudge = 0;
        width = '100%';
      }
      if(left > 0){
        left = left + fudge;
        timeline.css({
          left: left + "px",
          width: width
        });
      }
    }
    else{
      timeline.hide();
    }
  }
  this.viewDisplay = function(view, response){
    var d = $('#calendar').fullCalendar('getDate');
    wn = d.getWeekOfYearStartMonday(d);
    var bd = new Date(d.getFullYear(), d.getMonth(), 1, 0, 0, 0);
    bds = d.getWeekOfYearStartMonday(bd);
    var ed = new Date(d.getFullYear(), d.getMonth(), d.getDaysInMonth(), 23, 59, 59);
    eds = d.getWeekOfYearStartMonday(ed);
    var wr = bds + " - " + eds;
    if(view.name == "month"){
      $('#monthbut').focus();
      $('#datepicker-title').html("<center>"+view.title+"</center>");
      $('#weeknumber').html("<center>"+response.settings['calendar_week'] + ": " + wr + "</center>");
    }
    if(view.name == "agendaDay"){
      $('#daybut').focus();
      $('#datepicker-title').html("<center>"+view.title+"</center>");
      $('#weeknumber').html("&nbsp;");
    }
    if(view.name == "agendaWeek"){
      $('#weekbut').focus();
      $('#datepicker-title').html("<center>"+view.title+"</center>");
      $('#weeknumber').html("<center>"+response.settings['calendar_week'] + ": " + wn + "</center>");
    }
    if(view.name == "agendaWeek" || view.name == "agendaDay"){
      if(timelineInterval){
        window.clearInterval(timelineInterval);
      }
      var timelineInterval = window.setInterval(calendar_callbacks.setTimeline, 10000);
      try {
        calendar_callbacks.setTimeline();
      } catch(err) { }
    }
    else{
      if(rcmail.env.calendar_timeline)
        rcmail.env.calendar_timeline.hide();
    }
  }
  this.qtip = function(event, element, mode){
    element = calendar_common.qtip(event, element);
    return element;
  }
  this.loading = function(isLoading, msgid){
    var view = $('#calendar').fullCalendar('getView');
    var now = new Date().getTime();
    var vstart = view.start.getTime();
    var vend = view.end.getTime();
    $('#todaybut').attr('title', new Date(now));
    if(now < vstart || now > vend)
      $('#todaybut').prop('disabled', false);
    else
      $('#todaybut').prop('disabled', true);
    if(isLoading){
      $('#calendaroverlay').show();
      if(!msgid){
        msgid = rcmail.set_busy(true,'loading');
      }
      rcmail.enable_command('plugin.calendar_print', false);
    }
    else{
      rcmail.set_busy(false,'loading',msgid);
      $('#calendaroverlay').hide();
      /* refresh print preview */
      if(rcmail.env.calpopup){
        rcmail.env.calpopup = calendar_commands.previewPrintEvents();
      }
      if(rcmail.env.action != 'show')
        calendar_commands.triggerSearch();
    }
    if(msgid)
      rcmail.env.calendar_msgid = msgid;
    return msgid;  
  }
  this.eventRender_upcoming = function(event, element, view, response){
    element = this.qtip(event, element);
    if(event.end && event.allDay != 1){
      var date = event.end;
      var mydate = date.format(js_time_formats[rcmail.env.rc_time_format]);
      element.find('.fc-event-title').html(" - " + mydate + " " + event.title);
    }
    else{  
      calendar_common.modifyEvents(event, element, view, response); 
    }
    if(event.onclick){
      element.bind('click', function() {
        if(event.onclick == '__caluserid__'){
          var $dialogContent = $("#calswitch");
          var token = $dialogContent.find("input[name='_token']");
          if(!rcmail.env.replication_complete){
            rcmail.display_message(rcmail.gettext('backgroundreplication', 'calendar'), 'error');
            return;
          }
          rcmail.http_post('plugin.calendar_switch_user', '_caluser='+event.userid+'&_token='+token.val()+'&_date='+Math.round(event.start.getTime()/1000)+'&_event_id='+event.id);
          $("#calswitch option").each(function(i){
             if($(this).val() == event.userid){
               $('#calusernamecontent').html($(this).text());
               $("#_caluser").prop('selectedIndex', i);
             }
          });
        }
        else{
          window.open(event.onclick);
          rcmail.http_post('plugin.calendar_clearCache','');
        }
      });
    }
  }
  this.eventRender = function(event, element, view, response){
    rcmail.enable_command('plugin.calendar_print', true);
    if(element.find('span.fc-event-title').html() == ''){
      element.find('span.fc-event-title').html('&nbsp;');
    }
    element = this.qtip(event, element);
    if(view.name != "month"){
      if(event.className){
        if(!event.allDay){
          var disp = event.classNameDisp;
          if(!disp) disp = event.className;
          if(disp == 'null') disp = '';
          if(disp != '')
            element.find('div.fc-event-title').after("<div class=\"fc-event-categories\">["+disp+"]</div>");
        }
      }
      if(event.location){
        element.find('div.fc-event-title').after("<div class=\"fc-event-location\">@"+event.location+"</div>");
      }
      if(event.description) {
        if(!event.allDay){
          var mydescription = event.description;
          if(mydescription.length > 20){
            mydescription = mydescription.substring(0,20) + " ...";
          }
          element.find('div.fc-event-title').after("<div class=\"fc-event-description\">"+mydescription+"</div>");
        }
      }
      var insert = '.fc-event-time';
      if(event.allDay){
        calendar_common.modifyEvents(event, element, view, response);
        insert = '.fc-event-title';
        if(event.rr != 0){
          var mytime = element.find('.fc-event-title').html();
        }
      }
      if(event.rr != 0){
        var mytime = element.find(insert).html();
        element.find(insert).html(mytime + "&nbsp;<img style='padding: 0 1px' src='plugins/calendar/skins/" + rcmail.env.skin + "/images/recur.png' />");
      }
      if(event.reminderservice != 0){
        var myreminder = element.find(insert).html();
        element.find(insert).html(myreminder + "&nbsp;<img style='padding: 0 1px' src='plugins/calendar/skins/" + rcmail.env.skin + "/images/reminder.png' />");
      }
    }
    if(view.name == "month"){
      if(event.end && event.allDay != 1){
        var date = event.end;
        var mydate = date.format(js_time_formats[rcmail.env.rc_time_format]);
        element.find('.fc-event-title').html(" - " + mydate + " " + event.title);
      }
      else{
        calendar_common.modifyEvents(event, element, view, response);
      }
    }
    if(event.onclick){
      element.bind('click', function() {
        if(event.onclick == '__caluserid__'){
          var $dialogContent = $("#calswitch");
          var token = $dialogContent.find("input[name='_token']");
          if(!rcmail.env.replication_complete){
            rcmail.display_message(rcmail.gettext('backgroundreplication', 'calendar'), 'error');
            return;
          }
          rcmail.http_post('plugin.calendar_switch_user', '_caluser='+event.userid+'&_token='+token.val()+'&_date='+Math.round(event.start.getTime()/1000)+'&_event_id='+event.id);
          $("#calswitch option").each(function(i){
             if($(this).val() == event.userid){
               $('#calusernamecontent').html($(this).text());
               $("#_caluser").prop('selectedIndex', i);
             }
          });
        }
        else{
          window.open(event.onclick);
          rcmail.http_post('plugin.calendar_clearCache','');
        }
      });
    }
  }
  this.eventDragStart =  function(event, jsEvent, ui, view, response){
    rcmail.env.clone_gap = 0;
    // drag all day event
    if(event.end.getTime() - event.start.getTime() >= 86340000 && event.end.getTime() - event.start.getTime() <= 86400000){
      rcmail.env.allday_drag = true;
    }
    else{
      rcmail.env.allday_drag = false;
    }
    // recurring event
    if(event.clone){
      rcmail.env.clone_gap = event.start.getTime() / 1000 - event.clone;
    }
    if(!rcmail.env.replication_complete){
      rcmail.display_message(rcmail.gettext('backgroundreplication', 'calendar'), 'error');
      return;
    }
  }
  this.eventDrop = function(event, dayDelta, minuteDelta, allDay, revertFunc, response){
    if(!rcmail.env.replication_complete){
      rcmail.display_message(rcmail.gettext('backgroundreplication', 'calendar'), 'error');
      revertFunc(event, dayDelta, minuteDelta, allDay, revertFunc, response);
      return;
    }
    if(allDay){
      if(event.end.getTime() - event.start.getTime() <= 86400000){
        event.start = new Date(event.start.getFullYear(), event.start.getMonth(), event.start.getDate(), 0, 0, 0);
        event.end = new Date(event.start.getFullYear(), event.start.getMonth(), event.start.getDate(), 23, 59, 0);
      }
    }
    if(rcmail.env.allday_drag && !allDay){
      event.end = new Date(event.start.getTime() + rcmail.env.calsettings.settings.duration * 1000);
    }
    rcmail.env.edit_event = event;
    rcmail.env.edit_dayDelta = dayDelta;
    rcmail.env.edit_minuteDelta = minuteDelta;
    rcmail.env.edit_allDay = allDay;
    rcmail.env.edit_revertFunc = revertFunc;
    var refetch = 0;
    //recurring event
    if(event.clone){
      if(!rcmail.env.edit_recurring){
        calendar_commands.edit_recurring_html('move');
        return;
      }
      if(rcmail.env.edit_recurring == 'initial'){
        event.start = new Date(event.start.getTime() - (rcmail.env.clone_gap * 1000));
        event.end = new Date(event.end.getTime() - (rcmail.env.clone_gap * 1000));
        refetch = 1;
      }
    }
    if(event.rr != 0){
      refetch = 1;
    }
    var now = new Date().getTime();
    if(event.past && event.end.getTime() >= now || !event.past && event.end.getTime() < now){
      if(event.past && event.end.getTime() >= now){
        var color = '#' + event.color_save;
        event.past = false;
      }
      if(!event.past && event.end.getTime() < now){
        var color = '#' + lighter(event.backgroundColor, 50);
        event.past = true;
      }
      event.color = color;
      event.backgroundColor = color;
      event.borderColor = color;
    }
    var append = '';
    if(rcmail.env.edit_recurring){
      append = '&_mode=' + rcmail.env.edit_recurring;
    }
    if(rcmail.env.clone_gap){
      append = append + '&_gap=' + rcmail.env.clone_gap;
    }
    rcmail.env.edit_recurring = false;
    $('#calendaroverlay').show();
    msgid = rcmail.set_busy(true,'loading');
    // send request to RoundCube
    rcmail.http_post('plugin.moveEvent', '_event_id='+event.id+
                                         '&_uid='+event.uid+
                                         '&_start='+Math.round(event.start.getTime() / 1000)+
                                         '&_end='+Math.round(event.end.getTime() / 1000)+
                                         '&_allDay='+allDay+
                                         '&_refetch='+refetch+
                                         '&_reminder='+event.reminder+
                                         '&_msgid='+msgid+append);
    calendar_gui.upcoming(response);
  }
  this.eventResizeStop = function(event, jsEvent, ui, view){
    if(!rcmail.env.replication_complete){
      rcmail.display_message(rcmail.gettext('backgroundreplication', 'calendar'), 'error');
      $('#calendar').fullCalendar('refetchEvents');
      return;
    }
  }
  this.eventResize = function(event, delta, response){
    if(!rcmail.env.replication_complete){
      rcmail.display_message(rcmail.gettext('backgroundreplication', 'calendar'), 'error');
      return;
    }
    var refetch = 0;
    rcmail.env.edit_event = event;
    rcmail.env.edit_delta = delta;
    //recurring event
    if(event.clone){
      if(!rcmail.env.edit_recurring){
        calendar_commands.edit_recurring_html('resize');
        return;
      }
      if(rcmail.env.edit_recurring == 'initial'){
        var gap = event.start.getTime() / 1000 - event.clone;
        event.start = new Date(event.clone * 1000);
        event.end = new Date(event.end.getTime() - (gap * 1000));
        refetch = 1;
      }
    }
    var now = new Date().getTime();
    if(event.past && event.end.getTime() >= now || !event.past && event.end.getTime() < now){
      if(event.past && event.end.getTime() >= now){
        var color = '#' + event.color_save;
        event.past = false;
      }
      if(!event.past && event.end.getTime() < now){
        var color = '#' + lighter(event.backgroundColor, 50);
        event.past = true;
      }
      event.color = color;
      event.backgroundColor = color;
      event.borderColor = color;
    }
    var append = '';
    if(rcmail.env.edit_recurring){
      append = '&_mode=' + rcmail.env.edit_recurring;
    }
    rcmail.env.edit_recurring = false;
    $('#calendaroverlay').show();
    msgid = rcmail.set_busy(true,'loading');
    // send request to RoundCube
    rcmail.http_post('plugin.resizeEvent', '_event_id='+event.id+
                                           '&_uid='+event.uid+
                                           '&_start='+Math.round(event.start.getTime() / 1000)+
                                           '&_end='+Math.round(event.end.getTime() / 1000)+
                                           '&_allDay='+event.allDay+
                                           '&_reminder='+event.reminder+
                                           '&_refetch='+refetch+
                                           '&_msgid='+msgid+append);
  }
  this.select = function(startDate, endDate, allDay, jsEvent, view, response) {
    this.dayClick(startDate, allDay, jsEvent, view, response, endDate); 
  }
  this.dayClick = function(date, allDay, jsEvent, view, response, endtime){
    if(!jsEvent)
      return;
    if(!rcmail.env.replication_complete){
      rcmail.display_message(rcmail.gettext('backgroundreplication', 'calendar'), 'error');
      return;
    }
    var $dialogContent = $("#event");
    if($dialogContent.dialog('isOpen') === true)
      return;
    if(!date){
      var date = new Date(date.getTime()/1000);
    }
    if(!endtime){
      var endtime = new Date((date.getTime()/1000 + response.settings['duration']) * 1000);
    }
    if(rcmail.env.cal_remindermailto)
      $('#remindermailto').html(rcmail.env.cal_remindermailto);
    calendar_gui.resetForm($dialogContent);
    calendar_gui.initTabs(2,3);
    $('#hoursel').attr('checked',true);
    calendar_gui.initExpireDatepicker(endtime,response);
    calendar_gui.initStartdateDatepicker(date,response);
    calendar_gui.initEnddateDatepicker(endtime,response);
    calendar_gui.initReminderDatepicker(date,response);
    calendar_gui.reminderControls();
    var summary = $('#summary');
    var description = $('#description');
    var categories = $('#categories');
    if(!categories) categories = '';
    var location = $('#location');
    var expires = $('#expires');
    var shour = date.getHours() + '';
    if(shour.length < 2)
      shour = '0' + shour;
    var sminute = date.getMinutes() + '';
    if(sminute.length < 2)
      sminute = '0' + sminute;
    var start_val = shour + ':' + sminute;
    if(allDay && $('#calendar').fullCalendar('getView').name != 'month'){
      start_val = ('00:00');
    }
    var starttime = $('#starttime').val(start_val);
    var s_start = $('#starttime').val();
    var ehour = endtime.getHours() + '';
    if(ehour.length < 2)
      ehour = '0' + ehour;
    var eminute = endtime.getMinutes() + '';
    if(eminute.length < 2)
      eminute = '0' + eminute;
    var end_val = ehour + ':' + eminute;
    if(allDay){
      end_val = ('23:59');
    }
    $('#endtime').val(end_val);
    var s_end = $('#endtime').val();
    $('#occurrences').val(0);
    var recur = $('#recursel');
    recur.val(0);
    calendar_gui.toggleRecur();
    var attach = $('#calimport');
    var save = rcmail.gettext('save', 'calendar');
    var cancel = rcmail.gettext('cancel', 'calendar');
    var buttons = {};
    buttons[save] = function() {
      // IE workaround
      if(attach.val() != '' && attach.val() != rcmail.env.cal_lastimport){
        $dialogContent.dialog("close");
        $('#calendaroverlay').show();
        // start loading
        rcmail.env.calendar_msgid = rcmail.set_busy(true,'loading');
        var iframe = $('<iframe name="uploader" id="uploader" src="" style="width:0;height:0;visibility:hidden;" />');
        $('body').append( iframe );
        $('#form').submit();
        $("#uploader").load(function(){
          $('#calendar').fullCalendar('removeEvents');
          $('#calendar').fullCalendar('refetchEvents');
          rcmail.set_busy(false,'loading',rcmail.env.calendar_msgid);
          $('#calendaroverlay').hide();
          rcmail.env.cal_lastimport = attach.val();
          attach.val('');
        });
        return false;
      }
      var starttime = $.trim($('#starttime').val());
      var startdate = $.trim($('#startdate').val());
      var endtime = $.trim($('#endtime').val());
      if(starttime != s_start || endtime != s_end){
        allDay = false;
      }
      var _enddate = $.trim($('#enddate').val());
      if(_enddate + " " + endtime > expires.val()){
        expires.val(_enddate + " " + endtime);
      }
      if(recur.val() != 0){
        temparr = expires.val().split(" ");
        if(temparr[0] <= _enddate && $('#occurrences').val() == 0){
          if(confirm(rcmail.gettext('calendar.verifyexpiredate'))){
            $('#tab2').trigger('click');
            expires.val(temparr[0]);
            expires.focus();
            return false;
          }
        }
      }     
      var eyear = date.getFullYear();
      var emonth = (date.getMonth() + 1) + '';
      if(emonth.length < 2)
        emonth = '0' + emonth;
      var eday = date.getDate() + '';
      if(eday.length < 2)
        eday = '0' + eday;
      if(_enddate + ' ' + endtime <= eyear + "-" + emonth + "-" + eday + " " + starttime){
        var endtime = date.getTime()/1000 + response.settings['duration'];
        endtime = new Date(endtime * 1000);
        var ehour = endtime.getHours() + '';
        if(ehour.length < 2)
          ehour = '0' + ehour;
        var eminute = date.getMinutes() + '';
        if(eminute.length < 2)
          eminute = '0' + eminute;
        var end_val = ehour + ':' + eminute;
        endtime = $('#endtime').val(end_val);
      }
      var temparr = $('#starttime').val();
      temparr = temparr.split(':');
      var shour = temparr[0];
      var sminute = temparr[1];
      temparr = $('#endtime').val();
      temparr = temparr.split(':');
      var ehour = temparr[0];
      var eminute = temparr[1];
      temparr = startdate.split('-');
      starttime = new Date(
                            parseFloat(temparr[0]),
                            parseFloat(temparr[1])-1,
                            parseFloat(temparr[2]),
                            parseFloat(shour),
                            parseFloat(sminute),
                            0);
      var reminder = $('#remindercustom').val();
      temparr = reminder.split(' ');
      var dreminder = temparr[0];
      var treminder = temparr[1];
      if(treminder){
        temparr = treminder.split(':');
        var rhour = temparr[0];
        var rminute = temparr[1];
        temparr = dreminder.split('-');
        reminder = new Date(
                            parseFloat(temparr[0]),
                            parseFloat(temparr[1])-1,
                            parseFloat(temparr[2]),
                            parseFloat(rhour),
                            parseFloat(rminute),
                            0
                            );
        reminder = (starttime.getTime() - reminder.getTime()) / 1000;
        $('#durationcustom').val(reminder);
      }
      var occurrences = $('#occurrences');
      if(occurrences.val() == "") occurrences.val(0);
      recv = recur.val();
      rrsec = recv;
      rrsec = recv.substr(0,1);
      recv = recv.substr(1);
      switch(rrsec){
        case 'd':
          recv = recv * parseInt($('#dnums').val());
          break;
        case 'w':
          recv = recv * parseInt($('#wnums').val());
          break;
        case 'm':
          recv = recv * parseInt($('#mnums').val());
          break;
        case 'y':
          recv = recv * parseInt($('#ynums').val());
          break;
      }
      recv = rrsec + recv;
      var rrule = '';
      var ii = -1;
      var iii = 0;
      mydays = new Array("SU", "MO", "TU", "WE", "TH", "FR", "SA");
      $("#form input[type=checkbox]").each(function() {
        ii ++;
        if(this.checked){
          iii = ii;
          if(ii<7){
            rrule=rrule + mydays[ii] + ',';
          }
          else{
            rrule=rrule + (ii - 6) + ',';
          }
        }   
      });  
      rrule = rrule.substr(0,rrule.length-1);
      var append = "";
      if(iii > 6)
        append='&_bymonthday=' + rrule;
      else if(rrule != "")
        append='&_byday=' + rrule;
      if(rrsec == 'm'){
        if($('xmevery').val() != 0 && $('#mweekday').val() != 0){
          append='&_byday=' + $('#mevery').val() + $('#mweekday').val();
        }  
      }
      else if(rrsec == 'y'){
        if($('#yevery').val() != 0 && $('yweekday').val() != 0){
          append='&_byday=' + $('#yevery').val() + $('#yweekday').val();
        }
        if($('#ymonth').val() != 0){
          append=append + '&_bymonth=' + $('#ymonth').val();
        }
        if($('#ydnums').val() != 0 && $('#ymonthday').val() != 0){
          append=append + '&_bymonthday=' + $('#ydnums').val() + '&_bymonth=' + $('#ymonthday').val();
        }
      }
      $('#calendaroverlay').show();
      msgid = rcmail.set_busy(true,'loading');
      if(recv == 0)
        $('#occurrences').val(0);
      if(summary.val().substr(0,1) == '?')
        summary.val(escape(summary.val()));
      if(description.val().substr(0,1) == '?')
        description.val(escape(description.val()));
      if(location.val().substr(0,1) == '?')
        location.val(escape(location.val()));
      while(summary.val().indexOf('&') > -1){
        summary.val(summary.val().replace('&', '%26'));
      }
      while(description.val().indexOf('&') > -1){
        description.val(description.val().replace('&', '%26'));
      }
      while(location.val().indexOf('&') > -1){
        location.val(location.val().replace('&', '%26'));
      }
      rcmail.http_post('plugin.newEvent', $('#form').serialize()+
                                          '&_summary='+summary.val()+
                                          '&_description='+description.val()+
                                          '&_location='+location.val()+
                                          '&_categories='+categories.val()+
                                          '&_allDay='+allDay+
                                          '&_occurrences='+occurrences.val()+
                                          '&_recur='+recv+append+
                                          '&_msgid='+msgid);
      $dialogContent.dialog("close");
      rcmail.env.cal_search_string = '';
    };
    buttons[cancel] = function() {
      $dialogContent.dialog("close");
    };
    $dialogContent.dialog({
       modal: false,
       // find me: autodetect
       width: 630,
       position: 'center',
       zIndex: 5001,
       title: rcmail.gettext('new_event', 'calendar'),
       close: function() {
         $dialogContent.dialog("destroy");
         $dialogContent.hide();
       },
       buttons: buttons
    }).show();
    $('#summary').focus();
  }
  this.eventClick = function(event, response){
    if(event.editable && !rcmail.env.replication_complete && queryString('_event_id') == 'false'){
      rcmail.display_message(rcmail.gettext('backgroundreplication', 'calendar'), 'error');
      return;
    }
    if(event.onclick){
      return;
    }
    rcmail.env.edit_event = event;
    //recurring event
    if(event.clone && event.editable){
      if(!rcmail.env.edit_recurring){
        calendar_commands.edit_recurring_html('edit');
        return;
      }
      switch(rcmail.env.edit_recurring){
        case 'initial':
          if(event.initial){
            event = event.initial;
            event.start = new Date(event.start_unix * 1000);
            var offset = 0;
            if(event.allDay)
              offset = parseInt(event.start.getTimezoneOffset());
            event.start = new Date((parseInt(event.start_unix) + 60 * offset) * 1000);
            if(event.end){
              event.end = new Date(event.end_unix * 1000);
              offset = 0;
              if(event.allDay)
                offset = parseInt(event.end.getTimezoneOffset());
              event.end = new Date((parseInt(event.end_unix) + 60 * offset) * 1000);
            }
            rcmail.env.edit_recurring = false;
            $('#calendaroverlay').hide();
            $('#calendaroverlay').html('')
          }
          else{
            calendar_commands.gotoDate(event.clone, event.id);
            return;
          }
          break;
        case 'single':
          var recurrenceid = event.start_unix;
          break;
        case 'future':
          event.occurrences = Math.max(0, event.occurrences - event.hasoccurred);
          break;
      }
    }
    if(!event.end)
      event.end = new Date(event.start.getTime() + (response.settings['duration'] * 1000));
    var $dialogContent = $("#event");
    calendar_gui.resetForm($dialogContent);
    calendar_gui.initTabs(3,2);
    var starttime = event.start;
    calendar_gui.initExpireDatepicker(event.start,response);
    calendar_gui.initStartdateDatepicker(event.start,response);
    calendar_gui.initEnddateDatepicker(event.start,response);
    calendar_gui.initReminderDatepicker(event.start,response);
    shour = starttime.getHours() + '';
    if(shour.length < 2)
      shour = '0' + shour;
    sminute = starttime.getMinutes() + '';
    if(sminute.length < 2)
      sminute = '0' + sminute;
    $('#starttime').val(shour + ':' + sminute);
    var s_start = $('#starttime').val();
    var endtime = event.end;
    if(endtime)
      ehour = endtime.getHours() + '';
    else
      ehour = '0';
    if(ehour.length < 2)
      ehour = '0' + ehour;
    if(endtime)
      eminute = endtime.getMinutes() + '';
    else
      eminute = '0';
    if(eminute.length < 2)
      eminute = '0' + eminute;
    var eday = endtime.getDate() + '';
    if(eday.length < 2)
      eday = '0' + eday;
    var emonth = (endtime.getMonth() + 1) + '';
    if(emonth.length < 2)
      emonth = '0' + emonth;
    var eyear = endtime.getFullYear() + '';
    $('#enddate').val(eyear + "-" + emonth + "-" + eday);
    $('#endtime').val(ehour + ':' + eminute);
    var s_end = $('#endtime').val();
    var summary = $('#summary').val(event.title);
    var description = $('#description').val(event.description);
    var location = $('#location').val(event.location);
    var categories = $('#categories');
    var disp = event.classNameDisp;
    if(event.classNameICS)
      disp = event.classNameICS;
    if(!disp) disp = event.className;
    if(disp != ""){
      categories.val(disp);
    }
    else{
      categories.prop('selectedIndex', 0);
    }
    var old_categories = categories.val();
    var fexpires = new Date((parseInt(event.expires) + (3600 * parseInt(new Date(event.start).getTimezoneOffset() / 60))) * 1000).format('yyyy-MM-dd');
    var expires = $('#expires').val(fexpires);
    var occurrences = $('#occurrences').val(event.occurrences);
    var base = './?_task=dummy&_action=plugin.calendar_';
    $('#export_as_file').attr('href', base + 'single_export_as_file&_id=' + event.id + '&_edit=' + event.editable);
    $('#send_invitation').attr('href', base + 'send_invitation&_id=' + event.id + '&_edit=' + event.editable);
    var recv = false;
    switch(event.rr){
      case 'd':
        recv = 86400;
        break;  
      case 'w':
        recv = 604800;
        break;
      case 'm':
        recv = 2592000;
        break;
      case 'y':
        recv = 31536000;
        break;
    }
    var recur = $('#recursel');
    if(event.recur && event.recur != 0){
      if(recv)
        recur.val(event.rr+recv);
    }
    calendar_gui.toggleRecur('recursel');  
    //set properties
    recv = recur.val();
    rrsec = recv;
    if(recv){
      rrsec = recv.substr(0,1);
      recv = recv.substr(1);
    }
    var weekdays = new Array();
    weekdays['SU'] = 0;
    weekdays['MO'] = 1;
    weekdays['TU'] = 2;
    weekdays['WE'] = 3;
    weekdays['TH'] = 4;
    weekdays['FR'] = 5;
    weekdays['SA'] = 6;
    var temp = event.byday.split(',');
    switch(rrsec){
      case 'd':
        $('#dnums').val(parseInt(event.recur) / 86400);
        break;
      case 'w':
        $('#wnums').val(parseInt(event.recur) / 604800);
        if(event.byday != 0){
          if(calendar_gui.currentStyle('byweekdayslink'))
            $('#byweekdayslink').click();
          //set byday checkboxes
          var obj = document.forms.form;
          for(var i=0; i<obj.elements.length; i++){
            if(obj.elements[i].type=="checkbox"){
              break;
            }
          }
          for(var ii=0; ii<temp.length; ii++){
            if(typeof weekdays[temp[ii]] != undefined){
              try{
                obj.elements[i+weekdays[temp[ii]]].checked = true;
              }
              catch(e){
              }
            }
          } 
        }
        break;
      case 'm':
        $('#mnums').val( parseInt(event.recur) / 2592000);
        if(event.bymonthday != 0){
          if(calendar_gui.currentStyle('bymonthdayslink'))
            $('#bymonthdayslink').click();
          //set bymonthday checkboxes
          var temp = event.bymonthday.split(',');
          var obj = document.forms.form;
          for(var i=0; i<obj.elements.length; i++){
            if(obj.elements[i].type=="checkbox"){
              break;
            }
          }
          for(var ii=0; ii<temp.length; ii++){
            if(temp[ii] > 0){
              obj.elements[i+7+parseInt(temp[ii])].checked = true;
            }
          }
        }
        if(event.byday != 0){
          if(calendar_gui.currentStyle('byweekdaylink'))
            $('#byweekdaylink').click();
          $('#mweekday').val(event.byday.substr(event.byday.length-2));
          $('#mevery').val(event.byday.substr(0,event.byday.length-2));
        }
        break;
      case 'y':
        $('#ynums').val(parseInt(event.recur) / 31536000);
        if(event.bymonthday !=0 && event.bymonth !=0){
          if(calendar_gui.currentStyle('bymonthdaylink'))
            $('#bymonthdaylink').click();
          $('#ydnums').val(event.bymonthday);
          $('#ymonthday').val(event.bymonth);
        }
        if(event.byday !=0 && event.bymonth !=0 && event.bymonthday == 0){
          if(calendar_gui.currentStyle('byyeardaylink'))
            $('#byyeardaylink').click();
          $('#yweekday').val(event.byday.substr(event.byday.length-2));
          $('#yevery').val(event.byday.substr(0,event.byday.length-2));
          $('#ymonth').val(event.bymonth);
        }
        break;
    }
    if(event.reminderservice != 0){
      $('#reminderenable').attr('checked', true);
      switch(event.reminderservice){
        case 'email':
          $('#remindertype').prop('selectedIndex',0);
          $('#remindermailto').prop('disabled', false);
          break;
        case 'popup':
          $('#remindertype').prop('selectedIndex',1);
          $('#remindermailto').prop('disabled', true);
          break;
      }
    }
    else{
      $('#reminderdisable').attr('checked', true);
    }
    if(event.remindermailto){
      var opt = event.remindermailto;
      if($('#remindermailto option[value="' + opt + '"]').length > 0){
        // find me: fix for shared CalDAVs to prevent overwriting of Attendee property
        if(rcmail.env.cal_backend == 'caldav'){
          rcmail.env.cal_remindermailto = $('#remindermailto').html();
          $('#remindermailto').html('<option value="' + event.remindermailto + '">' + event.remindermailto + '</option>');
        }
        $('#remindermailto').val(opt);
      }
      else{
        if(event.remindermailto != 0){
          var html = $('#remindermailto').html();
          html = html + '<option value="' + event.remindermailto + '">' + event.remindermailto + '</option>' + "\r\n";
          $('#remindermailto').html(html);
          $('#remindermailto').val(opt);
        }
      }
    }
    if(event.reminder > 0){
      var opt;
      var customtrigger = true;
      if(event.reminder / 604800 >= 1){
        opt = event.reminder / 604800;
        if(opt == Math.round(opt) && $('#reminderweeksbefore option[value=' + opt + ']').length > 0){
          $('#weeksel').attr('checked',true);
          $('#reminderweeksbefore').val(opt);
          customtrigger = false;
        }
      }
      else if(event.reminder / 86400 >= 1){
        opt = event.reminder / 86400;
        if(opt == Math.round(opt) && $('#reminderdaysbefore option[value=' + opt + ']').length > 0){
          $('#daysel').attr('checked',true);
          $('#reminderdaysbefore').val(opt);
          customtrigger = false;
        }
      }
      else if(event.reminder / 3600 >= 1){
        opt = event.reminder / 3600;
        if(opt == Math.round(opt) && $('#reminderhoursbefore option[value=' + opt + ']').length > 0){
          $('#hoursel').attr('checked',true);
          $('#reminderhoursbefore').val(opt);
          customtrigger = false;
        }
      }
      else if(event.reminder / 60 >= 1){
        opt = event.reminder / 60;
        if(opt == Math.round(opt) && $('#reminderminutesbefore option[value=' + opt + ']').length > 0){
          $('#minsel').attr('checked',true);
          $('#reminderminutesbefore').val(opt);
          customtrigger = false;
        }
      }
      if(customtrigger){
        $('#customreminder').attr('checked',true);
        var preset = new Date(event.start.getTime() - (event.reminder * 1000));
        var y, m, d, h, min;
        y = preset.getFullYear();
        m = (preset.getMonth() + 1) + '';
        if(m.length < 2) m = '0' + m;
        d = preset.getDate() + '';
        if(d.length < 2) d = '0' + d;
        h = preset.getHours() + '';
        if(h.length < 2) h = '0' + h;
        min = preset.getMinutes() + '';
        if(min.length < 2) min = '0' + min;
        preset = y + '-' + m + '-' + d + ' ' + h + ':' + min;
        $('#remindercustom').val(preset);
      }
    }
    else{
      $('#hoursel').attr('checked',true);
    }
    calendar_gui.reminderControls();
    rcmail.env.event_initial = $('#form').serialize();
    var save = rcmail.gettext('save', 'calendar');
    var remove = rcmail.gettext('remove', 'calendar');
    var cancel = rcmail.gettext('cancel', 'calendar');
    var buttons = {};
    if(event.editable || typeof event.editable == 'undefined'){
      buttons[save] = function() {
        if(rcmail.env.event_initial == $('#form').serialize()){
          $('#rcmrow'+event.id).removeClass('selected');
          $('#rcmmatch' + event.id).removeClass('calsearchmatchselected');
          $('#rcmmatch' + event.id).addClass('calsearchmatch');
          $dialogContent.dialog("close");
          return;
        }
        event.title = summary.val();
        event.description = description.val();
        event.location = location.val();
        event.className = categories.val();
        var starttime = $.trim($('#starttime').val());
        var endtime = $.trim($('#endtime').val());
        if(starttime != s_start || endtime != s_end){
          event.allDay = false;
        }
        var temparr = $('#starttime').val();
        temparr = temparr.split(':');
        var shour = temparr[0];
        var sminute = temparr[1];
        temparr = $('#endtime').val();
        temparr = temparr.split(':');
        var ehour = temparr[0];
        var eminute = temparr[1];
        startdate = $('#startdate').val();
        temparr = startdate.split('-');
        starttime = new Date(
                              parseFloat(temparr[0]),
                              parseFloat(temparr[1])-1,
                              parseFloat(temparr[2]),
                              parseFloat(shour),
                              parseFloat(sminute),
                              0
                             );
        var endtime = $('#endtime').val();
        var _enddate = $('#enddate').val();
        if(_enddate + " " + endtime > expires.val() + " " + $('#starttime').val()){
          expires.val(_enddate + " " + endtime);
        }
        var reminder = $('#remindercustom').val();
        temparr = reminder.split(' ');
        var dreminder = temparr[0];
        var treminder = temparr[1];
        if(treminder){
          temparr = treminder.split(':');
          var rhour = temparr[0];
          var rminute = temparr[1];
          temparr = dreminder.split('-');
          reminder = new Date(
                            parseFloat(temparr[0]),
                            parseFloat(temparr[1])-1,
                            parseFloat(temparr[2]),
                            parseFloat(rhour),
                            parseFloat(rminute),
                            0
                            );
          reminder = (starttime.getTime() - reminder.getTime()) / 1000;
          $('#durationcustom').val(reminder);
        }
        temparr = expires.val().split('-');
        if(occurrences.val() == "") occurrences.val(0);
        var append = '';
        if($('#categories').val()){
          append = append + '&_categories='+categories.val();
        }
        if(event.token){
          append = append + '&_ct=' + event.token;
        }
        if(event.userid){
          append = append + '&_userid' + event.userid;
        }
        recv = recur.val();
        rrsec = recv;
        rrsec = recv.substr(0,1);
        recv = recv.substr(1);
        switch(rrsec){
          case 'd':
            recv = recv * parseInt($('#dnums').val());
            break;
          case 'w':
            recv = recv * parseInt($('#wnums').val());
            break;
          case 'm':
            recv = recv * parseInt($('#mnums').val());
            break;
          case 'y':
            recv = recv * parseInt($('#ynums').val());
            break;
        }
        recv = rrsec + recv;
        var obj = document.forms.form;
        var rrule = '';
        var ii = -1;
        var iii = 0;
        mydays = new Array("SU", "MO", "TU", "WE", "TH", "FR", "SA");
        for(i=0; i<obj.elements.length; i++){
          if(obj.elements[i].type=="checkbox"){
            ii ++;
            if(obj.elements[i].checked==true){
              iii = ii;
              if(ii<7){
                rrule=rrule + mydays[ii] + ',';
              }
              else{
                rrule=rrule + (ii - 6) + ',';
              }
            }
          }
        }
        rrule = rrule.substr(0,rrule.length-1);
        if(iii > 6)
          append='&_bymonthday=' + rrule;
        else if(rrule != "")
          append = '&_byday=' + rrule;
        if(rrsec == 'm'){
          if($('#mevery').val() != 0 && $('#mweekday').val() != 0){
            append = '&_byday=' + $('#mevery').val() + $('#mweekday').val();
          }  
        }
        else if(rrsec == 'y'){
          if($('#yevery').val() != 0 && $('#yweekday').val() != 0){
            append = '&_byday=' + $('#yevery').val() + $('#yweekday').val();
          }
          if($('#ymonth').val() != 0){
            append = append + '&_bymonth=' + $('#ymonth').val();
          }
          if($('#ydnums').val() != 0 && $('#ymonthday').val() != 0){
            append = append + '&_bymonthday=' + $('#ydnums').val() + '&_bymonth=' + $('#ymonthday').val();
          }
        }
        $('#calendaroverlay').show();
        msgid = rcmail.set_busy(true,'loading');
        var recurselnever = 0;
        if(rcmail.env.recurselnever)
          recurselnever = 1;
        if(recv == 0)
          $('#occurrences').val(0);
        var reload = 0;
        if(disp != categories.val())
          reload = 1;
        if(event.recurrence_id){
          append = append + '&_recurrence_id=' + event.recurrence_id;
        }
        if(recurrenceid){
          append = append + '&_recurrence_id=' + recurrenceid;
        }
        if(rcmail.env.edit_recurring){
          append = append + '&_mode=' + rcmail.env.edit_recurring;
        }
        if(summary.val().substr(0,1) == '?')
          summary.val(escape(summary.val()));
        if(description.val().substr(0,1) == '?')
          description.val(escape(description.val()));
        if(location.val().substr(0,1) == '?')
          location.val(escape(location.val()));
        while(summary.val().indexOf('&') > -1){
          summary.val(summary.val().replace('&', '%26'));
        }
        while(description.val().indexOf('&') > -1){
          description.val(description.val().replace('&', '%26'));
        }
        while(location.val().indexOf('&') > -1){
          location.val(location.val().replace('&', '%26'));
        }
        // send requests to RoundCube
        rcmail.http_post('plugin.editEvent', $('#form').serialize()+
                                             '&_event_id='+event.id+
                                             '&_uid='+event.uid+
                                             '&_summary='+summary.val()+
                                             '&_description='+description.val()+
                                             '&_location='+location.val()+
                                             '&_categories='+categories.val()+
                                             '&_old_categories='+ old_categories +
                                             '&_allDay='+event.allDay+
                                             '&_occurrences='+occurrences.val()+
                                             '&_recur='+recv+append+
                                             '&_recurselnever='+recurselnever+
                                             '&_reload='+reload+
                                             '&_edit=1'+
                                             '&_msgid='+msgid+append);
        rcmail.env.cal_search_string = '';
        $dialogContent.dialog("close");
      };
      buttons[remove] = function() {
        var append = '';
        if(rcmail.env.edit_recurring){
          append = '&_mode=' + rcmail.env.edit_recurring;
        }
        $('#rcmrow'+event.id).remove();
        $('#calendaroverlay').show();
        msgid = rcmail.set_busy(true,'loading');
        // send request to RoundCube
        rcmail.http_post('plugin.removeEvent', '_event_id='+event.id+'&_start='+event.start_unix+'&_msgid='+msgid+'&_uid='+event.uid+append);
        $('#calendar').fullCalendar('removeEvents', event.id);
        $('#upcoming').fullCalendar('removeEvents', event.id);
        $dialogContent.dialog("close");
        rcmail.env.cal_search_string = '';
        calendar_commands.triggerSearch();
      };
    }
    else{
      $('input, textarea, select', '#form').each(
        function(){
          $(this).prop('disabled', true);
          $('#event').tabs('disable',1);
          $('#event').tabs('disable',3);
          $('#event').tabs('disable',4);
        }
      );
    }
    buttons[cancel] = function() {
      $('#rcmrow'+event.id).removeClass('selected');
      $('#rcmmatch' + event.id).removeClass('calsearchmatchselected');
      $('#rcmmatch' + event.id).addClass('calsearchmatch');
      $dialogContent.dialog("close");
    };
    $dialogContent.dialog({
      modal: false,
      title: rcmail.gettext('edit_event', 'calendar'),
      // find me: autoadjust
      width: 630,
      zIndex: 5001,
      position: 'center',
      close: function() {
        $dialogContent.dialog("destroy");
        $dialogContent.hide();
        rcmail.env.edit_recurring = false;
      },
      buttons: buttons
    }).show();
    $('#summary').focus();
  }
}
var calendar_callbacks = new calendar_callbacks();