

var SocialEngineAPI={version:"0.1.0alpha"};

// Jean 14/04/2010
var tabObjComments = new Array();

var last_ref_comment_id;


SocialEngineAPI.Base=new Class({initialize:function(){this.version=SocialEngineAPI.version},RegisterModule:function(a){a.Base=this}});


SocialEngineAPI.Comments=new Class({

Implements:[Options],Base:{},page:1,total:0,changed:false,isEditing:false,

options:{ajaxURL:"misc_js.php",ajaxMethod:"post",ajaxSecure:false,canComment:false,commentHTML:false,commentCode:false,originalHeight:70,type:false,typeIdentifier:false,typeID:false,paginate:false,cpp:false,commentLinks:{reply:false,walltowall:false},object_owner:false,object_owner_id:false,typeTab:false,typeCol:false,typeTabParent:false,typeColParent:false,typeChild:false},

// Jean 22/09/2011
dicoColors: Array(),
dicoColorCursor: 0,
dicoColorByUser: Array(),
totalInjectedComments: 0,
totalLastInjectedComments: null,
dicoCommentIds: Array(),
iAmGettingComments: false,

initialize:function(a){

  this.setOptions(a);
  if(this.options.initialTotal)
    {this.total=this.options.initialTotal}

  var b=this;
  tabObjComments[this.options.type] = this;

  this.dicoColors = [
   '#3399FF', // turquoise
   '#EE820B', // orange
   '#27B639', // vert gazon
   '#7B85A6', // gris bleuté
   '#E71212', // rouge
   '#383A78', // violet
   '#DA10DA', // magenta
   '#848D12', // vert foncé
   '#1552C4', // bleu marine
   '#653232', // marron
   '#A7A7A7'  // gris clair
  ];

  window.addEvent("domready", function() {
    b.showPostComment();

    // Jean 22/09/2011
    if (b.options.modeWYSIWYG)
     {
      b.options.originalHeight = $('comment_body_'+ b.options.type).offsetHeight;
      initWYSIWYG('comment_body_'+ b.options.type, 'simple');
     }
    else
     {
      b.options.originalHeight = textarea_autogrow("comment_body_"+ b.options.type);
     }

    b.getComments(1);
  })

},

// Jean 15/12/2010 : ajout de : , commentIdWhichIsReplied, guyIdWhoIsReplied, guyNameWhoIsReplied
showPostComment:function(zoneReplyComment, parentCommentID, guyNameWhoIsReplied, commentIdWhichIsReplied, guyIdWhoIsReplied)
{
    var c="";

    var modeChatLive = this.options.modeLive && !parentCommentID;

//alert(parentCommentID +', '+ commentIdWhichIsReplied +', '+ guyIdWhoIsReplied +', '+ guyNameWhoIsReplied);

    // Jean 24/06/2011 : pour contourner bug IE en mode iframe
    if (!this.Base.Language)
     this.Base.Language = SocialEngine.Language;

    // Jean 14/04/2010
    var margeLargeur = zoneReplyComment ? 55 : 0;

    // Jean 15/12/2010
    if (commentIdWhichIsReplied)
      margeLargeur += 80;

    if ($(this.options.type +'_'+ this.options.typeID +'_'+ this.currentReplyCommentParentID +'_replycomment'))
      $(this.options.type +'_'+ this.options.typeID +'_'+ this.currentReplyCommentParentID +'_replycomment').innerHTML = '';

    if ($(this.options.type +'_'+ this.options.typeID +'_postcomment'))
      $(this.options.type +'_'+ this.options.typeID +'_postcomment').innerHTML = '';

    if (parentCommentID)
      this.currentReplyCommentParentID = parentCommentID;
    // Jean 14/04/2010

    // Jean 15/12/2010
    if (commentIdWhichIsReplied)
      this.currentReplyCommentParentID = commentIdWhichIsReplied;
    // Jean 15/12/2010

    // Nombre de commentaires :
    c+="<div class='comment_headline' style='width: "+ ((this.options.widthComments ? this.options.widthComments - 60 : 618) - margeLargeur) +"px; display:"+ (modeChatLive ? 'none' : '') +";' id='"+this.options.type+"_"+this.options.typeID+"_new_comment'>";

    // Jean 06/07/2011 : "Rafraîchir les commentaires"
    c+='<div style="float: right;">'
     + '<a href="javascript:;" onclick="$(\''+ this.options.type +'_'+ this.options.typeID +'_comments\').innerHTML = \'<img src=\\\'images/icons/loading2.gif\\\' border=0 />\'; setTimeout(\'window.parent.getComments(null, \\\''+ this.options.type +'\\\', 1);\');">'
     + '<img src="./images/icons/reload.png" align="absmiddle" border="0" class="menu_icon2" style="opacity: 0.70; filter: alpha(opacity=70);" title="'+ this.Base.Language.Translate(3511440) +'" />'
     + '</a></div>';

    // Intitulé du bloc = "Répondre à ce commentaire"
    if (zoneReplyComment)
      // "Annuler"
      c+= '<div style="float: right; padding-right: 4px;"><a href="javascript: tabObjComments[\''+ this.options.type +'\'].showPostComment();" style="color: #444444; font-family: arial;" title="'+ this.Base.Language.Translate(39) +'">'
          //+  style="text-transform: lowercase;"><small> + this.Base.Language.Translate(39)
          + 'X'
          // Jean 15/12/2010
          +'</a></div>'
          + (guyNameWhoIsReplied ? this.Base.Language.TranslateFormatted(3510844,[guyNameWhoIsReplied]) : this.Base.Language.Translate(3510414));
    else
     {
      // "Commentaires pour nous aider à préparer ce sujet en amont"
      c+= this.Base.Language.Translate(parent.objTournage ? 3511360 : 854);
      c+= " (<span class='tc' id='"+this.options.type+"_"+this.options.typeID+"_totalcomments_post'>"+ this.total +"</span>)";
     }
    c+= "</div>";

    if(this.options.canComment)
      {
       c+="<form id='my_form_comment"+ this.options.type +"_"+ (parentCommentID ? '_'+parentCommentID : '') +"' action='javascript: parent.essaiValidation(\"my_form_comment"+ this.options.type +"_"+ (parentCommentID ? '_'+parentCommentID : '') +"\", \""+ this.options.type +"\");' method='post' target='ajaxframe'>";
       c+="<div class='profile_postcomment' style='width: "+ ((this.options.widthComments ? this.options.widthComments - 80 : 600) - margeLargeur) +"px;'>";
       var largeurTextArea;
       // Jean 04/11/2009
       if (myPicture != '')
        {
         c+="<img src='"+ myPicture +"' align='left' style='width: "+ (this.options.modeLive ? '36' : '60') +"px; margin-right: 4px; margin-top: 1px;' />";
         largeurTextArea = ((this.options.widthComments ? this.options.widthComments - 150 : 535) - margeLargeur) +"px";
        }
       else
         largeurTextArea = "98%";

       c+="<textarea name='comment_body' id='comment_body_"+ this.options.type +"' class='comment_area' style='width: "+ largeurTextArea +"; height: "+ (this.options.modeLive ? '37' : '60') +"px; '></textarea>";

       // "Tags HTML autorisés"
       if (this.options.commentHTML)
        {c+="<div class='author_html_tags' style='margin-top: 5px;"+ (this.options.fontWidth ? "font-size: "+ this.options.fontWidth +"px;" : "font-size: 11px;") +"'>"+this.Base.Language.TranslateFormatted(1034,[this.options.commentHTML])+"</div>"}

       // Bouton pour couper ou non le son laissé par les nouveaux commentaires live
       if (modeChatLive)
        {
         // Son off
         audioImage1 = new Image(16,16);
         audioImage1.src = "./images/icons/chat_audio1.gif";
         // Son on
         audioImage2 = new Image(16,16);
         audioImage2.src = "./images/icons/chat_audio2.gif";

         c+="<div class='img_live_sound_on_off' style='float: left; margin: 2px 0px 0px 6px;'>"
          + "<img src='./images/icons/chat_audio2.gif' id='chat_audio_icon' border='0' class='icon'"
          +     " onclick='this.src = SocialEngine.EventComments.options.newLiveCommentsAreNoisy ? audioImage1.src : audioImage2.src;"
          +               "SocialEngine.EventComments.options.newLiveCommentsAreNoisy = !SocialEngine.EventComments.options.newLiveCommentsAreNoisy;'"
          // "Avertissement sonore à l'arrivée de nouveau messages ?"
          +     " title='"+ this.Base.Language.Translate(3511743).replace(/\'/, "&#39;") +"'"
          +     " style='cursor: pointer; margin-top: 2px; margin-left: 4px;'></div>";
        }

       if(this.options.commentCode)
        {c+="<div style='float: left; margin-top: 5px;'><a href='javascript:void(0);' onClick=\"this.blur();$('secure_image_"+ this.options.type +"').src=$('secure_image_"+ this.options.type +"').src+'?'+(new Date()).getTime();\"><img src='./images/secure.php' id='secure_image_"+ this.options.type +"' border='0' height='20' width='67' class='signup_code'></a> <input type='text' name='comment_secure' id='comment_secure_"+ this.options.type +"' class='text' size='6' maxlength='10'> <img src='./images/icons/tip.gif' border='0' class='Tips1' style='vertical-align: middle;' title='"+this.Base.Language.Translate(856)+"'></div>"
      }
    c+="<div style='text-align: right; margin-top: 5px;'>"
      +"<div id='comment_loading_zone_"+ this.options.type +"' style='display: none;'>"
      +"<img src='images/icons/loading2.gif' alt='Loading' border='0' /></div>"
      +"<input type='hidden' name='task' value='comment_post'>"
      +"<input type='hidden' name='type' value='"+ this.options.type +"'>"
      // Jean 19/09/2011
      +"<input type='hidden' name='is_live' value='"+ (modeChatLive ? '1' : '0') +"'>"
      +"<input type='hidden' name='iden' value='"+ this.options.typeIdentifier +"'>"
      +"<input type='hidden' name='value' value='"+ this.options.typeID +"'>"
// Jean 14/04/2010
      +"<input type='hidden' name='parentcommentid' value='"+ (parentCommentID ? parentCommentID : "") +"'>";

// Jean 24/10/2009
    self.alertIdentMessage = this.Base.Language.Translate(3000955);

    self.inner_field_name = new Array();
    self.inner_field_name["temp_displayname"] = this.Base.Language.Translate(3000956);
    self.inner_field_name["temp_email"]       = this.Base.Language.Translate(3000957);
    self.inner_field_name["temp_company"]     = this.Base.Language.Translate(3000958);
    self.inner_field_name["temp_website"]     = this.Base.Language.Translate(3000981);

    parent.essaiValidation = function (formID, comment_type)
     {
      if (self.identCommentValidate && !self.identCommentValidate(comment_type))
        {
         alert(self.alertIdentMessage);
        }
      else
        {
         setTimeout("$(\""+ formID +"\").action = \"misc_js.php\"; $(\""+ formID +"\").submit();",100);
        }
      $("comment_submit_"+ comment_type).disabled = false;
     }

    // Si pas loggué
    if (!isLogged)
     {
      // Jean 24/10/2009
      self.identCommentValidate = function(comment_type)
      {
        if ($("temp_displayname_"+ comment_type).value == self.inner_field_name["temp_displayname"]) return false;
        if ($("temp_email_"+ comment_type).value ==       self.inner_field_name["temp_email"]) return false;
        if (!$("temp_email_"+ comment_type).value.match(/^[a-z0-9]+([a-z0-9_+\.-]+)*@([a-z0-9]+([.-][a-z0-9]+)*)+\.[a-z]{2,}$/i)) return false;
        if ($("temp_company_"+ comment_type).value ==     self.inner_field_name["temp_company"]) $("temp_company_"+ comment_type).value = '';
        if ($("temp_website_"+ comment_type).value ==     self.inner_field_name["temp_website"]) $("temp_website_"+ comment_type).value = '';
        return true;
      };

      self.defaultCommentEmail = this.options.defaultEmail;

      self.identCommentInit = function(comment_type)
      {
        if (!$("temp_displayname_"+ comment_type))
          setTimeout("self.identCommentInit('"+ comment_type +"');", 100);
        else
         {
          $("temp_displayname_"+ comment_type).value = self.inner_field_name['temp_displayname'];
          $("temp_email_"+ comment_type).value       = self.inner_field_name['temp_email'];
          $("temp_company_"+ comment_type).value     = self.inner_field_name['temp_company'];
          $("temp_website_"+ comment_type).value     = self.inner_field_name['temp_website'];

          if (self.defaultCommentEmail)
            $("temp_email_"+ comment_type).value = self.defaultCommentEmail;
         }
      }

      c+='<span id="express_account_fields_'+ this.options.type +'">';
      c+='<input type="text" class="text" id="temp_displayname_'+ this.options.type +'" name="temp_displayname" style="font-size: 10px; color: gray; width: 128px;" onfocus="if (this.value == self.inner_field_name[\'temp_displayname\']) { this.value = \'\'; this.style.color = \'\'; }" onblur="if (this.value == \'\') { this.value = self.inner_field_name[\'temp_displayname\']; this.style.color = \'gray\'; }" /> &nbsp;';
      c+='<input type="text" class="text" id="temp_email_'+ this.options.type +'"       name="temp_email"       style="font-size: 10px;'+ (this.options.defaultEmail ? '' : ' color: gray;') +' width: 148px;" onfocus="if (this.value == self.inner_field_name[\'temp_email\']) { this.value = \'\'; this.style.color = \'\'; }" onblur="if (this.value == \'\') { this.value = self.inner_field_name[\'temp_email\']; this.style.color = \'gray\'; }" /> &nbsp;';
      c+='<input type="text" class="text" id="temp_company_'+ this.options.type +'"     name="temp_company"     style="font-size: 10px; color: gray; width: 138px;" onfocus="if (this.value == self.inner_field_name[\'temp_company\']) { this.value = \'\'; this.style.color = \'\'; }" onblur="if (this.value == \'\') { this.value = self.inner_field_name[\'temp_company\']; this.style.color = \'gray\'; }" /> &nbsp;';
      c+='<input type="text" class="text" id="temp_website_'+ this.options.type +'"     name="temp_website"     style="font-size: 10px; color: gray; width: 138px;" onfocus="if (this.value == self.inner_field_name[\'temp_website\']) { this.value = \'\'; this.style.color = \'\'; }" onblur="if (this.value == \'\') { this.value = self.inner_field_name[\'temp_website\']; this.style.color = \'gray\'; }" /><br><br>';
      c+='</span>';

      l = this;
      window.addEvent('domready', function()
       {
        self.identCommentInit(l.options.type);
       });
     }

     // POSTER
     c += '<input type="submit" id="comment_submit_'+ this.options.type +'" class="button" value="'+this.Base.Language.Translate(833)+'" />';

     // Jean 15/12/2010 : infos sur le commentaire auquel on fait suite
     if (commentIdWhichIsReplied)
       c += '<input type="hidden" name="commentIdWhichIsReplied" value="'+ commentIdWhichIsReplied +'" />';

     // Jean 15/03/2010 - "M'informer par email des prochains commentaires"
     if (this.options.type == 'blog' || this.options.type == 'event' || this.options.type == 'group')
       c += '<div style="margin-top: 10px;'+ (modeChatLive ? 'display: none;' : '') +'"'
            // "En tant que CM, je dois recevoir tous les commentaires"
            + (i_am_CM && !isExtranet ? ' title="'+ this.Base.Language.Translate(3511389) +'"' : '') +'>'
            +'<input type="checkbox" class="text" id="notify_me_'+ this.options.type +'" name="notify_me"'+ (this.options.notify_me || (i_am_CM && !isExtranet) ? ' checked' : '') + (this.options.notify_me && i_am_CM && !isExtranet ? ' disabled' : '') +' />'
            +'<label for="notify_me_'+ this.options.type +'" class="comment_notify_me'+ (i_am_CM && !isExtranet ? ' comment_notify_me_CM' : '') +'"> '+ this.Base.Language.Translate(3510238) +'</label></div>';

     // Jean 14/02/2011 - "Ne notifier personne par mail suite à ce commentaire"
     if (i_am_CM || isExtranet)
       c += '<div style="margin-top: 10px;'+ (modeChatLive ? 'display: none;' : '') +'"><input type="checkbox" class="text" id="no_notif_others_by_mail_'+ this.options.type +'" name="no_notif_others_by_mail"'+ (this.options.no_notif_others_by_mail ? ' checked' : '')
                       +' /><label for="no_notif_others_by_mail_'+ this.options.type +'"'+ (isExtranet ? '' : ' class="com_manager"')+ ' style="font-size: 11px;"> '+ this.Base.Language.Translate(3511079) +'</label></div>';

    if(this.options.object_owner&&this.options.object_owner_id)
     {c+='<input type="hidden" name="object_owner" value="'+this.options.object_owner+'"><input type="hidden" name="object_owner_id" value="'+this.options.object_owner_id+'">'}
    else
     {c+='<input type="hidden" name="user" value="'+this.Base.Owner.user_info.user_username+'">'}

    if(this.options.typeTab)
     {c+="<input type='hidden' name='tab' value='"+this.options.typeTab+"'>"}
    if(this.options.typeCol)
     {c+="<input type='hidden' name='col' value='"+this.options.typeCol+"'>"}
    if(this.options.typeTabParent)
     {c+='<input type="hidden" name="tab_parent" value="'+this.options.typeTabParent+'">'}
    if(this.options.typeColParent)
     {c+='<input type="hidden" name="col_parent" value="'+this.options.typeColParent+'">'}
    if(this.options.typeChild)
     {c+='<input type="hidden" name="child" value="1">'}
    c+="</div><div id='comment_error_"+ this.options.type +"' style='color: #FF0000;'>";
    // Jean 16/03/2010
    // Attention, vous avez demandé dans vos paramètres de compte à ne pas être prévenu par mail suite aux nouveaux articles de vos blogueurs préférés, ni suite aux prochains commentaires sur tout blog que vous commentez. Vous pouvez modifier ces préférences <a href="my_account">en allant ici</a>.
    if (this.options.type == 'blog' && !this.options.global_pref_notify)
     c += '<div style="color: #D20000; font-size: 11px; text-align: left;">'+ this.Base.Language.Translate(3510316) +'</div>';
    c+="</div></div></form>"
}

c+='<div style="display: none;" id="confirmcommentdelete_'+ this.options.type +'">'
 + '<div style="margin-top: 10px;">'+this.Base.Language.Translate(1026)+'</div><br />'
 + '<form action="misc_js.php" method="post" target="ajaxframe">'
 + '<input type="submit" id="btn_valid_delete_comment_'+ this.options.type +'" class="button" value="'+this.Base.Language.Translate(175)+'" onClick="parent.TB_remove();">'
 + ' '
 + '<input type="button" class="button" value="'+this.Base.Language.Translate(39)+'" onClick="parent.TB_remove();">'
 + '<input type="hidden" name="task" value="comment_delete">'
 + '<input type="hidden" name="comment_id" id="del_comment_id_'+ this.options.type +'" value="0">'
 + '<input type="hidden" name="type" value="'+this.options.type+'">'
 + '<input type="hidden" name="iden" value="'+this.options.typeIdentifier+'">'
 + '<input type="hidden" name="value" value="'+this.options.typeID+'">';

if(this.options.object_owner&&this.options.object_owner_id)
  {c+='<input type="hidden" name="object_owner" value="'+this.options.object_owner+'"><input type="hidden" name="object_owner_id" value="'+this.options.object_owner_id+'">'}
else
  {c+='<input type="hidden" name="user" value="'+this.Base.Owner.user_info.user_username+'">'}
if(this.options.typeTab)
  {c+='<input type="hidden" name="tab" value="'+this.options.typeTab+'">'}
if(this.options.typeCol)
  {c+='<input type="hidden" name="col" value="'+this.options.typeCol+'">'}
if(this.options.typeTabParent)
  {c+='<input type="hidden" name="tab_parent" value="'+this.options.typeTabParent+'">'}
if(this.options.typeColParent)
  {c+='<input type="hidden" name="col_parent" value="'+this.options.typeColParent+'">'}
if(this.options.typeChild)
  {c+='<input type="hidden" name="child" value="1">'}
c+="</form></div>";
// Jean 14/04/2010
var a = zoneReplyComment ? zoneReplyComment : $(this.options.type+"_"+this.options.typeID+"_postcomment");
a.innerHTML=c;

// Jean 14/04/2010
if (zoneReplyComment)
 {
  this.removeText(a.getElement("textarea"));
  //initWYSIWYG('comment_body_'+ this.options.type, 'simple');
  textarea_autogrow('comment_body_'+ this.options.type);
 }

if (zoneReplyComment || this.options.modeLive)
  setTimeout("$('comment_body_"+ this.options.type +"').focus();", 100);

var b=this;
if(this.options.canComment)
  {
   a.getElement("form").addEvent(
    "submit",
    function() {
      b.checkText();
    }
   );

   a.getElement("textarea").addEvent("focus",function(){b.removeText(this)});
   a.getElement("textarea").addEvent("blur",function(){b.addText(this)})
  }
  },

getComments:function(e, mustRefreshLiveComments)
  {
    if (mustRefreshLiveComments)
     {
      this.totalInjectedComments = 0;
      this.dicoCommentIds = Array();
     }

    // Jean 22/09/2011
    if (this.iAmGettingComments && !mustRefreshLiveComments)
      return;

    this.iAmGettingComments = true;

     if(e=="next"){this.page++}
     else{if(e=="previous"){this.page--}
     else{if($type(e)){this.page=e}}}
     if(this.options.paginate){window.scroll(0,0)}
     else{this.options.cpp=this.total}
     if(this.options.object_owner&&this.options.object_owner_id)
       {var d=this.options.object_owner;var a=this.options.object_owner_id;var b=""}
     else{var d="";var a="";var b=this.Base.Owner.user_info.user_username}
     var f=this;

     // télécharger seulement les nouveaux commentaires ?
     var onlyInjectNewComments = this.options.modeLive && this.totalInjectedComments > 0;

     var c=new Request.JSON({
        url:this.options.ajaxURL,
            method:this.options.ajaxMethod,
            secure:this.options.ajaxSecure,
            data:{task:"comment_get",
                  user:b,
                  object_owner:d,
                  object_owner_id:a,
                  type:this.options.type,
                  iden:this.options.typeIdentifier,
                  value:this.options.typeID,
                  // Jean 12/07/2011
                  cpp: this.options.paginate ? this.options.cpp : 0, //this.options.cpp,
                  p:this.page,
                  // Jean 19/09/2011
                  after_comment_id: onlyInjectNewComments ? SocialEngineAPI.Comments.lastCommentId : ''
                 },
            onComplete:function(g,h) {

              f.updateComments(g, onlyInjectNewComments, mustRefreshLiveComments)

              // Jean 22/09/2011
              f.iAmGettingComments = false;
            }
     });
     c.send()
   },

updateComments:function(b, onlyInjectNewComments, mustRefreshLiveComments){

     if($type(b)!="object")
       {/* alert("There was an error processing the request."); */ return false}

     this.total=parseInt(b.total_comments)||0;

     // Jean 19/09/2011
     if (this.options.modeLive && this.total == 0 && !mustRefreshLiveComments)
       return;

     this.page=b.p;
     var a = b.maxpage;var n=b.p_start;var m=b.p_end;
     // Là où seront injectés les commentaires
     var g = $(this.options.type +"_"+ this.options.typeID +"_comments");

     /*
     if (this.options.modeLive)
      {
       g.innerHTML = '<div id="'+ this.options.type +'_'+ this.options.typeID +'_comments_content"></div>';
       var g = $(this.options.type +"_"+ this.options.typeID +"_comments_content");
      }
     */

     var k = $H(b.comments);

     var f = document.createElement("div");

     // Jean 19/09/2011 : on ne vide la zone des commentaires que si on n'est pas en mode "rappatrier seulement les commentaires postés après telle date"
     if (!onlyInjectNewComments)
       g.empty();

     // Jean 06/07/2011 : "Rafraîchir les commentaires"
     this.btnRefreshHtml = // Jean 22/09/2011 : "Basculer en mode "chat live""
                           (!this.options.modeLive && this.options.type == 'event' ?
                               '<a href="chat_live.php?event_id='+ this.options.typeID +'">'
                             + '<img src="./images/icons/chat-live_noir-et-blanc_16.png" align="absmiddle" border="0" class="menu_icon2" style="opacity: 0.70; filter: alpha(opacity=70); margin-right: 10px;" title="'+ this.Base.Language.Translate(3511745).replace(/\"/g, '&#34;') +'" /></a>'
                            : '')

                         + '<a href="javascript:;" onclick="$(\''+ this.options.type +'_'+ this.options.typeID +'_comments\').innerHTML = \'<img src=\\\'images/icons/loading2.gif\\\' border=0 />\'; setTimeout(\'window.parent.getComments(null, \\\''+ this.options.type +'\\\', 1);\');">'
                         + '<img src="./images/icons/reload.png" align="absmiddle" border="0" class="menu_icon2" style="opacity: 0.70; filter: alpha(opacity=70);" title="'+ this.Base.Language.Translate(3511440) +'" /></a>';

     // Jean 21/09/2011
     if ($(this.options.type +'_'+ this.options.typeID +'_refreshcomments'))
       $(this.options.type +'_'+ this.options.typeID +'_refreshcomments').innerHTML = this.btnRefreshHtml;

     if (!onlyInjectNewComments)
       g.innerHTML = "<div class='comment_headline' style='"+ (parent.objTournage ? 'font-weight: bold; ' : '') +"width: "+ (this.options.widthComments ? this.options.widthComments - 60 : 618) +"px; display: none;' id='"+this.options.type+"_"+this.options.typeID+"_zone_comments'>"
                   + '<div style="float: right;">'+ this.btnRefreshHtml +'</div>'
                   // "Commentaires pour nous aider à préparer ce sujet en amont" / "Commentaires"
                   + this.Base.Language.Translate(parent.objTournage ? 3511360 : 854)
                   + " (<span class='tc' id='"+this.options.type+"_"+this.options.typeID+"_totalcomments'>"+ this.total +"</span>)"
                   + (this.options.htmlInHeader ? this.options.htmlInHeader : '')
                   + "</div>";

     var h_comment_header = $(this.options.type+"_"+this.options.typeID+"_zone_comments");

     var h_new_container = $(this.options.type+"_"+this.options.typeID+"_new_comment");

    // Jean 14/04/2010
     if (!h_new_container)
      {
       this.showPostComment();
       var h_new_container = $(this.options.type+"_"+this.options.typeID+"_new_comment");
      }

// Jean 21/07/2009 "Et toc, je suis le premier à donner mon commentaire :" / <libellé perso>
     if (!this.options.modeLive)
      {
       if (this.options.canComment)
         h_new_container.innerHTML = (this.options.firstCommentTitle ? this.options.firstCommentTitle : this.Base.Language.Translate(3000684))
                                   + '<div style="float: right;">'+ this.btnRefreshHtml +'</div>';
       else
         h_new_container.style.display = 'none';
      }

     var h = $(this.options.type+"_"+this.options.typeID+"_totalcomments");
     //var h_new=$(this.options.type+"_"+this.options.typeID+"_totalcomments_post");
     if (h)
       h.innerHTML = this.total;

     var l=this;
     if(l.Base.Core.settings.setting_url)
      {var e="?"}
     else
      {var e="&"}

     this.totalLastInjectedComments = 0;
     var lastCommentIsLive = false;
     var lastCommentIsMine = false;
     var scrollDiv = $(l.options.type +"_"+ l.options.typeID +"_comments");
     var jeSuisRemonteDansLeScroll = false;

     k.each(function(o,q){

       l.totalInjectedComments ++;
       l.totalLastInjectedComments ++;

       // Jean 14/04/2010 : On décode l'identifiant (on l'avait passé en string de manière à ce que le tri sur les commentaires tienne compte des sous-commentaires)
       init_q = q;

       q = q.replace(/^id_/, '');
       var isSubComment;

       if (l.cptComment)
         l.cptComment ++;
       else
         l.cptComment = 1;

       if (isSubComment = q.match(/^([0-9]+)_([0-9]+)_([0-9]+)$/))
         q = isSubComment[3];
       else { last_ref_comment_id = q; }; // Jean 11/2010

       // Jean 22/09/2011 : pour éviter d'afficher 2 fois le même commentaire
       if ( !(l.options.modeLive && l.dicoCommentIds[q]) )
        {
         l.dicoCommentIds[q] = 1;

         var isParentComment = init_q.match(/^id_/) && !isSubComment;
         // Jean 14/04/2010

         if (!l.options.modeLive)
           h_comment_header.style.display = 'block';
         h_new_container.innerHTML = l.Base.Language.Translate(700025) + (l.options.htmlInHeader ? l.options.htmlInHeader : '');

         var r=new Element("div",{id:"comment_"+q});
         var titreSection = "";
         var pasPremiereSection = false;

         // Jean 21/09/2011 : pour séparer les commentaires d avant le live et pendant le live
         if (!lastCommentIsLive && !onlyInjectNewComments && o.comment_live)
          {
           // "À partir d'ici démarre une conversation LIVE :"
           if (!l.options.noSectionHeaders)
             titreSection = l.Base.Language.Translate(3511741);
          }

         else if (lastCommentIsLive && !o.comment_live)
          {
           // "Suite au live :"
           if (!l.options.noSectionHeaders)
             titreSection = l.Base.Language.Translate(3511742);
          }

         // Jean 28/03/2011 : pour séparer les commentaires d avant la livraison de la vidéo et ceux d après la livraison de la vidéo
         else if (l.options.separ_date)
          {
           // Si la vidéo a été livrée après le premier commentaire, alors on affichera comme titre de la première section :
           // "Conversations préparatoires AVANT mise en ligne de la vidéo :"
           if (l.cptComment == 1 && o.comment_date_timestamp <= l.options.separ_date && !l.alreadyDrawedSeparLine)
             titreSection = l.Base.Language.TranslateFormatted(3511235, [getDateStr(l.options.separ_date*1000), getHourStr(l.options.separ_date*1000)]);

           // Si la vidéo a été livrée après le premier commentaire, alors on affichera après la première section le titre suivant :
           else if (o.comment_date_timestamp > l.options.separ_date && !l.alreadyDrawedSeparLine)
            {
             if (l.cptComment > 1)
               // "Discussion après publication de la vidéo :"
               titreSection = l.Base.Language.TranslateFormatted(3511227, [getDateStr(l.options.separ_date*1000), getHourStr(l.options.separ_date*1000)]);
             pasPremiereSection = true;
             l.alreadyDrawedSeparLine = true;
            }
          }
         else
          titreSection = '';

        var s = "";

        if (titreSection)
         {
          s += "<table border='0' cellpadding='0' cellspacing='0' class='comments_section_separ"+ (pasPremiereSection ? " comment_delivered_autre_section_separ" : "") +"'><tr><td>"
               +"<span>&nbsp; "+ titreSection +" &nbsp;</span>"
               +"</td></tr></table>";
         }

         s += "<div class='comment_block_container"+ (o.comment_live ? ' comment_block_container_live' : '') +"' style='"+ (isSubComment ? "margin-left: 22px;" : "") +"'>";

         // Jean 14/04/2010
         if (isSubComment)
           s += "<div style='float: left; text-align: center; width: 40px;'><img src='./images/sub_comment.png' /></div>";

         if (!o.comment_live)
          {
           if (o.comment_authoruser_id && o.comment_authoruser_exists)
             s += "<div style='float: left; text-align: center; width: 65px;'><a href='"+o.comment_authoruser_url+"' "+ o.comment_authoruser_infobulle_url +"><img src='"+o.comment_authoruser_photo+"' class='photo'"+ (o.comment_authoruser_photo_width == 0 ? " width='60' height='60'" : " width='"+ o.comment_authoruser_photo_width +"'") +" border='0'></a></div>"
           else
             s += "<div style='float: left; text-align: center; width: 65px;'><img src='./images/nophoto.gif' class='photo' width='60' border='0'></div>"
          }

         s += '<div id="comment_block_'+ q +'"'
                 +' style="overflow: hidden;"'
                 +' class="comment_block'
                         + (o.comment_live ? ' comment_block_live' : '')
                         // Jean 26/11/2011
                         + (!o.comment_approved && l.Base.Viewer.user_info.user_id != o.comment_authoruser_id ? ' comment_block_draft' : '') +'"';
         // En mode "live", on ne fait apparaître les boutons d'action sur un commentaire que lorsque la souris passe par-dessus
         if (o.comment_live)
          {
           s += ' onmouseover="if (!self.isEditingComment) { var t = this; this.getElements(\'.commentLinks_live\').each(function(node) { if (!t.hasClass(\'comment_block_draft\')) t.addClass(\'comment_block_over\'); node.style.display = \'block\'; });}"';
           s += ' onmouseout="var t = this; this.getElements(\'.commentLinks_live\').each(function(node) { t.removeClass(\'comment_block_over\'); node.style.display = \'none\'; });"';
          }
         s += '>';

        //--------------------------------------------------------------------------
        // On affiche le bloc commentaire
        //--------------------------------------------------------------------------
         var author_disp_name = '';

         if (!o.comment_authoruser_id)
          {
           author_disp_name = "<b>"+l.Base.Language.Translate(835)+"</b>"
          }
         else
          {
           // Jean 11/04/2011 : petite modif pour pouvoir afficher le nom des users supprimés
           if(!o.comment_authoruser_exists && !(o.comment_authoruser_displayname && o.comment_authoruser_displayname != '')){
             // "[Utilisateur supprimé]"
             author_disp_name ="<b>"+ l.Base.Language.Translate(1071) +"</b>"
           // Jean 11/04/2011
           }else if (!o.comment_authoruser_exists){
             author_disp_name =o.comment_authoruser_displayname + (i_am_CM ? ' &nbsp; <small><font class="com_manager">'+ l.Base.Language.Translate(1071) +"</font></small>" : '') +""
           }else{
             author_disp_name ="<a href='"+o.comment_authoruser_url+"' ";
             author_disp_name += o.comment_authoruser_infobulle_url;
             author_disp_name += (l.options.fontWidth ? " style='font-size: "+ l.options.fontWidth +"px;'" : "");

             // On détermine une couleur différente par chateur
             if (o.comment_live)
              {
               if (!l.dicoColorByUser['uz_'+ o.comment_authoruser_id])
                {
                 l.dicoColorByUser['uz_'+ o.comment_authoruser_id] = l.dicoColors[l.dicoColorCursor % l.dicoColors.length];
                 l.dicoColorCursor ++;
                }
               comment_auth_color = l.dicoColorByUser['uz_'+ o.comment_authoruser_id];
               author_disp_name += ' style="'+ (comment_auth_color ? 'color: '+ comment_auth_color +';' : '') +'"';
              }
             author_disp_name += ">";
             author_disp_name += "<b>"+o.comment_authoruser_displayname+"</b></a>";
             author_disp_name += (o.comment_main_webtv ? ' &nbsp; <font class="comment_origin">'+ o.comment_main_webtv +'</font>' : '');

             // Jean 29/11/2011 : "commentaire en attente de modération"
             if (!o.comment_approved && l.Base.Viewer.user_info.user_id != o.comment_authoruser_id)
               author_disp_name += ' &nbsp; <font id="comment_wait_moderation_'+ q +'" class="comment_origin" style="font-size: 11px;">('+ l.Base.Language.Translate(3511944) +')';
           }
         }

        var commentLinksHtml = "<div class='profile_comment_links"+ (o.comment_live ? '_live' : '') +"'>";

        var p = new Array();

        var jeSuisUnChef = !isExtranet && i_am_CM || isExtranet && i_am_rdc;

        if (l.Base.Viewer.user_exists && o.comment_authoruser_id && o.comment_authoruser_exists || jeSuisUnChef)
         {
          // "répondre"
          if (l.options.commentLinks.reply && l.Base.Viewer.user_info.user_id==l.Base.Owner.user_info.user_id && l.Base.Viewer.user_info.user_id != o.comment_authoruser_id)
            p.push("<a class='commentReplyLink' href='"+o.comment_authoruser_url+e+"v=comments' "+ o.comment_authoruser_infobulle_url +">"+l.Base.Language.Translate(787)+"</a>")

          // Jean 04/07/2010 : on conditionne la possiblilité de modifier ou supprimer son commentaire par le fait qu'il date de moins de 2 heures
          var isFreshComment = new Date().getTime() - o.comment_date_timestamp*1000 < 2*60*60*1000;

          // Jean 25/11/2011 : "Accepter"
          if (!o.comment_approved && l.options.iAmAdmin)
           {
            // "Accepter"
            p.push('<a id="commentAcceptLink_'+ q +'" class="commentAcceptLink com_manager" href="javascript:void(0);">'+ l.Base.Language.Translate(3511935) +"</a> ")
            // "Rejeter"
            p.push('<a id="commentRejectLink_'+ q +'" class="commentRejectLink com_manager" href="javascript:void(0);">'+ l.Base.Language.Translate(3511936) +"</a>")
           }

          // Lien "Éditer"
          if((o.comment_authoruser_id == l.Base.Viewer.user_info.user_id || jeSuisUnChef)
            && (isFreshComment || jeSuisUnChef)
           ){
            p.push('<a class="commentEditLink' + (o.comment_authoruser_id != l.Base.Viewer.user_info.user_id || !isFreshComment ? " com_manager" : "") +'" href="javascript:void(0);">'+ l.Base.Language.Translate(187) +"</a>")}}

          // Lien "Effacer"
          if (     (o.comment_authoruser_exists && o.comment_authoruser_id == l.Base.Viewer.user_info.user_id && isFreshComment)
               || (l.Base.Viewer.user_exists && l.Base.Viewer.user_info.user_id == l.Base.Owner.user_info.user_id)
               || jeSuisUnChef
           ){
            p.push('<a class="commentDeleteLink' + (o.comment_authoruser_id != l.Base.Viewer.user_info.user_id || !isFreshComment ? " com_manager" : "") +'" href="javascript:void(0);">'+ l.Base.Language.Translate(155) +"</a>")}

          // Jean 11/2010 : lien "répondre à ce commentaire" si le commentaire en question est déjà de niveau 1 (on reste donc dans la même hiérarchie)
          if (l.options.canComment && !l.options.modeLive/* && !o.comment_live*/)
           {
            var ref_comment_id;
            ref_comment_id = last_ref_comment_id;
            p.push("<a class='commentReplyLink' href=\"javascript:;\""
                    +" onclick=\"var zonePostReply = $('"+ l.options.type +"_"+ l.options.typeID +"_"+ ref_comment_id +"_replycomment');"
                              + (!isParentComment ? "zonePostReply = $('"+ l.options.type +"_"+ l.options.typeID +"_"+ q +"_replycomment');" : "")
                              +" if (zonePostReply.innerHTML == '') tabObjComments['"+ l.options.type +"'].showPostComment(zonePostReply, "+ ref_comment_id + ", '"+ o.comment_authoruser_displayname.replace(/(\'|&#039;)/g, "\\'") +"'"+ (!isParentComment ? ", '"+ q +"', '"+ o.comment_authoruser_id +"'" : "") +");"
                              +" else tabObjComments['"+ l.options.type +"'].showPostComment();"
                              +"\">"
                              // Jean 15/12/2010 : "Répondre à la suite de ce fil"
                              + (!isParentComment ? l.Base.Language.Translate(3510843) : l.Base.Language.Translate(3510414))
                             +"</a>");
           }

          // Lien "l'inviter sur ce tournage" (lien accessible aux seuls contributeurs et CM)
          if(o.comment_authoruser_exists && l.Base.Viewer.user_exists && l.Base.Viewer.user_info.user_id != l.Base.Owner.user_info.user_id
              && (l.Base.Viewer.user_info.user_level_id=="1" || jeSuisUnChef)
              && parent.objTournage && parent.objTournage.guests_and_speakers && parent.objTournage.guests_and_speakers.indexOf('#'+ o.comment_authoruser_id +'#') == -1
              && !l.options.modeLive
              )
            p.push('<a class="commentInviteLink" onclick="parent.SocialEngine.Event.oneMemberInviteSend('+ o.comment_authoruser_id +');" href="javascript:void(0);">'+l.Base.Language.Translate(3510054)+"</a>")

          // Jean 03/03/2011
          commentLinksHtml += '<img src="images/icons/loading2.gif" id="img_loading_comment_get_content_'+ q +'" style="display: none;" border="0" />';

          commentLinksHtml += p.join("&nbsp;<font class='commentSeparLinks'>|&nbsp;</font>&nbsp;");

          commentLinksHtml += "&nbsp;</div>";

          // Jean 14/04/2010 - Zone cible du lien "Répondre à ce commentaire"
          if(l.options.canComment)
            commentLinksHtml +='<div id="'+ l.options.type +'_'+ l.options.typeID +'_'+ q +'_replycomment"></div>';

        // Jean 21/09/2011 : si le commentaire courant a été posté en mode "chat live", alors on l'affiche dans un mode simplifié
        if (!o.comment_live)
         {
          author_disp_name = '<div class="profile_comment_author">'+ author_disp_name +'</div>';
          s += author_disp_name;
          s += "<div class='profile_comment_date'"+ (l.options.fontWidth ? " style='font-size: "+ l.options.fontWidth +"px;'" : "") +">"+ o.comment_date +"</div>";
         }

        r.setProperty("html",o.comment_body);
        var comment_body = "<div class='profile_comment_body"+ (o.comment_live ? '_live' : '') +"' id='profile_comment_body_"+q+"' style='"+ (o.comment_live ? 'padding-bottom: 0px;' : '') + (l.options.fontWidth ? "font-size: "+ l.options.fontWidth +"px;" : "") +"'>"+ o.comment_body +"&nbsp;</div>";

        if (!o.comment_live)
          s += comment_body + commentLinksHtml;

        //--------------------------------------------------------------------------
        // On affiche le bloc commentaire
        //--------------------------------------------------------------------------
        if (o.comment_live)
         {
          s += '<table border="0" cellspacing="0" cellpadding="0" class="profile_comment_live">';
          s += '<tr>';

          // nom du commentateur
          s += '<td class="profile_comment_author_live">';

          // liens "éditer" / "effacer" sur la droite
          if (p.length > 0)
            s += '<div id="comment_links_'+ q +'" class="commentLinks_live">'+ commentLinksHtml +'</div>';

          s += author_disp_name +' :';

          s += '</td>';

          // date du commentaire
          s += '<td class="profile_comment_date_live">'+ o.comment_date.replace(/ /g, '&nbsp;');
          //s += ' / '+ parseInt(q,10);
          s += '</td>';

          s += '</tr>';
          s += '<tr>';

          // corps du commentaire
          s += '<td colspan="2" class="profile_comment_body_live">';
          s += comment_body;
          s += '</td>';

          s += '</tr>';
          s += '</table>';
         }

        s += '</div></div>';

//var tab1 = s.match(/(<div)/gi); var tab2 = s.match(/(<\/div)/gi); alert(tab1.length +' / '+ tab2.length);

        if (SocialEngineAPI.Comments.lastCommentId)
          SocialEngineAPI.Comments.lastCommentId = Math.max(SocialEngineAPI.Comments.lastCommentId, parseInt(q,10));
        else
          SocialEngineAPI.Comments.lastCommentId = parseInt(q,10);

        // On vérifie si on a scrollé vers le haut dans le flux de commentaires live
        if (l.options.modeLive && J(scrollDiv).attr("scrollTop") + scrollDiv.offsetHeight < J(scrollDiv).attr("scrollHeight") - 100)
          jeSuisRemonteDansLeScroll = true;

        // Jean 19/09/2011 : on injecte le code HTML du commentaire courant dans le flux de commentaires
        r.setProperty("html",s);
        r.inject(g);

        // Jean 21/09/2011
        lastCommentIsLive = o.comment_live;
        lastCommentIsMine = (l.Base.Viewer.user_info.user_id == o.comment_authoruser_id);

        if(r.getElement(".commentEditLink")){r.getElement(".commentEditLink").addEvent("click",function(){l.editComment(q)})}
        if(r.getElement(".commentDeleteLink")){r.getElement(".commentDeleteLink").addEvent("click",function(){l.confirmDelete(q, l.options.type)})}
        if(r.getElement(".commentAcceptLink")){r.getElement(".commentAcceptLink").addEvent("click",function(){l.moderate(l.options.type, q, 1)})}
        if(r.getElement(".commentRejectLink")){r.getElement(".commentRejectLink").addEvent("click",function(){l.moderate(l.options.type, q, 0)})}
       }
     });
     // -- fin parcours commentaires

     // Si aucun commentaire dans le flux, alors on efface l'éventuelle image de chargement
     if (this.totalInjectedComments == 0)
       scrollDiv.innerHTML = '';

     // Jean 10/10/2011
     if (this.options.modeLive)
      {
       if ($('zone_total_livecomments_container'))
         $('zone_total_livecomments_container').setStyle('display', this.totalInjectedComments > 0 ? '' : 'none');
       if ($('zone_total_livecomments'))
         $('zone_total_livecomments').innerHTML = this.totalInjectedComments;

       // En mode chat live, on repositionne le focus sur la zone de saisie pour être prêt à envoyer un nouveau commentaire
       if (this.totalLastInjectedComments && lastCommentIsMine)
         setTimeout("$('comment_body_"+ this.options.type +"').focus();", 100);
      }

     if(this.options.paginate&&this.total>this.options.cpp){var i=new Element("div",{styles:{"text-align":"center"}});var j=new Element("div",{styles:{"text-align":"center"}});if(this.page>1){var d="<a href='javascript:void(0);' id='comment_last_page_top'>&#171; "+l.Base.Language.Translate(182)+"</a>";var c="<a href='javascript:void(0);' id='comment_last_page_bottom'>&#171; "+l.Base.Language.Translate(182)+"</a>"}else{var d="<font class='disabled'>&#171; "+l.Base.Language.Translate(182)+"</font>";var c="<font class='disabled'>&#171; "+l.Base.Language.Translate(182)+"</font>"}if(n==m){d+="&nbsp;|&nbsp; "+this.Base.Language.TranslateFormatted(184,[n,this.total])+"&nbsp;|&nbsp;";c+="&nbsp;|&nbsp; "+this.Base.Language.TranslateFormatted(184,[n,this.total])+"&nbsp;|&nbsp;"}else{d+="&nbsp;|&nbsp; "+this.Base.Language.TranslateFormatted(185,[n,m,this.total])+"&nbsp;|&nbsp;";c+="&nbsp;|&nbsp; "+this.Base.Language.TranslateFormatted(185,[n,m,this.total])+"&nbsp;|&nbsp;"}if(this.page!=a){d+="<a href='javascript:void(0);' id='comment_next_page_top'>"+l.Base.Language.Translate(183)+" &#187;</a>";c+="<a href='javascript:void(0);' id='comment_next_page_bottom'>"+l.Base.Language.Translate(183)+" &#187;</a>"}else{d+="<font class='disabled'>"+l.Base.Language.Translate(183)+" &#187;</font>";c+="<font class='disabled'>"+l.Base.Language.Translate(183)+" &#187;</font>"}i.setProperty("html",d);j.setProperty("html",c);i.inject(g,"top");j.inject(g);if(i.getElement("a[id=comment_last_page_top]")){i.getElement("a[id=comment_last_page_top]").addEvent("click",function(){l.getComments("previous")})}if(j.getElement("a[id=comment_last_page_bottom]")){j.getElement("a[id=comment_last_page_bottom]").addEvent("click",function(){l.getComments("previous")})}if(i.getElement("a[id=comment_next_page_top]")){i.getElement("a[id=comment_next_page_top]").addEvent("click",function(){l.getComments("next")})}if(j.getElement("a[id=comment_next_page_bottom]")){j.getElement("a[id=comment_next_page_bottom]").addEvent("click",function(){l.getComments("next")})}}

     // Jean 19/09/2011 : en mode "chat live"
     if (this.options.modeLive && (this.totalLastInjectedComments > 0 || mustRefreshLiveComments))
       this.redimChatLive();

     if (this.options.modeLive && this.totalLastInjectedComments > 0)
      {
       // On déclenche un son pour avertir des nouveaux messages (autres que les miens)
       if (this.options.newLiveCommentsAreNoisy && $(this.options.type + '_comments_sound') && onlyInjectNewComments && this.totalLastInjectedComments > 0 && !lastCommentIsMine)
        {
         $(this.options.type +'_comments_sound').empty();
         $(this.options.type +'_comments_sound').innerHTML = '<object data="/'+ subdir +'images/icons/chat_sound.swf" type="application/x-shockwave-flash" width="1" height="1" style="visibility:hidden"><param name="movie" value="/'+ subdir +'images/icons/chat_sound.swf" /><param name="menu" value="false" /><param name="quality" value="high" /></object>';
         setTimeout("$('"+ this.options.type +"_comments_sound').empty();", 2000);
        }

       // On scroll automatiquement tout en bas
       // (et on ne déclenche l'autoscroll que si le scroll est déjà descendu (pour éviter de gêner ceux qui veulent remonter dans le fil de commentaires)
       if (this.nbAutoScrolls == 0 || !(jeSuisRemonteDansLeScroll && onlyInjectNewComments))
         this.autoScrollChatLive();
      }
   },

  autoScrollChatLive: function(noAnimation)
   {
    var scrollDiv = $(this.options.type +"_"+ this.options.typeID +"_comments");

    // On descend au maximum
    J(scrollDiv).attr({ scrollTop: J(scrollDiv).attr("scrollHeight") + 1000 });
    if (!noAnimation)
     {
      // On remonte de 70 px vers le haut
      J(scrollDiv).attr({ scrollTop: Math.max(0, J(scrollDiv).attr("scrollTop") - 70) });
      // On lance le scroll auto sur les derniers pixels (pour l'effet visuel)
      J(scrollDiv).animate({ scrollTop: J(scrollDiv).attr("scrollHeight") }, 1500);
     }
    this.nbAutoScrolls ++;
   },

  redimChatLiveTO: null,
  redimChatLive: function()
   {
    clearTimeout(this.redimChatLiveTO);
    this.redimChatLiveTO = setTimeout('SocialEngine.EventComments.redimChatLive_suite();', 100);
   },
  redimChatLive_suite: function()
   {
    var commentsArea = $(this.options.type +"_"+ this.options.typeID +"_comments");
    commentsArea.style.height = 'auto';

    var hauteurDoc = typeof( window.innerWidth ) == 'number' ? window.innerHeight : document.documentElement.clientHeight;
    if (hauteurDoc == 0)
      hauteurDoc = document.documentElement.offsetHeight;
    this.maxChatLiveHeight = 310;
    this.minChatLiveHeight = 150;
    var videoHeight = this.options.videoHeight ?
                         this.options.videoHeight
                       : ($('event_video') ? $('event_video').offsetHeight : 0);
    commentsArea.style.height = Math.min(this.maxChatLiveHeight,
                                         Math.max(this.minChatLiveHeight,
                                                  hauteurDoc - videoHeight - (isIE ? 110 : 90)
                                                - (this.options.marge ? this.options.marge : 0))
                                 )+'px';

    commentsArea.style.height = Math.max(commentsArea.offsetHeight,
                                           document.body.clientHeight
                                         - (getTop(commentsArea) - document.body.scrollTop)
                                         - 65
                                         - ($('comment_body_'+ this.options.type) ? $('comment_body_'+ this.options.type).offsetHeight : 0));

    // On calcule la hauteur interne de la zone scrollable
    var commentsContentTotalHeight = 0;
    J(commentsArea).children().each(function() {
      commentsContentTotalHeight += J($(this)).height();
    });
    commentsContentTotalHeight += 50;
    if (commentsContentTotalHeight < commentsArea.offsetHeight)
      commentsArea.style.height = commentsContentTotalHeight;

    this.autoScrollChatLive(true);
   },


  nbAutoScrolls: 0,

  addComment:function(c,a,b,mustRefreshLiveComments){

    if(!this.options.canComment){return false}

    if(c){
      $("comment_error_"+ this.options.type).style.display="block";

      if(!a.trim()){this.addText($("comment_body_"+ this.options.type));
      // "Veuillez entrer un message."
      $("comment_error_"+ this.options.type).innerHTML=this.Base.Language.Translate(831)}
      else{$("comment_error_"+ this.options.type).innerHTML=this.Base.Language.Translate(832)}

      $("comment_submit_"+ this.options.type).value=this.Base.Language.Translate(833);
      $("comment_submit_"+ this.options.type).disabled=false
     }
    else
     {
      $("comment_error_"+ this.options.type).style.display="none";
      $("comment_error_"+ this.options.type).innerHTML="";
      $("comment_body_"+ this.options.type).value="";

      // Jean 22/09/2011
      if (this.options.modeWYSIWYG && tinyMCE.get("comment_body_"+ this.options.type))
        tinyMCE.get("comment_body_"+ this.options.type).remove();

      $("comment_body_"+ this.options.type).style.height=this.options.originalHeight+"px";
      this.addText($("comment_body_"+ this.options.type));
      $("comment_submit_"+ this.options.type).value=this.Base.Language.Translate(833);
      $("comment_submit_"+ this.options.type).disabled=false;
      if($("comment_secure_"+ this.options.type)){$("comment_secure_"+ this.options.type).value="";
      $("secure_image_"+ this.options.type).src=$("secure_image_"+ this.options.type).src+"?"+(new Date()).getTime()}this.page=1;
      this.total++;

      // Jean 21/09/2011 : on fait disparaître les champs d'inscription express dès que le premier commentaire est posté
      if ($("express_account_fields_"+ this.options.type))
        $("express_account_fields_"+ this.options.type).style.display = 'none';

      this.getComments(null, mustRefreshLiveComments);
    }
   },

   editComment:function(c){

     // Jean 22/09/2011 - on cache les éventuels liens flottants
     if ($('comment_links_'+ c))
       $('comment_links_'+ c).style.display = 'none';
     self.isEditingComment = true;

     // Jean 03/03/2011
     if (this.options.type == 'event')
       getCommentBody(c);
     else
       this.editCommentDirect(c);
   },

   editCommentDirect:function(c){
        var f=this;
        if(this.isEditing){return false}this.isEditing=true;var b=$("profile_comment_body_"+c);var a=b.offsetHeight+10;

        var d = b.innerHTML.replace(/<br>/gi,"\r\n");

        // Jean 01/03/2011 : pour éviter les liens "mailto" démultipliés à l'infini
        var texteInit = d.replace(/<a href=\"mailto:([^\"]+\@[^\"]+)\">([^\"]+\@[^\"]+)<\/a>/g, "$2");

        d = d.replace(/>/gi,"&gt;");

        var e="";

        e+="<form action='misc_js.php' method='post' target='ajaxframe' name='editCommentForm'>";

        // Jean 01/03/2011 : on retire les balises <a> sans utilité
        e+="<textarea name='comment_edit' id='comment_edit_"+ this.options.type +"_"+ c +"' style='height: "+ a +" px; width: 100%;'>"+ texteInit +"</textarea>";

        e+="<input type='hidden' name='task' value='comment_edit'>";e+="<input type='hidden' name='comment_id' value='"+c+"'>";
        e+="<input type='hidden' name='type' value='"+this.options.type+"'>";
        e+="<input type='hidden' name='iden' value='"+this.options.typeIdentifier+"'>";
        e+="<input type='hidden' name='value' value='"+this.options.typeID+"'>";

        if(this.options.typeTab){e+='<input type="hidden" name="tab" value="'+this.options.typeTab+'">'}
        if(this.options.typeCol){e+='<input type="hidden" name="col" value="'+this.options.typeCol+'">'}
        if(this.options.typeTabParent){e+='<input type="hidden" name="tab_parent" value="'+this.options.typeTabParent+'">'}
        if(this.options.typeColParent){e+='<input type="hidden" name="col_parent" value="'+this.options.typeColParent+'">'}
        if(this.options.typeChild){e+='<input type="hidden" name="child" value="1">'}

        e+="</form>";

        b.innerHTML=e;

        //initWYSIWYG('comment_edit_'+ this.options.type +"_"+ c, 'simple');
        textarea_autogrow("comment_edit_"+ this.options.type +"_"+ c);

        $("comment_edit_"+ this.options.type +"_"+ c).focus();
        // quand la souris quitte la zone de saisie, il faut déclencher la modif du commentaire et faire disparaître la zone de saisie
        $("comment_edit_"+ this.options.type +"_"+ c).addEvent("blur",
           function(){
             document.editCommentForm.submit();
             f.isEditing=false;
             self.isEditingComment = false;
        });
  },

  confirmDelete:function(a, comment_type){

        $("del_comment_id_"+ comment_type).value = a;

        TB_show(this.Base.Language.Translate(1025),"#TB_inline?height=100&width=300&inlineId=confirmcommentdelete_"+ comment_type,"","../images/trans.gif");

        // Jean 03/03/2010
        if ($('btn_valid_delete_comment_'+ comment_type)) $('btn_valid_delete_comment_'+ comment_type).focus();
        },

  // Jean 26/11/2011 : accepte un commentaire dans un fil de chat live où les commentaires sont modérés
  moderate:function(comment_type, comment_id, comment_approved){

      var first_draft_comment_id = null;
      document.body.getElements('.comment_block').each(function(node) {
        if ((node.hasClass('comment_block_draft') || node.hasClass('comment_block_rejected'))
           && first_draft_comment_id == null)
          first_draft_comment_id = node.id.replace(/^.*_([0-9]+)$/, "$1");
      });

      if (comment_id != first_draft_comment_id && comment_approved)
       {
        // "Attention : pour respecter la chronologie, merci de bien vouloir modérer en priorité les premiers commentaires saisis dans le flux live."
        //alert(this.Base.Language.Translate(3511937));
        //return;
       }

      if (comment_approved)
        $('commentAcceptLink_'+ comment_id).style.display = 'none';
      else
        $('commentRejectLink_'+ comment_id).style.display = 'none';

      // Ajax
      var request = new Request.JSON({
        'method' : 'post',
        'url' : 'misc_js.php',
        'data' : {
          'task' : 'comment_moderation',
          'comment_type' : comment_type,
          'comment_id' : comment_id,
          'comment_approved' : comment_approved
        },
        'onComplete':function(responseObject)
         {
          $('comment_block_'+ comment_id).removeClass('comment_block_draft');
          $('comment_block_'+ comment_id).removeClass('comment_block_rejected');
          if (comment_approved)
            $('comment_wait_moderation_'+ comment_id).style.display = 'none';
          else
            $('comment_block_'+ comment_id).addClass('comment_block_rejected');
         }
      });

   request.send();
  },

  removeText:function(a){if(!this.changed){a.value="";a.style.color="#000000";this.changed=true}},

  addText:function(a){if(!a.value.trim()){a.value=this.Base.Language.Translate(829);a.style.color="#888888";this.changed=false}},

  checkText:function(a){

      if(!this.changed){
        $("comment_body_"+ this.options.type).value="";
      }
      // Veuillez patientez...
      $("comment_submit_"+ this.options.type).value=this.Base.Language.Translate(830);
      $("comment_submit_"+ this.options.type).disabled=true;
   }
  });


  SocialEngineAPI.Core=new Class({Base:{},settings:{},plugins:{},options:{ajaxURL:"js_api.php"},initialize:function(){},ImportSettings:function(a){this.settings=a},ImportPlugins:function(a){this.plugins=a}});if(typeof(SocialEngineAPI)=="undefined"){var SocialEngineAPI={}}SocialEngineAPI.Language=new Class({Base:{},initialize:function(){this.languageVariables=new Hash()},Translate:function(b){var a=this.languageVariables.get(b)||"Missing Language Variable #"+b;return a},TranslateFormatted:function(d,c){var b=this.languageVariables.get(d)||"Missing Language Variable #"+d;c.unshift(b);var a=sprintf.run(c);return a},Import:function(a){if($type(a)=="object"){this.languageVariables.extend(a)}}});var SocialEngineLanguage=SocialEngineAPI.Language;SocialEngineAPI.Tags=new Class({Implements:[Options],Base:{},isTagging:false,newtag:false,tags:[],options:{ajaxURL:"misc_js.php",ajaxMethod:"post",ajaxSecure:false,canTag:false,type:false,media_id:false,media_dir:false,object_owner:false,object_owner_id:false},initialize:function(a){this.setOptions(a);if(this.options.initialTotal){this.total=this.options.initialTotal}var b=this;window.addEvent("domready",function(){b.showTagForm()})},showTagForm:function(){var e="";var d=this;if(this.options.canTag){e+="<div class='media_photo_tagform_titlebar'><img src='images/icons/photos16.gif' class='icon' />"+this.Base.Language.Translate(1212)+"</div><div style='padding: 7px;'><div style='text-align: left;'><div style='font-size: 7pt; margin-bottom: 5px;'>"+this.Base.Language.Translate(1213)+"</div><div style='text-align: center;'><input type='text' style='width: 130px; padding-left: 4px; font-size: 8pt;' name='media_photo_tag' id='media_photo_tag' class='text' maxlength='40'/></div></div><div id='media_photo_friendlist' class='media_photo_friendlist'>";if(d.Base.Viewer.user_exists){e+="<div><a href='javascript:void(0)' id='tag_me'>"+d.Base.Viewer.user_displayname+d.Base.Language.Translate(1214)+"</a></div>"}e+="</div><div><input type='button' class='button' name='save' id='tag_save' value='"+d.Base.Language.Translate(1215)+"' />&nbsp;&nbsp;<input type='button' class='button' id='tag_cancel' name='cancel' value='"+d.Base.Language.Translate(39)+"' /></div></div>";
        var a=new Element("div",{id:"media_photo_tagform","class":"media_photo_tagform",html:e});
        var c=$("media_photo_div");
        a.inject(c);
        if(a.getElement("input[id=tag_cancel]")){a.getElement("input[id=tag_cancel]").addEvent("click",function(){d.cancelTag()})}if(a.getElement("input[id=tag_save]")){a.getElement("input[id=tag_save]").addEvent("click",function(){d.saveTag(0)})}if(a.getElement("a[id=tag_me]")){a.getElement("a[id=tag_me]").addEvent("click",function(){d.saveTag(d.Base.Viewer.user_info.user_id)})}var b=new Request.JSON({secure:false,url:"misc_js.php?task=friends_all",onComplete:function(f){d.addFriendToList(f.friends)}}).send()}},addFriendToList:function(a){var b=this;a.each(function(f){for(var c in f){var e=new Element("div",{id:"friend_div_"+c});var d=new Element("a",{href:"javascript:void(0)",id:"friend_link_"+c,html:f[c]}).inject(e);e.inject($("media_photo_friendlist"));$("friend_link_"+c).addEvent("click",function(){b.saveTag(c)})}})},insertTag:function(a,l,m,j,h,k,i,c){var f="";var g=this;if($("media_tags").style.display=="none"){$("media_tags").style.display="block"}else{if(g.tags.length!=0){f='<span id="tag_comma_'+a+'">, </span>'}}var d=new Element("span",{id:"full_tag_"+a,html:f});if(l!=""){var e=new Element("a",{href:l,id:"tag_link_"+a,html:m}).inject(d)}else{var e=new Element("span",{id:"tag_link_"+a,html:m,styles:{cursor:"pointer"}}).inject(d)}if(g.Base.Viewer.user_exists&&(g.Base.Viewer.user_info.user_username==c||g.Base.Viewer.user_info.user_username==g.Base.Owner.user_info.user_username)){var b=$(d).get("html");$(d).set("html",b," (<a href='javascript:void(0);' id='new_removetag_link'>"+g.Base.Language.Translate(1228)+"</a>)")}d.inject($("media_tags"));g.createTag(a,m,j,h,k,i);$("tag_link_"+a).addEvent("mouseover",function(){g.showTag(a)});$("tag_link_"+a).addEvent("mouseout",function(){g.hideTag(a)});if($("new_removetag_link")){$("new_removetag_link").addEvent("click",function(){g.removeTag(a)});$("new_removetag_link").set("id","removetag_link_"+a)}g.tags.push(a)},createTag:function(f,d,c,b,e,a){var g=this;new Element("div",{id:"tag_"+f,html:'<img src="./images/trans.gif" width="100%" height="100%" />',"class":"tag_div_hidden",styles:{width:(parseInt(e)-4)+"px",height:(parseInt(a)-4)+"px",top:c+"px",left:b+"px"}}).inject($("media_photo_div"));new Element("div",{id:"tag_label_"+f,html:d,"class":"tag_label",styles:{display:"none",top:(parseInt(c)+parseInt(a)+10)+"px",left:b+"px"}}).inject($("media_photo_div"));$("tag_"+f).addEvent("mouseover",function(){g.showTag(f)});$("tag_"+f).addEvent("mouseout",function(){g.hideTag(f)})},showTag:function(a){$("tag_"+a).className="tag_div";$("tag_label_"+a).style.display="block"},hideTag:function(a){$("tag_"+a).className="tag_div_hidden";$("tag_label_"+a).style.display="none"},addTag:function(){if(!this.isTagging){this.isTagging=true;this.newtag=new MooCrop("media_photo");var b=this;var a=$("media_photo_tagform").inject(b.newtag.wrapper);a.setStyles({top:this.newtag.crop.bottom+10,left:this.newtag.crop.right+10,display:"block"});this.newtag.addEvent("onBegin",function(f,e,d,c){a.setStyle("display","none")});this.newtag.addEvent("onCrop",function(f,e,d,c){a.setStyles({top:e.bottom+10,left:e.right+10,display:"none"})});this.newtag.addEvent("onComplete",function(f,e,d,c){a.setStyle("display","block")})}},cancelTag:function(){if(this.isTagging){$("media_photo_tag").value="";$("media_photo_tagform").inject("media_photo_div").setStyle("display","none");var a=this.newtag.removeOverlay.bind(this.newtag);a();this.isTagging=false}},saveTag:function(e){if(this.isTagging){if(this.options.object_owner&&this.options.object_owner_id){var f=this.options.object_owner;var b=this.options.object_owner_id;var c=""}else{var f="";var b="";var c=this.Base.Owner.user_info.user_username}var d="misc_js.php?task=tag_do&mediatag_user_id="+e+"&mediatag_text="+encodeURIComponent($("media_photo_tag").value)+"&mediatag_x="+this.newtag.crop.top+"&mediatag_y="+this.newtag.crop.left+"&mediatag_height="+this.newtag.crop.height+"&mediatag_width="+this.newtag.crop.width+"&user="+c+"&object_owner="+f+"&object_owner_id="+b+"&type="+this.options.type+"&media_id="+this.options.media_id+"&media_dir="+this.options.media_dir;$("ajaxframe").src=d;$("media_photo_tag").value="";$("media_photo_tagform").inject("media_photo_div").setStyle("display","none");var a=this.newtag.removeOverlay.bind(this.newtag);a();this.isTagging=false}},removeTag:function(e){if(this.options.object_owner&&this.options.object_owner_id){var d=this.options.object_owner;var a=this.options.object_owner_id;var b=""}else{var d="";var a="";var b=this.Base.Owner.user_info.user_username}var c="misc_js.php?task=tag_remove&mediatag_id="+e+"&user="+b+"&object_owner="+d+"&object_owner_id="+a+"&type="+this.options.type+"&media_id="+this.options.media_id;$("ajaxframe").src=c;$("tag_"+e).destroy();$("tag_label_"+e).destroy();$("full_tag_"+e).destroy();if(this.tags.indexOf(e)==0&&$("tag_comma_"+this.tags[1])){$("tag_comma_"+this.tags[1]).destroy()}this.tags.splice(this.tags.indexOf(e),1);if(this.tags.length==0){$("media_tags").style.display="none"}}});var MooCrop=new Class({calculateHandles:true,current:{},options:{maskColor:"black",maskOpacity:".3",handleColor:"#FFFFFF",handleWidth:"5px",handleHeight:"5px",cropBorder:"1px dashed #FFFFFF",min:{width:50,height:50},showMask:true,showHandles:false},initialize:function(b,a){this.setOptions(a);this.img=$(b);if(this.img.get("tag")!="img"){return false}this.resizeFunc=this.refresh.bindWithEvent(this);this.removeFunc=this.removeListener.bind(this);this.buildOverlay();this.setup()},setup:function(){$(this.cropArea).setStyles({width:this.options.min.width,height:this.options.min.height,top:(this.img.height-this.options.min.height)/2,left:(this.img.width-this.options.min.width)/2});this.current.crop=this.crop=this.getCropArea();this.handleWidthOffset=this.options.handleWidth.toInt()/2;this.handleHeightOffset=this.options.handleHeight.toInt()/2;this.fixBoxModel();this.drawMasks();this.positionHandles()},getCropArea:function(){var a=this.cropArea.getCoordinates();a.left-=this.offsets.x;a.right-=this.offsets.x;a.top-=this.offsets.y;a.bottom-=this.offsets.y;return a},fixBoxModel:function(){var c=this.boxDiff=(this.crop.width-this.options.min.width)/2;var a=this.bounds={top:c,left:c,right:this.img.width+(c*2),bottom:this.img.height+(c*2),width:this.options.min.width+(c*2),height:this.options.min.height+(c*2)};this.wrapper.setStyles({width:a.right,height:a.bottom,background:"url("+this.img.src+") no-repeat "+c+"px "+c+"px"});this.north.setStyle("width",a.right);this.south.setStyle("width",a.right)},activate:function(a,b){a.stop();this.current={x:a.page.x,y:a.page.y,handle:b,crop:this.current.crop};if(this.current.handle=="NESW"&&!this.options.showHandles){this.hideHandles()}this.fireEvent("onBegin",[this.img.src,this.getCropInfo(),this.bounds,b]);document.addEvent("mousemove",this.resizeFunc);document.addEvent("mouseup",this.removeFunc)},removeListener:function(){if(this.current.handle=="NESW"&&!this.options.showHandles){this.showHandles()}document.removeEvent("mousemove",this.resizeFunc);document.removeEvent("mouseup",this.removeFunc);this.crop=this.current.crop;this.fireEvent("onComplete",[this.img.src,this.getCropInfo(),this.bounds,this.current.handle])},refresh:function(a){var e=this.current.x-a.page.x;var d=this.current.y-a.page.y;var i=this.bounds;var h=this.crop;var f=this.current.handle;var k={};var j=(f.length>2)?true:false;if(f.contains("S")){if(h.bottom-d>i.bottom){d=h.bottom-i.bottom}if(!j){if((h.height-d)<i.height){d=h.height-i.height}k.height=h.height-d}}if(f.contains("N")){if(h.top-d<i.top){d=h.top}if(!j){if((h.height+d)<i.height){d=i.height-h.height}k.height=h.height+d}k.top=h.top-d}if(f.contains("E")){if(h.right-e>i.right){e=h.right-i.right}if(!j){if((h.width-e)<i.width){e=h.width-i.width}k.width=h.width-e}}if(f.contains("W")){if(h.left-e<i.left){e=h.left}if(!j){if((h.width+e)<i.width){e=i.width-h.width}k.width=h.width+e}k.left=h.left-e}var g=$merge(k);if($defined(k.width)){k.width-=this.boxDiff*2}if($defined(k.height)){k.height-=this.boxDiff*2}this.cropArea.setStyles(k);this.getCurrentCoords(g);this.drawMasks();this.positionHandles();this.fireEvent("onCrop",[this.img.src,this.getCropInfo(),i,f])},getCurrentCoords:function(b){var a=$merge(this.crop);if($defined(b.left)){a.left=b.left;if($defined(b.width)){a.width=b.width}else{a.right=a.left+a.width}}if($defined(b.top)){a.top=b.top;if($defined(b.height)){a.height=b.height}else{a.bottom=a.top+a.height}}if($defined(b.width)&&!$defined(b.left)){a.width=b.width;a.right=a.left+a.width}if($defined(b.height)&&!$defined(b.top)){a.height=b.height;a.bottom=a.top+a.height}this.current.crop=a},drawMasks:function(){if(!this.options.showMask){return}var a=this.bounds;var e=this.current.crop;var d=this.current.handle;this.north.setStyle("height",e.top+"px");this.south.setStyle("height",a.bottom-e.bottom+"px");this.east.setStyles({height:e.height+"px",width:a.right-e.right+"px",top:e.top+"px",left:e.right+"px"});this.west.setStyles({height:e.height+"px",width:e.left+"px",top:e.top+"px"})},positionHandles:function(){if(!this.calculateHandles){return}var d=this.current.crop;var a=this.handleWidthOffset;var b=this.handleHeightOffset;this.handles.get("N").setStyles({left:d.width/2-a+"px",top:-b+"px"});this.handles.get("NE").setStyles({left:d.width-a+"px",top:-b+"px"});this.handles.get("E").setStyles({left:d.width-a+"px",top:d.height/2-b+"px"});this.handles.get("SE").setStyles({left:d.width-a+"px",top:d.height-b+"px"});this.handles.get("S").setStyles({left:d.width/2-a+"px",top:d.height-b+"px"});this.handles.get("SW").setStyles({left:-a+"px",top:d.height-b+"px"});this.handles.get("W").setStyles({left:-a+"px",top:d.height/2-b+"px"});this.handles.get("NW").setStyles({left:-a+"px",top:-b+"px"})},hideHandles:function(){this.calculateHandles=false;this.handles.each(function(a){a.setStyle("display","none")})},showHandles:function(){this.calculateHandles=true;this.positionHandles();this.handles.each(function(a){a.setStyle("display","block")})},buildOverlay:function(){var b=this.options;this.wrapper=new Element("div",{styles:{"z-index":2001,position:"relative",width:this.img.width,height:this.img.height,background:"url("+this.img.src+") no-repeat","float":this.img.getStyle("float"),"margin-left":"auto","margin-right":"auto"}}).injectBefore(this.img);this.img.setStyle("display","none");this.offsets={x:this.wrapper.getLeft(),y:this.wrapper.getTop()};this.wrapper.addEvent("mouseover",function(c){return false});if(this.options.showMask){var a={position:"absolute",overflow:"hidden","background-color":b.maskColor,opacity:b.maskOpacity};this.north=new Element("div",{styles:$merge(a,{left:"0px"})}).injectInside(this.wrapper);this.south=new Element("div",{styles:$merge(a,{bottom:"0px",left:"0px"})}).injectInside(this.wrapper);this.east=new Element("div",{styles:a}).injectInside(this.wrapper);this.west=new Element("div",{styles:$merge(a,{left:"0px"})}).injectInside(this.wrapper)}this.cropArea=new Element("div",{styles:{position:"absolute",top:"0px",left:"0px",border:b.cropBorder,cursor:"move"},events:{dblclick:function(){this.fireEvent("onDblClk",[this.img.src,this.getCropInfo(),this.bounds])}.bind(this),mousedown:this.activate.bindWithEvent(this,"NESW")}}).injectInside(this.wrapper);this.handles=new Hash();["N","NE","E","SE","S","SW","W","NW"].each(function(c){this.handles.set(c,new Element("div",{styles:{position:"absolute","background-color":b.handleColor,width:b.handleWidth,height:b.handleHeight,overflow:"hidden",cursor:(c.toLowerCase()+"-resize")},events:{mousedown:this.activate.bindWithEvent(this,c)}}).injectInside(this.cropArea))},this)},getCropInfo:function(){var a=$merge(this.current.crop);a.width-=this.boxDiff*2;a.height-=this.boxDiff*2;return a},removeOverlay:function(){this.wrapper.destroy();this.img.setStyle("display","")}});MooCrop.implement(new Events,new Options);SocialEngineAPI.URL=new Class({Base:{},url_base:null,url_info:{},initialize:function(){},url_create:function(c,a,e,d,b){var f=(SocialEngine.Core.settings.setting_url?this.url_info[c].url_subdirectory:this.url_info[c].url_regular);if(!f){return false}f=f.replace("$user",a);f=f.replace("$id1",e);f=f.replace("$id2",d);f=f.replace("$id3",b);return this.url_base+f},url_userdir:function(a){return"uploads_user/"+(a+999-((a-1)%1000)).toString()+"/"+a+"/"},ImportURLBase:function(a){this.url_base=a},ImportURLInfo:function(a){this.url_info=a}});SocialEngineAPI.User=new Class({Base:{},user_exists:false,user_displayname:false,user_displayname_short:false,user_info:{},profile_info:{},level_info:{},usersetting_info:{},options:{displayname_order:"standard"},initialize:function(){},userPhotoFullPath:function(){if(!this.Base.URL){return false}if(!this.user_info.user_photo){return this.Base.URL.url_base+"images/nophoto.gif"}return this.Base.URL.url_base+this.Base.URL.url_userdir(this.user_info.user_id)+this.user_info.user_photo},ImportUserInfo:function(a){if(!a||$type(a)!="object"||!a.user_exists){this.user_exists=false;return}this.user_exists=true;a.user_id=parseInt(a.user_id);delete a.user_exists;this.user_info=a;this.user_info.user_fname=this.user_info.user_fname.trim();this.user_info.user_lname=this.user_info.user_lname.trim();if(this.user_info.user_fname&&this.user_info.user_lname){if(this.options.displayname_order=="asian"){this.user_displayname_short=this.user_info.user_lname;this.user_displayname=this.user_info.user_lname+" "+this.user_info.user_fname}else{this.user_displayname_short=this.user_info.user_fname;this.user_displayname=this.user_info.user_fname+" "+this.user_info.user_lname}}else{if(this.user_info.user_fname){this.user_displayname=this.user_displayname_short=this.user_info.user_fname}else{if(this.user_info.user_lname){this.user_displayname=this.user_displayname_short=this.user_info.user_lname}else{if(this.user_info.user_username){this.user_displayname=this.user_displayname_short=this.user_info.user_username}}}}}});theObjects=document.getElementsByTagName("object");for(var i=0;i<theObjects.length;i++){theObjects[i].outerHTML=theObjects[i].outerHTML};Function.prototype.bind=function(b){var c=this,a=function(){return c.apply(b,arguments)};return(a)};SEMods=function(){};SEMods.TextAreaControl=function(a){this.obj=a;this.obj.style.overflow="hidden";this.originalHeight=this.obj.getStyle("height").toInt();var b=this.update.bind(this);a.addEvent("focus",this.onFocus.bind(this));a.addEvent("blur",this.onBlur.bind(this));this.update()};SEMods.TextAreaControl.prototype={obj:null,updating:false,autoGrow:false,originalHeight:null,shadowElement:null,increment:0,timer:null,lastLength:0,setAutoGrow:function(a){this.autoGrow=a;this.createShadowElement();this.update()},onUpdate:function(){if(this.autoGrow&&this.lastLength!=this.obj.value.length){this.lastLength=this.obj.value.length;this.updateShadowElement();this.obj.style.height=Math.max(this.originalHeight,this.shadowElement.offsetHeight+this.increment)+"px"}},beginUpdate:function(){if(this.updating){return false}this.updating=true;return true},endUpdate:function(){this.updating=false},update:function(){if(!this.beginUpdate()){return}this.onUpdate();this.endUpdate()},createShadowElement:function(){if(this.shadowElement){return}this.shadowElement=document.createElement("DIV");this.shadowElement.style.position="absolute";this.shadowElement.style.top="-99999px";this.shadowElement.style.left="-99999px";document.body.appendChild(this.shadowElement)},updateShadowElement:function(){if(this.shadowElement){text=this.obj.value+"<br>";this.shadowElement.innerHTML=text.toString().replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#039;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\n/g,"<br />");var b=this.getPXMetrics(this.obj.getStyle("font-size"),10);var a=this.obj.getStyle("line-height");if((/Opera/i.test(navigator.userAgent))){a=this.getPXMetrics(a,0)+3+"px"}this.increment=b+10;this.shadowElement.style.width=this.obj.offsetWidth+"px";this.shadowElement.style.lineHeight=a;this.shadowElement.style.fontSize=this.obj.getStyle("font-size");this.shadowElement.style.fontFamily=this.obj.getStyle("font-family");this.shadowElement.style.paddingLeft=this.obj.getStyle("padding-left");this.shadowElement.style.paddingRight=this.obj.getStyle("padding-right")}},onFocus:function(){this.timer=setInterval(this.update.bind(this),500)},onBlur:function(){if(this.timer){clearInterval(this.timer);this.timer=null}},getPXMetrics:function(c,b){var a=parseFloat(c);if(isNaN(a)){return b!=null?b:a}return/px/i.test(c)?a:/pt/i.test(c)?1.3333*a:a}};

        function textarea_autogrow(a){
        var b=$(a);if(b&&!b._controlled){b._controlled=true;new SEMods.TextAreaControl(b).setAutoGrow(true);return b.getStyle("height").toInt()}};if(typeof(bsn)=="undefined"){_b=bsn={}}

        if(typeof(_b.Autosuggest)=="undefined"){_b.Autosuggest={}}
        else{alert("Autosuggest is already set!")}

        _b.AutoSuggest=function(e,d){
          if(!document.getElementById){return 0}this.fld=_b.DOM.gE(e);if(!this.fld){return 0}

// Jean 19/09/2009
        if (this.fld.name.test(/(^to_|_search$)/))
         {
/*
  SocialEngine.Language = new SocialEngineAPI.Language();
  SocialEngine.RegisterModule(SocialEngine.Language);
  SELanguage = SocialEngine.Language;
  this.defaultText = SELanguage.Translate(300085); // 'Commencer à saisir un nom...'; // SocialEngineAPI.Language.Translate(300085); // Commencer à saisir un nom...
*/
          // Jean 31/01/2011
          if (d && d.defaultLabelText)
            this.defaultText = d.defaultLabelText;
          else
            // "Commencer à saisir un nom..."
            this.defaultText = SocialEngine && SocialEngine.Language ? SocialEngine.Language.Translate(3000845) : "Commencer à saisir un nom...";

          this.fld.defaultText = this.defaultText;
          this.fld.initMsg = function ()
           {
            if (this.value == '')
             {
              this.value = this.defaultText;
              this.style.fontSize = '11px';
              this.style.color = '#999999';
              this.style.fontStyle = 'italic';
             }
           }
          this.fld.siSaisie = function ()
           {
            this.style.fontSize = '12px';
            this.style.color = '';
            this.style.fontStyle = '';
           }
          if (!isIE)
           {
            this.fld.addEvent("keydown", function () { this.siSaisie(); });
            this.fld.addEvent("focus", function () { if (this.value == this.defaultText) this.value = ''; });
            this.fld.addEvent("blur", function () { this.initMsg(); });
           }
          else
           {
            this.fld.onkeydown = function () { this.siSaisie(); };
            this.fld.onfocus = function () { if (this.value == this.defaultText) this.value = ''; };
            this.fld.onblur = function () { this.initMsg(); };
           }
          this.fld.initMsg();
         }

        this.sInp="";this.nInpC=0;this.aSug=[];this.iHigh=0;this.oP=d?d:{};var a,b={minchars:1,meth:"get",varname:"input",className:"autosuggest",timeout:2500,delay:0,offsety:-5,shownoresults:true,noresults:"No results!",maxheight:250,cache:true,maxentries:25,blurtrigger:false,multisuggest:true, showOnTop: false};for(a in b){if(typeof(this.oP[a])!=typeof(b[a])){this.oP[a]=b[a]}}var c=this;this.fld.onkeypress=function(f){return c.onKeyPress(f)};this.fld.onkeyup=function(f){return c.onKeyUp(f)};if(typeof(this.oP.callback)=="function"&&this.oP.blurtrigger){

        this.fld.onblur=function(g){
        if(document.activeElement&&typeof(g)==="undefined")
         {var f=document.activeElement}
        else
         {
          var f=g.explicitOriginalTarget;

          while(f && f.parentNode)
           {
            if(f.tagName=="A"&&typeof(f.id)=="string")
             {
              if(f.id.substring(0,10)=="bsnsuggest")
               {break;}
             }
             if (f.parentNode) f=f.parentNode;
           }

          if(typeof(f.id)!="string"){f.id=""}
         }
        if(f.id.substring(0,10)!="bsnsuggest")
         {
          c.oP.callback({id:c.fld.value,value:c.fld.value});c.clearSuggestions()
         }
        }
        }this.fld.setAttribute("autocomplete","off")};

        _b.AutoSuggest.prototype.onKeyPress=function(f){var e=(window.event)?window.event.keyCode:f.keyCode;var d=13;var c=9;var g=27;var b=186;var a=1;

        switch(e){case d:
        if (self.majLoading) majLoading(this.fld,'none');
        if(this.aSug.length!=0&&this.iHigh){this.setHighlightedValue();a=false}else{if(this.fld.value.length>0){if(typeof(this.oP.callback)=="function"){this.clearSuggestions();
        if (self.majLoading) majLoading(this.fld,'none');
        this.oP.callback({id:this.fld.value,value:this.fld.value})}a=false}else{a=false}}break;case g:this.clearSuggestions();
        if (self.majLoading) majLoading(this.fld,'none');
        break}return a};

        _b.AutoSuggest.prototype.onKeyUp=function(f){var d=(window.event)?window.event.keyCode:f.keyCode;var c=38;var e=40;var a=1;switch(d){case c:this.changeHighlight(d);a=0;
        if (self.majLoading) majLoading(this.fld,'none');
        break;case e:this.changeHighlight(d);a=0;
        if (self.majLoading) majLoading(this.fld,'none');
        break;default:var b=this.fld.value.split(/[;]+/ig); if (d != 13 && d != 9 && d != 27 && d != 38 && d != 40) {
        if (self.majLoading) majLoading(this.fld,'inline');
        if (self.majLoading) majLoading(this.fld, b != '' ? 'inline' : 'none');
        }this.getSuggestions(b[b.length-1])}return a};

        _b.AutoSuggest.prototype.getSuggestions=function(g){if(g==this.sInp){return 0}_b.DOM.remE(this.idAs);this.sInp=g;if(g.length<this.oP.minchars){this.aSug=[];this.nInpC=g.length;return 0}var d=this.nInpC;this.nInpC=g.length?g.length:0;var b=this.aSug.length;if(this.nInpC>d&&b&&b<this.oP.maxentries&&this.oP.cache){var a=[];for(var e=0;e<b;e++){if(this.aSug[e].value.substr(0,g.length).toLowerCase()==g.toLowerCase()||this.aSug[e].info.substr(0,g.length).toLowerCase()==g.toLowerCase()){a.push(this.aSug[e])}}this.aSug=a;if(this.aSug.length<b){var f=this;var c=this.sInp;clearTimeout(this.ajID);this.ajID=setTimeout(function(){f.doAjaxRequest(c)},this.oP.delay)}else{this.createList(this.aSug)}return false}else{var f=this;var c=this.sInp;clearTimeout(this.ajID);this.ajID=setTimeout(function(){f.doAjaxRequest(c)},this.oP.delay)}return false};

        _b.AutoSuggest.prototype.doAjaxRequest=function(c){var e=this.fld.value.split(/[;]+/ig);if(c!=e[e.length-1]){return false}var h=this;if(typeof(this.oP.script)=="function"){var d=this.oP.script(encodeURIComponent(this.sInp))}else{var d=this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp)}
        if(!d){return false}

        // Jean 09/02/2011 : on rajoute l'éventuelle webtv sur laquelle procéder à l'interrogation
        else if (self.targetWebTvID)
          d += d +"&webtv_id="+ self.targetWebTvID;

        var b=this.oP.meth;var c=this.sInp;var a=function(i){h.setSuggestions(i,c)};var f=function(i){};var g=new _b.Ajax();g.makeRequest(d,b,a,f)};

        _b.AutoSuggest.prototype.setSuggestions=function(req,input){var new_value=this.fld.value.split(/[;]+/ig);if(input!=new_value[new_value.length-1]){return false}this.aSug=[];if(this.oP.json){var jsondata=eval("("+req.responseText+")");

        for(var i=0;i<jsondata.results.length;i++)
         {
          //alert();
          var infos = {
              id:jsondata.results[i].id,
              value:jsondata.results[i].value,
              info:jsondata.results[i].info,
              photo:jsondata.results[i].photo,
              photo_width:jsondata.results[i].photo_width,
              // Jean 22/08/2009
              username:jsondata.results[i].username
           };

          // Jean 01/02/2011
          if (jsondata.results[i].url_profile_popup)
            infos.url_profile_popup = jsondata.results[i].url_profile_popup;

          // Jean 29/10/2011
          if (jsondata.results[i].tel)
            infos.tel = jsondata.results[i].tel;
          if (jsondata.results[i].website)
            infos.website = jsondata.results[i].website;
          if (jsondata.results[i].sponsor_desc)
            infos.sponsor_desc = jsondata.results[i].sponsor_desc;
          if (jsondata.results[i].sector_id)
            infos.sector_id = jsondata.results[i].sector_id;
          if (jsondata.results[i].photo_path)
            infos.photo_path = jsondata.results[i].photo_path;
          if (jsondata.results[i].base_photo_width)
            infos.base_photo_width = jsondata.results[i].base_photo_width;
          if (jsondata.results[i].base_photo_height)
            infos.base_photo_height = jsondata.results[i].base_photo_height;
          // Jean 16/01/2012
          if (jsondata.results[i].audience_id)
            infos.audience_id = jsondata.results[i].audience_id;

          // Jean 12/11/2011
          if (jsondata.results[i].url)
            infos.url = jsondata.results[i].url;
          if (jsondata.results[i].obj_type)
            infos.obj_type = jsondata.results[i].obj_type;
          if (jsondata.results[i].cm_only)
            infos.cm_only = jsondata.results[i].cm_only;

          this.aSug.push(infos);
         }
        }
        else
        {var xml=req.responseXML;var results=xml.getElementsByTagName("results")[0].childNodes;for(var i=0;i<results.length;i++){if(results[i].hasChildNodes()){this.aSug.push({id:results[i].getAttribute("id"),value:results[i].childNodes[0].nodeValue,info:results[i].getAttribute("info")})}}}this.idAs="as_"+this.fld.id;this.createList(this.aSug)};

        _b.AutoSuggest.prototype.createList=function(b){
            if (self.majLoading) majLoading(this.fld,'none');
            var r=this;_b.DOM.remE(this.idAs);this.killTimeout();if(b.length==0&&!this.oP.shownoresults){return false}var m=_b.DOM.cE("div",{id:this.idAs,className:this.oP.className});var e=_b.DOM.cE("div",{className:"as_corner"});var h=_b.DOM.cE("div",{className:"as_bar"});var t=_b.DOM.cE("div",{className:"as_header"});t.appendChild(e);t.appendChild(h);m.appendChild(t);var l=_b.DOM.cE("ul",{id:"as_ul"});
        for(var u=0;u<b.length;u++){var z=b[u].value;var x=b[u].info;
        var q=z.toLowerCase().indexOf(this.sInp.toLowerCase());var c=x.toLowerCase().indexOf(this.sInp.toLowerCase());
        if(q!=-1){var j=z.substring(0,q)+"<em>"+z.substring(q,q+this.sInp.length)+"</em>"+z.substring(q+this.sInp.length);
        var p=x}
        else{
        var j=z;
        var p=x.substring(0,c)+"<em>"+x.substring(q,c+this.sInp.length)+"</em>"+x.substring(c+this.sInp.length)}

        if(z!=x){j=p+" ("+j+")"}
        //if(z!=x){j=p} // Jean 12/11/2011

        var s=_b.DOM.cE("span",{},j,true);

        // Jean 12/11/2011 : "Rechercher par tag :" / "Sujet :"
        if (b[u].obj_type && (b[u].obj_type == 'tag' || b[u].obj_type == 'event' || b[u].obj_type == 'profile' || b[u].obj_type == 'channel' || b[u].obj_type == 'crm'))
          s.insertBefore(_b.DOM.cE("font",{className:(b[u].cm_only == '1' ? "prefix_CM" : "prefix")},SocialEngine.Language.Translate(b[u].obj_type == 'tag' ? 3511906 : (b[u].obj_type == 'profile' ? 3511908 : (b[u].obj_type == 'channel' ? 3511909 : (b[u].obj_type == 'crm' ? 3511912 : 3511907))))+' ',true),s.childNodes[0]);

        // Jean 08/09/2009 : si on veut retirer la photo, il faut commenter la zone suivante
        var n=_b.DOM.cE("img",{src:b[u].photo, width:b[u].photo_width, border:"0"});
        n.removeAttribute("height");
        s.insertBefore(n,s.childNodes[0]);

        var w=_b.DOM.cE("a",{href:"javascript:void(0);",className:(b[u].cm_only == '1' ? "prefix_CM" : "")});
        var f=_b.DOM.cE("span",{className:"tl"}," ");
        var d=_b.DOM.cE("span",{className:"tr"}," ");

        w.appendChild(f);
        w.appendChild(d);
        w.appendChild(s);
        w.name=u+1;
        w.id="bsnsuggest_"+(u+1);
        w.onclick=function(){r.setHighlightedValue();return false};
        w.onmouseover=function(){r.setHighlight(this.name)};
        var k=_b.DOM.cE("li",{},w);
        l.appendChild(k)
       }

  if(b.length==0&&this.oP.shownoresults){
    var k=_b.DOM.cE("li",{className:"as_warning"},this.oP.noresults);
    l.appendChild(k)
  }
  m.appendChild(l);

  var v=_b.DOM.cE("div",{className:"as_corner"});
  var y=_b.DOM.cE("div",{className:"as_bar"});var o=_b.DOM.cE("div",{className:"as_footer"});o.appendChild(v);o.appendChild(y);m.appendChild(o);
  var g=_b.DOM.getPos(this.fld);
  m.style.left=g.x+"px";
  // Jean 21/08/2009
  m.style.top = (g.y+this.fld.offsetHeight+this.oP.offsety)+"px";
  m.style.width=this.fld.offsetWidth+"px";m.onmouseover=function(){r.killTimeout()};m.onmouseout=function(){r.resetTimeout()};document.getElementsByTagName("body")[0].appendChild(m);this.iHigh=0;var r=this;this.toID=setTimeout(function(){r.clearSuggestions()},this.oP.timeout)};_b.AutoSuggest.prototype.changeHighlight=function(a){var b=_b.DOM.gE("as_ul");if(!b){return false}var c;if(a==40){c=this.iHigh+1}else{if(a==38){c=this.iHigh-1}}if(c>b.childNodes.length){c=b.childNodes.length}if(c<1){c=1}this.setHighlight(c)};_b.AutoSuggest.prototype.setHighlight=function(b){var a=_b.DOM.gE("as_ul");if(!a){return false}if(this.iHigh>0){this.clearHighlight()}this.iHigh=Number(b);a.childNodes[this.iHigh-1].className="as_highlight";this.killTimeout()};_b.AutoSuggest.prototype.clearHighlight=function(){var a=_b.DOM.gE("as_ul");if(!a){return false}if(this.iHigh>0){a.childNodes[this.iHigh-1].className="";this.iHigh=0}};_b.AutoSuggest.prototype.setHighlightedValue=function(){if(this.iHigh){var a=this.fld.value.split(/[;]+/ig);a.pop();a.push(this.aSug[this.iHigh-1].value);if(this.oP.multisuggest){var b=";"}else{var b=""}this.sInp=this.fld.value=a.join(";")+b;this.fld.focus();if(this.fld.selectionStart){this.fld.setSelectionRange(this.sInp.length,this.sInp.length)}if(typeof(this.oP.callback)=="function"){this.oP.callback(this.aSug[this.iHigh-1])}this.clearSuggestions()}};_b.AutoSuggest.prototype.killTimeout=function(){clearTimeout(this.toID)};_b.AutoSuggest.prototype.resetTimeout=function(){clearTimeout(this.toID);var a=this;this.toID=setTimeout(function(){a.clearSuggestions()},1000)};_b.AutoSuggest.prototype.clearSuggestions=function(){this.killTimeout();this.aSug=[];var a=_b.DOM.gE(this.idAs);var c=this;if(a){var b=new _b.Fader(a,1,0,250,function(){_b.DOM.remE(c.idAs)})}};if(typeof(_b.Ajax)=="undefined"){_b.Ajax={}}_b.Ajax=function(){this.req={};this.isIE=false};_b.Ajax.prototype.makeRequest=function(c,b,a,d){if(b!="POST"){b="GET"}this.onComplete=a;this.onError=d;var e=this;if(window.XMLHttpRequest){this.req=new XMLHttpRequest();this.req.onreadystatechange=function(){e.processReqChange()};this.req.open("GET",c,true);this.req.send(null)}else{if(window.ActiveXObject){this.req=new ActiveXObject("Microsoft.XMLHTTP");if(this.req){this.req.onreadystatechange=function(){e.processReqChange()};this.req.open(b,c,true);this.req.send()}}}};_b.Ajax.prototype.processReqChange=function(){if(this.req.readyState==4){if(this.req.status==200){this.onComplete(this.req)}else{this.onError(this.req.status)}}};if(typeof(_b.DOM)=="undefined"){_b.DOM={}}_b.DOM.cE=function(g,c,b,f){var h=document.createElement(g);if(!h){return 0}for(var d in c){h[d]=c[d]}var e=typeof(b);if(e=="string"&&!f){h.appendChild(document.createTextNode(b))}else{if(e=="string"&&f){h.innerHTML=b}else{if(e=="object"){h.appendChild(b)}}}return h};_b.DOM.gE=function(c){var a=typeof(c);if(a=="undefined"){return 0}else{if(a=="string"){var b=document.getElementById(c);if(!b){return 0}else{if(typeof(b.appendChild)!="undefined"){return b}else{return 0}}}else{if(typeof(c.appendChild)!="undefined"){return c}else{return 0}}}};
  _b.DOM.remE=function(a){var b=this.gE(a);if(!b){return 0}else{if(b.parentNode.removeChild(b)){return true}else{return 0}}};_b.DOM.getPos=function(c){var c=this.gE(c);var b=c;var d=0;if(b.offsetParent){while(b.offsetParent){d+=b.offsetLeft;b=b.offsetParent}}else{if(b.x){d+=b.x}}var b=c;var a=0;if(b.offsetParent){while(b.offsetParent){a+=b.offsetTop;b=b.offsetParent}}else{if(b.y){a+=b.y}}return{x:d,y:a}};if(typeof(_b.Fader)=="undefined"){_b.Fader={}}_b.Fader=function(b,f,e,a,d){if(!b){return 0}this.e=b;this.from=f;this.to=e;this.cb=d;this.nDur=a;this.nInt=50;this.nTime=0;var c=this;this.nID=setInterval(function(){c._fade()},this.nInt)};_b.Fader.prototype._fade=function(){this.nTime+=this.nInt;var a=Math.round(this._tween(this.nTime,this.from,this.to,this.nDur)*100);var c=a/100;if(this.e.filters){try{this.e.filters.item("DXImageTransform.Microsoft.Alpha").opacity=a}catch(b){this.e.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity="+a+")"}}else{this.e.style.opacity=c}if(this.nTime==this.nDur){clearInterval(this.nID);if(this.cb!=undefined){this.cb()}}};_b.Fader.prototype._tween=function(e,a,g,f){return a+((g-a)*(e/f))};TB_WIDTH=0;TB_HEIGHT=0;var TB_doneOnce=0;var TB_ready=false;var TB_useReady=true;function TB_init(){TB_ready=true;$$("a.smoothbox").each(function(a){a.onclick=TB_bind})}window.addEvent("domready",TB_init);function TB_bind(b){if(TB_useReady&&!TB_ready){return}var b=new Event(b);b.preventDefault();this.blur();var a=this.title||this.name||"";var c=this.rel||false;TB_show(a,this.href,c);this.onclick=TB_bind;return false}function TB_show(j,b,k,e,h){if(TB_useReady&&!TB_ready){return}if(!h){h=0}if(!$("TB_overlay")){(new Element("div").setProperty("id","TB_overlay")).inject($("smoothbox_container")||document.body);$("TB_overlay").setOpacity(0.6);TB_overlaySize()}if(!$("TB_window")){(new Element("div").setProperty("id","TB_window")).inject($("smoothbox_container")||document.body);$("TB_window").setOpacity(0)}else{$("TB_window").destroy();(new Element("div").setProperty("id","TB_window")).inject($("smoothbox_container")||document.body);$("TB_window").setOpacity(0)}if(h==0){$("TB_overlay").onclick=TB_remove}else{$("TB_overlay").onclick=""; /* Jean 31/07/2009 : il faudrait aussi désactiver la touche echap (à faire plus tard) */}window.onscroll=TB_position;var c=b.match(/(.+)?/)[1]||b;var a=b.match(/\?(.+)/)[1];var f=TB_parseQuery(a);TB_WIDTH=(f.width*1)+30;TB_HEIGHT=(f.height*1)+40;var d=TB_WIDTH-30,i=TB_HEIGHT-45;

  if(b.indexOf("TB_iframe")!=-1){urlNoQuery=b.split("TB_");$("TB_window").innerHTML+="<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+j+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>X</a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"&in_smoothbox=true' id='TB_iframeContent' name='TB_iframeContent' scrolling='auto' style='width:"+(d+29)+"px;height:"+(i+17)+"px;' onload='TB_showWindow()'> </iframe>"}
  else{$("TB_window").innerHTML+="<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+j+"</div><div id='TB_closeAjaxWindow'><a href='javascript:;' id='TB_closeWindowButton'>X</a></div></div><div id='TB_ajaxContent' style='width:"+d+"px;height:"+i+"px;'></div>"}$("TB_closeWindowButton").onclick=TB_remove;
  if(b.indexOf("TB_inline")!=-1){$("TB_ajaxContent").innerHTML=($(f.inlineId).innerHTML);TB_position();TB_showWindow()}else{if(b.indexOf("TB_iframe")!=-1){TB_position();if(frames.TB_iframeContent==undefined){$(document).keyup(function(m){var l=m.keyCode;if(l==27){TB_remove()}});TB_showWindow()}}else{var g=function(){TB_position();TB_showWindow()};new Request.HTML({method:"get",update:$("TB_ajaxContent"),onComplete:g}).get(b)}}window.onresize=function(){TB_position();TB_overlaySize()};document.onkeyup=function(l){var l=new Event(l);if(l.code==27){TB_remove()}}}function TB_showWindow(){if(TB_useReady&&!TB_ready){return}if(TB_doneOnce==0){TB_doneOnce=1;$("TB_window").set("tween",{duration:250});$("TB_window").tween("opacity",0,1)}else{$("TB_window").setStyle("opacity",1)}}

function TB_remove(){if(TB_useReady&&!TB_ready){return}$("TB_overlay").onclick=null;document.onkeyup=null;document.onkeydown=null;if($("TB_closeWindowButton")){$("TB_closeWindowButton").onclick=null}$("TB_window").set("tween",{duration:250,onComplete:function(){$("TB_window").destroy()}});$("TB_window").tween("opacity",1,0);$("TB_overlay").set("tween",{duration:400,onComplete:function(){$("TB_overlay").destroy()}});$("TB_overlay").tween("opacity",0.6,0);window.onscroll=null;window.onresize=null; /* Jean 31/07/2009 */ if (window.onClosePopUp) onClosePopUp(); TB_init();TB_doneOnce=0;return false}

function TB_position()
 {
  if (TB_useReady && !TB_ready)
    return
  $("TB_window").set("morph",{duration:75});
  try { var contenant = parent.document.getElementById('event_discussions'); var profileContent = parent.document.getElementById('profile_content') }
  catch(e) { var contenant = null; var profileContent = null; }
  $("TB_window").morph({width:TB_WIDTH+"px",left:(window.getScrollLeft()+(window.getWidth()-TB_WIDTH)/2)+"px",top:( (parent != window && profileContent ? profileContent.scrollTop : window.getScrollTop()) + ( (parent != window && contenant ? contenant.clientHeight : window.getHeight())-TB_HEIGHT)/2)+"px"})
 }

function TB_overlaySize(){if(TB_useReady&&!TB_ready){return}$("TB_overlay").setStyles({height:"0px",width:"0px"});$("TB_overlay").setStyles({height:window.getScrollHeight()+"px",width:window.getScrollWidth()+"px"})}
function TB_parseQuery(c){if(TB_useReady&&!TB_ready){return}if(!c){return{}}var e={};var b=c.split(/[;&]/);for(var a=0;a<b.length;a++){var d=b[a].split("=");if(!d||d.length!=2){continue}e[unescape(d[0])]=unescape(d[1]).replace(/\+/g," ")}return e};
function str_repeat(b,a){for(var c=[];a>0;c[--a]=b){}return(c.join(""))}
function sprintf(){var g=0,e,h=arguments[g++],k=[],d,j,l,b;while(h){if(d=/^[^\x25]+/.exec(h)){k.push(d[0])}else{if(d=/^\x25{2}/.exec(h)){k.push("%")}else{if(d=/^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(h)){if(((e=arguments[d[1]||g++])==null)||(e==undefined)){throw ("Too few arguments.")}if(/[^s]/.test(d[7])&&(typeof(e)!="number")){throw ("Expecting number but found "+typeof(e))}switch(d[7]){case"b":e=e.toString(2);break;case"c":e=String.fromCharCode(e);break;case"d":e=parseInt(e);break;case"e":e=d[6]?e.toExponential(d[6]):e.toExponential();break;case"f":e=d[6]?parseFloat(e).toFixed(d[6]):parseFloat(e);break;case"o":e=e.toString(8);break;case"s":e=((e=String(e))&&d[6]?e.substring(0,d[6]):e);break;case"u":e=Math.abs(e);break;case"x":e=e.toString(16);break;case"X":e=e.toString(16).toUpperCase();break}e=(/[def]/.test(d[7])&&d[2]&&e>0?"+"+e:e);l=d[3]?d[3]=="0"?"0":d[3].charAt(1):" ";b=d[5]-String(e).length;j=d[5]?str_repeat(l,b):"";k.push(d[4]?e+j:j+e)}else{throw ("Huh ?!")}}}h=h.substring(d[0].length)}return k.join("")};

function retireAccents (exp)
 {
  exp = exp.replace(/[àâä]/g, "a");
  exp = exp.replace(/[éèêë]/g,"e");
  exp = exp.replace(/[iîï]/g, "i");
  exp = exp.replace(/[oôö]/g, "o");
  exp = exp.replace(/[ûùü]/g, "u");
  return exp;
 }

function profile_url_create (username, name, webtv_url)
 {
  return (webtv_url ? webtv_url : SocialEngine.URL.url_base) + username +'---'+ (name ? retireAccents(name).replace(/[^a-z]/gi, '-') : '');
 }



  // Transforme une durée (en secondes) en un text du format : hh:mm:ss
  function secondesToMinutes(nbsec)
   {
    // Vérification que le nombre de secondes est bien un nombre
    if (isNaN(nbsec)) return '?';

    var nbsec = Math.floor(nbsec);
    var duree = '';
    var negatif = nbsec < 0;
    if (negatif) nbsec *= -1;
    var espace = ':';

    // On calcule les parties heures, minutes, secondes de l'heure
    var nbHeur, min, minBrut;
    nbHeur = Math.floor(nbsec / 3600);  // partie entière de l'heure
    min = Math.floor(nbsec / 60) - nbHeur * 60;
    minBrut = Math.floor(nbsec / 60) - nbHeur * 60;  // partie entière des minutes
    if (minBrut < 10) min = '0'+ min;

    if (nbHeur < 10) nbHeur = '0'+ nbHeur;
    duree = nbHeur

    var affichMin;

    affichMin = min;

    duree += (duree != '' ? espace : '')+ affichMin;

    var affichSec = nbsec % 60;
    if (affichSec < 10) affichSec = '0'+ affichSec;
    // On affiche les secondes sur deux chiffres
    duree += (duree != '' ? espace : '')+ affichSec;

    if (negatif) duree = "- "+ duree;

    return duree;
   }

  // Jean 28/01/2010
  function fillTimeStampFromFlashPlayer (inputID, forceMAJ, pasFocus)
   {
    if ($(inputID).value == '' || forceMAJ)
     {
      iframeFlashVisu = isIE ? document.frames['apercu_video'] : ($('apercu_video') ? $('apercu_video').contentWindow : null);
      if (!iframeFlashVisu || !iframeFlashVisu.WCS_videoTimeStamp)
       $(inputID).value = '00:00:00';
      else
       $(inputID).value = secondesToMinutes(parseInt(iframeFlashVisu.WCS_videoTimeStamp, 10));
     }
    if (!pasFocus)
     setTimeout('$(\''+ inputID +'\').nextSibling.nextSibling.select();', 0);
   }

  // Jean 28/01/2010
  function seekIframeFlashVideo (inputID)
   {
    if ($(inputID).value != '')
     {
      iframeFlashVisu = isIE ? document.frames['apercu_video'] : ($('apercu_video') ? $('apercu_video').contentWindow : null);
      if (iframeFlashVisu && iframeFlashVisu.thisMovie)
       {
        if ( iframeFlashVisu.thisMovie("playerWCS") )
          iframeFlashVisu.thisMovie("playerWCS").seekFlashVideo($(inputID).value);
        else
          iframeFlashVisu.thisMovie("player").seekFlashVideo($(inputID).value);
       }
     }
   }


// Jean 26/03/2010
function go_login ()
 {
  var url_login = "/";
  if (SocialEngine.Profile && SocialEngine.Profile.options.subdir && SocialEngine.Profile.options.subdir != "")
    url_login += SocialEngine.Profile.options.subdir;
  url_login += "login.php?return_url="+ escape(document.location.href);
  document.location.replace(url_login);
 }

// Jean 18/04/2010
function getDateStr(timestamp)
  {
   var myDate = new Date();
   myDate.setTime(timestamp);
   return (myDate.getDate() < 10 ? '0'+ myDate.getDate() : myDate.getDate())
          +'.'
          + ((myDate.getMonth()+1) < 10 ? '0'+ (myDate.getMonth()+1) : (myDate.getMonth()+1))
          +'.'
          + (myDate.getFullYear() < 10 ? '0'+ myDate.getFullYear() : myDate.getFullYear());
  }

// Jean 04/07/2010
function getHourStr(timestamp)
  {
   var myDate = new Date();
   myDate.setTime(timestamp);
   return ((myDate.getHours() < 10 ? '0'+ myDate.getHours() : myDate.getHours())
          +':'
          + (myDate.getMinutes() < 10 ? '0'+ myDate.getMinutes() : myDate.getMinutes()));
  }

/* Jean 03/03/2010 : améliorations de la barre de menus */
//---------------------------------------------------------------------------
// --- Dit si zone html est en intersection avec le curseur de la souris
//---------------------------------------------------------------------------
function isCursorAbove (event, zoneID)
 {
  var area = $(zoneID);
  if (!area || area.style.display == 'none') return false;
  var leftZ = getLeft(area);
  var rightZ = leftZ + area.offsetWidth;
  var topZ = getTop(area);
  var bottomZ = topZ + area.offsetHeight;
  var coord_x = event.page ? event.page.x : (event.clientX ? event.clientX : event.pageX);
  var coord_y = event.page ? event.page.y : (event.clientY ? event.clientY : event.pageY);
  try { coord_y += document.body.scrollTop; } catch (e) {;}
  var aboveHoriz = (coord_x > leftZ && coord_x < rightZ);
  var aboveVert =  (coord_y > topZ && coord_y < bottomZ);
  return aboveVert && aboveHoriz;
 }

var genericDicoTO = new Array();
var x_vect = 4;
var y_vect = 0;

// Jean 10/06/2010 : fait bouger un object de quelques pixels (div, img...) au passage de la souris sur celui-ci
function moveIfOver(objID)
 {
  $(objID).onmouseover = function(event) {
    clearTimeout(genericDicoTO[objID]);
    animateObj(event, this.id, +1);
  };
  $(objID).onmouseout  = function(event) {
    clearTimeout(genericDicoTO[objID]);
    if (!isCursorAbove(event, objID))
      animateObj(event, this.id, -1);
  };
 }

function animateObj(event, objID, sens)
 {
  var marginRight = $(objID).style.marginRight.replace(/px$/, '');
  if (marginRight == '') marginRight = 0;
  else marginRight = parseInt(marginRight, 10);

  // On sort le morceau
  if (sens == +1)
   {
    if (marginRight < x_vect)
     {
      $(objID).style.marginRight = marginRight + 1;
      genericDicoTO[objID] = setTimeout("animateObj(null, '"+ objID +"', '"+ sens +"');", 30);
     }
   }

  // On rentre le morceau
  if (sens == -1)
   {
    if (marginRight > 0)
     {
      $(objID).style.marginRight = marginRight - 1;
      genericDicoTO[objID] = setTimeout("animateObj(null, '"+ objID +"', '"+ sens +"');", 30);
     }
   }
 }

//------------------------------------------------------------------
// Convertit une durée (nombre de secondes) en durée au format "<hh:mm:ss>"
//------------------------------------------------------------------
function dureeToHHmmSS (duree, libDureeNeante)
 {
  if (duree == '' || duree == 0) return libDureeNeante ? libDureeNeante : '0s';
  duree = parseInt(duree,10);
  var h, m, s, hh, mm, ss;

  // Partie jours
  j = duree / (3600*24);
  j = Math.floor(j);
  if (j > 0) duree = duree - (j * (3600*24));

  // Partie heure
  h = duree / 3600;
  hh = Math.floor(h);
  //if (hh < 10) hh = '0'+ hh;

  // Partie minutes
  m = duree / 60 - hh * 60;
  mm = Math.floor(m);
  //if (mm < 10) mm = '0'+ mm;

  // Partie secondes
  ss = duree - hh * 3600 - mm * 60;
  //if (ss < 10) ss = '0'+ ss;

  return (j > 0 ? j+' jour'+ (j > 1 ? 's' : '')
       + (hh > 0 || mm > 0 || ss > 0 ? ', ' : '') : '')
       + (hh > 0 ? hh +'h'+ (mm == 0 && ss > 0 || ss == 0 && mm > 0 ? ' et ' : (mm > 0 && ss > 0 ? ', ' : '')) : '')
       + (mm > 0 ? (mm < 10 ? '0' : '') + mm + (hh == 0 || ss > 0 ? 'min' : 'min') + (ss > 0 ? ' et ' : '') : '')
       + (ss > 0 ? ss +'s' : '');
 }
//for (var i=0; i<3600*24*3; i+= 417) document.write("<br>"+ dureeToHHmmSS(i));


function trim (exp)
 {
  return exp.replace(/^[ \t\n\b]+/g, '').replace(/[ \t\n\b]+$/g, '');
 }


// Jean 06/07/2010 : convertit une date str JJ/MM/AA ou JJ/MM/AAAA en timestamp Javascript
function strDateToTimestamp (strDate)
 {
  var tabMatch = strDate.match(/([0-9][0-9]?)\/([0-9][0-9]?)\/([0-9][0-9][0-9]?[0-9]?)/);

  if (!tabMatch)
    return 0;

  var jour = tabMatch[1];
  var mois = tabMatch[2];
  var annee = tabMatch[3];

  if (annee.length == 2)
    annee = '20'+ annee;

  var d = new Date();
  d.setDate(jour);
  d.setMonth(mois-1);
  d.setFullYear(annee);
  d.setHours(+1);
  d.setMinutes(0);
  d.setSeconds(0);
  d.setMilliseconds(0);

  return d.getTime();
 }


// ******************************************************************************
// Pour la barre de menus et les menus déroulants :
// ******************************************************************************

function SwapOut(id1) {
  $(id1).src = Rollarrow1.src;
  return true;
}

function SwapBack(id1) {
  $(id1).src = Rollarrow0.src;
  return true;
}

// Jean 22/02/2011 : timeout pour l'apparition des menus
var to_menu = null;

function navBarInit(timeoutValue)
 {
  // un menu s'affiche par défaut au bout de 300 milli-secondes
  if (!timeoutValue)
    timeoutValue = 300;

  $$('.lienMenu').each(function(objMenuLink) {

    var objMenuLinkID = objMenuLink.id;
    var objMenuID = 'menu_'+ objMenuLinkID;
    var objMenu = $(objMenuID);

    if (!objMenu) { alert('élément "'+ objMenuID +'" attendu !'); return; }

    // Si sous-menu
    if (objMenuLink.parentNode.className != 'top_menu_link' && objMenuLink.parentNode.className.indexOf("submenulink_parent") > -1)
      dicoSubMenusParents[objMenuID] = objMenuLink.parentNode.parentNode.parentNode;

    // Déclenchement de l'apparition du menu (Jean 22/02/2011 - avec délai)
    objMenuLink.addEvent('mouseover', function(e) { killMenuHideTimeout(objMenuID); to_menu = setTimeout('showMenu("'+ objMenuID +'");', timeoutValue); });

    // Disparition "programmée" du menu
    objMenuLink.addEvent('mouseout',  function(e) { if (!isCursorAbove(e, objMenuID) && !isCursorAbove(e,'current_submenu')) { startMenuHideTimeout(objMenuID); } else { killMenuHideTimeout(objMenuID); } });

    objMenu.addEvent('mouseover', function(e) { killMenuHideTimeout(objMenuID); });
    objMenu.addEvent('mouseout',  function(e) { if (!isCursorAbove(e, objMenuID.id) && !isCursorAbove(e,'current_submenu')) { startMenuHideTimeout(objMenuID);    } });
  });

  // On parcourt chaque item de menu
  $$('.menu_item_dropdown').each(function(objMenuItem) {

    // Disparition "programmée" du sous-menu éventuellement ouvert
    objMenuItem.addEvent('mouseover',  function(e) { if (!isCursorAbove(e,'current_submenu')) $('current_submenu').style.display = 'none'; });
  });

  // Annulation de la disparition "programmée"
  $('current_submenu').addEvent('mouseover',  function(e) { killMenuHideTimeout(objCurrentMenuID); });
  $('current_submenu').addEvent('mouseout',  function(e) { if (!isCursorAbove(e,'current_submenu')) { startMenuHideTimeout(objCurrentMenuID); } });
 }

function showMenu(menuID)
{
  var objMenu = $(menuID);

  if (!objMenu) return;

  if (objMenu.style.display == 'none')
   {
    //if ($(open_menu)) hideMenu(menuID);
    killMenuHideTimeout(menuID);

    var butNotHideThis = null;

    if (dicoSubMenusParents[menuID])
      butNotHideThis = dicoSubMenusParents[menuID];

    // Par sécurité, on cache d'abord tout autre menu déjà ouvert
    hideAllMenus(objMenu, butNotHideThis);

    // Si sous-menu
    if (dicoSubMenusParents[menuID])
     {
      var objMenuLinkID = menuID.replace(/^menu_/, "");
      setTimeout("afficheSousMenu('"+ objMenuLinkID +"','"+ menuID +"');", 0);
      currentSubMenuParent = objMenu;
      objCurrentMenuID = objMenu.parentNode.parentNode.parentNode.id;
     }
    else
     {
      objMenu.style.display = 'inline';

      // Jean 13/07/2010
      objMenu.setStyle('opacity', 0.4);
      objMenu.fade('in');
     }
    //open_menu = menuID;
   }
 }

function afficheSousMenu (objMenuLinkID, objMenuID)
 {
  $('current_submenu').innerHTML = $(objMenuID).innerHTML;
  $('current_submenu').style.display = 'inline';

  // Jean 21/07/2010
  $('current_submenu').setStyle('opacity', 0.4);
  $('current_submenu').fade('in');

  var objMenuLink = $(objMenuLinkID);
  if (objMenuLink.length) objMenuLink = objMenu[0];

  if (objMenuLink && getLeft(objMenuLink) > 0)
   {
    $('current_submenu').style.left = getLeft(objMenuLink) + objMenuLink.offsetWidth;  // event.page.x
    var remontee = 1;
    /*
    if ($('current_submenu').offsetHeight > 100)
      remontee = 36;
      */
    $('current_submenu').style.top = getTop(objMenuLink) - remontee;  // event.page.y
   }
 }
function killMenuHideTimeout(menuID)
 {
  clearTimeout(current_timeout[menuID]);
  current_timeout[menuID] = '';
 }
function startMenuHideTimeout(menuID)
 {
  // Jean 22/02/2011
  clearTimeout(to_menu);
  if (current_timeout[menuID] == '') {
    current_timeout[menuID] = setTimeout(function() { hideMenu(menuID); }, 800);
  }
 }
function hideMenu(menuID)
 {
  menu = $(menuID);

  // Tant qu'on y est, on ferme tous les menus
  //hideAllMenus();

  if (menu.style.display != 'none')
   {
    // Jean 13/07/2010
    menu.style.display = 'none';
    //menu.fade('out');
    //setTimeout('$("'+ menuID +'").style.display = "none"', 500);

    $('current_submenu').style.display = 'none';

    // Jean 26/05/2011
    if (top.show_first_menu) $('menu_dropdown_tocshows').style.display = '';

    currentSubMenuParent = null;
    clearTimeout(current_timeout[menuID]);
    current_timeout[menuID] = '';
   }
 }
function hideAllMenus(butNotThisOne, butNotThisOtherOne)
 {
   // On cache les autres menus
   $$('.lienMenu').each(function(objOtherMenuLink) {
     var objOtherMenu = $('menu_'+ objOtherMenuLink.id);
     if (!butNotThisOne || objOtherMenu != butNotThisOne && !butNotThisOtherOne || objOtherMenu != butNotThisOtherOne)
       hideMenu('menu_'+ objOtherMenuLink.id);
   });
}

function getLeft (obj)
 {
  if (obj.offsetParent) return (obj.offsetLeft + getLeft(obj.offsetParent));
  else return (obj.offsetLeft);
 }
function getTop (obj)
 {
  if (obj.offsetParent) return (obj.offsetTop + getTop(obj.offsetParent));
  else return (obj.offsetTop);
 }

// (fin barre de menus et les menus déroulants)
// ******************************************************************************


function retire_accents_minuscules (exp)
{
    exp = exp.replace(/[àâä]/gi, "a");
    exp = exp.replace(/[éèêë]/gi,"e");
    exp = exp.replace(/[iîï]/gi, "i");
    exp = exp.replace(/[oôö]/gi, "o");
    exp = exp.replace(/[ûùü]/gi, "u");
    return exp;
}
function sanitize_paranoid_string(string)
 {
  string = string.replace(/[^a-z0-9\.]/gi, "-");
  string = string.replace(/(^[\-\.]+|[\-\.]+$)/g, "");
  string = string.replace(/---+/g, "--");
  return string;
 }
function to_url (texte)
 {
  texte = retire_accents_minuscules(texte);
  texte = sanitize_paranoid_string(texte);
  texte = texte.toLowerCase();
  return texte;
 }

function tronque (texte, longueur, caractEnd)
 {
  var s = texte;
  if (s.length > longueur)
    s = s.substr(0, longueur) + (caractEnd ? caractEnd : ' [...]');
  return s;
 }

// Suppression d'un favori en AJAX
function deleteFavourite (userID, eventID)
 {
  if ($('img_loading_'+ userID +'_'+ eventID))
    $('img_loading_'+ userID +'_'+ eventID).style.display = 'inline';

  if ($('navbar_img_loading_'+ userID +'_'+ eventID))
    $('navbar_img_loading_'+ userID +'_'+ eventID).style.display = 'inline';

  // Ajax
  var request = new Request.JSON({
    'method' : 'post',
    'url' : 'event_ajax.php',
    'data' : {
      'task' : 'delete_favourite',
      'user_id' : userID,
      'event_id' : eventID
    },
    'onComplete':function(responseObject)
     {
      if( $type(responseObject)!="object" || !responseObject.result )
       {
        alert(responseObject.error);
       }
      else
       {
        // On fait disparaître l'image d'attente
        if ($('img_loading_'+ userID +'_'+ eventID))
          $('img_loading_'+ userID +'_'+ eventID).style.display = 'none';

        if ($('navbar_img_loading_'+ userID +'_'+ eventID))
          $('navbar_img_loading_'+ userID +'_'+ eventID).style.display = 'none';

        // On fait disparaître la ligne
        if ($('navbar_div_fav_'+ userID +'_'+ eventID))
          $('navbar_div_fav_'+ userID +'_'+ eventID).style.display = 'none';

        if ($('div_fav_'+ userID +'_'+ eventID))
          $('div_fav_'+ userID +'_'+ eventID).style.display = 'none';
       }
     }
  });

  request.send();
 }

// Jean 01/07/2010 : pour recherche mot exact dans tel champ de se_events
function rechercheExacte (only_in, text, selfTarget, exactSearch, typeObject)
 {
  // Jean 24/10/2011 : url dédiée pour les tags
  if (only_in == 'event_tags')
    document.location.href = subdir +'/tag/'+ escape(trim(text));
  else
   {
    $('exact_search_only_in').value = only_in;
    $('exact_search_text').value = text;
    $('form_exact_search')['t'].value = typeObject ? typeObject : 'event';
    $('form_exact_search').target = selfTarget ? '_self' : '_blank';
    $('whole_word_only').value = exactSearch ? 'on' : '';
    $('form_exact_search').submit();
   }
 }

// Jean 12/01/2011 pour l'ajout ou la modif de chaîne/workgroup
function showZoneGroupEmailSuffixes()
 {
  $('zone_group_email_suffixes').style.display = 'inline';
  $('group_email_suffixes').focus();
  textarea_autogrow('group_email_suffixes');
 }

function hideZoneGroupEmailSuffixes()
 {
  $('zone_group_email_suffixes').style.display = 'none';
 }


var current_express_sex;
var current_express_fname;
var current_express_lname;
var current_express_minibio;

// Jean 08/11/2011
var current_express_tel;
var current_express_address1;
var current_express_address2;
var current_express_cp;
var current_express_town;

var current_express_sector_id;
var current_express_company;
var current_express_audience_id;
var current_express_email = '';
// Jean 20 février 2012
var current_express_function_id;

// Jean 31/01/2012
var current_express_twitter;
var current_express_linked_in;
var current_express_google_plus;
var current_express_facebook;
var current_express_comp_website;
var current_express_blog;

var requested_group_id = '';
var requested_event_id = '';


// Initialisation du formulaire de création express d'un compte dans le but de souscrire à une chaîne
function channelSubscribe(group_id, event_id)
 {
  if (current_express_email == '')
   {
    // On prépare le titre du mini-formulaire de création express de compte
    var htmlTitre;

    htmlTitre = '<img src="./images/icons/messages48.gif" border="0" class="icon" style="width: 48px; height: 48px; float: left;" />'+ SocialEngine.Language.Translate(2000224) +'<br /><br />';
    // "NB : Ces données ne seront utilisées qu'aux fins de vous abonner aux nouveautés relatives à cette chaîne. Elles ne seront pas utilisées en-dehors de ce champ d'action ! De plus, il sera possible de vous désinscrire quand vous le souhaiterez."
    var htmlNB = SocialEngine.Language.Translate(3511334);

    $('zone_titre_express_account').style.display = 'block';
    $('zone_titre_express_account').innerHTML = htmlTitre;
    $('zone_nota_benne_express_account').innerHTML = htmlNB;

    // On ouvre la boîte de dialogue avec le mini formulaire de création express de compte
    requested_group_id = group_id;
    requested_event_id = event_id;
    TB_show('', '#TB_inline?width=600&height=555&inlineId=generic_zone_express_account', '', '../images/trans.gif');
    $('express_lname').focus();
    setTimeout("$('express_lname').focus();",200);
   }
  else
   {
    // "M'abonner à cette chaîne (m'alerter des nouveautés)"
    setTimeout("TB_show(SocialEngine.Language.Translate(2000224).replace('<br>', ' '), 'user_group_manage.php?group_id="+ group_id +"&task=join_do&want_subscribe"+ (event_id ? '&event_id='+ event_id : '') +"&TB_iframe=true&height=300&width=450', '', './images/trans.gif');", 800);
   }
 };

var jeton_20111111 = true;

function expressAccountConfirm()
 {
  $('loading_express_account').style.display = 'inline';

  // Test validité champs
  if (trim($('express_lname').value) == '' || trim($('express_email').value) == '' || !trim($('express_email').value).match(/.+@.+\..+/)
     // Jean 08/11/2011 : pour s'inscrire à un événement, les champs société / fonction / email / tel / adresse sont obligatoires
  || ($('express_address1')
       && (trim($('express_email').value) == ''
        || trim($('express_tel').value) == ''
        || trim($('express_lname').value) == ''
        || trim($('express_fname').value) == ''
        || trim($('express_minibio').value) == ''
        || trim($('express_address1').value) == ''
        || trim($('express_cp').value) == ''
        || trim($('express_town').value) == '')
      )
    )
   {
    // "Attention, certaines informations sont manquantes ou incorrectes... merci de vérifier votre saisie."
    $('loading_express_account').style.display = 'none';
    $('submit_express_account').disabled = false;
    alert(SocialEngine.Language.Translate(3511218));
    $('express_lname').focus();
   }
  else
   {
    // Si c'est la première fois depuis le chargement de la page qu'on doit récupérer les valeurs saisies dans le formulaire de création express de compte
    current_express_sex         = $('express_sex_male') && $('express_sex_male').checked ? '1' : ($('express_sex_female') && $('express_sex_female').checked ? '2' : '');
    current_express_fname       = $('express_fname')       ? $('express_fname').value       : '';
    current_express_lname       = $('express_lname')       ? $('express_lname').value       : '';
    current_express_company     = $('express_company')     ? $('express_company').value     : '';
    current_express_audience_id = $('express_audience_id') ? $('express_audience_id').value : '';
    current_express_minibio     = $('express_minibio')     ? $('express_minibio').value     : '';
    current_express_sector_id   = $('express_sector_id' )  ? $('express_sector_id').value   : '';
    current_express_function_id = $('express_function_id' )? $('express_function_id').value : '';
    current_express_email       = $('express_email')       ? $('express_email').value       : '';
    current_express_tel         = $('express_tel')         ? $('express_tel').value         : '';

    // Jean 08/11/2011
    current_express_address1   = $('express_address1')     ? $('express_address1').value    : '';
    current_express_address2   = $('express_address2')     ? $('express_address2').value    : '';
    current_express_cp         = $('express_cp')           ? $('express_cp').value          : '';
    current_express_town       = $('express_town')         ? $('express_town').value        : '';

		// Jean 31/01/2012
		current_express_twitter      = $('express_twitter')      ? $('express_twitter').value       : '';
		current_express_linked_in    = $('express_linked_in')    ? $('express_linked_in').value     : '';
		current_express_google_plus  = $('express_google_plus')  ? $('express_google_plus').value   : '';
		current_express_facebook     = $('express_facebook')     ? $('express_facebook').value      : '';
		current_express_comp_website = $('express_comp_website') ? $('express_comp_website').value  : '';
		current_express_blog         = $('express_blog')         ? $('express_blog').value          : '';

    // Ajax
    var tab_data = {
      'task' : 'express_account',
      'express_sex' :        current_express_sex,
      'express_fname' :      current_express_fname,
      'express_lname' :      current_express_lname,
      'express_minibio' :    current_express_minibio,
      'express_tel' :        current_express_tel,

			// Jean 08/11/2011
      'express_address1' :   current_express_address1,
      'express_address2' :   current_express_address2,
      'express_cp' :         current_express_cp,
      'express_town' :       current_express_town,

			// Jean 31/01/2012
      'express_twitter' :      current_express_twitter,
      'express_linked_in' :    current_express_linked_in ,
      'express_google_plus' :  current_express_google_plus,
      'express_facebook' :     current_express_facebook,
      'express_comp_website' : current_express_comp_website,
      'express_blog' :         current_express_blog,

      'express_sector_id' :  current_express_sector_id,
      'express_function_id': current_express_function_id,
      'express_company' :    current_express_company,
      'express_audience_id': current_express_audience_id,
      'express_email' :      current_express_email
    };

    // La raison est la souscription à une chaîne ?
    if (requested_group_id != '')
      tab_data['subscribe_group_id'] = requested_group_id;

    // Ou le vote sur un sujet ?
    else if (SocialEngine.Event && SocialEngine.Event.currentInterestType == 'vote')
     {
      tab_data['event_id'] = SocialEngine.Event.currentConfirmID;
      tab_data['interest_type'] = SocialEngine.Event.currentInterestType;
      tab_data['vote_value'] = SocialEngine.Event.currentInterestValue;
      tab_data['vote_explain'] = SocialEngine.Event.explainText;
     }

    // Ou l'intéressement à un sujet ?
    else if (SocialEngine.Event && SocialEngine.Event.currentInterestType)
     {
      tab_data['event_id'] = SocialEngine.Event.currentConfirmID;
      tab_data['interest_type'] = SocialEngine.Event.currentInterestType;
      tab_data['value'] = SocialEngine.Event.currentInterestType;
     }

    var request = new Request.JSON({
      'method' : 'post',
      'url' : 'misc_js.php',
      'data' : tab_data,
      'onComplete':function(responseObject)
       {
        if( $type(responseObject)!="object" || !responseObject.result )
         {
          alert(responseObject.error);
         }
        else
         {
          if (responseObject.error_msg)
           {
            $('loading_express_account').style.display = 'none';
            $('submit_express_account').disabled = false;
            alert('erreur dans la creation de votre compte');  // responseObject.error_msg
            $('express_lname').focus();
           }
          else
           {
            //alert('Votre user_id est : '+ responseObject.user_id);
            isLogged = true;

            // Si la création express de compte se fait dans le but de pouvoir voter contextuellement
            if (SocialEngine.Event && SocialEngine.Event.currentInterestType == 'contextualVote')
              setTimeout("SocialEngine.Event.contextualVote(SocialEngine.Event.currentConfirmID);", 1000);

            // Si la création express de compte se fait dans le but de pouvoir voter directement dans une page d'event
            else if (SocialEngine.Event && SocialEngine.Event.currentInterestType == 'vote')
              SocialEngine.Event.voteConfirm(SocialEngine.Event.currentConfirmID);

            // Si la création express de compte se fait dans le but de donner son feedback sur un sujet
            else if (SocialEngine.Event && SocialEngine.Event.currentInterestType)
              setTimeout("SocialEngine.Event.interestConfirm(SocialEngine.Event.currentInterestType, SocialEngine.Event.currentInterestValue, null, SocialEngine.Event.explainText, null, SocialEngine.Event.forceShowDialog);", 500);

            // Si la création express de compte se fait dans le but de pouvoir souscrire à une chaîne
            else if (requested_group_id != '')
              channelSubscribe(requested_group_id, requested_event_id);

            TB_remove();
           }
         }
       }
    });
    $('submit_express_account').disabled = true;
    request.send();
   }
 }

function getBodyHeight()
 {
  return document.body.clientHeight;
 }

// Jean 05/05/2011 : raccourci pour se porter volontaire
function volunteerShortCut ()
 {
  if (!$('seEventProfileWantTakePart').checked)
    $('seEventProfileWantTakePart').click();
 }

// Jean 05/05/2011 : raccourci pour proposer de sponsoriser
function feedbackShortCut (feedbackName, unCheckEnable)
 {
  if ($('seEventProfile'+ feedbackName).checked && !unCheckEnable)
    $('seEventProfile'+ feedbackName).checked = false;
  setTimeout("$('seEventProfile"+ feedbackName +"').click();", 0);
 }

// charge des onglets dans l'encart "about" de la home
var miniTabActive = 'about';
function loadMiniTab (nomTab)
 {
  miniTabActive = nomTab;
  $('zone_minitabs').getElements('.minitab_active').each(function(minitab) {
    $(minitab.id +'_content').style.display = 'none';
    minitab.className = 'minitab';
  });
  $(nomTab).className = 'minitab_active';
  $(nomTab +'_content').style.display = 'block';
 }

function rollOverMiniTab (minitab)
 {
  minitab.className = 'minitab_active';
 }

function rollOutMiniTab (minitab)
 {
  minitab.className = minitab.id == miniTabActive ? 'minitab_active' : 'minitab';
 }


var duree_minute_JS = 60 * 1000;
var duree_heure_JS = duree_minute_JS * 60;
var quartHeureJS = duree_heure_JS/4;
var cinqMinutesJS = quartHeureJS/3;
var duree_jour_JS = duree_heure_JS * 24;
var duree_jour_en_secondes = 3600 * 24;
var duree_jour_en_millisecondes = duree_jour_en_secondes * 1000;
var today = new Date();
var decalageHoraireJS = today.getTimezoneOffset() * duree_minute_JS;
var decalageHoraireMySQL = Math.round(decalageHoraireJS / 1000);


function getListeChoixDate(dateFieldName, timestampRefJS, minTimestampJS, maxTimestampJS, withPreciseHours, isDateEmpty, onDateChanged, isDateHidden)
 {
  var tmpHeure = new Date();
  var jourJS = new Date();
  var heureJS = new Date();
  var isLastDateSelected;

  // Date + heure sur lesquelles se positionner
  tmpHeure.setTime(timestampRefJS);

  jourJS.setTime(0);
  jourJS.setDate(tmpHeure.getDate());
  jourJS.setMonth(tmpHeure.getMonth());
  jourJS.setFullYear(tmpHeure.getFullYear());

  heureJS.setTime(0);
  heureJS.setMinutes(tmpHeure.getMinutes());
  heureJS.setHours(tmpHeure.getHours());

  defautDateJS_day = jourJS.getTime();
  defautDateJS_hour = heureJS.getTime();

  decalageHoraireJS = tmpHeure.getTimezoneOffset() * duree_minute_JS;
  defautDateJS_hour -= decalageHoraireJS;

  // Durée de la plage par défaut
  var nbJoursPlage = 200;
  var dureePlageJS = duree_jour_JS * nbJoursPlage;
  today.setTime(today.getTime() - dureePlageJS / 2);

  var debutPlageJS, finPlageJS;

  // S'il y a un début de plage spécifique à respecter
  if (minTimestampJS)
    debutPlageJS = Math.floor(minTimestampJS / duree_jour_en_millisecondes) * duree_jour_en_millisecondes;
  else
    debutPlageJS = timestampRefJS - (nbJoursPlage / 2) * duree_jour_JS;

  // S'il y a une fin de plage spécifique à respecter
  if (maxTimestampJS)
    finPlageJS = Math.floor(maxTimestampJS / duree_jour_en_millisecondes) * duree_jour_en_millisecondes;
  else
    finPlageJS = debutPlageJS + dureePlageJS;

  // On arrondit au jour près
  debutPlageJS =  Math.round(debutPlageJS / duree_jour_JS) * duree_jour_JS;
  finPlageJS =  Math.round(finPlageJS / duree_jour_JS) * duree_jour_JS;

  // Génération de la liste déroulante permettant de choisir le JOUR
  var html = '';
  var selectedDay = null;

  html += ' <select id="date_select_'+ dateFieldName +'"'
                 +' onchange="$(\'hour_select_'+ dateFieldName +'\').style.display = this.value == \'\' ? \'none\' : \'\';'
                 +(dateFieldName == 'task_date' ?
                     ' if ($(\'date_select_task_date_end\')) $(\'date_select_task_date_end\').style.display = this.value == \'\' ? \'none\' : \'\';'
                    +' if ($(\'hour_select_task_date_end\')) $(\'hour_select_task_date_end\').style.display = this.value == \'\' ? \'none\' : \'\';'
                   : '')
                 +(dateFieldName == 'event_date_start' ?
                     ' if ($(\'date_select_event_date_end\')) $(\'date_select_event_date_end\').style.display = this.value == \'\' ? \'none\' : \'\';'
                    +' if ($(\'hour_select_event_date_end\')) $(\'hour_select_event_date_end\').style.display = this.value == \'\' ? \'none\' : \'\';'
                   : '')
                 +'           if ($(\'duration_select_'+ dateFieldName +'\')) $(\'duration_select_'+ dateFieldName +'\').style.display = this.value == \'\' ? \'none\' : \'\';'
                 + (onDateChanged ? onDateChanged : '') +'"'
                 +' style="'+ (isDateHidden ? 'display: none;' : '') +'">';
  // aucune
  html += ' <option value=""></option>'; // '+ SocialEngine.Language.Translate(3000669) +'

  for (var curTimestampJS = debutPlageJS; curTimestampJS < finPlageJS; curTimestampJS += duree_jour_JS)
   {
    tmpHeure.setTime(curTimestampJS);
    jourJS.setTime(0);
    jourJS.setDate(tmpHeure.getDate());
    jourJS.setMonth(tmpHeure.getMonth());
    jourJS.setFullYear(tmpHeure.getFullYear());

    var isDateSelected = !isDateEmpty && defautDateJS_day == jourJS.getTime();
    if (isDateSelected)
     {
      isLastDateSelected = isDateSelected;
      selectedDay = jourJS;
      decalageHoraireJS = tmpHeure.getTimezoneOffset() * duree_minute_JS;
      decalageHoraireMySQL = Math.round(decalageHoraireJS / 1000);
     }

    var indiceJourDeLaSem = tmpHeure.getDay();
    var jourDeLaSem = SocialEngine.Language.Translate(3000229 + indiceJourDeLaSem + (indiceJourDeLaSem == 0 ? +7 : 0)).substr(0,3).toLowerCase();

    html += '<option value="'+ (Math.round(curTimestampJS/1000) + decalageHoraireMySQL) +'"'+ (isDateSelected ? ' selected' : '');
    html += '>';
    html += jourDeLaSem +' ';
    html += getDateStr(curTimestampJS); // +' / '+ indiceJourDeLaSem;
    // html += ' --- '+ curTimestampJS
    html += '</option>';

    // Si sépare visuellement les semaines
    if (indiceJourDeLaSem == 0)
      html += '<option value="" style="color: #999999;">-------------------</option>';
   }
  html += ' </select>';

  //-----------------------------------------------------------------------------------
  // Génération du choix de l'HEURE

  html += ' <select id="hour_select_'+ dateFieldName +'"'+ (onDateChanged ? ' onchange="'+ onDateChanged +'"' : '') + (!isLastDateSelected || isDateHidden ? ' style="display: none;"' : '') +'>';

  var pasJS = withPreciseHours ? duree_minute_JS : cinqMinutesJS;
  var timestampHereJS = defautDateJS_hour; // - decalageHoraireJS;
  var timestampMySQL = timestampHereJS / 1000;

  var jetonHeureExacte = false;
  debutPlageJS = 0;

  // On contruit la liste de choix d'heure, en échantillonnant de quart d'heure en quart d'heure
  for (var curTimestampJS = debutPlageJS; curTimestampJS < debutPlageJS + duree_jour_JS; curTimestampJS += pasJS)
   {
    var tmpCurTimestampJS = curTimestampJS - duree_heure_JS;
    var preSel = false;

    // Si l'heure par défaut n'est pas un chiffre rond, il faut quand-même l'afficher
    if (!jetonHeureExacte && tmpCurTimestampJS >= timestampHereJS + decalageHoraireJS)
     {
      var depasse = tmpCurTimestampJS > timestampHereJS;
      tmpCurTimestampJS = timestampHereJS + decalageHoraireJS + duree_heure_JS;
      preSel = true;
      jetonHeureExacte = true;
      // Si le pas de cette boucle avait déjà dépassé l'heure à pré-sélectionner
      if (depasse)
        curTimestampJS -= pasJS;
     }
    var curTimestampMySQL = Math.round(tmpCurTimestampJS / 1000) % duree_jour_en_secondes;

    tmpHeure.setTime(tmpCurTimestampJS);
    //decalageHoraireJS = tmpHeure.getTimezoneOffset() * duree_minute_JS;
    //decalageHoraireMySQL = Math.round(decalageHoraireJS / 1000);

    html += '<option value="'+ curTimestampMySQL +'"'+ (preSel ? ' selected' : '');
    // On met en évidence les heures arrondies
    if (tmpHeure.getMinutes() != 0 && tmpHeure.getMinutes() != 30)
      html += ' style="color: #999999;"';
    html += '>';

    // On affiche la date tenant compte du décalage horaire
    html += getHourStr(tmpCurTimestampJS - duree_heure_JS) // +' --- '+ curTimestampMySQL +' --- '+ tmpHeure.getTimezoneOffset();
    html += '</option>';
   }
   html += '</select>';

   return html;
  }


function getListeChoixDuree (dateFieldName, durationJS, withPreciseHours, isDateEmpty, onDateChanged)
 {
  var jetonDureeExacte = false;
  today = new Date();
  var pasJS = withPreciseHours ? duree_minute_JS : cinqMinutesJS;

  var html = '';

  // "Durée :"
  //html +=  SocialEngine.Language.Translate(3511162) +'<br>';
  html += ' <select id="duration_select_'+ dateFieldName +'"'+ (onDateChanged ? ' onchange="'+ onDateChanged +'"' : '') + (isDateEmpty ? ' style="display: none;"' : '') +'>';

  for (var curDurationJS = 0; curDurationJS < Math.max(durationJS, isExtranet ? duree_jour_JS*150 : duree_jour_JS*7); curDurationJS += pasJS)
   {
    //var curDurationMySQL = Math.round(curDurationJS / 1000);
    //var preSel = (durationJS >= curDurationJS);

    var tmpCurDurationJS = curDurationJS;
    var preSel = false;

    // Si la durée par défaut n'est pas un chiffre rond, il faut quand-même l'afficher
    if (!jetonDureeExacte && tmpCurDurationJS >= durationJS)
     {
      var depasse = tmpCurDurationJS > durationJS;
      tmpCurDurationJS = durationJS;
      preSel = true;
      jetonDureeExacte = true;
      // Si le pas de cette boucle avait déjà dépassé la durée à pré-sélectionner
      if (depasse)
        curDurationJS -= pasJS;
     }
    var curDurationMySQL = Math.round(tmpCurDurationJS / 1000);

    html += '<option value="'+ curDurationMySQL +'"'+ (preSel ? ' selected' : '');
    // On met en évidence les durées arrondies
    if (!((tmpCurDurationJS < duree_jour_JS/2 && tmpCurDurationJS % quartHeureJS == 0)
       || (tmpCurDurationJS < duree_jour_JS && tmpCurDurationJS % duree_jour_JS == 0)
       || (tmpCurDurationJS >= duree_jour_JS && tmpCurDurationJS % duree_jour_JS == 0)))
      html += ' style="color: #999999;"';
    html += '>';
    // "Durée :"
    html += SocialEngine.Language.Translate(3511162).toLowerCase()
            + ' '
            // "néante"
            + dureeToHHmmSS(tmpCurDurationJS/1000, SocialEngine.Language.Translate(3511163)); // +' --- '+ curDurationMySQL;
    html += '</option>';

    if (curDurationJS < duree_jour_JS)
      pasJS = withPreciseHours ? duree_minute_JS : cinqMinutesJS;
    else if (curDurationJS < duree_jour_JS * 7)
      pasJS = quartHeureJS * 4;
    else if (curDurationJS < duree_jour_JS * 30)
      pasJS = duree_jour_JS;
    else
      pasJS = duree_jour_JS * 30;
   }
   html += '</select>';

   return html;
 }

// Relation de dépendance entre 2 dates
function onChangeDate (mainDateName, relDateName, fromDuration, isFromDateStartModif)
 {
  var mainDatePart = $('date_select_'+ mainDateName).value;
  var mainHourPart = $('hour_select_'+ mainDateName).value;
  var mainTimestamp = mainDatePart*1 + mainHourPart*1;

  var relDatePart = $('date_select_'+ relDateName).value;
  var relHourPart = $('hour_select_'+ relDateName).value;
  var relTimestamp = relDatePart*1 + relHourPart*1;

  // On décompose la partie JOUR et la partie HEURE du timestamp à prendre en référence
  var refTimeStamp = isFromDateStartModif ? mainTimestamp : relTimestamp;
  var tmpHeure = new Date();
  tmpHeure.setTime(refTimeStamp * 1000);

  // Si on touche à une durée ou à la date de début, alors on décale la date de fin
  if (fromDuration || isFromDateStartModif)
    tmpHeure.setTime(tmpHeure.getTime() + Math.round(($('duration_select_'+ mainDateName).value == '' ? 0 : $('duration_select_'+ mainDateName).value) * 1000));

  tmpHeure.setTime(tmpHeure.getTime() + duree_heure_JS);

  var jourJS = new Date();
  jourJS.setTime(0);
  jourJS.setFullYear(tmpHeure.getFullYear());
  jourJS.setMonth(tmpHeure.getMonth());
  jourJS.setDate(tmpHeure.getDate());
  jourJS.setTime(jourJS.getTime() - duree_heure_JS);

  var heureJS = new Date();
  heureJS.setTime(0);
  heureJS.setHours(tmpHeure.getHours());
  heureJS.setMinutes(tmpHeure.getMinutes());

  // Si on touche à une durée, alors on décale la date de fin
  if (fromDuration && $('date_select_'+ relDateName))
   {
    $('date_select_'+ relDateName).value = Math.round(jourJS.getTime() / 1000);
    $('hour_select_'+ relDateName).value = Math.round(heureJS.getTime() / 1000);
   }
  // Si on touche à une date de début, alors on décale l'autre de manière à conserver la même durée
  else if (isFromDateStartModif && $('date_select_'+ relDateName))
   {
    $('date_select_'+ relDateName).value = Math.round(jourJS.getTime() / 1000);
    $('hour_select_'+ relDateName).value = Math.round(heureJS.getTime() / 1000);
   }
  // Si on touche à une date de fin, alors on conserve la même date de début, et donc on modifie la durée
  else if ($('duration_select_'+ relDateName))
   {
    tmpHeure.setTime(tmpHeure.getTime() - duree_heure_JS);
    var d_value = Math.round(Math.abs(tmpHeure.getTime() / 1000 - mainTimestamp));
    var d = $('duration_select_'+ relDateName);
    // On parcourt la liste déroulante de la durée
    for (var i=0; i<d.options.length; i++)
     {
      // Si la durée qu'on souhaite afficher est supérieure à l'item courant, alors on positionne la liste sur lui
      if (d_value >= d.options[i].value)
        d.selectedIndex = i;
     }
   }

  // On coche la case d'activation éventuelle
  onChangeDate_basic(mainDateName);
 }

function onChangeDate_basic (mainDateName)
 {
  // Case permettant de cocher
  var cb = $('is_dated_'+ mainDateName);
  if (!cb) cb = $('disable_'+ mainDateName);
  if (cb) cb.checked = true;
 }


//--------------------------------------------------------------------------------------------------------------------------------
// Fait que la touche "Entrée" soit active en tant que raccourci de validation dans tel mini-formulaire de maj contextuelle
// et que la touche "Echap" soit active en tant que raccourci de'annulation/fermeture dans tel mini-formulaire de maj contextuelle
//--------------------------------------------------------------------------------------------------------------------------------
function addShortCutsToCtxForm(zoneEdit, instr, addEnterKey)
 {
  zoneEdit.onkeyup = function(ev){
    var event = new Event(event);
    var RETURN = 13;
    var ECHAP = 27;
    var key = (window.event) ? window.event.keyCode : ev.keyCode;
    if (key == RETURN && addEnterKey)
      eval(instr);
    else if (key == ECHAP)
      zoneEdit.style.display = 'none';
  };
 }


//--------------------------------------------------------------------------------------------------------------------------------
// Jean 26/07/2011 : édition Ajax générique d'un champ de type DATE de la table se_<XXX>s
//--------------------------------------------------------------------------------------------------------------------------------
function majDateField(fromButton, objPrefix, objID, webtvID, dateFieldName, isDateNullable, isDatedFieldName, isDatedLangVarId, labelCompleteLangVarId, minTimestampJS, maxTimestampJS, durationMySQL, withPreciseHours, descLangID)
 {
  var zoneID = 'span_'+ dateFieldName +'_'+ objID + (webtvID ? '_'+ webtvID : '') +'_VALUE';
  var zone_value = $(zoneID);
  if (!zone_value) { alert('Champ "'+ zoneID +'" non trouvé !'); return; }

  //prompt('', dateFieldName +', '+ isDateNullable +', '+ isDatedFieldName +', '+ isDatedLangVarId +', '+ labelCompleteLangVarId +', '+ minTimestampJS +', '+ maxTimestampJS +', '+ durationMySQL +', '+ withPreciseHours);

  var today = new Date();

  // On va chercher la valeur initiale du champ
  var timestampMySQL = zone_value.innerHTML;
  // La date initiale est-elle vide ?
  var isDateEmpty = timestampMySQL == '' && !withPreciseHours;

  zone_maj_entire_date = $('span_entire_date_'+ dateFieldName +'_'+ objID + (webtvID ? '_'+ webtvID : ''));
  if (zone_maj_entire_date && zone_maj_entire_date.style.display == 'none' && !withPreciseHours)
    isDateEmpty = true;

  var timestampJS = !isDateEmpty ? timestampMySQL * 1000 : '';

  //if (dateFieldName == objPrefix +'_date_start' || dateFieldName == objPrefix +'_date_end')
  var dateFinExists = dateFieldName == 'event_date_start' || dateFieldName == 'event_date_end';

  // Si la durée doit être affichée, alors on va checker sa bonne valeur dans les spans
  if (durationMySQL && timestampJS && dateFinExists)
   {
    zone_other_date_value = $('span_'+ (dateFieldName == objPrefix +'_date_start' ? objPrefix +'_date_end' : objPrefix +'_date_start') +'_'+ objID + (webtvID ? '_'+ webtvID : '') +'_VALUE');
    if (zone_other_date_value && zone_other_date_value.innerHTML != '')
      durationMySQL = (dateFieldName == objPrefix +'_date_start' ? zone_other_date_value.innerHTML * 1000 - timestampJS : timestampJS - zone_other_date_value.innerHTML * 1000) / 1000;
   }

  // S'il faut aussi génération la liste de choix du jour et de l'heure d'une date dépendante (=> date de fin si c'est la date de début, ou l'inverse)
  var timestampJS_rel = null;
  var date_rel_exists = false;
  var isDateRelEmpty = true;
  var onChangeDate = null;

  if (dateFinExists)
   {
    date_rel_exists = true;
    var dateFieldName_rel = dateFieldName == objPrefix +'_date_start' ? objPrefix +'_date_end' : objPrefix +'_date_start';
    var zoneID_rel = 'span_'+ dateFieldName_rel +'_'+ objID + (webtvID ? '_'+ webtvID : '') +'_VALUE';
    var zone_value_rel = $(zoneID_rel);
    if (zone_value_rel)
     {
      // On va chercher la valeur initiale du champ
      var timestampMySQL_rel = zone_value_rel.innerHTML;
      if (timestampMySQL_rel != '' && !isNaN(timestampMySQL_rel))
       {
        isDateRelEmpty = false;
        timestampJS_rel = timestampMySQL_rel * 1000;
       }
      else
        timestampMySQL_rel = null;
     }
   }

  // On construit le formulaire à la volée
  var html = '';

  // 28/07/2011 - S'il faut intituler la zone de saisie
  if (descLangID)
    html += SocialEngine.Language.Translate(descLangID) +'<br>';


  //-----------------------------------------------------------------------------------
  // Si la date est facultative ou qu'elle peut être rendue nulle, il faut pouvoir la désactiver
  if (isDatedFieldName || isDateNullable && isDatedLangVarId)
   {
    html += '<input type="checkbox" id="'+ (isDatedFieldName ? 'is_dated' : 'disable') +'_'+ dateFieldName +'"';
    if (!isDateEmpty)
      html += ' checked';
    html += '       onclick="$(\'label_complete_'+ dateFieldName +'\').style.display = (this.checked ? \'inline\' : \'none\');';
    html += '                this.nextSibling.style.color = (this.checked ? \'black\' : \'#999999\');';
    html += '                $(\'date_select_'+ dateFieldName +'\').style.display = (this.checked ? \'\' : \'none\');';
    html += '                $(\'hour_select_'+ dateFieldName +'\').style.display = (this.checked ? \'\' : \'none\');';
    if (dateFieldName_rel)
     {
      html += '                $(\'date_select_'+ dateFieldName_rel +'\').style.display = (this.checked ? \'\' : \'none\');';
      html += '                $(\'hour_select_'+ dateFieldName_rel +'\').style.display = (this.checked ? \'\' : \'none\');';
     }
    html += '                if ($(\'duration_select_'+ dateFieldName +'\')) $(\'duration_select_'+ dateFieldName +'\').style.display = (this.checked ? \'\' : \'none\');';
    html += '">';

    html += '<label for="'+ (isDatedFieldName ? 'is_dated' : 'disable') +'_'+ dateFieldName +'" style="font-size: 12px;'+ (isDateEmpty ? ' color: #999999;' : '') +'">';
    html += (isDatedLangVarId ? SocialEngine.Language.Translate(isDatedLangVarId) : 'Activer').replace(/ /g, '&nbsp;') +'</label>';
    html += '<span id="label_complete_'+ dateFieldName +'"';
    if (isDateEmpty)
      html += ' style="display: none;"';
    html += '>'+ (labelCompleteLangVarId ? ', '+ SocialEngine.Language.Translate(labelCompleteLangVarId).replace(/ /g, '&nbsp;') : '') +'</span>';
    html += '<div style="height: 12px;"></div>';
   }

  // Date par défaut = aujourd'hui
  if (isDateEmpty || timestampMySQL == '')
   {
    // Si on publie de suite un sujet
    timestampJS = today.getTime();
    if (dateFieldName == objPrefix +'_datepublished')
      timestampJS -= 1000*60;

    // Si on publie un sujet "à retardement"
    else if (dateFieldName == objPrefix +'_dateplanned')
      timestampJS += 1000*60*5;

    // Équivalent MySQL
    timestampMySQL = Math.round(timestampJS / 1000);

    // On arrondie à la seconde près
    timestampJS = timestampMySQL * 1000;
   }

  var mainDateIsStart = (dateFieldName == objPrefix +'_date_start' || dateFieldName == 'task_date');

  // Génération du choix du JOUR et de l'HEURE de début
  html += getListeChoixDate(dateFieldName, timestampJS, minTimestampJS, maxTimestampJS, withPreciseHours, isDateEmpty, dateFieldName_rel ? "onChangeDate('"+ dateFieldName +"', '"+ dateFieldName_rel +"', false, true);" : "onChangeDate_basic('"+ dateFieldName +"');");

  // Génération du choix de la DURÉE
  if (dateFinExists && durationMySQL != null)
   {
    // On construit la liste de choix de la durée, en échantillonnant de quart d'heure en quart d'heure
    html += '<br /><img src="images/sub_comment_dark.png" border="0" style="width: 20px; height: 22px; margin-left: 30px;" align="absmiddle" />';
    html += getListeChoixDuree(dateFieldName, durationMySQL*1000, withPreciseHours, isDateEmpty, dateFieldName_rel ? "onChangeDate('"+ dateFieldName +"', '"+ dateFieldName_rel +"', true, "+ (mainDateIsStart ? 'true' : 'false') +");" : '');
   }

  // Génération du choix du JOUR et de l'HEURE de FIN
  if (date_rel_exists)
   {
    // "Fin :"
    html += '<br /><img src="images/sub_comment_dark.png" border="0" style="width: 20px; height: 22px; margin-left: 80px;" align="absmiddle" /> '+ SocialEngine.Language.Translate(3511351) +' ';
    html += getListeChoixDate(dateFieldName_rel, isDateRelEmpty ? timestampJS : timestampJS_rel, minTimestampJS, maxTimestampJS, withPreciseHours, isDateRelEmpty, "onChangeDate('"+ dateFieldName_rel +"', '"+ dateFieldName +"', false, "+ (mainDateIsStart ? 'true' : 'false') +");");
   }
  html += '<div style="height: 10px;"></div>';

  //-----------------------------------------------------------------------------------
  // "Annuler"
  html += '<input type="button" class="button small_cancel_button" value="'+ SocialEngine.Language.Translate(39) +'"';
  html +=       ' onclick="$(\'generic_zone_edit_date\').style.display = \'none\';"';
  html +=       ' style="float: right; margin: 3px 0px 3px 0px; padding-top: 1px;" />';

  //-----------------------------------------------------------------------------------
  // "Valider"
  var instrSubmit = 'majDateFieldConfirm(\''+ objPrefix +'\', '+ objID +', \''+ dateFieldName +'\', '+ (webtvID ? webtvID : 'null') +', '+ (isDatedFieldName ? '\''+ isDatedFieldName +'\'' : 'null') +','+ (minTimestampJS ? minTimestampJS : 'null') +','+ (maxTimestampJS ? maxTimestampJS : 'null') +');';

  html += ' <input type="button" class="button small_submit_button" value="'+ SocialEngine.Language.Translate(3000688) +'"';
  html +=        ' onclick="'+ instrSubmit +'"';
  html +=        ' style="float: right; margin: 3px 0px 3px 0px; padding-top: 1px;" />';

  html += '<img id="loading_'+ dateFieldName +'" src="images/images/icons/language_tool_loader.gif" align="middle" style="display: none; float: right; margin: 4px 20px 0px 0px; padding-top: 1px;" align="absmiddle" />';

  // Pour pouvoir inscrire une heure beaucoup plus précise (à la minute près)
  if (!withPreciseHours || dateFieldName == 'event_dateplanned')
   {
    html += '<div style="float: left;" class="link_precise_hour">';

    // Jean 08/08/2011 - Lien vers le planning des publications programmée
    if (dateFieldName == 'event_dateplanned')
     {
      // "Voir les programmations en cours"
      html += '<a href="upcoming_express?w=scheduled" target="_blank" style="color: black;">';
      html += SocialEngine.Language.Translate(3511555) +'</a>';
     }

    if (!withPreciseHours)
     {
      if (dateFieldName == 'event_dateplanned')
        html += '<div style="height: 7px;"></div>';
      html += '<a href="javascript:;"';
      html += ' onclick="majDateField(null, \''+ objPrefix +'\', '+ objID +', '+ webtvID +', \''+ dateFieldName +'\', '+ (isDateNullable ? 'true' : 'false') +', '+ (isDatedFieldName ? '\''+ isDatedFieldName +'\'' : 'null') +', '+ (isDatedLangVarId ? isDatedLangVarId : 'null') +', '+ (labelCompleteLangVarId ? labelCompleteLangVarId : 'null') +', '+ (minTimestampJS ? minTimestampJS : 'null') +', '+ (maxTimestampJS ? maxTimestampJS : 'null') +', '+ (durationMySQL != null ? durationMySQL : 'null') +', true);">';
      // "Choisir une heure à la minute près"
      html += SocialEngine.Language.Translate(3511168) +'</a>';
     }

    html += '</div>';
   }

  //-----------------------------------------------------------------------------------
  var zoneEdit = $('generic_zone_edit_date');
  zoneEdit.innerHTML = html;
  zoneEdit.style.display = 'block';

  if (fromButton)
   {
    zoneEdit.style.left = (getLeft(fromButton) - (zoneEdit.offsetWidth / 2)) +'px';
    zoneEdit.style.top = (getTop(fromButton) - zoneEdit.offsetHeight - 32) +'px';
   }

  // La touche "Entrée", en mode monoligne, équivaut à valider les données de ce mini-formulaire / Touche "Echap" pour le fermer
  addShortCutsToCtxForm(zoneEdit, instrSubmit, true);

  // On positionne le focus sur la zone de choix de la date (la case à cocher ou la liste déroulante, selon que cette dernière est active ou non)
  if (withPreciseHours && $('hour_select_'+ dateFieldName))
    $('hour_select_'+ dateFieldName).focus();
  else if ($('date_select_'+ dateFieldName).style.display == 'none')
    $((isDatedFieldName ? 'is_dated' : 'disable') +'_'+ dateFieldName).focus();
  else
    $('date_select_'+ dateFieldName).focus();
 }


//----------------------------------------------------------------------------------------------
// Validation d'une date
//----------------------------------------------------------------------------------------------
function majDateFieldConfirm(objPrefix, objID, dateFieldName, webtvID, isDatedFieldName, minTimestampJS, maxTimestampJS)
 {
  var newTimestampMySQL;
  var dateFieldName_rel, newTimestampMySQL_rel;
  var case_enable_date = $((isDatedFieldName ? 'is_dated' : 'disable') +'_'+ dateFieldName);

  var dateFinExists = dateFieldName == 'event_date_start' || dateFieldName == 'event_date_end';

  if (case_enable_date && !case_enable_date.checked)
    newTimestampMySQL = '';
  else
   {
    newTimestampMySQL = parseInt($('date_select_'+ dateFieldName).value,10) + parseInt($('hour_select_'+ dateFieldName).value,10);

    // Jean 19/05/2011
    if (dateFinExists && dateFieldName == objPrefix +'_date_start')
     {
      dateFieldName_rel = objPrefix +'_date_end';
      newTimestampMySQL_rel = parseInt($('date_select_'+ dateFieldName_rel).value,10) + parseInt($('hour_select_'+ dateFieldName_rel).value,10);
     }
   }

  var newTimestampJS = newTimestampMySQL == '' ? '' : newTimestampMySQL * 1000;

  // Vérif validité date
  if (newTimestampJS != ''
       // trop tôt ?
    && (minTimestampJS && (newTimestampJS < minTimestampJS)
       // trop tard ?
     || maxTimestampJS && (newTimestampJS > maxTimestampJS)
       // le user a sélectionné un "séparateur" de dates ?
     || $('date_select_'+ dateFieldName).value == '' && $('hour_select_'+ dateFieldName).value != '')
     )
   {
    alert(SocialEngine.Language.Translate(3511141));
    return;
    $('generic_zone_edit_date').style.display = 'none';
   }

  $('loading_'+ dateFieldName).style.display = 'inline';

  var datas = {
      'task' : 'edit_date_field',
      'webtv_id' : webtvID,
      'date_field_name' : dateFieldName,
      'date_field_value' : newTimestampMySQL,
      'date_rel_field_name' : dateFieldName_rel,
      'date_rel_field_value' : newTimestampMySQL_rel,
      'is_dated_field_name' : (isDatedFieldName ? isDatedFieldName : ''),
      'is_dated_field_value' : (isDatedFieldName && $('is_dated_'+ dateFieldName) && $('is_dated_'+ dateFieldName).checked ? '1' : '0')
    };
  datas[(objPrefix == 'user_subsc' ? 'user' : 'event') +'_id'] = objID;

  // Ajax
  var request = new Request.JSON({
    'method' : 'post',
    'url' : (objPrefix == 'user_subsc' ? 'profile' : objPrefix) +'_ajax.php',
    'data' : datas,
    'onComplete':function(responseObject)
    {
      if( $type(responseObject)!="object" || !responseObject.result || responseObject.result=="failure" )
       {
        alert(responseObject.error); // alert(responseObject && responseObject.error ? responseObject.error : 'Erreur côté serveur !');
       }
      else
       {
        zoneIsDatedFieldName = $('zone_is_dated_'+ dateFieldName);

        // La nouvelle date est-elle vide ?
        var isDateEmpty = (newTimestampMySQL == '');

        var isDateNotEmpty = (!isDatedFieldName || isDatedFieldName && $('is_dated_'+ dateFieldName).checked) && !isDateEmpty;

        // Mise à jour de la DATE telle qu'elle est affichée à l'écran
        zone_maj = $('span_'+ dateFieldName +'_'+ objID + (webtvID ? '_'+ webtvID : ''));

        // Dans l'extranet, il faut mettre à jour la date butoir qui est affichée à l'écran
        if (!zone_maj && dateFinExists && dateFieldName == objPrefix +'_date_start')
          zone_maj = $('span_'+ objPrefix +'_date_end_'+ objID + (webtvID ? '_'+ webtvID : ''));

        if (zone_maj)
          zone_maj.innerHTML = (isDateNotEmpty ? getDateStr(newTimestampMySQL * 1000) : '');

        // Zone miroir ?
        zone_maj_bis = $('span_'+ dateFieldName +'_'+ objID + (webtvID ? '_'+ webtvID : '') +'_bis');
        if (zone_maj_bis)
          zone_maj_bis.innerHTML = zone_maj.innerHTML;

        // Mise à jour de la zone cachée contenant la valeur timestamp de la date/heure
        zone_value = $('span_'+ dateFieldName +'_'+ objID + (webtvID ? '_'+ webtvID : '') +'_VALUE');

        // Jean 04/04/2011 - Affichage contextuel de la liste des webtvs sur lesquelles s'est propagée telle modif contextuelle
        if (responseObject.maj_webtv_urls && SocialEngine.Event && SocialEngine.Event.showMajWebtvUrls)
          SocialEngine.Event.showMajWebtvUrls(responseObject.maj_webtv_urls, getTop(zone_maj ? zone_maj : (zone_maj_bis ? zone_maj_bis : zone_value.nextSibling)) - 80);

        zone_maj_entire_date = $('span_entire_date_'+ dateFieldName +'_'+ objID + (webtvID ? '_'+ webtvID : ''));

        if (zone_maj_entire_date)
          zone_maj_entire_date.style.display = isDateNotEmpty ? '' : 'none';

        // Mise à jour de l'HEURE telle qu'elle est affichée à l'écran
        zone_maj_heure = $('span_hour_'+ dateFieldName +'_'+ objID + (webtvID ? '_'+ webtvID : ''));
        if (zone_maj_heure)
          zone_maj_heure.innerHTML = ((!isDatedFieldName || isDatedFieldName && $('is_dated_'+ dateFieldName).checked) && !isDateEmpty ? getHourStr(newTimestampMySQL * 1000) : '/');

        // Zone miroir ?
        zone_maj_heure_bis = $('span_hour_'+ dateFieldName +'_'+ objID + (webtvID ? '_'+ webtvID : '') +'_bis');
        if (zone_maj_heure_bis)
          zone_maj_heure_bis.innerHTML = zone_maj_heure.innerHTML;

        if (zone_value)
          zone_value.innerHTML = newTimestampMySQL;

        // On met aussi à jour l'éventuelle date/heure dépendant de celle-ci (date de fin si on a mis à jour la date de début + durée, ou inversement)
        if (responseObject.new_date_name_rel && responseObject.new_date_value_rel)
         {
          zone_value_rel = $('span_'+ responseObject.new_date_name_rel +'_'+ objID + (webtvID ? '_'+ webtvID : '') +'_VALUE');
          if (zone_value_rel)
            zone_value_rel.innerHTML = responseObject.new_date_value_rel;

          zone_day_rel = $('span_'+ responseObject.new_date_name_rel +'_'+ objID + (webtvID ? '_'+ webtvID : ''));
          if (zone_day_rel)
            zone_day_rel.innerHTML = getDateStr(responseObject.new_date_value_rel * 1000);

          zone_hour_rel = $('span_hour_'+ responseObject.new_date_name_rel +'_'+ objID + (webtvID ? '_'+ webtvID : ''));
          if (zone_hour_rel)
            zone_hour_rel.innerHTML = getHourStr(responseObject.new_date_value_rel * 1000);
         }

        // Mise à jour de "la date à laquelle a été activée la date"
        if (zoneIsDatedFieldName)
          zoneIsDatedFieldName.innerHTML = isDatedFieldName ? getDateStr((new Date()).getTime()) : '';

        // On montre ou on cache certaines zones en fonction de la date qui vient d'être activée/modifiée/désactivée

        // Zone relative à la programmation de la date de publication
        var zoneDatePlanned = $('span_entire_date_'+ objPrefix +'_dateplanned_'+ objID + (webtvID ? '_'+ webtvID : ''));
        var zoneDatePlannedByUser = $('span_'+ objPrefix +'_dateplanned_BY_'+ objID + (webtvID ? '_'+ webtvID : ''));

        var vientDeDater = dateFinExists && newTimestampMySQL;
        var vientDePublier = dateFieldName == objPrefix +'_datepublished' && newTimestampMySQL;
        var vientDeDePublier = dateFieldName == objPrefix +'_datepublished' && !newTimestampMySQL;
        var vientDeProgrammer = dateFieldName == objPrefix +'_dateplanned' && newTimestampMySQL;
        var vientDeDeProgrammer = dateFieldName == objPrefix +'_dateplanned' && !newTimestampMySQL;

        if (zoneDatePlanned && vientDePublier)
          zoneDatePlanned.style.display = 'none';

        if (zoneDatePlanned && vientDeProgrammer)
         {
          zoneDatePlanned.fade('in');
          if (zoneDatePlannedByUser)
            zoneDatePlannedByUser.style.display = 'none';
         }

        if (zoneDatePlanned && vientDeDeProgrammer)
          zoneDatePlanned.fade('out');

        if (vientDeProgrammer)
         {
          var zoneDatePlanned_jour = $('span_'+ objPrefix +'_dateplanned_'+ objID + (webtvID ? '_'+ webtvID : ''));
          if (zoneDatePlanned_heure)
            zoneDatePlanned_jour.innerHTML = getDateStr(newTimestampMySQL * 1000);

          var zoneDatePlanned_heure = $('span_hour_'+ objPrefix +'_dateplanned_'+ objID + (webtvID ? '_'+ webtvID : ''));
          if (zoneDatePlanned_heure)
            zoneDatePlanned_heure.innerHTML = getHourStr(newTimestampMySQL * 1000);
         }

        // Zone "Dépublié par XXX, le YYY"
        var zoneDateUnPublished = $('span_unpublished_'+ objID + (webtvID ? '_'+ webtvID : ''));
        if (zoneDateUnPublished && vientDePublier)
          zoneDateUnPublished.fade('out');

        // Date à laquelle la vidéo a été livrée
        var zoneValueDateRealized = $('span_'+ objPrefix +'_daterealized_'+ objID + (webtvID ? '_'+ webtvID : '') +'_VALUE');
        var videoIsDelivered = !zoneValueDateRealized || zoneValueDateRealized.innerHTML != '' && zoneValueDateRealized.innerHTML != '0';
        if (!videoIsDelivered)
         {
          var today = new Date();
          var zoneEnRetard = $('span_'+ objPrefix +'_late_'+ objID + (webtvID ? '_'+ webtvID : ''));
          var zoneEnRetardBis = $('span_'+ objPrefix +'_late_bis_'+ objID + (webtvID ? '_'+ webtvID : ''));
          if (zoneEnRetard && vientDeDater)
            zoneEnRetard.style.display = newTimestampMySQL * 1000 < today.getTime() ? '' : 'none';
          if (zoneEnRetardBis && vientDeDater)
            zoneEnRetardBis.style.display = newTimestampMySQL * 1000 < today.getTime() ? '' : 'none';
         }

        // Avant que la zone de saisie disparaisse, on la prend comme repère pour savoir à quelle coordonnée Y afficher la confirmation des mails envoyés
        var offsetY = $('generic_zone_edit_date').offsetTop;

        $('loading_'+ dateFieldName).style.display = 'none';
        $('generic_zone_edit_date').style.display = 'none';

        // On retournera le résultat des notifications par mail (avec possibilité d annuler les envois de mails)
        if (responseObject.mails_control_html && responseObject.mails_control_html != '' && $('generic_zone_mails_control_html'))
         {
          $('generic_zone_mails_control_html').innerHTML = responseObject.mails_control_html;
          $('generic_zone_mails_control_html').style.top = offsetY;
          $('generic_zone_mails_control_html').fade('in');

          dateDebCptReboursMails = new Date();
          toMails = setInterval("majCpteReboursEnvoiMails();", 1000);
          if (self.majCpteReboursEnvoiMails) majCpteReboursEnvoiMails();
         }

        // Si changement de plage d'abonnement dans une page profil, on met à jour le nbre d'intervention dans cette plage
        if (responseObject.nb_events_as_speaker && $('zone_nb_events_as_speaker'))
          $('zone_nb_events_as_speaker').innerHTML = responseObject.nb_events_as_speaker;
       }
    }
  });
  request.send();
 }


// Jean 22/08/2011 : ouverture de l'écran d'édition d'un user
function userEdit (user_id, creerMembre, creerProspect,
                   creerCompte, inAnotherWindow, eventID,
                   closeAfter, accountUserID, refreshParentAfter,
                   webtv_url)
 {
  SocialEngine.Profile.infoBulle_hide_suite();

  var hauteurDoc = typeof( window.innerWidth ) == 'number' ? window.innerHeight : document.documentElement.clientHeight;
  if (hauteurDoc == 0) hauteurDoc = document.documentElement.offsetHeight;
  var largeurDoc = typeof( window.innerWidth ) == 'number' ? window.innerWidth : document.documentElement.clientWidth;
  if (largeurDoc == 0) largeurDoc = document.documentElement.offsetWidth;

  var editPageUrl = (webtv_url ? webtv_url+'/' : (SocialEngine.Profile.options.fromAdmin ? '../' : ''))
                   +'user_profile_edit.php?user_id='+ user_id
                   + (creerProspect ? '&prospect' : '')
                   + (creerMembre ? '&member' : '')
                   + (creerCompte ? '&account' : '')
                   + (closeAfter ? '&closeAfter' : '')
                   + (eventID ? '&event_id='+ eventID : '')
                   + (accountUserID ? '&account_user_id='+ accountUserID : '')
                   + (refreshParentAfter ? '&refreshParentAfter='+ refreshParentAfter : '');

   TB_init();

  if (inAnotherWindow)
    window.open(editPageUrl, '_blank');

  else
    TB_show(SocialEngine.Language.Translate(3000245), // "Modifier"
            editPageUrl +'&banner=no&TB_iframe=true&height='+ (hauteurDoc - 100) +'&width='+ (largeurDoc - 100),
            '',
            './images/trans.gif',
            1
     );
 }


// Jean 16/09/2011 : initialisation nouveau WYSIWYG
function initWYSIWYG (specificEditorID, p_theme, onComplete, maxHeight, p_skin, noAutoSave, noAutoGrowth, noAutoFocus, onchangeCallback, noRelativeUrls, height)
 {
  var tabOptions = {
    mode : specificEditorID ? "exact" : "specific_textareas",
    theme : p_theme ? p_theme : "advanced",
    skin : p_skin ? p_skin : "default",
    skin_variant: "default",
    plugins: "autolink,lists,pagebreak,style,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,wordcount,advlist,"+ (noAutoGrowth ? "" : ",autoresize") + (noAutoSave ? "" : ",autosave"),  // ,template,layer  // ,spellchecker

    theme_advanced_buttons1 : "save,newdocument,|,tablecontrols,|,hr,visualaid,|,charmap,emotions,iespell,media,advhr,|,print,|,removeformat,code,fullscreen", // ,styleselect => à remettre pour styles personnalisés  ,cleanup
    theme_advanced_buttons2 : "undo,redo,|,formatselect,fontselect,fontsizeselect,|,justifyleft,justifycenter,justifyright,justifyfull,|,attribs,visualchars,nonbreaking,template,pagebreak,|,insertdate,inserttime,preview", // ,anchor,help,restoredraft
    theme_advanced_buttons3 : "bold,italic,strikethrough,underline,|,sub,sup,|,forecolor,backcolor,|,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,image,|,link,unlink",  // ,|,ltr,rtl  , ,cut,copy,paste,pastetexty
    //theme_advanced_buttons4 : "", // insertlayer ,spellchecker   , ,|,styleprops,|,cite,abbr,acronym , moveforward,movebackward,absolute,del,ins
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : true,

    /*
    force_br_newlines : true,
    force_p_newlines : false,
    */

    content_css : "/"+ subdir +"templates/tinymce.css",

    // Style formats
    /*
    style_formats : [
      {title : 'Bold text', inline : 'b'},
      {title : 'Red text', inline : 'span', styles : {color : '#ff0000'}},
      {title : 'Red header', block : 'h1', styles : {color : '#ff0000'}},
      {title : 'Example 1', inline : 'span', classes : 'example1'},
      {title : 'Example 2', inline : 'span', classes : 'example2'},
      {title : 'Table styles'},
      {title : 'Table row 1', selector : 'tr', classes : 'tablerow1'}
    ],
    */

    language : "fr"
   };

  // Si c'est TEL zone qu'il faut transformer en WYSIWYG
  if (specificEditorID)
    tabOptions.elements = specificEditorID;

  // Sinon, par défaut, on se base sur la classe CSS
  else
    tabOptions.editor_selector = "tinymce_"+ p_theme;

  // Jean 17/01/2012 : finalement, on ne garde les url relatives nulle part
  //if (noRelativeUrls)
   {
    tabOptions.relative_urls = false;
    tabOptions.document_base_url = this_webtv_url;
    tabOptions.remove_script_host = false;
   }

  // Focus de suite sur telle WYSIWYG ?
  if (specificEditorID && !noAutoFocus)
    tabOptions.auto_focus = specificEditorID;

  // Hauteur max pour certains textarea ?
  tabOptions.theme_advanced_resizing_max_height = maxHeight ? maxHeight : 480;

  // Jean 26/01/2012
  if (height) tabOptions.height = height;

  // Fonction a exécuter quand le WYSIWYG est prêt
  if (onComplete)
    tabOptions.oninit = onComplete;

  // En cas de changement du contenu
  if (onchangeCallback)
    tabOptions.onchange_callback = onchangeCallback;

  // Jean 6 février 2012 - Pour que les balises <style> ne sautent pas
  tabOptions.valid_children = "+body[style]";

  tinyMCE.init(tabOptions);
 }

// Jean 19/09/2011
function scruteChatLive(commentType, eventID, lastCommentId)
 {
  var now = new Date();
  getComments(1, commentType);
 }

function strcmp(a, b)
 {
  if (a > b) return +1;
  if (a < b) return -1;
  return 0;
 }

// Jean 08/11/2011 : nouvelle interface avec le player
function executeJsCode(jsCode)
 {
  eval(jsCode);
 }

function onVideoEnd(timecode)
 {
  //if (jsd) alert(timecode);
 }

// Jean 13/11/2011 : transforme une liste de user_id séparés par des # en un tableau javascript
function toUserIdsJsTab(diesSep)
 {
  var tab1 = diesSep.split('#');
  var tab2 = new Array();
  for (var i=0; i<tab1.length; i++)
   {
    if (trim(tab1[i]) != '' && !isNaN(tab1[i]))
    tab2[tab2.length] = tab1[i];
   }
  return tab2;
 }

function redimPlayer(largeur)
 {
  var matches = $('video_player_container').innerHTML.match(/width=\"([0-9]+)\"/);
  if (!matches) return;

  var init_largeur = matches[1];
  var matches = $('video_player_container').innerHTML.match(/height=\"([0-9]+)\"/);
  if (!matches) return;

  var init_hauteur = matches[1];
  var ratio = init_largeur / init_hauteur;
  if (ratio == 0) return;

  var hauteur = largeur / ratio;
  J($('playerWCS')).css({width: largeur }).css({height: hauteur });
  //$('video_player_container').innerHTML = style.width = largeur +'px';
 }

// Jean 06/01/2012 : pour générer un mot de passe user
function randomcode(longueur)
 {
  var pass = '';
  for( i=0; i<longueur; i++ )
   {
    var rand_i = 58;
    while( rand_i >= 57 && rand_i <= 64 )
      rand_i = 48 + Math.floor(Math.random() * 42)
    car = String.fromCharCode(rand_i);
    pass += car;
   }
  return pass;
 }


// Jean 29/01/2012
function nothing() {
}

