Subversion Repositories eFlore/Applications.cel

Rev

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

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