Subversion Repositories eFlore/Applications.cel

Rev

Rev 3317 | Go to most recent revision | Details | 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
	this.verifierAffichageMiniaturesResumeObs();
962
};
963
 
964
/**
965
 * Ajoute une boîte de miniatures avec défilement des images,
966
 * pour une obs de la liste des obs à transmettre
967
 */
968
ReleveApa.prototype.ajouterImgMiniatureAuTransfert = function( chargerImages ) {
969
	const lthis = this;
970
	var html         =
971
			'<div class="defilement-miniatures">'+
972
				'<figure class="centre">'+
973
					'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
974
				'</figure>'+
975
			'</div>',
976
		miniatures   = '',
977
		centre       = '',
978
		defilVisible = '',
979
		length       = 0;
980
 
981
	if ( this.utils.valOk( chargerImages ) || this.utils.valOk( $( '#miniatures img' ) ) ) {
982
		if ( this.utils.valOk( chargerImages ) ) {
983
			$.each(  chargerImages, function( i, value ) {
984
				var imgVisible = ( 0 < i ) ? 'miniature-cachee' : 'miniature-selectionnee';
985
 
986
				var css        = ( lthis.utils.valOk( value['b64'] ) ) ? 'miniature b64' : 'miniature',
987
					src        = value.src,
988
					alt        = value.nom,
989
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
990
 
991
				miniatures += miniature;
992
			});
993
			length = chargerImages.length;
994
 
995
		} else {
996
			var premiere     = true;
997
			$( '#miniatures img' ).each( function() {
998
				var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
999
				premiere = false;
1000
 
1001
				var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
1002
					src        = $( this ).attr( 'src' ),
1003
					alt        = $( this ).attr( 'alt' ),
1004
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1005
 
1006
				miniatures += miniature;
1007
			});
1008
			length = $( '#miniatures img' ).length;
1009
		}
1010
		if ( 1 === length ) {
1011
			centre       = 'centre';
1012
			defilVisible = ' defilement-miniatures-cache';
1013
		}
1014
		html             =
1015
			'<div class="defilement-miniatures">'+
1016
				'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
1017
				'<figure class="' + centre + '">'+
1018
					miniatures+
1019
				'</figure>'+
1020
				'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
1021
			'</div>';
1022
	}
1023
 
1024
	return html;
1025
};
1026
 
1027
/**
1028
 * Construit le html à afficher pour le numNom
1029
 */
1030
ReleveApa.prototype.ajouterNumNomSel = function( numNomSel ) {
1031
	var nn = '<span class="nn">[nn' + numNomSel + ']</span>';
1032
 
1033
	if ( !this.utils.valOk( numNomSel ) ) {
1034
		nn = '<span class="alert-error">[' + this.utils.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
1035
	}
1036
 
1037
	return nn;
1038
};
1039
 
1040
ReleveApa.prototype.verifierAffichageMiniaturesResumeObs = function() {
1041
	const lthis = this;
1042
 
1043
	var srcTest = '',
1044
		$that   = null;
1045
 
1046
	$( '.defilement-miniatures img' ).each( function() {
1047
		$( this ).error().closest('.defilement-miniatures' ).html(
1048
    		'<figure class="centre">'+
1049
				'<img class="miniature align-middle" alt="Aucune photo" src="' + lthis.pasDePhotoIconeUrl + '" width="80%" />'+
1050
			'</figure>'
1051
    	);
1052
	});
1053
};
1054
 
1055
/**
1056
 * Stocke des données d'obs à envoyer à la bdd
1057
 */
1058
ReleveApa.prototype.stockerObsData = function( obsDatas ) {
1059
	const lthis = this;
1060
	var obsNum      = obsDatas.obsNum,
1061
		numNomSel   = obsDatas.arbre.taxon.numNomSel,
1062
		referentiel = ( !this.utils.valOk( numNomSel ) ) ? 'autre' : 'bdtfx',
1063
		date        = lthis.utils.fournirDate( obsDatas.releve.date ),
1064
		// si releve dupliqué on ne stocke pas l'image :
1065
		stockerImg  = this.utils.valOk( obsDatas.arbre['miniature-img'] ),
1066
		imgNom      = [],
1067
		imgB64      = [];
1068
 
1069
		if( stockerImg ) {
1070
			$.each( obsDatas.arbre['miniature-img'], function( i, obj ) {
1071
				if( obj.hasOwnProperty( 'id' ) ) {
1072
					stockerImg = false;
1073
				}
1074
				return stockerImg;
1075
			});
1076
		}
1077
		if ( stockerImg ) {
1078
			$.each( obsDatas.arbre['miniature-img'] , function(i, value) {
1079
				if( lthis.utils.valOk( value.nom ) ) {
1080
					imgNom.push( value.nom );
1081
				}
1082
				if( lthis.utils.valOk( value['b64'] ) ) {
1083
					imgB64.push( value['b64'] );
1084
				}
1085
			});
1086
		} else {
1087
			imgNom = lthis.getNomsImgsOriginales();
1088
			imgB64 = lthis.getB64ImgsOriginales();
1089
		}
1090
 
1091
	// Stockage en data des données d'obs à transmettre
1092
	$( '#liste-obs' ).data( 'obsId' + obsNum, {
1093
		'num_nom_sel'        : numNomSel,
1094
		'nom_sel'            : obsDatas.arbre.taxon.value,
1095
		'nom_ret'            : obsDatas.arbre.taxon.nomRet,
1096
		'num_nom_ret'        : obsDatas.arbre.taxon.numNomRet,
1097
		'num_taxon'          : obsDatas.arbre.taxon.nt,
1098
		'famille'            : obsDatas.arbre.taxon.famille,
1099
		'referentiel'        : referentiel,
1100
		'certitude'          : obsDatas.arbre.certitude,
1101
		'date'               : date,
1102
		'notes'              : obsDatas.releve.commentaires.trim(),
1103
		'pays'               : obsDatas.releve.pays,
1104
		'commune_nom'        : obsDatas.releve['commune-nom'],
1105
		'commune_code_insee' : obsDatas.releve['commune-insee'],
1106
		'latitude'           : obsDatas.releve.latitude,
1107
		'longitude'          : obsDatas.releve.longitude,
1108
		'altitude'           : obsDatas.releve.altitude,
1109
		//Ajout des champs images
1110
		'image_nom'          : imgNom,
1111
		'image_b64'          : imgB64,
1112
		// Ajout des champs étendus de l'obs
1113
		'obs_etendue'        : lthis.getObsChpArbres( obsDatas )
1114
	});
1115
};
1116
 
1117
ReleveApa.prototype.getNomsImgsOriginales = function() {
1118
	var noms = new Array();
1119
 
1120
	$( '.miniature-img' ).each( function() {
1121
		noms.push( $( this ).attr( 'alt' ) );
1122
	});
1123
 
1124
	return noms;
1125
};
1126
 
1127
ReleveApa.prototype.getB64ImgsOriginales = function() {
1128
	var b64 = new Array();
1129
 
1130
	$( '.miniature-img' ).each( function() {
1131
		if ( $( this ).hasClass( 'b64' ) ) {
1132
			b64.push( $( this ).attr( 'src' ) );
1133
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
1134
			b64.push( $( this ).data( 'b64' ) );
1135
		}
1136
	});
1137
 
1138
	return b64;
1139
};
1140
 
1141
/**
1142
 * Retourne un Array contenant les valeurs des champs
1143
 * dont les données seront transmises dans la table cel-obs-etendues
1144
 */
1145
ReleveApa.prototype.getObsChpArbres = function( datasArbres ) {
1146
	const lthis = this;
1147
 
1148
	var retour = [],
1149
		champs = [
1150
			'rue',
1151
			'zone-pietonne',
1152
			'pres-lampadaires',
1153
			'latitude-arbres',
1154
			'longitude-arbres',
1155
			'altitude-arbres',
1156
			'circonference',
1157
			'surface-pied',
1158
			'equipement-pied-arbre',
1159
			'tassement',
1160
			'dejections',
1161
			'com-arbres'
1162
		];
1163
 
1164
	var cleValeur       = '',
1165
		faceOmbre       = '',
1166
		faceOmbreLength = datasArbres.arbre['face-ombre'].length;
1167
 
1168
	$.each( champs, function( i ,value ) {
1169
		cleValeur = ( 3 > i ) ? 'releve' : 'arbre';
1170
		// console.log(cleValeur);
1171
		// console.log(value);
1172
		// console.log(datasArbres[cleValeur][value]);
1173
 
1174
 
1175
		if ( lthis.utils.valOk( datasArbres[cleValeur][value] ) ) {
1176
			retour.push({ cle : value, valeur : datasArbres[cleValeur][value] });
1177
		}
1178
	});
1179
	if ( 'string' === typeof datasArbres.arbre['face-ombre'] ) {
1180
		faceOmbre = datasArbres.arbre['face-ombre'];
1181
	} else {
1182
		$.each( datasArbres.arbre['face-ombre'], function( i ,value ) {
1183
			faceOmbre += value
1184
			if ( faceOmbreLength > ( i + 1 ) ) {
1185
				faceOmbre += ';';
1186
			}
1187
		});
1188
	}
1189
	retour.push(
1190
		{ cle : 'face-ombre', valeur : faceOmbre },
1191
		{ cle : 'num_arbre' , valeur : datasArbres.obsNum }
1192
	);
1193
 
1194
	var stockerImg  = this.utils.valOk( datasArbres.arbre['miniature-img'] );
1195
 
1196
	if( stockerImg ) {
1197
		$.each( datasArbres.arbre['miniature-img'], function( i, paramsImg ) {
1198
			if( !paramsImg.hasOwnProperty( 'id' ) ) {
1199
				stockerImg = false;
1200
			}
1201
			return stockerImg;
1202
		});
1203
	}
1204
	if( stockerImg ) {
1205
		retour.push({ cle : 'miniature-img' , valeur : JSON.stringify( datasArbres.arbre['miniature-img'] ) });
1206
	}
1207
 
1208
	return retour;
1209
};
1210
 
1211
/**
1212
 * Efface toutes les miniatures (formulaire)
1213
 */
1214
ReleveApa.prototype.supprimerMiniatures = function() {
1215
	$( '#miniatures' ).empty();
1216
	$( '#miniature-msg' ).empty();
1217
};
1218
 
1219
ReleveApa.prototype.surChangementNbreObs = function() {
1220
	if ( 0 === this.obsNbre ) {
1221
		$( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
1222
		// $( '#zone-liste-obs' ).addClass( 'hidden' );
1223
		$( '#bloc-form-arbres' ).removeClass( 'hidden' );
1224
	} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1225
		$( '#ajouter-obs,#transmettre-obs' ).removeAttr( 'disabled' );
1226
		$( '#bloc-form-arbres' ).removeClass( 'hidden' );
1227
	} else if ( this.obsNbre >= this.obsMaxNbre ) {
1228
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1229
		$( '#bloc-form-arbres' ).addClass( 'hidden' );
1230
		this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
1231
	}
1232
};
1233
 
1234
ReleveApa.prototype.chargerInfosArbre = function( numArbre ) {
1235
	const lthis = this;
1236
	var desactiverForm = ( parseInt( numArbre ) !== ( this.numArbre + 1 ) );
1237
 
1238
	if ( desactiverForm ) {
1239
		var releveDatas = $.parseJSON( $( '#releve-data' ).val() ),
1240
			arbreDatas  = releveDatas[numArbre],
1241
			taxon       = {item:{}},
1242
			imgHtml     = '';
1243
 
1244
		$( '#arbre-nb').text( numArbre );
1245
 
1246
		taxon.item = arbreDatas.taxon;
1247
		this.surAutocompletionTaxon( {}, taxon );
1248
 
1249
		const SELECTS = ['certitude','equipement-pied-arbre','tassement'];
1250
 
1251
		$.each( SELECTS, function( i, value ) {
1252
			if( !lthis.utils.valOk( arbreDatas[value] ) ) {
1253
				arbreDatas[value] = '';
1254
			}
1255
			if ( $( this ).hasClass( 'other' ) && lthis.utils.valOk( $( this ).val() ) ) {
1256
				$( this ).text( $( this ).val() );
1257
			}
1258
			$( '#' + value + ' option' ).each( function() {
1259
				if ( arbreDatas[value] === $( this ).val() ) {
1260
					$( this ).prop( 'selected', true );
1261
				} else {
1262
					$( this ).prop( 'selected', false );
1263
				}
1264
			});
1265
		});
1266
		$( '#rue-arbres' ).val(releveDatas[0]['rue']);
1267
		$( '#latitude-arbres' ).val(arbreDatas['latitude-arbres']);
1268
		$( '#longitude-arbres' ).val(arbreDatas['longitude-arbres']);
1269
		$( '#commune-nom-arbres' ).val(releveDatas[0]['commune-nom']);
1270
		$( '#commune-insee-arbres' ).val(releveDatas[0]['commune-insee']);
1271
		$( '#altitude-arbres' ).val(arbreDatas['altitude-arbres']);
1272
		$( '#pays-arbres' ).val(releveDatas[0]['pays']);
1273
		// image
1274
		this.supprimerMiniatures();
1275
		$.each( arbreDatas['miniature-img'], function( i, value ) {
1276
			imgHtml +=
1277
			'<div class="miniature mb-3 mr-3">'+
1278
				'<img class="miniature-img" class="miniature img-rounded" alt="' + value.nom + '" src="' + value.src + '"/>'+
1279
			'</div>';
1280
		});
1281
		$( '#miniatures' ).append( imgHtml );
1282
		// remplacer les photos qui ne chargent pas par 'pasDePhotoIcon'
1283
		$( '.miniature-img' ).error().replaceWith(
1284
			'<img class="miniature align-middle" alt="Aucune photo" src="' + lthis.pasDePhotoIconeUrl + '" width="80%" />'
1285
		);
1286
 
1287
		$( '#circonference' ).val( arbreDatas.circonference );
1288
		$( '#surface-pied' ).val( arbreDatas['surface-pied'] );
1289
		$( '#com-arbres' ).val( arbreDatas['com-arbres'] );
1290
		if ( undefined != arbreDatas.dejections ) {
1291
			$( '#dejections-oui' ).prop( 'checked', arbreDatas.dejections );
1292
			$( '#dejections-non' ).prop( 'checked', !arbreDatas.dejections );
1293
		}
1294
		$( '#face-ombre input' ).each( function() {
1295
			if ( -1 < arbreDatas['face-ombre'].indexOf( $( this ).val() ) ) {
1296
				$( this ).prop( 'checked', true );
1297
			} else {
1298
				$( this ).prop( 'checked', false );
1299
			}
1300
		});
1301
	}
1302
 
1303
	this.modeArbresBasculerActivation( desactiverForm, numArbre );
1304
};
1305
 
1306
ReleveApa.prototype.modeArbresBasculerActivation = function( desactiver, numArbre = 0 ) {
1307
	$(
1308
		'#taxon,'+
1309
		'#certitude,'+
1310
		'#equipement-pied-arbre,'+
1311
		'#tassement,'+
1312
		'#latitude-arbres,'+
1313
		'#longitude-arbres,'+
1314
		'#rue-arbres,'+
1315
		'#fichier,'+
1316
		'#circonference,'+
1317
		'#surface-pied,'+
1318
		'#com-arbres,'+
1319
		'#ajouter-obs'
1320
	).prop( 'disabled', desactiver );
1321
	$( '#dejections,#face-ombre' ).find( 'input' ).prop( 'disabled', desactiver );
1322
 
1323
	if ( desactiver ) {
1324
		$( '#geoloc-arbres,#bouton-fichier,#miniature-arbres-info' ).addClass( 'hidden' );
1325
		$( '#geoloc-datas-arbres,#retour' ).removeClass( 'hidden' );
1326
	} else {
1327
		// quand on change ou qu'on revient à la normale :
1328
		$( '#geoloc-arbres,#bouton-fichier,#miniature-arbres-info' ).removeClass( 'hidden' );
1329
		$( '#geoloc-datas-arbres,#retour' ).addClass( 'hidden' );
1330
		// retour aux valeurs par defaut
1331
		$( '#equipement-pied-arbre .other' ).text( 'Autre' ).val( 'other' );
1332
		// $( '#equipement-pied-arbre .other' ).val( 'other' );
1333
		$(
1334
			'#certitude option,'+
1335
			'#equipement-pied-arbre option,'+
1336
			'#tassement option'
1337
		).each( function() {
1338
			if ( $( this ).hasClass( 'choisir' ) ) {
1339
				$( this ).prop( 'selected', true );
1340
			} else {
1341
				$( this ).prop( 'selected', false );
1342
			}
1343
		});
1344
		$( '#taxon' ).data( 'numNomSel', '' )
1345
			.data( 'nomRet','' )
1346
			.data( 'numNomRet', '' )
1347
			.data( 'nt', '' )
1348
			.data( 'famille', '' );
1349
		this.supprimerMiniatures();
1350
		$( '#dejections,#face-ombre' ).find( 'input' ).prop( 'checked', false );
1351
		$(
1352
			'#taxon,'+
1353
			'#circonference,'+
1354
			'#surface-pied,'+
1355
			'#com-arbres,'+
1356
			'#rue-arbres,'+
1357
			'#latitude-arbres,'+
1358
			'#longitude-arbres,'+
1359
			'#certitude,'+
1360
			'#equipement-pied-arbre,'+
1361
			'#tassement'
1362
		).val( '' );
1363
		$( '#arbre-nb' ).text( numArbre );
1364
		$( '#arbre-info-lien-' + numArbre ).addClass( 'disabled' );
1365
		$( '.arbre-info' ).not( '#arbre-info-lien-' + numArbre ).removeClass( 'disabled' );
1366
	}
1367
};
1368
 
1369
ReleveApa.prototype.defilerMiniatures = function( element ) {
1370
	var miniatureSelectionne  = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
1371
 
1372
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
1373
	miniatureSelectionne.addClass( 'miniature-cachee' );
1374
 
1375
	var miniatureAffichee     = miniatureSelectionne;
1376
 
1377
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
1378
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
1379
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
1380
		} else {
1381
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
1382
		}
1383
	} else {
1384
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
1385
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
1386
		} else {
1387
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
1388
		}
1389
	}
1390
	miniatureAffichee.addClass( 'miniature-selectionnee' );
1391
	miniatureAffichee.removeClass( 'miniature-cachee' );
1392
};
1393
 
1394
ReleveApa.prototype.supprimerObs = function( selector ) {
1395
	var obsId = $( selector ).val();
1396
 
1397
	// Problème avec IE 6 et 7
1398
	if ( 'Supprimer' === obsId ) {
1399
		obsId = $( selector ).attr( 'title' );
1400
	}
1401
	this.supprimerObsParId( obsId );
1402
};
1403
 
1404
/**
1405
 * Supprime l'obs et les data de l'obs
1406
 * et remonte les suivantes d'un cran
1407
 */
1408
ReleveApa.prototype.supprimerObsParId = function( obsId, transmission = false ) {
1409
	if ( !transmission ) {
1410
		this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1411
		this.releveData.splice( obsId , 1 );
1412
		$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1413
	}
1414
	$( '#arbre-info-' + ( this.numArbre ) ).remove();
1415
	$( '#arbre-nb' ).text( this.numArbre );
1416
 
1417
	this.obsNbre  -= 1;
1418
	this.numArbre -= 1;
1419
	$( '.obs-nbre' ).text( this.obsNbre );
1420
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1421
	$( '.obs' + obsId ).remove();
1422
 
1423
	obsId = parseInt(obsId);
1424
	var listObsData = $( '#liste-obs' ).data(),
1425
		exId        = 0,
1426
		indexObs    = '',
1427
		exIndexObs  = '',
1428
		arbreExId   = 0;
1429
 
1430
	for ( var id = obsId; id <= ( this.obsNbre + 1 ); id++ ) {
1431
		exId       = parseInt(id) + 1;
1432
		indexObs   = 'obsId' + id;
1433
		exIndexObs = 'obsId' + exId;
1434
		arbreExId  = parseInt( $( '#obs-arbre-' + exId ).data( 'arbre' ) );
1435
		arbreId    = arbreExId - 1;
1436
		$( '#liste-obs' ).removeData( indexObs );
1437
		if ( this.utils.valOk( listObsData[ exIndexObs ] ) ) {
1438
			$( '#liste-obs' ).data( indexObs, listObsData[ exIndexObs ] );
1439
		}
1440
		$( '#obs' + exId )
1441
			.attr( 'id', 'obs' + id )
1442
			.removeClass( 'obs' + exId )
1443
			.addClass( 'obs' + id )
1444
			.find( '.supprimer-obs' )
1445
				.attr( 'title', 'Observation n°' + id )
1446
				.val( id );
1447
		$( '#obs-arbre-' + arbreExId )
1448
			.attr( 'id', 'obs-arbre-' + arbreId )
1449
			.attr( 'data-arbre', arbreId )
1450
			.data( 'arbre', arbreId )
1451
			.text( 'Arbre ' + arbreId );
1452
 
1453
		if ( parseInt( id ) !== this.obsNbre ) {
1454
			id = parseInt(id);
1455
		}
1456
	}
1457
};
1458
 
1459
/*
1460
 * Actualise l'id_observation ( id de l'obs en bdd )
1461
 * à partir des données renvoyées par le service après transfert
1462
 */
1463
ReleveApa.prototype.actualiserReleveDataIdObs = function( obsId, id_observation ) {
1464
	this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1465
	this.releveData[obsId ]['id_observation'] = id_observation;
1466
	$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1467
};
1468
 
1469
ReleveApa.prototype.transmettreObs = function() {
1470
	const lthis = this;
1471
	var observations = $( '#liste-obs' ).data();
1472
 
1473
	if ( this.debug ) {
1474
		console.log( observations );
1475
	}
1476
	if ( !this.utils.valOk( typeof observations, true, 'object' ) ) {
1477
		this.afficherPanneau( '#dialogue-zero-obs' );
1478
	} else {
1479
		$( window ).on( 'beforeunload', function( event ) {
1480
			return lthis.utils.msgTraduction( 'rechargement-page' );
1481
		});
1482
		this.nbObsEnCours         = 1;
1483
		this.nbObsTransmises      = 0;
1484
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
1485
			return i;
1486
		}).length;
1487
		this.depilerObsPourEnvoi();
1488
	}
1489
 
1490
	return false;
1491
};
1492
 
1493
ReleveApa.prototype.depilerObsPourEnvoi = function() {
1494
	var observations = $( '#liste-obs' ).data();
1495
 
1496
	// la boucle est factice car on utilise un tableau
1497
	// dont on a besoin de n'extraire que le premier élément
1498
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1499
	// TODO: utiliser var.keys quand ça sera plus répandu
1500
	// ou bien utiliser un vrai tableau et pas un objet
1501
	for ( var obsNum in observations ) {
1502
		var obsATransmettre = {
1503
			'projet'  : this.tagProjet,
1504
			'tag-obs' : this.tagObs,
1505
			'tag-img' : this.tagImg
1506
		};
1507
		var utilisateur = {
1508
			id_utilisateur : this.infosUtilisateur.id,
1509
			prenom         : this.infosUtilisateur.prenom,
1510
			nom            : this.infosUtilisateur.nom,
1511
			courriel       : $( '#courriel' ).val()
1512
		};
1513
 
1514
		obsATransmettre['utilisateur'] = utilisateur;
1515
		obsATransmettre[obsNum]        = observations[obsNum];
1516
 
1517
		var idObsNumerique = obsNum.replace( 'obsId', '' );
1518
 
1519
		if( '' !== idObsNumerique ) {
1520
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
1521
		}
1522
		break;
1523
	}
1524
};
1525
 
1526
ReleveApa.prototype.envoyerObsAuCel = function( idObs, observation ) {
1527
	const lthis     = this;
1528
	var erreurMsg = '';
1529
 
1530
	$.ajax({
1531
		url        : lthis.serviceSaisieUrl,
1532
		type       : 'POST',
1533
		data       : observation,
1534
		dataType   : 'json',
1535
		beforeSend : function() {
1536
			$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
1537
			$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1538
			$( '.alert-txt' ).empty();
1539
			$( '.alert-txt .msg-erreur' ).remove();
1540
			$( '.alert-txt .msg-debug' ).remove();
1541
			$( '#chargement' ).removeClass( 'hidden' );
1542
		},
1543
		success    : function( transfertDatas, textStatus, jqXHR ) {
1544
			// actualisation de id_observation dans '#releve-data'
1545
			lthis.actualiserReleveDataIdObs( idObs, transfertDatas.id );
1546
			// mise à jour du nombre d'obs à transmettre
1547
			// et suppression de l'obs
1548
			lthis.supprimerObsParId( idObs, true );
1549
			lthis.nbObsEnCours++;
1550
			// mise à jour du statut
1551
			lthis.mettreAJourProgression();
1552
			if( 0 < lthis.obsNbre ) {
1553
				// dépilement de la suivante
1554
				lthis.depilerObsPourEnvoi();
1555
			}
1556
		},
1557
		statusCode  : {
1558
			500 : function( jqXHR, textStatus, errorThrown ) {
1559
				erreurMsg += lthis.utils.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1560
				}
1561
		},
1562
		error        : function( jqXHR, textStatus, errorThrown ) {
1563
			erreurMsg += lthis.utils.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1564
			try {
1565
				reponse = jQuery.parseJSON( jqXHR.responseText );
1566
				if ( null !== reponse ) {
1567
					$.each( reponse, function( cle, valeur ) {
1568
						erreurMsg += valeur + '\n';
1569
					});
1570
				}
1571
			} catch( e ) {
1572
				erreurMsg += lthis.utils.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
1573
			}
1574
		},
1575
		complete      : function( jqXHR, textStatus ) {
1576
			var debugMsg = extraireEnteteDebug( jqXHR );
1577
 
1578
			if ( '' !== erreurMsg ) {
1579
				if ( lthis.debug ) {
1580
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
1581
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1582
				}
1583
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1584
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagProjet+
1585
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
1586
 
1587
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
1588
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
1589
				// window.location.hash = 'obs' + idObs;
1590
 
1591
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
1592
					$( '#tpl-transmission-ko' ).clone()
1593
						.find( '.courriel-erreur' )
1594
						.attr( 'href', hrefCourriel )
1595
						.end()
1596
						.html()
1597
				);
1598
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
1599
				$( '#chargement' ).addClass( 'hidden' );
1600
				lthis.initialiserBarreProgression;
1601
			} else {
1602
				if ( lthis.debug ) {
1603
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1604
				}
1605
				if( 0 === lthis.obsNbre ) {
1606
					setTimeout( function() {
1607
						$( '#chargement,#bloc-arbres-gauche,#bloc-controle-liste-obs' ).addClass( 'hidden' );
1608
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
1609
						$( '#dialogue-obs-transaction-ok,#bouton-saisir-plantes,#bouton-saisir-lichens' ).removeClass( 'hidden' );
1610
					}, 1500 );
1611
				}
1612
			}
1613
		}
1614
	});
1615
};
1616
 
1617
ReleveApa.prototype.mettreAJourProgression = function() {
1618
	this.nbObsTransmises++;
1619
 
1620
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
1621
 
1622
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
1623
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
1624
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.utils.msgTraduction( 'observations-transmises' ) );
1625
	if( 0 === this.obsNbre ) {
1626
		$( '.progress' ).removeClass( 'active' );
1627
		$( '.progress' ).removeClass( 'progress-bar-striped' );
1628
	}
1629
};
1630
 
1631
ReleveApa.prototype.initialiserBarreProgression = function() {
1632
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
1633
	$( '#barre-progression-upload' ).css( 'width', '0%' );
1634
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.utils.msgTraduction( 'observations-transmises' ) );
1635
	$( '.progress' ).addClass( 'active' );
1636
	$( '.progress' ).addClass( 'progress-bar-striped' );
1637
};
1638
 
1639
// Form Validator *************************************************************/
1640
ReleveApa.prototype.configurerFormValidator = function() {
1641
	const lthis = this;
1642
 
1643
	$.validator.addMethod(
1644
		'dateCel',
1645
		function ( value, element ) {
1646
			return ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) );
1647
		},
1648
		lthis.utils.msgTraduction( 'date-incomplete' )
1649
	);
1650
 
1651
	$.validator.addMethod(
1652
		'userEmailOk',
1653
		function ( value, element ) {
1654
			return ( lthis.utils.valOk( value ) );
1655
		},
1656
		''
1657
	);
1658
	$.validator.addMethod(
1659
		'minMaxOk',
1660
		function ( value, element, param ) {
1661
			$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message;
1662
			return lthis.validerMinMax( element ).cond;
1663
		},
1664
		$.validator.messages.minMaxOk
1665
	);
1666
	$.validator.addMethod(
1667
		'listFields',
1668
		function ( value, element ) {
1669
			return ( lthis.utils.valOk( value ) );
1670
		},
1671
		''
1672
	);
1673
 
1674
	$.extend( $.validator.defaults, {
1675
		errorElement: 'span',
1676
		errorPlacement: function( error, element ) {
1677
			if ( 'checkbox' === element.attr( 'type' ) || 'radio' === element.attr( 'type' ) ) {
1678
				error.appendTo( element.closest( '.list' ) );
1679
			} else {
1680
				element.after( error );
1681
			}
1682
		},
1683
		onfocusout: function( element ) {
1684
			if ( $( element ).valid() ) {
1685
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1686
			} else {
1687
				$( element ).closest( '.control-group' ).addClass( 'error' );
1688
			}
1689
		},
1690
		onkeyup : function( element ) {
1691
			if ( $( element ).valid() ) {
1692
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1693
			} else {
1694
				$( element ).closest( '.control-group' ).addClass( 'error' );
1695
			}
1696
		},
1697
		unhighlight: function( element ) {
1698
			$( element ).closest( '.control-group' ).removeClass( 'error' );
1699
		},
1700
		highlight: function( element ) {
1701
			$( element ).closest( '.control-group' ).addClass( 'error' );
1702
		}
1703
	});
1704
};
1705
 
1706
ReleveApa.prototype.validerMinMax = function( element ) {
1707
	var mMCond      = new Boolean(),
1708
		minCond     = parseFloat( element.value ) >= parseFloat( element.min ),
1709
		maxCond     = parseFloat( element.value ) <= parseFloat( element.max ),
1710
		messageMnMx = 'La valeur entrée doit être',
1711
		returnMnMx  = { cond : true , message : '' };
1712
 
1713
	if (
1714
			( this.utils.valOk( element.type, true, 'number' ) || this.utils.valOk( element.type, true, 'range' ) ) &&
1715
			( this.utils.valOk( element.min ) || this.utils.valOk( element.max ) )
1716
		) {
1717
 
1718
		if ( element.min && element.max ) {
1719
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
1720
			mnMxCond     = ( minCond && maxCond );
1721
		} else if ( element.min ) {
1722
			messageMnMx += ' supérieure à ' + element.min;
1723
			mnMxCond     = minCond;
1724
		} else {
1725
			messageMnMx += ' inférieure à ' + element.max;
1726
			mnMxCond     = maxCond;
1727
		}
1728
		returnMnMx.cond    = mnMxCond;
1729
		returnMnMx.message = messageMnMx;
1730
	}
1731
 
1732
	return returnMnMx;
1733
};
1734
 
1735
/**
1736
 * Valider date/rue/commune par rapport aux relevés précédents
1737
 */
1738
ReleveApa.prototype.validerDateRueCommune = function( valeurDate, valeurRue, valeurCmn ) {
1739
	var valide = true;
1740
 
1741
	if (
1742
		this.utils.valOk( $( '#dates-rues-communes' ).val() ) &&
1743
		this.utils.valOk( valeurDate ) &&
1744
		this.utils.valOk( valeurRue ) &&
1745
		this.utils.valOk( valeurCmn )
1746
	) {
1747
		var valsEltDRC = $.parseJSON( $( '#dates-rues-communes' ).val() ),
1748
			valeurDRC = valeurDate + valeurRue + valeurCmn;
1749
		valide = ( -1 === valsEltDRC.indexOf( valeurDRC ) );
1750
 
1751
	}
1752
	return valide;
1753
};
1754
 
1755
/**
1756
 * FormValidator pour les champs date/rue/Commune
1757
 */
1758
ReleveApa.prototype.dateRueCommuneFormValidator = function() {
1759
	var dateValid    = ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( $( '#releve-date' ).val() ) ),
1760
		geolocValid  = ( this.utils.valOk( $( '#commune-nom' ).val() ) && this.utils.valOk( $( '#rue' ).val() ) );
1761
	const errorDateRue =
1762
			'<span id="error-drc" class="error">'+
1763
				this.utils.msgTraduction( 'date-rue' )+
1764
			'</span> ';
1765
 
1766
	if( this.validerDateRueCommune( $( '#releve-date' ).val(), $( '#rue' ).val(), $( '#commune-nom' ).val()  ) ) {
1767
		$( '#releve-date' )
1768
			.removeClass( 'erreur' )
1769
			.closest( '.control-group' )
1770
				.removeClass( 'error' )
1771
				.find( '#error-drc' )
1772
					.remove();
1773
		if ( geolocValid ) {
1774
			$( '#geoloc' )
1775
			.closest( '.control-group' )
1776
				.removeClass( 'error' );
1777
		}
1778
		$( '#geoloc #error-drc' ).remove();
1779
	} else {
1780
		$( '#releve-date' )
1781
			.addClass( 'erreur' )
1782
			.closest( '.control-group' )
1783
				.addClass( 'error' );
1784
		if ( !this.utils.valOk( $( '#releve-date' ).closest( '.control-group' ).find( '#error-drc' ) ) ) {
1785
			$( '#releve-date' ).after( errorDateRue );
1786
		}
1787
		$( '#geoloc' ).closest( '.control-group' ).addClass( 'error' );
1788
		if ( !this.utils.valOk( $( '#geoloc' ).find( '#error-drc' ) ) ) {
1789
			$( '#geoloc' ).prepend( errorDateRue );
1790
		}
1791
	}
1792
	if ( dateValid ) {
1793
		$( '#releve-date' ).closest( '.control-group span.error' ).not( '#error-drc' ).remove();
1794
	}
1795
};
1796
 
1797
ReleveApa.prototype.definirReglesFormValidator = function() {
1798
	const lthis = this;
1799
 
1800
	$( '#form-observation' ).validate({
1801
		rules : {
1802
			'zone-pietonne' : {
1803
				required : true,
1804
				minlength : 1
1805
			},
1806
			latitude : {
1807
				required : true,
1808
				minlength : 1,
1809
				range : [-90, 90]
1810
			},
1811
			longitude : {
1812
				required : true,
1813
				minlength : 1,
1814
				range : [-180, 180]
1815
			}
1816
		}
1817
	});
1818
	$( 'input[type=date]' ).not( '#releve-date' ).on( 'input', function() {
1819
		$( this ).valid();
1820
	});
1821
	// validation date/rue/commune au démarage
1822
	this.dateRueCommuneFormValidator();
1823
	// validation date/rue/commune sur event
1824
	$( '#releve-date,#rue,#commune-nom' ).on( 'change input focusout', this.dateRueCommuneFormValidator.bind( this ) );
1825
	$( '#form-arbre' ).validate({
1826
		rules : {
1827
			taxon : {
1828
				required : true,
1829
				minlength : 1
1830
			},
1831
			certitude : {
1832
				required : true,
1833
				minlength : 1
1834
			},
1835
			'latitude-arbres' : {
1836
				required : true,
1837
				minlength : 1,
1838
				range : [-90, 90]
1839
			},
1840
			'longitude-arbres' : {
1841
				required : true,
1842
				minlength : 1,
1843
				range : [-180, 180]
1844
			},
1845
			'rue-arbres' : {
1846
				required : true,
1847
				minlength : 1
1848
			}
1849
		}
1850
	});
1851
	$( '#form-arbre-fs' ).validate({
1852
		onkeyup : false,
1853
		onclick : false,
1854
		rules : {
1855
			circonference : {
1856
				required : true,
1857
				minlength : 1//,
1858
				//'minMaxOk' : true
1859
			},
1860
			'surface-pied' : {
1861
				required : true,
1862
				minlength : 1,
1863
				'minMaxOk' : true
1864
			},
1865
			'equipement-pied-arbre' : {
1866
				required : true,
1867
				minlength : 1
1868
			},
1869
			'face-ombre' : {
1870
				required : true,
1871
				minlength : 1
1872
			}
1873
		}
1874
	});
1875
	$( '#equipement-pied-arbre' ).change( function() {
1876
		if ( lthis.utils.valOk( $( this ).val(), false, 'other' ) ) {
1877
			$( this )
1878
				.closest( '.control-group' )
1879
					.removeClass( 'error' )
1880
					.find( 'span.error' )
1881
						.addClass( 'hidden' );
1882
		}
1883
	});
1884
	$( '#form-observateur' ).validate({
1885
		rules : {
1886
			courriel : {
1887
				required : true,
1888
				minlength : 1,
1889
				email : true,
1890
				'userEmailOk' : true
1891
			},
1892
			mdp : {
1893
				required : true,
1894
				minlength : 1
1895
			}
1896
		}
1897
	});
1898
	$( '#face-ombre input' ).click( function() {
1899
		var oneIsChecked = false;
1900
		$( '#face-ombre input' ).each( function() {
1901
			if ( $( this ).is( ':checked' ) ) {
1902
				oneIsChecked = true;
1903
				return false;
1904
			}
1905
		});
1906
		if ( oneIsChecked ) {
1907
			$( '#face-ombre.control-group' )
1908
				.removeClass( 'error' )
1909
				.find( 'span.error' )
1910
					.addClass( 'hidden' );
1911
		} else {
1912
			$( '#face-ombre.control-group' )
1913
				.addClass( 'error' )
1914
				.find( 'span.error' )
1915
					.removeClass( 'hidden' );
1916
		}
1917
	});
1918
	$( '#connexion,#inscription,#oublie' ).click( function() {
1919
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
1920
	});
1921
};
1922
 
1923
/**
1924
 * Valide le formulaire Relevé (= étape 1) au click sur un bouton "enregistrer"
1925
 */
1926
ReleveApa.prototype.validerReleve = function() {
1927
	const observateur = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() )
1928
	const obs         = $( '#form-observation' ).valid();
1929
	const geoloc      = (
1930
		this.utils.valOk( $( '#latitude' ).val() ) &&
1931
		this.utils.valOk( $( '#longitude' ).val() ) &&
1932
		this.utils.valOk( $( '#rue' ).val() ) &&
1933
		this.utils.valOk( $( '#commune-nom' ).val() )
1934
	) ;
1935
	var dateRue = true;
1936
	if ( this.utils.valOk( $( '#dates-rues-communes' ).val() ) ) {
1937
		dateRue = (
1938
			this.utils.valOk( $( '#releve-date' ).val() ) &&
1939
			this.utils.valOk( $( '#rue' ).val() ) &&
1940
			this.validerDateRueCommune( $( '#releve-date' ).val(), $( '#rue' ).val(), $( '#commune-nom' ).val() )
1941
		);
1942
	}
1943
	const validerReleve = ( observateur && obs && geoloc && dateRue );
1944
 
1945
	if ( !obs ) {
1946
		$( 'html, body' ).stop().animate({
1947
			scrollTop: $( '#zone-observation' ).offset().top
1948
		}, 300 );
1949
	}
1950
	// panneau observateur
1951
	if ( observateur ) {
1952
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
1953
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
1954
	} else {
1955
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
1956
		$( '#tb-observateur .control-group' ).addClass( 'error' );
1957
	}
1958
	if ( dateRue && geoloc ) {
1959
		this.masquerPanneau( '#dialogue-date-rue-ko' );
1960
		$( '#geoloc-datas' ).closest( '.control-group' ).removeClass( 'error' );
1961
	} else {
1962
		if (
1963
			this.utils.valOk( $( '#releve-date' ).val() ) &&
1964
			this.utils.valOk( $( '#rue' ).val() ) &&
1965
			this.utils.valOk( $( '#dates-rues-communes' ).val() )
1966
		) {
1967
			this.afficherPanneau( '#dialogue-date-rue-ko' );
1968
		}
1969
		$( '#geoloc-datas' ).closest( '.control-group' ).addClass( 'error' );
1970
	}
1971
	if (
1972
		!this.utils.valOk( $( '#releve-date' ).val() ) ||
1973
		!this.utils.valOk( $( '#rue' ).val() ) ||
1974
		!this.utils.valOk( $( '#dates-rues-communes' ).val() )
1975
	) {
1976
		this.masquerPanneau( '#dialogue-date-rue-ko' );
1977
	}
1978
	if ( geoloc ) {
1979
		this.masquerPanneau( '#dialogue-geoloc-ko' );
1980
		if ( dateRue ) {
1981
			$( '.geoloc' ).closest( '.control-group' ).removeClass( 'error' );
1982
		}
1983
	} else {
1984
		this.afficherPanneau( '#dialogue-geoloc-ko' );
1985
		$( '.geoloc' ).closest( '.control-group' ).addClass( 'error' );
1986
	}
1987
 
1988
	return validerReleve;
1989
};
1990
 
1991
/**
1992
 * Valide le formulaire Arbres (= étape 2) au click sur un bouton "suivant"
1993
 */
1994
ReleveApa.prototype.validerArbres = function( etapeReleve = false ) {
1995
	const observateur = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() )
1996
	const geoloc      = (
1997
		this.utils.valOk( $( '#latitude-arbres' ).val() ) &&
1998
		this.utils.valOk( $( '#longitude-arbres' ).val() ) &&
1999
		this.utils.valOk( $( '#rue-arbres' ).val() ) &&
2000
		this.utils.valOk( $( '#commune-nom-arbres' ).val() )
2001
	);
2002
	const piedArbre = this.utils.valOk( $( '#equipement-pied-arbre' ).val(), false, 'other' );
2003
	const taxon = this.utils.valOk( $( '#taxon' ).val() );
2004
	const obs   = (
2005
		$( '#form-observation' ).valid() &&
2006
		$( '#form-arbre' ).valid() &&
2007
		$( '#form-arbre-fs' ).valid() &&
2008
		piedArbre
2009
	);
2010
 
2011
	if ( piedArbre ) {
2012
		$( '#equipement-pied-arbre' )
2013
			.closest( '.control-group' )
2014
				.removeClass( 'error' )
2015
				.find( 'span.error' )
2016
					.addClass( 'hidden' );
2017
	} else {
2018
		$( '#equipement-pied-arbre' )
2019
			.closest( '.control-group' )
2020
				.addClass( 'error' )
2021
				.find( 'span.error' )
2022
					.removeClass( 'hidden' );
2023
	}
2024
	if ( geoloc ) {
2025
		this.masquerPanneau( '#dialogue-geoloc-ko' );
2026
		$( '.geoloc' ).closest( '.control-group' ).removeClass( 'error' );
2027
	} else {
2028
		this.afficherPanneau( '#dialogue-geoloc-ko' );
2029
		$( '.geoloc' ).closest( '.control-group' ).addClass( 'error' );
2030
	}
2031
	// panneau observateur
2032
	if ( observateur ) {
2033
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
2034
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
2035
	} else {
2036
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
2037
		$( '#tb-observateur .control-group' ).addClass( 'error' );
2038
	}
2039
 
2040
	return ( observateur && obs && geoloc && taxon );
2041
};
2042
 
2043
// Controle des panneaux d'infos **********************************************/
2044
 
2045
ReleveApa.prototype.afficherPanneau = function( selecteur ) {
2046
	$( selecteur )
2047
		.removeClass( 'hidden' )
2048
		.hide()
2049
		.show( 600 )
2050
		.delay( this.dureeMessage )
2051
		.hide( 600 );
2052
	$( 'html, body' ).stop().animate({scrollTop: $( selecteur ).offset().top}, 300);
2053
};
2054
 
2055
ReleveApa.prototype.masquerPanneau = function( selecteur ) {
2056
	$( selecteur ).addClass( 'hidden' );
2057
};
2058
 
2059
ReleveApa.prototype.fermerPanneauAlert = function() {
2060
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
2061
};
2062
 
2063
// lib hors objet --
2064
 
2065
/**
2066
* Stope l'évènement courant quand on clique sur un lien.
2067
* Utile pour Chrome, Safari...
2068
*/
2069
function arreter( event ) {
2070
	if ( event.stopPropagation ) {
2071
		event.stopPropagation();
2072
	}
2073
	if ( event.preventDefault ) {
2074
		event.preventDefault();
2075
	}
2076
 
2077
	return false;
2078
}
2079
 
2080
/**
2081
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
2082
 * @param jqXHR
2083
 * @returns {String}
2084
 */
2085
function extraireEnteteDebug( jqXHR ) {
2086
	var msgDebug = '';
2087
 
2088
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
2089
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
2090
		if ( null !== debugInfos ) {
2091
			$.each( debugInfos, function( cle, valeur ) {
2092
				msgDebug += valeur + '\n';
2093
			});
2094
		}
2095
	}
2096
 
2097
	return msgDebug;
2098
}
2099
 
2100
/*
2101
 * jQuery UI Autocomplete HTML Extension
2102
 *
2103
 * Copyright 2010, Scott González (http://scottgonzalez.com)
2104
 * Dual licensed under the MIT or GPL Version 2 licenses.
2105
 *
2106
 * http://github.com/scottgonzalez/jquery-ui-extensions
2107
 *
2108
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
2109
 */
2110
( function( $ ) {
2111
	var proto      = $.ui.autocomplete.prototype,
2112
		initSource = proto._initSource;
2113
 
2114
	ReleveApa.prototype.filter = function( array, term ) {
2115
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
2116
 
2117
		return $.grep( array, function( value ) {
2118
 
2119
			return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
2120
		});
2121
	}
2122
	$.extend( proto, {
2123
		_initSource: function() {
2124
			if ( this.options.html && $.isArray( this.options.source ) ) {
2125
				this.source = function( request, response ) {
2126
					response( filter( this.options.source, request.term ) );
2127
				};
2128
			} else {
2129
				initSource.call( this );
2130
			}
2131
		},
2132
		_renderItem: function( ul, item) {
2133
			if ( item.retenu ) {
2134
				item.label = '<strong>' + item.label + '</strong>';
2135
			}
2136
 
2137
			return $( '<li></li>' )
2138
				.data( 'item.autocomplete', item )
2139
				.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
2140
				.appendTo( ul );
2141
		}
2142
	});
2143
})( jQuery );