Subversion Repositories eFlore/Applications.cel

Rev

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

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