var APP_URL = "./";
var IMG_URL = APP_URL + "images/";
var CSS_URL = APP_URL + "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 resize()
{
   var conteneur = document.getElementById('conteneur');
   var heightConteneur = parseInt(conteneur.scrollHeight);
	
   var main = document.getElementById('main');
   var heightMain = parseInt(main.scrollHeight);
	
   var blocPrincipalMilieu = document.getElementById('bloc-principal-milieu');
   var heightBlocPrincipalMilieu = parseInt(blocPrincipalMilieu.scrollHeight);
	
   var blocPrincipalMilieuContenu = document.getElementById('bloc-principal-milieu-contenu');
   var heightBlocPrincipalMilieuContenu = parseInt(blocPrincipalMilieuContenu.scrollHeight);
	
   var googleMap = document.getElementById('google-map');
	if( googleMap != null )
	{
		var heightGoogleMap = parseInt(googleMap.scrollHeight);
	}
	
	var googleMap2 = document.getElementById('google-map2');
   if( googleMap2 != null )
   {
      var heightGoogleMap2 = parseInt(googleMap2.scrollHeight);
   }
   
   var googlePhoto = document.getElementById('google-photo');
   if( googlePhoto != null )
   {
      var heightGooglePhoto = parseInt(googlePhoto.scrollHeight);
   }
	
   var menuGaucheNiveau0 = document.getElementById('menu-gauche-niveau0');
	if( menuGaucheNiveau0 != null )
	{
		var heightMenuGaucheNiveau0 = parseInt(menuGaucheNiveau0.scrollHeight);
	}
	
   var heightBody = parseInt(document.body.clientHeight);
   height = heightBody - 1;
	
   if( heightBody < 660 )
   {
      height = 660;
   }
	
	if( menuGaucheNiveau0 != null && heightMenuGaucheNiveau0 >= height - 360 )
	{
		height = heightMenuGaucheNiveau0 + 360;
	}
	
   conteneur.style.height = ( height + 1 ) + 'px';
   main.style.height = ( height - 230 ) + 'px';
   blocPrincipalMilieu.style.height = ( height - 340 ) + 'px';
   blocPrincipalMilieuContenu.style.height = ( height - 360 ) + 'px';
	if( googleMap != null )
	{
		googleMap.style.height = ( height - 387 ) + 'px';
	}
	if( googleMap2 != null )
   {
      googleMap2.style.height = ( height - 387 ) + 'px';
   }
   if( googlePhoto != null )
   {
      googlePhoto.style.height = ( height - 387 ) + 'px';
   }
}

function openMenu(index, cpt)
{
   var contentHeightMenuHaut = document.getElementById('item-menu-haut-'+index).offsetHeight;
   var contentHeightMenuHautPartieMilieu = document.getElementById('item-menu-haut-partie-milieu-'+index).offsetHeight;
   if (contentHeightMenuHaut != 50 && cpt+37 == contentHeightMenuHaut)
   {
      document.getElementById('item-menu-haut-'+index).style.height = (contentHeightMenuHaut+1)+'px';
      document.getElementById('item-menu-haut-partie-milieu-'+index).style.height = (contentHeightMenuHautPartieMilieu+1)+'px';
      setTimeout("openMenu(" + index + ", " + (cpt+1) + ")", 37);
   }
}

function closeMenu(index)
{
   var contentHeightMenuHaut = document.getElementById('item-menu-haut-'+index).offsetHeight;
   var contentHeightMenuHautPartieMilieu = document.getElementById('item-menu-haut-partie-milieu-'+index).offsetHeight;
   if (contentHeightMenuHaut != 37)
   {
      var cpt = contentHeightMenuHaut - 37;
      document.getElementById('item-menu-haut-'+index).style.height = (contentHeightMenuHaut-1)+'px';
      document.getElementById('item-menu-haut-partie-milieu-'+index).style.height = (contentHeightMenuHautPartieMilieu-1)+'px';
      setTimeout("closeMenu(" + index + ")", 37);
   }
}

function containsDOM(aoContainer, aoContainee)
{
   var isParent = false;
   do
   {
      if ((isParent = aoContainer == aoContainee))
      {
         break;
      }
      aoContainee = aoContainee.parentNode;
   }
   while (aoContainee != null);
   return isParent;
}

function checkMouseEnter(aoContainer, aoEvt)
{
   if (aoContainer.contains && aoEvt.fromElement)
   {
      return !aoContainer.contains(aoEvt.fromElement);
   }
   else if (aoEvt.relatedTarget)
   {
      return !containsDOM(aoContainer, aoEvt.relatedTarget);
   }
}

function checkMouseLeave(aoContainer, aoEvt)
{
   if (aoContainer.contains && aoEvt.toElement)
   {
      return !aoContainer.contains(aoEvt.toElement);
   }
   else if (aoEvt.relatedTarget)
   {
      return !containsDOM(aoContainer, aoEvt.relatedTarget);
   }
}

var gsIdFrame = "";

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.formInternet[asDatefield])
   {
      var lsId = parent.document.formInternet[asDatefield].id;
      loWindow = parent.document.getElementById(parent.document.formInternet[asDatefield].id+"Calendar").contentWindow;
   }
   else if (window.document && window.document.formInternet[asDatefield])
   {
      var lsId = window.document.formInternet[asDatefield].id;
      loWindow = window;
   }

   windowOpener = "parent";
   windowClose = "parent.document.getElementById('"+parent.document.formInternet[asDatefield].id+"Calendar').style.display='none'";
   
   if (parent.document && parent.document.formInternet[asDatefield+"DayName"])
   {
      lsFieldDayName = "javascript:parent.document.formInternet."+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"+
		// "   <script type=\"text/javascript\">\n"+
		// "      function resizeIframe()\n"+
		// "      {\n"+
		// "         aoIFrame = parent.document.getElementById('"+document.formInternet[asDatefield].id+"Calendar');\n"+
		// "         aoIFrame.height = aoIFrame.contentWindow.document.body.scrollHeight;\n"+
		// "      }\n"+
		// "   </script>\n"+
      "</head>\n"+
      // "<body class=\"calendarBody\" onLoad=\"setTimeout('self.focus()', 500);resizeIframe();resizeIframe();\">\n" +
      "<body class=\"calendarBody\" onLoad=\"setTimeout('self.focus()', 500);\">\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)
         else if (ldCurrentDay.getDay() == 0)
         {
            // 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.formInternet."+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.formInternet."+asDatefield+".value='"+getDatetime(ldCurrentDay)+"';"+ windowClose +"\">";
         }
         else
         {
            // Affichage des jours des autres mois
            lsBuffer += "<a class=\"otherMonthDate\" href=\"javascript:"+ windowOpener +".document.formInternet."+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.formInternet[asDatefield].id+"Calendar');\n"+
         // "   aoIFrame.height = aoIFrame.contentWindow.document.body.scrollHeight;\n"+
         // "}\n"+
         // "</script>\n"+
      "</html>\n");
   lsHeight = "204";
   
   var loCalendarDoc = loWindow.document;
	
	// function resizeIframe()
	// {
		// aoIFrame = parent.document.getElementById(document.formInternet[asDatefield].id+'Calendar');
		// aoIFrame.height = aoIFrame.contentWindow.document.body.scrollHeight;
	// }
   
   if (loCalendarDoc.getElementById('calendarTable') != null)
   {
      loCalendarDoc.getElementById('calendarTable').innerHTML = lsBuffer;
      // resizeIframe(windowOpener.document.getElementById(windowOpener.document.formInternet[asDatefield].id+"Calendar"));
      // Pour Firefox, faire un 2nd appel pour bien redimensionner l'iframe
      // resizeIframe(windowOpener.document.getElementById(windowOpener.document.formInternet[asDatefield].id+"Calendar"));
   }
   else
   {
      loCalendarDoc.write (lsBufferBegin + lsBufferEnd);
      loCalendarDoc.close();
      loCalendarDoc.getElementById('calendarTable').innerHTML = lsBuffer;
      // resizeIframe(windowOpener.document.getElementById(windowOpener.document.formInternet[asDatefield].id+"Calendar"));
      // Pour Firefox, faire un 2nd appel pour bien redimensionner l'iframe
      // resizeIframe(windowOpener.document.getElementById(windowOpener.document.formInternet[asDatefield].id+"Calendar"));
   }
}

// 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);
}

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

var imageBanniere = new Image( );

function lancementBanniere( image )
{
   imageBanniere.src = IMG_URL + 'bannieres/animees/' + image;
   chargementBanniere( image );
}

function chargementBanniere( image )
{
	if( !imageBanniere.complete )
   {
      setTimeout( 'chargementBanniere( \'' + image + '\' )', 100 );
   }
   else
   {
      document.getElementById( 'banniere-2-image' ).src = IMG_URL + 'bannieres/animees/' + image;
   }
}
