Subversion Repositories eFlore/Applications.cel

Rev

Rev 3381 | 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
3383 idir 611
		$( '#zone-arbres' ).on( 'submit blur click focus mousedown mouseleave mouseup change', '#tb-geolocation-arbres *', 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' );
3383 idir 1333
		// reset carto
1334
		$( '#tb-geolocation-arbres' ).remove();
1335
		$( '#geoloc-arbres' ).append(
1336
			'<tb-geolocation-element'+
1337
				' id="tb-geolocation-arbres"'+
1338
				' layer="google hybrid"'+
1339
				' zoom_init="20"'+
1340
				' lat_init="' + $( '#latitude' ).val() + '"'+
1341
				' lng_init="' + $( '#longitude' ).val() + '"'+
1342
				' marker="true"'+
1343
				' polyline="false"'+
1344
				' polygon="false"'+
1345
				' show_lat_lng_elevation_inputs="true"'+
1346
				' osm_class_filter=""'+
1347
				' elevation_provider="mapquest"'+
1348
				' map_quest_api_key="mG6oU5clZHRHrOSnAV0QboFI7ahnGg34"'+
1349
			'>'+
1350
			'</tb-geolocation-element>'
1351
		);
1352
		$( '#tb-geolocation-arbres' ).on( 'location', this.locationArbresHandler.bind( this ) );
3312 idir 1353
		// retour aux valeurs par defaut
1354
		$( '#equipement-pied-arbre .other' ).text( 'Autre' ).val( 'other' );
1355
		$(
1356
			'#certitude option,'+
1357
			'#equipement-pied-arbre option,'+
1358
			'#tassement option'
1359
		).each( function() {
1360
			if ( $( this ).hasClass( 'choisir' ) ) {
1361
				$( this ).prop( 'selected', true );
1362
			} else {
1363
				$( this ).prop( 'selected', false );
1364
			}
1365
		});
3368 idir 1366
		$('#collect-other-equipement-pied-arbre').closest('.control-group').remove();
3312 idir 1367
		this.supprimerMiniatures();
1368
		$( '#dejections,#face-ombre' ).find( 'input' ).prop( 'checked', false );
1369
		$(
1370
			'#circonference,'+
1371
			'#surface-pied,'+
1372
			'#com-arbres,'+
1373
			'#rue-arbres,'+
1374
			'#latitude-arbres,'+
1375
			'#longitude-arbres,'+
1376
			'#certitude,'+
1377
			'#equipement-pied-arbre,'+
1378
			'#tassement'
1379
		).val( '' );
3333 idir 1380
		if( 0 < numArbre ) {
1381
			$( '#arbre-nb' ).text( numArbre );
1382
			$( '#arbre-info-lien-' + numArbre ).addClass( 'disabled' );
1383
			$( '.arbre-info' ).not( '#arbre-info-lien-' + numArbre ).removeClass( 'disabled' );
1384
		}
3312 idir 1385
	}
1386
};
1387
 
1388
ReleveApa.prototype.defilerMiniatures = function( element ) {
1389
	var miniatureSelectionne  = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
1390
 
1391
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
1392
	miniatureSelectionne.addClass( 'miniature-cachee' );
1393
 
1394
	var miniatureAffichee     = miniatureSelectionne;
1395
 
1396
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
1397
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
1398
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
1399
		} else {
1400
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
1401
		}
1402
	} else {
1403
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
1404
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
1405
		} else {
1406
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
1407
		}
1408
	}
1409
	miniatureAffichee.addClass( 'miniature-selectionnee' );
1410
	miniatureAffichee.removeClass( 'miniature-cachee' );
1411
};
1412
 
1413
ReleveApa.prototype.supprimerObs = function( selector ) {
1414
	var obsId = $( selector ).val();
1415
 
1416
	// Problème avec IE 6 et 7
1417
	if ( 'Supprimer' === obsId ) {
1418
		obsId = $( selector ).attr( 'title' );
1419
	}
1420
	this.supprimerObsParId( obsId );
1421
};
1422
 
1423
/**
1424
 * Supprime l'obs et les data de l'obs
1425
 * et remonte les suivantes d'un cran
1426
 */
1427
ReleveApa.prototype.supprimerObsParId = function( obsId, transmission = false ) {
1428
	if ( !transmission ) {
1429
		this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1430
		this.releveData.splice( obsId , 1 );
1431
		$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1432
	}
1433
	$( '#arbre-info-' + ( this.numArbre ) ).remove();
1434
	$( '#arbre-nb' ).text( this.numArbre );
1435
 
1436
	this.obsNbre  -= 1;
1437
	this.numArbre -= 1;
1438
	$( '.obs-nbre' ).text( this.obsNbre );
1439
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1440
	$( '.obs' + obsId ).remove();
1441
 
1442
	obsId = parseInt(obsId);
1443
	var listObsData = $( '#liste-obs' ).data(),
1444
		exId        = 0,
1445
		indexObs    = '',
1446
		exIndexObs  = '',
3333 idir 1447
		arbreExId   = 0,
1448
		arbreId     = 0;
3312 idir 1449
 
1450
	for ( var id = obsId; id <= ( this.obsNbre + 1 ); id++ ) {
1451
		exId       = parseInt(id) + 1;
1452
		indexObs   = 'obsId' + id;
1453
		exIndexObs = 'obsId' + exId;
1454
		arbreExId  = parseInt( $( '#obs-arbre-' + exId ).data( 'arbre' ) );
1455
		arbreId    = arbreExId - 1;
1456
		$( '#liste-obs' ).removeData( indexObs );
1457
		if ( this.utils.valOk( listObsData[ exIndexObs ] ) ) {
1458
			$( '#liste-obs' ).data( indexObs, listObsData[ exIndexObs ] );
1459
		}
1460
		$( '#obs' + exId )
1461
			.attr( 'id', 'obs' + id )
1462
			.removeClass( 'obs' + exId )
1463
			.addClass( 'obs' + id )
1464
			.find( '.supprimer-obs' )
1465
				.attr( 'title', 'Observation n°' + id )
1466
				.val( id );
1467
		$( '#obs-arbre-' + arbreExId )
1468
			.attr( 'id', 'obs-arbre-' + arbreId )
1469
			.attr( 'data-arbre', arbreId )
1470
			.data( 'arbre', arbreId )
1471
			.text( 'Arbre ' + arbreId );
1472
 
1473
		if ( parseInt( id ) !== this.obsNbre ) {
1474
			id = parseInt(id);
1475
		}
1476
	}
1477
};
1478
 
1479
/*
1480
 * Actualise l'id_observation ( id de l'obs en bdd )
1481
 * à partir des données renvoyées par le service après transfert
1482
 */
1483
ReleveApa.prototype.actualiserReleveDataIdObs = function( obsId, id_observation ) {
1484
	this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1485
	this.releveData[obsId ]['id_observation'] = id_observation;
1486
	$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1487
};
1488
 
1489
ReleveApa.prototype.transmettreObs = function() {
1490
	const lthis = this;
1491
	var observations = $( '#liste-obs' ).data();
1492
 
1493
	if ( this.debug ) {
1494
		console.log( observations );
1495
	}
1496
	if ( !this.utils.valOk( typeof observations, true, 'object' ) ) {
1497
		this.afficherPanneau( '#dialogue-zero-obs' );
1498
	} else {
1499
		$( window ).on( 'beforeunload', function( event ) {
1500
			return lthis.utils.msgTraduction( 'rechargement-page' );
1501
		});
1502
		this.nbObsEnCours         = 1;
1503
		this.nbObsTransmises      = 0;
1504
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
1505
			return i;
1506
		}).length;
1507
		this.depilerObsPourEnvoi();
1508
	}
1509
 
1510
	return false;
1511
};
1512
 
1513
ReleveApa.prototype.depilerObsPourEnvoi = function() {
1514
	var observations = $( '#liste-obs' ).data();
1515
 
1516
	// la boucle est factice car on utilise un tableau
1517
	// dont on a besoin de n'extraire que le premier élément
1518
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1519
	// TODO: utiliser var.keys quand ça sera plus répandu
1520
	// ou bien utiliser un vrai tableau et pas un objet
1521
	for ( var obsNum in observations ) {
1522
		var obsATransmettre = {
1523
			'projet'  : this.tagProjet,
1524
			'tag-obs' : this.tagObs,
1525
			'tag-img' : this.tagImg
1526
		};
1527
		var utilisateur = {
1528
			id_utilisateur : this.infosUtilisateur.id,
1529
			prenom         : this.infosUtilisateur.prenom,
1530
			nom            : this.infosUtilisateur.nom,
1531
			courriel       : $( '#courriel' ).val()
1532
		};
1533
 
1534
		obsATransmettre['utilisateur'] = utilisateur;
1535
		obsATransmettre[obsNum]        = observations[obsNum];
1536
 
1537
		var idObsNumerique = obsNum.replace( 'obsId', '' );
1538
 
1539
		if( '' !== idObsNumerique ) {
1540
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
1541
		}
1542
		break;
1543
	}
1544
};
1545
 
1546
ReleveApa.prototype.envoyerObsAuCel = function( idObs, observation ) {
1547
	const lthis     = this;
1548
	var erreurMsg = '';
1549
 
1550
	$.ajax({
1551
		url        : lthis.serviceSaisieUrl,
1552
		type       : 'POST',
1553
		data       : observation,
1554
		dataType   : 'json',
1555
		beforeSend : function() {
1556
			$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
1557
			$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1558
			$( '.alert-txt' ).empty();
1559
			$( '.alert-txt .msg-erreur' ).remove();
1560
			$( '.alert-txt .msg-debug' ).remove();
1561
			$( '#chargement' ).removeClass( 'hidden' );
1562
		},
1563
		success    : function( transfertDatas, textStatus, jqXHR ) {
1564
			// actualisation de id_observation dans '#releve-data'
1565
			lthis.actualiserReleveDataIdObs( idObs, transfertDatas.id );
1566
			// mise à jour du nombre d'obs à transmettre
1567
			// et suppression de l'obs
1568
			lthis.supprimerObsParId( idObs, true );
1569
			lthis.nbObsEnCours++;
1570
			// mise à jour du statut
1571
			lthis.mettreAJourProgression();
1572
			if( 0 < lthis.obsNbre ) {
1573
				// dépilement de la suivante
1574
				lthis.depilerObsPourEnvoi();
1575
			}
1576
		},
1577
		statusCode  : {
1578
			500 : function( jqXHR, textStatus, errorThrown ) {
1579
				erreurMsg += lthis.utils.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1580
				}
1581
		},
1582
		error        : function( jqXHR, textStatus, errorThrown ) {
1583
			erreurMsg += lthis.utils.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1584
			try {
1585
				reponse = jQuery.parseJSON( jqXHR.responseText );
1586
				if ( null !== reponse ) {
1587
					$.each( reponse, function( cle, valeur ) {
1588
						erreurMsg += valeur + '\n';
1589
					});
1590
				}
1591
			} catch( e ) {
1592
				erreurMsg += lthis.utils.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
1593
			}
1594
		},
1595
		complete      : function( jqXHR, textStatus ) {
1596
			var debugMsg = extraireEnteteDebug( jqXHR );
1597
 
1598
			if ( '' !== erreurMsg ) {
1599
				if ( lthis.debug ) {
1600
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
1601
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1602
				}
1603
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1604
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagProjet+
1605
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
1606
 
1607
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
1608
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
1609
				// window.location.hash = 'obs' + idObs;
1610
 
1611
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
1612
					$( '#tpl-transmission-ko' ).clone()
1613
						.find( '.courriel-erreur' )
1614
						.attr( 'href', hrefCourriel )
1615
						.end()
1616
						.html()
1617
				);
1618
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
1619
				$( '#chargement' ).addClass( 'hidden' );
1620
				lthis.initialiserBarreProgression;
1621
			} else {
1622
				if ( lthis.debug ) {
1623
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1624
				}
1625
				if( 0 === lthis.obsNbre ) {
1626
					setTimeout( function() {
1627
						$( '#chargement,#bloc-arbres-gauche,#bloc-controle-liste-obs' ).addClass( 'hidden' );
1628
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
1629
						$( '#dialogue-obs-transaction-ok,#bouton-saisir-plantes,#bouton-saisir-lichens' ).removeClass( 'hidden' );
1630
					}, 1500 );
1631
				}
1632
			}
1633
		}
1634
	});
1635
};
1636
 
1637
ReleveApa.prototype.mettreAJourProgression = function() {
1638
	this.nbObsTransmises++;
1639
 
1640
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
1641
 
1642
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
1643
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
1644
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.utils.msgTraduction( 'observations-transmises' ) );
1645
	if( 0 === this.obsNbre ) {
1646
		$( '.progress' ).removeClass( 'active' );
1647
		$( '.progress' ).removeClass( 'progress-bar-striped' );
1648
	}
1649
};
1650
 
1651
ReleveApa.prototype.initialiserBarreProgression = function() {
1652
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
1653
	$( '#barre-progression-upload' ).css( 'width', '0%' );
1654
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.utils.msgTraduction( 'observations-transmises' ) );
1655
	$( '.progress' ).addClass( 'active' );
1656
	$( '.progress' ).addClass( 'progress-bar-striped' );
1657
};
1658
 
1659
// Form Validator *************************************************************/
1660
ReleveApa.prototype.configurerFormValidator = function() {
1661
	const lthis = this;
1662
 
1663
	$.validator.addMethod(
1664
		'dateCel',
1665
		function ( value, element ) {
1666
			return ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) );
1667
		},
1668
		lthis.utils.msgTraduction( 'date-incomplete' )
1669
	);
1670
 
1671
	$.validator.addMethod(
1672
		'userEmailOk',
1673
		function ( value, element ) {
1674
			return ( lthis.utils.valOk( value ) );
1675
		},
1676
		''
1677
	);
1678
	$.validator.addMethod(
1679
		'minMaxOk',
1680
		function ( value, element, param ) {
1681
			$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message;
1682
			return lthis.validerMinMax( element ).cond;
1683
		},
1684
		$.validator.messages.minMaxOk
1685
	);
1686
 
1687
	$.extend( $.validator.defaults, {
1688
		errorElement: 'span',
1689
		errorPlacement: function( error, element ) {
1690
			if ( 'checkbox' === element.attr( 'type' ) || 'radio' === element.attr( 'type' ) ) {
1691
				error.appendTo( element.closest( '.list' ) );
1692
			} else {
1693
				element.after( error );
1694
			}
1695
		},
1696
		onfocusout: function( element ) {
1697
			if ( $( element ).valid() ) {
1698
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1699
			} else {
1700
				$( element ).closest( '.control-group' ).addClass( 'error' );
1701
			}
1702
		},
1703
		onkeyup : function( element ) {
1704
			if ( $( element ).valid() ) {
1705
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1706
			} else {
1707
				$( element ).closest( '.control-group' ).addClass( 'error' );
1708
			}
1709
		},
1710
		unhighlight: function( element ) {
1711
			$( element ).closest( '.control-group' ).removeClass( 'error' );
1712
		},
1713
		highlight: function( element ) {
1714
			$( element ).closest( '.control-group' ).addClass( 'error' );
1715
		}
1716
	});
1717
};
1718
 
1719
ReleveApa.prototype.validerMinMax = function( element ) {
1720
	var mMCond      = new Boolean(),
1721
		minCond     = parseFloat( element.value ) >= parseFloat( element.min ),
1722
		maxCond     = parseFloat( element.value ) <= parseFloat( element.max ),
1723
		messageMnMx = 'La valeur entrée doit être',
1724
		returnMnMx  = { cond : true , message : '' };
1725
 
1726
	if (
1727
			( this.utils.valOk( element.type, true, 'number' ) || this.utils.valOk( element.type, true, 'range' ) ) &&
1728
			( this.utils.valOk( element.min ) || this.utils.valOk( element.max ) )
1729
		) {
1730
 
1731
		if ( element.min && element.max ) {
1732
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
1733
			mnMxCond     = ( minCond && maxCond );
1734
		} else if ( element.min ) {
1735
			messageMnMx += ' supérieure à ' + element.min;
1736
			mnMxCond     = minCond;
1737
		} else {
1738
			messageMnMx += ' inférieure à ' + element.max;
1739
			mnMxCond     = maxCond;
1740
		}
1741
		returnMnMx.cond    = mnMxCond;
1742
		returnMnMx.message = messageMnMx;
1743
	}
1744
 
1745
	return returnMnMx;
1746
};
1747
 
1748
/**
1749
 * Valider date/rue/commune par rapport aux relevés précédents
1750
 */
1751
ReleveApa.prototype.validerDateRueCommune = function( valeurDate, valeurRue, valeurCmn ) {
1752
	var valide = true;
1753
 
1754
	if (
1755
		this.utils.valOk( $( '#dates-rues-communes' ).val() ) &&
1756
		this.utils.valOk( valeurDate ) &&
1757
		this.utils.valOk( valeurRue ) &&
1758
		this.utils.valOk( valeurCmn )
1759
	) {
1760
		var valsEltDRC = $.parseJSON( $( '#dates-rues-communes' ).val() ),
1761
			valeurDRC = valeurDate + valeurRue + valeurCmn;
1762
		valide = ( -1 === valsEltDRC.indexOf( valeurDRC ) );
1763
 
1764
	}
1765
	return valide;
1766
};
1767
 
1768
/**
1769
 * FormValidator pour les champs date/rue/Commune
1770
 */
1771
ReleveApa.prototype.dateRueCommuneFormValidator = function() {
1772
	var dateValid    = ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( $( '#releve-date' ).val() ) ),
1773
		geolocValid  = ( this.utils.valOk( $( '#commune-nom' ).val() ) && this.utils.valOk( $( '#rue' ).val() ) );
1774
	const errorDateRue =
1775
			'<span id="error-drc" class="error">'+
1776
				this.utils.msgTraduction( 'date-rue' )+
1777
			'</span> ';
1778
 
1779
	if( this.validerDateRueCommune( $( '#releve-date' ).val(), $( '#rue' ).val(), $( '#commune-nom' ).val()  ) ) {
1780
		$( '#releve-date' )
1781
			.removeClass( 'erreur' )
1782
			.closest( '.control-group' )
1783
				.removeClass( 'error' )
1784
				.find( '#error-drc' )
1785
					.remove();
1786
		if ( geolocValid ) {
1787
			$( '#geoloc' )
1788
			.closest( '.control-group' )
1789
				.removeClass( 'error' );
1790
		}
1791
	} else {
1792
		$( '#releve-date' )
1793
			.addClass( 'erreur' )
1794
			.closest( '.control-group' )
1795
				.addClass( 'error' );
1796
		if ( !this.utils.valOk( $( '#releve-date' ).closest( '.control-group' ).find( '#error-drc' ) ) ) {
1797
			$( '#releve-date' ).after( errorDateRue );
1798
		}
1799
		$( '#geoloc' ).closest( '.control-group' ).addClass( 'error' );
1800
	}
1801
	if ( dateValid ) {
1802
		$( '#releve-date' ).closest( '.control-group span.error' ).not( '#error-drc' ).remove();
1803
	}
1804
};
1805
 
1806
ReleveApa.prototype.definirReglesFormValidator = function() {
1807
	const lthis = this;
1808
 
1809
	$( '#form-observation' ).validate({
1810
		rules : {
1811
			'zone-pietonne' : {
1812
				required : true,
1813
				minlength : 1
1814
			},
1815
			latitude : {
1816
				required : true,
1817
				minlength : 1,
1818
				range : [-90, 90]
1819
			},
1820
			longitude : {
1821
				required : true,
1822
				minlength : 1,
1823
				range : [-180, 180]
1824
			}
1825
		}
1826
	});
1827
	$( 'input[type=date]' ).not( '#releve-date' ).on( 'input', function() {
1828
		$( this ).valid();
1829
	});
1830
	// validation date/rue/commune au démarage
1831
	this.dateRueCommuneFormValidator();
1832
	// validation date/rue/commune sur event
1833
	$( '#releve-date,#rue,#commune-nom' ).on( 'change input focusout', this.dateRueCommuneFormValidator.bind( this ) );
1834
	$( '#form-arbre' ).validate({
1835
		rules : {
1836
			taxon : {
1837
				required : true,
1838
				minlength : 1
1839
			},
1840
			certitude : {
1841
				required : true,
1842
				minlength : 1
1843
			},
1844
			'latitude-arbres' : {
1845
				required : true,
1846
				minlength : 1,
1847
				range : [-90, 90]
1848
			},
1849
			'longitude-arbres' : {
1850
				required : true,
1851
				minlength : 1,
1852
				range : [-180, 180]
1853
			}
1854
		}
1855
	});
1856
	$( '#form-arbre-fs' ).validate({
1857
		onkeyup : false,
1858
		onclick : false,
1859
		rules : {
1860
			circonference : {
1861
				required : true,
1862
				minlength : 1//,
1863
				//'minMaxOk' : true
1864
			},
1865
			'surface-pied' : {
1866
				required : true,
1867
				minlength : 1,
1868
				'minMaxOk' : true
1869
			},
1870
			'equipement-pied-arbre' : {
1871
				required : true,
1872
				minlength : 1
1873
			},
1874
			'face-ombre' : {
1875
				required : true,
1876
				minlength : 1
1877
			}
1878
		}
1879
	});
1880
	$( '#equipement-pied-arbre' ).change( function() {
1881
		if ( lthis.utils.valOk( $( this ).val(), false, 'other' ) ) {
1882
			$( this )
1883
				.closest( '.control-group' )
1884
					.removeClass( 'error' )
1885
					.find( 'span.error' )
1886
						.addClass( 'hidden' );
1887
		}
1888
	});
1889
	$( '#form-observateur' ).validate({
1890
		rules : {
1891
			courriel : {
1892
				required : true,
1893
				minlength : 1,
1894
				email : true,
1895
				'userEmailOk' : true
1896
			},
1897
			mdp : {
1898
				required : true,
1899
				minlength : 1
1900
			}
1901
		}
1902
	});
1903
	$( '#face-ombre input' ).click( function() {
1904
		var oneIsChecked = false;
1905
		$( '#face-ombre input' ).each( function() {
1906
			if ( $( this ).is( ':checked' ) ) {
1907
				oneIsChecked = true;
1908
				return false;
1909
			}
1910
		});
1911
		if ( oneIsChecked ) {
1912
			$( '#face-ombre.control-group' )
1913
				.removeClass( 'error' )
1914
				.find( 'span.error' )
1915
					.addClass( 'hidden' );
1916
		} else {
1917
			$( '#face-ombre.control-group' )
1918
				.addClass( 'error' )
1919
				.find( 'span.error' )
1920
					.removeClass( 'hidden' );
1921
		}
1922
	});
1923
	$( '#connexion,#inscription,#oublie' ).click( function() {
1924
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
1925
	});
1926
};
1927
 
1928
/**
1929
 * Valide le formulaire Relevé (= étape 1) au click sur un bouton "enregistrer"
1930
 */
1931
ReleveApa.prototype.validerReleve = function() {
1932
	const observateur = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() )
1933
	const obs         = $( '#form-observation' ).valid();
1934
	const geoloc      = (
1935
		this.utils.valOk( $( '#latitude' ).val() ) &&
1936
		this.utils.valOk( $( '#longitude' ).val() ) &&
1937
		this.utils.valOk( $( '#rue' ).val() ) &&
1938
		this.utils.valOk( $( '#commune-nom' ).val() )
1939
	) ;
1940
	var dateRue = true;
1941
	if ( this.utils.valOk( $( '#dates-rues-communes' ).val() ) ) {
1942
		dateRue = (
1943
			this.utils.valOk( $( '#releve-date' ).val() ) &&
1944
			this.utils.valOk( $( '#rue' ).val() ) &&
1945
			this.validerDateRueCommune( $( '#releve-date' ).val(), $( '#rue' ).val(), $( '#commune-nom' ).val() )
1946
		);
1947
	}
1948
	if ( !obs ) {
1949
		$( 'html, body' ).stop().animate({
1950
			scrollTop: $( '#zone-observation' ).offset().top
1951
		}, 300 );
1952
	}
1953
	// panneau observateur
1954
	if ( observateur ) {
1955
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
1956
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
1957
	} else {
1958
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
1959
		$( '#tb-observateur .control-group' ).addClass( 'error' );
1960
	}
1961
	if ( dateRue && geoloc ) {
1962
		this.masquerPanneau( '#dialogue-date-rue-ko' );
1963
		$( '#geoloc-datas' ).closest( '.control-group' ).removeClass( 'error' );
1964
	} else {
1965
		if (
1966
			this.utils.valOk( $( '#releve-date' ).val() ) &&
1967
			this.utils.valOk( $( '#rue' ).val() ) &&
1968
			this.utils.valOk( $( '#dates-rues-communes' ).val() )
1969
		) {
1970
			this.afficherPanneau( '#dialogue-date-rue-ko' );
1971
		}
1972
		$( '#geoloc-datas' ).closest( '.control-group' ).addClass( 'error' );
1973
	}
1974
	if (
1975
		!this.utils.valOk( $( '#releve-date' ).val() ) ||
1976
		!this.utils.valOk( $( '#rue' ).val() ) ||
1977
		!this.utils.valOk( $( '#dates-rues-communes' ).val() )
1978
	) {
1979
		this.masquerPanneau( '#dialogue-date-rue-ko' );
1980
	}
1981
	if ( geoloc ) {
1982
		this.masquerPanneau( '#dialogue-geoloc-ko' );
1983
		if ( dateRue ) {
3322 idir 1984
			$( '#geoloc' ).closest( '.control-group' ).removeClass( 'error' );
3312 idir 1985
		}
1986
	} else {
1987
		this.afficherPanneau( '#dialogue-geoloc-ko' );
3322 idir 1988
		$( '#geoloc' ).closest( '.control-group' ).addClass( 'error' );
3312 idir 1989
	}
1990
 
3322 idir 1991
	return  (observateur && obs && geoloc && dateRue);
3312 idir 1992
};
1993
 
1994
/**
1995
 * Valide le formulaire Arbres (= étape 2) au click sur un bouton "suivant"
1996
 */
3322 idir 1997
ReleveApa.prototype.validerArbres = function() {
1998
	const validerReleve = this.validerReleve();
3312 idir 1999
	const geoloc      = (
2000
		this.utils.valOk( $( '#latitude-arbres' ).val() ) &&
3322 idir 2001
		this.utils.valOk( $( '#longitude-arbres' ).val() )
3312 idir 2002
	);
2003
	const piedArbre = this.utils.valOk( $( '#equipement-pied-arbre' ).val(), false, 'other' );
2004
	const taxon = this.utils.valOk( $( '#taxon' ).val() );
2005
	const obs   = (
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' );
3322 idir 2026
		$( '#geoloc-arbres' ).closest( '.control-group' ).removeClass( 'error' );
3312 idir 2027
	} else {
2028
		this.afficherPanneau( '#dialogue-geoloc-ko' );
3322 idir 2029
		$( '#geoloc-arbres' ).closest( '.control-group' ).addClass( 'error' );
3312 idir 2030
	}
2031
 
3322 idir 2032
	return ( validerReleve && obs && geoloc && taxon );
3312 idir 2033
};
2034
 
2035
// Controle des panneaux d'infos **********************************************/
2036
 
2037
ReleveApa.prototype.afficherPanneau = function( selecteur ) {
2038
	$( selecteur )
2039
		.removeClass( 'hidden' )
2040
		.hide()
2041
		.show( 600 )
2042
		.delay( this.dureeMessage )
2043
		.hide( 600 );
2044
	$( 'html, body' ).stop().animate({scrollTop: $( selecteur ).offset().top}, 300);
2045
};
2046
 
2047
ReleveApa.prototype.masquerPanneau = function( selecteur ) {
2048
	$( selecteur ).addClass( 'hidden' );
2049
};
2050
 
2051
ReleveApa.prototype.fermerPanneauAlert = function() {
2052
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
2053
};
2054
 
2055
// lib hors objet --
2056
 
2057
/**
2058
* Stope l'évènement courant quand on clique sur un lien.
2059
* Utile pour Chrome, Safari...
2060
*/
2061
function arreter( event ) {
2062
	if ( event.stopPropagation ) {
2063
		event.stopPropagation();
2064
	}
2065
	if ( event.preventDefault ) {
2066
		event.preventDefault();
2067
	}
2068
 
2069
	return false;
2070
}
2071
 
2072
/**
2073
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
2074
 * @param jqXHR
2075
 * @returns {String}
2076
 */
2077
function extraireEnteteDebug( jqXHR ) {
2078
	var msgDebug = '';
2079
 
2080
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
2081
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
2082
		if ( null !== debugInfos ) {
2083
			$.each( debugInfos, function( cle, valeur ) {
2084
				msgDebug += valeur + '\n';
2085
			});
2086
		}
2087
	}
2088
 
2089
	return msgDebug;
2090
}
2091
 
2092
/*
2093
 * jQuery UI Autocomplete HTML Extension
2094
 *
2095
 * Copyright 2010, Scott González (http://scottgonzalez.com)
2096
 * Dual licensed under the MIT or GPL Version 2 licenses.
2097
 *
2098
 * http://github.com/scottgonzalez/jquery-ui-extensions
2099
 *
2100
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
2101
 */
2102
( function( $ ) {
2103
	var proto      = $.ui.autocomplete.prototype,
2104
		initSource = proto._initSource;
2105
 
2106
	ReleveApa.prototype.filter = function( array, term ) {
2107
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
2108
 
2109
		return $.grep( array, function( value ) {
2110
 
2111
			return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
2112
		});
2113
	}
2114
	$.extend( proto, {
2115
		_initSource: function() {
2116
			if ( this.options.html && $.isArray( this.options.source ) ) {
2117
				this.source = function( request, response ) {
2118
					response( filter( this.options.source, request.term ) );
2119
				};
2120
			} else {
2121
				initSource.call( this );
2122
			}
2123
		},
2124
		_renderItem: function( ul, item) {
2125
			if ( item.retenu ) {
2126
				item.label = '<strong>' + item.label + '</strong>';
2127
			}
2128
 
2129
			return $( '<li></li>' )
2130
				.data( 'item.autocomplete', item )
2131
				.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
2132
				.appendTo( ul );
2133
		}
2134
	});
2135
})( jQuery );