JeS.cmp.soireeEdit =
{ 
  data: {},
  
  init: function()
  {
    Ext.QuickTips.init();
    
    this.initIcons();
    this.initButtons();
    this.initDurees();
  },
  initButtons: function()
  {
    var boutonsNote = Ext.DomQuery.select("div[class^=bouton]");
    Ext.each(boutonsNote, function(bouton)
    {
      new Ext.Button(
      {
        renderTo: bouton, text: "Ajouter un joueur",
        handler: function()
        {
          var b = Ext.get(bouton);
          this.ajouter({ idPartie: b.getAttributeNS("jes", "partie"), jeu: b.getAttributeNS("jes", "jeu")});
        },
        scope: this
      });
    }, this);
    
    var b =  Ext.get("ajout_remarque");
    new Ext.Button(
    {
      renderTo: Ext.fly("ajout_remarque"), text: "Ajouter une remarque",
      handler: function()
      {
        this.data.type = "remarque";
        this.data.id = b.getAttributeNS("jes", "soiree");
        this.data.mode = "ajout";
        this.afficherDialog();
      },
      scope: this
    });
  },
  initDurees: function()
  {
    var getId = function(el)
    {
      return el.id.match(/^duree-wrapper-(\d+)$/)[1];
    }
    
    var durees = Ext.DomQuery.select("div[id^=duree-wrapper-]");
    Ext.each(durees, function(duree)
    {
      var id = getId(duree);
      var icon = Ext.get("edit-duree-" + id);
      Ext.fly(duree).on({
        "mouseover": function()
        {
          icon.setVisible(true);
        },
        "mouseout": function()
        {
          icon.setVisible(false);
        }
      });
      icon.on("click",
      function()
      {
        var duree = Ext.get("duree-" + id);
        var editor = new Ext.Editor(new Ext.form.TextField({ 	selectOnFocus: true }),
        {
          cancelOnEsc: true, completeOnEnter: true, ignoreNoChange: true,
          listeners:
          {
            "complete": function(editor, value)
            {
              Ext.Ajax.request(
              {
                url: "/soirees/editer",
                params: { champ: "duree", valeur: value, id: id },
                success: function()
                {
                  duree.dom.innerHTML = value;
                },
                failure: JeS.erreurCommunication
              });
            }
          }
        });
        editor.startEdit(duree);
      });
    });
  },
  initIcons: function()
  {
    var notes = Ext.DomQuery.select("*[id^=note_]");
    var that = this;
    var getId = function(el)
    {
      return el.id.match(/^.*_(\d+)$/)[1];
    }
        
    Ext.each(["note", "commentaire", "remarque"], function(type)
    {
      var list = Ext.DomQuery.select("*[id^="+ type +"_]");
      Ext.each(list, function(item)
      {
        Ext.fly(item).removeAllListeners();
        Ext.fly(item).on({
          "mouseover": function()
          {
            var item = Ext.get(this);
            Ext.fly("edit_" + type + "_" + getId(item)).setVisible(true);
          },
          "mouseout": function()
          {
            var item = Ext.get(this);
            Ext.fly("edit_"+ type +"_" + getId(item)).setVisible(false);
          }
        });
      });
    });
  },
  
  afficherDialog: function()
  {
    var fields;
    var toggleEnvoi = function(state)
    {
      if(!state) Ext.getCmp("dialog-appliquer").setDisabled(true);
      else Ext.getCmp("dialog-appliquer").setDisabled(false);
    }
    var checkErreurs = function()
    {
      var state = true;
      Ext.each(fields, function(field)
      {
        if(!Ext.getCmp(field.id).isValid(true))
        {
          state = false;
          return false;
        }
      });
      toggleEnvoi(state);
      
      Ext.getCmp("dialog").syncSize();
    }
    
    var title = "Ajout/Edition de commentaire";
    var comboStore = new Ext.data.SimpleStore(
    {
      autoLoad: true, url: "soirees/charger_joueurs",
      fields: ["nom"], autoDestroy: true
    });
    fields =
    [
      {
        xtype: "combo", id: "dialog-joueur", fieldLabel: "Joueur ",
        store: comboStore, triggerAction: "all", mode: "local",
        typeAhead: true, displayField: "nom", valueField: "nom",
        msgTarget: "under", invalidText: "Ce champ doit contenir entre 2 et 32 caractères",
        value: this.data.joueur || JeS.cp.get("joueur_id", ""), allowBlank: false, blankText: "Ce champ doit contenir entre 2 et 32 caractères",
        validator: function(value)
        {
          return (value.length >= 2 && value.length < 32);
        },
        listeners: {"valid": checkErreurs, "invalid": checkErreurs }
      }
    ]
    if(this.data.type == "note")
    {
      title = String.format("Ajout/Edition de note sur {0}", this.data.jeu);
      fields.push(
      {
        xtype: "textfield", id: "dialog-note", fieldLabel: "Note ",
        msgTarget: "under", invalidText: "Ce champ doit contenir un nombre entre 1 et 10",
        value: this.data.note || "", allowBlank: true, enableKeyEvents: true,
        validator: function(value)
        {
          /*
           * SEB 12/08/09: A la demande d'Antoine B. je modifie la validation de la note.
           * Il est maintenant possible de rentrer une note vide.
           */
          return value != "" ? isNaN(value) || value < 1 || value > 10 ? false : true : true;
        },
        listeners:
        {
          // Force les virgules en point
          "keydown": function(field, e)
          {
            if (e.getCharCode() == 188) // Virgule
            {
              e.stopEvent();
              field.setValue(field.getValue()+".");
            }
          },
          "valid": checkErreurs,
          "invalid": checkErreurs
        }
      });
    }
    
    if(!Ext.isIE6)
    {
      fields.push({
        xtype: "htmleditor", id: "dialog-commentaire", fieldLabel: "Commentaire ",
        width: 360, height: 250, value: this.data.commentaire || "",
        enableAlignments: false, enableFont: false
      });
    }
    else
    {
      fields.push({
        xtype: "textarea", id: "dialog-commentaire", fieldLabel: "Commentaire ",
        width: 360, height: 250, value: this.data.commentaire ? Ext.util.Format.htmlDecode(Ext.util.Format.stripTags(this.data.commentaire)) : ""
        
      });
    }
    
    var title;
    this.win = new Ext.Window(
    {
      title: title, width: 500, autoHeight: true,
      modal: true, constrain: true, resizable: false, layout: "anchor", id: "dialog",
      items: new Ext.FormPanel(
      {
        border: false, baseCls: "plain", bodyStyle: "padding: 10px; background-color: #ccff99",
        items: fields
      }),
      buttons:
      [
        { text: "Appliquer", id: "dialog-appliquer", disabled: true, handler: function() { this.envoyer() } , scope: this },
        { text: "Annuler", id: "dialog-annuler", handler: function() { this.win.close() }, scope: this}
      ],
      listeners: { "destroy": function()
      {
        delete this.win;
        this.data = {}
      }, scope: this}
    });
    
    Ext.each(fields, function(field)
    {
      Ext.getCmp(field.id).validate();
    });
    
    this.data.fields = fields;
   
    this.win.show();
  },
  
  ajouter: function(conf)
  {
    this.data =
    {
      idPartie: conf.idPartie,
      id: conf.id,
      jeu: conf.jeu,
      type: "note",
      mode: "ajout"
    }
    this.afficherDialog();
  },
  
  editer: function(conf)
  {
    this.chargerDetails(conf.id, conf.type, function(response)
    {
      var data = Ext.decode(response.responseText);
      this.data = 
      {
        joueur: data.joueur,
        jeu: data.jeu,
        note: data.note,
        commentaire: data.commentaire,
        id: data.id,
        idPartie: data.idPartie,
        type: conf.type,
        mode: "edition"
      }
      this.afficherDialog();
    });
  },
  
  supprimer: function(id, type)
  {
    var mask = JeS.creerMask();
    this.chargerDetails(id, type, function(response)
    {
      var data = Ext.decode(response.responseText);
      var msg;
      if(type == "note")
        msg = String.format("Etes-vous sûr de vouloir supprimer la note et le commentaire de {0} à propos de {1} ?", data.joueur, data.jeu);
      else msg = String.format("Etes-vous sûr de vouloir supprimer la remarque de {0} ?", data.joueur);
      var confirmation = confirm(msg);
      if(confirmation)
      {
        Ext.Ajax.request(
        {
          url: "/soirees/"+ type +"/supprimer",
          params: { id: id }, scope: this,
          failure: function()
          {
            JeS.erreurCommunication();
            mask.remove();
          },
          success: function()
          {
            if(type == "note")
            {
              // Suppression de la note et du commentaire
              Ext.fly("note_" + id).remove();
              var comment = Ext.get("commentaire_" + id);
              if(comment) comment.remove();
              
              this.supprimerJoueur(data);
            }
            else
            {
              Ext.fly("remarque_" + id).remove();
            }
            
            mask.remove();
          }
        });
      }
      else mask.remove();
    });
  },
  
  envoyer: function()
  {
    var values = {}
    Ext.each(this.data.fields, function(field)
    {
      // Hack atroce pour IE6
      if(Ext.isIE6 && field.id == "dialog-commentaire")
      {
        values[field.id] = String.trim(Ext.util.Format.nl2br(Ext.getCmp(field.id).getValue()));
      }
      else values[field.id] = String.trim(Ext.getCmp(field.id).getValue());
    }); 
    
    // Convertir "<br>" et "<p></p>" seul en ""
    if(/^<br>|<p><\/p>$/i.test(values["dialog-commentaire"])) values["dialog-commentaire"] = "";
    
    var url = String.format("/soirees/{0}/{1}", this.data.type, (this.data.mode || "ajout"));
    var params = { joueur: values["dialog-joueur"], commentaire: values["dialog-commentaire"] }
    if(this.data.type == "note")
    {
      params.note = values["dialog-note"];
      params.partie = this.data.idPartie;
    }
    params.id = this.data.id;
    
    Ext.Ajax.request(
    {
      url: url,
      params: params,
      scope: this,
      success: function(response)
      {
        JeS.cp.set("joueur_id", values["dialog-joueur"]);
        var errorCodes =
        {
          "NO_ERROR": 0,
          "NOTE_COMMENTAIRE_EXISTS": 1,
          "PARTIE_NOT_EXISTS": 2,
          "NOTE_OR_JOUEUR_INVALID": 3
        }
        
        var result = Ext.decode(response.responseText);
        if(result.error == errorCodes["NO_ERROR"])
        {
          if(this.data.type == "note")
          {
            this.data.id = result.id;
            if(this.data.mode  != "edition")
              this.ajouterJoueur(values);
            else this.afficherNoteCommentaire(values);
          }
          else
          {
            this.data.id = result.id;
            this.afficherRemarque(values);
          }
          
          this.initIcons();
          this.win.close();
        }
        else if(result.error == errorCodes["NOTE_COMMENTAIRE_EXISTS"])
        {
          alert(String.format("Il existe déjà une note et un commentaire pour le joueur {0}.\nVeuillez modifier l'existant ou utiliser un autre nom de joueur.", values["dialog-joueur"]));
        }
        else JeS.erreurCommunication();
      },
      failure: JeS.erreurCommunication
    });
  },
  
  afficherNoteCommentaire: function(values)
  {
    var note, comment;
    
    note = this.afficherNote(values);
    
    if(values["dialog-commentaire"].length > 0)
      comment = this.afficherCommentaire(values);
    else
    {
      var c = Ext.get("commentaire_"+ this.data.id);
      if(c) c.remove();
    }
    
    var el = values["dialog-commentaire"].length == 0 ? Ext.get(note) : Ext.get(comment); 
    var b = Ext.getBody();
    
    setTimeout(function()
    {
      el.scrollIntoView();
      el.highlight();
    }, 100);
  },
  
  ajouterJoueur: function(values)
  {
    // Liste générale
    var listeJoueurs = Ext.get("liste_joueurs");
    if(listeJoueurs.dom.innerHMTL == "Aucun") listeJoueurs.update("");
    var joueursArray = listeJoueurs.dom.innerHTML.split(", ");
    if(joueursArray.indexOf(values["dialog-joueur"]) == -1)
      listeJoueurs.dom.innerHTML += ", " + values["dialog-joueur"];
      
    var nb_joueurs = Ext.get("nb_joueurs_" + this.data.idPartie);
    nb_joueurs.dom.innerHTML = Number(nb_joueurs.dom.innerHTML) + 1;
    
    this.afficherNoteCommentaire(values);
  },
  
  supprimerJoueur: function(data)
  {
    // Le joueur apparaît-il dans une autre partie ?
    var result = Ext.DomQuery.select("li[id^=note_]");
    var found = false;
    Ext.each(result, function(res)
    {
      if(res.innerHTML.indexOf(data.joueur +" :") != -1)
      {
        found = true;
        return false;
      }
    });
    
    if(!found)
    {
      // Suppression de la liste des joueurs
      var joueurs = Ext.fly("liste_joueurs").dom.innerHTML;
      joueurs = joueurs.split(", ");
      var copy = joueurs.slice();
      Ext.each(copy, function(joueur)
      {
        if(joueur == data.joueur) 
        {
          joueurs.remove(data.joueur);
          return false;
        }
      });
      Ext.fly("liste_joueurs").dom.innerHTML = joueurs.join(", ");
    }
    
    var nb_joueurs = Ext.get("nb_joueurs_" + data.idPartie);
    nb_joueurs.dom.innerHTML = Number(nb_joueurs.dom.innerHTML) - 1;
  },
  
  afficherNote: function(values)
  {
    var editer = "editer(" + this.data.idPartie + "," + this.data.id +", 'note')";
    var supprimer = "supprimer(" + this.data.id +", 'note')";
    var action = this.data.mode == "ajout" ? "append" : "overwrite";
    
    var children =
    [
      { tag: "b", html: values["dialog-joueur"] + " : "},
      { tag: "span", html: values["dialog-note"] || "-"},
      {
        tag: "span", id: "edit_note_" + this.data.id, style: "visibility: hidden;",
        children:
        [
          { tag: "img", src: MEDIA_URL + "images/icons/pencil.png", cls: "note-edit", onclick: editer },
          { tag: "img", src: MEDIA_URL + "images/icons/cross.png", cls: "note-edit", onclick: supprimer }
        ]
      }
    ]
    
    if(action=="overwrite") return Ext.DomHelper[action]("note_" + this.data.id, { children: children });
    
    return Ext.DomHelper[action]("liste_notes_" + this.data.idPartie, {
      tag: "li", id: "note_" + this.data.id, children: children
    });
  },
  afficherCommentaire: function(values)
  {
    var editer = "editer(" + this.data.idPartie + "," + this.data.id +", 'note')";
    var supprimer = "supprimer(" + this.data.id +", 'note')";
    var action = this.data.mode == "ajout" ? "append" : "overwrite";
    
    var children =
    [
      { tag: "b", html: values["dialog-joueur"] + " :"},
      {
        tag: "span", id: "edit_commentaire_"+ this.data.id, style: "visibility: hidden;",
        children:
        [
          { tag: "img", src: MEDIA_URL + "images/icons/pencil.png", cls: "note-edit", onclick: editer },
          { tag: "img", src: MEDIA_URL + "images/icons/cross.png", cls: "note-edit", onclick: supprimer }
        ]
      },
      { tag: "div", cls: "commentaire", html: values["dialog-commentaire"] }
    ]
    
    if(action=="overwrite")
    {
      if(!Ext.fly("commentaire_"+ this.data.id))
        action = "append";
      else return Ext.DomHelper[action]("commentaire_"+ this.data.id, { children: children });
    }
    
    return Ext.DomHelper[action]("liste_commentaires_" + this.data.idPartie, {
      tag: "li", id: "commentaire_"+ this.data.id, children: children
    });
  },
  
  afficherRemarque: function(values)
  {
    var editerRemarque = "editer(null, " + this.data.id +", 'remarque')";
    var supprimerRemarque = "supprimer(" + this.data.id +", 'remarque')";
    var action = this.data.mode == "ajout" ? "append" : "overwrite";
    
    var children =
    [
      { tag: "b", html: values["dialog-joueur"] + " :"},
      {
        tag: "span", id: "edit_remarque_"+ this.data.id, style: "visibility: hidden;",
        children:
        [
          { tag: "img", src: MEDIA_URL + "images/icons/pencil.png", cls: "note-edit", onclick: editerRemarque },
          { tag: "img", src: MEDIA_URL + "images/icons/cross.png", cls: "note-edit", onclick: supprimerRemarque }
        ]
      },
      { tag: "div", cls: "commentaire", html: values["dialog-commentaire"] }
    ]
    
    if(action=="overwrite")
    {
      if(!Ext.fly("remarque_"+ this.data.id))
        action = "append";
        
      return Ext.DomHelper[action]("remarque_"+ this.data.id, { children: children });
    }
    
    return Ext.DomHelper[action]("liste_remarques", {
      tag: "li", id: "remarque_"+ this.data.id, children: children
    });
  },
  
  chargerDetails: function(id, type, cb)
  {
    Ext.Ajax.request(
    {
      url: "/soirees/" + type + "/details",
      params: { id: id },
      success: cb, scope: this,
      failure: JeS.erreurCommunication
    });
  }
}

/**
 * Wrappers dans namespace global
 */
function ajouter(idPartie, jeu)
{
  JeS.cmp.soireeEdit.ajouter.call(JeS.cmp.soireeEdit, { idPartie: idPartie, jeu: jeu });
}

function editer(idPartie, id, type)
{
  JeS.cmp.soireeEdit.editer.call(JeS.cmp.soireeEdit, { idPartie: idPartie, id: id, type: type });
}

function supprimer(id, type)
{
  JeS.cmp.soireeEdit.supprimer.call(JeS.cmp.soireeEdit, id, type);
}


function toggleBareme()
{
  var b = Ext.get("bareme");
  b.setVisibilityMode(2);
  var action = b.isVisible() ? "slideOut" : "slideIn";
  
  b[action]("t", 
  {
    easing: "easeOut",
    duration: 0.5,
    callback: function()
    {
      var v = b.isVisible();
      Ext.fly("bareme_toggle").update(v ? "(cacher)" : "(afficher)").set({"title": v ? "Cacher le barême" : "Afficher le barême"});
    }
  });
}

