Subversion Repositories eFlore/Applications.cel

Rev

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

Rev Author Line No. Line
3425 idir 1
const utils = new Utils;
2
 
3
/**
4
 * WidgetsSaisiesCommun
5
 * Methodes communes aux widgets de saisie
6
 */
7
function WidgetsSaisiesCommun(){}
8
 
9
WidgetsSaisiesCommun.prototype.init = function() {
10
	// ASL : APA, sTREETs, Lichen's Go!
11
	// const ASL = ['tb_aupresdemonarbre','tb_streets','tb_lichensgo'];
12
	// this.isASL = ( utils.valOk( this.module ) && -1 < $.inArray( this.module , ASL ) );
13
	this.initForm();
14
	this.initEvts();
15
};
16
 
17
WidgetsSaisiesCommun.prototype.initFormConnection = function() {
18
	this.urlBaseAuth = this.urlRacine + '/service:annuaire:auth';
19
	$( '#inscription' ).attr( 'href',  this.urlSiteTb() + 'inscription' );
20
	if ( this.isASL ) {
21
		$( '#mdp' ).val( '' );
22
		$( '#oublie' ).attr( 'href',  this.urlSiteTb() + 'wp-login.php?action=lostpassword' );
23
	}
24
};
25
 
26
WidgetsSaisiesCommun.prototype.initFormTaxonListe = function() {
27
	const lthis = this;
28
 
29
	this.surChangementTaxonListe();
30
	$( '#taxon-liste' ).on( 'change', lthis.surChangementTaxonListe );
31
	$( '#taxon-liste' ).on( 'change', lthis.surChangementValeurTaxon.bind( lthis ) );
32
	if ( this.debug ) {
33
		console.dir( 'Selected taxon:' + $( '#taxon-liste option:selected' ).val());
34
	}
35
};
36
 
37
WidgetsSaisiesCommun.prototype.initEvtsConnection = function() {
38
	const lthis = this;
39
 
40
	this.chargerStatutSSO();
41
	$( '#utilisateur-connecte .volet-toggle, #profil-utilisateur a, #deconnexion a' ).on( 'click', function( event ) {
42
		if( $( this ).hasClass( 'volet-toggle' ) ) {
43
			event.preventDefault();
44
		}
45
		$( '#utilisateur-connecte .volet-menu' ).toggleClass( 'hidden' );
46
	});
47
	$( '#deconnexion a' ).on( 'click', function( event ) {
48
		event.preventDefault();
49
		lthis.deconnecterUtilisateur();
50
	});
51
	if ( !this.isASL ) {
52
		$( '#bouton-anonyme' ).on( 'click', function( event ) {
53
			lthis.arreter( event );
54
			$( this ).css({
55
				'background-color': 'rgba(0, 159, 184, 0.7)',
56
				'color': '#fff'
57
			});
58
			$( '#identite' ).removeClass( 'hidden' );
59
			$( '#courriel' ).focus();
60
		});
61
		if ( '' === $( '#nom-complet').text() ) {
62
			$( '#courriel' ).on( 'blur', this.requeterIdentiteCourriel.bind( this ) );
63
			$( '#courriel' ).on( 'keypress', this.testerLancementRequeteIdentite.bind( this ) );
64
		}
65
		$( '#prenom' ).on( 'change', function() {
66
			lthis.formaterPrenom();
67
			lthis.reduireVoletIdentite();
68
		});
69
		$( '#nom' ).on( 'change', function() {
70
			lthis.formaterNom();
71
			lthis.reduireVoletIdentite();
72
		});
73
		$( '#courriel_confirmation' ).on( 'paste', this.bloquerCopierCollerCourriel.bind( this ) );
74
		$( '#courriel_confirmation' ).on( 'blur', this.reduireVoletIdentite.bind( this ) );
75
		$( '#courriel_confirmation' ).on( 'keypress', function( event ) {
76
			if ( lthis.valOk( event.which, true, 13 ) ) {
77
				lthis.reduireVoletIdentite();
78
				event.preventDefault();
79
				event.stopPropagation();
80
			}
81
		});
82
	}
83
};
84
 
85
WidgetsSaisiesCommun.prototype.initEvtsFichier = function() {
86
	const lthis = this;
87
 
3435 idir 88
	function fileInputFonctionne() {
89
		var ua = navigator.userAgent;
90
 
91
		if (
92
			ua.match( /(Android (1.0|1.1|1.5|1.6|2.0|2.1))|(Windows Phone (OS 7|8.0))|(XBLWP)|(ZuneWP)|(w(eb)?OSBrowser)|(webOS)|(Kindle\/(1.0|2.0|2.5|3.0))/ ) ||
93
			ua.match( /\swv\).+(chrome)\/([\w\.]+)/i )
94
		) {
95
		  return false;
96
		}
97
 
98
		var elem = document.createElement( 'input' );
99
 
3434 idir 100
		elem.type = 'file';
3425 idir 101
 
3435 idir 102
		return !elem.disabled;
103
	}
104
 
105
	if ( fileInputFonctionne() ) {
3434 idir 106
		// Sur téléchargement image
107
		$( '#fichier' ).on( 'change', function ( event ) {
108
			lthis.arreter ( event );
3425 idir 109
 
3434 idir 110
			var options        = {
111
				beforeSend : function ( jqXHR, settings ) {
112
					$( '#miniatures' ).on( 'click', '.effacer-miniature', function() {
113
						jqXHR.abort(jqXHR);
114
					});
115
				},
116
				success: lthis.afficherMiniature.bind( lthis ), // post-submit callback
117
				dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
118
				resetForm: true // reset the form after successful submit
119
			};
120
			var imgCheminTmp    = $( '#fichier' ).val(),
121
				parts           = imgCheminTmp.split( '\\' ),
122
				nomImage        = parts[ parts.length - 1 ],
123
				formatImgOk     = lthis.verifierFormat( nomImage ),
124
				imgNonDupliquee = lthis.verifierDuplication( nomImage );
3425 idir 125
 
3434 idir 126
 
127
			if( formatImgOk && imgNonDupliquee ) {
128
				$( '#form-upload' ).ajaxSubmit( options );
129
				$( '#miniatures' ).append(
130
					'<div class="miniature mr-3 miniature-chargement" data-image="' + nomImage + '">'+
131
						'<img class="miniature-img chargement-img" alt="chargement" src="' + lthis.chargementImageIconeUrl + '" style="min-height:100%;"/>'+
132
						'<a class="effacer-miniature">Supprimer</a>'+
133
					'</div>'
134
				);
135
				$( '#ajouter-obs' ).addClass( 'hidden' );
136
				$( '#message-chargement' ).removeClass( 'hidden' );
137
			} else {
138
				$( '#form-upload' )[0].reset();
139
				if ( !formatImgOk ) {
140
					lthis.activerModale( lthis.msgTraduction( 'format-non-supporte' ) + ' : ' + $( '#fichier' ).attr( 'accept' ) );
141
				}
142
				if ( !imgNonDupliquee ) {
143
					lthis.activerModale( lthis.msgTraduction( 'image-deja-chargee' ) );
144
				}
145
			}
146
			return false;
147
		});
148
		$( 'body' ).on( 'click', '.effacer-miniature', function() {
149
			$( this ).parent().remove();
150
			if ( !lthis.valOk( $('.miniature-chargement' ) ) ) {
151
				$( '#ajouter-obs' ).removeClass( 'hidden' );
152
				$( '#message-chargement' ).addClass( 'hidden' );
153
			}
154
		});
155
	} else {
156
		$( '#form-upload' )
157
			.addClass( 'hidden' )
158
			.after(
159
				'<div class="alert alert-info" role="alert">'+
160
					this.msgTraduction( 'upload-non-suppote' )+
3433 idir 161
				'</div>'
162
			);
3434 idir 163
	}
164
 
3425 idir 165
};
166
 
167
WidgetsSaisiesCommun.prototype.initEvtsGeoloc = function( isFormArbre = false ) {
168
	const lthis = this;
169
 
170
	var ancre               = '-observation',
171
		complementSelecteur = '';
172
 
173
	if ( isFormArbre ) {
174
		ancre               = '-arbres';
175
		complementSelecteur = ancre;
176
	}
177
	// Empêcher que le module carto ne bind ses events partout
178
	$( '#zone' + ancre ).on( 'submit blur click focus mousedown mouseleave mouseup change', '#tb-geolocation' + complementSelecteur + ' *', function( event ) {
179
		event.preventDefault();
180
		return false;
181
	});
182
	// evenement location
183
	$( '#tb-geolocation' + complementSelecteur ).on( 'location' , this.locationHandler.bind( this ) );
184
};
185
 
186
WidgetsSaisiesCommun.prototype.initEvtsObs = function() {
187
	const lthis = this;
188
 
189
	$( '#ajouter-obs' ).on( 'click', this.ajouterObs.bind( this ) );
190
	$( '.obs-nbre' ).on( 'changement', this.surChangementNbreObs.bind( this ) );
191
	$( 'body' ).on( 'click', '.defilement-miniatures-gauche', function( event ) {
192
		event.preventDefault();
193
		lthis.defilerMiniatures( $( this ) );
194
	});
195
	$( 'body' ).on( 'click', '.defilement-miniatures-droite', function( event ) {
196
		event.preventDefault();
197
		lthis.defilerMiniatures( $( this ) );
198
	});
199
	// mécanisme de suppression d'une obs
200
	$( '#liste-obs' ).on( 'click', '.supprimer-obs', function() {
201
		var buttons = [
202
				{
203
					label   : 'Annuler',
204
					class   : 'btn-secondary',
205
					dismiss : true
206
				},
207
				{
208
					label   : 'Confirmer',
209
					class   : 'btn-success confirmer',
210
					dismiss : true
211
				}
212
			];
213
		// bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
214
		var that    = this,
215
			suppObs = lthis.supprimerObs.bind( lthis );
216
 
217
		lthis.activerModale( lthis.msgTraduction( 'confirmation-suppression' ), '', buttons );
218
		$( '.confirmer' ).on( 'click', function() {
219
			suppObs( that );
220
		});
221
	});
222
	$( '#transmettre-obs' ).on( 'click', this.transmettreObs.bind( this ) );
223
};
224
 
225
// Alertes et aides
226
WidgetsSaisiesCommun.prototype.initEvtsAlertes = function() {
227
	$( '.alert .close' ).on( 'click', this.fermerPanneauAlert );
228
	$( '#btn-aide' ).on( 'click', this.basculerAffichageAide );
229
};
230
 
231
/**
232
 * Interroge le SSO pour connaître le statut de l'utilisateur, et change le menu
233
 * à droite de la barre en fonction
234
 */
235
WidgetsSaisiesCommun.prototype.chargerStatutSSO = function() {
236
	const lthis = this;
237
	var urlAuth = this.urlBaseAuth + '/identite';
238
 
239
	if( 'local' !== this.mode ) {
240
		this.connexion( urlAuth, true );
241
		if( this.isASL) {
242
			$( '#connexion' ).on( 'click', function( event ) {
243
				event.preventDefault();
244
				if( $( '#utilisateur-connecte' ).hasClass( 'hidden' ) || !lthis.valOk( $( '#nom-complet' ).text() ) ) {
245
					var login = $( '#courriel' ).val(),
246
						mdp   = $( '#mdp' ).val();
247
					if ( lthis.valOk( login ) && lthis.valOk( mdp ) ) {
248
						urlAuth = lthis.urlBaseAuth + '/connexion?login=' + login + '&password=' + mdp;
249
						lthis.connexion( urlAuth, true );
250
					} else {
251
						lthis.activerModale( lthis.msgTraduction( 'non-connexion' ) );
252
					}
253
				}
254
			});
255
		}
256
	} else {
257
		urlAuth = this.urlWidgets + 'modules/saisie2/test-token.json';
258
		// $( '#connexion' ).on( 'click', function( event ) {
259
		// 	event.preventDefault();
260
			// lthis.connexion( urlAuth, true );
261
			this.connexion( urlAuth, true );
262
		// });
263
	}
264
};
265
 
266
/**
267
 * Déconnecte l'utilisateur du SSO
268
 */
269
WidgetsSaisiesCommun.prototype.deconnecterUtilisateur = function() {
270
	var urlAuth = this.urlBaseAuth + '/deconnexion';
271
 
272
	if( 'local' === this.mode ) {
273
		this.definirUtilisateur();
274
		window.location.reload();
275
		return;
276
	}
277
	this.connexion( urlAuth, false );
278
};
279
 
280
WidgetsSaisiesCommun.prototype.connexion = function( urlAuth, connexionOnOff ) {
281
	const lthis = this;
282
 
283
	$.ajax({
284
		url: urlAuth,
285
		type: "GET",
286
		dataType: 'json',
287
		xhrFields: {
288
			withCredentials: true
289
		}
290
	})
291
	.done( function( data ) {
292
		if( connexionOnOff ) {
293
			// connecté
294
			lthis.definirUtilisateur( data.token );
295
		} else {
296
			lthis.definirUtilisateur();
297
			window.location.reload();
298
		}
299
	})
300
	.fail( function( error ) {
301
		// @TODO gérer l'affichage de l'erreur, mais pas facile à placer
302
		// dans l'interface actuelle sans que ce soit moche
303
		//afficherErreurServeur();
304
	});
305
};
306
 
307
WidgetsSaisiesCommun.prototype.definirUtilisateur = function( jeton ) {
308
	const thisObj = this;
309
	var idUtilisateur = '',
310
		prenom        = '',
311
		nom           = '',
312
		nomComplet    = '',
313
		courriel      = '',
314
		pseudo        = '';
315
 
316
	// affichage
317
	if ( undefined !== jeton ) {
318
		// décodage jeton
319
		this.infosUtilisateur = this.decoderJeton( jeton );
320
		idUtilisateur = this.infosUtilisateur.id;
321
		prenom        = this.infosUtilisateur.prenom;
322
		nom           = this.infosUtilisateur.nom;
323
		nomComplet    = this.infosUtilisateur.intitule;
324
		courriel      = this.infosUtilisateur.sub;
325
		pseudo        = this.infosUtilisateur.pseudo;
326
		$( '#courriel' ).attr( 'disabled', 'disabled' );
327
		$( '#utilisateur-connecte, #identite' ).removeClass( 'hidden' );
328
		if ( this.isASL ) {
329
			$( '#bloc-connexion' ).addClass( 'hidden' );
330
		} else {
331
			$( '#courriel_confirmation' ).attr( 'disabled', 'disabled' );
332
			$( '#prenom' ).attr( 'disabled', 'disabled' );
333
			$( '#nom' ).attr( 'disabled', 'disabled' );
334
			$( '#bouton-connexion, #creation-compte' ).addClass( 'hidden' );
335
			$( '#zone-courriel, #zone-prenom-nom' ).addClass( 'hidden' );
336
			$( '#date-releve' ).focus();
337
		}
338
	}
339
	$( '#id_utilisateur' ).val( idUtilisateur );
340
	$( '#prenom' ).val( prenom );
341
	$( '#nom' ).val( nom );
342
	$( '#nom-complet' ).html( nomComplet );
343
	$( '#courriel' ).val( courriel );
344
	$( '#profil-utilisateur a' ).attr( 'href', this.urlSiteTb() + 'membres/' + pseudo.toLowerCase().replace( ' ', '-' ) );
345
	if ( this.isASL ) {
346
		if ( this.valOk( idUtilisateur ) ) {
347
			var nomSquelette = $( '#charger-form' ).data( 'load' ) || 'arbres';
348
			this.chargerForm( nomSquelette, thisObj );
349
		}
350
	} else {
351
		$( '.warning' ).remove();
352
		$( '#courriel_confirmation' ).val( courriel );
353
	}
354
};
355
 
356
/**
357
 * Décodage à l'arrache d'un jeton JWT, ATTENTION CONSIDERE QUE LE
358
 * JETON EST VALIDE, ne pas décoder n'importe quoi - pas trouvé de lib simple
359
 */
360
WidgetsSaisiesCommun.prototype.decoderJeton = function( jeton ) {
361
	var parts = jeton.split( '.' ),
362
		payload = parts[1];
363
	payload = this.b64d( payload );
364
	payload = JSON.parse( payload, true );
365
	return payload;
366
};
367
 
368
/**
369
 * Décodage "url-safe" des chaînes base64 retournées par le SSO (lib jwt)
370
 */
371
WidgetsSaisiesCommun.prototype.b64d = function( input ) {
372
  var remainder = input.length % 4;
373
 
374
  if ( 0 !== remainder ) {
375
	var padlen = 4 - remainder;
376
 
377
	for ( var i = 0; i < padlen; i++ ) {
378
	  input += '=';
379
	}
380
  }
381
  input = input.replace( '-', '+' );
382
  input = input.replace( '_', '/' );
383
  return atob( input );
384
};
385
 
386
WidgetsSaisiesCommun.prototype.urlSiteTb = function() {
387
	var urlPart = ( 'test' === this.mode ) ? '/test/' : '/';
388
 
389
	return this.urlRacine + urlPart;
390
};
391
 
392
// uniquement utilisé si taxon-liste ******************************************/
393
/**
394
 * Affiche/Cache le champ taxon
395
 */
396
WidgetsSaisiesCommun.prototype.surChangementTaxonListe = function() {
397
	if ( utils.valOk( $( '#taxon-liste' ).val() ) ) {
398
		if ( 'autre' !== $( '#taxon-liste' ).val() ) {
399
			$( '#taxon-input-groupe' )
400
				.hide( 200, function () {
401
					$( this ).addClass( 'hidden' ).show();
402
				})
403
				.find( '#taxon-autre' ).val( '' );
404
		} else {
405
			$( '#taxon-input-groupe' )
406
				.hide()
407
				.removeClass( 'hidden' )
408
				.show(200)
409
				.find( '#taxon-autre' )
410
					.on( 'change', function() {
411
						if( !utils.valOk( $( '#taxon-autre' ).data( 'numNomSel' ) ) ) {
412
							$( '#taxon' ).val( $( '#taxon-autre' ).val() )
413
								.data( 'value', $( '#taxon-autre' ).val() )
414
								.removeData([
415
									'numNomSel',
416
									'nomRet',
417
									'numNomRet',
418
									'nt',
419
									'famille'
420
								]);
421
						}
422
						$( '#taxon' ).trigger( 'change' );
423
					});
424
		}
425
	}
426
};
427
 
428
WidgetsSaisiesCommun.prototype.surChangementValeurTaxon = function() {
429
	var numNomSel = 0;
430
 
431
	if( this.valOk( $( '#taxon-liste' ).val() ) ) {
432
		if( 'autre' === $( '#taxon-liste' ).val() ) {
433
			this.ajouterAutocompletionNoms();
434
		} else {
435
			var optionRetenue = $( '#taxon-liste' ).find( 'option[value="' + $( '#taxon-liste' ).val() + '"]' );
436
			$( '#taxon' ).val( $( '#taxon-liste' ).val() )
437
				.data( 'value', $( '#taxon-liste' ).val() )
438
				.data( 'numNomSel', optionRetenue.data( 'num-nom-sel' ) )
439
				.data( 'nomRet', optionRetenue.data( 'nom-ret' ) )
440
				.data( 'numNomRet', optionRetenue.data( 'num-nom-ret' ) )
441
				.data( 'nt', optionRetenue.data( 'nt' ) )
442
				.data( 'famille', optionRetenue.data( 'famille' ) );
443
			$( '#taxon' ).trigger( 'change' );
444
 
445
			numNomSel = $( '#taxon' ).data( 'numNomSel' );
446
			// Si l'espèce est mal déterminée la certitude est "à déterminer"
447
			if( !this.valOk( numNomSel ) ) {
448
				$( '#certitude' ).find( 'option' ).each( function() {
449
					if ( $( this ).hasClass( 'aDeterminer' ) ) {
450
						$( this ).attr( 'selected', true );
451
					} else {
452
						$( this ).attr( 'selected', false );
453
					}
454
				});
455
			}
456
		}
457
	}
458
};
459
 
460
// Autocompletion taxons ******************************************************/
461
/**
462
 * Initialise l'autocompletion taxons
463
 */
464
WidgetsSaisiesCommun.prototype.ajouterAutocompletionNoms = function() {
465
	const lthis = this;
466
	var taxonSelecteur = '#taxon';
467
 
468
	if ( this.valOk( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
469
		taxonSelecteur += '-autre';
470
	}
471
	$( taxonSelecteur ).autocomplete({
472
		source: function( requete, add ) {
473
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
474
			requete = '';
3436 idir 475
			$( '#taxon-autocomplete-label' ).addClass( 'loading' );
3425 idir 476
			if( lthis.valOk( $( '#referentiel' ).val(), false, 'autre' ) ) {
477
				var url = lthis.getUrlAutocompletionNomsSci();
478
				$.getJSON( url, requete, function( data ) {
479
					var suggestions = lthis.traiterRetourNomsSci( data );
480
					add( suggestions );
481
				})
482
				.fail( function() {
483
					$( '#certitude' ).find( 'option' ).each( function() {
484
						if ( $( this ).hasClass( 'aDeterminer' ) ) {
485
							$( this ).prop( 'selected', true );
486
						} else {
487
							$( this ).prop( 'selected', false );
488
						}
489
					});
3436 idir 490
				})
491
				.always(function() {
492
					$( '#taxon-autocomplete-label' ).removeClass( 'loading' );
3425 idir 493
				});
494
			}
495
		},
496
		html: true
497
	});
498
	$( taxonSelecteur ).on( 'autocompleteselect', this.surAutocompletionTaxon );
499
};
500
 
501
WidgetsSaisiesCommun.prototype.getUrlAutocompletionNomsSci = function() {
502
	var taxonSelecteur = '#taxon';
503
 
504
	if ( this.valOk( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
505
		taxonSelecteur += '-autre';
506
	}
507
	var mots = $( taxonSelecteur ).val();
508
	var url = this.serviceAutocompletionNomSciUrlTpl.replace( '{referentiel}', this.nomSciReferentiel );
509
	url = url.replace( '{masque}', mots );
510
 
511
	return url;
512
};
513
 
514
/**
515
 * Objet taxons pour autocompletion en fonction de la recherche
516
 */
517
WidgetsSaisiesCommun.prototype.traiterRetourNomsSci = function( data ) {
518
	var taxonSelecteur = '#taxon',
519
		suggestions    = [];
520
 
521
	if ( this.valOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
522
		taxonSelecteur += '-autre';
523
	}
524
	if ( undefined != data.resultat ) {
525
		$.each( data.resultat, function( i, val ) {
526
			val.nn = i;
527
 
528
			var nom = {
529
				label : '',
530
				value : '',
531
				nt : 0,
532
				nomSel : '',
533
				nomSelComplet : '',
534
				numNomSel : 0,
535
				nomRet : '',
536
				numNomRet : 0,
537
				famille : '',
538
				retenu : false
539
			};
540
			if ( suggestions.length >= this.autocompletionElementsNbre ) {
541
				nom.label = '...';
542
				nom.value = $( taxonSelecteur ).val();
543
				suggestions.push( nom );
544
				return false;
545
			} else {
546
				nom.label = val.nom_sci_complet;
547
				nom.value = val.nom_sci_complet;
548
				nom.nt = val.num_taxonomique;
549
				nom.nomSel = val.nom_sci;
550
				nom.nomSelComplet = val.nom_sci_complet;
551
				nom.numNomSel = val.nn;
552
				nom.nomRet = val.nom_retenu_complet;
553
				nom.numNomRet = val['nom_retenu.id'];
554
				nom.famille = val.famille;
555
				// Tester dans ce sens, permet de considérer 'absent' comme 'false' => est-ce opportun ?
556
				// en tout cas c'est harmonisé avec le CeL
557
				nom.retenu = ( 'true' == val.retenu );
558
				suggestions.push( nom );
559
			}
560
		});
561
	}
562
	return suggestions;
563
};
564
 
565
/**
566
 * charge les données dans #taxon
567
 */
568
WidgetsSaisiesCommun.prototype.surAutocompletionTaxon = function( event, ui ) {
569
	if ( utils.valOk( ui ) ) {
570
		$( '#taxon' ).val( ui.item.value );
571
		$( '#taxon' ).data( 'value', ui.item.value )
572
			.data( 'numNomSel', ui.item.numNomSel )
573
			.data( 'nomRet', ui.item.nomRet )
574
			.data( 'numNomRet', ui.item.numNomRet )
575
			.data( 'nt', ui.item.nt )
576
			.data( 'famille', ui.item.famille );
577
		if ( ui.item.retenu ) {
578
			$( '#taxon' ).addClass( 'ns-retenu' );
579
		} else {
580
			$( '#taxon' ).removeClass( 'ns-retenu' );
581
		}
582
		// Si l'espèce est mal déterminée la certitude est "à déterminer"
583
		if( !utils.valOk( $( '#taxon' ).data( 'numNomSel' ) ) ) {
584
			$( '#certitude' ).find( 'option' ).each( function() {
585
				if ( $( this ).hasClass( 'aDeterminer' ) ) {
586
					$( this ).attr( 'selected', true );
587
				} else {
588
					$( this ).attr( 'selected', false );
589
				}
590
			});
591
		}
592
	}
593
	$( '#taxon' ).change();
594
};
595
 
596
// Fichier Images *************************************************************/
597
/**
598
 * Affiche temporairement (formulaire)
599
 * la miniature d'une image ajoutée à l'obs
600
 */
601
WidgetsSaisiesCommun.prototype.afficherMiniature = function( reponse ) {
602
	if ( this.debug ) {
603
		var debogage = $( 'debogage', reponse ).text();
604
	}
605
 
3433 idir 606
	var message        = $( 'message', reponse ).text();
607
		$blocMiniature = $( '#miniatures .miniature[data-image="' + $( 'image-nom', reponse ).text() + '"]');
3425 idir 608
 
3433 idir 609
	if( this.valOk( $blocMiniature ) ) {
610
		if ( this.valOk( message ) ) {
611
			$( '#miniature-msg' ).append( message );
612
			$blocMiniature.remove();
613
 
614
		} else {
615
			this.creerWidgetMiniature( reponse, $blocMiniature );
616
		}
617
		if ( !lthis.valOk( $( '.miniature-chargement' ) ) ) {
618
			$( '#ajouter-obs' ).removeClass( 'hidden' );
619
			$( '#message-chargement' ).addClass( 'hidden' );
620
		}
621
		$( '#ajouter-obs' ).removeAttr( 'disabled' );
3425 idir 622
	}
623
};
624
 
625
/**
626
 * Crée la miniature temporaire (formulaire) + bouton pour l'effacer
627
 */
3433 idir 628
WidgetsSaisiesCommun.prototype.creerWidgetMiniature = function( reponse, $blocMiniature ) {
3425 idir 629
	var miniatureUrl = $( 'miniature-url', reponse ).text();
3427 idir 630
	var imgNom       = $( 'image-nom', reponse ).text();
3425 idir 631
 
3433 idir 632
	$blocMiniature.removeClass( 'miniature-chargement' );
633
	$( '.miniature-img', $blocMiniature )
634
		.removeClass( 'chargement-img' )
635
		.attr({
636
			'alt' : imgNom,
637
			'src' : miniatureUrl
638
		});
3425 idir 639
};
640
 
641
/**
642
 * Retourne true si l'extension de l'image 'nom' est .jpg ou .jpeg
643
 */
3433 idir 644
WidgetsSaisiesCommun.prototype.verifierFormat = function( nomImage ) {
645
	var parts     = nomImage.split( '.' ),
3425 idir 646
		extension = parts[ parts.length - 1 ];
647
 
648
	return ( 'jpeg' === extension.toLowerCase() || 'jpg' === extension.toLowerCase() );
649
};
650
 
651
/**
652
 * Check les miniatures déjà téléchargées
653
 * renvoie false si le même nom est rencontré 2 fois
654
 * renvoie true sinon
655
 */
3433 idir 656
WidgetsSaisiesCommun.prototype.verifierDuplication = function( nomImage ) {
3425 idir 657
	const lthis = this;
658
 
3433 idir 659
	var thisSrcParts = [],
3425 idir 660
		thisNomImage = '',
661
		nonDupliquee = true;
662
 
663
	$( 'img.miniature-img,img.miniature' ).each( function() {
664
		// vérification avec alt de l'image
665
		if ( lthis.valOk ( $( this ).attr ( 'alt' ), true, nomImage ) ) {
666
			nonDupliquee = false;
667
			return false;// Pas besoin de poursuivre la boucle
668
		} else { // sinon vérifie aussi avec l'adresse (src) de l'image
669
			thisSrcParts = $( this ).attr( 'src' ).split( '/' );
670
			thisNomImage = thisSrcParts[ thisSrcParts.length - 1 ].replace( '_min', '' );
671
			if ( lthis.valOk ( thisNomImage, true, nomImage ) ) {
672
				nonDupliquee = false;
673
				return false;
674
			}
675
		}
676
	});
677
	return nonDupliquee;
678
};
679
 
680
/**
681
 * Efface une miniature (formulaire)
682
 */
683
WidgetsSaisiesCommun.prototype.supprimerMiniature = function( miniature ) {
684
	miniature.parents( '.miniature' ).remove();
685
};
686
 
687
// Geoloc *********************************************************************/
688
WidgetsSaisiesCommun.prototype.transfererCarto = function( donnees ) {
689
	var typeLocalisation = donnees.typeLocalisation || 'point',
690
		isPoint          = ( typeLocalisation === 'point' ).toString(),
691
		suffixe          = ( this.valOk( donnees.suffixe ) ) ? '-' + donnees.suffixe : '',
692
		$cartoRemplacee  = donnees.cartoRemplacee || $( '#tb-geolocation' ),
693
		layer            = donnees.layer || 'osm',
694
		latitude         = donnees.latitude || '46.5',
695
		longitude        = donnees.longitude || '2.9',
696
		// 18 est le zoom max
697
		zoomInit         = donnees.zoomInit || 18;
698
 
699
	$cartoRemplacee.remove();
700
	$( '#geoloc' + suffixe ).append(
701
		'<tb-geolocation-element'+
702
			' id="tb-geolocation' + suffixe +'"'+
703
			' layer="' + layer + '"'+
704
			' zoom_init="' + zoomInit + '"'+
705
			' lat_init="' + latitude + '"'+
706
			' lng_init="' + longitude + '"'+
707
			' marker="' + isPoint + '"'+
708
			' polyline="' + !isPoint + '"'+
709
			' polygon="false"'+
710
			' show_lat_lng_elevation_inputs="' + isPoint + '"'+
711
			' osm_class_filter=""'+
712
			' elevation_provider="mapquest"'+
713
			' map_quest_api_key="mG6oU5clZHRHrOSnAV0QboFI7ahnGg34"'+
714
		'>'+
715
		'</tb-geolocation-element>'
716
	);
717
	this.initEvtsGeoloc( true );
718
};
719
 
720
// Ajouter Obs ****************************************************************/
721
/**
722
 * Ajoute une observation à la liste des obs à transmettre
723
 * (résumé obs)
724
 */
725
WidgetsSaisiesCommun.prototype.ajouterObs = function() {
726
	if ( this.isASL ) {
3426 idir 727
		this.scrollFormTop( '#zone-' + this.sujet );
3425 idir 728
	}
729
	// Fermeture automatique des dialogue de transmission de données
730
	// @WARNING TEST
731
	$( '#dialogue-obs-transaction-ko,#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
732
	if ( this.validerForm() ) {
733
		this.masquerPanneau( '#dialogue-form-invalide' );
734
		this.obsNbre += 1;
735
		if ( this.isASL && 'arbres' === this.sujet ) {
736
			this.numArbre += 1;
737
			// bouton info de cet arbre et affichage numéro du prochain arbre
738
			this.lienArbreInfo( this.numArbre );
739
			$( '#arbre-nb' ).text( this.numArbre + 1 );
740
		}
741
		$( '.obs-nbre' ).text( this.obsNbre );
742
		$( '.obs-nbre' ).triggerHandler( 'changement' );
743
		//formatage des données
744
		var obsData = this.formaterFormObsData();
745
		this.afficherObs( obsData );
746
		this.stockerObsData( obsData );
747
		if ( this.isASL && 'arbres' === this.sujet ) {
748
			var arbreData = obsData.sujet;
749
			// Ajout de donnée utiles puis stockage dans input hidden "releve-data"
750
			arbreData['date_rue_commune']  = obsData.releve.date + obsData.releve.rue + obsData.releve['commune-nom'];
751
			arbreData['id_observation']    = 0;
752
			this.releveDatas               = $.parseJSON( $( '#releve-data' ).val() );
753
			this.releveDatas[this.obsNbre] = arbreData;
754
			$( '#releve-data' ).val( JSON.stringify( this.releveDatas ) );
755
			this.modeArbresBasculerActivation( false );
756
		} else {
757
			this.reinitialiserForm();
758
		}
759
		$( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre );
760
		$( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' ' + this.msgTraduction( 'observations-transmises' ) );
761
	} else {
762
		this.afficherPanneau( '#dialogue-form-invalide' );
763
	}
764
};
765
 
766
/**
767
 * Formatage des données du formulaire pour stockage et envoi
768
 */
769
WidgetsSaisiesCommun.prototype.formaterFormObsData = function() {
770
	var obsData      = { obsNum : this.obsNbre, sujet : {}},
771
		numNomSel    = $( '#taxon' ).data( 'numNomSel' ),
772
		nomSel       = $( '#taxon' ).val(),
773
		nomRet       = $( '#taxon' ).data( 'nomRet' ),
774
		numNomRet    = $( '#taxon' ).data( 'numNomRet' ),
775
		numTaxon     = $( '#taxon' ).data( 'nt' ),
776
		famille      = $( '#taxon' ).data( 'famille' ),
777
		referentiel  = ( this.valOk( numNomSel ) ) ? this.nomSciReferentiel : 'autre',
778
		certitude    = ( this.valOk( numNomSel ) ) ? $( '#certitude' ).val() : 'à determiner',
779
		imgB64       = [],
780
		imgNom       = [],
781
		date         = '',
782
		notes        = '',
783
		pays         = '',
784
		communeNom   = '',
785
		communeInsee = '',
786
		latitude     = '',
787
		longitude    = '',
788
		altitude     = '',
789
		obsEtendue   = [];
790
 
791
	if( !this.isASL ) {
792
		notes            = $( '#notes' ).val().trim() || '';
793
		pays             = $( '#pays' ).val() || '';
794
		communeNom       = $( '#commune-nom' ).val();
795
		communeInsee     = $( '#commune-insee' ).val() || '';
796
		latitude         = $( '#latitude' ).val();
797
		longitude        = $( '#longitude' ).val();
798
		altitude         = $( '#altitude' ).val();
799
		obsEtendue       = this.getObsChpSpecifiques();
3426 idir 800
		date             = this.fournirDate( $('#date_releve').val());
3425 idir 801
	} else {
802
		var miniatureImg = [];
803
		notes = $( '#commentaire' ).val() || '';
804
		if ( 'arbres' === this.sujet ) {
805
		// Dans ce cas cette fonction doit renvoyer des données au même format que l'input hidden "releve-data"
806
		// car les données dans stockerObsData provenir soit de cette fonction soit de l'input
807
			$( '.miniature-img' ).each( function() {
808
				if ( $( this ).hasClass( 'b64' ) ) {
809
					imgB64 = $( this ).attr( 'src' ) || '';
810
				} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
811
					imgB64 = $( this ).data( 'b64' ) || '';
812
				}
813
				miniatureImg.push({
814
					'nom' : $( this ).attr( 'alt' ),
815
					'src' : $( this ).attr( 'src' ),
816
					'b64' : imgB64
817
				});
818
			});
819
			obsData.sujet = {
820
				'num-arbre' : this.numArbre,
821
				taxon       : {
822
					'numNomSel' : numNomSel,
823
					'value'     : nomSel,
824
					'nomRet'    : nomRet,
825
					'numNomRet' : numNomRet,
826
					'nt'        : numTaxon,
827
					'famille'   : famille
828
				},
829
				'referentiel'      : referentiel,
830
				'certitude'        : certitude,
831
				'rue-arbres'       : ( $( '#rue-arbres' ).val() ) ? $('#rue-arbres').val() : '',
832
				'latitude-arbres'  : $( '#latitude-arbres' ).val(),
833
				'longitude-arbres' : $( '#longitude-arbres' ).val(),
834
				'altitude-arbres'  : $( '#altitude-arbres' ).val(),
835
				'circonference'    : $( '#circonference' ).val(),
836
				'com-arbres'       : ( $( '#com-arbres' ).val() ) ? $('#com-arbres').val() : '',
837
				'miniature-img'    : miniatureImg
838
			};
839
			obsData.releve = {
840
				'date'                  : this.fournirDate( $( '#releve-date' ).val() ),
841
				'rue'                   : $( '#rue' ).val(),
842
				'latitude-releve'       : $( '#latitude-releve' ).val(),
843
				'longitude-releve'      : $( '#longitude-releve' ).val(),
844
				'altitude-releve'       : $( '#altitude-releve' ).val(),
845
				'commune-nom'           : $( '#commune-nom' ).val(),
846
				'commune-insee'         : ( $( '#commune-insee' ).val() ) ? $('#commune-insee').val() : '',
847
				'pays'                  : ( $( '#pays' ).val() ) ? $('#pays').val() : '',
848
				'commentaires'          : notes
849
			};
850
			if ( 'tb_lichensgo' !== this.module ) {
851
				obsData.sujet['surface-pied']          = $( '#surface-pied' ).val();
852
				obsData.sujet['equipement-pied-arbre'] = $( '#equipement-pied-arbre' ).val();
853
				obsData.sujet['tassement']             = $( '#tassement' ).val() || '';
854
				obsData.sujet['dejections']            = $( '#dejections input:checked' ).val() || '';
855
				obsData.releve['zone-pietonne']        = $( '#zone-pietonne input:checked' ).val();
856
				obsData.releve['pres-lampadaires']     = $( '#pres-lampadaires input:checked' ).val() || '';
857
			}
858
			if ( 'tb_streets' !== this.module ) {
859
				var faceOmbre = [];
860
				$( '#face-ombre input' ).each( function() {
861
					if( $( this ).is( ':checked' ) ) {
862
						faceOmbre.push( $( this ).val() );
863
					}
864
				});
865
				obsData.sujet['face-ombre'] = faceOmbre;
866
			}
867
		} else {
868
			this.releveDatas = $.parseJSON( $( '#releve-data' ).val() );
869
			obsData.numArbre = $( '#choisir-arbre' ).val();
870
			pays             = this.releveDatas[0].pays || '';
871
			communeNom       = this.releveDatas[0]['commune-nom'];
872
			communeInsee     = this.releveDatas[0]['commune-insee'] || '';
873
			latitude         = this.releveDatas[obsData.numArbre]['latitude-arbres'];
874
			longitude        = this.releveDatas[obsData.numArbre]['longitude-arbres'];
875
			altitude         = this.releveDatas[obsData.numArbre]['altitude-arbres'];
876
			obsEtendue       = this.getObsChpSpecifiques( obsData.numArbre );
3426 idir 877
			date             = this.fournirDate( $( '#obs-date' ).val() );
3425 idir 878
		}
879
	}
880
	if ( !this.isASL || 'arbres' !== this.sujet ) {
881
		imgNom        = this.getNomsImgsOriginales();
882
		imgB64        = this.getB64ImgsOriginales();
883
 
884
		obsData.sujet = {
885
			'num_nom_sel'        : numNomSel,
886
			'nom_sel'            : nomSel,
887
			'nom_ret'            : nomRet,
888
			'num_nom_ret'        : numNomRet,
889
			'num_taxon'          : numTaxon,
890
			'famille'            : famille,
891
			'referentiel'        : referentiel,
892
			'certitude'          : certitude,
893
			'date'               : date,
894
			'notes'              : notes,
895
			'pays'               : pays,
896
			'commune_nom'        : communeNom,
897
			'commune_code_insee' : communeInsee,
898
			'latitude'           : latitude,
899
			'longitude'          : longitude,
900
			'altitude'           : altitude,
901
			//Ajout des champs images
902
			'image_nom'          : imgNom,
903
			'image_b64'          : imgB64,
904
			// Ajout des champs étendus de l'obs
905
			'obs_etendue'        : obsEtendue
906
		};
907
		if ( !this.isASL ) {
908
			obsData.sujet['lieudit'] = $( '#lieudit' ).val() || '';
909
			obsData.sujet['station'] = $( '#station' ).val() || '';
910
			obsData.sujet['milieu']  = $( '#milieu' ).val() || '';
911
		}
912
	}
913
	return obsData;
914
};
915
 
916
/**
917
 * Affiche une observation dans la liste des observations à transmettre
918
 */
919
WidgetsSaisiesCommun.prototype.afficherObs = function( datasObs ) {
920
	// différences html liéees au responsive
921
	var responsivDiff1 = '',
922
		responsivDiff2 = '',
923
		responsivDiff3 = '',
924
		responsivDiff4 = '',
925
		responsivDiff5 = '',
926
		responsivDiff6 = '';
927
	if ( window.matchMedia( '(min-width: 576px)' ).matches ) {
928
		/* La largeur minimum de l'affichage est 600 px inclus */
929
		responsivDiff1 = ' droite';
930
		responsivDiff2 = '<div></div>';
931
		responsivDiff3 = '<div class="row">';
932
		responsivDiff4 = ( !this.isASL ) ? ' col-md-2 col-sm-4' : ' col-md-4 col-sm-5';
933
		responsivDiff5 = ( !this.isASL ) ? ' class="col-md-9 col-sm-7"' : ' class="col-md-7 col-sm-6"';
934
		responsivDiff6 = '</div>';
935
	}
936
 
937
	var obsNum           = datasObs.obsNum,
3426 idir 938
		numNomSel        = datasObs.sujet['num_nom_sel'] || '',
3425 idir 939
		taxon            = '',
940
		miniatures       = '',
941
		notes            = '',
942
		commentaires     = '',
943
		date             = '',
944
		latitude         = '',
945
		longitude        = '',
946
		coordonnees      = '',
947
		commune          = '',
948
		lieuObs          = '',
949
		inseeCommuneText = '',
950
		referentiel      = '',
951
		nn               = '',
952
		lieudit          = '',
953
		station          = '',
954
		milieu           = '',
955
		certitude        = '',
956
		numArbre         = '',
957
		obsArbre         = '';
958
 
959
	if ( !this.isASL ) {
960
		latitude     = datasObs.sujet['latitude'] || '';
961
		longitude    = datasObs.sujet['longitude'] || '';
962
		inseeCommune = datasObs.sujet['commune_code_insee'] || '';
3426 idir 963
		commune      = datasObs.sujet['commune_nom'] || '';
3425 idir 964
		if ( this.valOk( inseeCommune ) ) {
965
			inseeCommuneText = '(INSEE Commune:' + inseeCommune + ') ';
966
		}
967
		if ( this.valOk( numNomSel ) ) {
968
			referentiel = '<span class="referentiel-obs">' + '[' + datasObs.sujet['referentiel'] + ']' + '</span>';
969
		}
970
		if ( this.valOk( datasObs.sujet['lieudit'] ) ) {
971
			lieudit = '<span>' + this.msgTraduction( 'lieu-dit' ) + ' :</span> ' + datasObs.sujet['lieudit'] + ' ';
972
		}
973
		if ( this.valOk( datasObs.sujet['station'] ) ) {
974
			station = '<span>' + this.msgTraduction( 'station' ) + ' :</span> ' + datasObs.sujet['station'] + ' ';
975
		}
976
		if ( this.valOk( datasObs.sujet['milieu'] ) ) {
977
			milieu = '<span>' + this.msgTraduction( 'milieu' ) + ' :</span> ' + datasObs.sujet['milieu'] + ' ';
978
		}
979
		nn = this.ajouterNumNomSel( numNomSel );
980
	} else {
981
		certitude = ' [certitude : ' + datasObs.sujet.certitude + ']';
982
		if ( 'arbres' === this.sujet ) {
983
			numArbre   = datasObs.sujet['num-arbre'];
984
			numNomSel  = datasObs.sujet.taxon.numNomSel;
985
			taxon      = datasObs.sujet.taxon.value;
986
			miniatures = this.ajouterImgMiniatureAuTransfert(datasObs.sujet['miniature-img'] );
987
			notes      = datasObs.sujet['com-arbres'] || '';
988
			latitude   = datasObs.sujet['latitude-arbres'];
989
			longitude  = datasObs.sujet['longitude-arbres'];
990
			numArbre   = datasObs.sujet['num-arbre'];
991
			// s'assurer que la date est au bon format
992
			date       = this.fournirDate( datasObs.releve.date );
3426 idir 993
			commune    = datasObs.releve['commune-nom'] || '';
3425 idir 994
		} else {
3426 idir 995
			numArbre   = datasObs.numArbre;
3425 idir 996
		}
997
		obsArbre = '<span id="obs-arbre-' + numArbre + '" class="badge num-obs-arbre" data-arbre="' + numArbre + '">Arbre ' + numArbre + '</span>';
998
	}
999
	if ( !this.isASL || 'arbres' !== this.sujet ) {
1000
		taxon      = datasObs.sujet['nom_sel'];
1001
		miniatures = this.ajouterImgMiniatureAuTransfert();
1002
		notes      = datasObs.sujet['notes'] || '';
1003
		date       = this.fournirDate( datasObs.sujet.date );
1004
	}
1005
	if( !this.isASL || 'arbres' === this.sujet ) {
1006
		if ( this.valOk( commune ) ) {
1007
			lieuObs = ' '  + this.msgTraduction( 'lieu-obs' ) + ' ' + '<span class="commune">' + commune + '</span> ';
1008
		}
1009
		if ( this.valOk( latitude ) && this.valOk( longitude ) ) {
1010
			coordonnees = '[' + latitude + ' / ' + longitude + ']';
1011
		}
1012
	}
1013
	if ( this.valOk( notes ) ) {
1014
		commentaires =
1015
			this.msgTraduction( 'commentaires' ) +
1016
			' : <span>'+
1017
				notes +
1018
			'</span> ';
1019
	}
1020
	// html du bloc résumé de l'obs
1021
	$( '#liste-obs' ).prepend(
1022
		'<div id="obs' + obsNum + '" class="obs obs' + obsNum + ' mb-2">'+
1023
			'<div '+
1024
				'class="obs-action" '+
1025
				'title="' + this.msgTraduction( 'supprimer-observation-liste' ) + '"'+
1026
			'>'+
1027
				'<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ obsNum + '" title="' + this.msgTraduction( 'obs-numero' ) + obsNum + '">'+
1028
				'<i class="far fa-trash-alt"></i>'+
1029
				'</button>'+
1030
				responsivDiff2 +
1031
			'</div> '+
1032
			responsivDiff3 +
1033
				'<div class="thumbnail' + responsivDiff4 + '">'+
1034
					miniatures +
1035
				'</div>'+
1036
				'<div' + responsivDiff5 + '>'+
1037
					'<ul class="unstyled">'+
1038
						'<li>'+
1039
							// isASL
1040
							obsArbre +
1041
							// toujours
1042
							'<span class="nom-sci">' + taxon + '</span> '+
1043
							// !isASL
1044
							nn +
1045
							referentiel +
1046
							// isASL
1047
							certitude +
1048
							// !this.isASL || 'arbres' === this.sujet
1049
							lieuObs +
1050
							// !isASL
1051
							inseeCommuneText +
1052
							// !this.isASL || 'arbres' === this.sujet
1053
							coordonnees +
1054
							// toujours
1055
							' ' + this.msgTraduction( 'obs-le' ) + ' '+
1056
							'<span class="date">' + date + '</span>'+
1057
						'</li>'+
1058
						'<li>'+
1059
							// !isASL
1060
							lieudit +
1061
							station +
1062
							milieu +
1063
						'</li>'+
1064
						'<li>'+
1065
							// this.valOk( notes )
1066
							commentaires +
1067
						'</li>'+
1068
					'</ul>'+
1069
				'</div>'+
1070
			responsivDiff6+
1071
		'</div>'
1072
	);
1073
 
1074
	$( '#zone-liste-obs' ).removeClass( 'hidden' );
1075
};
1076
 
1077
/**
1078
 * Ajoute une boîte de miniatures avec défilement des images,
1079
 * pour une obs de la liste des obs à transmettre
1080
 */
1081
WidgetsSaisiesCommun.prototype.ajouterImgMiniatureAuTransfert = function( chargerImages = undefined ) {
1082
	const lthis = this;
1083
	var html         =
1084
			'<div class="defilement-miniatures">'+
1085
				'<figure class="centre">'+
1086
					'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
1087
				'</figure>'+
1088
			'</div>',
1089
		miniatures   = '',
1090
		centre       = '',
1091
		defilVisible = '',
1092
		length       = 0;
1093
 
1094
	if ( this.valOk( chargerImages ) || this.valOk( $( '#miniatures img' ) ) ) {
1095
		if ( this.valOk( chargerImages ) ) {
1096
			$.each(  chargerImages, function( i, value ) {
1097
				var imgVisible = ( 0 < i ) ? 'miniature-cachee' : 'miniature-selectionnee';
1098
 
1099
				var css        = ( lthis.valOk( value['b64'] ) ) ? 'miniature b64' : 'miniature',
1100
					src        = value.src,
1101
					alt        = value.nom,
1102
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1103
 
1104
				miniatures += miniature;
1105
			});
1106
			length = chargerImages.length;
1107
		} else {
1108
			var premiere     = true;
1109
			$( '#miniatures img' ).each( function() {
1110
				var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
1111
				premiere = false;
1112
 
1113
				var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
1114
					src        = $( this ).attr( 'src' ),
1115
					alt        = $( this ).attr( 'alt' ),
1116
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1117
 
1118
				miniatures += miniature;
1119
			});
1120
			length = $( '#miniatures img' ).length;
1121
		}
1122
		if ( 1 === length ) {
1123
			centre       = 'centre';
1124
			defilVisible = ' defilement-miniatures-cache';
1125
		}
1126
		html             =
1127
			'<div class="defilement-miniatures">'+
1128
				'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
1129
				'<figure class="' + centre + '">'+
1130
					miniatures+
1131
				'</figure>'+
1132
				'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
1133
			'</div>';
1134
	}
1135
 
1136
	return html;
1137
};
1138
 
1139
/**
1140
 * Construit le html à afficher pour le numNom
1141
 */
1142
WidgetsSaisiesCommun.prototype.ajouterNumNomSel = function( numNomSel ) {
1143
	var nn = '<span class="nn">[nn' + numNomSel + ']</span>';
1144
 
1145
	if ( !this.valOk( numNomSel ) ) {
1146
		nn = '<span class="alert-error">[' + this.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
1147
	}
1148
 
1149
	return nn;
1150
};
1151
 
1152
/**
1153
 * Stocke des données d'obs à envoyer à la bdd
1154
 */
1155
WidgetsSaisiesCommun.prototype.stockerObsData = function( obsDatas ) {
1156
	if ( this.isASL && 'arbres' === this.sujet ) {
1157
		// Dans ce cas la fonction formaterFormObsData renvoie des données au même format que l'input hidden "releve-data"
1158
		// car les données peuvent provenir soit de la formaterFormObsData soit de cet input
1159
		const lthis = this;
3428 idir 1160
		// si releve dupliqué on ne stocke pas l'image :
1161
		var stockerImg  = this.valOk( obsDatas.sujet['miniature-img'] ),
3425 idir 1162
			imgNom      = [],
1163
			imgB64      = [];
1164
 
1165
		// Si on a bien un 'miniature-img' dans les données
1166
		if( stockerImg ) {
1167
			$.each( obsDatas.sujet['miniature-img'], function( i, obj ) {
1168
				if( obj.hasOwnProperty( 'id' ) ) {
1169
					stockerImg = false;
1170
				}
1171
				return stockerImg;
1172
			});
1173
		}
1174
		// Si les miniatures ne sont pas déjà stockées (résultat de la loop précédente)
1175
		if( stockerImg ) {
1176
			$.each( obsDatas.sujet['miniature-img'] , function( i, obj ) {
1177
				if( lthis.valOk( obj.nom ) ) {
1178
					imgNom.push( obj.nom );
1179
				}
1180
				if( lthis.valOk( obj['b64'] ) ) {
1181
					imgB64.push( obj['b64'] );
1182
				}
1183
			});
1184
		} else {
1185
			imgNom = lthis.getNomsImgsOriginales();
1186
			imgB64 = lthis.getB64ImgsOriginales();
1187
		}
1188
		// Stockage en data des données d'obs à transmettre
3428 idir 1189
		$( '#liste-obs' ).data( 'obsId' + obsDatas.obsNum, {
1190
			'num_nom_sel'        : obsDatas.sujet.taxon.numNomSel,
3425 idir 1191
			'nom_sel'            : obsDatas.sujet.taxon.value,
1192
			'nom_ret'            : obsDatas.sujet.taxon.nomRet,
1193
			'num_nom_ret'        : obsDatas.sujet.taxon.numNomRet,
1194
			'num_taxon'          : obsDatas.sujet.taxon.nt,
1195
			'famille'            : obsDatas.sujet.taxon.famille,
1196
			'referentiel'        : obsDatas.sujet.referentiel,
1197
			'certitude'          : obsDatas.sujet.certitude,
1198
			// La date provenant de input "releve-data" n'est pas au bon format
3428 idir 1199
			'date'               : this.fournirDate( obsDatas.releve.date ),
3425 idir 1200
			'notes'              : obsDatas.releve.commentaires.trim(),
1201
			'pays'               : obsDatas.releve.pays,
1202
			'commune_nom'        : obsDatas.releve['commune-nom'],
1203
			'commune_code_insee' : obsDatas.releve['commune-insee'],
1204
			'latitude'           : obsDatas.sujet['latitude-arbres'],
1205
			'longitude'          : obsDatas.sujet['longitude-arbres'],
1206
			'altitude'           : obsDatas.sujet['altitude-arbres'],
1207
			'image_nom'          : imgNom,
1208
			'image_b64'          : imgB64,
1209
			// Ajout des champs étendus de l'obs
1210
			'obs_etendue'        : lthis.getObsChpSpecifiques( obsDatas )
1211
		});
1212
	} else {
1213
		// Stockage en data des données d'obs à transmettre
1214
		$( '#liste-obs' ).data( 'obsId' + obsDatas.obsNum, obsDatas.sujet );
1215
	}
1216
};
1217
 
1218
WidgetsSaisiesCommun.prototype.getNomsImgsOriginales = function() {
1219
	var noms = new Array();
1220
 
1221
	$( '.miniature-img' ).each( function() {
1222
		noms.push( $( this ).attr( 'alt' ) );
1223
	});
1224
 
1225
	return noms;
1226
};
1227
 
1228
WidgetsSaisiesCommun.prototype.getB64ImgsOriginales = function() {
1229
	var b64 = new Array();
1230
 
1231
	$( '.miniature-img' ).each( function() {
1232
		if ( $( this ).hasClass( 'b64' ) ) {
1233
			b64.push( $( this ).attr( 'src' ) );
1234
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
1235
			b64.push( $( this ).data( 'b64' ) );
1236
		}
1237
	});
1238
 
1239
	return b64;
1240
};
1241
 
1242
/**
1243
 * Efface toutes les miniatures (formulaire)
1244
 */
1245
WidgetsSaisiesCommun.prototype.supprimerMiniatures = function() {
1246
	if ( !this.isASL ) {
1247
		// Déconnection MutationObserver miniatures
1248
		// Sinon on a une erreur avant la création d'une nouvelle obs
1249
		this.observer.disconnect();
1250
		$( '#miniatures' ).empty();
1251
		// Validation miniatures reprend à 0 pour une nouvelle obs
1252
		this.surPresenceAbsenceMiniature();
1253
	} else {
1254
		$( '#miniatures' ).empty();
1255
	}
1256
	$( '#miniature-msg' ).empty();
1257
};
1258
 
1259
WidgetsSaisiesCommun.prototype.surChangementNbreObs = function() {
1260
	if ( 0 === this.obsNbre ) {
1261
		$( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
1262
	} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1263
		$( '#ajouter-obs,#transmettre-obs' ).removeAttr( 'disabled' );
1264
	} else if ( this.obsNbre >= this.obsMaxNbre ) {
1265
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1266
		this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
1267
	}
1268
	if ( this.isASL && 'arbres' === this.sujet ) {
1269
		if ( 0 <= this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1270
			$( '#bloc-form-arbres' ).removeClass( 'hidden' );
1271
		} else {
1272
			$( '#bloc-form-arbres' ).addClass( 'hidden' );
1273
		}
1274
	}
1275
};
1276
 
1277
WidgetsSaisiesCommun.prototype.defilerMiniatures = function( element ) {
1278
	var miniatureSelectionne  = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
1279
 
1280
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
1281
	miniatureSelectionne.addClass( 'miniature-cachee' );
1282
 
1283
	var miniatureAffichee     = miniatureSelectionne;
1284
 
1285
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
1286
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
1287
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
1288
		} else {
1289
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
1290
		}
1291
	} else {
1292
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
1293
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
1294
		} else {
1295
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
1296
		}
1297
	}
1298
	miniatureAffichee.addClass( 'miniature-selectionnee' );
1299
	miniatureAffichee.removeClass( 'miniature-cachee' );
1300
};
1301
 
1302
WidgetsSaisiesCommun.prototype.supprimerObs = function( selector ) {
1303
	var obsId = $( selector ).val();
1304
 
1305
	// Problème avec IE 6 et 7
1306
	if ( 'Supprimer' === obsId ) {
1307
		obsId = $( selector ).attr( 'title' );
1308
	}
1309
	this.supprimerObsParId( obsId );
1310
};
1311
 
1312
/**
1313
 * Supprime l'obs et les data de l'obs
1314
 * et remonte les suivantes d'un cran
1315
 */
1316
WidgetsSaisiesCommun.prototype.supprimerObsParId = function( obsId, transmission = false ) {
1317
	if ( this.isASL && 'arbres' === this.sujet ) {
1318
		if ( !transmission ) {
1319
			this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1320
			this.releveData.splice( obsId , 1 );
1321
			$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1322
		}
1323
		$( '#arbre-info-' + ( this.numArbre ) ).remove();
1324
		$( '#arbre-nb' ).text( this.numArbre );
1325
		this.numArbre -= 1;
1326
		if ( 1 > this.numArbre ) {
1327
			$( '#bloc-info-arbres-title' ).addClass( 'hidden' );
1328
		}
1329
 
1330
		var arbreExId   = 0,
1331
			arbreId     = 0;
1332
	}
1333
	this.obsNbre  -= 1;
1334
	$( '.obs-nbre' ).text( this.obsNbre );
1335
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1336
	$( '.obs' + obsId ).remove();
1337
	obsId = parseInt(obsId);
1338
 
1339
	if ( !transmission ) {
1340
		var listObsData = $( '#liste-obs' ).data(),
1341
			exId        = 0,
1342
			indexObs    = '',
1343
			exIndexObs  = '';
1344
 
1345
		for ( var id = obsId; id <= ( this.obsNbre + 1 ); id++ ) {
1346
			exId       = parseInt(id) + 1;
1347
			indexObs   = 'obsId' + id;
1348
			exIndexObs = 'obsId' + exId;
1349
			$( '#liste-obs' ).removeData( indexObs );
1350
			$( '#obs' + exId )
1351
				.attr( 'id', 'obs' + id )
1352
				.removeClass( 'obs' + exId )
1353
				.addClass( 'obs' + id )
1354
				.find( '.supprimer-obs' )
1355
					.attr( 'title', 'Observation n°' + id )
1356
					.val( id );
1357
 
1358
			if ( this.isASL && 'arbres' === this.sujet ) {
1359
				arbreExId = parseInt( $( '#obs-arbre-' + exId ).data( 'arbre' ) );
1360
				arbreId   = arbreExId - 1;
1361
				$( '#obs-arbre-' + arbreExId )
1362
					.attr( 'id', 'obs-arbre-' + arbreId )
1363
					.attr( 'data-arbre', arbreId )
1364
					.data( 'arbre', arbreId )
1365
					.text( 'Arbre ' + arbreId );
1366
				// modification du numero d'arbre dans les obs étendues
1367
				if ( this.valOk( listObsData[exIndexObs] ) ) {
1368
					$.each( listObsData[exIndexObs].obs_etendue, function( i, obsE ) {
1369
						if ('num_arbre' === obsE.cle ) {
1370
							listObsData[exIndexObs].obs_etendue[i].valeur = arbreId;
1371
							return false;
1372
						}
1373
					});
1374
				}
1375
			}
1376
 
1377
			// Mise à jour des données à transmettre
1378
			if ( this.valOk( listObsData[exIndexObs] ) ) {
1379
				$( '#liste-obs' ).data( indexObs, listObsData[exIndexObs] );
1380
			}
1381
			if ( parseInt( id ) !== this.obsNbre ) {
1382
				id = parseInt(id);
1383
			}
1384
		}
1385
	} else {
1386
		$( '#liste-obs' ).removeData( 'obsId' + obsId );
1387
	}
1388
};
1389
 
1390
WidgetsSaisiesCommun.prototype.transmettreObs = function() {
1391
	const lthis = this;
1392
	var observations = $( '#liste-obs' ).data();
1393
 
1394
	if ( this.debug ) {
1395
		console.dir( observations );
1396
	}
1397
	if ( !this.valOk( typeof observations, true, 'object' ) ) {
1398
		this.afficherPanneau( '#dialogue-zero-obs' );
1399
	} else {
1400
		this.nbObsEnCours         = 1;
1401
		this.nbObsTransmises      = 0;
1402
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
1403
			return i;
1404
		}).length;
1405
		this.depilerObsPourEnvoi();
1406
	}
1407
 
1408
	return false;
1409
};
1410
 
1411
WidgetsSaisiesCommun.prototype.depilerObsPourEnvoi = function() {
1412
	var observations = $( '#liste-obs' ).data();
1413
	// la boucle est factice car on utilise un tableau
1414
	// dont on a besoin de n'extraire que le premier élément
1415
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1416
	// TODO: utiliser var.keys quand ça sera plus répandu
1417
	// ou bien utiliser un vrai tableau et pas un objet
1418
	for ( var obsNum in observations ) {
1419
		var obsATransmettre = {
1420
			'projet'  : this.tagsProjet,
1421
			'tag-obs' : this.tagObs,
1422
			'tag-img' : this.tagImg
1423
		};
1424
		var utilisateur = {
1425
			id_utilisateur : $( '#id_utilisateur' ).val(),
1426
			prenom         : $( '#prenom' ).val(),
1427
			nom            : $( '#nom' ).val(),
1428
			courriel       : $( '#courriel' ).val()
1429
		};
1430
 
1431
		obsATransmettre['utilisateur'] = utilisateur;
1432
		obsATransmettre[obsNum]        = observations[obsNum];
1433
 
1434
		var idObsNumerique = obsNum.replace( 'obsId', '' );
1435
 
1436
		if( '' !== idObsNumerique ) {
1437
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
1438
		}
1439
		break;
1440
	}
1441
};
1442
 
1443
WidgetsSaisiesCommun.prototype.envoyerObsAuCel = function( idObs, observation ) {
1444
	const lthis = this;
1445
 
1446
	var erreurMsg = '';
1447
 
1448
	$.ajax({
1449
		url        : lthis.serviceSaisieUrl,
1450
		type       : 'POST',
1451
		data       : observation,
1452
		dataType   : 'json',
1453
		beforeSend : function() {
1454
			$( '#dialogue-obs-transaction-ko,#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1455
			$( '.alert-txt' ).empty();
1456
			$( '.alert-txt .msg-erreur,.alert-txt .msg-debug' ).remove();
1457
			$( '#chargement' ).removeClass( 'hidden' );
1458
		},
1459
		success    : function( transfertDatas, textStatus, jqXHR ) {
1460
			if( lthis.isASL && 'arbres' === lthis.sujet ) {
1461
				// actualisation de id_observation dans '#releve-data'
1462
				lthis.actualiserReleveDataIdObs( idObs, transfertDatas.id );
1463
			}
1464
			// mise à jour du nombre d'obs à transmettre
1465
			// et suppression de l'obs
1466
			lthis.supprimerObsParId( idObs, true );
1467
			lthis.nbObsEnCours++;
1468
			// mise à jour du statut
1469
			lthis.mettreAJourProgression();
1470
			if( 0 < lthis.obsNbre ) {
1471
				// dépilement de la suivante
1472
				lthis.depilerObsPourEnvoi();
1473
			}
1474
		},
1475
		statusCode  : {
1476
			500 : function( jqXHR, textStatus, errorThrown ) {
1477
				erreurMsg += lthis.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1478
				}
1479
		},
1480
		error        : function( jqXHR, textStatus, errorThrown ) {
1481
			erreurMsg += lthis.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1482
			try {
1483
				reponse = jQuery.parseJSON( jqXHR.responseText );
1484
				if ( null !== reponse ) {
1485
					$.each( reponse, function( cle, valeur ) {
1486
						erreurMsg += valeur + '\n';
1487
					});
1488
				}
1489
			} catch( e ) {
1490
				erreurMsg += lthis.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
1491
			}
1492
		},
1493
		complete      : function( jqXHR, textStatus ) {
1494
			var debugMsg = lthis.extraireEnteteDebug( jqXHR );
1495
 
1496
			if ( '' !== erreurMsg ) {
1497
				if ( lthis.debug ) {
1498
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
1499
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1500
				}
1501
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1502
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagsProjet+
1503
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
1504
 
1505
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
1506
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
1507
					$( '#tpl-transmission-ko' ).clone()
1508
						.find( '.courriel-erreur' )
1509
						.attr( 'href', hrefCourriel )
1510
						.end()
1511
						.html()
1512
				);
1513
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
1514
				$( '#chargement' ).addClass( 'hidden' );
1515
				lthis.initialiserBarreProgression;
1516
			} else {
1517
				if ( lthis.debug ) {
1518
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1519
				}
1520
				if( 0 === lthis.obsNbre ) {
1521
					setTimeout( function() {
1522
						if ( lthis.isASL ) {
1523
							if ( 'arbres' === lthis.sujet ) {
1524
								if ( 'tb_streets' !== lthis.module ) {
1525
									$( '#bouton-saisir-lichens' ).removeClass( 'hidden' );
1526
								}
1527
								if ( 'tb_lichensgo' !== lthis.module ) {
1528
									$( '#bouton-saisir-plantes' ).removeClass( 'hidden' );
1529
								}
1530
							} else {
1531
								$( '#bouton-poursuivre' ).removeClass( 'hidden' );
1532
							}
1533
							$( '#bloc-controle-liste-obs,#bloc-gauche' ).addClass( 'hidden' );
1534
						}
1535
						$( '#chargement' ).addClass( 'hidden' );
1536
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
1537
						$( '#dialogue-obs-transaction-ok' ).removeClass( 'hidden' );
1538
					}, 1500 );
1539
				}
1540
			}
1541
		}
1542
	});
1543
};
1544
 
1545
WidgetsSaisiesCommun.prototype.mettreAJourProgression = function() {
1546
	this.nbObsTransmises++;
1547
 
1548
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
1549
 
1550
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
1551
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
1552
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.msgTraduction( 'observations-transmises' ) );
1553
	if( 0 === this.obsNbre ) {
1554
		$( '.progress' ).removeClass( 'active' );
1555
		$( '.progress' ).removeClass( 'progress-bar-striped' );
1556
	}
1557
};
1558
 
1559
WidgetsSaisiesCommun.prototype.initialiserBarreProgression = function() {
1560
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
1561
	$( '#barre-progression-upload' ).css( 'width', '0%' );
1562
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.msgTraduction( 'observations-transmises' ) );
1563
	$( '.progress' ).addClass( 'active' );
1564
	$( '.progress' ).addClass( 'progress-bar-striped' );
1565
};
1566
 
1567
// Form Validator *************************************************************/
1568
WidgetsSaisiesCommun.prototype.configurerFormValidator = function() {
1569
	const lthis = this;
1570
 
1571
	$.validator.addMethod(
1572
		'dateCel',
1573
		function ( value, element ) {
1574
			return ( lthis.valOk( value ) && ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) ) );
1575
		},
1576
		lthis.msgTraduction( 'date-incomplete' )
1577
	);
1578
	$.validator.addMethod(
1579
		'userEmailOk',
1580
		function ( value, element ) {
1581
			return ( lthis.valOk( value ) );
1582
		},
1583
		''
1584
	);
1585
	$.validator.addMethod(
1586
		'minMaxOk',
1587
		function ( value, element, param ) {
1588
			$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message;
1589
			return lthis.validerMinMax( element ).cond;
1590
		},
1591
		$.validator.messages.minMaxOk
1592
	);
1593
	$.validator.addMethod(
1594
		'listFields',
1595
		function ( value, element ) {
1596
			return ( lthis.valOk( value ) );
1597
		},
1598
		''
1599
	);
1600
	$.extend( $.validator.defaults, {
1601
		errorElement: 'span',
1602
		errorPlacement: function( error, element ) {
1603
			if ( lthis.isASL && 'arbres' === lthis.sujet && ( 'checkbox' === element.attr( 'type' ) || 'radio' === element.attr( 'type' ) ) ) {
1604
				error.appendTo( element.closest( '.list' ) );
1605
			} else {
1606
				element.after( error );
1607
			}
1608
		},
1609
		onfocusout: function( element ) {
1610
			if( lthis.valOk( element.id, false, 'taxon' ) || ( lthis.isASL && 'arbres' === lthis.sujet ) ) {
1611
				if ( $( element ).valid() ) {
1612
					$( element ).closest( '.control-group' ).removeClass( 'error' );
1613
				} else {
1614
					$( element ).closest( '.control-group' ).addClass( 'error' );
1615
				}
1616
			}
1617
		},
1618
		onkeyup : function( element ) {
1619
			if( lthis.valOk( element.id, false, 'taxon' ) || ( lthis.isASL && 'arbres' === lthis.sujet ) ) {
1620
				if ( $( element ).valid() ) {
1621
					$( element ).closest( '.control-group' ).removeClass( 'error' );
1622
				} else {
1623
					$( element ).closest( '.control-group' ).addClass( 'error' );
1624
				}
1625
			}
1626
		},
1627
		unhighlight: function( element ) {
1628
			if( lthis.valOk( element.id, false, 'taxon' ) || ( lthis.isASL && 'arbres' === lthis.sujet ) ) {
1629
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1630
			}
1631
		},
1632
		highlight: function( element ) {
1633
			$( element ).closest( '.control-group' ).addClass( 'error' );
1634
		}
1635
	});
1636
};
1637
 
1638
// Formatage date *************************************************************/
1639
WidgetsSaisiesCommun.prototype.fournirDate = function( dateObs ) {
1640
	if ( /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/.test( dateObs ) ) {
1641
		return dateObs;
1642
	} else if ( /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test( dateObs ) ) {
1643
		var dateArray = dateObs.split( '-' );
1644
		return dateArray[2] + '/' + dateArray[1] + '/' + dateArray[0]
1645
	} else {
1646
		console.dir( 'erreur date : ' + dateObs )
1647
	}
1648
};
1649
 
1650
// scroll vers le formulaire
1651
WidgetsSaisiesCommun.prototype.scrollFormTop = function( scrollSelecteur, focus = '' ) {
1652
	const lthis = this;
1653
 
1654
	$( 'html, body' ).stop().animate({
1655
		scrollTop: $( scrollSelecteur ).offset().top
1656
	}, 300, function() {
1657
		if ( lthis.valOk( focus ) ) {
1658
			$( focus ).focus();
1659
		} else {
1660
			return;
1661
		}
1662
	});
1663
};
1664
 
1665
// Controle des panneaux d'infos **********************************************/
1666
 
1667
WidgetsSaisiesCommun.prototype.afficherPanneau = function( selecteur ) {
1668
	$( selecteur )
1669
		.removeClass( 'hidden' )
1670
		.hide()
1671
		.show( 600 )
1672
		.delay( this.dureeMessage )
1673
		.hide( 600 );
1674
	this.scrollFormTop( selecteur );
1675
};
1676
 
1677
WidgetsSaisiesCommun.prototype.masquerPanneau = function( selecteur ) {
1678
	$( selecteur ).addClass( 'hidden' );
1679
};
1680
 
1681
WidgetsSaisiesCommun.prototype.fermerPanneauAlert = function() {
1682
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
1683
};
1684
 
1685
/**
1686
 * Si la langue est définie dans this.langue, et si des messages sont définis
1687
 * dans this.msgs, tente de trouver le message dont la clé est [cle] dans la
1688
 * langue en cours. S'il n'est pas trouvé, retourne la version française (par
1689
 * défaut); si celle-ci n'exite pas, retourne "N/A".
1690
 */
1691
WidgetsSaisiesCommun.prototype.msgTraduction = function( cle ) {
1692
	var msg = 'N/A';
1693
 
1694
	if ( this.msgs ) {
1695
		if ( this.langue in this.msgs && cle in this.msgs[this.langue] ) {
1696
			msg = this.msgs[this.langue][cle];
1697
		} else if ( cle in this.msgs['fr'] ) {
1698
			msg = this.msgs['fr'][cle];
1699
		}
1700
	}
1701
	return msg;
1702
};
1703
 
1704
/**
1705
* Stope l'évènement courant quand on clique sur un lien.
1706
* Utile pour Chrome, Safari...
1707
*/
1708
WidgetsSaisiesCommun.prototype.arreter = function( event ) {
1709
	if ( event.stopPropagation ) {
1710
		event.stopPropagation();
1711
	}
1712
	if ( event.preventDefault ) {
1713
		event.preventDefault();
1714
	}
1715
 
1716
	return false;
1717
};
1718
 
1719
/**
1720
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1721
 * @param jqXHR
1722
 * @returns {String}
1723
 */
1724
WidgetsSaisiesCommun.prototype.extraireEnteteDebug = function( jqXHR ) {
1725
	var msgDebug = '';
1726
 
1727
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
1728
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
1729
		if ( null !== debugInfos ) {
1730
			$.each( debugInfos, function( cle, valeur ) {
1731
				msgDebug += valeur + '\n';
1732
			});
1733
		}
1734
	}
1735
 
1736
	return msgDebug;
1737
};
1738
 
1739
 
1740
WidgetsSaisiesCommun.prototype.confirmerSortie = function() {
1741
	$( window ).off( 'beforeunload' ).on( 'beforeunload', function( event ) {
1742
		if ( !event ) {
1743
			event = window.event;
1744
		}
1745
		return false;
1746
	});
1747
};
1748
 
1749
WidgetsSaisiesCommun.prototype.valOk = function ( valeur, sensComparaison = true, comparer = undefined ) {
1750
	return utils.valOk( valeur, sensComparaison, comparer );
1751
};
1752
 
1753
WidgetsSaisiesCommun.prototype.activerModale = function ( label, content = '', buttons = [] ) {
1754
	return utils.activerModale( label, content, buttons );
1755
};
1756
 
1757
// Lib hors objet
1758
 
1759
/*
1760
 * jQuery UI Autocomplete HTML Extension
1761
 *
1762
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1763
 * Dual licensed under the MIT or GPL Version 2 licenses.
1764
 *
1765
 * http://github.com/scottgonzalez/jquery-ui-extensions
1766
 *
1767
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1768
 */
1769
( function( $ ) {
1770
	var proto      = $.ui.autocomplete.prototype,
1771
		initSource = proto._initSource;
1772
 
1773
	WidgetsSaisiesCommun.prototype.filter = function( array, term ) {
1774
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
1775
 
1776
		return $.grep( array, function( value ) {
1777
 
1778
			return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
1779
		});
1780
	}
1781
	$.extend( proto, {
1782
		_initSource: function() {
1783
			if ( this.options.html && $.isArray( this.options.source ) ) {
1784
				this.source = function( request, response ) {
1785
					response( filter( this.options.source, request.term ) );
1786
				};
1787
			} else {
1788
				initSource.call( this );
1789
			}
1790
		},
1791
		_renderItem: function( ul, item) {
1792
			if ( item.retenu ) {
1793
				item.label = '<strong>' + item.label + '</strong>';
1794
			}
1795
 
1796
			return $( '<li></li>' )
1797
				.data( 'item.autocomplete', item )
1798
				.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
1799
				.appendTo( ul );
1800
		}
1801
	});
1802
})( jQuery );