Subversion Repositories eFlore/Applications.cel

Rev

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