Subversion Repositories eFlore/Applications.cel

Rev

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