Subversion Repositories eFlore/Applications.cel

Rev

Rev 3260 | Rev 3270 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 3260 Rev 3263
1
/**
1
/**
2
 * Constructeur WidgetSaisie par défaut
2
 * Constructeur WidgetSaisie par défaut
3
 */
3
 */
4
function WidgetSaisie() {
4
function WidgetSaisie() {
5
	this.langue = 'fr';
5
	this.langue = 'fr';
6
	this.obsNbre = 0;
6
	this.obsNbre = 0;
7
	this.nbObsEnCours = 1;
7
	this.nbObsEnCours = 1;
8
	this.totalObsATransmettre = 0;
8
	this.totalObsATransmettre = 0;
9
	this.nbObsTransmises = 0;
9
	this.nbObsTransmises = 0;
10
	this.debug = null;
10
	this.debug = null;
11
	this.html5 = null;
11
	this.html5 = null;
12
	this.tagProjet = null;
12
	this.tagProjet = null;
13
	this.tagImg = null;
13
	this.tagImg = null;
14
	this.tagObs = null;
14
	this.tagObs = null;
15
	this.separationTagImg = null;
15
	this.separationTagImg = null;
16
	this.separationTagObs = null;
16
	this.separationTagObs = null;
17
	this.obsId = null;
17
	this.obsId = null;
18
	this.serviceSaisieUrl = null;
18
	this.serviceSaisieUrl = null;
19
	this.serviceObsUrl = null;
19
	this.serviceObsUrl = null;
20
	this.nomSciReferentiel = null;
20
	this.nomSciReferentiel = null;
21
	this.especeImposee = false;
21
	this.especeImposee = false;
22
	this.infosEspeceImposee = null;
22
	this.infosEspeceImposee = null;
23
	this.isTaxonListe = false;
23
	this.isTaxonListe = false;
24
	this.autocompletionElementsNbre = null;
24
	this.autocompletionElementsNbre = null;
25
	this.referentielImpose = null;
25
	this.referentielImpose = null;
26
	this.serviceAutocompletionNomSciUrl = null;
26
	this.serviceAutocompletionNomSciUrl = null;
27
	this.serviceAutocompletionNomSciUrlTpl = null;
27
	this.serviceAutocompletionNomSciUrlTpl = null;
28
	this.obsMaxNbre = null;
28
	this.obsMaxNbre = null;
29
	this.dureeMessage = null;
29
	this.dureeMessage = null;
30
	this.serviceAnnuaireIdUrl = null;
30
	this.serviceAnnuaireIdUrl = null;
31
	this.serviceNomCommuneUrl = null;
31
	this.serviceNomCommuneUrl = null;
32
	this.serviceNomCommuneUrlAlt = null;
32
	this.serviceNomCommuneUrlAlt = null;
33
	this.chargementIconeUrl = null;
33
	this.chargementIconeUrl = null;
34
	this.chargementImageIconeUrl = null;
34
	this.chargementImageIconeUrl = null;
35
	this.calendrierIconeUrl = null;
35
	this.calendrierIconeUrl = null;
36
	this.pasDePhotoIconeUrl = null;
36
	this.pasDePhotoIconeUrl = null;
37
 
37
 
38
	// système de traduction minimaliste
38
	// système de traduction minimaliste
39
	this.msgs = {
39
	this.msgs = {
40
		fr: {
40
		fr: {
41
			'format-non-supporte': 'Le format de fichier n\'est pas supporté, les formats acceptés sont',
41
			'format-non-supporte': 'Le format de fichier n\'est pas supporté, les formats acceptés sont',
42
			'date-incomplete': 'Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.',
42
			'date-incomplete': 'Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.',
43
			'observations-transmises': 'observations transmises',
43
			'observations-transmises': 'observations transmises',
44
			'taxon-ou-image' : 'Veuillez transmettre au moins, soit une image, soit une espèce',
44
			'taxon-ou-image' : 'Veuillez transmettre au moins, soit une image, soit une espèce',
45
			'supprimer-observation-liste': 'Supprimer cette observation de la liste à transmettre',
45
			'supprimer-observation-liste': 'Supprimer cette observation de la liste à transmettre',
46
			'milieu': 'Milieu',
46
			'milieu': 'Milieu',
47
			'commentaires': 'Commentaires',
47
			'commentaires': 'Commentaires',
48
			'erreur-inconnue': 'Erreur inconnue',
48
			'erreur-inconnue': 'Erreur inconnue',
49
			'non-lie-au-ref': 'non lié au référentiel',
49
			'non-lie-au-ref': 'non lié au référentiel',
50
			'obs-le': 'le',
50
			'obs-le': 'le',
51
			'quitter-page' : 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.',
51
			'quitter-page' : 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.',
52
			'courriel-connu' : 'Un compte existe pour ce courriel, connectez-vous pour saisir votre observation',
52
			'courriel-connu' : 'Un compte existe pour ce courriel, connectez-vous pour saisir votre observation',
53
			'obs-numero' : 'Observation n°',
53
			'obs-numero' : 'Observation n°',
54
			'erreur-ajax' : 'Erreur Ajax',
54
			'erreur-ajax' : 'Erreur Ajax',
55
			'erreur' : 'Erreur',
55
			'erreur' : 'Erreur',
56
			'erreur-chargement' : 'Erreur lors du chargement de l\'observation',
56
			'erreur-chargement' : 'Erreur lors du chargement de l\'observation',
57
			'lieu-obs' : 'observé à',
57
			'lieu-obs' : 'observé à',
58
			'lieu-dit' : 'Lieu-dit',
58
			'lieu-dit' : 'Lieu-dit',
59
			'station' : 'Station'
59
			'station' : 'Station'
60
		},
60
		},
61
		en: {
61
		en: {
62
			'format-non-supporte': 'The file format is not supported, the accepted formats are',
62
			'format-non-supporte': 'The file format is not supported, the accepted formats are',
63
			'date-incomplete': 'Format: dd / mm / yyyy. Incomplete date, use 0, example: 00/12/2011.',
63
			'date-incomplete': 'Format: dd / mm / yyyy. Incomplete date, use 0, example: 00/12/2011.',
64
			'observations-transmises': 'observations transmitted',
64
			'observations-transmises': 'observations transmitted',
65
			'taxon-ou-image' : 'Please transmit at least one image or one species',
65
			'taxon-ou-image' : 'Please transmit at least one image or one species',
66
			'supprimer-observation-liste': 'Delete this observation from the list to be transmitted',
66
			'supprimer-observation-liste': 'Delete this observation from the list to be transmitted',
67
			'milieu': 'Environment',
67
			'milieu': 'Environment',
68
			'commentaires': 'Comments',
68
			'commentaires': 'Comments',
69
			'erreur-inconnue': 'Unknown error',
69
			'erreur-inconnue': 'Unknown error',
70
			'non-lie-au-ref': 'unrelated to the referencial ',
70
			'non-lie-au-ref': 'unrelated to the referencial ',
71
			'obs-le': 'the',
71
			'obs-le': 'the',
72
			'quitter-page' : 'Are you sure you want to leave the page?\nThe observations entered but not transmitted will be lost.',
72
			'quitter-page' : 'Are you sure you want to leave the page?\nThe observations entered but not transmitted will be lost.',
73
			'courriel-connu' : 'An account exists for this email, log in to enter your observation',
73
			'courriel-connu' : 'An account exists for this email, log in to enter your observation',
74
			'obs-numero' : 'Observation number ',
74
			'obs-numero' : 'Observation number ',
75
			'erreur-ajax' : 'Ajax Error',
75
			'erreur-ajax' : 'Ajax Error',
76
			'erreur' : 'Error',
76
			'erreur' : 'Error',
77
			'erreur-chargement' : 'Error loading the observation',
77
			'erreur-chargement' : 'Error loading the observation',
78
			'lieu-obs' : 'observed at',
78
			'lieu-obs' : 'observed at',
79
			'lieu-dit' : 'Locality',
79
			'lieu-dit' : 'Locality',
80
			'station' : 'Place'
80
			'station' : 'Place'
81
		}
81
		}
82
	};
82
	};
83
}
83
}
84
 
84
 
85
/**
85
/**
86
 * Initialisation du widget
86
 * Initialisation du widget
87
 */
87
 */
88
WidgetSaisie.prototype.init = function() {
88
WidgetSaisie.prototype.init = function() {
89
	this.initForm();
89
	this.initForm();
90
	this.initEvts();
90
	this.initEvts();
91
	// Auth.js s'en occuppe
91
	// Auth.js s'en occuppe
92
	if ( '' === $( '#nom-complet').text() && valeurOk ( $( '#courriel' ).val() ) ) {
92
	if ( '' === $( '#nom-complet').text() && valeurOk ( $( '#courriel' ).val() ) ) {
93
		this.requeterIdentite();
93
		this.requeterIdentite();
94
	}
94
	}
95
};
95
};
96
 
96
 
97
/**
97
/**
98
 * Initialise le formulaire, les validateurs, les listes de complétion...
98
 * Initialise le formulaire, les validateurs, les listes de complétion...
99
 */
99
 */
100
WidgetSaisie.prototype.initForm = function() {
100
WidgetSaisie.prototype.initForm = function() {
101
 
101
 
102
	var lthis = this;
102
	var lthis = this;
103
	if ( valeurOk( this.obsId ) ) {
103
	if ( valeurOk( this.obsId ) ) {
104
		this.chargerInfoObs();
104
		this.chargerInfoObs();
105
	}
105
	}
106
 
106
 
107
	if( this.isTaxonListe ) {
107
	if( this.isTaxonListe ) {
108
		this.surChangementTaxonListe();
108
		this.surChangementTaxonListe();
109
		$( '#taxon-liste' ).on( 'change', lthis.surChangementTaxonListe );
109
		$( '#taxon-liste' ).on( 'change', lthis.surChangementTaxonListe );
110
		$( '#taxon-liste' ).on( 'change', lthis.surChangementValeurTaxon.bind( lthis ) );
110
		$( '#taxon-liste' ).on( 'change', lthis.surChangementValeurTaxon.bind( lthis ) );
111
		if ( this.debug ) {
111
		if ( this.debug ) {
112
			console.log( 'Selected taxon:' + $( '#taxon-liste option:selected' ).val());
112
			console.log( 'Selected taxon:' + $( '#taxon-liste option:selected' ).val());
113
		}
113
		}
114
	} else {
114
	} else {
115
		this.ajouterAutocompletionNoms();
115
		this.ajouterAutocompletionNoms();
116
	}
116
	}
117
	// au rafraichissement de la page,
117
	// au rafraichissement de la page,
118
	// les input date semblent conserver la valeur entrée précedemment
118
	// les input date semblent conserver la valeur entrée précedemment
119
	// c'est voulu après la création d'un obs mais pas quand la page est actualisée
119
	// c'est voulu après la création d'un obs mais pas quand la page est actualisée
120
	// Déjà tenté: onbeforeunload avec un location.reload(true) n'a pas permis de le faire
120
	// Déjà tenté: onbeforeunload avec un location.reload(true) n'a pas permis de le faire
121
	$( 'input[type=date]' ).each( function () {
121
	$( 'input[type=date]' ).each( function () {
122
		( valeurOk( $( this ).data( 'default' ) ) ) ? $( this ).val( $( this ).data( 'default' ) ) : $( this ).val( '' );
122
		( valeurOk( $( this ).data( 'default' ) ) ) ? $( this ).val( $( this ).data( 'default' ) ) : $( this ).val( '' );
123
	});
123
	});
124
	this.configurerFormValidator();
124
	this.configurerFormValidator();
125
	this.definirReglesFormValidator();
125
	this.definirReglesFormValidator();
126
 
126
 
127
	if( this.especeImposee ) {
127
	if( this.especeImposee ) {
128
	  $( '#taxon' ).attr( 'disabled', 'disabled' );
128
	  $( '#taxon' ).attr( 'disabled', 'disabled' );
129
	  $( '#taxon-input-groupe' ).attr( 'title', '' );
129
	  $( '#taxon-input-groupe' ).attr( 'title', '' );
130
	  // Bricolage cracra pour avoir le nom retenu avec auteur (nom_retenu.libelle ne le mentionne pas)
130
	  // Bricolage cracra pour avoir le nom retenu avec auteur (nom_retenu.libelle ne le mentionne pas)
131
	  var infosEspeceImposee = $.parseJSON( this.infosEspeceImposee );
131
	  var infosEspeceImposee = $.parseJSON( this.infosEspeceImposee );
132
	  var nomRetenuComplet = infosEspeceImposee.nom_retenu_complet,
132
	  var nomRetenuComplet = infosEspeceImposee.nom_retenu_complet,
133
	    debutAnneRefBiblio = nomRetenuComplet.indexOf( ' [' );
133
	    debutAnneRefBiblio = nomRetenuComplet.indexOf( ' [' );
134
	  if ( -1 !== debutAnneRefBiblio ) {
134
	  if ( -1 !== debutAnneRefBiblio ) {
135
	    nomRetenuComplet = nomRetenuComplet.substr( 0, debutAnneRefBiblio );
135
	    nomRetenuComplet = nomRetenuComplet.substr( 0, debutAnneRefBiblio );
136
	  }
136
	  }
137
	  // fin bricolage cracra
137
	  // fin bricolage cracra
138
	  var infosAssociee = {
138
	  var infosAssociee = {
139
	    label : infosEspeceImposee.nom_sci_complet,
139
	    label : infosEspeceImposee.nom_sci_complet,
140
	    value : infosEspeceImposee.nom_sci_complet,
140
	    value : infosEspeceImposee.nom_sci_complet,
141
	    nt : infosEspeceImposee.num_taxonomique,
141
	    nt : infosEspeceImposee.num_taxonomique,
142
	    nomSel : infosEspeceImposee.nom_sci,
142
	    nomSel : infosEspeceImposee.nom_sci,
143
	    nomSelComplet : infosEspeceImposee.nom_sci_complet,
143
	    nomSelComplet : infosEspeceImposee.nom_sci_complet,
144
	    numNomSel : infosEspeceImposee.id,
144
	    numNomSel : infosEspeceImposee.id,
145
	    nomRet : nomRetenuComplet,
145
	    nomRet : nomRetenuComplet,
146
	    numNomRet : infosEspeceImposee['nom_retenu.id'],
146
	    numNomRet : infosEspeceImposee['nom_retenu.id'],
147
	    famille : infosEspeceImposee.famille,
147
	    famille : infosEspeceImposee.famille,
148
	    retenu : ( 'false' === infosEspeceImposee.retenu ) ? false : true
148
	    retenu : ( 'false' === infosEspeceImposee.retenu ) ? false : true
149
	  };
149
	  };
150
	  $( '#taxon' ).data( infosAssociee );
150
	  $( '#taxon' ).data( infosAssociee );
151
	}
151
	}
152
};
152
};
153
 
153
 
154
/**
154
/**
155
 * Initialise les écouteurs d'événements
155
 * Initialise les écouteurs d'événements
156
 */
156
 */
157
WidgetSaisie.prototype.initEvts = function() {
157
WidgetSaisie.prototype.initEvts = function() {
158
	var lthis = this;
158
	var lthis = this;
159
 
-
 
160
 
-
 
161
 
159
 
162
	// identité
160
	// identité
163
	$( '#bouton-anonyme' ).on( 'click', function() {
161
	$( '#bouton-anonyme' ).on( 'click', function() {
164
		$( this ).css({
162
		$( this ).css({
165
			'background-color': 'rgba(0, 159, 184, 0.7)',
163
			'background-color': 'rgba(0, 159, 184, 0.7)',
166
			'color': '#fff'
164
			'color': '#fff'
167
		});
165
		});
168
		$( '#anonyme' ).removeClass( 'hidden' );
166
		$( '#anonyme' ).removeClass( 'hidden' );
169
		$( '#courriel' ).focus();
167
		$( '#courriel' ).focus();
170
	});
168
	});
171
	if ( '' === $( '#nom-complet').text() ) {
169
	if ( '' === $( '#nom-complet').text() ) {
172
		$( '#courriel' ).on( 'blur', this.requeterIdentite.bind( this ) );
170
		$( '#courriel' ).on( 'blur', this.requeterIdentite.bind( this ) );
173
		$( '#courriel' ).on( 'keypress', this.testerLancementRequeteIdentite.bind( this ) );
171
		$( '#courriel' ).on( 'keypress', this.testerLancementRequeteIdentite.bind( this ) );
174
	}
172
	}
175
	$( '#prenom' ).on( 'change', this.formaterPrenom );
173
	$( '#prenom' ).on( 'change', this.formaterPrenom );
176
	$( '#nom' ).on( 'change', this.formaterNom );
174
	$( '#nom' ).on( 'change', this.formaterNom );
177
	$( '#courriel_confirmation' ).on( 'paste', this.bloquerCopierCollerCourriel.bind( this ) );
175
	$( '#courriel_confirmation' ).on( 'paste', this.bloquerCopierCollerCourriel.bind( this ) );
178
 
176
 
179
	// Sur téléchargement image
177
	// Sur téléchargement image
180
	$( '#fichier' ).on( 'change', function ( e ) {
178
	$( '#fichier' ).on( 'change', function ( e ) {
181
		arreter( e );
179
		arreter( e );
182
		var options = {
180
		var options = {
183
			success: lthis.afficherMiniature.bind( lthis ), // post-submit callback
181
			success: lthis.afficherMiniature.bind( lthis ), // post-submit callback
184
			dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
182
			dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
185
			resetForm: true // reset the form after successful submit
183
			resetForm: true // reset the form after successful submit
186
		};
184
		};
187
		$( '#miniature' ).append( '<img id="miniature-chargement" class="miniature" alt="chargement" src="' + this.chargementImageIconeUrl + '"/>' );
185
		$( '#miniature' ).append( '<img id="miniature-chargement" class="miniature" alt="chargement" src="' + this.chargementImageIconeUrl + '"/>' );
188
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
186
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
189
		if( lthis.verifierFormat( $( '#fichier' ).val() ) ) {
187
		if( lthis.verifierFormat( $( '#fichier' ).val() ) ) {
190
			$( '#form-upload' ).ajaxSubmit( options );
188
			$( '#form-upload' ).ajaxSubmit( options );
191
		} else {
189
		} else {
192
			$( '#form-upload' )[0].reset();
190
			$( '#form-upload' )[0].reset();
193
			window.alert( lthis.msgTraduction( 'format-non-supporte' ) + ' ' + $( '#fichier' ).attr( 'accept' ) );
191
			window.alert( lthis.msgTraduction( 'format-non-supporte' ) + ' ' + $( '#fichier' ).attr( 'accept' ) );
194
		}
192
		}
195
		return false;
193
		return false;
196
	});
194
	});
197
 
195
 
198
	$( 'body' ).on( 'click', '.effacer-miniature', function() {
196
	$( 'body' ).on( 'click', '.effacer-miniature', function() {
199
		$( this ).parent().remove();
197
		$( this ).parent().remove();
200
	});
198
	});
201
 
199
 
202
	$( '#referentiel' ).on( 'change', this.surChangementReferentiel.bind( this ) );
200
	$( '#referentiel' ).on( 'change', this.surChangementReferentiel.bind( this ) );
203
 
201
 
204
	$( '#ajouter-obs' ).on( 'click', this.ajouterObs.bind( this ) );
202
	$( '#ajouter-obs' ).on( 'click', this.ajouterObs.bind( this ) );
205
	$( '.obs-nbre' ).on( 'changement', this.surChangementNbreObs.bind( this ) );
203
	$( '.obs-nbre' ).on( 'changement', this.surChangementNbreObs.bind( this ) );
206
 
204
 
207
	$( 'body' ).on( 'click', '.defilement-miniatures-gauche', function( event ) {
205
	$( 'body' ).on( 'click', '.defilement-miniatures-gauche', function( event ) {
208
		event.preventDefault();
206
		event.preventDefault();
209
		lthis.defilerMiniatures( $( this ) );
207
		lthis.defilerMiniatures( $( this ) );
210
	});
208
	});
211
	$( 'body' ).on( 'click', '.defilement-miniatures-droite', function( event ) {
209
	$( 'body' ).on( 'click', '.defilement-miniatures-droite', function( event ) {
212
		event.preventDefault();
210
		event.preventDefault();
213
		lthis.defilerMiniatures( $( this ) );
211
		lthis.defilerMiniatures( $( this ) );
214
	});
212
	});
215
	$( 'body' ).on( 'click', '.supprimer-obs', function() {
213
	$( 'body' ).on( 'click', '.supprimer-obs', function() {
216
	 var that = this,
214
	 var that = this,
217
			suppObs = lthis.supprimerObs.bind( lthis );
215
			suppObs = lthis.supprimerObs.bind( lthis );
218
	 // bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
216
	 // bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
219
	 suppObs( that );
217
	 suppObs( that );
220
	});
218
	});
221
 
219
 
222
	$( '#transmettre-obs' ).on( 'click', this.transmettreObs.bind( this ) );
220
	$( '#transmettre-obs' ).on( 'click', this.transmettreObs.bind( this ) );
223
 
221
 
224
	// Alertes et tooltips
222
	// Alertes et tooltips
225
	$( '.alert .close' ).on( 'click', this.fermerPanneauAlert );
223
	$( '.alert .close' ).on( 'click', this.fermerPanneauAlert );
226
	$( '#btn-aide' ).on( 'click', this.basculerAffichageAide );
224
	$( '#btn-aide' ).on( 'click', this.basculerAffichageAide );
227
	$( '.has-tooltip' ).tooltip( 'enable' );
225
	$( '.has-tooltip' ).tooltip( 'enable' );
228
};
226
};
229
 
227
 
230
// Identité Observateur *******************************************************/
228
// Identité Observateur *******************************************************/
231
WidgetSaisie.prototype.requeterIdentite = function() {
229
WidgetSaisie.prototype.requeterIdentite = function() {
232
	var lthis = this;
230
	var lthis = this;
233
	var courriel = $( '#courriel' ).val();
231
	var courriel = $( '#courriel' ).val();
234
	var urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;
232
	var urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;
235
	if ( valeurOk( courriel ) ) {
233
	if ( valeurOk( courriel ) ) {
236
		$.ajax({
234
		$.ajax({
237
			url : urlAnnuaire,
235
			url : urlAnnuaire,
238
			type : 'GET',
236
			type : 'GET',
239
			success : function( data, textStatus, jqXHR ) {
237
			success : function( data, textStatus, jqXHR ) {
240
				if ( lthis.debug ) {
238
				if ( lthis.debug ) {
241
					console.log( 'SUCCESS: ' + textStatus );
239
					console.log( 'SUCCESS: ' + textStatus );
242
				}
240
				}
243
				if ( valeurOk( data ) && valeurOk( data[courriel] ) ) {
241
				if ( valeurOk( data ) && valeurOk( data[courriel] ) ) {
244
					var infos = data[courriel];
242
					var infos = data[courriel];
245
					lthis.surSuccesCompletionCourriel( infos, courriel );
243
					lthis.surSuccesCompletionCourriel( infos, courriel );
246
				} else {
244
				} else {
247
					lthis.surErreurCompletionCourriel();
245
					lthis.surErreurCompletionCourriel();
248
				}
246
				}
249
			},
247
			},
250
			error : function( jqXHR, textStatus, errorThrown ) {
248
			error : function( jqXHR, textStatus, errorThrown ) {
251
				if ( lthis.debug ) {
249
				if ( lthis.debug ) {
252
					console.log( 'ERREUR: '+ textStatus );
250
					console.log( 'ERREUR: '+ textStatus );
253
				}
251
				}
254
				lthis.surErreurCompletionCourriel();
252
				lthis.surErreurCompletionCourriel();
255
			},
253
			},
256
			complete : function( jqXHR, textStatus ) {
254
			complete : function( jqXHR, textStatus ) {
257
				if ( lthis.debug ) {
255
				if ( lthis.debug ) {
258
					console.log( 'COMPLETE: '+ textStatus );
256
					console.log( 'COMPLETE: '+ textStatus );
259
				}
257
				}
260
			}
258
			}
261
		});
259
		});
262
	}
260
	}
263
};
261
};
264
 
262
 
265
WidgetSaisie.prototype.surSuccesCompletionCourriel = function( infos, courriel ) {
263
WidgetSaisie.prototype.surSuccesCompletionCourriel = function( infos, courriel ) {
266
	$( '#zone-courriel' ).before( '<p class="warning"><i class="fas fa-exclamation-triangle"></i> ' + this.msgTraduction( 'courriel-connu' ) + '</p>' );
264
	$( '#zone-courriel' ).before( '<p class="warning"><i class="fas fa-exclamation-triangle"></i> ' + this.msgTraduction( 'courriel-connu' ) + '</p>' );
267
	$( '#bouton-inscription, #zone-prenom-nom, #zone-courriel-confirmation' ).addClass( 'hidden' );
265
	$( '#bouton-inscription, #zone-prenom-nom, #zone-courriel-confirmation' ).addClass( 'hidden' );
268
	$( '#prenom, #nom, #courriel_confirmation' ).attr( 'disabled', 'disabled' );
266
	$( '#prenom, #nom, #courriel_confirmation' ).attr( 'disabled', 'disabled' );
269
	$( '#bouton-connexion a' ).css( 'box-shadow', '0 0 1.5px 1px red' );
267
	$( '#bouton-connexion a' ).css( 'box-shadow', '0 0 1.5px 1px red' );
270
};
268
};
271
 
269
 
272
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
270
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
273
	$( '#creation-compte, #zone-prenom-nom, #zone-courriel-confirmation' ).removeClass( 'hidden' );
271
	$( '#creation-compte, #zone-prenom-nom, #zone-courriel-confirmation' ).removeClass( 'hidden' );
274
	$( '.warning' ).remove();
272
	$( '.warning' ).remove();
275
	$( '#bouton-connexion a' ).css( 'box-shadow', '' );
273
	$( '#bouton-connexion a' ).css( 'box-shadow', '' );
276
 
274
 
277
	$( '#prenom, #nom, #courriel_confirmation' ).val( '' );
275
	$( '#prenom, #nom, #courriel_confirmation' ).val( '' );
278
	$( '#prenom, #nom, #courriel_confirmation' ).removeAttr( 'disabled' );
276
	$( '#prenom, #nom, #courriel_confirmation' ).removeAttr( 'disabled' );
279
};
277
};
280
 
278
 
281
WidgetSaisie.prototype.testerLancementRequeteIdentite = function( event ) {
279
WidgetSaisie.prototype.testerLancementRequeteIdentite = function( event ) {
282
	if ( valeurOk( event.which, true, 13 ) ) {
280
	if ( valeurOk( event.which, true, 13 ) ) {
283
		this.requeterIdentite();
281
		this.requeterIdentite();
284
		event.preventDefault();
282
		event.preventDefault();
285
		event.stopPropagation();
283
		event.stopPropagation();
286
	}
284
	}
287
};
285
};
288
 
286
 
289
WidgetSaisie.prototype.formaterNom = function() {
287
WidgetSaisie.prototype.formaterNom = function() {
290
	$( this ).val( $( this ).val().toUpperCase() );
288
	$( this ).val( $( this ).val().toUpperCase() );
291
};
289
};
292
 
290
 
293
WidgetSaisie.prototype.formaterPrenom = function() {
291
WidgetSaisie.prototype.formaterPrenom = function() {
294
	var prenom = new Array(),
292
	var prenom = new Array(),
295
			mots = $( this ).val().split( ' ' ),
293
			mots = $( this ).val().split( ' ' ),
296
			motsLength = mots.length;
294
			motsLength = mots.length;
297
 
295
 
298
	for ( var i = 0; i < motsLength; i++ ) {
296
	for ( var i = 0; i < motsLength; i++ ) {
299
		var mot = mots[i];
297
		var mot = mots[i];
300
		if ( 0 <= mot.indexOf( '-' ) ) {
298
		if ( 0 <= mot.indexOf( '-' ) ) {
301
			var prenomCompose = new Array(),
299
			var prenomCompose = new Array(),
302
					motsComposes = mot.split( '-' )
300
					motsComposes = mot.split( '-' )
303
					motsComposesLength = motsComposes.length;
301
					motsComposesLength = motsComposes.length;
304
			for ( var j = 0; j < motsComposesLength; j++ ) {
302
			for ( var j = 0; j < motsComposesLength; j++ ) {
305
				var motSimple = motsComposes[j],
303
				var motSimple = motsComposes[j],
306
						motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
304
						motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
307
 
305
 
308
				prenomCompose.push( motMajuscule );
306
				prenomCompose.push( motMajuscule );
309
			}
307
			}
310
			prenom.push( prenomCompose.join( '-' ) );
308
			prenom.push( prenomCompose.join( '-' ) );
311
		} else {
309
		} else {
312
			var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
310
			var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
313
			prenom.push( motMajuscule );
311
			prenom.push( motMajuscule );
314
		}
312
		}
315
	}
313
	}
316
	$( this ).val( prenom.join( ' ' ) );
314
	$( this ).val( prenom.join( ' ' ) );
317
};
315
};
318
 
316
 
319
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
317
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
320
	this.afficherPanneau( '#dialogue-bloquer-copier-coller' );
318
	this.afficherPanneau( '#dialogue-bloquer-copier-coller' );
321
	return false;
319
	return false;
322
};
320
};
323
 
321
 
324
// Préchargement des infos-obs ************************************************/
322
// Préchargement des infos-obs ************************************************/
325
WidgetSaisie.prototype.chargerInfoObs = function() {
323
WidgetSaisie.prototype.chargerInfoObs = function() {
326
	var urlObs = this.serviceObsUrl + '/' + this.obsId;
324
	var urlObs = this.serviceObsUrl + '/' + this.obsId;
327
	var lthis = this;
325
	var lthis = this;
328
	$.ajax({
326
	$.ajax({
329
		url: urlObs,
327
		url: urlObs,
330
		type: 'GET',
328
		type: 'GET',
331
		success: function( data, textStatus, jqXHR ) {
329
		success: function( data, textStatus, jqXHR ) {
332
			if ( valeurOk( data ) ) {
330
			if ( valeurOk( data ) ) {
333
				lthis.prechargerForm( data );
331
				lthis.prechargerForm( data );
334
			} else {
332
			} else {
335
				lthis.surErreurChargementInfosObs.bind( lthis );
333
				lthis.surErreurChargementInfosObs.bind( lthis );
336
			}
334
			}
337
		},
335
		},
338
		error: function( jqXHR, textStatus, errorThrown ) {
336
		error: function( jqXHR, textStatus, errorThrown ) {
339
			lthis.surErreurChargementInfosObs();
337
			lthis.surErreurChargementInfosObs();
340
		}
338
		}
341
	});
339
	});
342
};
340
};
343
 
341
 
344
// @TODO faire mieux que ça !
342
// @TODO faire mieux que ça !
345
WidgetSaisie.prototype.surErreurChargementInfosObs = function() {
343
WidgetSaisie.prototype.surErreurChargementInfosObs = function() {
346
	alert( this.msgTraduction( 'erreur-chargement' ) );
344
	alert( this.msgTraduction( 'erreur-chargement' ) );
347
};
345
};
348
 
346
 
349
WidgetSaisie.prototype.prechargerForm = function( data ) {
347
WidgetSaisie.prototype.prechargerForm = function( data ) {
350
 
348
 
351
	$( '#milieu' ).val( data.milieu );
349
	$( '#milieu' ).val( data.milieu );
352
 
350
 
353
	// $( '#carte-recherche' ).val( data.zoneGeo );
351
	// $( '#carte-recherche' ).val( data.zoneGeo );
354
	// $( '#commune-nom' ).text( data.zoneGeo );
352
	// $( '#commune-nom' ).text( data.zoneGeo );
355
 
353
 
356
	// if( data.hasOwnProperty( 'codeZoneGeo' ) ) {
354
	// if( data.hasOwnProperty( 'codeZoneGeo' ) ) {
357
	//   // TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
355
	//   // TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
358
	//   $( '#commune-code-insee' ).text( data.codeZoneGeo.replace( 'INSEE-C:', '' ) );
356
	//   $( '#commune-code-insee' ).text( data.codeZoneGeo.replace( 'INSEE-C:', '' ) );
359
	// }
357
	// }
360
 
358
 
361
	// if( data.hasOwnProperty( 'latitude' ) && data.hasOwnProperty( 'longitude' ) ) {
359
	// if( data.hasOwnProperty( 'latitude' ) && data.hasOwnProperty( 'longitude' ) ) {
362
	//   var latLng = new google.maps.LatLng( data.latitude, data.longitude );
360
	//   var latLng = new google.maps.LatLng( data.latitude, data.longitude );
363
	//   this.mettreAJourMarkerPosition( latLng );
361
	//   this.mettreAJourMarkerPosition( latLng );
364
	//   this.marker.setPosition( latLng );
362
	//   this.marker.setPosition( latLng );
365
	//   this.map.setCenter( latLng );
363
	//   this.map.setCenter( latLng );
366
	//   this.map.setZoom( 16 );
364
	//   this.map.setZoom( 16 );
367
	// }
365
	// }
368
};
366
};
369
 
367
 
370
// uniquement utilisé si taxon-liste ******************************************/
368
// uniquement utilisé si taxon-liste ******************************************/
371
// Affiche/Cache le champ taxon
369
// Affiche/Cache le champ taxon
372
WidgetSaisie.prototype.surChangementTaxonListe = function() {
370
WidgetSaisie.prototype.surChangementTaxonListe = function() {
373
	if ( valeurOk( $( '#taxon-liste' ).val() ) ) {
371
	if ( valeurOk( $( '#taxon-liste' ).val() ) ) {
374
		if ( 'autre' !== $( '#taxon-liste' ).val() ) {
372
		if ( 'autre' !== $( '#taxon-liste' ).val() ) {
375
			$( '#taxon-input-groupe' ).hide( 200, function () {
373
			$( '#taxon-input-groupe' ).hide( 200, function () {
376
				$( this ).addClass( 'hidden' ).show();
374
				$( this ).addClass( 'hidden' ).show();
377
			});
375
			});
378
		} else {
376
		} else {
379
			$( '#taxon-input-groupe' ).hide().removeClass( 'hidden' ).show(200);
377
			$( '#taxon-input-groupe' ).hide().removeClass( 'hidden' ).show(200);
380
		}
378
		}
381
	}
379
	}
382
};
380
};
383
 
381
 
384
 
382
 
385
WidgetSaisie.prototype.surChangementValeurTaxon = function() {
383
WidgetSaisie.prototype.surChangementValeurTaxon = function() {
386
	var numNomSel = 0;
384
	var numNomSel = 0;
387
 
385
 
388
	if( valeurOk( $( '#taxon-liste' ).val() ) ) {
386
	if( valeurOk( $( '#taxon-liste' ).val() ) ) {
389
		if( 'autre' === $( '#taxon-liste' ).val() ) {
387
		if( 'autre' === $( '#taxon-liste' ).val() ) {
390
			this.ajouterAutocompletionNoms();
388
			this.ajouterAutocompletionNoms();
391
		} else {
389
		} else {
392
			var optionRetenue = $( '#taxon-liste' ).find( 'option[value="' + $( '#taxon-liste' ).val() + '"]' );
390
			var optionRetenue = $( '#taxon-liste' ).find( 'option[value="' + $( '#taxon-liste' ).val() + '"]' );
393
			// $( '#taxon' ).val( $( '#taxon-liste' ).val() );
391
			// $( '#taxon' ).val( $( '#taxon-liste' ).val() );
394
			$( '#taxon' ).val( $( '#taxon-liste' ).val() )
392
			$( '#taxon' ).val( $( '#taxon-liste' ).val() )
395
				.data( 'value', $( '#taxon-liste' ).val() )
393
				.data( 'value', $( '#taxon-liste' ).val() )
396
				.data( 'numNomSel', optionRetenue.data( 'num-nom-sel' ) )
394
				.data( 'numNomSel', optionRetenue.data( 'num-nom-sel' ) )
397
				.data( 'nomRet', optionRetenue.data( 'nom-ret' ) )
395
				.data( 'nomRet', optionRetenue.data( 'nom-ret' ) )
398
				.data( 'numNomRet', optionRetenue.data( 'num-nom-ret' ) )
396
				.data( 'numNomRet', optionRetenue.data( 'num-nom-ret' ) )
399
				.data( 'nt', optionRetenue.data( 'nt' ) )
397
				.data( 'nt', optionRetenue.data( 'nt' ) )
400
				.data( 'famille', optionRetenue.data( 'famille' ) );
398
				.data( 'famille', optionRetenue.data( 'famille' ) );
401
 
399
 
402
			numNomSel = $( '#taxon' ).data( 'numNomSel' );
400
			numNomSel = $( '#taxon' ).data( 'numNomSel' );
403
			// Si l'espèce est mal déterminée la certitude est "à déterminer"
401
			// Si l'espèce est mal déterminée la certitude est "à déterminer"
404
			if( !valeurOk( numNomSel ) ) {
402
			if( !valeurOk( numNomSel ) ) {
405
				$( '#certitude' ).find( 'option' ).each( function() {
403
				$( '#certitude' ).find( 'option' ).each( function() {
406
					if ( $( this ).hasClass( 'aDeterminer' ) ) {
404
					if ( $( this ).hasClass( 'aDeterminer' ) ) {
407
						$( this ).attr( 'selected', true );
405
						$( this ).attr( 'selected', true );
408
					} else {
406
					} else {
409
						$( this ).attr( 'selected', false );
407
						$( this ).attr( 'selected', false );
410
					}
408
					}
411
				});
409
				});
412
			}
410
			}
413
		}
411
		}
414
	}
412
	}
415
};
413
};
416
 
414
 
417
// Autocompletion taxons ******************************************************/
415
// Autocompletion taxons ******************************************************/
418
WidgetSaisie.prototype.ajouterAutocompletionNoms = function() {
416
WidgetSaisie.prototype.ajouterAutocompletionNoms = function() {
419
	var lthis = this;
417
	var lthis = this;
420
 
418
 
421
	var taxonSelecteur = '#taxon';
419
	var taxonSelecteur = '#taxon';
422
	if ( valeurOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
420
	if ( valeurOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
423
		taxonSelecteur += '-autre';
421
		taxonSelecteur += '-autre';
424
	}
422
	}
425
	$( taxonSelecteur ).autocomplete({
423
	$( taxonSelecteur ).autocomplete({
426
		source: function( requete, add ) {
424
		source: function( requete, add ) {
427
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
425
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
428
			requete = '';
426
			requete = '';
429
			if( valeurOk( $( '#referentiel' ).val(), false, 'autre' ) ) {
427
			if( valeurOk( $( '#referentiel' ).val(), false, 'autre' ) ) {
430
				var url = lthis.getUrlAutocompletionNomsSci();
428
				var url = lthis.getUrlAutocompletionNomsSci();
431
				$.getJSON( url, requete, function( data ) {
429
				$.getJSON( url, requete, function( data ) {
432
					var suggestions = lthis.traiterRetourNomsSci( data );
430
					var suggestions = lthis.traiterRetourNomsSci( data );
433
					add( suggestions );
431
					add( suggestions );
-
 
432
				})
-
 
433
				.fail( function() {
-
 
434
				    $( '#certitude' ).find( 'option' ).each( function() {
-
 
435
						if ( $( this ).hasClass( 'aDeterminer' ) ) {
-
 
436
							$( this ).attr( 'selected', true );
-
 
437
						} else {
-
 
438
							$( this ).attr( 'selected', false );
-
 
439
						}
-
 
440
					});
434
				});
441
				});
435
			}
442
			}
436
		},
443
		},
437
		html: true
444
		html: true
438
	});
445
	});
439
	$( taxonSelecteur ).on( 'autocompleteselect change', this.surAutocompletionTaxon );
446
	$( taxonSelecteur ).on( 'autocompleteselect change', this.surAutocompletionTaxon );
440
};
447
};
441
 
448
 
442
WidgetSaisie.prototype.getUrlAutocompletionNomsSci = function() {
449
WidgetSaisie.prototype.getUrlAutocompletionNomsSci = function() {
443
	var taxonSelecteur = '#taxon';
450
	var taxonSelecteur = '#taxon';
444
	if ( valeurOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
451
	if ( valeurOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
445
		taxonSelecteur += '-autre';
452
		taxonSelecteur += '-autre';
446
	}
453
	}
447
	var mots = $( taxonSelecteur ).val();
454
	var mots = $( taxonSelecteur ).val();
448
	var url = this.serviceAutocompletionNomSciUrlTpl.replace( '{referentiel}', this.nomSciReferentiel );
455
	var url = this.serviceAutocompletionNomSciUrlTpl.replace( '{referentiel}', this.nomSciReferentiel );
449
	url = url.replace( '{masque}', mots );
456
	url = url.replace( '{masque}', mots );
450
	return url;
457
	return url;
451
};
458
};
452
 
459
 
453
WidgetSaisie.prototype.traiterRetourNomsSci = function( data ) {
460
WidgetSaisie.prototype.traiterRetourNomsSci = function( data ) {
454
 
461
 
455
	var taxonSelecteur = '#taxon';
462
	var taxonSelecteur = '#taxon';
456
	if ( valeurOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
463
	if ( valeurOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
457
		taxonSelecteur += '-autre';
464
		taxonSelecteur += '-autre';
458
	}
465
	}
459
	var suggestions = [];
466
	var suggestions = [];
460
	if ( undefined != data.resultat ) {
467
	if ( undefined != data.resultat ) {
461
		$.each( data.resultat, function( i, val ) {
468
		$.each( data.resultat, function( i, val ) {
462
			val.nn = i;
469
			val.nn = i;
463
			var nom = {
470
			var nom = {
464
				label : '',
471
				label : '',
465
				value : '',
472
				value : '',
466
				nt : 0,
473
				nt : 0,
467
				nomSel : '',
474
				nomSel : '',
468
				nomSelComplet : '',
475
				nomSelComplet : '',
469
				numNomSel : 0,
476
				numNomSel : 0,
470
				nomRet : '',
477
				nomRet : '',
471
				numNomRet : 0,
478
				numNomRet : 0,
472
				famille : '',
479
				famille : '',
473
				retenu : false
480
				retenu : false
474
			};
481
			};
475
			if ( suggestions.length >= this.autocompletionElementsNbre ) {
482
			if ( suggestions.length >= this.autocompletionElementsNbre ) {
476
				nom.label = '...';
483
				nom.label = '...';
477
				nom.value = $( taxonSelecteur ).val();
484
				nom.value = $( taxonSelecteur ).val();
478
				suggestions.push( nom );
485
				suggestions.push( nom );
479
				return false;
486
				return false;
480
			} else {
487
			} else {
481
				nom.label = val.nom_sci_complet;
488
				nom.label = val.nom_sci_complet;
482
				nom.value = val.nom_sci_complet;
489
				nom.value = val.nom_sci_complet;
483
				nom.nt = val.num_taxonomique;
490
				nom.nt = val.num_taxonomique;
484
				nom.nomSel = val.nom_sci;
491
				nom.nomSel = val.nom_sci;
485
				nom.nomSelComplet = val.nom_sci_complet;
492
				nom.nomSelComplet = val.nom_sci_complet;
486
				nom.numNomSel = val.nn;
493
				nom.numNomSel = val.nn;
487
				nom.nomRet = val.nom_retenu_complet;
494
				nom.nomRet = val.nom_retenu_complet;
488
				nom.numNomRet = val['nom_retenu.id'];
495
				nom.numNomRet = val['nom_retenu.id'];
489
				nom.famille = val.famille;
496
				nom.famille = val.famille;
490
				// Tester dans ce sens, permet de considérer 'absent' comme 'false' => est-ce opportun ?
497
				// Tester dans ce sens, permet de considérer 'absent' comme 'false' => est-ce opportun ?
491
				// en tout cas c'est harmonisé avec le CeL
498
				// en tout cas c'est harmonisé avec le CeL
492
				nom.retenu = ( 'true' == val.retenu );
499
				nom.retenu = ( 'true' == val.retenu );
493
 
500
 
494
				suggestions.push( nom );
501
				suggestions.push( nom );
495
			}
502
			}
496
		});
503
		});
497
	}
504
	}
498
	return suggestions;
505
	return suggestions;
499
};
506
};
500
 
507
 
501
WidgetSaisie.prototype.surAutocompletionTaxon = function( event, ui ) {
508
WidgetSaisie.prototype.surAutocompletionTaxon = function( event, ui ) {
502
 
509
 
503
	if ( valeurOk( ui ) ) {
510
	if ( valeurOk( ui ) ) {
504
		$( '#taxon' ).val( ui.item.value );
511
		$( '#taxon' ).val( ui.item.value );
505
		$( '#taxon' ).data( 'value', ui.item.value )
512
		$( '#taxon' ).data( 'value', ui.item.value )
506
			.data( 'numNomSel', ui.item.numNomSel )
513
			.data( 'numNomSel', ui.item.numNomSel )
507
			.data( 'nomRet', ui.item.nomRet )
514
			.data( 'nomRet', ui.item.nomRet )
508
			.data( 'numNomRet', ui.item.numNomRet )
515
			.data( 'numNomRet', ui.item.numNomRet )
509
			.data( 'nt', ui.item.nt )
516
			.data( 'nt', ui.item.nt )
510
			.data( 'famille', ui.item.famille );
517
			.data( 'famille', ui.item.famille );
511
		if ( ui.item.retenu ) {
518
		if ( ui.item.retenu ) {
512
			$( '#taxon' ).addClass( 'ns-retenu' );
519
			$( '#taxon' ).addClass( 'ns-retenu' );
513
		} else {
520
		} else {
514
			$( '#taxon' ).removeClass( 'ns-retenu' );
521
			$( '#taxon' ).removeClass( 'ns-retenu' );
515
		}
522
		}
516
 
523
 
517
		// Si l'espèce est mal déterminée la certitude est "à déterminer"
524
		// Si l'espèce est mal déterminée la certitude est "à déterminer"
518
		if( !valeurOk( $( '#taxon' ).data( 'numNomSel' ) ) ) {
525
		if( !valeurOk( $( '#taxon' ).data( 'numNomSel' ) ) ) {
519
			$( '#certitude' ).find( 'option' ).each( function() {
526
			$( '#certitude' ).find( 'option' ).each( function() {
520
				if ( $( this ).hasClass( 'aDeterminer' ) ) {
527
				if ( $( this ).hasClass( 'aDeterminer' ) ) {
521
					$( this ).attr( 'selected', true );
528
					$( this ).attr( 'selected', true );
522
				} else {
529
				} else {
523
					$( this ).attr( 'selected', false );
530
					$( this ).attr( 'selected', false );
524
				}
531
				}
525
			});
532
			});
526
		}
533
		}
527
	}
534
	}
528
};
535
};
529
 
536
 
530
// Form Validator *************************************************************/
537
// Form Validator *************************************************************/
531
WidgetSaisie.prototype.configurerFormValidator = function() {
538
WidgetSaisie.prototype.configurerFormValidator = function() {
532
		var lthis = this;
539
		var lthis = this;
533
 
540
 
534
	$.validator.addMethod(
541
	$.validator.addMethod(
535
		'dateCel',
542
		'dateCel',
536
		function ( value, element ) {
543
		function ( value, element ) {
537
			return ( valeurOk( value ) && ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) ) );
544
			return ( valeurOk( value ) && ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) ) );
538
		},
545
		},
539
		lthis.msgTraduction( 'date-incomplete' )
546
		lthis.msgTraduction( 'date-incomplete' )
540
	);
547
	);
541
 
548
 
542
	$.validator.addMethod(
549
	$.validator.addMethod(
543
		'userEmailOk',
550
		'userEmailOk',
544
		function ( value, element ) {
551
		function ( value, element ) {
545
			return ( valeurOk( value ) );
552
			return ( valeurOk( value ) );
546
		},
553
		},
547
		''
554
		''
548
	);
555
	);
549
 
556
 
550
	$.validator.addMethod(
557
	$.validator.addMethod(
551
		'minMaxOk',
558
		'minMaxOk',
552
		function ( value, element, param ) {
559
		function ( value, element, param ) {
553
			$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message;
560
			$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message;
554
			return lthis.validerMinMax( element ).cond;
561
			return lthis.validerMinMax( element ).cond;
555
		},
562
		},
556
		$.validator.messages.minMaxOk
563
		$.validator.messages.minMaxOk
557
	);
564
	);
558
 
565
 
559
	$.validator.addMethod(
566
	$.validator.addMethod(
560
		'listFields',
567
		'listFields',
561
		function ( value, element ) {
568
		function ( value, element ) {
562
			return ( valeurOk( value ) );
569
			return ( valeurOk( value ) );
563
		},
570
		},
564
		''
571
		''
565
	);
572
	);
566
 
573
 
567
	$.extend( $.validator.defaults, {
574
	$.extend( $.validator.defaults, {
568
		errorElement: 'span',
575
		errorElement: 'span',
569
		onfocusout: function( element ) {
576
		onfocusout: function( element ) {
570
			if ( $( element ).valid() ) {
577
			if ( $( element ).valid() ) {
571
				$( element ).closest( '.control-group' ).removeClass( 'error' );
578
				$( element ).closest( '.control-group' ).removeClass( 'error' );
572
			} else {
579
			} else {
573
				$( element ).closest( '.control-group' ).addClass( 'error' );
580
				$( element ).closest( '.control-group' ).addClass( 'error' );
574
			}
581
			}
575
		},
582
		},
576
		onkeyup : function( element ) {
583
		onkeyup : function( element ) {
577
			if ( $( element ).valid() ) {
584
			if ( $( element ).valid() ) {
578
				$( element ).closest( '.control-group' ).removeClass( 'error' );
585
				$( element ).closest( '.control-group' ).removeClass( 'error' );
579
			} else {
586
			} else {
580
				$( element ).closest( '.control-group' ).addClass( 'error' );
587
				$( element ).closest( '.control-group' ).addClass( 'error' );
581
			}
588
			}
582
		},
589
		},
583
		highlight: function( element ) {
590
		highlight: function( element ) {
584
			$( element ).closest( '.control-group' ).addClass( 'error' );
591
			$( element ).closest( '.control-group' ).addClass( 'error' );
585
		},
592
		},
586
		unhighlight: function( element ) {
593
		unhighlight: function( element ) {
587
			$( element ).closest( '.control-group' ).removeClass( 'error' );
594
			$( element ).closest( '.control-group' ).removeClass( 'error' );
588
		},
595
		},
589
 
596
 
590
	});
597
	});
591
};
598
};
592
 
599
 
593
 
600
 
594
/**
601
/**
595
 * validation des champs étendus
602
 * validation des champs étendus
596
 */
603
 */
597
WidgetSaisie.prototype.chpEtendusValidation = function() {
604
WidgetSaisie.prototype.chpEtendusValidation = function() {
598
	var lthis = this;
605
	var lthis = this;
599
	var $thisForm = $( '#form-supp' ),
606
	var $thisForm = $( '#form-supp' ),
600
			elements  =
607
			elements  =
601
				'.checkbox,'+
608
				'.checkbox,'+
602
				'.radio,'+
609
				'.radio,'+
603
				'.checkboxes,'+
610
				'.checkboxes,'+
604
				'.select,'+
611
				'.select,'+
605
				'textarea,'+
612
				'textarea,'+
606
				'input[type=text]:not(.collect-other),'+
613
				'input[type=text]:not(.collect-other),'+
607
				'input[type=email],'+
614
				'input[type=email],'+
608
				'input[type=number],'+
615
				'input[type=number],'+
609
				'input[type=range],'+
616
				'input[type=range],'+
610
				'input[type=date]',
617
				'input[type=date]',
611
			speFields = ['checkbox','radio','checkboxes','select'],
618
			speFields = ['checkbox','radio','checkboxes','select'],
612
			spefieldsCount = speFields.length,
619
			spefieldsCount = speFields.length,
613
			chpSuppValidation = {
620
			chpSuppValidation = {
614
				rules : {},
621
				rules : {},
615
				messages : {},
622
				messages : {},
616
				minmax : []
623
				minmax : []
617
			},
624
			},
618
			errors = {},
625
			errors = {},
619
			namesListFields = [],
626
			namesListFields = [],
620
			picked = '';
627
			picked = '';
621
 
628
 
622
	$( elements, $thisForm ).each( function() {
629
	$( elements, $thisForm ).each( function() {
623
		for( var fieldsClass = 0; spefieldsCount > fieldsClass; fieldsClass++ ) {
630
		for( var fieldsClass = 0; spefieldsCount > fieldsClass; fieldsClass++ ) {
624
			if ( valeurOk( $( this ).attr( 'required' ) ) && $( this ).hasClass( speFields[fieldsClass] ) && !valeurOk( chpSuppValidation.rules[ dataName ] ) ) {
631
			if ( valeurOk( $( this ).attr( 'required' ) ) && $( this ).hasClass( speFields[fieldsClass] ) && !valeurOk( chpSuppValidation.rules[ dataName ] ) ) {
625
				var dataName = $( this ).data( 'name' );
632
				var dataName = $( this ).data( 'name' );
626
 
633
 
627
				namesListFields.push( dataName );
634
				namesListFields.push( dataName );
628
				chpSuppValidation.rules[ dataName ] = { required : true };
635
				chpSuppValidation.rules[ dataName ] = { required : true };
629
 
636
 
630
				if ( valeurOk( $( '.other', $( this ) ) ) ) {
637
				if ( valeurOk( $( '.other', $( this ) ) ) ) {
631
					picked = ( 'select' === speFields[fieldsClass] ) ? ':selected' : ':checked';
638
					picked = ( 'select' === speFields[fieldsClass] ) ? ':selected' : ':checked';
632
					chpSuppValidation.rules[ 'collect-other-' + dataName.replace( '[]', '' ) ] = {
639
					chpSuppValidation.rules[ 'collect-other-' + dataName.replace( '[]', '' ) ] = {
633
						required : '#other-' + dataName.replace( '[]', '' ) + picked,
640
						required : '#other-' + dataName.replace( '[]', '' ) + picked,
634
						minlength: 1
641
						minlength: 1
635
					};
642
					};
636
					chpSuppValidation.messages[ 'collect-other-' + dataName.replace( '[]', '' ) ] = false;
643
					chpSuppValidation.messages[ 'collect-other-' + dataName.replace( '[]', '' ) ] = false;
637
				}
644
				}
638
				chpSuppValidation.rules[ dataName ]['listFields'] = true;
645
				chpSuppValidation.rules[ dataName ]['listFields'] = true;
639
				chpSuppValidation.messages[ dataName ] = 'Ce champ est requis :\nVeuillez choisir une option, ou entrer une valeur autre valide.';
646
				chpSuppValidation.messages[ dataName ] = 'Ce champ est requis :\nVeuillez choisir une option, ou entrer une valeur autre valide.';
640
				errors[dataName] = '.' + speFields[fieldsClass];
647
				errors[dataName] = '.' + speFields[fieldsClass];
641
			}
648
			}
642
		}
649
		}
643
		if ( valeurOk( $( this ).attr( 'name' ) ) && valeurOk ( $( this ).attr( 'required' ) ) && 0 > $.inArray( $( this ).attr( 'name' ) , namesListFields ) ) {
650
		if ( valeurOk( $( this ).attr( 'name' ) ) && valeurOk ( $( this ).attr( 'required' ) ) && 0 > $.inArray( $( this ).attr( 'name' ) , namesListFields ) ) {
644
			chpSuppValidation.rules[ $( this ).attr( 'name' ) ] = { required : true, minlength: 1 };
651
			chpSuppValidation.rules[ $( this ).attr( 'name' ) ] = { required : true, minlength: 1 };
645
			if(
652
			if(
646
					( valeurOk( $( this ).attr( 'type' ), true, 'number' ) || valeurOk( $( this ).attr( 'type' ), true, 'range' ) ) &&
653
					( valeurOk( $( this ).attr( 'type' ), true, 'number' ) || valeurOk( $( this ).attr( 'type' ), true, 'range' ) ) &&
647
					( valeurOk( $( this )[0].min ) || valeurOk( $( this )[0].max ) )
654
					( valeurOk( $( this )[0].min ) || valeurOk( $( this )[0].max ) )
648
				) {
655
				) {
649
				chpSuppValidation.rules[ $( this ).attr('name') ]['minMaxOk'] = true;
656
				chpSuppValidation.rules[ $( this ).attr('name') ]['minMaxOk'] = true;
650
				chpSuppValidation.messages[ $( this ).attr('name') ] = lthis.validerMinMax( $( this )[0] ).message;
657
				chpSuppValidation.messages[ $( this ).attr('name') ] = lthis.validerMinMax( $( this )[0] ).message;
651
			}
658
			}
652
		}
659
		}
653
	});
660
	});
654
	if ( valeurOk( chpSuppValidation.rules ) ) {
661
	if ( valeurOk( chpSuppValidation.rules ) ) {
655
		$.each( chpSuppValidation.rules, function( key ) {
662
		$.each( chpSuppValidation.rules, function( key ) {
656
			if ( !valeurOk( chpSuppValidation.messages[key] ) ) {
663
			if ( !valeurOk( chpSuppValidation.messages[key] ) ) {
657
				chpSuppValidation.messages[key] = 'Ce champ est requis :\nVeuillez entrer une valeur valide.';
664
				chpSuppValidation.messages[key] = 'Ce champ est requis :\nVeuillez entrer une valeur valide.';
658
			}
665
			}
659
		});
666
		});
660
		if ( 0 < Object.keys( errors ).length ) {
667
		if ( 0 < Object.keys( errors ).length ) {
661
			chpSuppValidation['errors'] = errors;
668
			chpSuppValidation['errors'] = errors;
662
		}
669
		}
663
	}
670
	}
664
	return chpSuppValidation;
671
	return chpSuppValidation;
665
};
672
};
666
 
673
 
667
WidgetSaisie.prototype.validerMinMax = function( element ) {
674
WidgetSaisie.prototype.validerMinMax = function( element ) {
668
 
675
 
669
	var mMCond      = new Boolean(),
676
	var mMCond      = new Boolean(),
670
			minCond     = parseFloat( element.value ) >= parseFloat( element.min ),
677
			minCond     = parseFloat( element.value ) >= parseFloat( element.min ),
671
			maxCond     = parseFloat( element.value ) <= parseFloat( element.max ),
678
			maxCond     = parseFloat( element.value ) <= parseFloat( element.max ),
672
			messageMnMx = 'La valeur entrée doit être',
679
			messageMnMx = 'La valeur entrée doit être',
673
			returnMnMx  = { cond : true , message : '' };
680
			returnMnMx  = { cond : true , message : '' };
674
 
681
 
675
	if(
682
	if(
676
			( valeurOk( element.type, true, 'number' ) || valeurOk( element.type, true, 'range' ) ) &&
683
			( valeurOk( element.type, true, 'number' ) || valeurOk( element.type, true, 'range' ) ) &&
677
			( valeurOk( element.min ) || valeurOk( element.max ) )
684
			( valeurOk( element.min ) || valeurOk( element.max ) )
678
		) {
685
		) {
679
		if ( element.min && element.max ) {
686
		if ( element.min && element.max ) {
680
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
687
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
681
			mnMxCond     = ( minCond && maxCond );
688
			mnMxCond     = ( minCond && maxCond );
682
		} else if ( element.min ) {
689
		} else if ( element.min ) {
683
			messageMnMx += ' supérieure à ' + element.min;
690
			messageMnMx += ' supérieure à ' + element.min;
684
			mnMxCond     = minCond;
691
			mnMxCond     = minCond;
685
		} else {
692
		} else {
686
			messageMnMx += ' inférieure à ' + element.max;
693
			messageMnMx += ' inférieure à ' + element.max;
687
			mnMxCond     = maxCond;
694
			mnMxCond     = maxCond;
688
		}
695
		}
689
		returnMnMx.cond    = mnMxCond;
696
		returnMnMx.cond    = mnMxCond;
690
		returnMnMx.message = messageMnMx;
697
		returnMnMx.message = messageMnMx;
691
	}
698
	}
692
	return returnMnMx;
699
	return returnMnMx;
693
 
700
 
694
};
701
};
695
 
702
 
696
 
703
 
697
WidgetSaisie.prototype.definirReglesFormValidator = function() {
704
WidgetSaisie.prototype.definirReglesFormValidator = function() {
698
	var formSuppValidation = this.chpEtendusValidation();
705
	var formSuppValidation = this.chpEtendusValidation();
699
 
706
 
700
	$( '#form-supp' ).validate({
707
	$( '#form-supp' ).validate({
701
		onclick : function( element ) {
708
		onclick : function( element ) {
702
			if (
709
			if (
703
				(
710
				(
704
					valeurOk( element.type, true, 'checkbox' ) ||
711
					valeurOk( element.type, true, 'checkbox' ) ||
705
					valeurOk( element.type, true, 'radio' )
712
					valeurOk( element.type, true, 'radio' )
706
				) &&
713
				) &&
707
				(
714
				(
708
					!valeurOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':checked' ) ) ||
715
					!valeurOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':checked' ) ) ||
709
					valeurOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':not(.other):checked' ) ) ||
716
					valeurOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':not(.other):checked' ) ) ||
710
					!valeurOk( $( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ) ) ||
717
					!valeurOk( $( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ) ) ||
711
					$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) ||
718
					$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) ||
712
					(
719
					(
713
						$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) &&
720
						$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) &&
714
						$( element ).closest( '.control-group' ).hasClass('error')
721
						$( element ).closest( '.control-group' ).hasClass('error')
715
					)
722
					)
716
				)
723
				)
717
			) {
724
			) {
718
				$( element ).valid();
725
				$( element ).valid();
719
				if ( $( element ).valid() ) {
726
				if ( $( element ).valid() ) {
720
					$( element ).closest( '.control-group' ).removeClass( 'error' );
727
					$( element ).closest( '.control-group' ).removeClass( 'error' );
721
					$( element ).next( $( 'span.error' ) ).remove();
728
					$( element ).next( $( 'span.error' ) ).remove();
722
				} else {
729
				} else {
723
					$( element ).closest( '.control-group' ).addClass( 'error' );
730
					$( element ).closest( '.control-group' ).addClass( 'error' );
724
				}
731
				}
725
			}
732
			}
726
			return false;
733
			return false;
727
		},
734
		},
728
		rules : formSuppValidation.rules,
735
		rules : formSuppValidation.rules,
729
		messages : formSuppValidation.messages,
736
		messages : formSuppValidation.messages,
730
		errorPlacement : function( error , element ) {
737
		errorPlacement : function( error , element ) {
731
			if ( 0 < Object.keys( formSuppValidation.errors ).length ) {
738
			if ( 0 < Object.keys( formSuppValidation.errors ).length ) {
732
				var errorsKeys = Object.keys( formSuppValidation.errors ),
739
				var errorsKeys = Object.keys( formSuppValidation.errors ),
733
						thisKey = '',
740
						thisKey = '',
734
						errorsFlag = true;
741
						errorsFlag = true;
735
				for ( i = 0 ; i < errorsKeys.length ; i++ ) {
742
				for ( i = 0 ; i < errorsKeys.length ; i++ ) {
736
					thisKey = errorsKeys[i];
743
					thisKey = errorsKeys[i];
737
					if( $( element ).attr( 'name' ) === thisKey ) {
744
					if( $( element ).attr( 'name' ) === thisKey ) {
738
						$( formSuppValidation.errors[thisKey] ).append( error );
745
						$( formSuppValidation.errors[thisKey] ).append( error );
739
						errorsFlag = false;
746
						errorsFlag = false;
740
					}
747
					}
741
				}
748
				}
742
				if ( errorsFlag ) {
749
				if ( errorsFlag ) {
743
					error.insertAfter( element );
750
					error.insertAfter( element );
744
				}
751
				}
745
			} else {
752
			} else {
746
				error.insertAfter( element );
753
				error.insertAfter( element );
747
			}
754
			}
748
		}
755
		}
749
	});
756
	});
750
 
757
 
751
	$( '#form-supp .select' ).change( function() {
758
	$( '#form-supp .select' ).change( function() {
752
		$( this ).valid();
759
		$( this ).valid();
753
	});
760
	});
754
 
761
 
755
	$( 'input[type=date]' ).on( 'input', function() {
762
	$( 'input[type=date]' ).on( 'input', function() {
756
		$( this ).valid();
763
		$( this ).valid();
757
	});
764
	});
758
 
765
 
759
	$( '#form-observation' ).validate({
766
	$( '#form-observation' ).validate({
760
		rules : {
767
		rules : {
761
			date_releve : {
768
			date_releve : {
762
				required : true,
769
				required : true,
763
				'dateCel' : true
770
				'dateCel' : true
764
			},
771
			},
765
			latitude : {
772
			latitude : {
766
				range: [-90, 90]
773
				range: [-90, 90]
767
			},
774
			},
768
			longitude : {
775
			longitude : {
769
				range: [-180, 180]
776
				range: [-180, 180]
770
			}
777
			}
771
		}
778
		}
772
	});
779
	});
773
 
780
 
774
	$( '#form-observateur' ).validate({
781
	$( '#form-observateur' ).validate({
775
		rules : {
782
		rules : {
776
			courriel : {
783
			courriel : {
777
				required : true,
784
				required : true,
778
				email : true,
785
				email : true,
779
				'userEmailOk' : true
786
				'userEmailOk' : true
780
			},
787
			},
781
			courriel_confirmation : {
788
			courriel_confirmation : {
782
				required : true,
789
				required : true,
783
				equalTo : '#courriel'
790
				equalTo : '#courriel'
784
			}
791
			}
785
		}
792
		}
786
	});
793
	});
787
};
794
};
788
 
795
 
789
WidgetSaisie.prototype.validerFormulaire = function() {
796
WidgetSaisie.prototype.validerFormulaire = function() {
790
	var observateur = $( '#form-observateur' ).valid();
797
	var observateur = $( '#form-observateur' ).valid();
791
	var obs = $( '#form-observation' ).valid();
798
	var obs = $( '#form-observation' ).valid();
792
	var images = valeurOk( $( '#miniatures .miniature' ) );
799
	var images = valeurOk( $( '#miniatures .miniature' ) );
793
	var taxon = ( valeurOk( $( '#taxon' ).data( 'numNomSel' ) ) || valeurOk( $( '#taxon-liste' ).data( 'numNomSel' ) ) );
800
	var taxon = ( valeurOk( $( '#taxon' ).data( 'numNomSel' ) ) || valeurOk( $( '#taxon-liste' ).data( 'numNomSel' ) ) );
794
	var geoloc = ( $( '#latitude' ).valid() && $( '#longitude' ).valid() );
801
	var geoloc = ( $( '#latitude' ).valid() && $( '#longitude' ).valid() );
795
	var chpsSupp = new Boolean();
802
	var chpsSupp = new Boolean();
796
	if ( valeurOk( $( '#form-supp' ) ) ) {
803
	if ( valeurOk( $( '#form-supp' ) ) ) {
797
		chpsSupp = ( function () {
804
		chpsSupp = ( function () {
798
			var otherFlag = $( '#form-supp' ).valid();
805
			var otherFlag = $( '#form-supp' ).valid();
799
			if( valeurOk( $( '.other', $( '#form-supp' ) ) ) ) {
806
			if( valeurOk( $( '.other', $( '#form-supp' ) ) ) ) {
800
				$( '.other', $( '#form-supp' ) ).each( function() {
807
				$( '.other', $( '#form-supp' ) ).each( function() {
801
					var picked = ( $( this ).data( 'element' ) !== 'select' ) ? ':checked' : ':selected';
808
					var picked = ( $( this ).data( 'element' ) !== 'select' ) ? ':checked' : ':selected';
802
						if ( $( this ).is( picked ) && valeurOk( $( this ).val(), true, 'other' ) ) {
809
						if ( $( this ).is( picked ) && valeurOk( $( this ).val(), true, 'other' ) ) {
803
							otherFlag = false;
810
							otherFlag = false;
804
						}
811
						}
805
				});
812
				});
806
			}
813
			}
807
			return otherFlag;
814
			return otherFlag;
808
		})();
815
		})();
809
	} else {
816
	} else {
810
		chpsSupp = true;
817
		chpsSupp = true;
811
	}
818
	}
812
 
819
 
813
	( geoloc ) ? this.masquerPanneau( '#dialogue-geoloc-ko' ) : this.afficherPanneau( '#dialogue-geoloc-ko' );
820
	( geoloc ) ? this.masquerPanneau( '#dialogue-geoloc-ko' ) : this.afficherPanneau( '#dialogue-geoloc-ko' );
814
	( observateur ) ? this.masquerPanneau( '#dialogue-utilisateur-non-identifie' ) : this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
821
	( observateur ) ? this.masquerPanneau( '#dialogue-utilisateur-non-identifie' ) : this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
815
	if ( images || taxon ) {
822
	if ( images || taxon ) {
816
		this.masquerPanneau( '#dialogue-taxon-or-image' );
823
		this.masquerPanneau( '#dialogue-taxon-or-image' );
817
		this.masquerPanneau( '#dialogue-image-or-taxon' );
824
		this.masquerPanneau( '#dialogue-image-or-taxon' );
818
	} else {
825
	} else {
819
		this.afficherPanneau( '#dialogue-taxon-or-image' );
826
		this.afficherPanneau( '#dialogue-taxon-or-image' );
820
		this.afficherPanneau( '#dialogue-image-or-taxon' );
827
		this.afficherPanneau( '#dialogue-image-or-taxon' );
821
	}
828
	}
822
	return ( observateur && obs && ( images || taxon ) && chpsSupp );
829
	return ( observateur && obs && ( images || taxon ) && chpsSupp );
823
};
830
};
824
 
831
 
825
// Fichier Images *************************************************************/
832
// Fichier Images *************************************************************/
826
/**
833
/**
827
 * Affiche la miniature d'une image temporaire (formulaire) qu'on a ajoutée à l'obs
834
 * Affiche la miniature d'une image temporaire (formulaire) qu'on a ajoutée à l'obs
828
 */
835
 */
829
WidgetSaisie.prototype.afficherMiniature = function( reponse ) {
836
WidgetSaisie.prototype.afficherMiniature = function( reponse ) {
830
	if ( this.debug ) {
837
	if ( this.debug ) {
831
		var debogage = $( 'debogage', reponse ).text();
838
		var debogage = $( 'debogage', reponse ).text();
832
		//console.log( 'Débogage upload : '+debogage);
839
		//console.log( 'Débogage upload : '+debogage);
833
	}
840
	}
834
	var message = $( 'message', reponse ).text();
841
	var message = $( 'message', reponse ).text();
835
	if ( valeurOk( message ) ) {
842
	if ( valeurOk( message ) ) {
836
		$( '#miniature-msg' ).append( message );
843
		$( '#miniature-msg' ).append( message );
837
	} else {
844
	} else {
838
		$( '#miniatures' ).append( this.creerWidgetMiniature( reponse ) );
845
		$( '#miniatures' ).append( this.creerWidgetMiniature( reponse ) );
839
	}
846
	}
840
	$( '#ajouter-obs' ).removeAttr( 'disabled' );
847
	$( '#ajouter-obs' ).removeAttr( 'disabled' );
841
};
848
};
842
 
849
 
843
/**
850
/**
844
 * Crée la miniature d'une image temporaire (formulaire), avec le bouton pour l'effacer
851
 * Crée la miniature d'une image temporaire (formulaire), avec le bouton pour l'effacer
845
 */
852
 */
846
WidgetSaisie.prototype.creerWidgetMiniature = function( reponse ) {
853
WidgetSaisie.prototype.creerWidgetMiniature = function( reponse ) {
847
	var miniatureUrl = $( 'miniature-url', reponse ).text();
854
	var miniatureUrl = $( 'miniature-url', reponse ).text();
848
	var imgNom = $( 'image-nom', reponse ).text();
855
	var imgNom = $( 'image-nom', reponse ).text();
849
	var html =
856
	var html =
850
		'<div class="miniature mb-3 mr-3">'+
857
		'<div class="miniature mb-3 mr-3">'+
851
			'<img class="miniature-img" class="miniature img-rounded" alt="' + imgNom + '" src="' + miniatureUrl + '"/>'+
858
			'<img class="miniature-img" class="miniature img-rounded" alt="' + imgNom + '" src="' + miniatureUrl + '"/>'+
852
			'<a class="effacer-miniature"><i class="far fa-trash-alt"></i></a>'+
859
			'<a class="effacer-miniature"><i class="far fa-trash-alt"></i></a>'+
853
		'</div>'
860
		'</div>'
854
	return html;
861
	return html;
855
};
862
};
856
 
863
 
857
/**
864
/**
858
 * Retourne true si l'extension de l'image 'nom' est .jpg ou .jpeg
865
 * Retourne true si l'extension de l'image 'nom' est .jpg ou .jpeg
859
 */
866
 */
860
WidgetSaisie.prototype.verifierFormat = function( nom ) {
867
WidgetSaisie.prototype.verifierFormat = function( nom ) {
861
	var parts = nom.split( '.' );
868
	var parts = nom.split( '.' );
862
	extension = parts[ parts.length - 1 ];
869
	extension = parts[ parts.length - 1 ];
863
	return ( 'jpeg' === extension.toLowerCase() || 'jpg' === extension.toLowerCase() );
870
	return ( 'jpeg' === extension.toLowerCase() || 'jpg' === extension.toLowerCase() );
864
};
871
};
865
 
872
 
866
/**
873
/**
867
 * Efface une miniature (formulaire)
874
 * Efface une miniature (formulaire)
868
 */
875
 */
869
WidgetSaisie.prototype.supprimerMiniature = function( miniature ) {
876
WidgetSaisie.prototype.supprimerMiniature = function( miniature ) {
870
	miniature.parents( '.miniature' ).remove();
877
	miniature.parents( '.miniature' ).remove();
871
};
878
};
872
 
879
 
873
// Referentiel ****************************************************************/
880
// Referentiel ****************************************************************/
874
// N'est pas utilisé en cas de taxon-liste
881
// N'est pas utilisé en cas de taxon-liste
875
WidgetSaisie.prototype.surChangementReferentiel = function() {
882
WidgetSaisie.prototype.surChangementReferentiel = function() {
876
	this.nomSciReferentiel = $( '#referentiel' ).val();
883
	this.nomSciReferentiel = $( '#referentiel' ).val();
877
	//réinitialise taxon.val
884
	//réinitialise taxon.val
878
	$( '#taxon' ).val( '' );
885
	$( '#taxon' ).val( '' );
879
	$( '#taxon' ).data( 'numNomSel', 0 );
886
	$( '#taxon' ).data( 'numNomSel', '' );
880
	// this.initialiserAutocompleteCommune();
887
	// this.initialiserAutocompleteCommune();
881
	// this.initialiserGoogleMap( false );
888
	// this.initialiserGoogleMap( false );
882
};
889
};
883
 
890
 
884
// Ajouter Obs ****************************************************************/
891
// Ajouter Obs ****************************************************************/
885
/**
892
/**
886
 * Ajoute une observation saisie dans le formulaire à la liste des observations à transmettre
893
 * Ajoute une observation saisie dans le formulaire à la liste des observations à transmettre
887
 */
894
 */
888
WidgetSaisie.prototype.ajouterObs = function() {
895
WidgetSaisie.prototype.ajouterObs = function() {
889
	// Fermeture automatique des dialogue de transmission de données
896
	// Fermeture automatique des dialogue de transmission de données
890
	// @WARNING TEST
897
	// @WARNING TEST
891
	$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
898
	$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
892
	$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
899
	$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
893
 
900
 
894
	if ( this.validerFormulaire() ) {
901
	if ( this.validerFormulaire() ) {
895
		this.masquerPanneau( '#dialogue-form-invalide' );
902
		this.masquerPanneau( '#dialogue-form-invalide' );
896
		this.obsNbre = this.obsNbre + 1;
903
		this.obsNbre = this.obsNbre + 1;
897
		$( '.obs-nbre' ).text( this.obsNbre );
904
		$( '.obs-nbre' ).text( this.obsNbre );
898
		$( '.obs-nbre' ).triggerHandler( 'changement' );
905
		$( '.obs-nbre' ).triggerHandler( 'changement' );
899
		this.afficherObs();
906
		this.afficherObs();
900
		this.stockerObsData();
907
		this.stockerObsData();
901
		this.supprimerMiniatures();
908
		this.supprimerMiniatures();
902
		if( !this.especeImposee ) {
909
		if( !this.especeImposee ) {
903
			$( '#taxon' ).val( '' );
910
			$( '#taxon' ).val( '' );
904
			$( '#taxon' ).data( 'numNomSel', '' )
911
			$( '#taxon' ).data( 'numNomSel', '' )
905
			.data( 'nomRet','' )
912
			.data( 'nomRet','' )
906
			.data( 'numNomRet', '' )
913
			.data( 'numNomRet', '' )
907
			.data( 'nt', '' )
914
			.data( 'nt', '' )
908
			.data( 'famille', '' );
915
			.data( 'famille', '' );
909
			if( this.isTaxonListe ) {
916
			if( this.isTaxonListe ) {
910
				$( '#taxon-liste' ).find( 'option' ).each( function() {
917
				$( '#taxon-liste' ).find( 'option' ).each( function() {
911
					if ( $( this ).hasClass( 'choisir' ) ) {
918
					if ( $( this ).hasClass( 'choisir' ) ) {
912
						$( this ).attr( 'selected', true );
919
						$( this ).attr( 'selected', true );
913
					} else {
920
					} else {
914
						$( this ).attr( 'selected', false );
921
						$( this ).attr( 'selected', false );
915
					}
922
					}
916
				});
923
				});
917
				$( '#taxon-input-groupe' ).addClass( 'hidden' );
924
				$( '#taxon-input-groupe' ).addClass( 'hidden' );
918
				$('#taxon-autre').val('');
925
				$('#taxon-autre').val('');
919
			}
926
			}
920
		}
927
		}
921
		if ( valeurOk( $( '#form-supp' ) ) ) {
928
		if ( valeurOk( $( '#form-supp' ) ) ) {
922
			$( '#form-supp' ).validate().resetForm();
929
			$( '#form-supp' ).validate().resetForm();
923
			// if ( valeurOk( $( '#form-supp' ) ) ) {
930
			// if ( valeurOk( $( '#form-supp' ) ) ) {
924
		}
931
		}
925
		$( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre );
932
		$( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre );
926
		$( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' ' + this.msgTraduction( 'observations-transmises' ) );
933
		$( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' ' + this.msgTraduction( 'observations-transmises' ) );
927
	} else {
934
	} else {
928
		this.afficherPanneau( '#dialogue-form-invalide' );
935
		this.afficherPanneau( '#dialogue-form-invalide' );
929
	}
936
	}
930
};
937
};
931
 
938
 
932
/**
939
/**
933
 * Affiche une observation dans la liste des observations à transmettre
940
 * Affiche une observation dans la liste des observations à transmettre
934
 */
941
 */
935
WidgetSaisie.prototype.afficherObs = function() {
942
WidgetSaisie.prototype.afficherObs = function() {
936
 
943
 
937
	var numNomSel = $( '#taxon' ).data( 'numNomSel' ),
944
	var numNomSel = $( '#taxon' ).data( 'numNomSel' ),
938
			taxon = $( '#taxon' ).val(),
945
			taxon = $( '#taxon' ).val(),
939
			referentiel = '',
946
			referentiel = '',
940
			commune = '',
947
			commune = '',
941
			inseeLatitudeLongitude = '',
948
			inseeLatitudeLongitude = '',
942
			lieudit = '',
949
			lieudit = '',
943
			station = '',
950
			station = '',
944
			milieu = '',
951
			milieu = '',
945
			commentaires = '';
952
			commentaires = '';
946
 
953
 
947
	if ( valeurOk( numNomSel ) ) {
954
	if ( valeurOk( numNomSel ) ) {
948
		referentiel = '<span class="referentiel-obs">' + '[' + this.nomSciReferentiel + ']' + '</span>';
955
		referentiel = '<span class="referentiel-obs">' + '[' + this.nomSciReferentiel + ']' + '</span>';
949
	}
956
	}
950
	if ( valeurOk( $( '#commune-nom' ).val() ) ) {
957
	if ( valeurOk( $( '#commune-nom' ).val() ) ) {
951
		commune = ' '  + this.msgTraduction( 'lieu-obs' ) + ' <span class="commune">' + $( '#commune-nom' ).val() + '</span> ';
958
		commune = ' '  + this.msgTraduction( 'lieu-obs' ) + ' <span class="commune">' + $( '#commune-nom' ).val() + '</span> ';
952
	}
959
	}
953
	if ( valeurOk( $( '#commune-insee' ).val() ) &&  valeurOk( $( '#latitude' ).val() ) && valeurOk( $( '#longitude' ).val() ) ) {
960
	if ( valeurOk( $( '#commune-insee' ).val() ) &&  valeurOk( $( '#latitude' ).val() ) && valeurOk( $( '#longitude' ).val() ) ) {
954
		inseeLatitudeLongitude = '(INSEE Commune:' + $('#commune-insee').val() + ') [' + $( '#latitude' ).val() + ' / ' + $( '#longitude' ).val() + ']';
961
		inseeLatitudeLongitude = '(INSEE Commune:' + $('#commune-insee').val() + ') [' + $( '#latitude' ).val() + ' / ' + $( '#longitude' ).val() + ']';
955
	}
962
	}
956
	if ( valeurOk( $( '#lieudit' ).val() ) ) {
963
	if ( valeurOk( $( '#lieudit' ).val() ) ) {
957
		lieudit = '<span>' + this.msgTraduction( 'lieu-dit' ) + ' :</span> ' + $( '#lieudit' ).val() + ' ';
964
		lieudit = '<span>' + this.msgTraduction( 'lieu-dit' ) + ' :</span> ' + $( '#lieudit' ).val() + ' ';
958
	}
965
	}
959
	if ( valeurOk( $( '#station' ).val() ) ) {
966
	if ( valeurOk( $( '#station' ).val() ) ) {
960
		station = '<span>' + this.msgTraduction( 'station' ) + ' :</span> ' + $( '#station' ).val() + ' ';
967
		station = '<span>' + this.msgTraduction( 'station' ) + ' :</span> ' + $( '#station' ).val() + ' ';
961
	}
968
	}
962
	if ( valeurOk( $( '#milieu' ).val() ) ) {
969
	if ( valeurOk( $( '#milieu' ).val() ) ) {
963
		milieu = '<span>' + this.msgTraduction( 'milieu' ) + ' :</span> ' + $( '#milieu' ).val() + ' ';
970
		milieu = '<span>' + this.msgTraduction( 'milieu' ) + ' :</span> ' + $( '#milieu' ).val() + ' ';
964
	}
971
	}
965
	if ( valeurOk( $( '#notes' ).val() ) ) {
972
	if ( valeurOk( $( '#notes' ).val() ) ) {
966
		commentaires = this.msgTraduction( 'commentaires' ) + ' : <span class="discretion">' + $( '#notes' ).val() + '</span>' + ' ';
973
		commentaires = this.msgTraduction( 'commentaires' ) + ' : <span class="discretion">' + $( '#notes' ).val() + '</span>' + ' ';
967
	}
974
	}
968
 
975
 
969
	var responsivDiff1 = '',
976
	var responsivDiff1 = '',
970
			responsivDiff2 = '',
977
			responsivDiff2 = '',
971
			responsivDiff3 = '',
978
			responsivDiff3 = '',
972
			responsivDiff4 = '',
979
			responsivDiff4 = '',
973
			responsivDiff5 = '',
980
			responsivDiff5 = '',
974
			responsivDiff6 = '';
981
			responsivDiff6 = '';
975
	if ( window.matchMedia( '(min-width: 576px)' ).matches ) {
982
	if ( window.matchMedia( '(min-width: 576px)' ).matches ) {
976
		/* La largeur minimum de l'affichage est 600 px inclus */
983
		/* La largeur minimum de l'affichage est 600 px inclus */
977
		responsivDiff1 = ' droite';
984
		responsivDiff1 = ' droite';
978
		responsivDiff2 = '<div></div>';
985
		responsivDiff2 = '<div></div>';
979
		responsivDiff3 = '<div class="row">';
986
		responsivDiff3 = '<div class="row">';
980
		responsivDiff4 = ' col-md-2 col-sm-4';
987
		responsivDiff4 = ' col-md-2 col-sm-4';
981
		responsivDiff5 = ' class="col-md-9 col-sm-7"';
988
		responsivDiff5 = ' class="col-md-9 col-sm-7"';
982
		responsivDiff6 = '</div>';
989
		responsivDiff6 = '</div>';
983
	}
990
	}
984
 
991
 
985
 
992
 
986
		$( '#liste-obs' ).prepend(
993
		$( '#liste-obs' ).prepend(
987
			'<div id="obs' + this.obsNbre + '" class="obs obs' + this.obsNbre + ' mb-2">'+
994
			'<div id="obs' + this.obsNbre + '" class="obs obs' + this.obsNbre + ' mb-2">'+
988
 
995
 
989
				'<div '+
996
				'<div '+
990
					'class="obs-action" '+
997
					'class="obs-action" '+
991
					'title="' + this.msgTraduction( 'supprimer-observation-liste' ) + '"'+
998
					'title="' + this.msgTraduction( 'supprimer-observation-liste' ) + '"'+
992
				'>'+
999
				'>'+
993
					'<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ this.obsNbre + '" title="' + this.msgTraduction( 'obs-numero' ) + this.obsNbre + '">'+
1000
					'<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ this.obsNbre + '" title="' + this.msgTraduction( 'obs-numero' ) + this.obsNbre + '">'+
994
					'<i class="far fa-trash-alt"></i>'+
1001
					'<i class="far fa-trash-alt"></i>'+
995
					'</button>'+
1002
					'</button>'+
996
					responsivDiff2 +
1003
					responsivDiff2 +
997
				'</div> '+
1004
				'</div> '+
998
 
1005
 
999
				responsivDiff3 +
1006
				responsivDiff3 +
1000
					'<div class="thumbnail' + responsivDiff4 + '">'+
1007
					'<div class="thumbnail' + responsivDiff4 + '">'+
1001
						this.ajouterImgMiniatureAuTransfert()+
1008
						this.ajouterImgMiniatureAuTransfert()+
1002
					'</div>'+
1009
					'</div>'+
1003
					'<div' + responsivDiff5 + '>'+
1010
					'<div' + responsivDiff5 + '>'+
1004
						'<ul class="unstyled">'+
1011
						'<ul class="unstyled">'+
1005
							'<li>'+
1012
							'<li>'+
1006
								'<span class="nom-sci">' + taxon + '</span> '+
1013
								'<span class="nom-sci">' + taxon + '</span> '+
1007
								this.ajouterNumNomSel( numNomSel ) +
1014
								this.ajouterNumNomSel( numNomSel ) +
1008
								referentiel +
1015
								referentiel +
1009
								commune +
1016
								commune +
1010
								inseeLatitudeLongitude +
1017
								inseeLatitudeLongitude +
1011
								' ' + this.msgTraduction( 'obs-le' ) + ' ' +
1018
								' ' + this.msgTraduction( 'obs-le' ) + ' ' +
1012
								'<span class="date">' + this.fournirDate( $( '#date_releve' ).val() ) + '</span>'+
1019
								'<span class="date">' + this.fournirDate( $( '#date_releve' ).val() ) + '</span>'+
1013
							'</li>'+
1020
							'</li>'+
1014
							'<li>'+
1021
							'<li>'+
1015
								lieudit +
1022
								lieudit +
1016
								station +
1023
								station +
1017
								milieu +
1024
								milieu +
1018
							'</li>'+
1025
							'</li>'+
1019
							'<li>'+
1026
							'<li>'+
1020
								commentaires +
1027
								commentaires +
1021
							'</li>'+
1028
							'</li>'+
1022
						'</ul>'+
1029
						'</ul>'+
1023
					'</div>'+
1030
					'</div>'+
1024
				responsivDiff6+
1031
				responsivDiff6+
1025
			'</div>'
1032
			'</div>'
1026
		);
1033
		);
1027
 
1034
 
1028
	$( '#zone-liste-obs' ).removeClass( 'hidden' );
1035
	$( '#zone-liste-obs' ).removeClass( 'hidden' );
1029
};
1036
};
1030
 
1037
 
1031
/**
1038
/**
1032
 * Ajoute une boîte de miniatures avec défilement des images,
1039
 * Ajoute une boîte de miniatures avec défilement des images,
1033
 * pour une obs de la liste des obs à transmettre
1040
 * pour une obs de la liste des obs à transmettre
1034
 */
1041
 */
1035
WidgetSaisie.prototype.ajouterImgMiniatureAuTransfert = function() {
1042
WidgetSaisie.prototype.ajouterImgMiniatureAuTransfert = function() {
1036
	var html        =
1043
	var html        =
1037
				'<div class="defilement-miniatures">'+
1044
				'<div class="defilement-miniatures">'+
1038
					'<figure class="centre">'+
1045
					'<figure class="centre">'+
1039
						'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
1046
						'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
1040
					'</figure>'+
1047
					'</figure>'+
1041
				'</div>',
1048
				'</div>',
1042
			miniatures   = '',
1049
			miniatures   = '',
1043
			premiere     = true,
1050
			premiere     = true,
1044
			centre       = '';
1051
			centre       = '';
1045
			defilVisible = '';
1052
			defilVisible = '';
1046
 
1053
 
1047
	if ( valeurOk( $( '#miniatures img' ) ) ) {
1054
	if ( valeurOk( $( '#miniatures img' ) ) ) {
1048
		$( '#miniatures img' ).each( function() {
1055
		$( '#miniatures img' ).each( function() {
1049
			var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
1056
			var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
1050
			premiere = false;
1057
			premiere = false;
1051
 
1058
 
1052
			var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
1059
			var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
1053
					src        = $( this ).attr( 'src' ),
1060
					src        = $( this ).attr( 'src' ),
1054
					alt        = $( this ).attr( 'alt' ),
1061
					alt        = $( this ).attr( 'alt' ),
1055
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1062
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1056
 
1063
 
1057
			miniatures += miniature;
1064
			miniatures += miniature;
1058
		});
1065
		});
1059
		if ( 1 === $( '#miniatures img' ).length ) {
1066
		if ( 1 === $( '#miniatures img' ).length ) {
1060
			centre       = 'centre';
1067
			centre       = 'centre';
1061
			defilVisible = ' defilement-miniatures-cache';
1068
			defilVisible = ' defilement-miniatures-cache';
1062
		}
1069
		}
1063
		html             =
1070
		html             =
1064
			'<div class="defilement-miniatures">'+
1071
			'<div class="defilement-miniatures">'+
1065
				'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
1072
				'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
1066
				'<figure class="' + centre + '">'+
1073
				'<figure class="' + centre + '">'+
1067
					miniatures+
1074
					miniatures+
1068
				'</figure>'+
1075
				'</figure>'+
1069
				'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
1076
				'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
1070
			'</div>';
1077
			'</div>';
1071
	}
1078
	}
1072
	return html;
1079
	return html;
1073
};
1080
};
1074
 
1081
 
1075
WidgetSaisie.prototype.fournirDate = function( dateObs ) {
1082
WidgetSaisie.prototype.fournirDate = function( dateObs ) {
1076
	if ( /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/.test( dateObs ) ) {
1083
	if ( /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/.test( dateObs ) ) {
1077
		return dateObs;
1084
		return dateObs;
1078
	} else if ( /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test( dateObs ) ) {
1085
	} else if ( /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test( dateObs ) ) {
1079
		var dateArray = dateObs.split( '-' );
1086
		var dateArray = dateObs.split( '-' );
1080
		return dateArray[2] + '/' + dateArray[1] + '/' + dateArray[0]
1087
		return dateArray[2] + '/' + dateArray[1] + '/' + dateArray[0]
1081
	} else {
1088
	} else {
1082
		console.log( 'erreur date : ' + dateObs )
1089
		console.log( 'erreur date : ' + dateObs )
1083
	}
1090
	}
1084
}
1091
}
1085
 
1092
 
1086
WidgetSaisie.prototype.ajouterNumNomSel = function( numNomSel ) {
1093
WidgetSaisie.prototype.ajouterNumNomSel = function( numNomSel ) {
1087
	var nn = '<span class="nn">[nn' + numNomSel + ']</span>';
1094
	var nn = '<span class="nn">[nn' + numNomSel + ']</span>';
1088
	if ( !valeurOk( numNomSel ) ) {
1095
	if ( !valeurOk( numNomSel ) ) {
1089
		nn = '<span class="alert-error">[' + this.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
1096
		nn = '<span class="alert-error">[' + this.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
1090
	}
1097
	}
1091
	return nn;
1098
	return nn;
1092
};
1099
};
1093
 
1100
 
1094
 
1101
 
1095
WidgetSaisie.prototype.stockerObsData = function() {
1102
WidgetSaisie.prototype.stockerObsData = function() {
1096
	var lthis = this;
1103
	var lthis = this;
1097
 
1104
 
1098
	var numNomSel   = $( '#taxon' ).data( 'numNomSel' ),
1105
	var numNomSel   = $( '#taxon' ).data( 'numNomSel' ),
1099
			nomSel      = $( '#taxon' ).val(),
1106
			nomSel      = $( '#taxon' ).val(),
1100
			nomRet      = $( '#taxon' ).data( 'nomRet' ),
1107
			nomRet      = $( '#taxon' ).data( 'nomRet' ),
1101
			numNomRet   = $( '#taxon' ).data( 'numNomRet' ),
1108
			numNomRet   = $( '#taxon' ).data( 'numNomRet' ),
1102
			numTaxon    = $( '#taxon' ).data( 'nt' ),
1109
			numTaxon    = $( '#taxon' ).data( 'nt' ),
1103
			famille     = $( '#taxon' ).data( 'famille' ),
1110
			famille     = $( '#taxon' ).data( 'famille' ),
1104
			referentiel = ( !valeurOk( numNomSel ) ) ? '' : this.nomSciReferentiel;
1111
			referentiel = ( !valeurOk( numNomSel ) ) ? 'autre' : this.nomSciReferentiel;
1105
 
1112
 
1106
	$( '#liste-obs' ).data( 'obsId' + this.obsNbre, {
1113
	$( '#liste-obs' ).data( 'obsId' + this.obsNbre, {
1107
		'num_nom_sel'        : numNomSel,
1114
		'num_nom_sel'        : numNomSel,
1108
		'nom_sel'            : nomSel,
1115
		'nom_sel'            : nomSel,
1109
		'nom_ret'            : nomRet,
1116
		'nom_ret'            : nomRet,
1110
		'num_nom_ret'        : numNomRet,
1117
		'num_nom_ret'        : numNomRet,
1111
		'num_taxon'          : numTaxon,
1118
		'num_taxon'          : numTaxon,
1112
		'famille'            : famille,
1119
		'famille'            : famille,
1113
		'referentiel'        : referentiel,
1120
		'referentiel'        : referentiel,
1114
		'certitude'          : $( '#certitude' ).val(),
1121
		'certitude'          : $( '#certitude' ).val(),
1115
		'date'               : lthis.fournirDate( $( '#date_releve' ).val() ),
1122
		'date'               : lthis.fournirDate( $( '#date_releve' ).val() ),
1116
		'notes'              : $( '#notes' ).val().trim(),
1123
		'notes'              : $( '#notes' ).val().trim(),
1117
		'pays'               : $( '#pays' ).val(),
1124
		'pays'               : $( '#pays' ).val(),
1118
		'commune_nom'        : $( '#commune-nom' ).val(),
1125
		'commune_nom'        : $( '#commune-nom' ).val(),
1119
		'commune_code_insee' : $( '#commune-insee' ).val(),
1126
		'commune_code_insee' : $( '#commune-insee' ).val(),
1120
		'latitude'           : $( '#latitude' ).val(),
1127
		'latitude'           : $( '#latitude' ).val(),
1121
		'longitude'          : $( '#longitude' ).val(),
1128
		'longitude'          : $( '#longitude' ).val(),
1122
		'altitude'           : $( '#altitude' ).val(),
1129
		'altitude'           : $( '#altitude' ).val(),
1123
// début valeurs pour test:
1130
// début valeurs pour test:
1124
		// 'commune_nom'        : 'Montpellier',
1131
		// 'commune_nom'        : 'Montpellier',
1125
		// 'commune_code_insee' : '34172',
1132
		// 'commune_code_insee' : '34172',
1126
		// 'latitude'           : '43.608320',
1133
		// 'latitude'           : '43.608320',
1127
		// 'longitude'          : '3.880196',
1134
		// 'longitude'          : '3.880196',
1128
		// 'altitude'           : '0',
1135
		// 'altitude'           : '0',
1129
//fin valeurs pour test
1136
//fin valeurs pour test
1130
		'lieudit'            : $( '#lieudit' ).val(),
1137
		'lieudit'            : $( '#lieudit' ).val(),
1131
		'station'            : $( '#station' ).val(),
1138
		'station'            : $( '#station' ).val(),
1132
		'milieu'             : $( '#milieu' ).val(),
1139
		'milieu'             : $( '#milieu' ).val(),
1133
		//Ajout des champs images
1140
		//Ajout des champs images
1134
		'image_nom'          : lthis.getNomsImgsOriginales(),
1141
		'image_nom'          : lthis.getNomsImgsOriginales(),
1135
		'image_b64'          : lthis.getB64ImgsOriginales(),
1142
		'image_b64'          : lthis.getB64ImgsOriginales(),
1136
		// Ajout des champs étendus de l'obs
1143
		// Ajout des champs étendus de l'obs
1137
		'obs_etendue'        : lthis.getObsChpEtendus()
1144
		'obs_etendue'        : lthis.getObsChpEtendus()
1138
	});
1145
	});
1139
};
1146
};
1140
 
1147
 
1141
WidgetSaisie.prototype.getNomsImgsOriginales = function() {
1148
WidgetSaisie.prototype.getNomsImgsOriginales = function() {
1142
	var noms = new Array();
1149
	var noms = new Array();
1143
	$( '.miniature-img' ).each( function() {
1150
	$( '.miniature-img' ).each( function() {
1144
		noms.push( $( this ).attr( 'alt' ) );
1151
		noms.push( $( this ).attr( 'alt' ) );
1145
	});
1152
	});
1146
	return noms;
1153
	return noms;
1147
};
1154
};
1148
 
1155
 
1149
WidgetSaisie.prototype.getB64ImgsOriginales = function() {
1156
WidgetSaisie.prototype.getB64ImgsOriginales = function() {
1150
	var b64 = new Array();
1157
	var b64 = new Array();
1151
	$( '.miniature-img' ).each( function() {
1158
	$( '.miniature-img' ).each( function() {
1152
		if ( $( this ).hasClass( 'b64' ) ) {
1159
		if ( $( this ).hasClass( 'b64' ) ) {
1153
			b64.push( $( this ).attr( 'src' ) );
1160
			b64.push( $( this ).attr( 'src' ) );
1154
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
1161
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
1155
			b64.push( $( this ).data( 'b64' ) );
1162
			b64.push( $( this ).data( 'b64' ) );
1156
		}
1163
		}
1157
	});
1164
	});
1158
	return b64;
1165
	return b64;
1159
};
1166
};
1160
 
1167
 
1161
/**
1168
/**
1162
 * Retourne un Array contenant les valeurs des champs étendus
1169
 * Retourne un Array contenant les valeurs des champs étendus
1163
 */
1170
 */
1164
WidgetSaisie.prototype.getObsChpEtendus = function() {
1171
WidgetSaisie.prototype.getObsChpEtendus = function() {
1165
	var champs    = new Array(),
1172
	var champs    = new Array(),
1166
			$thisForm = $( '#form-supp' ),
1173
			$thisForm = $( '#form-supp' ),
1167
			elements  =
1174
			elements  =
1168
				'input[type=text]:not(.collect-other),'+
1175
				'input[type=text]:not(.collect-other),'+
1169
				'input[type=checkbox]:checked,'+
1176
				'input[type=checkbox]:checked,'+
1170
				'input[type=radio]:checked,'+
1177
				'input[type=radio]:checked,'+
1171
				'input[type=email],'+
1178
				'input[type=email],'+
1172
				'input[type=number],'+
1179
				'input[type=number],'+
1173
				'input[type=range],'+
1180
				'input[type=range],'+
1174
				'input[type=date],'+
1181
				'input[type=date],'+
1175
				'textarea,'+
1182
				'textarea,'+
1176
				'.select',
1183
				'.select',
1177
			retour    = new Array();
1184
			retour    = new Array();
1178
 
1185
 
1179
	$( elements, $thisForm ).each( function() {
1186
	$( elements, $thisForm ).each( function() {
1180
		if ( valeurOk( $( this ).val() ) && ( valeurOk( $( this ).attr( 'name' ) ) || valeurOk( $( this ).data( 'name' ) ) ) ) {
1187
		if ( valeurOk( $( this ).val() ) && ( valeurOk( $( this ).attr( 'name' ) ) || valeurOk( $( this ).data( 'name' ) ) ) ) {
1181
			var valeur = $( this ).val(),
1188
			var valeur = $( this ).val(),
1182
					cle    = ( valeurOk( $( this ).attr( 'name' ) ) ) ? $( this ).attr( 'name' ) : $( this ).data( 'name' );
1189
					cle    = ( valeurOk( $( this ).attr( 'name' ) ) ) ? $( this ).attr( 'name' ) : $( this ).data( 'name' );
1183
			if ( cle in champs ) {
1190
			if ( cle in champs ) {
1184
				champs[cle] += ';' + valeur;
1191
				champs[cle] += ';' + valeur;
1185
			} else {
1192
			} else {
1186
				champs[cle] = valeur;
1193
				champs[cle] = valeur;
1187
			}
1194
			}
1188
		}
1195
		}
1189
	});
1196
	});
1190
	for( var key in champs ) {
1197
	for( var key in champs ) {
1191
		retour.push({ 'cle' : key , 'valeur' : champs[key] });
1198
		retour.push({ 'cle' : key , 'valeur' : champs[key] });
1192
	};
1199
	};
1193
	return retour;
1200
	return retour;
1194
};
1201
};
1195
 
1202
 
1196
/**
1203
/**
1197
 * Efface toutes les miniatures (formulaire)
1204
 * Efface toutes les miniatures (formulaire)
1198
 */
1205
 */
1199
WidgetSaisie.prototype.supprimerMiniatures = function() {
1206
WidgetSaisie.prototype.supprimerMiniatures = function() {
1200
	$( '#miniatures' ).empty();
1207
	$( '#miniatures' ).empty();
1201
	$( '#miniature-msg' ).empty();
1208
	$( '#miniature-msg' ).empty();
1202
};
1209
};
1203
 
1210
 
1204
WidgetSaisie.prototype.surChangementNbreObs = function() {
1211
WidgetSaisie.prototype.surChangementNbreObs = function() {
1205
	if ( 0 === this.obsNbre ) {
1212
	if ( 0 === this.obsNbre ) {
1206
		$( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
1213
		$( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
1207
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1214
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1208
	} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1215
	} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1209
		$( '#transmettre-obs' ).removeAttr( 'disabled' );
1216
		$( '#transmettre-obs' ).removeAttr( 'disabled' );
1210
		$( '#ajouter-obs' ).removeAttr( 'disabled' );
1217
		$( '#ajouter-obs' ).removeAttr( 'disabled' );
1211
	} else if ( this.obsNbre >= this.obsMaxNbre ) {
1218
	} else if ( this.obsNbre >= this.obsMaxNbre ) {
1212
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1219
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1213
		this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
1220
		this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
1214
	}
1221
	}
1215
};
1222
};
1216
 
1223
 
1217
WidgetSaisie.prototype.defilerMiniatures = function( element ) {
1224
WidgetSaisie.prototype.defilerMiniatures = function( element ) {
1218
 
1225
 
1219
	var miniatureSelectionne = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
1226
	var miniatureSelectionne = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
1220
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
1227
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
1221
	miniatureSelectionne.addClass( 'miniature-cachee' );
1228
	miniatureSelectionne.addClass( 'miniature-cachee' );
1222
 
1229
 
1223
	var miniatureAffichee    = miniatureSelectionne;
1230
	var miniatureAffichee    = miniatureSelectionne;
1224
 
1231
 
1225
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
1232
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
1226
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
1233
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
1227
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
1234
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
1228
		} else {
1235
		} else {
1229
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
1236
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
1230
		}
1237
		}
1231
	} else {
1238
	} else {
1232
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
1239
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
1233
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
1240
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
1234
		} else {
1241
		} else {
1235
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
1242
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
1236
		}
1243
		}
1237
	}
1244
	}
1238
	miniatureAffichee.addClass( 'miniature-selectionnee' );
1245
	miniatureAffichee.addClass( 'miniature-selectionnee' );
1239
	miniatureAffichee.removeClass( 'miniature-cachee' );
1246
	miniatureAffichee.removeClass( 'miniature-cachee' );
1240
};
1247
};
1241
 
1248
 
1242
WidgetSaisie.prototype.supprimerObs = function( selector ) {
1249
WidgetSaisie.prototype.supprimerObs = function( selector ) {
1243
	var obsId = $( selector ).val();
1250
	var obsId = $( selector ).val();
1244
	// Problème avec IE 6 et 7
1251
	// Problème avec IE 6 et 7
1245
	if ( 'Supprimer' === obsId ) {
1252
	if ( 'Supprimer' === obsId ) {
1246
		obsId = $( selector ).attr( 'title' );
1253
		obsId = $( selector ).attr( 'title' );
1247
	}
1254
	}
1248
	this.supprimerObsParId( obsId );
1255
	this.supprimerObsParId( obsId );
1249
};
1256
};
1250
 
1257
 
1251
WidgetSaisie.prototype.supprimerObsParId = function( obsId ) {
1258
WidgetSaisie.prototype.supprimerObsParId = function( obsId ) {
1252
	this.obsNbre = this.obsNbre - 1;
1259
	this.obsNbre = this.obsNbre - 1;
1253
	$( '.obs-nbre' ).text( this.obsNbre );
1260
	$( '.obs-nbre' ).text( this.obsNbre );
1254
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1261
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1255
	$( '.obs' + obsId ).remove();
1262
	$( '.obs' + obsId ).remove();
1256
	$( '#liste-obs' ).removeData( 'obsId' + obsId );
1263
	$( '#liste-obs' ).removeData( 'obsId' + obsId );
1257
};
1264
};
1258
 
1265
 
1259
WidgetSaisie.prototype.transmettreObs = function() {
1266
WidgetSaisie.prototype.transmettreObs = function() {
1260
	var observations = $( '#liste-obs' ).data();
1267
	var observations = $( '#liste-obs' ).data();
1261
	if ( this.debug ) {
1268
	if ( this.debug ) {
1262
		console.log( observations );
1269
		console.log( observations );
1263
	}
1270
	}
1264
	if ( !valeurOk( typeof observations, true, 'object' ) ) {
1271
	if ( !valeurOk( typeof observations, true, 'object' ) ) {
1265
		this.afficherPanneau( '#dialogue-zero-obs' );
1272
		this.afficherPanneau( '#dialogue-zero-obs' );
1266
	} else {
1273
	} else {
1267
		this.nbObsEnCours = 1;
1274
		this.nbObsEnCours = 1;
1268
		this.nbObsTransmises = 0;
1275
		this.nbObsTransmises = 0;
1269
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
1276
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
1270
			return i;
1277
			return i;
1271
		}).length;
1278
		}).length;
1272
		this.depilerObsPourEnvoi();
1279
		this.depilerObsPourEnvoi();
1273
	}
1280
	}
1274
	return false;
1281
	return false;
1275
};
1282
};
1276
 
1283
 
1277
WidgetSaisie.prototype.depilerObsPourEnvoi = function() {
1284
WidgetSaisie.prototype.depilerObsPourEnvoi = function() {
1278
	var observations = $( '#liste-obs' ).data();
1285
	var observations = $( '#liste-obs' ).data();
1279
	// la boucle est factice car on utilise un tableau
1286
	// la boucle est factice car on utilise un tableau
1280
	// dont on a besoin de n'extraire que le premier élément
1287
	// dont on a besoin de n'extraire que le premier élément
1281
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1288
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1282
	// TODO: utiliser var.keys quand ça sera plus répandu
1289
	// TODO: utiliser var.keys quand ça sera plus répandu
1283
	// ou bien utiliser un vrai tableau et pas un objet
1290
	// ou bien utiliser un vrai tableau et pas un objet
1284
	for ( var obsNum in observations ) {
1291
	for ( var obsNum in observations ) {
1285
		var obsATransmettre = {
1292
		var obsATransmettre = {
1286
			'projet'  : this.tagProjet,
1293
			'projet'  : this.tagProjet,
1287
			'tag-obs' : this.tagObs,
1294
			'tag-obs' : this.tagObs,
1288
			'tag-img' : this.tagImg
1295
			'tag-img' : this.tagImg
1289
		};
1296
		};
1290
		var utilisateur = {
1297
		var utilisateur = {
1291
			id_utilisateur : $( '#id_utilisateur' ).val(),
1298
			id_utilisateur : $( '#id_utilisateur' ).val(),
1292
			prenom         : $( '#prenom' ).val(),
1299
			prenom         : $( '#prenom' ).val(),
1293
			nom            : $( '#nom' ).val(),
1300
			nom            : $( '#nom' ).val(),
1294
			courriel       : $( '#courriel' ).val()
1301
			courriel       : $( '#courriel' ).val()
1295
		};
1302
		};
1296
		obsATransmettre['utilisateur'] = utilisateur;
1303
		obsATransmettre['utilisateur'] = utilisateur;
1297
		obsATransmettre[obsNum] = observations[obsNum];
1304
		obsATransmettre[obsNum] = observations[obsNum];
1298
		var idObsNumerique = obsNum.replace( 'obsId', '' );
1305
		var idObsNumerique = obsNum.replace( 'obsId', '' );
1299
		if( '' !== idObsNumerique ) {
1306
		if( '' !== idObsNumerique ) {
1300
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
1307
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
1301
		}
1308
		}
1302
		break;
1309
		break;
1303
	}
1310
	}
1304
};
1311
};
1305
 
1312
 
1306
WidgetSaisie.prototype.envoyerObsAuCel = function( idObs, observation ) {
1313
WidgetSaisie.prototype.envoyerObsAuCel = function( idObs, observation ) {
1307
	var lthis = this;
1314
	var lthis = this;
1308
 
1315
 
1309
	var erreurMsg = '';
1316
	var erreurMsg = '';
1310
	$.ajax({
1317
	$.ajax({
1311
		url        : lthis.serviceSaisieUrl,
1318
		url        : lthis.serviceSaisieUrl,
1312
		type       : 'POST',
1319
		type       : 'POST',
1313
		data       : observation,
1320
		data       : observation,
1314
		dataType   : 'json',
1321
		dataType   : 'json',
1315
		beforeSend : function() {
1322
		beforeSend : function() {
1316
			$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
1323
			$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
1317
			$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1324
			$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1318
			$( '.alert-txt' ).empty();
1325
			$( '.alert-txt' ).empty();
1319
			$( '.alert-txt .msg-erreur' ).remove();
1326
			$( '.alert-txt .msg-erreur' ).remove();
1320
			$( '.alert-txt .msg-debug' ).remove();
1327
			$( '.alert-txt .msg-debug' ).remove();
1321
			$( '#chargement' ).removeClass( 'hidden' );
1328
			$( '#chargement' ).removeClass( 'hidden' );
1322
		},
1329
		},
1323
		success    : function( data, textStatus, jqXHR ) {
1330
		success    : function( data, textStatus, jqXHR ) {
1324
			// mise à jour du nombre d'obs à transmettre
1331
			// mise à jour du nombre d'obs à transmettre
1325
			// et suppression de l'obs
1332
			// et suppression de l'obs
1326
			lthis.supprimerObsParId( idObs );
1333
			lthis.supprimerObsParId( idObs );
1327
			lthis.nbObsEnCours++;
1334
			lthis.nbObsEnCours++;
1328
			// mise à jour du statut
1335
			// mise à jour du statut
1329
			lthis.mettreAJourProgression();
1336
			lthis.mettreAJourProgression();
1330
			if( 0 < lthis.obsNbre ) {
1337
			if( 0 < lthis.obsNbre ) {
1331
				// dépilement de la suivante
1338
				// dépilement de la suivante
1332
				lthis.depilerObsPourEnvoi();
1339
				lthis.depilerObsPourEnvoi();
1333
			}
1340
			}
1334
		},
1341
		},
1335
		statusCode  : {
1342
		statusCode  : {
1336
			500 : function( jqXHR, textStatus, errorThrown ) {
1343
			500 : function( jqXHR, textStatus, errorThrown ) {
1337
				erreurMsg += lthis.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1344
				erreurMsg += lthis.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1338
				}
1345
				}
1339
		},
1346
		},
1340
		error        : function( jqXHR, textStatus, errorThrown ) {
1347
		error        : function( jqXHR, textStatus, errorThrown ) {
1341
			erreurMsg += lthis.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1348
			erreurMsg += lthis.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1342
			try {
1349
			try {
1343
				reponse = jQuery.parseJSON( jqXHR.responseText );
1350
				reponse = jQuery.parseJSON( jqXHR.responseText );
1344
				if ( null !== reponse ) {
1351
				if ( null !== reponse ) {
1345
					$.each( reponse, function( cle, valeur ) {
1352
					$.each( reponse, function( cle, valeur ) {
1346
						erreurMsg += valeur + '\n';
1353
						erreurMsg += valeur + '\n';
1347
					});
1354
					});
1348
				}
1355
				}
1349
			} catch( e ) {
1356
			} catch( e ) {
1350
				erreurMsg += lthis.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
1357
				erreurMsg += lthis.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
1351
			}
1358
			}
1352
		},
1359
		},
1353
		complete      : function( jqXHR, textStatus ) {
1360
		complete      : function( jqXHR, textStatus ) {
1354
			var debugMsg = extraireEnteteDebug( jqXHR );
1361
			var debugMsg = extraireEnteteDebug( jqXHR );
1355
 
1362
 
1356
			if ( '' !== erreurMsg ) {
1363
			if ( '' !== erreurMsg ) {
1357
				if ( lthis.debug ) {
1364
				if ( lthis.debug ) {
1358
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
1365
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
1359
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1366
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1360
				}
1367
				}
1361
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1368
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1362
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagProjet+
1369
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagProjet+
1363
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
1370
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
1364
 
1371
 
1365
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
1372
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
1366
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
1373
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
1367
				window.location.hash = 'obs' + idObs;
1374
				window.location.hash = 'obs' + idObs;
1368
 
1375
 
1369
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
1376
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
1370
					$( '#tpl-transmission-ko' ).clone()
1377
					$( '#tpl-transmission-ko' ).clone()
1371
						.find( '.courriel-erreur' )
1378
						.find( '.courriel-erreur' )
1372
						.attr( 'href', hrefCourriel )
1379
						.attr( 'href', hrefCourriel )
1373
						.end()
1380
						.end()
1374
						.html()
1381
						.html()
1375
				);
1382
				);
1376
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
1383
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
1377
				$( '#chargement' ).addClass( 'hidden' );
1384
				$( '#chargement' ).addClass( 'hidden' );
1378
				lthis.initialiserBarreProgression;
1385
				lthis.initialiserBarreProgression;
1379
			} else {
1386
			} else {
1380
				if ( lthis.debug ) {
1387
				if ( lthis.debug ) {
1381
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1388
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1382
				}
1389
				}
1383
				if( 0 === lthis.obsNbre ) {
1390
				if( 0 === lthis.obsNbre ) {
1384
					setTimeout( function() {
1391
					setTimeout( function() {
1385
						$( '#chargement' ).addClass( 'hidden' );
1392
						$( '#chargement' ).addClass( 'hidden' );
1386
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
1393
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
1387
						$( '#dialogue-obs-transaction-ok' ).removeClass( 'hidden' );
1394
						$( '#dialogue-obs-transaction-ok' ).removeClass( 'hidden' );
1388
						window.location.hash = 'dialogue-obs-transaction-ok';
1395
						window.location.hash = 'dialogue-obs-transaction-ok';
1389
						lthis.initialiserObs.bind( lthis );
1396
						lthis.initialiserObs.bind( lthis );
1390
					}, 1500 );
1397
					}, 1500 );
1391
				}
1398
				}
1392
			}
1399
			}
1393
		}
1400
		}
1394
	});
1401
	});
1395
};
1402
};
1396
 
1403
 
1397
WidgetSaisie.prototype.mettreAJourProgression = function() {
1404
WidgetSaisie.prototype.mettreAJourProgression = function() {
1398
	this.nbObsTransmises++;
1405
	this.nbObsTransmises++;
1399
 
1406
 
1400
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
1407
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
1401
 
1408
 
1402
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
1409
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
1403
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
1410
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
1404
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.msgTraduction( 'observations-transmises' ) );
1411
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.msgTraduction( 'observations-transmises' ) );
1405
	if( 0 === this.obsNbre ) {
1412
	if( 0 === this.obsNbre ) {
1406
		$( '.progress' ).removeClass( 'active' );
1413
		$( '.progress' ).removeClass( 'active' );
1407
		$( '.progress' ).removeClass( 'progress-bar-striped' );
1414
		$( '.progress' ).removeClass( 'progress-bar-striped' );
1408
	}
1415
	}
1409
};
1416
};
1410
 
1417
 
1411
WidgetSaisie.prototype.initialiserBarreProgression = function() {
1418
WidgetSaisie.prototype.initialiserBarreProgression = function() {
1412
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
1419
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
1413
	$( '#barre-progression-upload' ).css( 'width', '0%' );
1420
	$( '#barre-progression-upload' ).css( 'width', '0%' );
1414
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.msgTraduction( 'observations-transmises' ) );
1421
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.msgTraduction( 'observations-transmises' ) );
1415
	$( '.progress' ).addClass( 'active' );
1422
	$( '.progress' ).addClass( 'active' );
1416
	$( '.progress' ).addClass( 'progress-bar-striped' );
1423
	$( '.progress' ).addClass( 'progress-bar-striped' );
1417
};
1424
};
1418
 
1425
 
1419
WidgetSaisie.prototype.initialiserObs = function() {
1426
WidgetSaisie.prototype.initialiserObs = function() {
1420
	this.obsNbre = 0;
1427
	this.obsNbre = 0;
1421
	this.nbObsTransmises = 0;
1428
	this.nbObsTransmises = 0;
1422
	this.nbObsEnCours = 0;
1429
	this.nbObsEnCours = 0;
1423
	this.totalObsATransmettre = 0;
1430
	this.totalObsATransmettre = 0;
1424
	this.initialiserBarreProgression();
1431
	this.initialiserBarreProgression();
1425
	$( '.obs-nbre' ).text( this.obsNbre );
1432
	$( '.obs-nbre' ).text( this.obsNbre );
1426
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1433
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1427
	$( '#liste-obs' ).removeData();
1434
	$( '#liste-obs' ).removeData();
1428
	$( '.obs' ).remove();
1435
	$( '.obs' ).remove();
1429
	$( '#dialogue-bloquer-creer-obs' ).addClass( 'hidden' );
1436
	$( '#dialogue-bloquer-creer-obs' ).addClass( 'hidden' );
1430
};
1437
};
1431
 
1438
 
1432
WidgetSaisie.prototype.afficherPanneau = function( selecteur ) {
1439
WidgetSaisie.prototype.afficherPanneau = function( selecteur ) {
1433
	$( selecteur )
1440
	$( selecteur )
1434
		.removeClass( 'hidden')
1441
		.removeClass( 'hidden')
1435
		.hide()
1442
		.hide()
1436
		.show( 600 )
1443
		.show( 600 )
1437
		.delay( this.dureeMessage )
1444
		.delay( this.dureeMessage )
1438
		.hide( 600 );
1445
		.hide( 600 );
1439
};
1446
};
1440
 
1447
 
1441
WidgetSaisie.prototype.masquerPanneau = function( selecteur ) {
1448
WidgetSaisie.prototype.masquerPanneau = function( selecteur ) {
1442
	$( selecteur ).addClass( 'hidden' );
1449
	$( selecteur ).addClass( 'hidden' );
1443
};
1450
};
1444
 
1451
 
1445
WidgetSaisie.prototype.fermerPanneauAlert = function() {
1452
WidgetSaisie.prototype.fermerPanneauAlert = function() {
1446
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
1453
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
1447
};
1454
};
1448
 
1455
 
1449
/**
1456
/**
1450
 * Si la langue est définie dans this.langue, et si des messages sont définis
1457
 * Si la langue est définie dans this.langue, et si des messages sont définis
1451
 * dans this.msgs, tente de trouver le message dont la clé est [cle] dans la
1458
 * dans this.msgs, tente de trouver le message dont la clé est [cle] dans la
1452
 * langue en cours. S'il n'est pas trouvé, retourne la version française (par
1459
 * langue en cours. S'il n'est pas trouvé, retourne la version française (par
1453
 * défaut); si celle-ci n'exite pas, retourne "N/A".
1460
 * défaut); si celle-ci n'exite pas, retourne "N/A".
1454
 */
1461
 */
1455
WidgetSaisie.prototype.msgTraduction = function( cle ) {
1462
WidgetSaisie.prototype.msgTraduction = function( cle ) {
1456
	var msg = 'N/A';
1463
	var msg = 'N/A';
1457
	if ( this.msgs ) {
1464
	if ( this.msgs ) {
1458
		if ( this.langue in this.msgs && cle in this.msgs[this.langue] ) {
1465
		if ( this.langue in this.msgs && cle in this.msgs[this.langue] ) {
1459
			msg = this.msgs[this.langue][cle];
1466
			msg = this.msgs[this.langue][cle];
1460
		} else if ( cle in this.msgs['fr'] ) {
1467
		} else if ( cle in this.msgs['fr'] ) {
1461
			msg = this.msgs['fr'][cle];
1468
			msg = this.msgs['fr'][cle];
1462
		}
1469
		}
1463
	}
1470
	}
1464
	return msg;
1471
	return msg;
1465
};
1472
};
1466
 
1473
 
1467
// lib hors objet --
1474
// lib hors objet --
1468
 
1475
 
1469
/**
1476
/**
1470
* Permet à la fois de vérifier qu'une valeur ou objet existe et n'est pas vide
1477
* Permet à la fois de vérifier qu'une valeur ou objet existe et n'est pas vide
1471
* et de comparer à une autre valeur :
1478
* et de comparer à une autre valeur :
1472
* Vérifie qu'une variable ou objet n'est pas : vide, null, undefined, NaN
1479
* Vérifie qu'une variable ou objet n'est pas : vide, null, undefined, NaN
1473
* Si comparer est défini on le compare à valeur en fonction de sensComparaison
1480
* Si comparer est défini on le compare à valeur en fonction de sensComparaison
1474
* Un booléen est une variable valide : on retourne true
1481
* Un booléen est une variable valide : on retourne true
1475
* @param { string || number || object || undefined } valeur
1482
* @param { string || number || object || undefined } valeur
1476
* @param { boolean } sensComparaison : true = rechercher, false = refuser
1483
* @param { boolean } sensComparaison : true = rechercher, false = refuser
1477
* @param { string || number || object || undefined || boolean } comparer :valeur à comparer
1484
* @param { string || number || object || undefined || boolean } comparer :valeur à comparer
1478
* @returns {boolean}
1485
* @returns {boolean}
1479
*/
1486
*/
1480
function valeurOk( valeur, sensComparaison = true, comparer = undefined ) {
1487
function valeurOk( valeur, sensComparaison = true, comparer = undefined ) {
1481
 
1488
 
1482
	if ( 'boolean' !== typeof valeur ) {
1489
	if ( 'boolean' !== typeof valeur ) {
1483
		switch( typeof valeur ) {
1490
		switch( typeof valeur ) {
1484
			case 'string' :
1491
			case 'string' :
1485
				retour = ( '' !== valeur );
1492
				retour = ( '' !== valeur );
1486
			 break;
1493
			 break;
1487
			case 'number' :
1494
			case 'number' :
1488
					retour = ( NaN !== valeur );
1495
					retour = ( NaN !== valeur );
1489
				break;
1496
				break;
1490
			case 'object' :
1497
			case 'object' :
1491
					retour = ( null !== valeur && undefined !== valeur && !$.isEmptyObject( valeur ) );
1498
					retour = ( null !== valeur && undefined !== valeur && !$.isEmptyObject( valeur ) );
1492
					if ( undefined !== valeur.length ) {
1499
					if ( undefined !== valeur.length ) {
1493
						retour = ( retour  && 0 < valeur.length );
1500
						retour = ( retour  && 0 < valeur.length );
1494
					}
1501
					}
1495
				break;
1502
				break;
1496
			case 'undefined' :
1503
			case 'undefined' :
1497
			default :
1504
			default :
1498
				retour = false;
1505
				retour = false;
1499
		}
1506
		}
1500
		if ( retour && comparer !== undefined ) {
1507
		if ( retour && comparer !== undefined ) {
1501
			var resultComparaison = ( comparer === valeur );
1508
			var resultComparaison = ( comparer === valeur );
1502
			retour = ( sensComparaison ) ? resultComparaison : !resultComparaison ;
1509
			retour = ( sensComparaison ) ? resultComparaison : !resultComparaison ;
1503
		}
1510
		}
1504
		return retour;
1511
		return retour;
1505
	} else {
1512
	} else {
1506
		// Un booléen est une valeur valable
1513
		// Un booléen est une valeur valable
1507
		return true;
1514
		return true;
1508
	}
1515
	}
1509
}
1516
}
1510
 
1517
 
1511
/**
1518
/**
1512
* Stope l'évènement courant quand on clique sur un lien.
1519
* Stope l'évènement courant quand on clique sur un lien.
1513
* Utile pour Chrome, Safari...
1520
* Utile pour Chrome, Safari...
1514
*/
1521
*/
1515
function arreter( evenement ) {
1522
function arreter( evenement ) {
1516
	if ( evenement.stopPropagation ) {
1523
	if ( evenement.stopPropagation ) {
1517
		evenement.stopPropagation();
1524
		evenement.stopPropagation();
1518
	}
1525
	}
1519
	if ( evenement.preventDefault ) {
1526
	if ( evenement.preventDefault ) {
1520
		evenement.preventDefault();
1527
		evenement.preventDefault();
1521
	}
1528
	}
1522
	return false;
1529
	return false;
1523
}
1530
}
1524
 
1531
 
1525
/**
1532
/**
1526
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1533
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1527
 * @param jqXHR
1534
 * @param jqXHR
1528
 * @returns {String}
1535
 * @returns {String}
1529
 */
1536
 */
1530
function extraireEnteteDebug( jqXHR ) {
1537
function extraireEnteteDebug( jqXHR ) {
1531
	var msgDebug = '';
1538
	var msgDebug = '';
1532
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
1539
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
1533
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
1540
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
1534
		if ( null !== debugInfos ) {
1541
		if ( null !== debugInfos ) {
1535
			$.each( debugInfos, function( cle, valeur ) {
1542
			$.each( debugInfos, function( cle, valeur ) {
1536
				msgDebug += valeur + '\n';
1543
				msgDebug += valeur + '\n';
1537
			});
1544
			});
1538
		}
1545
		}
1539
	}
1546
	}
1540
	return msgDebug;
1547
	return msgDebug;
1541
}
1548
}
1542
 
1549
 
1543
/*
1550
/*
1544
 * jQuery UI Autocomplete HTML Extension
1551
 * jQuery UI Autocomplete HTML Extension
1545
 *
1552
 *
1546
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1553
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1547
 * Dual licensed under the MIT or GPL Version 2 licenses.
1554
 * Dual licensed under the MIT or GPL Version 2 licenses.
1548
 *
1555
 *
1549
 * http://github.com/scottgonzalez/jquery-ui-extensions
1556
 * http://github.com/scottgonzalez/jquery-ui-extensions
1550
 *
1557
 *
1551
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1558
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1552
 */
1559
 */
1553
	( function( $ ) {
1560
	( function( $ ) {
1554
		var proto = $.ui.autocomplete.prototype,
1561
		var proto = $.ui.autocomplete.prototype,
1555
			initSource = proto._initSource;
1562
			initSource = proto._initSource;
1556
 
1563
 
1557
		WidgetSaisie.prototype.filter = function( array, term ) {
1564
		WidgetSaisie.prototype.filter = function( array, term ) {
1558
			var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
1565
			var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
1559
			return $.grep( array, function( value ) {
1566
			return $.grep( array, function( value ) {
1560
				return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
1567
				return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
1561
			});
1568
			});
1562
		}
1569
		}
1563
		$.extend( proto, {
1570
		$.extend( proto, {
1564
			_initSource: function() {
1571
			_initSource: function() {
1565
				if ( this.options.html && $.isArray( this.options.source ) ) {
1572
				if ( this.options.html && $.isArray( this.options.source ) ) {
1566
					this.source = function( request, response ) {
1573
					this.source = function( request, response ) {
1567
						response( filter( this.options.source, request.term ) );
1574
						response( filter( this.options.source, request.term ) );
1568
					};
1575
					};
1569
				} else {
1576
				} else {
1570
					initSource.call( this );
1577
					initSource.call( this );
1571
				}
1578
				}
1572
			},
1579
			},
1573
			_renderItem: function( ul, item) {
1580
			_renderItem: function( ul, item) {
1574
				if ( item.retenu ) {
1581
				if ( item.retenu ) {
1575
					item.label = '<strong>' + item.label + '</strong>';
1582
					item.label = '<strong>' + item.label + '</strong>';
1576
				}
1583
				}
1577
 
1584
 
1578
				return $( '<li></li>' )
1585
				return $( '<li></li>' )
1579
					.data( 'item.autocomplete', item )
1586
					.data( 'item.autocomplete', item )
1580
					.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
1587
					.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
1581
					.appendTo( ul );
1588
					.appendTo( ul );
1582
			}
1589
			}
1583
		});
1590
		});
1584
	})( jQuery );
1591
	})( jQuery );