//compile 0a1a5a5d8ee6affa8ab79b4be4d87ea8
// adjust width and height
function calendar_splitter(){
  this.init = function(){
    rcube_event.add_listener({
      element:document.getElementById('mailviewsplitterv'),
      event:'mousedown',
      object:this,
      method:'onDragStart'
    });  
  }
  this.onDragStart = function(){
    rcube_event.add_listener({
      element:document,
      event:'mousemove',
      object:this,
      method:'onDrag'
    });
    rcube_event.add_listener({
      element:document,
      event:'mouseup',
      object:this,
      method:'onDragStop'
    });
  }
  this.onDrag = function(){
    this.adjust_mboxlist_width();
  }
  this.onDragStop = function(){
    this.adjust_mboxlist_width();
    rcube_event.remove_listener({
      element:document,
      event:'mousemove',
      object:this,
      method:'onDrag'
    });
    rcube_event.remove_listener({
      element:document,
      event:'mouseup',
      object:this,
      method:'onDragStop'
    });  
  }
  this.adjust_mboxlist_height = function(){
    var container = 'mailboxlist';
    var fudge = -2;
    if(rcmail.env.calskin == 'litecube-f')
      fudge = -17;
    if(!rcmail.env.mboxlistheight){
      if(rcmail.env.calskin == 'larry'){
        fudge = -45;
        rcmail.env.mboxlistheight = $('#' + container).parent().parent().height() + fudge;
      }
      else
        rcmail.env.mboxlistheight = $('#' + container).parent().height() + fudge;
    }
    var h = rcmail.env.mboxlistheight;
    var m = Math.round(h/4);
    $('#' + container).parent().height(Math.max(0,h-m-1));
    this.set_cookie('mailboxlist-height',Math.max(0,h-m-1)); 
    $('#upcoming-content').height(Math.max(0,m));
    $('#calendaroverlay').height(Math.max(0,m));
    this.set_cookie('upcoming-height',Math.max(0,m));  
  }
  this.adjust_mboxlist_width = function(){
    var w = $('#mailboxlist-container').width();
    if(!w){
      w = $('#mailboxcontainer').width() - 1;
    }
    $('#upcoming-content').width(w);
    $('#calendaroverlay').width(w);
    $('#upcoming-container').width(w);
    this.set_cookie('upcoming-width',w);
  }
  this.set_cookie = function(name,value){
    var exp = new Date();
    exp.setYear(exp.getFullYear() + 1);
    bw.set_cookie(name, value, exp);
  };   
}
var spl = new calendar_splitter();

$(window).load(function(){
  spl.adjust_mboxlist_height();
  spl.adjust_mboxlist_width();
});
  
$(window).resize(function(){
  var container = 'mailboxlist';
  rcmail.env.mboxlistheight = false;
  $('#' + container).parent().height($('#mailboxlist-container').height()-44);
  spl.adjust_mboxlist_height();
  spl.adjust_mboxlist_width();
});

$(window).load(function() {
  if(window.rcmail){
    rcmail.env.calendar_occupied = new Array();
    rcmail.env.calendar_msgid = null;
    rcmail.env.calendar_response = null;
  

    // adjust width/height of upcoming-container
    spl.init();

    var tz_info = jzTimezoneDetector.determine_timezone();
    response_text = tz_info.key;
    if(typeof(tz_info.timezone) == 'undefined'){
      response_text = 'undefined'
    }
    else{
      response_text = tz_info.timezone['olson_tz']; 
    }
    // get settings
    if(!rcmail.env.terms && !parent.summaryisparent){
      rcmail.addEventListener('plugin.getSettings', loadUpcoming);
      rcmail.http_post('plugin.getSettings', '_tzname='+response_text+"&_init=1");
    }
  }
  
  function loadUpcoming(response){
    /* remember settings */
    rcmail.env.calsettings = response;
  
    /* Replicaten */
    var delay = 1000;
    if(rcmail.env.noreplication){
      delay = 100;
    }
    if(response.settings['backend'] == 'caldav'){
      window.setTimeout("calendar_replicate.init(rcmail.env.calsettings, 'upcoming');", delay);
    }
  
    // upcoming events
    $('#upcoming').fullCalendar({
      header: {
        left: '',
        center: '',
        right: ''
      },
      readyState: function() {
        calendar_init_previews(response); 
      },
      titleFormat: {
        month: response.settings['titleFormatMonth'],
        week: response.settings['titleFormatWeek'],
        day: response.settings['titleFormatDay']
      },      
      columnFormat: {
        month: response.settings['columnFormatMonth'],
        week: response.settings['columnFormatWeek'],
        day: response.settings['columnFormatDay']
       },    
      theme: response.settings['ui_theme_upcoming'],
      editable: false,
      ignoreTimezone: false,
      //lazyFetching: false,
      eventSources: calendar_common.eSources(response, false),  
      monthNames : response.settings['months'],
      monthNamesShort : response.settings['months_short'],
      dayNames : response.settings['days'],
      dayNamesShort : response.settings['days_short'],
      firstDay : response.settings['first_day'],
      firstHour : response.settings['first_hour'],
      slotMinutes : 60/response.settings['timeslots'],
      timeFormat: js_time_formats[rcmail.env.rc_time_format],
      axisFormat : js_time_formats[rcmail.env.rc_time_format],
      defaultView: 'basicDay',
      allDayText: rcmail.gettext('all-day', 'calendar'),
      height: 1,
      loading: function(isLoading, view){
        if(isLoading){
          $('#calendaroverlay').show();
        }
        else{
          $('#calendaroverlay').hide();
          $('#upcoming').fullCalendar('removeEvents','preview');
          if(typeof rcmail.env.myevents != 'undefined'){
            if(rcmail.env.myevents[0]){
              $('#upcoming').fullCalendar('addEventSource',rcmail.env.myevents);
            }
          }
        }
      },   
      eventRender: function(event, element, view){
        element = calendar_common.qtip(event, element);
        if(event.end && event.allDay != 1){
          var date = event.end;
          var start = Math.round(event.start.getTime()/1000/60);
          var end = Math.round(event.end.getTime()/1000/60);
          var mydate = date.format(js_time_formats[rcmail.env.rc_time_format]);
          var newtitle = " - " + mydate + " " + event.title;
          element.find('.fc-event-title').html(newtitle);
          if(event.id != 'preview'){
            for(i=start;i<=end;i++){
              rcmail.env.calendar_occupied[i] = 1;
            }
          }
          else{
            if(rcmail.env.calendar_occupied[start] || rcmail.env.calendar_occupied[end]){
              event.className = new Array('occupied');
              myclass = element.attr('class');
              myclass = myclass.replace('preview','occupied');
              element.attr('class',myclass);
            }
          }
        }
        else{
          calendar_common.modifyEvents(event, element, view, response);
        }
      },
      eventAfterRender: function(event, element){
        if(event.id == 'preview'){
          var offset = element.css('top');
          if(typeof offset != 'undefined'){
            offset = parseInt(offset.replace('px',''));// + 150;
            offset = Math.max(offset,0);
            $('#upcoming-container').scrollTop(offset);
          }
        }      
      }
    });
    $('#upcoming').click(function() {
      var d = $('#upcoming').fullCalendar('getDate');
      document.location.href="./?_task=dummy&_action=plugin.calendar&_date=" + Math.round(d.getTime() / 1000);
    });
    if(response.settings['cal_previews'] > 1){
      for(i=1; i < response.settings['cal_previews']; i++){
        $('#upcoming_' + i).click(function() {
          var d = $('#' + this.id).fullCalendar('getDate');
          document.location.href="./?_task=dummy&_action=plugin.calendar&_date=" + escape(Math.round(d.getTime() / 1000));
        });
      }
    }        
    $('#caltoday').click(function() {
      $('#upcoming').fullCalendar('today');
      if(response.settings['cal_previews'] > 1){
        for(i=1; i < response.settings['cal_previews']; i++){
          var d =  new Date($('#upcoming').fullCalendar('getDate').getTime() + (86400 * 1000 * i));
          $('#upcoming_' + i).fullCalendar('gotoDate', d);
        }
      }
    });
    $('#calback').click(function() {
      $('#upcoming').fullCalendar('prev');
      if(response.settings['cal_previews'] > 1){
        for(i=1; i < response.settings['cal_previews']; i++){
          $('#upcoming_' + i).fullCalendar('prev');
        }
      }
    });
    $('#calforward').click(function() {
      $('#upcoming').fullCalendar('next');
      if(response.settings['cal_previews'] > 1){
        for(i=1; i < response.settings['cal_previews']; i++){
          $('#upcoming_' + i).fullCalendar('next');
        }
      }
    });
  }
  
  function calendar_init_previews(response){
    if(response.settings['cal_previews'] > 7)
      response.settings['cal_previews'] = 7;
    for(var i=1; i < response.settings['cal_previews']; i++){
      var cyear  = new Date($('#upcoming').fullCalendar('getDate').getTime() + (86400 * 1000 * i)).getFullYear();
      var cmonth = new Date($('#upcoming').fullCalendar('getDate').getTime() + (86400 * 1000 * i)).getMonth();
      var cdate  = new Date($('#upcoming').fullCalendar('getDate').getTime() + (86400 * 1000 * i)).getDate();
      $('#upcoming_' + i).fullCalendar('destroy');
      $('#upcoming_' + i).fullCalendar({
        header: {
          left: '',
          center: '',
          right: ''
        },
        titleFormat: {
          month: response.settings['titleFormatMonth'],
          week: response.settings['titleFormatWeek'],
          day: response.settings['titleFormatDay']
        },      
        columnFormat: {
          month: response.settings['columnFormatMonth'],
          week: response.settings['columnFormatWeek'],
          day: response.settings['columnFormatDay']
        },    
        theme: response.settings['ui_theme_upcoming'],
        editable: false,
        ignoreTimezone: false,
        events: $('#upcoming').fullCalendar('clientEvents'), 
        monthNames : response.settings['months'],
        monthNamesShort : response.settings['months_short'],
        dayNames : response.settings['days'],
        dayNamesShort : response.settings['days_short'],
        firstDay : response.settings['first_day'],
        firstHour : response.settings['first_hour'],
        slotMinutes : 60/response.settings['timeslots'],
        timeFormat: js_time_formats[rcmail.env.rc_time_format],
        axisFormat : js_time_formats[rcmail.env.rc_time_format],
        defaultView: 'basicDay',
        allDayText: rcmail.gettext('all-day', 'calendar'),
        height: 1,
        eventRender: function(event, element, view) {
          element = calendar_common.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]);
            var newtitle = " - " + mydate + " " + event.title;
            element.find('.fc-event-title').html(newtitle);
          }
          else{
            calendar_common.modifyEvents(event, element, view, response);
          }
        },
        year: cyear,
        month: cmonth,
        date: cdate
      });
    }
  }
});