Subversion Repositories eFlore/Applications.cel

Rev

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