Subversion Repositories eFlore/Applications.cel

Rev

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