var APP_URL = "../../";
var THEME   = APP_URL + "theme/";
var IMG_URL = THEME + "images/";
var CSS_URL = THEME + "css/";

var DivioLang = {
   /***** Calendar *****/
   daysFull                 : ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"],
   months                   : ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
   days                     : ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"],
   weekStart                : 1, // 0 -> Dimanche, 1 -> Lundi
   calendar                 : "Calendrier",
   prevYear                 : "Année précédente",
   prevMonth                : "Mois précédent",
   nextMonth                : "Mois suivant",
   nextYear                 : "Année suivante",
   time                     : "Heure :",
   msgErrorDateFormat       : "Format date heure invalide :"
};

function montre_div(nomdiv)
{
   this.document.getElementById(nomdiv).style.display='block';
}

function cache_div(nomdiv)
{
   this.document.getElementById(nomdiv).style.display='none';
}


function ctlTextArea(asFieldName, anMaxLength)
{
   var txt = document.principal.elements[asFieldName].value;
   var nb  = document.principal.elements[asFieldName].value.length;
   if (nb > anMaxLength)
   {
      document.principal.elements[asFieldName].value = txt.substring(0, anMaxLength);
      nb = anMaxLength;
   }
   if (document.getElementById(asFieldName + 'NbChar'))
   {
      document.getElementById(asFieldName + 'NbChar').innerHTML = anMaxLength - document.principal.elements[asFieldName].value.length;
   }
}

function openWindow(asPage, anWidth, anHeight)
{
   if (!anWidth)
   {
      anWidth = screen.width;
   }
   if (!anHeight)
   {
      anHeight = screen.height;
   }
   if (anHeight > screen.height)
   {
      anHeight = screen.height;
      anWidth += 24;
   }
   anPosX = (screen.width - anWidth) / 2;
   anPosY = (screen.height - anHeight) / 2;
   asName = 'window1';
   window1 = window.open(asPage,asName,"toolbar=no,location=no,dependent=yes,directories=no,status=yes,menubar=no,resizable=yes,scrollbars=yes,left="+anPosX+",screenX="+anPosX+",top="+anPosY+",screenY="+anPosY+",width="+anWidth+",height="+anHeight);
}

var gsIdFrame = "";

/**
 * Ouvrir une iframe
 * @param string idFrame - l'id de la frame
 */
function openIFrame(idFrame) {
   gsIdFrame = idFrame;
   if (document.getElementById(idFrame).style.display=='block') {
      document.getElementById(idFrame).style.display = 'none';
   } else {
      try {
         document.onclick = check;
      } catch(e) {}
         document.getElementById(idFrame).style.display = 'block';
      try {
      	 document.getElementById(idFrame).contentWindow.init();
      } catch(e) {}
   }
}

/**
 * Fermer l'iframe lors d'un clic de souris à l'extérieur de la frame
 * @param e - évènement
 */
function check(e) {
   var target = (e && e.target) || (event && event.srcElement);
   var obj = document.getElementById(gsIdFrame);
   var obj2 = document.getElementById(gsIdFrame+'Img');
   if (target == obj2) {
      if (obj.style.display == "block") {
         obj.style.display = 'block';
      } else {
         obj.style.display = 'none';
      }
   } else if (checkParent(target)) {
      obj.style.display = 'none';
   }
}

/**
 * Vérifier si l'objet est dans l'iframe
 * @param t - objet du DOM
 */
function checkParent(t) {
   while (t.parentNode) {
      if (t == document.getElementById(gsIdFrame)) {
         return false;
      }
      t = t.parentNode;
   }
   return true;
}


function showCalendar(asDatefield, asDatevalue)
{
   var loWindow;
   
   if (parent.document && parent.document.principal[asDatefield])
   {
      var lsId = parent.document.principal[asDatefield].id;
      loWindow = parent.document.getElementById(parent.document.principal[asDatefield].id+"Calendar").contentWindow;
   }
   else if (window.document && window.document.principal[asDatefield])
   {
      var lsId = window.document.principal[asDatefield].id;
      loWindow = window;
   }

   windowOpener = "parent";
   loWindowOpener = parent;
   windowClose = "parent.document.getElementById('"+parent.document.principal[asDatefield].id+"Calendar').style.display='none'";
   
   if (parent.document && parent.document.principal[asDatefield+"DayName"])
   {
      lsFieldDayName = "javascript:parent.document.principal."+asDatefield+"DayName.value = ";
   }

   var ldDatevalue = (asDatevalue == null || asDatevalue =="" ?  new Date() : str2Date(asDatevalue));
   var ldPrevYear  = new Date(ldDatevalue);
       ldPrevYear.setYear(ldDatevalue.getFullYear()-1);
   var ldPrevMonth = new Date(ldDatevalue);
       ldPrevMonth.setMonth(ldDatevalue.getMonth()-1);
   var ldNextMonth = new Date(ldDatevalue);
       ldNextMonth.setMonth(ldDatevalue.getMonth()+1)
   var ldNextYear  = new Date(ldDatevalue);
       ldNextYear.setYear(ldDatevalue.getFullYear()+1);
   var ldFirstDay  = new Date(ldDatevalue);
       ldFirstDay.setDate(1);
       ldFirstDay.setDate(1-(7+ldFirstDay.getDay()-DivioLang["weekStart"])%7);
   var liMonth;
   var liYear;
   var ldSelected;

   var lsSelectBuffer = "<select class=\"calendarListBox\" name=\"lbDate\" onChange=\"javascript:"+ windowOpener +".showCalendar('"+asDatefield+"', this.options[this.selectedIndex].value);\">\n";
   for (var nbMonths = -12 ; nbMonths <= 12 ; nbMonths++)
   {
      if (ldDatevalue.getMonth()+nbMonths < 0)
      {
         liMonth = 12 + (ldDatevalue.getMonth()+nbMonths);
         liYear = ldDatevalue.getFullYear()-1;
      }
      else if (ldDatevalue.getMonth()+nbMonths > 11)
      {
         liMonth = ldDatevalue.getMonth()+nbMonths-12;
         liYear = ldDatevalue.getFullYear()+1;
      }
      else
      {
         liMonth = ldDatevalue.getMonth()+nbMonths;
         liYear = ldDatevalue.getFullYear();
      }
      ldSelected = new Date(ldDatevalue);
      ldSelected.setMonth(ldDatevalue.getMonth()+nbMonths)
      lsSelectBuffer += "<option value=\""+date2D(ldSelected)+"\"";
      if (nbMonths == 0)
      {
         lsSelectBuffer += " selected ";
      }
      lsSelectBuffer += ">"+DivioLang["months"][liMonth]+" "+liYear+"</option>\n";
   }
	
   lsSelectBuffer += "</select>\n";

   // Génération en HTML

   // Affichage de l'ent?te du calendrier
   var lsBufferBegin = new String (
      "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"+
      "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"fr\" xml:lang=\"fr\">\n"+
      "<head>\n"+
      "   <title>"+DivioLang["calendar"]+"</title>\n"+
      "   <link href=\""+ CSS_URL +"calendar.css\" rel=\"stylesheet\" type=\"text/css\" />\n"+
      "</head>\n"+
      "<body class=\"calendarBody\" onLoad=\"setTimeout('self.focus()', 500);resizeIframe();resizeIframe();\">\n" +
         "<form name=\"cal\" action=\"\">\n"+
            "<div id=\"calendarTable\">\n");
   var lsBuffer = new String (
            "<table class=\"calendarTable\" align=\"center\" cellspacing=\"0\" cellpadding=\"0\">\n"+
               "<tr>\n"+
                  "<td>\n"+
                     "<table class=\"intoCalendarTable\" cellspacing=\"1\" cellpadding=\"3\">\n"+
                        "<tr>\n"+
                           "<td class=\"calendarNavigation\" colspan=\"7\" width=\"100%\">\n"+
                              "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\">\n"+
                                 "<tr>\n"+
                                    "<td width=\"43\">\n"+
                                       "<a href=\"javascript:"+ windowOpener +".showCalendar('"+asDatefield+"', '"+date2D(ldPrevYear)+"');\" title=\""+DivioLang["prevYear"]+"\">"+
                                          "<img class=\"calendarImage\" src=\""+IMG_URL+"form-action-first.gif\" border=\"0\" alt=\""+DivioLang["prevYear"]+"\"/></a>\n"+
                                       "<a href=\"javascript:"+ windowOpener +".showCalendar('"+asDatefield+"', '"+date2D(ldPrevMonth)+"');\" title=\""+DivioLang["prevMonth"]+"\">"+
                                          "<img class=\"calendarImage\" src=\""+IMG_URL+"form-action-previous.gif\" border=\"0\" alt=\""+DivioLang["prevMonth"]+"\"/></a>\n"+
                                    "</td>\n"+
                                    "<td align=\"center\">\n"+
                                       lsSelectBuffer+
                                    "</td>\n"+
                                    "<td align=\"right\" width=\"43\">\n"+
                                       "<a href=\"javascript:"+ windowOpener +".showCalendar('"+asDatefield+"', '"+date2D(ldNextMonth)+"');\" title=\""+DivioLang["nextMonth"]+"\">"+
                                       "<img class=\"calendarImage\" src=\""+IMG_URL+"form-action-next.gif\" border=\"0\" alt=\""+DivioLang["nextMonth"]+"\"/></a>\n"+
                                       "<a href=\"javascript:"+ windowOpener +".showCalendar('"+asDatefield+"', '"+date2D(ldNextYear)+"');\" title=\""+DivioLang["nextYear"]+"\">"+
                                       "<img class=\"calendarImage\" src=\""+IMG_URL+"form-action-last.gif\" border=\"0\" alt=\""+DivioLang["nextYear"]+"\"/></a>\n"+
                                    "</td>\n"+
                                 "</tr>\n"+
                              "</table>\n"+
                           "</td>\n"+
                        "</tr>\n");

   var ldCurrentDay = new Date(ldFirstDay);

   // Titres des jours de la semaine
   lsBuffer += "<tr>\n";
   for (var nbDays=0; nbDays<7; nbDays++)
   {
      lsBuffer += "<td class=\"calendarHeader\" width=\"14%\" align=\"center\" colspan=\"1\">\n"+
                       DivioLang["days"][(DivioLang["weekStart"]+nbDays)%7]+"\n";
                    "</td>\n";
   }
   // Tableau Calendrier
   lsBuffer += "</tr>\n";
   while (ldCurrentDay.getMonth() == ldDatevalue.getMonth() || ldCurrentDay.getMonth() == ldFirstDay.getMonth())
   {
      // Affichage d'une ligne
      lsBuffer += "<tr>\n";
      for (var nbDays=0; nbDays<7; nbDays++)
      {
         if (ldCurrentDay.getDate() == ldDatevalue.getDate() && ldCurrentDay.getMonth() == ldDatevalue.getMonth())
         {
            // Date courante
            lsBuffer += "<td class=\"currentDate\">";
         }
         else if (ldCurrentDay.getDay() == 0 || ldCurrentDay.getDay() == 6)
         {
            // Jours de week-end
            lsBuffer += "<td  class=\"weekendDate\">";
         }
         else
         {
            // Jours travaill?s du mois courant
            lsBuffer += "<td class=\"weekDate\">";
         }

         lsValueDayName = '';

         if (ldCurrentDay.getDate() == ldDatevalue.getDate() && ldCurrentDay.getMonth() == ldDatevalue.getMonth())
         {
            // Affichage du jour courant
            lsBuffer += "<a class=\"currentDayDate\" href=\"javascript:"+ windowOpener +".document.principal."+asDatefield+".value='"+getDatetime(ldCurrentDay)+"';"+ windowClose +"\">";
         }
         else if (ldCurrentDay.getMonth() == ldDatevalue.getMonth())
         {
            // Affichage des jours du mois courant
            lsBuffer += "<a class=\"monthDate\" href=\"javascript:"+ windowOpener +".document.principal."+asDatefield+".value='"+getDatetime(ldCurrentDay)+"';"+ windowClose +"\">";
         }
         else
         {
            // Affichage des jours des autres mois
            lsBuffer += "<a class=\"otherMonthDate\" href=\"javascript:"+ windowOpener +".document.principal."+asDatefield+".value='"+getDatetime(ldCurrentDay)+"';"+ windowClose +"\">";
         }

         lsBuffer += ldCurrentDay.getDate()+"</a>\n"+
                                                "</td>\n";
         ldCurrentDay.setDate(ldCurrentDay.getDate()+1);
      }
      lsBuffer += "</tr>\n";
   }

   // Affichage du pied du calendrier
   lsBuffer +=           "</table>\n"+
                     "</td>\n"+
                  "</tr>\n"+
               "</table>\n";
   var lsBufferEnd = new String (
            "</div>\n"+
            "</form>\n"+
         "</body>\n"+
         "<script type=\"text/javascript\">\n"+
         "function resizeIframe() {\n"+
         "   aoIFrame = parent.document.getElementById('"+document.principal[asDatefield].id+"Calendar');\n"+
         "   aoIFrame.height = aoIFrame.contentWindow.document.body.scrollHeight;\n"+
         "}\n"+
         "</script>\n"+
      "</html>\n");
   
   var loCalendarDoc = loWindow.document;
   if (loCalendarDoc.getElementById('calendarTable') != null)
   {
      loCalendarDoc.getElementById('calendarTable').innerHTML = lsBuffer;
      resizeIframe(loWindowOpener.document.getElementById(loWindowOpener.document.principal[asDatefield].id+"Calendar"));
      // Pour Firefox, faire un 2nd appel pour bien redimensionner l'iframe
      resizeIframe(loWindowOpener.document.getElementById(loWindowOpener.document.principal[asDatefield].id+"Calendar"));
   }
   else
   {
      loCalendarDoc.write (lsBufferBegin + lsBufferEnd);
      loCalendarDoc.close();
      loCalendarDoc.getElementById('calendarTable').innerHTML = lsBuffer;
      resizeIframe(loWindowOpener.document.getElementById(loWindowOpener.document.principal[asDatefield].id+"Calendar"));
      // Pour Firefox, faire un 2nd appel pour bien redimensionner l'iframe
      resizeIframe(loWindowOpener.document.getElementById(loWindowOpener.document.principal[asDatefield].id+"Calendar"));
   }
}

// Redimensionne l'iframe
// Id iframe à redimensionner
function resizeIframe(aoIFrame) {
   aoIFrame.height = aoIFrame.contentWindow.document.body.scrollHeight;
}

// Transforme une date string au format date
// asDateValue : valeur de la date en string
function str2Date(asDatevalue)
{
   var reDate = /^(\d+)\/(\d+)\/(\d+)\s+$/;
   if (!reDate.exec(asDatevalue))
   {
      var reDate = /^(\d+)\/(\d+)\/(\d+)$/;
      if (!reDate.exec(asDatevalue))
      {
         alert(DivioLang["msgErrorDateFormat"] + asDatevalue);
         return new Date();
      }
      return (new Date (RegExp.$3, RegExp.$2-1, RegExp.$1));
   }
   return (new Date (RegExp.$3, RegExp.$2-1, RegExp.$1));
}


// Transforme une date string au format date
// adDatevalue      : date à transformer
function date2D(adDatevalue, asLanguageFormat)
{
   return (new String (
      (adDatevalue.getDate() < 10 ? "0" : "")+adDatevalue.getDate()+
      "/"+
      ((adDatevalue.getMonth()+1) < 10 ? "0" : "")+(adDatevalue.getMonth()+1)+
      "/"+
      adDatevalue.getFullYear()));
}

// Appelle les fonctions qui transforment une date en string au format

function getDatetime(adDatevalue)
{
    return date2D(adDatevalue);
}
