Subversion Repositories eFlore/Applications.cel

Rev

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

Rev Author Line No. Line
3312 idir 1
/**
2
 * Constructeur ReleveApa par défaut
3
 */
4
function ReleveApa() {
5
	this.obsNbre = 0;
6
	this.numArbre = 0;
7
	this.nbObsEnCours = 1;
8
	this.totalObsATransmettre = 0;
9
	this.nbObsTransmises = 0;
10
	this.debug = null;
11
	this.html5 = null;
12
	this.tagProjet = null;
13
	this.tagImg = null;
14
	this.tagObs = null;
15
	this.separationTagImg = null;
16
	this.separationTagObs = null;
17
	this.obsId = null;
18
	this.serviceSaisieUrl = null;
19
	this.serviceObsUrl = null;
20
	this.serviceObsListUrl = null;
21
	this.serviceObsImgs = null;
22
	this.serviceObsImgUrl = null;
23
	this.nomSciReferentiel = null;
24
	this.isTaxonListe = false;
25
	this.autocompletionElementsNbre = null;
26
	this.referentielImpose = null;
27
	this.serviceAutocompletionNomSciUrl = null;
28
	this.serviceAutocompletionNomSciUrlTpl = null;
29
	this.obsMaxNbre = null;
30
	this.dureeMessage = null;
31
	this.serviceNomCommuneUrl = null;
32
	this.serviceNomCommuneUrlAlt = null;
33
	this.chargementImageIconeUrl = null;
34
	this.pasDePhotoIconeUrl = null;
35
	this.infosUtilisateur = {};
36
	this.releveDatas = null;
37
	this.utils = new UtilsApa();
38
}
39
 
40
ReleveApa.prototype.init = function() {
41
	this.initForm();
42
	this.initEvts();
43
};
44
 
45
/**
46
 * Initialise le formulaire, les validateurs, les listes de complétion...
47
 */
48
ReleveApa.prototype.initForm = function() {
49
	const lthis = this;
50
	var releveDatas = [];
51
	this.infosUtilisateur.id     = $( '#id_utilisateur' ).val();
52
	this.infosUtilisateur.prenom = $( '#prenom' ).val();
53
	this.infosUtilisateur.nom    = $( '#nom' ).val();
54
 
55
	if( this.utils.valOk( this.infosUtilisateur.id ) ) {
56
		if ( this.utils.valOk( $( '#releve-data' ).val() ) ) {
57
			const datRuComun = $.parseJSON( $( '#dates-rues-communes' ).val() );
58
			releveDatas = $.parseJSON( $( '#releve-data' ).val() );
59
 
60
			if ( !this.utils.valOk( releveDatas[1] ) || -1 === datRuComun.indexOf( releveDatas[1]['date_rue_commune'] )  ) {
61
				this.releveDatas = releveDatas;
62
				if ( this.utils.valOk( this.releveDatas[0].utilisateur, true, this.infosUtilisateur.id ) ) {
63
					$( '#releve-date' ).val( this.releveDatas[0].date );
64
					this.rechargerFormulaire();
65
					this.saisirArbres();
66
					$( '#bouton-list-releves' )
67
						.removeClass( 'hidden' )
68
						.click( function() {
69
							$( '#table-releves' ).removeClass( 'hidden' );
70
							$( this ).addClass( 'hidden' );
71
					});
72
				}
73
			}
74
		}
75
		if ( this.utils.valOk( $( '#apa-obs' ).val() ) ) {
76
			const apaObs = $.parseJSON( $( '#apa-obs' ).val() );
77
 
78
			$( '.charger-releve,.saisir-plantes,.saisir-lichens' ).click( function() {
79
				var nomSquelette = $( this ).data( 'load' );
80
				releveDatas = apaObs[ $( this ).data( 'releve' ) ];
81
				$( '#releve-data' ).val( JSON.stringify( releveDatas ) );
82
				lthis.utils.chargerForm( nomSquelette, lthis );
83
				$( '#bouton-list-releves' ).removeClass( 'hidden' );
84
				$( '#table-releves' ).addClass( 'hidden' );
85
			});
86
		}
87
	}
88
	this.ajouterAutocompletionNoms();
89
	this.configurerFormValidator();
90
	this.definirReglesFormValidator();
91
};
92
 
93
/**
94
 * Initialise les écouteurs d'événements
95
 */
96
ReleveApa.prototype.initEvts = function() {
97
	const lthis = this;
98
 
99
	$( '#bouton-nouveau-releve' ).click( function() {
100
		$( '#releve-data' ).val( '' );
101
		if ( lthis.utils.valOk( lthis.infosUtilisateur.id ) ) {
102
			lthis.utils.chargerForm( 'arbres', lthis );
103
			$( 'html, body' ).stop().animate({
104
				scrollTop: $( '#zone-observation' ).offset().top
105
			}, 300 );
106
		}
107
	});
108
 
109
	// Empêcher que le module carto ne bind ses events partout
110
	$( '#tb-geolocation' ).on( 'submit blur click focus mousedown mouseleave mouseup touchend touchstart change', '*', function( event ) {
111
		event.preventDefault();
112
		return false;
113
	});
114
	$( '#tb-geolocation' ).on( 'location' , lthis.locationHandler.bind( lthis ) );
115
 
116
	// Sur téléchargement image
117
	$( '#fichier' ).on( 'change', function ( e ) {
118
		arreter( e );
119
 
120
		var options        = {
121
			success: lthis.afficherMiniature.bind( lthis ), // post-submit callback
122
			dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
123
			resetForm: true // reset the form after successful submit
124
		};
125
 
126
		$( '#miniature' ).append( '<img id="miniature-chargement" class="miniature" alt="chargement" src="' + this.chargementImageIconeUrl + '"/>' );
127
 
128
		var imgCheminTmp    = $( '#fichier' ).val(),
129
			formatImgOk     = lthis.verifierFormat( imgCheminTmp ),
130
			imgNonDupliquee = lthis.verifierDuplication( imgCheminTmp );
131
 
132
		if( formatImgOk && imgNonDupliquee ) {
133
			$( '#form-upload' ).ajaxSubmit( options );
134
		} else {
135
			$( '#form-upload' )[0].reset();
136
			if ( !formatImgOk ) {
137
				window.alert( lthis.utils.msgTraduction( 'format-non-supporte' ) + ' ' + $( '#fichier' ).attr( 'accept' ) );
138
			}
139
			if ( !imgNonDupliquee ) {
140
				window.alert( lthis.utils.msgTraduction( 'image-deja-chargee' ) );
141
			}
142
		}
143
		return false;
144
	});
145
	// Gérer une option "aucune" sur plusieurs checkboxes
146
	$( '#face-ombre input' ).on( 'click', function () {
147
		if ( 'aucune' === $( this ).val() ) {
148
			$( '#face-ombre input' ).not( '#aucune' ).prop( 'checked' , false );
149
		} else {
150
			$( '#aucune' ).prop( 'checked' , false );
151
		}
152
	});
153
	$( 'body' ).on( 'click', '.effacer-miniature', function() {
154
		$( this ).parent().remove();
155
	});
156
 
157
	$( '#soumettre-releve' ).on( 'click', function( even ) {
158
		event.preventDefault();
159
		lthis.saisirArbres();
160
	});
161
	$( '#ajouter-obs' ).on( 'click', this.ajouterObs.bind( this ) );
162
	$( '.obs-nbre' ).on( 'changement', this.surChangementNbreObs.bind( this ) );
163
	$( '#bloc-info-arbres' ).on( 'click', '.arbre-info', function ( event ) {
164
		event.preventDefault();
165
		$( this ).addClass( 'disabled' );
166
		$( '.arbre-info' ).not( $( this ) ).removeClass( 'disabled' );
167
		var numArbre = $( this ).data( 'arbre-info' );
168
		lthis.chargerInfosArbre( numArbre );
169
	});
170
	// après avoir visualisé les champs d'un arbre, retour à la saisie
171
	$( '#retour' ).on( 'click', function( event ) {
172
		event.preventDefault();
173
		var numArbre = lthis.numArbre + 1;
174
		$( 'html, body' ).stop().animate({
175
			scrollTop: $( '#zone-arbres' ).offset().top
176
		}, 300);
177
		// activation des champs et retour à la saisie
178
		lthis.modeArbresBasculerActivation( false, numArbre );
179
	});
180
	// défilement des miniatures dans le résumé obs
181
	$( 'body' ).on( 'click', '.defilement-miniatures-gauche', function( event ) {
182
		event.preventDefault();
183
		lthis.defilerMiniatures( $( this ) );
184
	});
185
	$( 'body' ).on( 'click', '.defilement-miniatures-droite', function( event ) {
186
		event.preventDefault();
187
		lthis.defilerMiniatures( $( this ) );
188
	});
189
	// mécanisme de suppression d'une obs
190
	$( '#liste-obs' ).on( 'click', '.supprimer-obs', function() {
191
		var that = this,
192
		suppObs = lthis.supprimerObs.bind( lthis );
193
		// bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
194
		suppObs( that );
195
	});
196
 
197
	$( '#transmettre-obs' ).on( 'click', this.transmettreObs.bind( this ) );
198
 
199
	// chargement plantes ou lichens
200
	$( '#charger-form' ).on( 'click', '#bouton-saisir-plantes,#bouton-saisir-lichens', function() {
201
		var nomSquelette = $( this ).data( 'load' );
202
		$( '#charger-form' ).data( 'load', nomSquelette );
203
		lthis.utils.chargerForm( nomSquelette, lthis );
204
		$( 'html, body' ).stop().animate({
205
			scrollTop: $( '#charger-form' ).offset().top
206
		}, 300 );
207
	});
208
 
209
	// Alertes et tooltips
210
	$( '.alert .close' ).on( 'click', this.fermerPanneauAlert );
211
	$( '#btn-aide' ).on( 'click', this.basculerAffichageAide );
212
	// $( '.has-tooltip' ).tooltip( 'enable' );
213
};
214
 
215
// Préchargement des infos-obs ************************************************/
216
 
217
/**
218
 * Callback dans le chargement du formulaire dans #charger-form
219
 */
220
ReleveApa.prototype.chargerSquelette = function( squelette, nomSquelette ) {
221
	switch( nomSquelette ) {
222
		case 'plantes' :
223
		case 'lichens' :
224
			this.utils.chargerFormPlantesOuLichens( squelette, nomSquelette );
225
			break;
226
		case 'arbres' :
227
		default :
228
			this.reinitialiserWidget( squelette );
229
		break;
230
	}
231
};
232
 
233
ReleveApa.prototype.reinitialiserWidget = function( squelette ) {
234
	$( '#charger-form' ).html( squelette );
235
	if ( this.utils.valOk( $( '#releve-data' ).val() ) ) {
236
		this.rechargerFormulaire();
237
	}
238
};
239
 
240
/**
241
 * Recharge le formulaire relevé (étape 1) à partir des infos
242
 * présentes dans l'input hidden '#releve-data'
243
 */
244
ReleveApa.prototype.rechargerFormulaire = function() {
245
	const lthis = this;
246
 
247
	this.releveDatas = $.parseJSON( $( '#releve-data' ).val() );
248
	$.each( this.releveDatas[0], function( cle , valeur ) {
249
		if ( 'zone-pietonne' === cle ||  'pres-lampadaires' === cle ) {
250
			$( 'input[name=' + cle + '][value=' + valeur + ']' , '#zone-observation' ).prop( 'checked', true );
251
		} else if ( lthis.utils.valOk( $( '#' + cle ) ) ) {
252
			$( '#' + cle ).val( valeur );
253
		}
254
	});
255
 
256
	$( 'html, body' ).stop().animate({
257
		scrollTop: $( '#charger-form' ).offset().top
258
	}, 300, function() {
259
		$( '#releve-date' ).focus();
260
	});
261
	if (
262
		this.utils.valOk( $( '#latitude' ).val() ) &&
263
		this.utils.valOk( $( '#longitude' ).val() ) &&
264
		this.utils.valOk( $( '#rue' ).val() ) &&
265
		this.utils.valOk( $( '#commune-nom' ).val() )
266
	) {
267
		$( '#geoloc' ).addClass( 'hidden' );
268
		$( '#geoloc-datas' ).removeClass( 'hidden' );
269
	}
270
};
271
 
272
/**
273
 * Recharge le formulaire étape arbres à partir des infos
274
 * présentes dans l'input hidden '#releve-data'
275
 */
276
ReleveApa.prototype.chargerArbres = function() {
277
	this.releveDatas = $.parseJSON( $( '#releve-data' ).val() );
278
	this.obsNbre     = this.releveDatas.length - 1;
279
	this.numArbre    = parseInt( this.releveDatas[ this.obsNbre ]['num-arbre'] ) || this.obsNbre;
280
	$( '.obs-nbre' ).text( this.obsNbre );
281
	$( '.obs-nbre' ).triggerHandler( 'changement' );
282
	$( '#arbre-nb' ).text( this.numArbre + 1 );
283
 
284
	var infosArbre = {
285
		releve : this.releveDatas[0],
286
		obsNum : 0,
287
		arbre  : {}
288
	};
289
 
290
	for( var i = 1; i <= this.obsNbre; i ++ ) {
291
		infosArbre.obsNum = i;
292
		infosArbre.arbre = this.releveDatas[i];
293
		this.lienArbreInfo( infosArbre.arbre['num-arbre'] );
294
		this.afficherObs( infosArbre );
295
		this.stockerObsData( infosArbre, true );
296
	}
297
};
298
 
299
ReleveApa.prototype.lienArbreInfo = function( numArbre ) {
300
	$( '#bloc-info-arbres' ).append(
301
		'<div'+
302
			' id="arbre-info-' + numArbre + '"'+
303
			' class="col-sm-8"'+
304
		'>'+
305
			'<a'+
306
				' id="arbre-info-lien-' + numArbre + '"'+
307
				' href=""'+
308
				' class="arbre-info btn btn-outline-info btn-block mb-3"'+
309
				' data-arbre-info="' + numArbre + '"'+
310
			'>'+
311
				'<i class="fas fa-info-circle"></i>'+
312
				' Arbre ' + numArbre +
313
			'</a>'+
314
		'</div>'
315
	);
316
};
317
 
318
 
319
 
320
// Autocompletion taxons ******************************************************/
321
/**
322
 * Initialise l'autocompletion taxons
323
 */
324
ReleveApa.prototype.ajouterAutocompletionNoms = function() {
325
	const lthis = this;
326
 
327
	$( '#taxon' ).autocomplete({
328
		source: function( requete, add ) {
329
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
330
			requete = '';
331
			if( lthis.utils.valOk( $( '#referentiel' ).val(), false, 'autre' ) ) {
332
				var url = lthis.getUrlAutocompletionNomsSci();
333
				$.getJSON( url, requete, function( data ) {
334
					var suggestions = lthis.traiterRetourNomsSci( data );
335
					add( suggestions );
336
				})
337
				.fail( function() {
338
					$( '#certitude' ).find( 'option' ).each( function() {
339
						if ( $( this ).hasClass( 'aDeterminer' ) ) {
340
							$( this ).attr( 'selected', true );
341
						} else {
342
							$( this ).attr( 'selected', false );
343
						}
344
					});
345
				});
346
			}
347
		},
348
		html: true
349
	});
350
	$( '#taxon' ).on( 'autocompleteselect', this.surAutocompletionTaxon );
351
};
352
 
353
ReleveApa.prototype.getUrlAutocompletionNomsSci = function() {
354
	var mots = $( '#taxon' ).val();
355
	var url = this.serviceAutocompletionNomSciUrlTpl.replace( '{referentiel}', this.nomSciReferentiel );
356
	url = url.replace( '{masque}', mots );
357
 
358
	return url;
359
};
360
 
361
/**
362
 * Objet taxons pour autocompletion en fonction de la recherche
363
 */
364
ReleveApa.prototype.traiterRetourNomsSci = function( data ) {
365
	var suggestions = [];
366
 
367
	if ( undefined != data.resultat ) {
368
		$.each( data.resultat, function( i, val ) {
369
			val.nn = i;
370
 
371
			var nom = {
372
				label : '',
373
				value : '',
374
				nt : 0,
375
				nomSel : '',
376
				nomSelComplet : '',
377
				numNomSel : 0,
378
				nomRet : '',
379
				numNomRet : 0,
380
				famille : '',
381
				retenu : false
382
			};
383
			if ( suggestions.length >= this.autocompletionElementsNbre ) {
384
				nom.label = '...';
385
				nom.value = $( '#taxon' ).val();
386
				suggestions.push( nom );
387
				return false;
388
			} else {
389
				nom.label = val.nom_sci_complet;
390
				nom.value = val.nom_sci_complet;
391
				nom.nt = val.num_taxonomique;
392
				nom.nomSel = val.nom_sci;
393
				nom.nomSelComplet = val.nom_sci_complet;
394
				nom.numNomSel = val.nn;
395
				nom.nomRet = val.nom_retenu_complet;
396
				nom.numNomRet = val['nom_retenu.id'];
397
				nom.famille = val.famille;
398
				// Tester dans ce sens, permet de considérer 'absent' comme 'false' => est-ce opportun ?
399
				// en tout cas c'est harmonisé avec le CeL
400
				nom.retenu = ( 'true' == val.retenu );
401
				suggestions.push( nom );
402
			}
403
		});
404
	}
405
	return suggestions;
406
};
407
 
408
/**
409
 * charge les données dans #taxon
410
 */
411
ReleveApa.prototype.surAutocompletionTaxon = function( event, ui ) {
412
	const utils = new UtilsApa();
413
 
414
	if ( utils.valOk( ui ) ) {
415
		$( '#taxon' ).val( ui.item.value );
416
		$( '#taxon' ).data( 'value', ui.item.value )
417
			.data( 'numNomSel', ui.item.numNomSel )
418
			.data( 'nomRet', ui.item.nomRet )
419
			.data( 'numNomRet', ui.item.numNomRet )
420
			.data( 'nt', ui.item.nt )
421
			.data( 'famille', ui.item.famille );
422
		if ( ui.item.retenu ) {
423
			$( '#taxon' ).addClass( 'ns-retenu' );
424
		} else {
425
			$( '#taxon' ).removeClass( 'ns-retenu' );
426
		}
427
		// Si l'espèce est mal déterminée la certitude est "à déterminer"
428
		if( !utils.valOk( $( '#taxon' ).data( 'numNomSel' ) ) ) {
429
			$( '#certitude' ).find( 'option' ).each( function() {
430
				if ( $( this ).hasClass( 'aDeterminer' ) ) {
431
					$( this ).attr( 'selected', true );
432
				} else {
433
					$( this ).attr( 'selected', false );
434
				}
435
			});
436
		}
437
	}
438
	$( '#taxon' ).change();
439
};
440
 
441
// Referentiel ****************************************************************/
442
// N'est pas utilisé en cas de taxon-liste
443
ReleveApa.prototype.surChangementReferentiel = function() {
444
	this.nomSciReferentiel = $( '#referentiel' ).val();
445
	//réinitialise taxon.val
446
	$( '#taxon' ).val( '' );
447
	$( '#taxon' ).data( 'numNomSel', '' );
448
	// this.initialiserAutocompleteCommune();
449
	// this.initialiserGoogleMap( false );
450
};
451
 
452
// Fichier Images *************************************************************/
453
/**
454
 * Affiche temporairement (formulaire)
455
 * la miniature d'une image ajoutée à l'obs
456
 */
457
ReleveApa.prototype.afficherMiniature = function( reponse ) {
458
	if ( this.debug ) {
459
		var debogage = $( 'debogage', reponse ).text();
460
	}
461
 
462
	var message = $( 'message', reponse ).text();
463
 
464
	if ( this.utils.valOk( message ) ) {
465
		$( '#miniature-msg' ).append( message );
466
	} else {
467
		$( '#miniatures' ).append( this.creerWidgetMiniature( reponse ) );
468
	}
469
	$( '#ajouter-obs' ).removeAttr( 'disabled' );
470
};
471
 
472
/**
473
 * Crée la miniature temporaire (formulaire) + bouton pour l'effacer
474
 */
475
ReleveApa.prototype.creerWidgetMiniature = function( reponse ) {
476
	var miniatureUrl = $( 'miniature-url', reponse ).text();
477
	var imgNom = $( 'image-nom', reponse ).text();
478
	var html =
479
		'<div class="miniature mb-3 mr-3">'+
480
			'<img class="miniature-img" class="miniature img-rounded" alt="' + imgNom + '" src="' + miniatureUrl + '"/>'+
481
			'<a class="effacer-miniature"><i class="fas fa-times"></i></a>'+
482
		'</div>';
483
 
484
	return html;
485
};
486
 
487
/**
488
 * Retourne true si l'extension de l'image 'nom' est .jpg ou .jpeg
489
 */
490
ReleveApa.prototype.verifierFormat = function( cheminTmp ) {
491
	var parts     = cheminTmp.split( '.' ),
492
		extension = parts[ parts.length - 1 ];
493
 
494
	return ( 'jpeg' === extension.toLowerCase() || 'jpg' === extension.toLowerCase() );
495
};
496
 
497
/**
498
 * Check les miniatures déjà téléchargées
499
 * renvoie false si le même nom est rencontré 2 fois
500
 * renvoie true sinon
501
 */
502
ReleveApa.prototype.verifierDuplication = function( cheminTmp ) {
503
	const lthis = this;
504
	var parts        = cheminTmp.split( '\\' ),
505
		nomImage     = parts[ parts.length - 1 ],
506
		thisSrcParts = [],
507
		thisNomImage = '',
508
		nonDupliquee = true;
509
 
510
	$( 'img.miniature-img,img.miniature' ).each( function() {
511
		// vérification avec alt de l'image
512
		if ( lthis.utils.valOk ( $( this ).attr ( 'alt' ), true, nomImage ) ) {
513
			nonDupliquee = false;
514
			return false;// Pas besoin de poursuivre la boucle
515
		} else { // sinon vérifie aussi avec l'adresse (src) de l'image
516
			thisSrcParts = $( this ).attr( 'src' ).split( '/' );
517
			thisNomImage = thisSrcParts[ thisSrcParts.length - 1 ].replace( '_min', '' );
518
			if ( lthis.utils.valOk ( thisNomImage, true, nomImage ) ) {
519
				nonDupliquee = false;
520
				return false;
521
			}
522
		}
523
	});
524
	return nonDupliquee;
525
};
526
 
527
/**
528
 * Efface une miniature (formulaire)
529
 */
530
ReleveApa.prototype.supprimerMiniature = function( miniature ) {
531
	miniature.parents( '.miniature' ).remove();
532
};
533
 
534
// Ajouter Obs ****************************************************************/
535
 
536
/**
537
 * Etape formulaire avec transfert carto
538
 */
539
ReleveApa.prototype.saisirArbres = function() {
540
	const lthis = this;
541
 
542
	if ( this.validerReleve() ) {
543
		$( '#soumettre-releve' )
544
			.addClass( 'disabled' )
545
			.attr( 'aria-disabled', true )
546
			.off( event );
547
		$( '#form-observation' ).find( 'input, textarea' ).prop( 'disabled', true );
548
		$( '#zone-arbres,#geoloc-datas' ).removeClass( 'hidden' );
549
		if ( !this.utils.valOk( $( '#releve-data' ).val() ) ) {
550
			this.releveDatas = this.utils.formaterReleveData({
551
				obs  : {
552
					ce_utilisateur     : this.infosUtilisateur.id,
553
					date_observation   : $( '#releve-date' ).val(),
554
					zone_geo           : $( '#commune-nom' ).val(),
555
					ce_zone_geo        : $( '#commune-insee' ).val(),
556
					pays               : $( '#pays' ).val(),
557
					latitude           : $( '#latitude' ).val(),
558
					longitude          : $( '#longitude' ).val(),
559
					altitude           : $( '#altitude' ).val(),
560
					commentaire        : $( '#commentaires' ).val().trim()
561
				},
562
				obsE : {
563
					rue                : $( '#rue' ).val(),
564
					'zone-pietonne'    : $( '#zone-pietonne input:checked' ).val(),
565
					'pres-lampadaires' : $( '#pres-lampadaires input:checked' ).val()
566
				}
567
			});
568
			$( '#releve-data' ).val( JSON.stringify( this.releveDatas ) );
569
			this.numArbre = this.releveDatas.length - 1;
570
		} else {
571
			this.releveDatas = $.parseJSON( $( '#releve-data' ).val() );
572
			this.releveDatas[0].date                = $( '#releve-date' ).val();
573
			this.releveDatas[0]['zone-pietonne']    = $( '#zone-pietonne input:checked' ).val();
574
			this.releveDatas[0]['pres-lampadaires'] = $( '#pres-lampadaires input:checked' ).val();
575
			this.releveDatas[0].commentaires        = $( '#commentaires' ).val().trim();
576
			for ( var i = 1 ; i < this.releveDatas.length; i++ ) {
577
				this.releveDatas[i]['date_rue_commune'] = (
578
					this.releveDatas[0].date +
579
					this.releveDatas[0].rue +
580
					this.releveDatas[0]['commune-nom']
581
				);
582
			}
583
			$( '#releve-data' ).val( JSON.stringify( this.releveDatas ) );
584
			//charger les images
585
			this.chargerImgEnregistrees();
586
			this.numArbre = $.parseJSON( $( '#releve-data' ).val() ).length - 1;
587
		}
588
 
589
		// transfert carto
590
		const ERROR_TXT_GEOLOC = $( '#geoloc-error' )[0].textContent;
591
		$( '#tb-geolocation,#geoloc-error' ).remove();
592
		$( '#geoloc-arbres' ).append(
593
			'<span id="geoloc-error" class="error hidden">' + ERROR_TXT_GEOLOC + '</span>'+
594
			'<tb-geolocation-element'+
595
				' id="tb-geolocation-arbres"'+
596
				' layer="osm"'+
597
				' zoom_init="20"'+
598
				' lat_init="' + $( '#latitude' ).val() + '"'+
599
				' lng_init="' + $( '#longitude' ).val() + '"'+
600
				' marker="true"'+
601
				' polyline="false"'+
602
				' polygon="false"'+
603
				' show_lat_lng_elevation_inputs="true"'+
604
				' osm_class_filter=""'+
605
				' elevation_provider="mapquest"'+
606
				' map_quest_api_key="mG6oU5clZHRHrOSnAV0QboFI7ahnGg34"'+
607
			'>'+
608
			'</tb-geolocation-element>'
609
		);
610
 
611
		const geolocElements = ['geoloc','geolocalisation','rue','latitude','longitude','commune-nom','commune-insee','altitude','pays'];
612
 
613
		$.each( geolocElements, function( i, elementGeo ) {
614
			$( '#' + elementGeo ).removeClass( elementGeo );
615
			$( '#' + elementGeo + '-arbres' ).addClass( elementGeo );
616
		});
617
		// Empêcher que le module carto ne bind ses events partout
618
		$( '#tb-geolocation-arbres' ).on( 'submit blur click focus mousedown mouseleave mouseup touchend touchstart change', '*', function( event ) {
619
			event.preventDefault();
620
			return false;
621
		});
622
		$( '#tb-geolocation-arbres' ).on( 'location', this.locationHandler.bind(this) );
623
	}
624
};
625
 
626
ReleveApa.prototype.chargerImgEnregistrees = function() {
627
	const releveL = this.releveDatas.length;
628
	var idArbre = 0,
629
		last  = false;
630
 
631
	for ( var i = 1; i < releveL; i++ ) {
632
		idArbre = this.releveDatas[i]['id_observation'];
633
 
634
		var urlImgObs = this.serviceObsImgs + idArbre,
635
			imgDatas  = {
636
				'indice'      : i,
637
				'idArbre'     : idArbre,
638
				'numArbre'    : this.releveDatas[i]['num-arbre'],
639
				'nomRet'      : this.releveDatas[i].taxon.nomRet.replace( /\s/, '_' ),
640
				'releveDatas' : this.releveDatas
641
			};
642
 
643
		if ( ( releveL - 1) === i ) {
644
			last = true;
645
		}
646
		this.chargerImgArbre( urlImgObs, imgDatas, last );
647
	}
648
};
649
 
650
ReleveApa.prototype.chargerImgArbre = function( urlImgObs, imgDatas, last ) {
651
	const lthis   = this;
652
 
653
	$.ajax({
654
		url: urlImgObs,
655
		type: 'GET',
656
		success: function( idsImg, textStatus, jqXHR ) {
657
			if ( lthis.utils.valOk( idsImg ) ) {
658
				var urlImg   = '',
659
					images   = [];
660
 
661
				idsImg = idsImg[parseInt( imgDatas.idArbre )];
662
				$.each( idsImg, function( i, idImg ) {
663
					urlImg = lthis.serviceObsImgUrl.replace( '{id}', idImg );
664
					images[i] = {
665
						nom : imgDatas.nomRet + '_arbre'+ imgDatas.numArbre +'_image' + ( i + 1 ),
666
						src : urlImg,
667
						b64 :[],
668
						id  : idImg
669
					};
670
				});
671
				imgDatas.releveDatas[imgDatas.indice]['miniature-img'] = images;
672
				$( '#releve-data' ).val( JSON.stringify( imgDatas.releveDatas ) );
673
				// dejsonifier releve data
674
				// mettre l'array image dans miniature(s?)-img
675
			} else {
676
				console.log( lthis.utils.msgTraduction( 'erreur-image' ) + ' : ' + lthis.utils.msgTraduction( 'arbre' ) + ' ' + imgDatas.idArbre );
677
			}
678
		},
679
		error: function( jqXHR, textStatus, errorThrown ) {
680
			console.log( lthis.utils.msgTraduction( 'erreur-image' ) );
681
		}
682
	})
683
	.always( function() {
684
		if (last) {
685
			lthis.chargerArbres();
686
		}
687
	});
688
};
689
 
690
/**
691
 * Fonction handler de l'évenement location du module tb-geoloc
692
 */
693
ReleveApa.prototype.locationHandler = function( location ) {
694
	var locDatas     = location.originalEvent.detail;
695
 
696
	if ( this.utils.valOk( locDatas ) ) {
697
		var rue          = ( this.utils.valOk( locDatas.osmRoad ) ) ? locDatas.osmRoad : '';
698
		var latitude     = ( this.utils.valOk( locDatas.geometry.coordinates[1] ) ) ? locDatas.geometry.coordinates[1] : '';
699
		var longitude    = ( this.utils.valOk( locDatas.geometry.coordinates[0] ) ) ? locDatas.geometry.coordinates[0] : '';
700
		var nomCommune   = '';
701
		var	communeInsee = '';
702
 
703
		console.log( locDatas );
704
 
705
		if ( this.utils.valOk( locDatas.inseeData ) ) {
706
			nomCommune = locDatas.inseeData.nom;
707
			communeInsee = ( this.utils.valOk( locDatas.inseeData.code ) ) ? locDatas.inseeData.code : '';
708
		} else if ( this.utils.valOk( locDatas.locality ) ) {
709
			nomCommune = locDatas.locality;
710
		} else if ( this.utils.valOk( locDatas.locality ) ) {
711
			nomCommune = locDatas.osmCounty;
712
		}
713
 
714
		var altitude     = ( this.utils.valOk( locDatas.elevation ) ) ? locDatas.elevation : '';
715
		var pays         = ( this.utils.valOk( locDatas.osmCountryCode ) ) ? locDatas.osmCountryCode.toUpperCase() : 'FR';
716
 
717
		$( '.rue' ).val( rue );
718
		$( '.latitude' ).val( latitude );
719
		$( '.longitude' ).val( longitude );
720
		$( '.commune-nom' ).val( nomCommune );
721
		$( '.commune-insee' ).val( communeInsee );
722
		$( '.altitude' ).val( altitude );
723
		$( '.pays' ).val( pays );
724
 
725
		//validation champs géoloc
726
		if ( this.utils.valOk( $( '.rue' ).val() ) && this.utils.valOk( $( '.commune-nom' ).val() ) ) {
727
			if ( 'rue-arbres' === $( '.rue' ).attr( 'id' ) ) {
728
				if( $( '.rue' ).val() === $( '#rue' ).val() && $( '.commune-nom' ).val() === $( '#commune-nom' ).val() ) {
729
					$( '#rue-error' ).addClass( 'hidden' );
730
					$( '.geoloc' ).closest( '.control-group' ).removeClass( 'error' );
731
				} else {
732
					$( '#rue-error' ).removeClass( 'hidden' );
733
					$( '.geoloc' ).closest( '.control-group' ).addClass( 'error' );
734
				}
735
			} else {
736
				if( !this.utils.valOk( $( '#geoloc #error-drc' ) ) ) {
737
					$( '#geoloc' ).closest( '.control-group' ).removeClass( 'error' );
738
				}
739
			}
740
			$( '#geoloc-error' ).addClass( 'hidden' );
741
		} else {
742
			$( '.geoloc' ).closest( '.control-group' ).addClass( 'error' );
743
			$( '#geoloc-error' ).removeClass( 'hidden' );
744
			$( '#releve-date' ).removeClass( 'erreur' ).closest( '.control-group' ).removeClass( 'error' ).find( '#error-drc' ).remove();
745
			$( '#geoloc #error-drc' ).remove();
746
		}
747
	} else {
748
		console.log( 'Error location' );
749
	}
750
}
751
 
752
/**
753
 * Ajoute une observation à la liste des obs à transmettre
754
 * (résumé obs)
755
 */
756
ReleveApa.prototype.ajouterObs = function() {
757
	// Fermeture automatique des dialogue de transmission de données
758
	// @WARNING TEST
759
	$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
760
	$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
761
	$( 'html, body' ).stop().animate({
762
		scrollTop: $( '#zone-arbres' ).offset().top
763
	}, 300);
764
 
765
	if ( this.validerArbres() ) {
766
		this.masquerPanneau( '#dialogue-form-invalide' );
767
		this.obsNbre  += 1;
768
		this.numArbre += 1;
769
		$( '.obs-nbre' ).text( this.obsNbre );
770
		$( '.obs-nbre' ).triggerHandler( 'changement' );
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
		//formatage des données
775
		var obsData   = this.formaterFormObsData(),
776
			arbreData = obsData.arbre;
777
 
778
		// Résumé obs et stockage en data de "#list-obs" pour envoi
779
		this.afficherObs( obsData );
780
		this.stockerObsData( obsData );
781
		// Ajout de donnée utiles puis stockage dans input hidden "releve-data"
782
		arbreData['date_rue_commune']  = obsData.releve.date + obsData.releve.rue + obsData.releve['commune-nom'];
783
		arbreData['id_observation']    = 0;
784
		this.releveDatas               = $.parseJSON( $( '#releve-data' ).val() );
785
		this.releveDatas[this.obsNbre] = arbreData;
786
		$( '#releve-data' ).val( JSON.stringify( this.releveDatas ) );
787
 
788
		this.supprimerMiniatures();
789
		$( '#taxon' ).val( '' );
790
		$( '#taxon' ).data( 'numNomSel', '' )
791
			.data( 'nomRet','' )
792
			.data( 'numNomRet', '' )
793
			.data( 'nt', '' )
794
			.data( 'famille', '' );
795
		if( this.isTaxonListe ) {
796
			$( '#taxon-liste' ).find( 'option' ).each( function() {
797
				if ( $( this ).hasClass( 'choisir' ) ) {
798
					$( this ).attr( 'selected', true );
799
				} else {
800
					$( this ).attr( 'selected', false );
801
				}
802
			});
803
			$( '#taxon-input-groupe' ).addClass( 'hidden' );
804
			$('#taxon-autre').val('');
805
		}
806
		$( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre );
807
		$( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' ' + this.utils.msgTraduction( 'observations-transmises' ) );
808
	} else {
809
		this.afficherPanneau( '#dialogue-form-invalide' );
810
	}
811
};
812
 
813
/**
814
 * Formatage des données du formulaire pour stockage et envoi
815
 */
816
ReleveApa.prototype.formaterFormObsData = function() {
817
	var miniatureImg  = [],
818
		faceOmbre     = [],
819
		imgB64        = [],
820
		imgNom        = [],
821
		numNomSel     = $( '#taxon' ).data( 'numNomSel' ),
822
		referentiel   = ( !this.utils.valOk( numNomSel ) ) ? 'autre' : 'bdtfx';
823
 
824
	$( '.miniature-img' ).each( function() {
825
		if ( $( this ).hasClass( 'b64' ) ) {
826
			imgB64 = $( this ).attr( 'src' );
827
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
828
			imgB64 = $( this ).data( 'b64' );
829
		}
830
		miniatureImg.push({
831
			'nom' : $( this ).attr( 'alt' ),
832
			'src' : $( this ).attr( 'src' ),
833
			'b64' : imgB64
834
		});
835
	});
836
	$( '#face-ombre input' ).each( function() {
837
		if( $( this ).is( ':checked' ) ) {
838
			faceOmbre.push( $( this ).val() );
839
		}
840
	});
841
	var obsData = {
842
		obsNum : this.obsNbre,
843
		arbre  : {
844
			'num-arbre'            : this.numArbre,
845
			'taxon'                : {
846
				'numNomSel' : numNomSel,
847
				'value'     : $( '#taxon' ).val(),
848
				'nomRet'    : $( '#taxon' ).data( 'nomRet' ),
849
				'numNomRet' : $( '#taxon' ).data( 'numNomRet' ),
850
				'nt'        : $( '#taxon' ).data( 'nt' ),
851
				'famille'   : $( '#taxon' ).data( 'famille' )
852
			},
853
			'referentiel'           : referentiel,
854
			'certitude'             : $( '#certitude' ).val(),
855
			'latitude-arbres'       : $( '#latitude-arbres' ).val(),
856
			'longitude-arbres'      : $( '#longitude-arbres' ).val(),
857
			'altitude-arbres'       : $( '#altitude-arbres' ).val(),
858
			'circonference'         : $( '#circonference' ).val(),
859
			'surface-pied'          : $( '#surface-pied' ).val(),
860
			'equipement-pied-arbre' : $( '#equipement-pied-arbre' ).val(),
861
			'tassement'             : $( '#tassement' ).val(),
862
			'dejections'            : $( '#dejections input:checked' ).val(),
863
			'face-ombre'            : faceOmbre,
864
			'com-arbres'            : $( '#com-arbres' ).val(),
865
			'miniature-img'         : miniatureImg,
866
		},
867
		releve : {
868
			'date'                  : this.utils.fournirDate( $( '#releve-date' ).val() ),
869
			'rue'                   : $( '#rue' ).val(),
870
			'commune-nom'           : $( '#commune-nom' ).val(),
871
			'commentaires'          : $( '#commentaires' ).val(),
872
			'pays'                  : $( '#pays' ).val(),
873
			'commune-insee'         : $( '#commune-insee' ).val(),
874
			'latitude'              : $( '#latitude' ).val(),
875
			'longitude'             : $( '#longitude' ).val(),
876
			'altitude'              : $( '#altitude' ).val(),
877
			'zone-pietonne'         : $( '#zone-pietonne input:checked' ).val(),
878
			'pres-lampadaires'      : $( '#pres-lampadaires input:checked' ).val()
879
		}
880
	};
881
	return obsData;
882
};
883
 
884
/**
885
 * Résumé obs
886
 */
887
ReleveApa.prototype.afficherObs = function( datasObs ) {
888
	var obsNum            = datasObs.obsNum,
889
		numArbre          = datasObs.arbre['num-arbre'],
890
		dateObs           = this.utils.fournirDate( datasObs.releve.date ),
891
		numNomSel         = datasObs.arbre.taxon.numNomSel,
892
		taxon             = datasObs.arbre.taxon.value,
893
		certitude         = datasObs.arbre.certitude,
894
		rue               = datasObs.releve.rue,
895
		commune           = datasObs.releve['commune-nom'],
896
		latitudeLongitude = '[' + datasObs.arbre['latitude-arbres'] + ' / ' + datasObs.arbre['longitude-arbres'] + ']',
897
		miniatures        = this.ajouterImgMiniatureAuTransfert( datasObs.arbre['miniature-img'] ),
898
		commentaires      = '';
899
 
900
	if ( this.utils.valOk( datasObs.arbre['com-arbres'] ) ) {
901
		commentaires =
902
			this.utils.msgTraduction( 'commentaires' ) +
903
			' : <span>'+
904
				datasObs.arbre['com-arbres'] +
905
			'</span> ';
906
	}
907
 
908
	var responsivDiff1 = '',
909
		responsivDiff2 = '',
910
		responsivDiff3 = '',
911
		responsivDiff4 = '',
912
		responsivDiff5 = '',
913
		responsivDiff6 = '';
914
 
915
	if ( window.matchMedia( '(min-width: 576px)' ).matches ) {
916
		/* La largeur minimum de l'affichage est 600 px inclus */
917
		responsivDiff1 = ' droite';
918
		responsivDiff2 = '<div></div>';
919
		responsivDiff3 = '<div class="row">';
920
		responsivDiff4 = ' col-md-4 col-sm-5';
921
		responsivDiff5 = ' class="col-md-7 col-sm-6"';
922
		responsivDiff6 = '</div>';
923
	}
924
	$( '#liste-obs' ).prepend(
925
		'<div id="obs' + obsNum + '" class="obs obs' + obsNum + ' mb-2">'+
926
			'<div '+
927
				'class="obs-action" '+
928
				'title="' + this.utils.msgTraduction( 'supprimer-observation-liste' ) + '"'+
929
			'>'+
930
				'<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ obsNum + '" title="' + this.utils.msgTraduction( 'obs-numero' ) + obsNum + '">'+
931
				'<i class="far fa-trash-alt"></i>'+
932
				'</button>'+
933
				responsivDiff2 +
934
			'</div> '+
935
			responsivDiff3 +
936
				'<div class="thumbnail' + responsivDiff4 + '">'+
937
					miniatures+
938
				'</div>'+
939
				'<div' + responsivDiff5 + '>'+
940
					'<ul class="unstyled">'+
941
						'<li>'+
942
							'<span id="obs-arbre-' + numArbre + '" class="badge num-obs-arbre" data-arbre="' + numArbre + '">Arbre ' + numArbre + '</span>' +
943
							' <span class="nom-sci">' + taxon + '</span> '+
944
							' [certitude : ' + certitude + ']'+
945
							' '  + this.utils.msgTraduction( 'lieu-obs' ) +
946
							' ' + rue +
947
							', ' + commune +
948
							latitudeLongitude +
949
							' ' + this.utils.msgTraduction( 'obs-le' ) + ' ' +
950
							'<span class="date">' + this.utils.fournirDate( dateObs ) + '</span>'+
951
						'</li>'+
952
						'<li>'+
953
							commentaires +
954
						'</li>'+
955
					'</ul>'+
956
				'</div>'+
957
			responsivDiff6+
958
		'</div>'
959
	);
960
	$( '#zone-liste-obs' ).removeClass( 'hidden' );
961
};
962
 
963
/**
964
 * Ajoute une boîte de miniatures avec défilement des images,
965
 * pour une obs de la liste des obs à transmettre
966
 */
967
ReleveApa.prototype.ajouterImgMiniatureAuTransfert = function( chargerImages ) {
968
	const lthis = this;
969
	var html         =
970
			'<div class="defilement-miniatures">'+
971
				'<figure class="centre">'+
972
					'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
973
				'</figure>'+
974
			'</div>',
975
		miniatures   = '',
976
		centre       = '',
977
		defilVisible = '',
978
		length       = 0;
979
 
980
	if ( this.utils.valOk( chargerImages ) || this.utils.valOk( $( '#miniatures img' ) ) ) {
981
		if ( this.utils.valOk( chargerImages ) ) {
982
			$.each(  chargerImages, function( i, value ) {
983
				var imgVisible = ( 0 < i ) ? 'miniature-cachee' : 'miniature-selectionnee';
984
 
985
				var css        = ( lthis.utils.valOk( value['b64'] ) ) ? 'miniature b64' : 'miniature',
986
					src        = value.src,
987
					alt        = value.nom,
988
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
989
 
990
				miniatures += miniature;
991
			});
992
			length = chargerImages.length;
993
 
994
		} else {
995
			var premiere     = true;
996
			$( '#miniatures img' ).each( function() {
997
				var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
998
				premiere = false;
999
 
1000
				var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
1001
					src        = $( this ).attr( 'src' ),
1002
					alt        = $( this ).attr( 'alt' ),
1003
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1004
 
1005
				miniatures += miniature;
1006
			});
1007
			length = $( '#miniatures img' ).length;
1008
		}
1009
		if ( 1 === length ) {
1010
			centre       = 'centre';
1011
			defilVisible = ' defilement-miniatures-cache';
1012
		}
1013
		html             =
1014
			'<div class="defilement-miniatures">'+
1015
				'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
1016
				'<figure class="' + centre + '">'+
1017
					miniatures+
1018
				'</figure>'+
1019
				'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
1020
			'</div>';
1021
	}
1022
 
1023
	return html;
1024
};
1025
 
1026
/**
1027
 * Construit le html à afficher pour le numNom
1028
 */
1029
ReleveApa.prototype.ajouterNumNomSel = function( numNomSel ) {
1030
	var nn = '<span class="nn">[nn' + numNomSel + ']</span>';
1031
 
1032
	if ( !this.utils.valOk( numNomSel ) ) {
1033
		nn = '<span class="alert-error">[' + this.utils.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
1034
	}
1035
 
1036
	return nn;
1037
};
1038
 
1039
/**
1040
 * Stocke des données d'obs à envoyer à la bdd
1041
 */
1042
ReleveApa.prototype.stockerObsData = function( obsDatas ) {
1043
	const lthis = this;
1044
	var obsNum      = obsDatas.obsNum,
1045
		numNomSel   = obsDatas.arbre.taxon.numNomSel,
1046
		referentiel = ( !this.utils.valOk( numNomSel ) ) ? 'autre' : 'bdtfx',
1047
		date        = lthis.utils.fournirDate( obsDatas.releve.date ),
1048
		// si releve dupliqué on ne stocke pas l'image :
1049
		stockerImg  = this.utils.valOk( obsDatas.arbre['miniature-img'] ),
1050
		imgNom      = [],
1051
		imgB64      = [];
1052
 
1053
		if( stockerImg ) {
1054
			$.each( obsDatas.arbre['miniature-img'], function( i, obj ) {
1055
				if( obj.hasOwnProperty( 'id' ) ) {
1056
					stockerImg = false;
1057
				}
1058
				return stockerImg;
1059
			});
1060
		}
1061
		if ( stockerImg ) {
1062
			$.each( obsDatas.arbre['miniature-img'] , function(i, value) {
1063
				if( lthis.utils.valOk( value.nom ) ) {
1064
					imgNom.push( value.nom );
1065
				}
1066
				if( lthis.utils.valOk( value['b64'] ) ) {
1067
					imgB64.push( value['b64'] );
1068
				}
1069
			});
1070
		} else {
1071
			imgNom = lthis.getNomsImgsOriginales();
1072
			imgB64 = lthis.getB64ImgsOriginales();
1073
		}
1074
 
1075
	// Stockage en data des données d'obs à transmettre
1076
	$( '#liste-obs' ).data( 'obsId' + obsNum, {
1077
		'num_nom_sel'        : numNomSel,
1078
		'nom_sel'            : obsDatas.arbre.taxon.value,
1079
		'nom_ret'            : obsDatas.arbre.taxon.nomRet,
1080
		'num_nom_ret'        : obsDatas.arbre.taxon.numNomRet,
1081
		'num_taxon'          : obsDatas.arbre.taxon.nt,
1082
		'famille'            : obsDatas.arbre.taxon.famille,
1083
		'referentiel'        : referentiel,
1084
		'certitude'          : obsDatas.arbre.certitude,
1085
		'date'               : date,
1086
		'notes'              : obsDatas.releve.commentaires.trim(),
1087
		'pays'               : obsDatas.releve.pays,
1088
		'commune_nom'        : obsDatas.releve['commune-nom'],
1089
		'commune_code_insee' : obsDatas.releve['commune-insee'],
1090
		'latitude'           : obsDatas.releve.latitude,
1091
		'longitude'          : obsDatas.releve.longitude,
1092
		'altitude'           : obsDatas.releve.altitude,
1093
		//Ajout des champs images
1094
		'image_nom'          : imgNom,
1095
		'image_b64'          : imgB64,
1096
		// Ajout des champs étendus de l'obs
1097
		'obs_etendue'        : lthis.getObsChpArbres( obsDatas )
1098
	});
1099
};
1100
 
1101
ReleveApa.prototype.getNomsImgsOriginales = function() {
1102
	var noms = new Array();
1103
 
1104
	$( '.miniature-img' ).each( function() {
1105
		noms.push( $( this ).attr( 'alt' ) );
1106
	});
1107
 
1108
	return noms;
1109
};
1110
 
1111
ReleveApa.prototype.getB64ImgsOriginales = function() {
1112
	var b64 = new Array();
1113
 
1114
	$( '.miniature-img' ).each( function() {
1115
		if ( $( this ).hasClass( 'b64' ) ) {
1116
			b64.push( $( this ).attr( 'src' ) );
1117
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
1118
			b64.push( $( this ).data( 'b64' ) );
1119
		}
1120
	});
1121
 
1122
	return b64;
1123
};
1124
 
1125
/**
1126
 * Retourne un Array contenant les valeurs des champs
1127
 * dont les données seront transmises dans la table cel-obs-etendues
1128
 */
1129
ReleveApa.prototype.getObsChpArbres = function( datasArbres ) {
1130
	const lthis = this;
1131
 
1132
	var retour = [],
1133
		champs = [
1134
			'rue',
1135
			'zone-pietonne',
1136
			'pres-lampadaires',
1137
			'latitude-arbres',
1138
			'longitude-arbres',
1139
			'altitude-arbres',
1140
			'circonference',
1141
			'surface-pied',
1142
			'equipement-pied-arbre',
1143
			'tassement',
1144
			'dejections',
1145
			'com-arbres'
1146
		];
1147
 
1148
	var cleValeur       = '',
1149
		faceOmbre       = '',
1150
		faceOmbreLength = datasArbres.arbre['face-ombre'].length;
1151
 
1152
	$.each( champs, function( i ,value ) {
1153
		cleValeur = ( 3 > i ) ? 'releve' : 'arbre';
1154
		// console.log(cleValeur);
1155
		// console.log(value);
1156
		// console.log(datasArbres[cleValeur][value]);
1157
 
1158
 
1159
		if ( lthis.utils.valOk( datasArbres[cleValeur][value] ) ) {
1160
			retour.push({ cle : value, valeur : datasArbres[cleValeur][value] });
1161
		}
1162
	});
1163
	if ( 'string' === typeof datasArbres.arbre['face-ombre'] ) {
1164
		faceOmbre = datasArbres.arbre['face-ombre'];
1165
	} else {
1166
		$.each( datasArbres.arbre['face-ombre'], function( i ,value ) {
1167
			faceOmbre += value
1168
			if ( faceOmbreLength > ( i + 1 ) ) {
1169
				faceOmbre += ';';
1170
			}
1171
		});
1172
	}
1173
	retour.push(
1174
		{ cle : 'face-ombre', valeur : faceOmbre },
1175
		{ cle : 'num_arbre' , valeur : datasArbres.obsNum }
1176
	);
1177
 
1178
	var stockerImg  = this.utils.valOk( datasArbres.arbre['miniature-img'] );
1179
 
1180
	if( stockerImg ) {
1181
		$.each( datasArbres.arbre['miniature-img'], function( i, paramsImg ) {
1182
			if( !paramsImg.hasOwnProperty( 'id' ) ) {
1183
				stockerImg = false;
1184
			}
1185
			return stockerImg;
1186
		});
1187
	}
1188
	if( stockerImg ) {
1189
		retour.push({ cle : 'miniature-img' , valeur : JSON.stringify( datasArbres.arbre['miniature-img'] ) });
1190
	}
1191
 
1192
	return retour;
1193
};
1194
 
1195
/**
1196
 * Efface toutes les miniatures (formulaire)
1197
 */
1198
ReleveApa.prototype.supprimerMiniatures = function() {
1199
	$( '#miniatures' ).empty();
1200
	$( '#miniature-msg' ).empty();
1201
};
1202
 
1203
ReleveApa.prototype.surChangementNbreObs = function() {
1204
	if ( 0 === this.obsNbre ) {
1205
		$( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
1206
		// $( '#zone-liste-obs' ).addClass( 'hidden' );
1207
		$( '#bloc-form-arbres' ).removeClass( 'hidden' );
1208
	} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1209
		$( '#ajouter-obs,#transmettre-obs' ).removeAttr( 'disabled' );
1210
		$( '#bloc-form-arbres' ).removeClass( 'hidden' );
1211
	} else if ( this.obsNbre >= this.obsMaxNbre ) {
1212
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1213
		$( '#bloc-form-arbres' ).addClass( 'hidden' );
1214
		this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
1215
	}
1216
};
1217
 
1218
ReleveApa.prototype.chargerInfosArbre = function( numArbre ) {
1219
	const lthis = this;
1220
	var desactiverForm = ( parseInt( numArbre ) !== ( this.numArbre + 1 ) );
1221
 
1222
	if ( desactiverForm ) {
1223
		var releveDatas = $.parseJSON( $( '#releve-data' ).val() ),
1224
			arbreDatas  = releveDatas[numArbre],
1225
			taxon       = {item:{}},
1226
			imgHtml     = '';
1227
 
1228
		$( '#arbre-nb').text( numArbre );
1229
 
1230
		taxon.item = arbreDatas.taxon;
1231
		this.surAutocompletionTaxon( {}, taxon );
1232
 
1233
		const SELECTS = ['certitude','equipement-pied-arbre','tassement'];
1234
 
1235
		$.each( SELECTS, function( i, value ) {
1236
			if( !lthis.utils.valOk( arbreDatas[value] ) ) {
1237
				arbreDatas[value] = '';
1238
			}
1239
			if ( $( this ).hasClass( 'other' ) && lthis.utils.valOk( $( this ).val() ) ) {
1240
				$( this ).text( $( this ).val() );
1241
			}
1242
			$( '#' + value + ' option' ).each( function() {
1243
				if ( arbreDatas[value] === $( this ).val() ) {
1244
					$( this ).prop( 'selected', true );
1245
				} else {
1246
					$( this ).prop( 'selected', false );
1247
				}
1248
			});
1249
		});
1250
		$( '#rue-arbres' ).val(releveDatas[0]['rue']);
1251
		$( '#latitude-arbres' ).val(arbreDatas['latitude-arbres']);
1252
		$( '#longitude-arbres' ).val(arbreDatas['longitude-arbres']);
1253
		$( '#commune-nom-arbres' ).val(releveDatas[0]['commune-nom']);
1254
		$( '#commune-insee-arbres' ).val(releveDatas[0]['commune-insee']);
1255
		$( '#altitude-arbres' ).val(arbreDatas['altitude-arbres']);
1256
		$( '#pays-arbres' ).val(releveDatas[0]['pays']);
1257
		// image
1258
		this.supprimerMiniatures();
1259
		$.each( arbreDatas['miniature-img'], function( i, value ) {
1260
			imgHtml +=
1261
			'<div class="miniature mb-3 mr-3">'+
1262
				'<img class="miniature-img" class="miniature img-rounded" alt="' + value.nom + '" src="' + value.src + '"/>'+
1263
			'</div>';
1264
		});
1265
		$( '#miniatures' ).append( imgHtml );
1266
		$( '#circonference' ).val( arbreDatas.circonference );
1267
		$( '#surface-pied' ).val( arbreDatas['surface-pied'] );
1268
		$( '#com-arbres' ).val( arbreDatas['com-arbres'] );
1269
		if ( undefined != arbreDatas.dejections ) {
1270
			$( '#dejections-oui' ).prop( 'checked', arbreDatas.dejections );
1271
			$( '#dejections-non' ).prop( 'checked', !arbreDatas.dejections );
1272
		}
1273
		$( '#face-ombre input' ).each( function() {
1274
			if ( -1 < arbreDatas['face-ombre'].indexOf( $( this ).val() ) ) {
1275
				$( this ).prop( 'checked', true );
1276
			} else {
1277
				$( this ).prop( 'checked', false );
1278
			}
1279
		});
1280
	}
1281
 
1282
	this.modeArbresBasculerActivation( desactiverForm, numArbre );
1283
};
1284
 
1285
ReleveApa.prototype.modeArbresBasculerActivation = function( desactiver, numArbre = 0 ) {
1286
	$(
1287
		'#taxon,'+
1288
		'#certitude,'+
1289
		'#equipement-pied-arbre,'+
1290
		'#tassement,'+
1291
		'#latitude-arbres,'+
1292
		'#longitude-arbres,'+
1293
		'#rue-arbres,'+
1294
		'#fichier,'+
1295
		'#circonference,'+
1296
		'#surface-pied,'+
1297
		'#com-arbres,'+
1298
		'#ajouter-obs'
1299
	).prop( 'disabled', desactiver );
1300
	$( '#dejections,#face-ombre' ).find( 'input' ).prop( 'disabled', desactiver );
1301
 
1302
	if ( desactiver ) {
1303
		$( '#geoloc-arbres,#bouton-fichier,#miniature-arbres-info' ).addClass( 'hidden' );
1304
		$( '#geoloc-datas-arbres,#retour' ).removeClass( 'hidden' );
1305
	} else {
1306
		// quand on change ou qu'on revient à la normale :
1307
		$( '#geoloc-arbres,#bouton-fichier,#miniature-arbres-info' ).removeClass( 'hidden' );
1308
		$( '#geoloc-datas-arbres,#retour' ).addClass( 'hidden' );
1309
		// retour aux valeurs par defaut
1310
		$( '#equipement-pied-arbre .other' ).text( 'Autre' ).val( 'other' );
1311
		// $( '#equipement-pied-arbre .other' ).val( 'other' );
1312
		$(
1313
			'#certitude option,'+
1314
			'#equipement-pied-arbre option,'+
1315
			'#tassement option'
1316
		).each( function() {
1317
			if ( $( this ).hasClass( 'choisir' ) ) {
1318
				$( this ).prop( 'selected', true );
1319
			} else {
1320
				$( this ).prop( 'selected', false );
1321
			}
1322
		});
1323
		$( '#taxon' ).data( 'numNomSel', '' )
1324
			.data( 'nomRet','' )
1325
			.data( 'numNomRet', '' )
1326
			.data( 'nt', '' )
1327
			.data( 'famille', '' );
1328
		this.supprimerMiniatures();
1329
		$( '#dejections,#face-ombre' ).find( 'input' ).prop( 'checked', false );
1330
		$(
1331
			'#taxon,'+
1332
			'#circonference,'+
1333
			'#surface-pied,'+
1334
			'#com-arbres,'+
1335
			'#rue-arbres,'+
1336
			'#latitude-arbres,'+
1337
			'#longitude-arbres,'+
1338
			'#certitude,'+
1339
			'#equipement-pied-arbre,'+
1340
			'#tassement'
1341
		).val( '' );
1342
		$( '#arbre-nb' ).text( numArbre );
1343
		$( '#arbre-info-lien-' + numArbre ).addClass( 'disabled' );
1344
		$( '.arbre-info' ).not( '#arbre-info-lien-' + numArbre ).removeClass( 'disabled' );
1345
	}
1346
};
1347
 
1348
ReleveApa.prototype.defilerMiniatures = function( element ) {
1349
	var miniatureSelectionne  = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
1350
 
1351
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
1352
	miniatureSelectionne.addClass( 'miniature-cachee' );
1353
 
1354
	var miniatureAffichee     = miniatureSelectionne;
1355
 
1356
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
1357
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
1358
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
1359
		} else {
1360
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
1361
		}
1362
	} else {
1363
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
1364
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
1365
		} else {
1366
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
1367
		}
1368
	}
1369
	miniatureAffichee.addClass( 'miniature-selectionnee' );
1370
	miniatureAffichee.removeClass( 'miniature-cachee' );
1371
};
1372
 
1373
ReleveApa.prototype.supprimerObs = function( selector ) {
1374
	var obsId = $( selector ).val();
1375
 
1376
	// Problème avec IE 6 et 7
1377
	if ( 'Supprimer' === obsId ) {
1378
		obsId = $( selector ).attr( 'title' );
1379
	}
1380
	this.supprimerObsParId( obsId );
1381
};
1382
 
1383
/**
1384
 * Supprime l'obs et les data de l'obs
1385
 * et remonte les suivantes d'un cran
1386
 */
1387
ReleveApa.prototype.supprimerObsParId = function( obsId, transmission = false ) {
1388
	if ( !transmission ) {
1389
		this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1390
		this.releveData.splice( obsId , 1 );
1391
		$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1392
	}
1393
	$( '#arbre-info-' + ( this.numArbre ) ).remove();
1394
	$( '#arbre-nb' ).text( this.numArbre );
1395
 
1396
	this.obsNbre  -= 1;
1397
	this.numArbre -= 1;
1398
	$( '.obs-nbre' ).text( this.obsNbre );
1399
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1400
	$( '.obs' + obsId ).remove();
1401
 
1402
	obsId = parseInt(obsId);
1403
	var listObsData = $( '#liste-obs' ).data(),
1404
		exId        = 0,
1405
		indexObs    = '',
1406
		exIndexObs  = '',
1407
		arbreExId   = 0;
1408
 
1409
	for ( var id = obsId; id <= ( this.obsNbre + 1 ); id++ ) {
1410
		exId       = parseInt(id) + 1;
1411
		indexObs   = 'obsId' + id;
1412
		exIndexObs = 'obsId' + exId;
1413
		arbreExId  = parseInt( $( '#obs-arbre-' + exId ).data( 'arbre' ) );
1414
		arbreId    = arbreExId - 1;
1415
		$( '#liste-obs' ).removeData( indexObs );
1416
		if ( this.utils.valOk( listObsData[ exIndexObs ] ) ) {
1417
			$( '#liste-obs' ).data( indexObs, listObsData[ exIndexObs ] );
1418
		}
1419
		$( '#obs' + exId )
1420
			.attr( 'id', 'obs' + id )
1421
			.removeClass( 'obs' + exId )
1422
			.addClass( 'obs' + id )
1423
			.find( '.supprimer-obs' )
1424
				.attr( 'title', 'Observation n°' + id )
1425
				.val( id );
1426
		$( '#obs-arbre-' + arbreExId )
1427
			.attr( 'id', 'obs-arbre-' + arbreId )
1428
			.attr( 'data-arbre', arbreId )
1429
			.data( 'arbre', arbreId )
1430
			.text( 'Arbre ' + arbreId );
1431
 
1432
		if ( parseInt( id ) !== this.obsNbre ) {
1433
			id = parseInt(id);
1434
		}
1435
	}
1436
};
1437
 
1438
/*
1439
 * Actualise l'id_observation ( id de l'obs en bdd )
1440
 * à partir des données renvoyées par le service après transfert
1441
 */
1442
ReleveApa.prototype.actualiserReleveDataIdObs = function( obsId, id_observation ) {
1443
	this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1444
	this.releveData[obsId ]['id_observation'] = id_observation;
1445
	$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1446
};
1447
 
1448
ReleveApa.prototype.transmettreObs = function() {
1449
	const lthis = this;
1450
	var observations = $( '#liste-obs' ).data();
1451
 
1452
	if ( this.debug ) {
1453
		console.log( observations );
1454
	}
1455
	if ( !this.utils.valOk( typeof observations, true, 'object' ) ) {
1456
		this.afficherPanneau( '#dialogue-zero-obs' );
1457
	} else {
1458
		$( window ).on( 'beforeunload', function( event ) {
1459
			return lthis.utils.msgTraduction( 'rechargement-page' );
1460
		});
1461
		this.nbObsEnCours         = 1;
1462
		this.nbObsTransmises      = 0;
1463
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
1464
			return i;
1465
		}).length;
1466
		this.depilerObsPourEnvoi();
1467
	}
1468
 
1469
	return false;
1470
};
1471
 
1472
ReleveApa.prototype.depilerObsPourEnvoi = function() {
1473
	var observations = $( '#liste-obs' ).data();
1474
 
1475
	// la boucle est factice car on utilise un tableau
1476
	// dont on a besoin de n'extraire que le premier élément
1477
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1478
	// TODO: utiliser var.keys quand ça sera plus répandu
1479
	// ou bien utiliser un vrai tableau et pas un objet
1480
	for ( var obsNum in observations ) {
1481
		var obsATransmettre = {
1482
			'projet'  : this.tagProjet,
1483
			'tag-obs' : this.tagObs,
1484
			'tag-img' : this.tagImg
1485
		};
1486
		var utilisateur = {
1487
			id_utilisateur : this.infosUtilisateur.id,
1488
			prenom         : this.infosUtilisateur.prenom,
1489
			nom            : this.infosUtilisateur.nom,
1490
			courriel       : $( '#courriel' ).val()
1491
		};
1492
 
1493
		obsATransmettre['utilisateur'] = utilisateur;
1494
		obsATransmettre[obsNum]        = observations[obsNum];
1495
 
1496
		var idObsNumerique = obsNum.replace( 'obsId', '' );
1497
 
1498
		if( '' !== idObsNumerique ) {
1499
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
1500
		}
1501
		break;
1502
	}
1503
};
1504
 
1505
ReleveApa.prototype.envoyerObsAuCel = function( idObs, observation ) {
1506
	const lthis     = this;
1507
	var erreurMsg = '';
1508
 
1509
	$.ajax({
1510
		url        : lthis.serviceSaisieUrl,
1511
		type       : 'POST',
1512
		data       : observation,
1513
		dataType   : 'json',
1514
		beforeSend : function() {
1515
			$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
1516
			$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1517
			$( '.alert-txt' ).empty();
1518
			$( '.alert-txt .msg-erreur' ).remove();
1519
			$( '.alert-txt .msg-debug' ).remove();
1520
			$( '#chargement' ).removeClass( 'hidden' );
1521
		},
1522
		success    : function( transfertDatas, textStatus, jqXHR ) {
1523
			// actualisation de id_observation dans '#releve-data'
1524
			lthis.actualiserReleveDataIdObs( idObs, transfertDatas.id );
1525
			// mise à jour du nombre d'obs à transmettre
1526
			// et suppression de l'obs
1527
			lthis.supprimerObsParId( idObs, true );
1528
			lthis.nbObsEnCours++;
1529
			// mise à jour du statut
1530
			lthis.mettreAJourProgression();
1531
			if( 0 < lthis.obsNbre ) {
1532
				// dépilement de la suivante
1533
				lthis.depilerObsPourEnvoi();
1534
			}
1535
		},
1536
		statusCode  : {
1537
			500 : function( jqXHR, textStatus, errorThrown ) {
1538
				erreurMsg += lthis.utils.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1539
				}
1540
		},
1541
		error        : function( jqXHR, textStatus, errorThrown ) {
1542
			erreurMsg += lthis.utils.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1543
			try {
1544
				reponse = jQuery.parseJSON( jqXHR.responseText );
1545
				if ( null !== reponse ) {
1546
					$.each( reponse, function( cle, valeur ) {
1547
						erreurMsg += valeur + '\n';
1548
					});
1549
				}
1550
			} catch( e ) {
1551
				erreurMsg += lthis.utils.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
1552
			}
1553
		},
1554
		complete      : function( jqXHR, textStatus ) {
1555
			var debugMsg = extraireEnteteDebug( jqXHR );
1556
 
1557
			if ( '' !== erreurMsg ) {
1558
				if ( lthis.debug ) {
1559
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
1560
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1561
				}
1562
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1563
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagProjet+
1564
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
1565
 
1566
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
1567
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
1568
				// window.location.hash = 'obs' + idObs;
1569
 
1570
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
1571
					$( '#tpl-transmission-ko' ).clone()
1572
						.find( '.courriel-erreur' )
1573
						.attr( 'href', hrefCourriel )
1574
						.end()
1575
						.html()
1576
				);
1577
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
1578
				$( '#chargement' ).addClass( 'hidden' );
1579
				lthis.initialiserBarreProgression;
1580
			} else {
1581
				if ( lthis.debug ) {
1582
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1583
				}
1584
				if( 0 === lthis.obsNbre ) {
1585
					setTimeout( function() {
1586
						$( '#chargement,#bloc-arbres-gauche,#bloc-controle-liste-obs' ).addClass( 'hidden' );
1587
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
1588
						$( '#dialogue-obs-transaction-ok,#bouton-saisir-plantes,#bouton-saisir-lichens' ).removeClass( 'hidden' );
1589
					}, 1500 );
1590
				}
1591
			}
1592
		}
1593
	});
1594
};
1595
 
1596
ReleveApa.prototype.mettreAJourProgression = function() {
1597
	this.nbObsTransmises++;
1598
 
1599
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
1600
 
1601
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
1602
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
1603
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.utils.msgTraduction( 'observations-transmises' ) );
1604
	if( 0 === this.obsNbre ) {
1605
		$( '.progress' ).removeClass( 'active' );
1606
		$( '.progress' ).removeClass( 'progress-bar-striped' );
1607
	}
1608
};
1609
 
1610
ReleveApa.prototype.initialiserBarreProgression = function() {
1611
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
1612
	$( '#barre-progression-upload' ).css( 'width', '0%' );
1613
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.utils.msgTraduction( 'observations-transmises' ) );
1614
	$( '.progress' ).addClass( 'active' );
1615
	$( '.progress' ).addClass( 'progress-bar-striped' );
1616
};
1617
 
1618
// Form Validator *************************************************************/
1619
ReleveApa.prototype.configurerFormValidator = function() {
1620
	const lthis = this;
1621
 
1622
	$.validator.addMethod(
1623
		'dateCel',
1624
		function ( value, element ) {
1625
			return ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) );
1626
		},
1627
		lthis.utils.msgTraduction( 'date-incomplete' )
1628
	);
1629
 
1630
	$.validator.addMethod(
1631
		'userEmailOk',
1632
		function ( value, element ) {
1633
			return ( lthis.utils.valOk( value ) );
1634
		},
1635
		''
1636
	);
1637
	$.validator.addMethod(
1638
		'minMaxOk',
1639
		function ( value, element, param ) {
1640
			$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message;
1641
			return lthis.validerMinMax( element ).cond;
1642
		},
1643
		$.validator.messages.minMaxOk
1644
	);
1645
	$.validator.addMethod(
1646
		'listFields',
1647
		function ( value, element ) {
1648
			return ( lthis.utils.valOk( value ) );
1649
		},
1650
		''
1651
	);
1652
 
1653
	$.extend( $.validator.defaults, {
1654
		errorElement: 'span',
1655
		errorPlacement: function( error, element ) {
1656
			if ( 'checkbox' === element.attr( 'type' ) || 'radio' === element.attr( 'type' ) ) {
1657
				error.appendTo( element.closest( '.list' ) );
1658
			} else {
1659
				element.after( error );
1660
			}
1661
		},
1662
		onfocusout: function( element ) {
1663
			if ( $( element ).valid() ) {
1664
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1665
			} else {
1666
				$( element ).closest( '.control-group' ).addClass( 'error' );
1667
			}
1668
		},
1669
		onkeyup : function( element ) {
1670
			if ( $( element ).valid() ) {
1671
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1672
			} else {
1673
				$( element ).closest( '.control-group' ).addClass( 'error' );
1674
			}
1675
		},
1676
		unhighlight: function( element ) {
1677
			$( element ).closest( '.control-group' ).removeClass( 'error' );
1678
		},
1679
		highlight: function( element ) {
1680
			$( element ).closest( '.control-group' ).addClass( 'error' );
1681
		}
1682
	});
1683
};
1684
 
1685
ReleveApa.prototype.validerMinMax = function( element ) {
1686
	var mMCond      = new Boolean(),
1687
		minCond     = parseFloat( element.value ) >= parseFloat( element.min ),
1688
		maxCond     = parseFloat( element.value ) <= parseFloat( element.max ),
1689
		messageMnMx = 'La valeur entrée doit être',
1690
		returnMnMx  = { cond : true , message : '' };
1691
 
1692
	if (
1693
			( this.utils.valOk( element.type, true, 'number' ) || this.utils.valOk( element.type, true, 'range' ) ) &&
1694
			( this.utils.valOk( element.min ) || this.utils.valOk( element.max ) )
1695
		) {
1696
 
1697
		if ( element.min && element.max ) {
1698
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
1699
			mnMxCond     = ( minCond && maxCond );
1700
		} else if ( element.min ) {
1701
			messageMnMx += ' supérieure à ' + element.min;
1702
			mnMxCond     = minCond;
1703
		} else {
1704
			messageMnMx += ' inférieure à ' + element.max;
1705
			mnMxCond     = maxCond;
1706
		}
1707
		returnMnMx.cond    = mnMxCond;
1708
		returnMnMx.message = messageMnMx;
1709
	}
1710
 
1711
	return returnMnMx;
1712
};
1713
 
1714
/**
1715
 * Valider date/rue/commune par rapport aux relevés précédents
1716
 */
1717
ReleveApa.prototype.validerDateRueCommune = function( valeurDate, valeurRue, valeurCmn ) {
1718
	var valide = true;
1719
 
1720
	if (
1721
		this.utils.valOk( $( '#dates-rues-communes' ).val() ) &&
1722
		this.utils.valOk( valeurDate ) &&
1723
		this.utils.valOk( valeurRue ) &&
1724
		this.utils.valOk( valeurCmn )
1725
	) {
1726
		var valsEltDRC = $.parseJSON( $( '#dates-rues-communes' ).val() ),
1727
			valeurDRC = valeurDate + valeurRue + valeurCmn;
1728
		valide = ( -1 === valsEltDRC.indexOf( valeurDRC ) );
1729
 
1730
	}
1731
	return valide;
1732
};
1733
 
1734
/**
1735
 * FormValidator pour les champs date/rue/Commune
1736
 */
1737
ReleveApa.prototype.dateRueCommuneFormValidator = function() {
1738
	var dateValid    = ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( $( '#releve-date' ).val() ) ),
1739
		geolocValid  = ( this.utils.valOk( $( '#commune-nom' ).val() ) && this.utils.valOk( $( '#rue' ).val() ) );
1740
	const errorDateRue =
1741
			'<span id="error-drc" class="error">'+
1742
				this.utils.msgTraduction( 'date-rue' )+
1743
			'</span> ';
1744
 
1745
	if( this.validerDateRueCommune( $( '#releve-date' ).val(), $( '#rue' ).val(), $( '#commune-nom' ).val()  ) ) {
1746
		$( '#releve-date' )
1747
			.removeClass( 'erreur' )
1748
			.closest( '.control-group' )
1749
				.removeClass( 'error' )
1750
				.find( '#error-drc' )
1751
					.remove();
1752
		if ( geolocValid ) {
1753
			$( '#geoloc' )
1754
			.closest( '.control-group' )
1755
				.removeClass( 'error' );
1756
		}
1757
		$( '#geoloc #error-drc' ).remove();
1758
	} else {
1759
		$( '#releve-date' )
1760
			.addClass( 'erreur' )
1761
			.closest( '.control-group' )
1762
				.addClass( 'error' );
1763
		if ( !this.utils.valOk( $( '#releve-date' ).closest( '.control-group' ).find( '#error-drc' ) ) ) {
1764
			$( '#releve-date' ).after( errorDateRue );
1765
		}
1766
		$( '#geoloc' ).closest( '.control-group' ).addClass( 'error' );
1767
		if ( !this.utils.valOk( $( '#geoloc' ).find( '#error-drc' ) ) ) {
1768
			$( '#geoloc' ).prepend( errorDateRue );
1769
		}
1770
	}
1771
	if ( dateValid ) {
1772
		$( '#releve-date' ).closest( '.control-group span.error' ).not( '#error-drc' ).remove();
1773
	}
1774
};
1775
 
1776
ReleveApa.prototype.definirReglesFormValidator = function() {
1777
	const lthis = this;
1778
 
1779
	$( '#form-observation' ).validate({
1780
		rules : {
1781
			'zone-pietonne' : {
1782
				required : true,
1783
				minlength : 1
1784
			},
1785
			latitude : {
1786
				required : true,
1787
				minlength : 1,
1788
				range : [-90, 90]
1789
			},
1790
			longitude : {
1791
				required : true,
1792
				minlength : 1,
1793
				range : [-180, 180]
1794
			}
1795
		}
1796
	});
1797
	$( 'input[type=date]' ).not( '#releve-date' ).on( 'input', function() {
1798
		$( this ).valid();
1799
	});
1800
	// validation date/rue/commune au démarage
1801
	this.dateRueCommuneFormValidator();
1802
	// validation date/rue/commune sur event
1803
	$( '#releve-date,#rue,#commune-nom' ).on( 'change input focusout', this.dateRueCommuneFormValidator.bind( this ) );
1804
	$( '#form-arbre' ).validate({
1805
		rules : {
1806
			taxon : {
1807
				required : true,
1808
				minlength : 1
1809
			},
1810
			certitude : {
1811
				required : true,
1812
				minlength : 1
1813
			},
1814
			'latitude-arbres' : {
1815
				required : true,
1816
				minlength : 1,
1817
				range : [-90, 90]
1818
			},
1819
			'longitude-arbres' : {
1820
				required : true,
1821
				minlength : 1,
1822
				range : [-180, 180]
1823
			},
1824
			'rue-arbres' : {
1825
				required : true,
1826
				minlength : 1
1827
			}
1828
		}
1829
	});
1830
	$( '#form-arbre-fs' ).validate({
1831
		onkeyup : false,
1832
		onclick : false,
1833
		rules : {
1834
			circonference : {
1835
				required : true,
1836
				minlength : 1//,
1837
				//'minMaxOk' : true
1838
			},
1839
			'surface-pied' : {
1840
				required : true,
1841
				minlength : 1,
1842
				'minMaxOk' : true
1843
			},
1844
			'equipement-pied-arbre' : {
1845
				required : true,
1846
				minlength : 1
1847
			},
1848
			'face-ombre' : {
1849
				required : true,
1850
				minlength : 1
1851
			}
1852
		}
1853
	});
1854
	$( '#equipement-pied-arbre' ).change( function() {
1855
		if ( lthis.utils.valOk( $( this ).val(), false, 'other' ) ) {
1856
			$( this )
1857
				.closest( '.control-group' )
1858
					.removeClass( 'error' )
1859
					.find( 'span.error' )
1860
						.addClass( 'hidden' );
1861
		}
1862
	});
1863
	$( '#form-observateur' ).validate({
1864
		rules : {
1865
			courriel : {
1866
				required : true,
1867
				minlength : 1,
1868
				email : true,
1869
				'userEmailOk' : true
1870
			},
1871
			mdp : {
1872
				required : true,
1873
				minlength : 1
1874
			}
1875
		}
1876
	});
1877
	$( '#face-ombre input' ).click( function() {
1878
		var oneIsChecked = false;
1879
		$( '#face-ombre input' ).each( function() {
1880
			if ( $( this ).is( ':checked' ) ) {
1881
				oneIsChecked = true;
1882
				return false;
1883
			}
1884
		});
1885
		if ( oneIsChecked ) {
1886
			$( '#face-ombre.control-group' )
1887
				.removeClass( 'error' )
1888
				.find( 'span.error' )
1889
					.addClass( 'hidden' );
1890
		} else {
1891
			$( '#face-ombre.control-group' )
1892
				.addClass( 'error' )
1893
				.find( 'span.error' )
1894
					.removeClass( 'hidden' );
1895
		}
1896
	});
1897
	$( '#connexion,#inscription,#oublie' ).click( function() {
1898
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
1899
	});
1900
};
1901
 
1902
/**
1903
 * Valide le formulaire Relevé (= étape 1) au click sur un bouton "enregistrer"
1904
 */
1905
ReleveApa.prototype.validerReleve = function() {
1906
	const observateur = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() )
1907
	const obs         = $( '#form-observation' ).valid();
1908
	const geoloc      = (
1909
		this.utils.valOk( $( '#latitude' ).val() ) &&
1910
		this.utils.valOk( $( '#longitude' ).val() ) &&
1911
		this.utils.valOk( $( '#rue' ).val() ) &&
1912
		this.utils.valOk( $( '#commune-nom' ).val() )
1913
	) ;
1914
	var dateRue = true;
1915
	if ( this.utils.valOk( $( '#dates-rues-communes' ).val() ) ) {
1916
		dateRue = (
1917
			this.utils.valOk( $( '#releve-date' ).val() ) &&
1918
			this.utils.valOk( $( '#rue' ).val() ) &&
1919
			this.validerDateRueCommune( $( '#releve-date' ).val(), $( '#rue' ).val(), $( '#commune-nom' ).val() )
1920
		);
1921
	}
1922
	const validerReleve = ( observateur && obs && geoloc && dateRue );
1923
 
1924
	if ( !obs ) {
1925
		$( 'html, body' ).stop().animate({
1926
			scrollTop: $( '#zone-observation' ).offset().top
1927
		}, 300 );
1928
	}
1929
	// panneau observateur
1930
	if ( observateur ) {
1931
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
1932
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
1933
	} else {
1934
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
1935
		$( '#tb-observateur .control-group' ).addClass( 'error' );
1936
	}
1937
	if ( dateRue && geoloc ) {
1938
		this.masquerPanneau( '#dialogue-date-rue-ko' );
1939
		$( '#geoloc-datas' ).closest( '.control-group' ).removeClass( 'error' );
1940
	} else {
1941
		if (
1942
			this.utils.valOk( $( '#releve-date' ).val() ) &&
1943
			this.utils.valOk( $( '#rue' ).val() ) &&
1944
			this.utils.valOk( $( '#dates-rues-communes' ).val() )
1945
		) {
1946
			this.afficherPanneau( '#dialogue-date-rue-ko' );
1947
		}
1948
		$( '#geoloc-datas' ).closest( '.control-group' ).addClass( 'error' );
1949
	}
1950
	if (
1951
		!this.utils.valOk( $( '#releve-date' ).val() ) ||
1952
		!this.utils.valOk( $( '#rue' ).val() ) ||
1953
		!this.utils.valOk( $( '#dates-rues-communes' ).val() )
1954
	) {
1955
		this.masquerPanneau( '#dialogue-date-rue-ko' );
1956
	}
1957
	if ( geoloc ) {
1958
		this.masquerPanneau( '#dialogue-geoloc-ko' );
1959
		if ( dateRue ) {
1960
			$( '.geoloc' ).closest( '.control-group' ).removeClass( 'error' );
1961
		}
1962
	} else {
1963
		this.afficherPanneau( '#dialogue-geoloc-ko' );
1964
		$( '.geoloc' ).closest( '.control-group' ).addClass( 'error' );
1965
	}
1966
 
1967
	return validerReleve;
1968
};
1969
 
1970
/**
1971
 * Valide le formulaire Arbres (= étape 2) au click sur un bouton "suivant"
1972
 */
1973
ReleveApa.prototype.validerArbres = function( etapeReleve = false ) {
1974
	const observateur = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() )
1975
	const geoloc      = (
1976
		this.utils.valOk( $( '#latitude-arbres' ).val() ) &&
1977
		this.utils.valOk( $( '#longitude-arbres' ).val() ) &&
1978
		this.utils.valOk( $( '#rue-arbres' ).val() ) &&
1979
		this.utils.valOk( $( '#commune-nom-arbres' ).val() )
1980
	);
1981
	const piedArbre = this.utils.valOk( $( '#equipement-pied-arbre' ).val(), false, 'other' );
1982
	const taxon = this.utils.valOk( $( '#taxon' ).val() );
1983
	const obs   = (
1984
		$( '#form-observation' ).valid() &&
1985
		$( '#form-arbre' ).valid() &&
1986
		$( '#form-arbre-fs' ).valid() &&
1987
		piedArbre
1988
	);
1989
 
1990
	if ( piedArbre ) {
1991
		$( '#equipement-pied-arbre' )
1992
			.closest( '.control-group' )
1993
				.removeClass( 'error' )
1994
				.find( 'span.error' )
1995
					.addClass( 'hidden' );
1996
	} else {
1997
		$( '#equipement-pied-arbre' )
1998
			.closest( '.control-group' )
1999
				.addClass( 'error' )
2000
				.find( 'span.error' )
2001
					.removeClass( 'hidden' );
2002
	}
2003
	if ( geoloc ) {
2004
		this.masquerPanneau( '#dialogue-geoloc-ko' );
2005
		$( '.geoloc' ).closest( '.control-group' ).removeClass( 'error' );
2006
	} else {
2007
		this.afficherPanneau( '#dialogue-geoloc-ko' );
2008
		$( '.geoloc' ).closest( '.control-group' ).addClass( 'error' );
2009
	}
2010
	// panneau observateur
2011
	if ( observateur ) {
2012
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
2013
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
2014
	} else {
2015
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
2016
		$( '#tb-observateur .control-group' ).addClass( 'error' );
2017
	}
2018
 
2019
	return ( observateur && obs && geoloc && taxon );
2020
};
2021
 
2022
// Controle des panneaux d'infos **********************************************/
2023
 
2024
ReleveApa.prototype.afficherPanneau = function( selecteur ) {
2025
	$( selecteur )
2026
		.removeClass( 'hidden' )
2027
		.hide()
2028
		.show( 600 )
2029
		.delay( this.dureeMessage )
2030
		.hide( 600 );
2031
	$( 'html, body' ).stop().animate({scrollTop: $( selecteur ).offset().top}, 300);
2032
};
2033
 
2034
ReleveApa.prototype.masquerPanneau = function( selecteur ) {
2035
	$( selecteur ).addClass( 'hidden' );
2036
};
2037
 
2038
ReleveApa.prototype.fermerPanneauAlert = function() {
2039
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
2040
};
2041
 
2042
// lib hors objet --
2043
 
2044
/**
2045
* Stope l'évènement courant quand on clique sur un lien.
2046
* Utile pour Chrome, Safari...
2047
*/
2048
function arreter( event ) {
2049
	if ( event.stopPropagation ) {
2050
		event.stopPropagation();
2051
	}
2052
	if ( event.preventDefault ) {
2053
		event.preventDefault();
2054
	}
2055
 
2056
	return false;
2057
}
2058
 
2059
/**
2060
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
2061
 * @param jqXHR
2062
 * @returns {String}
2063
 */
2064
function extraireEnteteDebug( jqXHR ) {
2065
	var msgDebug = '';
2066
 
2067
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
2068
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
2069
		if ( null !== debugInfos ) {
2070
			$.each( debugInfos, function( cle, valeur ) {
2071
				msgDebug += valeur + '\n';
2072
			});
2073
		}
2074
	}
2075
 
2076
	return msgDebug;
2077
}
2078
 
2079
/*
2080
 * jQuery UI Autocomplete HTML Extension
2081
 *
2082
 * Copyright 2010, Scott González (http://scottgonzalez.com)
2083
 * Dual licensed under the MIT or GPL Version 2 licenses.
2084
 *
2085
 * http://github.com/scottgonzalez/jquery-ui-extensions
2086
 *
2087
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
2088
 */
2089
( function( $ ) {
2090
	var proto      = $.ui.autocomplete.prototype,
2091
		initSource = proto._initSource;
2092
 
2093
	ReleveApa.prototype.filter = function( array, term ) {
2094
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
2095
 
2096
		return $.grep( array, function( value ) {
2097
 
2098
			return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
2099
		});
2100
	}
2101
	$.extend( proto, {
2102
		_initSource: function() {
2103
			if ( this.options.html && $.isArray( this.options.source ) ) {
2104
				this.source = function( request, response ) {
2105
					response( filter( this.options.source, request.term ) );
2106
				};
2107
			} else {
2108
				initSource.call( this );
2109
			}
2110
		},
2111
		_renderItem: function( ul, item) {
2112
			if ( item.retenu ) {
2113
				item.label = '<strong>' + item.label + '</strong>';
2114
			}
2115
 
2116
			return $( '<li></li>' )
2117
				.data( 'item.autocomplete', item )
2118
				.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
2119
				.appendTo( ul );
2120
		}
2121
	});
2122
})( jQuery );