var g_oDateStart = null;
var g_oDateEnd = null;



function cWeekAgenda(psAddURL, pbCanEdit, pnTimeStart, pnTimeEnd)
{
  // Constantes
  cWeekAgenda.CONST_CELL_DURATION = 30;
  cWeekAgenda.CONST_CELL_HEIGHT = 25;
  cWeekAgenda.CONST_CELL_HEADER_HEIGHT = 20;
  cWeekAgenda.CONST_HOUR_START = 8;
  cWeekAgenda.CONST_HOUR_END = 21;
  cWeekAgenda.CONST_COLUMN_WIDTH = 13;

  this.m_nTimeStart = pnTimeStart;
  this.m_nTimeEnd = pnTimeEnd;

  // Disable text select
  if ($.browser.mozilla) $("#agenda_block").css({'MozUserSelect' : 'none'});
  if ($.browser.msie) $("#agenda_block").bind('selectstart.disableTextSelect', function() { return false; });
  if (!$.browser.msie && !$.browser.mozilla)$("#agenda_block").bind('mousedown.disableTextSelect', function() { return false; });

  // Table contenant les cellules de l'agenda
  oCells = $(".agenda_cell");

  // Effet de survol sur les cellules
  oCells.hover(function() {$(this).addClass("agenda_cell_over");}, function() {$(this).removeClass("agenda_cell_over");});

  // Si on peut modifier l'agenda on ajoute les écouteur d'evenement
  if (pbCanEdit)
  {
    // on change le type de pointeur
    oCells.css('pointer', 'cursor');

    // on commence la selection sur le mousedown
    oCells.mousedown(function()
    {
      $("table.agenda_weekagenda td.agenda_cell_selected").removeClass("agenda_cell_selected");
      g_oDateStart = new Date();
      g_oDateStart.setTime(parseInt(this.id) * 1000);
      $(this).addClass("agenda_cell_selected");

      $(document).mouseup(function()
      {
        g_oDateStart = null;
        g_oDateEnd = null;
        $("table.agenda_weekagenda td.agenda_cell_selected").removeClass("agenda_cell_selected");
      });
    });


    oCells.mouseover( function()
    {
      if (g_oDateStart != null)
      {
        var oDateEnd =  new Date();
        oDateEnd.setTime(parseInt(this.id) * 1000);

        if (oDateEnd.getHours() * 60 + oDateEnd.getMinutes() >= g_oDateStart.getHours() * 60 + g_oDateStart.getMinutes())
        {
          nHourEnd = oDateEnd.getHours();
          nMinuteEnd = oDateEnd.getMinutes();

          var oDate = new Date();
          oDate.setTime(g_oDateStart.getTime());

          //$("table.agenda_weekagenda td.agenda_cell").css("background-color", "");
          $(".agenda_cell_selected").removeClass("agenda_cell_selected");

          while(oDate.getHours() * 60 + oDate.getMinutes() <= nHourEnd * 60 + nMinuteEnd)
          {
            $("#" + oDate.getTime() / 1000).addClass("agenda_cell_selected");
            oDate = new Date(oDate.valueOf() + (cWeekAgenda.CONST_CELL_DURATION * 60 * 1000));
          }
          g_oDateEnd = oDate;
        }
      }
    });

  	oCells.mouseup(function()
    {
      if (g_oDateStart == null) return ;
      if (g_oDateEnd == null)
      {
        g_oDateEnd = new Date(g_oDateStart);
        g_oDateEnd.setMinutes(g_oDateEnd.getMinutes() + 30);
      }

      var sURL = psAddURL.replace("datestart", g_oDateStart.getTime() / 1000);
      sURL = sURL.replace("dateend", g_oDateEnd.getTime() / 1000)

      ExecuteAction(sURL, 600, $(window).height() - 20);
      $('#divaction').show();

//      doResize('divaction', 600, $(window).height() - 20);
      g_oDateStart = null;
      g_oDateEnd = null;
    });
  }

  this.m_aoWeekEvents = new Array();
}

cWeekAgenda.prototype.Draw = function()
{
  // div contenant l'agenda
  oRoot = $(".agenda_block");

  // On déssine les séparateurs horizontaux
  for (nHour = cWeekAgenda.CONST_HOUR_START; nHour < cWeekAgenda.CONST_HOUR_END; nHour++)
  {
    for (nMinute = 0; nMinute < cWeekAgenda.CONST_CELL_HEIGHT * 2; nMinute += cWeekAgenda.CONST_CELL_HEIGHT)
    {
      oDiv = $(document.createElement("div"));

      oDiv.css("top", ((nHour - cWeekAgenda.CONST_HOUR_START) * 2 * cWeekAgenda.CONST_CELL_HEIGHT + cWeekAgenda.CONST_CELL_HEADER_HEIGHT + nMinute) + "px");
      if (nMinute != 0)
      {
        oDiv.addClass("agenda_hsep_halfhour");
        oDiv.css("right", "0px");
        oDiv.css("width", (cWeekAgenda.CONST_COLUMN_WIDTH * 7) + "%");
      }
      else
        oDiv.addClass("agenda_hsep_hour");

      oRoot.append(oDiv);
    }
  }

  // On déssine les séparateurs verticaux
  for (nCurrentDay = 1; nCurrentDay <= 7; nCurrentDay++)
  {
    oDiv = $(document.createElement("div"));
    oDiv.addClass("agenda_vsep");
    oDiv.css("right", (cWeekAgenda.CONST_COLUMN_WIDTH * nCurrentDay) + "%");
    oDiv.css("top", cWeekAgenda.CONST_CELL_HEADER_HEIGHT);
    oDiv.css("height", ((cWeekAgenda.CONST_HOUR_END - cWeekAgenda.CONST_HOUR_START) * 2 * cWeekAgenda.CONST_CELL_HEIGHT) + "px");
    oRoot.append(oDiv);
  }

  // on calcule les collisions de chaque évènements avec ses suivants
  for (nEventA=0; nEventA<this.m_aoWeekEvents.length; nEventA++)
  {
    for (nEventB = nEventA+1; nEventB < this.m_aoWeekEvents.length; nEventB++)
    {
      // Chaque évènements contrôle un conflit potentiel avec son prédecesseur
      // Chaque conflit détecté augment la position du 2ème
      this.m_aoWeekEvents[nEventA].ControlConflictDate(this.m_aoWeekEvents[nEventB]);
    }
  }

  // on dessine les evenements
  jQuery.each(this.m_aoWeekEvents, function() { this.Draw(); });

  // On dessine les marqueurs pour la date en cour
  this.DrawCurrentDate();
}

cWeekAgenda.prototype.AddEvent = function(poEvent)
{
  this.m_aoWeekEvents.push(poEvent);
}

cWeekAgenda.prototype.DrawCurrentDate = function()
{
  oCurrentDate = new Date();

  if (oCurrentDate.getTime() > this.m_nTimeStart && oCurrentDate.getTime() < this.m_nTimeEnd && oCurrentDate.getHours() >= cWeekAgenda.CONST_HOUR_START && oCurrentDate.getHours() < cWeekAgenda.CONST_HOUR_END)
  {
    oDiv = $(document.createElement("div"));

    oDiv.css("top", ((oCurrentDate.getHours() - cWeekAgenda.CONST_HOUR_START) * (2 * cWeekAgenda.CONST_CELL_HEIGHT) + (oCurrentDate.getMinutes() / cWeekAgenda.CONST_CELL_DURATION) * cWeekAgenda.CONST_CELL_HEIGHT + cWeekAgenda.CONST_CELL_HEADER_HEIGHT) + "px");
    oDiv.css("right", (Math.abs(oCurrentDate.getDay() - 7) * cWeekAgenda.CONST_COLUMN_WIDTH) + "%");
    oDiv.css("width", cWeekAgenda.CONST_COLUMN_WIDTH + "%");
    oDiv.css("position", "absolute");
    oDiv.css("z-index", "5");
    oDiv.addClass("agenda_currentdate");

    $(".agenda_block").append(oDiv);

    oDiv = $(document.createElement("div"));
    oCurrentDate = new Date();
    oDiv.css("top", ((oCurrentDate.getHours() - cWeekAgenda.CONST_HOUR_START) * (2 * cWeekAgenda.CONST_CELL_HEIGHT) + (oCurrentDate.getMinutes() / cWeekAgenda.CONST_CELL_DURATION) * cWeekAgenda.CONST_CELL_HEIGHT + cWeekAgenda.CONST_CELL_HEADER_HEIGHT - 3) + "px");
    oDiv.css("left", "0");
    oDiv.css("position", "absolute");
    oDiv.css("z-index", "5");
    oDiv.addClass("agenda_currentdate_arrow");

    $(".agenda_block").append(oDiv);
  }
}


/**
 * Class WeekEvent
 */

function cWeekEvent(psCoords, psType, psTitle, psDescription, psURL, pbStartPreviousWeek, pbEndNextWeek)
{
  this.m_asCoords = psCoords;
  this.m_sType = psType;
  this.m_sTitle = psTitle;
  this.m_sDescription = psDescription;
  this.m_sURL = psURL;
  this.m_bStartPreviousWeek = pbStartPreviousWeek;
  this.m_bEndNextWeek = pbEndNextWeek;

  this.m_oDivs = new Array();
  this.m_oContentDivs = new Array();
  var nLength = this.m_asCoords.events.length;
  for (nCurrent = 0; nCurrent < nLength; nCurrent++)
  {
    this.m_oDivs[nCurrent] = $(document.createElement("div"));
    this.m_oContentDivs[nCurrent] = $(document.createElement("div"));
    this.m_oDivs[nCurrent].append(this.m_oContentDivs[nCurrent]);
    $(".agenda_block").append(this.m_oDivs[nCurrent]);

    var sTitle = '';

    // Si l'evenement est sur plus d'une journée
    if (nLength > 1)
    {
      // Si on est pas sur le dernier jour
      if (nCurrent < nLength - 1)
      {
        sTitle += this.HourToString(this.m_asCoords.events[nCurrent].hour, this.m_asCoords.events[nCurrent].minute) + '...';
      }
      else
      {
        var oDate = new Date();
        oDate.setHours(this.m_asCoords.events[nCurrent].hour);
        oDate.setMinutes(this.m_asCoords.events[nCurrent].minute + this.m_asCoords.events[nCurrent].size);
        sTitle += this.HourToString(this.m_asCoords.events[nCurrent].hour, this.m_asCoords.events[nCurrent].minute);
        sTitle += ' - ' + this.HourToString(oDate.getHours(), oDate.getMinutes());
      }
    }
    else
    {
      if (this.m_asCoords.events[nCurrent].size > cWeekAgenda.CONST_CELL_DURATION)
      {
        var oDate = new Date();
        oDate.setHours(this.m_asCoords.events[nCurrent].hour);
        oDate.setMinutes(this.m_asCoords.events[nCurrent].minute + this.m_asCoords.events[nCurrent].size);
        sTitle += this.HourToString(this.m_asCoords.events[nCurrent].hour, this.m_asCoords.events[nCurrent].minute);
        sTitle += ' - ' + this.HourToString(oDate.getHours(), oDate.getMinutes());
      }
      else
      {
        sTitle += this.HourToString(this.m_asCoords.events[nCurrent].hour, this.m_asCoords.events[nCurrent].minute);
        sTitle += ' - ' + this.m_sTitle;
      }
    }

    this.m_oContentDivs[nCurrent].append("<strong><a href='" + this.m_sURL + "'>" + sTitle + "</a><strong>");
    this.m_oContentDivs[nCurrent].append("<em>" + this.m_sType + ' - ' + this.m_sTitle + "</em>");
    this.m_oContentDivs[nCurrent].append("<small>" + this.m_sDescription + "</small>");
  }
}

cWeekEvent.prototype.ControlConflictDate = function (poEvent)
{
  nCountA = this.m_asCoords.events.length;
  nCountB = poEvent.m_asCoords.events.length;

  // On contrôle chaque jour de présence de l'évènement
  for (nIndexA = 0; nIndexA < nCountA; nIndexA++)
  {
    for (nIndexB = 0;nIndexB < nCountB; nIndexB++)
    {
      bConflict = false;

      // S'il s'agit du même jour
      if (this.m_asCoords.events[nIndexA].day == poEvent.m_asCoords.events[nIndexB].day)
      {
        nDebutA = this.m_asCoords.events[nIndexA].hour*60+this.m_asCoords.events[nIndexA].minute;
        nFinA = this.m_asCoords.events[nIndexA].hour*60+this.m_asCoords.events[nIndexA].minute+this.m_asCoords.events[nIndexA].size;
        nDebutB = poEvent.m_asCoords.events[nIndexB].hour*60+poEvent.m_asCoords.events[nIndexB].minute;
        nFinB = poEvent.m_asCoords.events[nIndexB].hour*60+poEvent.m_asCoords.events[nIndexB].minute+poEvent.m_asCoords.events[nIndexB].size;

        // Si le début de B est entre le début de A et sa fin, il y a conflit
        if (nDebutB >= nDebutA && nDebutB < nFinA) bConflict = true;

        // Si le début de A est entre le début de B et sa fin, il y a conflit
        if (nDebutA >= nDebutB && nDebutA < nFinB) bConflict = true;

        // S'il y a conflit
        if (bConflict)
        {
          this.m_asCoords.events[nIndexA].m_nCountConflict = this.m_asCoords.events[nIndexA].m_nCountConflict + 1;
          poEvent.m_asCoords.events[nIndexB].m_nCountConflict = poEvent.m_asCoords.events[nIndexB].m_nCountConflict + 1;
          this.m_asCoords.events[nIndexA].m_nPositionConflict = this.m_asCoords.events[nIndexA].m_nPositionConflict + 1;
        }
      }
    }
  }
}

cWeekEvent.prototype.HourToString = function(pnHour, pnMinute)
{
  var sHour = '';
  if (pnHour < 10) sHour += '0'
  sHour += pnHour;
  sHour +=  ':'
  if (pnMinute < 10) sHour += '0'
  sHour += pnMinute;
  return sHour;
}

cWeekEvent.prototype.Draw = function()
{
  var nLength = this.m_asCoords.events.length;
  for (nCurrent = 0; nCurrent < nLength; nCurrent++)
  {
    this.m_oDivs[nCurrent].css("height", ((this.m_asCoords.events[nCurrent].size / cWeekAgenda.CONST_CELL_DURATION) * cWeekAgenda.CONST_CELL_HEIGHT) + "px");
    this.m_oDivs[nCurrent].css("top", ((this.m_asCoords.events[nCurrent].hour - cWeekAgenda.CONST_HOUR_START) * (2 * cWeekAgenda.CONST_CELL_HEIGHT) + (this.m_asCoords.events[nCurrent].minute / cWeekAgenda.CONST_CELL_DURATION) * cWeekAgenda.CONST_CELL_HEIGHT + cWeekAgenda.CONST_CELL_HEADER_HEIGHT) + "px");

    // On gère la superposition des evenements
    if (this.m_asCoords.events[nCurrent].m_nCountConflict > 0)
    {
      nWidth = (2 * cWeekAgenda.CONST_COLUMN_WIDTH) / (this.m_asCoords.events[nCurrent].m_nCountConflict + 2);
      nDecalage = (nWidth / 2) * this.m_asCoords.events[nCurrent].m_nPositionConflict;
    }
    else
    {
      nWidth = cWeekAgenda.CONST_COLUMN_WIDTH;
      nDecalage = 0;
    }

    this.m_oDivs[nCurrent].css("right", (Math.abs(this.m_asCoords.events[nCurrent].day - 7) * (cWeekAgenda.CONST_COLUMN_WIDTH) + nDecalage) + "%");
    this.m_oDivs[nCurrent].css("width", nWidth + "%");
    this.m_oDivs[nCurrent].css("position", "absolute");
    this.m_oDivs[nCurrent].css("z-index", "1");

    this.m_oContentDivs[nCurrent].addClass("agenda_weekevent");
    this.m_oContentDivs[nCurrent].css("height", (((this.m_asCoords.events[nCurrent].size / cWeekAgenda.CONST_CELL_DURATION) * cWeekAgenda.CONST_CELL_HEIGHT) - 4) + "px");
    if (nLength > 1)
    {
      if (nCurrent != 0 || this.m_bStartPreviousWeek)
      {
        this.m_oContentDivs[nCurrent].append($(document.createElement("div")).addClass("agenda_from_previousday"));
      }

      if (nCurrent < nLength - 1 || this.m_bEndNextWeek)
      {
        this.m_oContentDivs[nCurrent].append($(document.createElement("div")).addClass("agenda_continue_nextday"));
      }
    }
  }
}