(function($){$(function(){

  // all the elements of the agenda.
  var agenda = $('#calendar, #calendar-month, #calendar-content, #calendar-closing');
  if(!agenda.length)return;
  // create a div for the modal.
  var modal = $('<div id="eventModal" class="jqmWindow">Chargement...</div>').appendTo('body').hide();
  // the trigger of the modal.
  modal_trigger = $('.modify_events_trigger');

  var agenda_height = 0;
  agenda.each(function(){
    agenda_height += $(this).outerHeight();
  });

  var agenda_overlay = $('<div id="calendarOverlay" class="ajaxOverlay"></div>').appendTo('#global-wrapper').hide();
  if(typeof agenda){
	  agenda_overlay.css({
	    left: (typeof agenda.position()!='undefined')?agenda.position().left:0,
	    height: agenda_height +'px',
	    opacity: 0.7,
	    top: (typeof agenda.position()!='undefined')?agenda.position().top:0,
	    width: agenda.outerWidth(true) +'px'
	  });
  }
  /*
   * calendar.
   */
  var agenda_refresh = function(url) {
    agenda.fadeTo('normal', 0.33);
    agenda_overlay.show();

    var agenda_height = 0;
    agenda.each(function(){
      agenda_height += $(this).outerHeight();
    });

    agenda_overlay.css({
      left: (typeof agenda.offset()!='undefined')?agenda.offset().left:0,
      top: (typeof agenda.offset()!='undefined')?agenda.offset().top:0,
      height: agenda_height+'px',
      width: agenda.outerWidth(true)+'px'
    });
    $.ajax({
      url: url,
      dataType: 'html',
      success: function(html){
        $('#calendar-month, #calendar-content, #calendar-closing').remove();
        $('#calendar').replaceWith(html);
        agenda.fadeTo('normal', 1);
        agenda_overlay.hide();
        agenda = $('#calendar, #calendar-month, #calendar-content, #calendar-closing');
        agenda_bubble();
        modal_trigger = modal.jqmAddTrigger('.modify_events_trigger');
      }
    });
  };

  /*
   * agenda bubble.
   */
  var agenda_bubble = function() {
    $('td.day')
      .bind('mouseenter', function() {
        $(this).find('div.day_events').show();
      })
      .bind('mouseleave', function() {
        $(this).find('div.day_events').hide();
      });
  };

  // bubble for all cells.
  agenda_bubble();

  /*
   * "pagination" links.
   */
  $('#agenda_prev a, #agenda_next a').live('click', function() {
    agenda_refresh($(this).attr('href'));
    return false;
  });

  /*
   * subscribe and unsubscribe links.
   */
  $('.day_event_add a, .day_event_remove a').live('click', function() {
    // url of the current month of the agenda.
    var agenda_url = '/agenda?';
    $(this).attr('href').replace(/[?&]([^=]+)=([^&]*)/g, function(m, key, value){
      if (key == 'year' || key == 'month') {
        agenda_url += key +'='+ value +'&';
      }
    });

    // subscribe or unsubscribe.
    $.ajax({
      url: $(this).attr('href'),
      dataType: 'html',
      success: function(html){
        // refresh the agenda.
        agenda_refresh(agenda_url);
      }
    });

    return false;
  });

  /*
   * modal to add an event.
   */
  // fuction to create a link to close the modal.
  var add_undo_to_modal = function(form) {
    $('<a href="#nogo">Annuler</a>')
      .appendTo($('.buttons', form))
      .bind('click', function() {
        modal.jqmHide();
        return false;
      });
  };
  // function to submit the add an event form by Ajax.
  var bind_ajax_submit = function(hash) {
    $('#form-event', modal).bind('submit', function() {
      $.ajax({
        type: "POST",
        url: $(this).attr('action'),
        data: $(this).serialize(),
        beforeSend: function() {
          hash.w.fadeTo('normal', 0.33);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          modal.html('<p class="error">Oups, une erreur est survenue. Veuillez réessayer.</p>');
          $('<a href="#nogo">Fermer</a>')
            .appendTo(modal)
            .bind('click', function() { 
              modal.jqmHide();
              return false;
            });
          hash.w.fadeTo('normal', 1);
        },
        success: function(msg){
          // if the response is the "1" flag
          // close the modal and refresh the calendar.
          if ('1' == msg) {
            modal.jqmHide();
            hash.w.fadeTo('fast', 1);
            agenda_refresh('/agenda');
          }
          // else get the response and insert it in the modal.
          else {
            hash.w
              .fadeTo('normal', 1)
              .html(msg);
            bind_ajax_submit(hash);
            add_undo_to_modal($('#form-event', modal));
          }
        }
      });
      return false;
    });
  };


  // create the modal.
  modal.jqm({
    ajax: '@href',
    trigger: modal_trigger,
    onLoad: function(hash) {
      bind_ajax_submit(hash);
      add_undo_to_modal($('#form-event', modal));

      if (typeof $.fn.mirrorField === 'function')
      {
        $('select', modal).mirrorField({
          'left':     '[name*=date_start]',
          'right':    '[name*=date_end]'
        });
      }
    }
  });

  /*
   * switch to public / private links.
   */
  $('#switch_public, #switch_private').live('click', function() {
    agenda_refresh($(this).attr('href'));
    return false;
  });

  $('#add_next_chat_to_private_agenda').live('click', function() {
    $.ajax({
            url: '/add-next-chat-to-my-agenda',
            dataType: 'html',
            success: function(html) {
              agenda_refresh('/agenda?public=0');
              $('#add_next_chat_to_private_agenda').remove();
             }
           });
    return false;
  });

});})(jQuery);
