Subversion Repositories eFlore/Applications.cel

Rev

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