Subversion Repositories eFlore/Applications.cel

Rev

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