Subversion Repositories eFlore/Applications.cel

Rev

Rev 3263 | Rev 3271 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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