Subversion Repositories eFlore/Applications.cel

Rev

Rev 461 | Blame | Last modification | View Log | RSS feed

package org.tela_botanica.client.vues.observation;

// TODO Detecter redim et supprimer ajuster

import java.util.Date;
import java.util.Iterator;

import org.tela_botanica.client.CarnetEnLigneMediateur;
import org.tela_botanica.client.Util;
import org.tela_botanica.client.interfaces.Rafraichissable;
import org.tela_botanica.client.modeles.Configuration;
import org.tela_botanica.client.modeles.EntiteGeographiqueObservation;
import org.tela_botanica.client.modeles.ListeObservation;
import org.tela_botanica.client.modeles.ListeReferentielCommune;
import org.tela_botanica.client.modeles.ListeReferentielNom;
import org.tela_botanica.client.modeles.Observation;
import org.tela_botanica.client.modeles.ReferentielCommune;
import org.tela_botanica.client.modeles.ReferentielNom;
import org.tela_botanica.client.observation.ObservationMediateur;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HTML;
import com.gwtext.client.core.EventCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Ext;
import com.gwtext.client.core.ExtElement;
import com.gwtext.client.core.Function;
import com.gwtext.client.core.ListenerConfig;
import com.gwtext.client.core.Position;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.MemoryProxy;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.SimpleStore;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.BoxComponent;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Component;
import com.gwtext.client.widgets.Container;
import com.gwtext.client.widgets.DatePicker;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.ToolTip;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.event.ContainerListenerAdapter;
import com.gwtext.client.widgets.event.DatePickerListenerAdapter;
import com.gwtext.client.widgets.event.PanelListenerAdapter;
import com.gwtext.client.widgets.form.ComboBox;
import com.gwtext.client.widgets.form.DateField;
import com.gwtext.client.widgets.form.Field;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.Label;
import com.gwtext.client.widgets.form.MultiFieldPanel;
import com.gwtext.client.widgets.form.TextArea;
import com.gwtext.client.widgets.form.TextField;
import com.gwtext.client.widgets.form.event.ComboBoxCallback;
import com.gwtext.client.widgets.form.event.ComboBoxListener;
import com.gwtext.client.widgets.form.event.ComboBoxListenerAdapter;
import com.gwtext.client.widgets.form.event.TextFieldListener;
import com.gwtext.client.widgets.form.event.TextFieldListenerAdapter;
import com.gwtext.client.widgets.layout.AnchorLayoutData;
import com.gwtext.client.widgets.layout.ColumnLayout;
import com.gwtext.client.widgets.layout.ColumnLayoutData;
import com.gwtext.client.widgets.layout.FormLayout;
import com.gwtext.client.widgets.layout.RowLayout;
import com.gwtext.client.data.Record;

/**
 * Panneau contenant les infos, les métadonnées et l'arbre des mots clés, il implémente l'interface rafraichissable
 * @author aurelien
 *
 */
public class FormulaireSaisieObservationVue extends Panel implements Rafraichissable  {


        /**
         * Le médiateur associé à la vue
         */
        private ObservationMediateur    observationMediateur            = null;
        
        FormPanel panneauFormulaire = null;

        private DateField date = null;
        private TextField lieudit = null;
        private TextField station = null;
        private TextField milieu = null;
        private TextField comment = null;
        private ComboBox  commune = null;
        private String departement = null;
        private ComboBox  espece = null;
        private String numeroNom = null;
        private String numeroOrdre = null;
        
        private String referentielGeo = null;

        // Pour remise a zero partielle lors d'une validation
        
        private  enum Champs {
            DATE, LIEUDIT, STATION, MILIEU, COMMENT, COMMUNE, ESPECE, TOUT, LATITUDE, LONGITUDE ;
            
            public String toString() {
                
                switch(this) {
                case DATE:
                        return "date";
                        
                case COMMUNE:
                        return "commune";
                
                case LIEUDIT:
                        return "lieu dit";
                
                case STATION:
                        return "station";
                
                case MILIEU:
                        return "milieu";
                
                case COMMENT:
                        return "commentaire";
                
                case ESPECE:
                        return "espèce";
                        
                case LATITUDE:
                        return "latitude";
                        
                case LONGITUDE:
                        return "longitude";
                
                case TOUT:
                        return "date, commune, lieu dit, station, milieu, espèce, commentaire, latitude, longitude";
                }
                        return TOUT.toString();
            }
        };
        
        private String formatDate = null ;
        private Button boutonOK = new Button("Créer");
        private Button boutonAnnuler = new Button("Réinitialiser");

        private boolean selectionCommune=false;
        private boolean selectionEspece=false;
        
        private boolean modification = false ;
        private Toolbar bt = null ;
        
        private final String VALEURS_MULTIPLES = "(Valeurs multiples)";
        private final String modeleMessageModif = "commune:lieu-dit:station:milieu:latitude:longitude:date:espece:commentaire";
        private boolean communeModifiee = false;
        private boolean lieuDitModifie = false;
        private boolean stationModifiee = false;
        private boolean milieuModifie = false;
        private boolean dateModifiee = false;
        private boolean especeModifiee = false;
        private boolean commModifie = false;
        
        
        private final int KEY_ALT = 18;
        private final int KEY_BACKSPACE = 8;
        private final int KEY_CTRL = 17;
        private final int KEY_DELETE = 46;
        private final int KEY_DOWN = 40;
        private final int KEY_END = 35;
        private final int KEY_ENTER = 13;
        private final int KEY_ESCAPE = 27;
        private final int KEY_HOME = 36;
        private final int KEY_LEFT = 37;
        private final int KEY_PAGEDOWN = 34;
        private final int KEY_PAGEUP = 33;
        private final int KEY_RIGHT = 39;
        private final int KEY_SHIFT = 16;
        private final int KEY_TAB = 9;
        private final int KEY_UP = 38;
        
        
        /**
         * Combobox permettant de selectionner le mode
         * modification ou bien création
         */
        private ComboBox selecteurMode = new ComboBox();
        
        Store storeMode = null ;

        /**
         * Booleen d'instanciation
         */
        boolean estInstancie = false ;

        private Panel panneauIntermediaire;

        private Panel panneauPremierColonne;

        private Panel panneauSecondeColonne;

        private boolean masseModification =false ;

        private TextField longitude;

        private TextField latitude;

        private MultiFieldPanel coordPanel;

        private TextField coordonnees;
        
        private Label lienSelectionCommune = null;

        private HTML accesformulaire;

        private HTML basculerverscarto;
        
        private boolean longlatAjoutee;

        private boolean latModifiee;

        private boolean longModifiee;

        protected boolean rechercheCommuneEnCours = false;

        private Timer tCoord;
        
        /**
         * Constructeur sans argument (privé car ne doit pas être utilisé)
         */
        @SuppressWarnings("unused")
        private FormulaireSaisieObservationVue()
        {
                super() ;
        }
        
        /**
         * Constructeur avec argument
         * @param im
         */
        public FormulaireSaisieObservationVue(ObservationMediateur obs)
        {
                
                super("Saisie");
                // on associe le médiateur
                observationMediateur = obs ;
                
                
                panneauFormulaire = new FormPanel(Position.RIGHT);
                panneauFormulaire.setBorder(false);
                
                
                
                // Panneau intermediaire qui contient deux colonnes de formulaire
                
                panneauIntermediaire = new Panel();  
                
                if (Window.getClientWidth()> Window.getClientHeight()) {
                        panneauIntermediaire.setLayout(new ColumnLayout()); 
                }
                else {
                        panneauIntermediaire.setLayout(new RowLayout()); 
                }
                
                panneauIntermediaire.setBorder(false);

                //création du panneau formulaire de gauche auquels on ajoute les champs
                panneauPremierColonne = new Panel();  
                panneauPremierColonne.setLayout(new FormLayout());  
                panneauPremierColonne.setBorder(false);

                //création du panneau formulaire de droite
            panneauSecondeColonne = new Panel();  
                panneauSecondeColonne.setLayout(new FormLayout());  
                panneauSecondeColonne.setBorder(false);
                                
                this.setPaddings(5) ;
        
                // Accesskey pour debugging
                commune=new ComboBox("Commune","commune\" accesskey=\"1");  
                
                final String resultTplCommune = "<div class=\"search-item-commune\">{commune}</div>";  
                commune.setTpl(resultTplCommune);
                commune.setMode(ComboBox.REMOTE);
                // commune.setPageSize(10); // Ne fonctionne pas 
                commune.setItemSelector("div.search-item-commune");
                commune.setTypeAhead(true);  
                commune.setLoadingText("Recherche...");  
                  
                commune.setHideTrigger(true);
                //commune.setTabIndex(1);
                
                  //création du lien "Accès carto" dans le formulaire 
                basculerverscarto = new HTML(" <a id=\"lien_carto\" href=\"#\" tabindex=\"2\">Localiser</a>");
                basculerverscarto.addStyleName("lien_actif");
                
                //création info bulle sur le lien "accès carto"
                ToolTip tip2 = new ToolTip();  
                tip2.setHtml("Via une carte, obtenez les coordonnées (latitude/longitude) de votre observation ");  
                tip2.applyTo(basculerverscarto.getElement());
                
                //Sur une meme ligne, ajout de plusieurs champs
                final MultiFieldPanel htmlCommunePanel = new MultiFieldPanel(); 
                
                htmlCommunePanel.addToRow(commune,new ColumnLayoutData(0.7)); 
                htmlCommunePanel.addToRow(basculerverscarto,new ColumnLayoutData(0.3)); 

                htmlCommunePanel.setBorder(false);
                htmlCommunePanel.setId("x-commune-panel"); 

                panneauPremierColonne.add(htmlCommunePanel);

            station = new TextField("Station", "station");  
            station.setAllowBlank(true);

            panneauPremierColonne.add(station, new AnchorLayoutData("95%"));  
            
                latitude = new TextField("Lat", "x");
                latitude.setGrowMax(70);
                latitude.setAllowBlank(true);
            
            longitude = new TextField("Lon", "y");
            longitude.setGrowMax(70);
                longitude.setAllowBlank(true);
                                
                lienSelectionCommune = new Label("");
                
                
                lienSelectionCommune.setId("conteneur_selection_commune");
                lienSelectionCommune.setStyleName("conteneur_selection_commune");
                lienSelectionCommune.addStyleName("lien_actif");
                        
                // Panneau de type plusieurs champs de formulaire sur une meme ligne, où seront renseignés X/Y
                coordPanel = new MultiFieldPanel(); 
                coordPanel.setPaddings(0, 0, 0, 10);
                coordPanel.setVisible(false);
                
                final double largeur ;
                largeur = 120;
                                
                coordPanel.addToRow(latitude, new ColumnLayoutData(largeur)); 
                coordPanel.addToRow(longitude, new ColumnLayoutData(largeur));  
                coordPanel.addToRow(lienSelectionCommune, new ColumnLayoutData(largeur)); 
                lienSelectionCommune.addClass("lien_decale");
                coordPanel.setBorder(false);
                
                  //création du champs coordonnées    
                referentielGeo = Configuration.getReferentielGeo();
                
                coordonnees = new TextField("Coordonnées", "", 0);
                coordonnees.setMaxLength(0);
                coordonnees.setReadOnly(true);
                coordonnees.setCls("fieldname");
                
                //création du lien "saisie X/Y" dans le formulaire
                accesformulaire = new HTML("<a id=\"lien_coord\" href=\"#\" tabindex=\"6\">Saisie Lat/Lon ("+referentielGeo+")</a>");
                accesformulaire.setWidth("100%");
                accesformulaire.addStyleName("lien_actif");
                        
                //création info bulle sur le lien "saisie X/Y"
                        ToolTip tip1 = new ToolTip();  
                        tip1.setHtml("Lat / Lon sont les latitudes / longitudes, à remplir en degrés décimaux");  
                        tip1.applyTo(accesformulaire.getElement());
                        
                        //ajout d'un listener sur le lien "saisie X/Y"
                        
                        coordPanel.addListener(new PanelListenerAdapter() {
                                
                                public void onAfterLayout(Container c) {
                                        ExtElement lienCoord = Ext.get("lien_coord");
                                        lienCoord.removeAllListeners();
                                        lienCoord.addListener("click", new EventCallback() {
                                                public void execute(EventObject e) {
                                                        
                                                        coordPanel.setVisible(!coordPanel.isVisible());
                                                        
                                                        if(Ext.isIE()) {
                                                                latitude.focus();
                                                        }
                                                        
                                                        CarnetEnLigneMediateur.fireResize();
                                                }
                                        }) ;
                                
                                        ExtElement lienCarto = Ext.get("lien_carto");
                                        lienCarto.removeAllListeners();
                                        lienCarto.addListener("click", new EventCallback() {

                                                public void execute(EventObject e) {
                                                        
                                                        if(commune.getValue() != null && !commune.getValue().equals("") && !getDepartement().equals("")) {
                                                                obtenirInformationCommune();
                                                                longlatAjoutee = true;
                                        
                                                        } else {
                                                                Window.alert("Veuillez renseigner une commune et un numéro de département sous la forme : Commune (departement)");
                                                        }
                                                }
                                        });
                                        
                                        if(!Ext.isIE() && Window.getClientWidth() < 1200) {
                                                
                                                int largeurN = (int)largeur;
                                                
                                                latitude.setWidth(largeurN+"px");
                                                longitude.setWidth(largeurN+"px");
                                                lienSelectionCommune.setWidth(largeurN+"px");
                                                
                                        }
                                }
                        });
                                                
                //Sur une meme ligne, ajout de plusieurs champs
                final MultiFieldPanel htmlPanel = new MultiFieldPanel();  
                
                htmlPanel.addToRow(coordonnees, 100); 
                htmlPanel.addToRow(accesformulaire, new ColumnLayoutData(0.5)); 
                htmlPanel.setBorder(false);
                htmlPanel.setId("x-coord-panel");
                        
                panneauPremierColonne.add(htmlPanel);
                panneauPremierColonne.add(coordPanel);
            
            date = new DateField("Date", "date", 100);  
            date.setAllowBlank(true);
            formatDate = "d/m/Y";
            date.setFormat(formatDate) ;
            //date.setTabIndex(5);
            panneauPremierColonne.add(date, new AnchorLayoutData("60%"));  
        
                espece=new ComboBox("Espèce","nom");  
                        
                final String resultTplEspece = "<div class=\"search-item-espece {indicateurNomRetenu}\">{nom}</div>";  

                
                espece.setTpl(resultTplEspece);
                espece.setMode(ComboBox.REMOTE);
                // espece.setPageSize(10); // Ne fonctionne pas 
                espece.setItemSelector("div.search-item-espece");
                espece.setTypeAhead(true);  
                espece.setLoadingText("Recherche...");  
                  
                espece.setHideTrigger(true);
                //espece.setTabIndex(6);

            panneauPremierColonne.add(espece, new AnchorLayoutData("95%"));   
            
            lieudit = new TextField("Lieu-dit", "lieudit");  
            lieudit.setAllowBlank(true);
            //lieudit.setTabIndex(2);
            panneauSecondeColonne.add(lieudit,  new AnchorLayoutData("95%"));  
               
        
            milieu = new TextField("Milieu", "milieu");  
            milieu.setAllowBlank(true);
            //milieu.setTabIndex(4);
            panneauSecondeColonne.add(milieu,  new AnchorLayoutData("95%"));
            
            comment = new TextArea("Notes", "comment");  
            comment.setAllowBlank(true);
            comment.setHeight(50);
            
            //comment.setTabIndex(7);
            panneauSecondeColonne.add(comment, new AnchorLayoutData("95%") );
            
            if (Window.getClientWidth() > Window.getClientHeight() || Window.getClientWidth() < 800) {
                        panneauIntermediaire.add(panneauPremierColonne, new ColumnLayoutData(.5));
                        panneauIntermediaire.add(panneauSecondeColonne, new ColumnLayoutData(.5));
            }
            else {
                        panneauIntermediaire.add(panneauPremierColonne);
                        panneauIntermediaire.add(panneauSecondeColonne);
                
            }
                        
                panneauFormulaire.add(panneauIntermediaire);
                
                Object[][] mode = {{"création",false} , {"modification", true} };
                storeMode = new SimpleStore(new String[] { "nom_mode", "mode" },
                                mode);
                storeMode.load();
                selecteurMode.setStore(storeMode);
                selecteurMode.setDisplayField("nom_mode") ;
                selecteurMode.setLabel("mode ") ;
                selecteurMode.setForceSelection(true) ;
                selecteurMode.setValue("création") ;
                selecteurMode.setEditable(false) ;
                selecteurMode.setCls("x-selec-crea") ;
                
                bt = new Toolbar() ;
                bt.addSpacer() ;
                bt.addText("Mode de saisie ") ;
                bt.addField(selecteurMode) ;
                
                
                if (Ext.isIE()) {
                        panneauPremierColonne.setButtonAlign(Position.RIGHT);
                        panneauPremierColonne.addButton(boutonOK);
                        panneauSecondeColonne.setButtonAlign(Position.LEFT);
                        panneauPremierColonne.addButton(boutonAnnuler);
                }
                else {
                
                        panneauFormulaire.addButton(boutonOK);
                        panneauFormulaire.addButton(boutonAnnuler);             
                }
                
                
                selecteurMode.addListener(new ComboBoxListenerAdapter() {

                        public void onSelect(ComboBox comboBox, Record record, int index) {
                                
                                // et on met la valeur à jour dans la combobox
                                comboBox.setValue(record.getAsString("nom_mode"));
                                setModification(record.getAsString("mode")) ;
                        }

                });
        
                this.add(panneauFormulaire) ;
                this.setTopToolbar(bt) ;
                
                this.setAutoScroll(true);
        
                
                panneauFormulaire.addListener(new PanelListenerAdapter() {
                public void onResize(BoxComponent component, int adjWidth, int adjHeight, int rawWidth, int rawHeight) {
                        panneauIntermediaire.setWidth(rawWidth);
                        panneauIntermediaire.setHeight(rawHeight);
                        
                        panneauPremierColonne.doLayout();
                        panneauSecondeColonne.doLayout();
                        
                        htmlCommunePanel.doLayout();
                        htmlPanel.doLayout();
                        
                        doLayout();
             }});
                
                // on ajoute les listeners
                
                
                ajouterListeners() ;
                
                saisieTabindex();
                
        }
        
        private void ajouterListeners()
        {       
                // Listener completion communne 
                final Rafraichissable r = this;
                
                   commune.addListener(new ComboBoxListenerAdapter() {  
                     public void onSelect(ComboBox comboBox, Record record, int index) {  
                         commune.setValue(record.getAsString("commune"));
                         departement=record.getAsString("departement");
                         selectionCommune=true;
                         commune.collapse();
                     }  
                     
                     public void onExpand(ComboBox comboBox) {
                         comboBox.focus();
                     }
                 });  
                 
                
                        ListenerConfig listenerConfigCommune=new ListenerConfig();
                        listenerConfigCommune.setDelay(200);
                        listenerConfigCommune.setStopPropagation(false);
                        listenerConfigCommune.setStopEvent(false);
                        
                    commune.addKeyPressListener(new EventCallback()     {
                        
                    public void execute(EventObject e) {
                        
                                  
                                switch(e.getKey()) {
                              
                                        case KEY_ALT:
                                case KEY_CTRL:
                                case KEY_DOWN:
                                case KEY_END:
                                case KEY_ESCAPE:
                                case KEY_HOME:
                                case KEY_LEFT:
                                case KEY_PAGEDOWN:
                                case KEY_PAGEUP:
                                case KEY_RIGHT:
                                case KEY_SHIFT:
                                case KEY_TAB:
                                case KEY_UP:
                                
                                break;
                                
                                case KEY_ENTER:
                                  
                                         if (selectionCommune) {
                                                 communeModifiee= true;
                                                 selectionCommune=false;
                                         }
                                        else {
        
                                                validerSaisie(Champs.COMMUNE);
                                                // lancer mise a jour                                    
                                         }
                                    break;
                               
                                    default:
                                          
                                          departement="";
                                          commune.collapse();   
                                          obtenirListeReferentielCommune();
                                          communeModifiee= true;
                                                                        
                                    break;
                            }
                                }
                        },    listenerConfigCommune
                        );
                    
                    date.addKeyPressListener(new EventCallback() {

                                public void execute(EventObject e) {
                                        // TODO Auto-generated method stub
                                        switch(e.getKey()) {
                                        
                                                case KEY_ALT:
                                case KEY_CTRL:
                                case KEY_DOWN:
                                case KEY_END:
                                case KEY_ESCAPE:
                                case KEY_HOME:
                                case KEY_LEFT:
                                case KEY_PAGEDOWN:
                                case KEY_PAGEUP:
                                case KEY_RIGHT:
                                case KEY_SHIFT:
                                case KEY_TAB:
                                        if(date.getRawValue().equals(VALEURS_MULTIPLES)) {
                                                date.clearInvalid();
                                        }
                                case KEY_UP:
                                
                                break;
                              
                              case KEY_ENTER:           
                                        validerSaisie(Champs.DATE); 
                                  break;
                               
                              default:
                                                dateModifiee = true;
                                        }
                                }
                    });
                    
                    date.addListener(new DatePickerListenerAdapter() {

                                public void onSelect(DatePicker dataPicker, Date date) {
                                        dateModifiee = true;
                                }
                    });
                    
                    station.addKeyPressListener(new EventCallback() {

                                public void execute(EventObject e) {
                                        // TODO Auto-generated method stub
                                        switch(e.getKey()) {
                              
                                                case KEY_ALT:
                                case KEY_CTRL:
                                case KEY_DOWN:
                                case KEY_END:
                                case KEY_ESCAPE:
                                case KEY_HOME:
                                case KEY_LEFT:
                                case KEY_PAGEDOWN:
                                case KEY_PAGEUP:
                                case KEY_RIGHT:
                                case KEY_SHIFT:
                                case KEY_TAB:
                                case KEY_UP:
                              break;
                              
                              case KEY_ENTER:                             
                                        validerSaisie(Champs.STATION);                           
                                  break;
                               
                              default:
                                  stationModifiee = true;
                                        }
                                }
                    });
                    
                    
                        
                        // Listener completion espece 
                        espece.addListener(new ComboBoxListenerAdapter() {  
                     public void onSelect(ComboBox comboBox, Record record, int index) {  
                         espece.setValue(record.getAsString("nom"));
                         numeroNom=record.getAsString("numeroNom");
                         selectionEspece=true;
                         observationMediateur.obtenirImageInformationExternes(numeroNom);
                     }  
                 });  
                 

                        ListenerConfig listenerConfigEspece=new ListenerConfig();
                        listenerConfigEspece.setDelay(10);
                        listenerConfigEspece.setStopPropagation(false);
                        listenerConfigEspece.setStopEvent(false);                       

                
                        espece.addKeyPressListener(new EventCallback()  {
                        
                            public void execute(EventObject e) {
                                
                                          
                                          switch(e.getKey()) {
                                                          
                                          
                                          case KEY_ALT:
                                      case KEY_CTRL:
                                      case KEY_DOWN:
                                      case KEY_END:
                                      case KEY_ESCAPE:
                                      case KEY_HOME:
                                      case KEY_LEFT:
                                      case KEY_PAGEDOWN:
                                      case KEY_PAGEUP:
                                      case KEY_RIGHT:
                                      case KEY_SHIFT:
                                      case KEY_TAB:
                                      case KEY_UP:
                                        
                                        break;
                                      
                                      case KEY_ENTER:
                                          
                                                if(selectionEspece) {
                                                        especeModifiee = true;
                                                        selectionEspece=false;
                                                }
                                                else {
                                                        validerSaisie(Champs.ESPECE);                            
                                                }
                                        
                                          break;
                                       
                                      default:
                                          
                                          numeroNom="";
                                          obtenirListeReferentielNom();
                                          especeModifiee = true;
                                                                        
                                        break;
                                    }

                                 
                                
                                }
                         
                                },    listenerConfigEspece
                        
                        );
                    
                        lieudit.addKeyPressListener(new EventCallback() {

                                public void execute(EventObject e) {
                                        // TODO Auto-generated method stub
                                        switch(e.getKey()) {
                              
                                        case KEY_ALT:
                              case KEY_CTRL:
                              case KEY_DOWN:
                              case KEY_END:
                              case KEY_ESCAPE:
                              case KEY_HOME:
                              case KEY_LEFT:
                              case KEY_PAGEDOWN:
                              case KEY_PAGEUP:
                              case KEY_RIGHT:
                              case KEY_SHIFT:
                              case KEY_TAB:
                              case KEY_UP:
                        
                        break;
                                        
                              case KEY_ENTER:                             
                                        validerSaisie(Champs.LIEUDIT);                           
                                  break;
                               
                              default:
                                                lieuDitModifie = true;
                                        }
                                }
                    });
                        
                        milieu.addKeyPressListener(new EventCallback() {

                                public void execute(EventObject e) {
                                        // TODO Auto-generated method stub
                                        switch(e.getKey()) {
                                        
                                                case KEY_ALT:
                              case KEY_CTRL:
                              case KEY_DOWN:
                              case KEY_END:
                              case KEY_ESCAPE:
                              case KEY_HOME:
                              case KEY_LEFT:
                              case KEY_PAGEDOWN:
                              case KEY_PAGEUP:
                              case KEY_RIGHT:
                              case KEY_SHIFT:
                              case KEY_TAB:
                              case KEY_UP:
                                
                                break;
                              
                              case KEY_ENTER:                             
                                        validerSaisie(Champs.MILIEU);                            
                                  break;
                               
                              default:
                                                milieuModifie = true;
                                        }
                                }
                    });
                        
                        comment.addKeyPressListener(new EventCallback() {

                                public void execute(EventObject e) {
                                        switch(e.getKey()) { 
                                                case KEY_ALT:
                                      case KEY_CTRL:
                                      case KEY_DOWN:
                                      case KEY_END:
                                      case KEY_ESCAPE:
                                      case KEY_HOME:
                                      case KEY_LEFT:
                                      case KEY_PAGEDOWN:
                                      case KEY_PAGEUP:
                                      case KEY_RIGHT:
                                      case KEY_SHIFT:
                                      case KEY_TAB:
                                      case KEY_UP:
                                
                                break;

                                default:
                                                commModifie = true;
                                        }
                                }
                    });
                        
                        tCoord = new Timer() {

                                public void run() {
                        double[] coord = coordonneesValides();
                        if(!rechercheCommuneEnCours && coord != null && (longModifiee || latModifiee)) {
                                rechercheCommuneEnCours = true;
                                Ext.get(lienSelectionCommune.getElement()).mask("recherche");
                                observationMediateur.obtenirInformationCoord(r,LatLng.newInstance(coord[0], coord[1]));
                        }
                                }
                                
                        };
                        
                        latitude.addKeyPressListener(new EventCallback() {

                                public void execute(EventObject e) {
                                        switch(e.getKey()) { 
                                                case KEY_ALT:
                                      case KEY_CTRL:
                                      case KEY_DOWN:
                                      case KEY_END:
                                      case KEY_ESCAPE:
                                      case KEY_HOME:
                                      case KEY_LEFT:
                                      case KEY_PAGEDOWN:
                                      case KEY_PAGEUP:
                                      case KEY_RIGHT:
                                      case KEY_SHIFT:
                                      case KEY_TAB:
                                      case KEY_UP:
                                
                                break;
                                
                                      case KEY_ENTER:                             
                                        validerSaisie(Champs.LATITUDE);                                  
                                  break;

                                default:
                                                latModifiee = true;
                                tCoord.cancel();
                                tCoord.schedule(250);
                                        }
                                }
                    });
                        
                        longitude.addKeyPressListener(new EventCallback() {

                                public void execute(EventObject e) {
                                        switch(e.getKey()) { 
                                        
                                                case KEY_ALT:
                                      case KEY_CTRL:
                                      case KEY_DOWN:
                                      case KEY_END:
                                      case KEY_ESCAPE:
                                      case KEY_HOME:
                                      case KEY_LEFT:
                                      case KEY_PAGEDOWN:
                                      case KEY_PAGEUP:
                                      case KEY_RIGHT:
                                      case KEY_SHIFT:
                                      case KEY_UP:
                                      case KEY_TAB:
                                      break;
                                      
                                      case KEY_ENTER:                             
                                                validerSaisie(Champs.LONGITUDE);                                 
                                        break;

                                default:
                                                        longModifiee = true;
                                        tCoord.cancel();
                                        tCoord.schedule(250);
                                        }
                                }
                    });

                boutonOK.addListener(new ButtonListenerAdapter() {
                        
                        public void onClick(Button button, EventObject e) {
                
                                if(modification) {
                                        if(masseModification) {
                                                        modifierObservationEnMasse(null);
                                        } else {
                                                modifierObservation() ;
                                        }
                                }
                                else {
                                        ajouterObservation();
                                }
                                
                                
                        }
                        
                });
                
                boutonAnnuler.addListener(new ButtonListenerAdapter() {
                        
                        public void onClick(Button button, EventObject e) {
                                
                                if(modification)
                                {
                                        supprimerObservation() ;
                                }
                                else
                                {
                                        raz();
                                }
                        }
                        
                });
                
                this.addListener(new ContainerListenerAdapter() {
                        public void onAfterLayout(Container self) {
                                commune.focus();
                        }
                });     
                        
        }
        
        /**
         * Validation de la saisie 
         */
        
        private void validerSaisie(Champs champs) {
                
                if(modification) {
                        if(masseModification) {
                                        modifierObservationEnMasse(champs);
                        } else {
                                modifierObservation();
                        }
                        
                        raz(champs);
                }
                else {
                        ajouterObservation();
                        raz(champs);
                }
        }
        
        /**
         * Desactive visuellement ce panneau
         */
        public void desactiverPanneau()
        {
                this.setDisabled(true) ;
        }
        
        /**
         * Active visuellement ce panneau
         */
        public void activerPanneau()
        {
                this.setDisabled(false) ;
        }

        public void rafraichir(Object nouvelleDonnees, boolean repandreRaffraichissement) {
                
                // si l'on a reçu une liste du referentiel commune (completion referentiel commune)
                        if(nouvelleDonnees instanceof ListeReferentielCommune)
                        {
                                ListeReferentielCommune data = (ListeReferentielCommune) nouvelleDonnees ;
                                Object[][] communeData = new Object[data.size()][2];
                                int i = 0 ;
                        
                                // on la parse et on récupère les informations quiç nous interessent
                                for (Iterator it = data.keySet().iterator(); it.hasNext();) 
                                {
                                        
                                        ReferentielCommune ref=(ReferentielCommune) data.get(it.next());
                                
                                        
                                        communeData[i][0]= ref.getCommune();
                                        communeData[i][1]= ref.getDepartement();
                                        
                                        i++ ;
                                }
                                
                                   //     creation du store
                                FieldDef defCommune = new StringFieldDef("commune");
                                FieldDef defDepartement = new StringFieldDef("departement");
                                
                                
                                FieldDef[] defTab = { defCommune, defDepartement};
                                
                                RecordDef rd = new RecordDef(defTab);
                                
                                final MemoryProxy dataProxy = new MemoryProxy(communeData);
                                final ArrayReader reader = new ArrayReader(rd);         
                                                                
                                Store store=new Store(dataProxy,reader);        
                                commune.setStore(store);
                                store.load();
                                
                        }
                        
                        //                       si l'on a reçu une liste du référentiel nom (complétion referentiel nom)
                        
                        if(nouvelleDonnees instanceof ListeReferentielNom)
                        {
                                
                                ListeReferentielNom data = (ListeReferentielNom) nouvelleDonnees ;
                                Object[][] nomData = new Object[data.size()][3];
                                int i = 0 ;
                        
                                // on la parse et on récupère les informations quiç nous interessent
                                for (Iterator it = data.keySet().iterator(); it.hasNext();) 
                                {
                                        
                                        ReferentielNom ref=(ReferentielNom) data.get(it.next());
                                        
                                        nomData[i][0]= ref.getNom();
                                        nomData[i][1]= ref.getNumeroNom();
                                        if (ref.getStatut().equals("3")) {
                                                nomData[i][2]="nom_retenu";
                                        }
                                        else {
                                                nomData[i][2]="";
                                        }
                                        
                                                                                                                                
                                        i++ ;
                                }
                                
                                   //     creation du store
                                FieldDef defNom = new StringFieldDef("nom");
                                FieldDef defNumeroNom = new StringFieldDef("numeroNom");
                                FieldDef indicateurNomRetenu = new StringFieldDef("indicateurNomRetenu");
                                
                                
                                FieldDef[] defTab = { defNom, defNumeroNom, indicateurNomRetenu};
                                
                                RecordDef rd = new RecordDef(defTab);
                                
                                final MemoryProxy dataProxy = new MemoryProxy(nomData);
                                final ArrayReader reader = new ArrayReader(rd);         
                                
                                Store store=new Store(dataProxy,reader);
                                store.load() ;
        
                                espece.setStore(store);
                                
                        }
                        
                        // On recoit une observation dont on veut afficher le detail 
                        
                        if(nouvelleDonnees instanceof Observation)
                        {
                                Observation obs = (Observation)nouvelleDonnees ;
                                afficherDetailsObservation(obs) ;
                        }
                        
                        if(nouvelleDonnees instanceof ListeObservation) {
                                
                                ListeObservation listeObs = (ListeObservation)nouvelleDonnees;
                                calculerAfficherDifferences(listeObs);
                        }
                        
                        // Sur Mise à jour ou suppression d'une suppression ?
                        
                        if(nouvelleDonnees instanceof String)
                        {
                                String str = (String)nouvelleDonnees ;
                                observationMediateur.obtenirNombreObservation() ;
                        }
                        
                        if(nouvelleDonnees instanceof String[]) {
                                String[] anumNom = (String[])nouvelleDonnees ;
                                numeroNom = anumNom[1];
                                espece.setValue(anumNom[0]);
                                setModification("false");
                        }
                        
                        if(nouvelleDonnees instanceof EntiteGeographiqueObservation)
                        {
                                EntiteGeographiqueObservation infosComm = (EntiteGeographiqueObservation)nouvelleDonnees ;
                                if(rechercheCommuneEnCours) {
                                        afficherIndicationCommune(infosComm);
                                } else {
                                        rafraichirCommuneEtCoord(infosComm);
                                }
                        }

        }
        
        
        private void afficherIndicationCommune(
                        final EntiteGeographiqueObservation infosCom) {
                
                String nCommune = "";
                if(infosCom != null && !infosCom.getCommune().trim().equals("")){
                        nCommune += infosCom.getCommune();
                        if(!infosCom.getIdLocalite().trim().equals(""))
                        nCommune += " ("+infosCom.getIdLocalite()+")";
                }
                lienSelectionCommune.setHtml("<a id=\"lien_selection_commune\" tabindex=\"9\">"+nCommune+"</a>");
                lienSelectionCommune.setStyleName("img-curseur-depl");
                
                Ext.get("lien_selection_commune").addListener("click",new EventCallback() {
                        public void execute(EventObject e) {
                                rafraichirCommune(infosCom);
                        }                       
                });
                
                Ext.get("lien_selection_commune").addListener("keypress",new EventCallback() {
                        public void execute(EventObject e) {
                                if(e.getCharCode() == KEY_ENTER) {
                                        rafraichirCommune(infosCom);
                                }
                        }                       
                });
                
                Ext.get("lien_selection_commune").addListener("focus",new EventCallback() {
                        public void execute(EventObject e) {
                                Ext.get("lien_selection_commune").toggleClass("lien_sel");
                        }                       
                });
                
                Ext.get("lien_selection_commune").addListener("blur",new EventCallback() {
                        public void execute(EventObject e) {
                                Ext.get("lien_selection_commune").toggleClass("lien_sel");
                        }                       
                });

                Ext.get(lienSelectionCommune.getElement()).unmask();
                rechercheCommuneEnCours = false;
        }
        
        private void rafraichirCommune(EntiteGeographiqueObservation infosCom) {
                String nCommune = "";

                
                if(infosCom.getCommune() != null && !infosCom.getCommune().equals("")) {
                        nCommune += infosCom.getCommune();
                }
                
                if(infosCom.getIdLocalite() != null && !infosCom.getIdLocalite().equals("")) {
                        nCommune += " ("+infosCom.getIdLocalite()+")";
                        departement = infosCom.getIdLocalite();
                }
                commune.setValue(nCommune);
                communeModifiee = true;
        }

        private void rafraichirCommuneEtCoord(EntiteGeographiqueObservation infosCom) {
                ;
                // on ne remplace la commune que si le champ était vide
                if(commune.getRawValue() == null || commune.getRawValue().equals("")) {
                        rafraichirCommune(infosCom);
                } 

                if(infosCom.getLat() != null && !infosCom.getLat().equals("")) {
                        latitude.setValue(infosCom.getLat());
                }

                if(infosCom.getLon() != null && !infosCom.getLon().equals("")) {
                        longitude.setValue(infosCom.getLon());
                }
                
                latModifiee = true;
                longModifiee = true;
                
                coordPanel.setVisible(true);
        }

        public void obtenirListeReferentielCommune() {
                
         String com=commune.getText();
         com=com.replaceAll("%","");
                  
         observationMediateur.obtenirListeReferentielCommune(this,com);
         
        }
        

        public void obtenirListeReferentielNom() {
         
         // FIXME : trouver un autre moyen que le hack "/*" pour rechercher les taxons lors de la saisie d'un espace apres le genre
         
          String esp=espece.getText().replaceAll(" ","/*");
          esp=esp.replaceAll("%","");
                
          observationMediateur.obtenirListeReferentielNom(this,esp);
         
        }
   

        public void ajouterObservation() {
                
                if(departement != null) {  
                // TODO : regler le probleme a la base plutot que ce patch
                        
                        if(departement.equals("000null") || departement.equals("")) {
                                String[] depCom = commune.getText().split(" ");
                                if(depCom.length > 1) {
                                        String dep = depCom[1].replace('(', ' ');
                                        dep =dep.replace(')', ' ');
                                        dep = dep.trim();
                                        dep = dep.replace('\\',' ');
                                        dep = dep.trim();
                                        
                                        try
                                        {
                                                int nDep = Integer.parseInt(dep);
                                                if(nDep > 0 && nDep < 110) {
                                                        departement = dep ;
                                                }
                                        }
                                        catch(NumberFormatException e)
                                        {
                                                departement = "" ;
                                        }
                                }
                        }
                }

                Observation obs=new Observation(espece.getText(),numeroNom,commune.getText(),departement,lieudit.getText(),station.getText(),milieu.getText(), comment.getText(),date.getRawValue());   
                
                String[] coords = getValeurCoordonnees();
                
                obs.setCoordonneeX(coords[0]);
                obs.setCoordonneeY(coords[1]);
                
                observationMediateur.ajouterObservation(obs);
        }
        
        private void modifierObservation() {
                
                if(departement.equals("000null") || departement.equals("")) {
                        String[] depCom = commune.getText().split(" ");
                        if(depCom.length > 1) {
                                String dep = depCom[1].replace('(', ' ');
                                dep =dep.replace(')', ' ');
                                dep = dep.trim();
                                dep = dep.replace('\\',' ');
                                dep = dep.trim();
                                
                                try
                                {
                                        int nDep = Integer.parseInt(dep);
                                        if(nDep > 0 && nDep < 110) {
                                                departement = dep ;
                                        }
                                }
                                catch(NumberFormatException e)
                                {
                                        departement = "" ;
                                }
                        }
                }
                
                Observation obs=new Observation(espece.getText(),numeroNom,commune.getText(),departement,lieudit.getText(),station.getText(),milieu.getText(), comment.getText(),date.getRawValue());
                obs.setNumeroOrdre(numeroOrdre);
                
                String[] coords = getValeurCoordonnees();
                
                obs.setCoordonneeX(coords[0]);
                obs.setCoordonneeY(coords[1]);
                
                observationMediateur.modifierObservation(obs);

                selecteurMode.setValue("création");
                setModification("false");
                
        }
        
        private void modifierObservationEnMasse(Champs champModifie) {
                String communeM = null;
                String departementM = null;
                String numNomSelM = null;
                String lieuDitM = null;
                String stationM = null;
                String milieuM = null;
                String dateM = null;
                String especeM = null;
                String commM = null; 
                String latM = null;
                String longM = null;
                
                String champs = modeleMessageModif;
                        
                if(communeModifiee) {
                        communeM = commune.getText();
                        
                        if(departement.equals("000null") || departement.equals("")) {
                                String[] depCom = commune.getText().split(" ");
                                if(depCom.length > 1) {
                                        String dep = depCom[1].replace('(', ' ');
                                        dep =dep.replace(')', ' ');
                                        dep = dep.trim();
                                        dep = dep.replace('\\',' ');
                                        dep = dep.trim();
                                        
                                        try
                                        {
                                                int nDep = Integer.parseInt(dep);
                                                if(nDep > 0 && nDep < 110) {
                                                        departement = dep ;
                                                }
                                        }
                                        catch(NumberFormatException e)
                                        {
                                                departement = "" ;
                                        }
                                }
                        }
                        
                        departementM = departement;
                } else {
                        champs = champs.replaceAll("commune", "");
                }
                
                if(lieuDitModifie) {
                        lieuDitM = lieudit.getText();
                }else {
                        champs = champs.replaceAll(":lieu-dit", "");
                }
                
                if(stationModifiee) {
                        stationM = station.getText();
                }else {
                        champs = champs.replaceAll(":station", "");
                }

                if(milieuModifie) {
                        milieuM = milieu.getText();
                }else {
                        champs = champs.replaceAll(":milieu", "");
                }

                if(dateModifiee && !date.getRawValue().equals(VALEURS_MULTIPLES)) {
                        dateM = date.getRawValue();
                }else {
                        champs = champs.replaceAll(":date", "");
                }

                if(especeModifiee) {
                        especeM = espece.getText();
                        numNomSelM = numeroNom;
                }else {
                        champs = champs.replaceAll(":espece", "");
                }

                if(commModifie) {
                        commM = comment.getText();
                }else {
                        champs = champs.replaceAll(":commentaire", "");
                }
                
                if(latModifiee) {
                        latM = latitude.getText();
                }else {
                        champs = champs.replaceAll(":latitude", "");
                }
                
                if(longModifiee) {
                        longM = longitude.getText();
                }else {
                        champs = champs.replaceAll(":longitude", "");
                }
                
                champs = champs.replaceAll(":",", ");
                if(champs.startsWith(",")) {
                        champs = champs.replaceFirst(",", "");
                }
                
                String message = "Voulez vous modifier le(s) champ(s) suivant(s) : "+champs+"   pour les observations selectionnées ?" ;
                
                if(champs.trim().equals("")) {
                        Window.alert("Aucun champ n'a été modifié");
                } else {
                        Observation obs = new Observation(especeM,numNomSelM,communeM,departementM,lieuDitM,stationM,milieuM, commM,dateM);
                        obs.setNumeroOrdre(numeroOrdre);
                        obs.setCoordonneeX(latM);
                        obs.setCoordonneeY(longM);
                        if(Window.confirm(message)) {
                                observationMediateur.modifierObservationEnMasse(obs);
                                reinitialiserValeurModifiees();
                        }
                }
        }
        
        private void supprimerObservation() {
                
                observationMediateur.supprimerObservation(this, numeroOrdre);
        }
        
        public void afficherDetailsObservation(Observation obs)
        {
                raz() ;
                String idLoc ;
                if(obs.getIdentifiantLocalite() != VALEURS_MULTIPLES) {
                        idLoc =obs.getIdentifiantLocalite().replaceAll(" ","/");
                        idLoc = idLoc.replaceAll("%","");
                        idLoc = idLoc.replaceAll("\"","");
                        idLoc = idLoc.replace('\\',' ');
                        idLoc = idLoc.trim();
                } else {
                        idLoc = obs.getIdentifiantLocalite();
                }
                
                if(!obs.getDate().equals("null") && !obs.getDate().equals("000null") && !obs.getDate().equals(VALEURS_MULTIPLES)) {
                        String[] dateEtHeure = obs.getDate().split(" ", 2);
                        if(verifierFormatDate(dateEtHeure[0])) {
                                date.setValue(dateEtHeure[0]) ;
                        }
                        else
                        {
                                date.setRawValue(""); 
                        }
                } else {
                        date.setRawValue(VALEURS_MULTIPLES);
                        date.clearInvalid();
                }
                if(!obs.getLieudit().equals("null") && !obs.getLieudit().equals("000null")) {
                        lieudit.setValue(obs.getLieudit()) ;
                }
                if(!obs.getStation().equals("null") && !obs.getStation().equals("000null")) {
                        station.setValue(obs.getStation()) ;
                }
                if(!obs.getMilieu().equals("null") && !obs.getMilieu().equals("000null")) {
                        milieu.setValue(obs.getMilieu()) ;
                }
                if(!obs.getCommentaire().equals("null") && !obs.getCommentaire().equals("000null")) {

                        comment.setRawValue(remplacerSautsDeligneMalEncodes(obs.getCommentaire()));
                        
                }
                if(!obs.getLocalite().equals("null") && !obs.getLocalite().equals("000null")) {
                        if(!idLoc.equals("000null")) {
                                if(!idLoc.equals(VALEURS_MULTIPLES)) {
                                        commune.setValue(obs.getLocalite()+" ("+idLoc+")") ;
                                } else {
                                        commune.setValue(VALEURS_MULTIPLES);
                                }
                        }
                        else
                        {
                                commune.setValue(obs.getLocalite());
                        }
                }
                if(!obs.getIdentifiantLocalite().equals("null") && !obs.getIdentifiantLocalite().equals("000null")) {
                        departement = idLoc;
                }
                if(!obs.getNomSaisi().equals("null") && !obs.getNomSaisi().equals("000null")) {
                        espece.setValue(obs.getNomSaisi()) ;
                }
                if(!obs.getNumeroNomenclaturalSaisi().equals("null") && !obs.getNumeroNomenclaturalSaisi().equals("000null")) {
                        numeroNom = obs.getNumeroNomenclaturalSaisi() ;
                }
                if(!obs.getNumeroOrdre().equals("null") && !obs.getNumeroOrdre().equals("000nu2ll")) {
                        numeroOrdre = obs.getNumeroOrdre() ;
                }
                
                if(!obs.getCoordonneeX().equals("null") && !obs.getCoordonneeX().equals("000null")
                                && !obs.getCoordonneeY().equals("null") && !obs.getCoordonneeY().equals("000null")) {
                        latitude.setValue(obs.getCoordonneeX()) ;
                        longitude.setValue(obs.getCoordonneeY()) ;
                }
        }
        
        
        public void raz()
        {
                raz(Champs.TOUT);
                
        }
        public void raz(Champs champs)
        {
                switch (champs) {
                
                
                        case DATE:
                                date.reset() ;
                                break;
                
                        case LIEUDIT:
                                lieudit.reset() ;
                                break;
                
                        case STATION:
                                station.reset() ;
                                break;
                
                        case MILIEU:
                                milieu.reset() ;
                                break;
                
                        case COMMENT:
                                comment.reset() ;
                                break;


                        case COMMUNE:
                                commune.reset() ;
                                departement ="";
                                latitude.reset();
                                longitude.reset();
                                break;
                                
                        case ESPECE:
                                espece.reset();
                                numeroNom = "" ;
                                numeroOrdre = "";
                                break;
                                
                        case LATITUDE:
                                latitude.reset();
                                afficherIndicationCommune(null);
                                break;
                                
                        case LONGITUDE:
                                longitude.reset();
                                afficherIndicationCommune(null);
                                break;
                                
                        case TOUT:
                                commune.reset();
                                date.reset() ;
                                lieudit.reset() ;
                                station.reset() ;
                                milieu.reset() ;
                                comment.reset() ;
                                milieu.reset() ;
                                latitude.reset();
                                longitude.reset();
                                departement ="";
                                espece.reset();
                                numeroNom = "" ;
                                numeroOrdre = "";
                                afficherIndicationCommune(null);
                                break;

                }
                
        }
        
        private void setModification(String mode)
        {
                if(mode.equals("true")) {

                        boutonOK.setText("Modifier") ;
                        setTitle("Modification") ;
                        boutonAnnuler.setText("Supprimer") ;
                        modification = true ;
                        selecteurMode.removeClass("x-selec-crea") ;
                        selecteurMode.setCls("x-selec-modif") ;
                        observationMediateur.onModeModification();
                }
                else
                {
                        boutonOK.setText("Créer") ;
                        setTitle("Saisir") ;
                        boutonAnnuler.setText("Réinitialiser") ;
                        modification = false ;
                        selecteurMode.removeClass("x-selec-modif") ;
                        selecteurMode.setCls("x-selec-crea") ;
                        observationMediateur.onModeCreation();
                }       
        }
        
        /**
         * renvoie vrai si on est en mode modification, faux si on est en mode création
         * @return
         */
        public boolean getModification()
        {
                return modification ;
        }
        
        /**
         * renvoie vrai si on est en mode modification de masse, faux sinon
         * @return
         */
        public boolean getMasseModification()
        {
                return masseModification ;
        }
        
        public boolean verifierFormatDate(String date) {
                
                String regex = "[1-9][0-9]{3}-[0-9]{2}-[0-9]{2}" ;
                if(date.matches(regex) && !date.equals("0000-00-00")) {
                        return true ;
                }
                else {
                        return false;
                }
        }

        public void setMasseModification(boolean masseModification) {
                this.masseModification = masseModification;
                if(masseModification) {
                        reinitialiserValeurModifiees();
                }
        }
        
        private void calculerAfficherDifferences(ListeObservation listeObs) {
                
                String departement = null;
                String commune = null;
                String lieuDit = null;
                String station = null;
                String milieu = null;
                String espece = null;
                String date = null;
                String notes = null;
                String lat = null;
                String lon = null;
                
                String ordreObs = "";
                
                for(Iterator<String> it = listeObs.keySet().iterator();it.hasNext();) {
                        Observation obsEnCours = listeObs.get(it.next());
                        departement = comparerDifferencesChamps(departement, obsEnCours.getIdentifiantLocalite());
                        commune = comparerDifferencesChamps(commune, obsEnCours.getLocalite());
                        lieuDit = comparerDifferencesChamps(lieuDit, obsEnCours.getLieudit());
                        station = comparerDifferencesChamps(station, obsEnCours.getStation());
                        milieu = comparerDifferencesChamps(milieu, obsEnCours.getMilieu());
                        espece = comparerDifferencesChamps(espece, obsEnCours.getNomSaisi()); 
                        date = comparerDifferencesChamps(date, obsEnCours.getDate());
                        notes = comparerDifferencesChamps(notes, obsEnCours.getCommentaire());
                        lat = comparerDifferencesChamps(lat, obsEnCours.getCoordonneeX());
                        lon = comparerDifferencesChamps(lon, obsEnCours.getCoordonneeY());
                        
                        ordreObs += obsEnCours.getNumeroOrdre()+",";
                }
                
                Observation obs=new Observation(espece,numeroNom,commune,departement,lieuDit,station,milieu, notes,date);
                obs.setNumeroOrdre(ordreObs);
                obs.setCoordonneeX(lat);
                obs.setCoordonneeY(lon);
                rafraichir(obs, false);
                
        }
        
        private String comparerDifferencesChamps(String valeurActuelle, String nouvelleValeur) {
                
                String retour = "000null";
                
                        if(valeurActuelle == null) {
                                retour = nouvelleValeur;
                        } else {
                                if(valeurActuelle.equals(nouvelleValeur)) {
                                        retour = valeurActuelle;
                                } else {
                                        retour = VALEURS_MULTIPLES;
                                }
                        }
                return retour;
        }
        
        private void reinitialiserValeurModifiees() {
                
                communeModifiee = false;
                lieuDitModifie = false;
                stationModifiee = false;
                milieuModifie = false;
                dateModifiee = false;
                especeModifiee = false;
                commModifie = false;
                latModifiee = false;
                longModifiee = false;
        }
        
        public void saisieTabindex()
        {
                
                selecteurMode.setTabIndex(0);
                commune.setTabIndex(1);
                lieudit.setTabIndex(3);
                station.setTabIndex(4);
                milieu.setTabIndex(5);
                coordonnees.setTabIndex(-1);
                coordonnees.addListener(new TextFieldListenerAdapter() {

                        public void onFocus(Field field) {
                                if(coordPanel.isVisible()) {
                                        latitude.focus();
                                } else {
                                        Ext.get("lien_carto").focus();
                                }
                        }       
                });
                        
                latitude.setTabIndex(7);
                longitude.setTabIndex(8);
                comment.setTabIndex(10);
                date.setTabIndex(11);
                espece.setTabIndex(12);
                boutonOK.setTabIndex(13);
                boutonAnnuler.setTabIndex(14);
                
        }
        
        private void obtenirInformationCoord() {
                if(coordonneesValides() != null) {
                        observationMediateur.obtenirInformationCoord(LatLng.newInstance(coordonneesValides()[0],coordonneesValides()[1]));
                } else {
                        Window.alert("Les coordonnées saisies sont invalides");
                }

        }
        
        private void obtenirInformationCommune() {
                observationMediateur.obtenirInformationCommune(getCommune(), obtenirDepartementAPartirChampCommune());
        }
        
        public double[] coordonneesValides() {
                
                try {
                                                
                        double lat = Double.parseDouble(latitude.getValueAsString().replaceAll(",", "."));
                        double lon = Double.parseDouble(longitude.getValueAsString().replaceAll(",", "."));
                        
                        double[] coord = {lat, lon};
                        return coord;
                        
                } catch (NumberFormatException ne) {
                        return null;
                }
        }
        
        private String[] getValeurCoordonnees() {
                double[] coDouble = coordonneesValides();
                
                if(coDouble != null) {
                        String[] coord = {coDouble[0]+"",coDouble[1]+""};
                        return coord;
                } else {
                        String[] coord = {"000null","000null" };
                        return coord;
                }
        }
        
        private String obtenirDepartementAPartirChampCommune() {
                
                String dep = "";
                
                if(departement == null) {
                        departement = "";
                }
                
                if(departement.equals("000null") || departement.equals("")) {
                                        
                        String[] depCom = commune.getText().split(" ");
                        if(depCom.length > 1) {
                                dep = depCom[1].replace('(', ' ');
                        } else {
                                dep = "";
                        }
                } else {
                        dep = departement;
                }
                
                dep = dep.replace(')', ' ');
                dep = dep.trim();
                dep = dep.replace('\\',' ');
                dep = dep.trim();
                
                try
                {
                        int nDep = Integer.parseInt(dep);
                        if(nDep > 0 && nDep < 110) {
                                departement = dep ;
                        }
                        
                        if(departement.length() == 1) {
                                departement = "0"+departement;
                        }
                }
                catch(NumberFormatException e)
                {
                        departement = "" ;
                }
                
                return departement;
        }
        
        public String getCommune() {
                
                String valeurCommune = "";
                
                if(commune.getValue() != null) {
                        valeurCommune = commune.getValue(); 
                }
                return valeurCommune;
        }
        
        public String getDepartement() {
                return obtenirDepartementAPartirChampCommune();
        }
        
        public String getCommuneSansDepartement() {
                return Util.supprimerNumDepartementChaineLocalite(getCommune());
        }

        public boolean communeInitialisee() {
                return communeModifiee;
        }
        
        public void redimensionnerFormulaire() {
                doLayout();
                //panneauIntermediaire.doLayout();
        }
        
        public String remplacerSautsDeligneMalEncodes(String chaineAvecSautsDeLignesMalEncodes) {
                
                String chaineAvecSautsDeLignesBienEncodes = chaineAvecSautsDeLignesMalEncodes.replace('\\','%');
                chaineAvecSautsDeLignesBienEncodes = chaineAvecSautsDeLignesBienEncodes.replaceAll("%n","%");
                chaineAvecSautsDeLignesBienEncodes = chaineAvecSautsDeLignesBienEncodes.replace('%','\n');
                
                return chaineAvecSautsDeLignesBienEncodes;
        }
}