JeS.cmp.chat =
{
  timestamp: -1,
  demarre: false,
  affichage: false,
  messages: [],
  /**
 * Initialisation
 */
  init: function()
  {
    // On crée qq réf
    this.chatBox = Ext.get("chatbox");
    this.chatBody = Ext.get("chat_body");
    this.chats = Ext.get("chats");
    this.loading = Ext.get("chat_loading");
    
    // On cache le chat
    this.chatBody.setVisibilityMode(2);
    this.chatBody.setVisible(false);
    
    if(JeS.cp.get("chat_open"))
    {
      Ext.fly("chat_body").setDisplayed("block");
      Ext.fly("chat_toggle").update("-");
      this.charger();
    }
    
    // Gestion du cacher/montrer de la chatbox    
    Ext.fly("chat_barre").on("click", function()
    {
      if (this.chatBody.isVisible()) 
        this.cacherChat();
      else 
        this.afficherChat();
    }, this);
    
    
    var listeners = 
    {
      "keypress": 
      {
        fn: this.messageVide,
        buffer: 100
      },
      "change": this.messageVide,
      scope: this
    }
    
    // Décoration de quelques élements
    this.chatboxLogin = new Ext.form.TextField(
    {
      applyTo: "chat_login",
      emptyText: "Pseudo...", value: JeS.cp.get("chat_id", ""),
      maxLength: 32, enableKeyEvents: true,
      listeners: 
      {
        "change": function(champ)
        {
          JeS.cp.set("chat_id", champ.getValue());
          this.messageVide();
        },
        scope: this
      }
    });
    this.chatboxInput = new Ext.form.TextField(
    {
      applyTo: "chat_texte",
      emptyText: "Entrez votre message...", value: "",
      maxLength: 255, enableKeyEvents: true,
      listeners: 
      {
        "change": this.messageVide,
        "keypress": function(champ, evt)
        {
          var touche = evt.getKey();
          if (!this.messageVide() && touche == evt.ENTER || touche == evt.NUM_CENTER) this.poster();
        },
        scope: this
      }
    });
    
    this.chatBouton = new Ext.Button(
    {
      renderTo: "chat_bouton", scope: this, text: "Envoyer",
      height: 30, disabled: true,
      handler: function()
      {
        this.poster();
      }
    });
  },
  afficherChat: function()
  {
    this.chatBody.slideIn("t", 
    {
      easing: "easeOut",
      duration: 0.5,
      scope: this,
      callback: function()
      {
        if (!this.demarre) this.charger();
        Ext.fly("chat_toggle").update("-");
        JeS.cp.set("chat_open", true);
      }
    });
  },
  cacherChat: function()
  {
    this.chatBody.slideOut("t", 
    {
      easing: "easeOut",
      duration: 0.5,
      scope: this,
      callback: function()
      {
        this.stop();
        Ext.fly("chat_toggle").update("+");
        JeS.cp.set("chat_open", false);
      }
    });
  },
  messageVide: function()
  {
    if (this.chatboxInput.isDirty() && !this.chatboxLogin.getValue() == "") 
    {
      this.chatBouton.setDisabled(false);
      return false;
    }
    this.chatBouton.setDisabled(true);
    return true;
  },
  /**
 * Démarre le chargement des messages
 */
  charger: function()
  {
    if (!this.chatBody.isVisible()) 
    {
      this.demarre = false;
      return;
    }
    if (!this.demarre) this.loading.setVisible(true);
    this.demarre = true;
    
    Ext.Ajax.abort();
    Ext.Ajax.request(
    {
      url: "/chat/charger/",
      scope: this,
      params: 
      {
        timestamp: Ext.encode(this.timestamp)
      },
      success: function(response)
      {
        var data = Ext.decode(response.responseText)
        if (data) this.afficherMessages(data);
        
        new Ext.util.DelayedTask(this.charger, this).delay(5000);
      },
      failure: function()
      {
        new Ext.util.DelayedTask(this.charger, this).delay(5000);
      },
      callback: function()
      {
        this.loading.setVisible(false);
      }
    });
  },
  poster: function()
  {
    this.loading.setVisible(true);
    
    var user = this.chatboxLogin.getValue();
    var msg = this.chatboxInput.getValue();
    this.chatBouton.setDisabled(true);
    this.chatboxInput.setValue("");
    
    Ext.Ajax.abort();
    Ext.Ajax.request(
    {
      url: "/chat/post/",
      scope: this,
      params: 
      {
        user: user,
        msg: msg,
        id: Math.round(1e10 * Math.random())
      },
      success: function(response)
      {
        var data = Ext.decode(response.responseText)
        if (data) this.afficherMessages(data);
        this.chatBouton.setDisabled(false);
      },
      callback: function()
      {
        this.loading.setVisible(false);
        this.charger();
      }
    })
  },
  stop: function()
  {
    Ext.Ajax.abort();
    this.demarre = false;
  },
  
  afficherMessages: function(reponse)
  {
    if (this.affichage)           
      return;
    
    this.affichage = true;
    this.timestamp = reponse.timestamp;
    this.messages = reponse.messages || [];
    
    this.pre_scroll();
        
    var liste = Ext.get("liste_chats");
    Ext.each(this.messages, function(message)
    {
      var el = Ext.get("msg_" + message.id);
      if (!el) 
      {
        liste.createChild(
        {
          tag: "li",
          id: "msg_" + message.id,
          html: String.format("{0} - <b>{1}</b> : {2}", new Date(message.timestamp).format("j/m G:i"), message.user, message.msg)
        });
      }
    }, this);
    var messages_courant = Ext.DomQuery.select("li", liste);
    Ext.each(messages_courant, function(message)
    {
      if (!this.messages[message.id]) message.remove();
    }, this);
    
    this.scroll();
    
    this.affichage = false;
  },
  
  pre_scroll: function()
  {
    var dom = this.chats.dom;
    if (dom.scrollTop + dom.offsetHeight > dom.scrollHeight - 20) 
      this._hasScrolled = true;
    else 
      this._hasScrolled = false;
  },
  scroll: function()
  {
    if (this._hasScrolled) this.chats.scrollTo("top", this.chats.dom.scrollHeight);
  }
}

