Subversion Repositories eFlore/Applications.cel

Rev

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