Subversion Repositories eFlore/Applications.cel

Rev

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