Subversion Repositories eFlore/Applications.cel

Rev

Rev 3318 | Rev 3326 | 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
 */
3324 idir 675
ReleveApa.prototype.locationHandler = function( location ) {
3318 idir 676
	var locDatas     = location.originalEvent.detail;
677
 
678
	if ( this.utils.valOk( locDatas ) ) {
3324 idir 679
		console.log( locDatas );
3318 idir 680
		var rue          = ( this.utils.valOk( locDatas.osmRoad ) ) ? locDatas.osmRoad : '';
681
		var latitude     = ( this.utils.valOk( locDatas.geometry.coordinates[1] ) ) ? locDatas.geometry.coordinates[1] : '';
682
		var longitude    = ( this.utils.valOk( locDatas.geometry.coordinates[0] ) ) ? locDatas.geometry.coordinates[0] : '';
683
		var nomCommune   = '';
684
		var	communeInsee = '';
685
 
686
		if ( this.utils.valOk( locDatas.inseeData ) ) {
687
			nomCommune = locDatas.inseeData.nom;
688
			communeInsee = ( this.utils.valOk( locDatas.inseeData.code ) ) ? locDatas.inseeData.code : '';
689
		} else if ( this.utils.valOk( locDatas.locality ) ) {
690
			nomCommune = locDatas.locality;
691
		} else if ( this.utils.valOk( locDatas.locality ) ) {
692
			nomCommune = locDatas.osmCounty;
693
		}
694
 
695
		var altitude     = ( this.utils.valOk( locDatas.elevation ) ) ? locDatas.elevation : '';
696
		var pays         = ( this.utils.valOk( locDatas.osmCountryCode ) ) ? locDatas.osmCountryCode.toUpperCase() : 'FR';
697
 
3324 idir 698
		$( '#rue' ).val( rue );
699
		$( '#latitude' ).val( latitude );
700
		$( '#longitude' ).val( longitude );
701
		$( '#commune-nom' ).val( nomCommune );
702
		$( '#commune-insee' ).val( communeInsee );
703
		$( '#altitude' ).val( altitude );
704
		$( '#pays' ).val( pays );
705
		if ( this.utils.valOk( $( '#rue' ).val() ) && this.utils.valOk( $( '#commune-nom' ).val() ) ) {
706
			if( !this.utils.valOk( $( '#geoloc #error-drc' ) ) ) {
707
				$( '#geoloc' ).closest( '.control-group' ).removeClass( 'error' );
3318 idir 708
			}
709
			$( '#geoloc-error' ).addClass( 'hidden' );
710
		} else {
3324 idir 711
			$( '#geoloc' ).closest( '.control-group' ).addClass( 'error' );
3318 idir 712
			$( '#geoloc-error' ).removeClass( 'hidden' );
713
			$( '#releve-date' ).removeClass( 'erreur' ).closest( '.control-group' ).removeClass( 'error' ).find( '#error-drc' ).remove();
714
			$( '#geoloc #error-drc' ).remove();
715
		}
716
	} else {
717
		console.log( 'Error location' );
718
	}
719
}
720
 
721
/**
3324 idir 722
 * Fonction handler de l'évenement location du module tb-geoloc étape arbres
723
 */
724
ReleveApa.prototype.locationArbresHandler = function( location ) {
725
	var locDatas     = location.originalEvent.detail;
726
 
727
	if ( this.utils.valOk( locDatas ) ) {
728
		console.log( locDatas );
729
		var rue          = ( this.utils.valOk( locDatas.osmRoad ) ) ? locDatas.osmRoad : '';
730
		var latitude     = ( this.utils.valOk( locDatas.geometry.coordinates[1] ) ) ? locDatas.geometry.coordinates[1] : '';
731
		var longitude    = ( this.utils.valOk( locDatas.geometry.coordinates[0] ) ) ? locDatas.geometry.coordinates[0] : '';
732
		var altitude     = ( this.utils.valOk( locDatas.elevation ) ) ? locDatas.elevation : '';
733
 
734
		$( '#rue-arbres' ).val( rue );
735
		$( '#latitude-arbres' ).val( latitude );
736
		$( '#longitude-arbres' ).val( longitude );
737
		$( '#altitude-arbres' ).val( altitude );
738
		if ( this.utils.valOk( $( '#latitude-arbres' ).val() ) && this.utils.valOk( $( '#longitude-arbres' ).val() ) ) {
739
			$( '#geoloc-arbres' ).closest( '.control-group' ).removeClass( 'error' );
740
		} else {
741
			$( '#geoloc-arbres' ).closest( '.control-group' ).addClass( 'error' );
742
		}
743
	} else {
744
		console.log( 'Error location' );
745
	}
746
}
747
 
748
/**
3318 idir 749
 * Ajoute une observation à la liste des obs à transmettre
750
 * (résumé obs)
751
 */
752
ReleveStreets.prototype.ajouterObs = function() {
753
	// Fermeture automatique des dialogue de transmission de données
754
	// @WARNING TEST
755
	$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
756
	$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
757
	$( 'html, body' ).stop().animate({
758
		scrollTop: $( '#zone-arbres' ).offset().top
759
	}, 300);
760
 
761
	if ( this.validerArbres() ) {
762
		this.masquerPanneau( '#dialogue-form-invalide' );
763
		this.obsNbre  += 1;
764
		this.numArbre += 1;
765
		$( '.obs-nbre' ).text( this.obsNbre );
766
		$( '.obs-nbre' ).triggerHandler( 'changement' );
767
		// bouton info de cet arbre et affichage numéro du prochain arbre
768
		this.lienArbreInfo( this.numArbre );
769
		$( '#arbre-nb' ).text( this.numArbre + 1 );
770
		//formatage des données
771
		var obsData   = this.formaterFormObsData(),
772
			arbreData = obsData.arbre;
773
 
774
		// Résumé obs et stockage en data de "#list-obs" pour envoi
775
		this.afficherObs( obsData );
776
		this.stockerObsData( obsData );
777
		// Ajout de donnée utiles puis stockage dans input hidden "releve-data"
778
		arbreData['date_rue_commune']  = obsData.releve.date + obsData.releve.rue + obsData.releve['commune-nom'];
779
		arbreData['id_observation']    = 0;
780
		this.releveDatas               = $.parseJSON( $( '#releve-data' ).val() );
781
		this.releveDatas[this.obsNbre] = arbreData;
782
		$( '#releve-data' ).val( JSON.stringify( this.releveDatas ) );
783
 
784
		this.supprimerMiniatures();
785
		$( '#taxon' ).val( '' );
786
		$( '#taxon' ).data( 'numNomSel', '' )
787
			.data( 'nomRet','' )
788
			.data( 'numNomRet', '' )
789
			.data( 'nt', '' )
790
			.data( 'famille', '' );
791
		if( this.isTaxonListe ) {
792
			$( '#taxon-liste' ).find( 'option' ).each( function() {
793
				if ( $( this ).hasClass( 'choisir' ) ) {
794
					$( this ).attr( 'selected', true );
795
				} else {
796
					$( this ).attr( 'selected', false );
797
				}
798
			});
799
			$( '#taxon-input-groupe' ).addClass( 'hidden' );
800
			$('#taxon-autre').val('');
801
		}
802
		$( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre );
803
		$( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' ' + this.utils.msgTraduction( 'observations-transmises' ) );
804
	} else {
805
		this.afficherPanneau( '#dialogue-form-invalide' );
806
	}
807
};
808
 
809
/**
810
 * Formatage des données du formulaire pour stockage et envoi
811
 */
812
ReleveStreets.prototype.formaterFormObsData = function() {
813
	var miniatureImg  = [],
814
		imgB64        = [],
815
		imgNom        = [],
816
		numNomSel     = $( '#taxon' ).data( 'numNomSel' ),
817
		referentiel   = ( !this.utils.valOk( numNomSel ) ) ? 'autre' : 'bdtfx';
818
 
819
	$( '.miniature-img' ).each( function() {
820
		if ( $( this ).hasClass( 'b64' ) ) {
821
			imgB64 = $( this ).attr( 'src' );
822
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
823
			imgB64 = $( this ).data( 'b64' );
824
		}
825
		miniatureImg.push({
826
			'nom' : $( this ).attr( 'alt' ),
827
			'src' : $( this ).attr( 'src' ),
828
			'b64' : imgB64
829
		});
830
	});
831
	var obsData = {
832
		obsNum : this.obsNbre,
833
		arbre  : {
834
			'num-arbre'            : this.numArbre,
835
			'taxon'                : {
836
				'numNomSel' : numNomSel,
837
				'value'     : $( '#taxon' ).val(),
838
				'nomRet'    : $( '#taxon' ).data( 'nomRet' ),
839
				'numNomRet' : $( '#taxon' ).data( 'numNomRet' ),
840
				'nt'        : $( '#taxon' ).data( 'nt' ),
841
				'famille'   : $( '#taxon' ).data( 'famille' )
842
			},
843
			'referentiel'           : referentiel,
844
			'certitude'             : $( '#certitude' ).val(),
3324 idir 845
			'rue-arbres'            : $( '#rue-arbres' ).val(),
3318 idir 846
			'latitude-arbres'       : $( '#latitude-arbres' ).val(),
847
			'longitude-arbres'      : $( '#longitude-arbres' ).val(),
848
			'altitude-arbres'       : $( '#altitude-arbres' ).val(),
849
			'circonference'         : $( '#circonference' ).val(),
850
			'surface-pied'          : $( '#surface-pied' ).val(),
851
			'equipement-pied-arbre' : $( '#equipement-pied-arbre' ).val(),
852
			'tassement'             : $( '#tassement' ).val(),
853
			'dejections'            : $( '#dejections input:checked' ).val(),
854
			'com-arbres'            : $( '#com-arbres' ).val(),
855
			'miniature-img'         : miniatureImg,
856
		},
857
		releve : {
858
			'date'                  : this.utils.fournirDate( $( '#releve-date' ).val() ),
859
			'rue'                   : $( '#rue' ).val(),
3324 idir 860
			'latitude'              : $( '#latitude' ).val(),
861
			'longitude'             : $( '#longitude' ).val(),
3318 idir 862
			'commune-nom'           : $( '#commune-nom' ).val(),
863
			'commune-insee'         : $( '#commune-insee' ).val(),
864
			'altitude'              : $( '#altitude' ).val(),
3324 idir 865
			'pays'                  : $( '#pays' ).val(),
3318 idir 866
			'zone-pietonne'         : $( '#zone-pietonne input:checked' ).val(),
3324 idir 867
			'pres-lampadaires'      : $( '#pres-lampadaires input:checked' ).val(),
868
			'commentaires'          : $( '#commentaires' ).val()
3318 idir 869
		}
870
	};
871
	return obsData;
872
};
873
 
874
/**
875
 * Résumé obs
876
 */
877
ReleveStreets.prototype.afficherObs = function( datasObs ) {
878
	var obsNum            = datasObs.obsNum,
879
		numArbre          = datasObs.arbre['num-arbre'],
880
		dateObs           = this.utils.fournirDate( datasObs.releve.date ),
881
		numNomSel         = datasObs.arbre.taxon.numNomSel,
882
		taxon             = datasObs.arbre.taxon.value,
883
		certitude         = datasObs.arbre.certitude,
3324 idir 884
		rue               = datasObs.arbre['rue-arbres'],
3318 idir 885
		commune           = datasObs.releve['commune-nom'],
886
		latitudeLongitude = '[' + datasObs.arbre['latitude-arbres'] + ' / ' + datasObs.arbre['longitude-arbres'] + ']',
887
		miniatures        = this.ajouterImgMiniatureAuTransfert( datasObs.arbre['miniature-img'] ),
888
		commentaires      = '';
889
 
890
	if ( this.utils.valOk( datasObs.arbre['com-arbres'] ) ) {
891
		commentaires =
892
			this.utils.msgTraduction( 'commentaires' ) +
893
			' : <span>'+
894
				datasObs.arbre['com-arbres'] +
895
			'</span> ';
896
	}
897
 
898
	var responsivDiff1 = '',
899
		responsivDiff2 = '',
900
		responsivDiff3 = '',
901
		responsivDiff4 = '',
902
		responsivDiff5 = '',
903
		responsivDiff6 = '';
904
 
905
	if ( window.matchMedia( '(min-width: 576px)' ).matches ) {
906
		/* La largeur minimum de l'affichage est 600 px inclus */
907
		responsivDiff1 = ' droite';
908
		responsivDiff2 = '<div></div>';
909
		responsivDiff3 = '<div class="row">';
910
		responsivDiff4 = ' col-md-4 col-sm-5';
911
		responsivDiff5 = ' class="col-md-7 col-sm-6"';
912
		responsivDiff6 = '</div>';
913
	}
914
	$( '#liste-obs' ).prepend(
915
		'<div id="obs' + obsNum + '" class="obs obs' + obsNum + ' mb-2">'+
916
			'<div '+
917
				'class="obs-action" '+
918
				'title="' + this.utils.msgTraduction( 'supprimer-observation-liste' ) + '"'+
919
			'>'+
920
				'<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ obsNum + '" title="' + this.utils.msgTraduction( 'obs-numero' ) + obsNum + '">'+
921
				'<i class="far fa-trash-alt"></i>'+
922
				'</button>'+
923
				responsivDiff2 +
924
			'</div> '+
925
			responsivDiff3 +
926
				'<div class="thumbnail' + responsivDiff4 + '">'+
927
					miniatures+
928
				'</div>'+
929
				'<div' + responsivDiff5 + '>'+
930
					'<ul class="unstyled">'+
931
						'<li>'+
932
							'<span id="obs-arbre-' + numArbre + '" class="badge num-obs-arbre" data-arbre="' + numArbre + '">Arbre ' + numArbre + '</span>' +
933
							' <span class="nom-sci">' + taxon + '</span> '+
934
							' [certitude : ' + certitude + ']'+
935
							' '  + this.utils.msgTraduction( 'lieu-obs' ) +
936
							' ' + rue +
937
							', ' + commune +
938
							latitudeLongitude +
939
							' ' + this.utils.msgTraduction( 'obs-le' ) + ' ' +
940
							'<span class="date">' + this.utils.fournirDate( dateObs ) + '</span>'+
941
						'</li>'+
942
						'<li>'+
943
							commentaires +
944
						'</li>'+
945
					'</ul>'+
946
				'</div>'+
947
			responsivDiff6+
948
		'</div>'
949
	);
950
	$( '#zone-liste-obs' ).removeClass( 'hidden' );
951
};
952
 
953
/**
954
 * Ajoute une boîte de miniatures avec défilement des images,
955
 * pour une obs de la liste des obs à transmettre
956
 */
957
ReleveStreets.prototype.ajouterImgMiniatureAuTransfert = function( chargerImages ) {
958
	const lthis = this;
959
	var html         =
960
			'<div class="defilement-miniatures">'+
961
				'<figure class="centre">'+
962
					'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
963
				'</figure>'+
964
			'</div>',
965
		miniatures   = '',
966
		centre       = '',
967
		defilVisible = '',
968
		length       = 0;
969
 
970
	if ( this.utils.valOk( chargerImages ) || this.utils.valOk( $( '#miniatures img' ) ) ) {
971
		if ( this.utils.valOk( chargerImages ) ) {
972
			$.each(  chargerImages, function( i, value ) {
973
				var imgVisible = ( 0 < i ) ? 'miniature-cachee' : 'miniature-selectionnee';
974
 
975
				var css        = ( lthis.utils.valOk( value['b64'] ) ) ? 'miniature b64' : 'miniature',
976
					src        = value.src,
977
					alt        = value.nom,
978
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
979
 
980
				miniatures += miniature;
981
			});
982
			length = chargerImages.length;
983
 
984
		} else {
985
			var premiere     = true;
986
			$( '#miniatures img' ).each( function() {
987
				var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
988
				premiere = false;
989
 
990
				var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
991
					src        = $( this ).attr( 'src' ),
992
					alt        = $( this ).attr( 'alt' ),
993
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
994
 
995
				miniatures += miniature;
996
			});
997
			length = $( '#miniatures img' ).length;
998
		}
999
		if ( 1 === length ) {
1000
			centre       = 'centre';
1001
			defilVisible = ' defilement-miniatures-cache';
1002
		}
1003
		html             =
1004
			'<div class="defilement-miniatures">'+
1005
				'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
1006
				'<figure class="' + centre + '">'+
1007
					miniatures+
1008
				'</figure>'+
1009
				'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
1010
			'</div>';
1011
	}
1012
 
1013
	return html;
1014
};
1015
 
1016
/**
1017
 * Construit le html à afficher pour le numNom
1018
 */
1019
ReleveStreets.prototype.ajouterNumNomSel = function( numNomSel ) {
1020
	var nn = '<span class="nn">[nn' + numNomSel + ']</span>';
1021
 
1022
	if ( !this.utils.valOk( numNomSel ) ) {
1023
		nn = '<span class="alert-error">[' + this.utils.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
1024
	}
1025
 
1026
	return nn;
1027
};
1028
 
1029
/**
1030
 * Stocke des données d'obs à envoyer à la bdd
1031
 */
1032
ReleveStreets.prototype.stockerObsData = function( obsDatas ) {
1033
	const lthis = this;
1034
	var obsNum      = obsDatas.obsNum,
1035
		numNomSel   = obsDatas.arbre.taxon.numNomSel,
1036
		referentiel = ( !this.utils.valOk( numNomSel ) ) ? 'autre' : 'bdtfx',
1037
		date        = lthis.utils.fournirDate( obsDatas.releve.date ),
1038
		// si releve dupliqué on ne stocke pas l'image :
1039
		stockerImg  = this.utils.valOk( obsDatas.arbre['miniature-img'] ),
1040
		imgNom      = [],
1041
		imgB64      = [];
1042
 
1043
		if( stockerImg ) {
1044
			$.each( obsDatas.arbre['miniature-img'], function( i, obj ) {
1045
				if( obj.hasOwnProperty( 'id' ) ) {
1046
					stockerImg = false;
1047
				}
1048
				return stockerImg;
1049
			});
1050
		}
1051
		if ( stockerImg ) {
1052
			$.each( obsDatas.arbre['miniature-img'] , function(i, value) {
1053
				if( lthis.utils.valOk( value.nom ) ) {
1054
					imgNom.push( value.nom );
1055
				}
1056
				if( lthis.utils.valOk( value['b64'] ) ) {
1057
					imgB64.push( value['b64'] );
1058
				}
1059
			});
1060
		} else {
1061
			imgNom = lthis.getNomsImgsOriginales();
1062
			imgB64 = lthis.getB64ImgsOriginales();
1063
		}
1064
 
1065
	// Stockage en data des données d'obs à transmettre
1066
	$( '#liste-obs' ).data( 'obsId' + obsNum, {
1067
		'num_nom_sel'        : numNomSel,
1068
		'nom_sel'            : obsDatas.arbre.taxon.value,
1069
		'nom_ret'            : obsDatas.arbre.taxon.nomRet,
1070
		'num_nom_ret'        : obsDatas.arbre.taxon.numNomRet,
1071
		'num_taxon'          : obsDatas.arbre.taxon.nt,
1072
		'famille'            : obsDatas.arbre.taxon.famille,
1073
		'referentiel'        : referentiel,
1074
		'certitude'          : obsDatas.arbre.certitude,
1075
		'date'               : date,
1076
		'notes'              : obsDatas.releve.commentaires.trim(),
1077
		'pays'               : obsDatas.releve.pays,
1078
		'commune_nom'        : obsDatas.releve['commune-nom'],
1079
		'commune_code_insee' : obsDatas.releve['commune-insee'],
1080
		'latitude'           : obsDatas.releve.latitude,
1081
		'longitude'          : obsDatas.releve.longitude,
1082
		'altitude'           : obsDatas.releve.altitude,
1083
		//Ajout des champs images
1084
		'image_nom'          : imgNom,
1085
		'image_b64'          : imgB64,
1086
		// Ajout des champs étendus de l'obs
1087
		'obs_etendue'        : lthis.getObsChpArbres( obsDatas )
1088
	});
1089
};
1090
 
1091
ReleveStreets.prototype.getNomsImgsOriginales = function() {
1092
	var noms = new Array();
1093
 
1094
	$( '.miniature-img' ).each( function() {
1095
		noms.push( $( this ).attr( 'alt' ) );
1096
	});
1097
 
1098
	return noms;
1099
};
1100
 
1101
ReleveStreets.prototype.getB64ImgsOriginales = function() {
1102
	var b64 = new Array();
1103
 
1104
	$( '.miniature-img' ).each( function() {
1105
		if ( $( this ).hasClass( 'b64' ) ) {
1106
			b64.push( $( this ).attr( 'src' ) );
1107
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
1108
			b64.push( $( this ).data( 'b64' ) );
1109
		}
1110
	});
1111
 
1112
	return b64;
1113
};
1114
 
1115
/**
1116
 * Retourne un Array contenant les valeurs des champs
1117
 * dont les données seront transmises dans la table cel-obs-etendues
1118
 */
1119
ReleveStreets.prototype.getObsChpArbres = function( datasArbres ) {
1120
	const lthis = this;
1121
 
1122
	var retour = [],
1123
		champs = [
1124
			'rue',
1125
			'zone-pietonne',
1126
			'pres-lampadaires',
3324 idir 1127
			'rue-arbres',
3318 idir 1128
			'latitude-arbres',
1129
			'longitude-arbres',
1130
			'altitude-arbres',
1131
			'circonference',
1132
			'surface-pied',
1133
			'equipement-pied-arbre',
1134
			'tassement',
1135
			'dejections',
1136
			'com-arbres'
1137
		];
1138
 
1139
	var cleValeur       = '';
1140
 
1141
	$.each( champs, function( i ,value ) {
1142
		cleValeur = ( 3 > i ) ? 'releve' : 'arbre';
1143
 
1144
		if ( lthis.utils.valOk( datasArbres[cleValeur][value] ) ) {
1145
			retour.push({ cle : value, valeur : datasArbres[cleValeur][value] });
1146
		}
1147
	});
1148
	retour.push({ cle : 'num_arbre' , valeur : datasArbres.obsNum });
1149
 
1150
	var stockerImg  = this.utils.valOk( datasArbres.arbre['miniature-img'] );
1151
 
1152
	if( stockerImg ) {
1153
		$.each( datasArbres.arbre['miniature-img'], function( i, paramsImg ) {
1154
			if( !paramsImg.hasOwnProperty( 'id' ) ) {
1155
				stockerImg = false;
1156
			}
1157
			return stockerImg;
1158
		});
1159
	}
1160
	if( stockerImg ) {
1161
		retour.push({ cle : 'miniature-img' , valeur : JSON.stringify( datasArbres.arbre['miniature-img'] ) });
1162
	}
1163
 
1164
	return retour;
1165
};
1166
 
1167
/**
1168
 * Efface toutes les miniatures (formulaire)
1169
 */
1170
ReleveStreets.prototype.supprimerMiniatures = function() {
1171
	$( '#miniatures' ).empty();
1172
	$( '#miniature-msg' ).empty();
1173
};
1174
 
1175
ReleveStreets.prototype.surChangementNbreObs = function() {
1176
	if ( 0 === this.obsNbre ) {
1177
		$( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
1178
		// $( '#zone-liste-obs' ).addClass( 'hidden' );
1179
		$( '#bloc-form-arbres' ).removeClass( 'hidden' );
1180
	} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1181
		$( '#ajouter-obs,#transmettre-obs' ).removeAttr( 'disabled' );
1182
		$( '#bloc-form-arbres' ).removeClass( 'hidden' );
1183
	} else if ( this.obsNbre >= this.obsMaxNbre ) {
1184
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1185
		$( '#bloc-form-arbres' ).addClass( 'hidden' );
1186
		this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
1187
	}
1188
};
1189
 
1190
ReleveStreets.prototype.chargerInfosArbre = function( numArbre ) {
1191
	const lthis = this;
1192
	var desactiverForm = ( parseInt( numArbre ) !== ( this.numArbre + 1 ) );
1193
 
1194
	if ( desactiverForm ) {
1195
		var releveDatas = $.parseJSON( $( '#releve-data' ).val() ),
1196
			arbreDatas  = releveDatas[numArbre],
1197
			taxon       = {item:{}},
1198
			imgHtml     = '';
1199
 
1200
		$( '#arbre-nb').text( numArbre );
1201
 
1202
		taxon.item = arbreDatas.taxon;
1203
		this.surAutocompletionTaxon( {}, taxon );
1204
 
1205
		const SELECTS = ['certitude','equipement-pied-arbre','tassement'];
1206
 
1207
		$.each( SELECTS, function( i, value ) {
1208
			if( !lthis.utils.valOk( arbreDatas[value] ) ) {
1209
				arbreDatas[value] = '';
1210
			}
1211
			if ( $( this ).hasClass( 'other' ) && lthis.utils.valOk( $( this ).val() ) ) {
1212
				$( this ).text( $( this ).val() );
1213
			}
1214
			$( '#' + value + ' option' ).each( function() {
1215
				if ( arbreDatas[value] === $( this ).val() ) {
1216
					$( this ).prop( 'selected', true );
1217
				} else {
1218
					$( this ).prop( 'selected', false );
1219
				}
1220
			});
1221
		});
3324 idir 1222
		$( '#rue-arbres' ).val(arbreDatas['rue-arbres']);
3318 idir 1223
		$( '#latitude-arbres' ).val(arbreDatas['latitude-arbres']);
1224
		$( '#longitude-arbres' ).val(arbreDatas['longitude-arbres']);
1225
		$( '#altitude-arbres' ).val(arbreDatas['altitude-arbres']);
1226
		// image
1227
		this.supprimerMiniatures();
1228
		$.each( arbreDatas['miniature-img'], function( i, value ) {
1229
			imgHtml +=
1230
			'<div class="miniature mb-3 mr-3">'+
1231
				'<img class="miniature-img" class="miniature img-rounded" alt="' + value.nom + '" src="' + value.src + '"/>'+
1232
			'</div>';
1233
		});
1234
		$( '#miniatures' ).append( imgHtml );
1235
		$( '#circonference' ).val( arbreDatas.circonference );
1236
		$( '#surface-pied' ).val( arbreDatas['surface-pied'] );
1237
		$( '#com-arbres' ).val( arbreDatas['com-arbres'] );
1238
		if ( undefined != arbreDatas.dejections ) {
1239
			$( '#dejections-oui' ).prop( 'checked', arbreDatas.dejections );
1240
			$( '#dejections-non' ).prop( 'checked', !arbreDatas.dejections );
1241
		}
1242
	}
1243
 
1244
	this.modeArbresBasculerActivation( desactiverForm, numArbre );
1245
};
1246
 
1247
ReleveStreets.prototype.modeArbresBasculerActivation = function( desactiver, numArbre = 0 ) {
1248
	$(
1249
		'#taxon,'+
1250
		'#certitude,'+
1251
		'#equipement-pied-arbre,'+
1252
		'#tassement,'+
1253
		'#latitude-arbres,'+
1254
		'#longitude-arbres,'+
1255
		'#rue-arbres,'+
1256
		'#fichier,'+
1257
		'#circonference,'+
1258
		'#surface-pied,'+
1259
		'#com-arbres,'+
1260
		'#ajouter-obs'
1261
	).prop( 'disabled', desactiver );
1262
	$( '#dejections' ).find( 'input' ).prop( 'disabled', desactiver );
1263
 
1264
	if ( desactiver ) {
1265
		$( '#geoloc-arbres,#bouton-fichier,#miniature-arbres-info' ).addClass( 'hidden' );
1266
		$( '#geoloc-datas-arbres,#retour' ).removeClass( 'hidden' );
1267
	} else {
1268
		// quand on change ou qu'on revient à la normale :
1269
		$( '#geoloc-arbres,#bouton-fichier,#miniature-arbres-info' ).removeClass( 'hidden' );
1270
		$( '#geoloc-datas-arbres,#retour' ).addClass( 'hidden' );
1271
		// retour aux valeurs par defaut
1272
		$( '#equipement-pied-arbre .other' ).text( 'Autre' ).val( 'other' );
1273
		// $( '#equipement-pied-arbre .other' ).val( 'other' );
1274
		$(
1275
			'#certitude option,'+
1276
			'#equipement-pied-arbre option,'+
1277
			'#tassement option'
1278
		).each( function() {
1279
			if ( $( this ).hasClass( 'choisir' ) ) {
1280
				$( this ).prop( 'selected', true );
1281
			} else {
1282
				$( this ).prop( 'selected', false );
1283
			}
1284
		});
1285
		$( '#taxon' ).data( 'numNomSel', '' )
1286
			.data( 'nomRet','' )
1287
			.data( 'numNomRet', '' )
1288
			.data( 'nt', '' )
1289
			.data( 'famille', '' );
1290
		this.supprimerMiniatures();
1291
		$( '#dejections' ).find( 'input' ).prop( 'checked', false );
1292
		$(
1293
			'#taxon,'+
1294
			'#circonference,'+
1295
			'#surface-pied,'+
1296
			'#com-arbres,'+
1297
			'#rue-arbres,'+
1298
			'#latitude-arbres,'+
1299
			'#longitude-arbres,'+
1300
			'#certitude,'+
1301
			'#equipement-pied-arbre,'+
1302
			'#tassement'
1303
		).val( '' );
1304
		$( '#arbre-nb' ).text( numArbre );
1305
		$( '#arbre-info-lien-' + numArbre ).addClass( 'disabled' );
1306
		$( '.arbre-info' ).not( '#arbre-info-lien-' + numArbre ).removeClass( 'disabled' );
1307
	}
1308
};
1309
 
1310
ReleveStreets.prototype.defilerMiniatures = function( element ) {
1311
	var miniatureSelectionne  = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
1312
 
1313
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
1314
	miniatureSelectionne.addClass( 'miniature-cachee' );
1315
 
1316
	var miniatureAffichee     = miniatureSelectionne;
1317
 
1318
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
1319
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
1320
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
1321
		} else {
1322
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
1323
		}
1324
	} else {
1325
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
1326
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
1327
		} else {
1328
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
1329
		}
1330
	}
1331
	miniatureAffichee.addClass( 'miniature-selectionnee' );
1332
	miniatureAffichee.removeClass( 'miniature-cachee' );
1333
};
1334
 
1335
ReleveStreets.prototype.supprimerObs = function( selector ) {
1336
	var obsId = $( selector ).val();
1337
 
1338
	// Problème avec IE 6 et 7
1339
	if ( 'Supprimer' === obsId ) {
1340
		obsId = $( selector ).attr( 'title' );
1341
	}
1342
	this.supprimerObsParId( obsId );
1343
};
1344
 
1345
/**
1346
 * Supprime l'obs et les data de l'obs
1347
 * et remonte les suivantes d'un cran
1348
 */
1349
ReleveStreets.prototype.supprimerObsParId = function( obsId, transmission = false ) {
1350
	if ( !transmission ) {
1351
		this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1352
		this.releveData.splice( obsId , 1 );
1353
		$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1354
	}
1355
	$( '#arbre-info-' + ( this.numArbre ) ).remove();
1356
	$( '#arbre-nb' ).text( this.numArbre );
1357
 
1358
	this.obsNbre  -= 1;
1359
	this.numArbre -= 1;
1360
	$( '.obs-nbre' ).text( this.obsNbre );
1361
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1362
	$( '.obs' + obsId ).remove();
1363
 
1364
	obsId = parseInt(obsId);
1365
	var listObsData = $( '#liste-obs' ).data(),
1366
		exId        = 0,
1367
		indexObs    = '',
1368
		exIndexObs  = '',
1369
		arbreExId   = 0;
1370
 
1371
	for ( var id = obsId; id <= ( this.obsNbre + 1 ); id++ ) {
1372
		exId       = parseInt(id) + 1;
1373
		indexObs   = 'obsId' + id;
1374
		exIndexObs = 'obsId' + exId;
1375
		arbreExId  = parseInt( $( '#obs-arbre-' + exId ).data( 'arbre' ) );
1376
		arbreId    = arbreExId - 1;
1377
		$( '#liste-obs' ).removeData( indexObs );
1378
		if ( this.utils.valOk( listObsData[ exIndexObs ] ) ) {
1379
			$( '#liste-obs' ).data( indexObs, listObsData[ exIndexObs ] );
1380
		}
1381
		$( '#obs' + exId )
1382
			.attr( 'id', 'obs' + id )
1383
			.removeClass( 'obs' + exId )
1384
			.addClass( 'obs' + id )
1385
			.find( '.supprimer-obs' )
1386
				.attr( 'title', 'Observation n°' + id )
1387
				.val( id );
1388
		$( '#obs-arbre-' + arbreExId )
1389
			.attr( 'id', 'obs-arbre-' + arbreId )
1390
			.attr( 'data-arbre', arbreId )
1391
			.data( 'arbre', arbreId )
1392
			.text( 'Arbre ' + arbreId );
1393
 
1394
		if ( parseInt( id ) !== this.obsNbre ) {
1395
			id = parseInt(id);
1396
		}
1397
	}
1398
};
1399
 
1400
/*
1401
 * Actualise l'id_observation ( id de l'obs en bdd )
1402
 * à partir des données renvoyées par le service après transfert
1403
 */
1404
ReleveStreets.prototype.actualiserReleveDataIdObs = function( obsId, id_observation ) {
1405
	this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1406
	this.releveData[obsId ]['id_observation'] = id_observation;
1407
	$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1408
};
1409
 
1410
ReleveStreets.prototype.transmettreObs = function() {
1411
	const lthis = this;
1412
	var observations = $( '#liste-obs' ).data();
1413
 
1414
	if ( this.debug ) {
1415
		console.log( observations );
1416
	}
1417
	if ( !this.utils.valOk( typeof observations, true, 'object' ) ) {
1418
		this.afficherPanneau( '#dialogue-zero-obs' );
1419
	} else {
1420
		$( window ).on( 'beforeunload', function( event ) {
1421
			return lthis.utils.msgTraduction( 'rechargement-page' );
1422
		});
1423
		this.nbObsEnCours         = 1;
1424
		this.nbObsTransmises      = 0;
1425
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
1426
			return i;
1427
		}).length;
1428
		this.depilerObsPourEnvoi();
1429
	}
1430
 
1431
	return false;
1432
};
1433
 
1434
ReleveStreets.prototype.depilerObsPourEnvoi = function() {
1435
	var observations = $( '#liste-obs' ).data();
1436
 
1437
	// la boucle est factice car on utilise un tableau
1438
	// dont on a besoin de n'extraire que le premier élément
1439
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1440
	// TODO: utiliser var.keys quand ça sera plus répandu
1441
	// ou bien utiliser un vrai tableau et pas un objet
1442
	for ( var obsNum in observations ) {
1443
		var obsATransmettre = {
1444
			'projet'  : this.tagProjet,
1445
			'tag-obs' : this.tagObs,
1446
			'tag-img' : this.tagImg
1447
		};
1448
		var utilisateur = {
1449
			id_utilisateur : this.infosUtilisateur.id,
1450
			prenom         : this.infosUtilisateur.prenom,
1451
			nom            : this.infosUtilisateur.nom,
1452
			courriel       : $( '#courriel' ).val()
1453
		};
1454
 
1455
		obsATransmettre['utilisateur'] = utilisateur;
1456
		obsATransmettre[obsNum]        = observations[obsNum];
1457
 
1458
		var idObsNumerique = obsNum.replace( 'obsId', '' );
1459
 
1460
		if( '' !== idObsNumerique ) {
1461
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
1462
		}
1463
		break;
1464
	}
1465
};
1466
 
1467
ReleveStreets.prototype.envoyerObsAuCel = function( idObs, observation ) {
1468
	const lthis     = this;
1469
	var erreurMsg = '';
1470
 
1471
	$.ajax({
1472
		url        : lthis.serviceSaisieUrl,
1473
		type       : 'POST',
1474
		data       : observation,
1475
		dataType   : 'json',
1476
		beforeSend : function() {
1477
			$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
1478
			$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1479
			$( '.alert-txt' ).empty();
1480
			$( '.alert-txt .msg-erreur' ).remove();
1481
			$( '.alert-txt .msg-debug' ).remove();
1482
			$( '#chargement' ).removeClass( 'hidden' );
1483
		},
1484
		success    : function( transfertDatas, textStatus, jqXHR ) {
1485
			// actualisation de id_observation dans '#releve-data'
1486
			lthis.actualiserReleveDataIdObs( idObs, transfertDatas.id );
1487
			// mise à jour du nombre d'obs à transmettre
1488
			// et suppression de l'obs
1489
			lthis.supprimerObsParId( idObs, true );
1490
			lthis.nbObsEnCours++;
1491
			// mise à jour du statut
1492
			lthis.mettreAJourProgression();
1493
			if( 0 < lthis.obsNbre ) {
1494
				// dépilement de la suivante
1495
				lthis.depilerObsPourEnvoi();
1496
			}
1497
		},
1498
		statusCode  : {
1499
			500 : function( jqXHR, textStatus, errorThrown ) {
1500
				erreurMsg += lthis.utils.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1501
				}
1502
		},
1503
		error        : function( jqXHR, textStatus, errorThrown ) {
1504
			erreurMsg += lthis.utils.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1505
			try {
1506
				reponse = jQuery.parseJSON( jqXHR.responseText );
1507
				if ( null !== reponse ) {
1508
					$.each( reponse, function( cle, valeur ) {
1509
						erreurMsg += valeur + '\n';
1510
					});
1511
				}
1512
			} catch( e ) {
1513
				erreurMsg += lthis.utils.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
1514
			}
1515
		},
1516
		complete      : function( jqXHR, textStatus ) {
1517
			var debugMsg = extraireEnteteDebug( jqXHR );
1518
 
1519
			if ( '' !== erreurMsg ) {
1520
				if ( lthis.debug ) {
1521
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
1522
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1523
				}
1524
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1525
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagProjet+
1526
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
1527
 
1528
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
1529
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
1530
				// window.location.hash = 'obs' + idObs;
1531
 
1532
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
1533
					$( '#tpl-transmission-ko' ).clone()
1534
						.find( '.courriel-erreur' )
1535
						.attr( 'href', hrefCourriel )
1536
						.end()
1537
						.html()
1538
				);
1539
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
1540
				$( '#chargement' ).addClass( 'hidden' );
1541
				lthis.initialiserBarreProgression;
1542
			} else {
1543
				if ( lthis.debug ) {
1544
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1545
				}
1546
				if( 0 === lthis.obsNbre ) {
1547
					setTimeout( function() {
1548
						$( '#chargement,#bloc-arbres-gauche,#bloc-controle-liste-obs' ).addClass( 'hidden' );
1549
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
1550
						$( '#dialogue-obs-transaction-ok,#bouton-saisir-plantes' ).removeClass( 'hidden' );
1551
					}, 1500 );
1552
				}
1553
			}
1554
		}
1555
	});
1556
};
1557
 
1558
ReleveStreets.prototype.mettreAJourProgression = function() {
1559
	this.nbObsTransmises++;
1560
 
1561
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
1562
 
1563
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
1564
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
1565
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.utils.msgTraduction( 'observations-transmises' ) );
1566
	if( 0 === this.obsNbre ) {
1567
		$( '.progress' ).removeClass( 'active' );
1568
		$( '.progress' ).removeClass( 'progress-bar-striped' );
1569
	}
1570
};
1571
 
1572
ReleveStreets.prototype.initialiserBarreProgression = function() {
1573
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
1574
	$( '#barre-progression-upload' ).css( 'width', '0%' );
1575
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.utils.msgTraduction( 'observations-transmises' ) );
1576
	$( '.progress' ).addClass( 'active' );
1577
	$( '.progress' ).addClass( 'progress-bar-striped' );
1578
};
1579
 
1580
// Form Validator *************************************************************/
1581
ReleveStreets.prototype.configurerFormValidator = function() {
1582
	const lthis = this;
1583
 
1584
	$.validator.addMethod(
1585
		'dateCel',
1586
		function ( value, element ) {
1587
			return ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) );
1588
		},
1589
		lthis.utils.msgTraduction( 'date-incomplete' )
1590
	);
1591
 
1592
	$.validator.addMethod(
1593
		'userEmailOk',
1594
		function ( value, element ) {
1595
			return ( lthis.utils.valOk( value ) );
1596
		},
1597
		''
1598
	);
1599
	$.validator.addMethod(
1600
		'minMaxOk',
1601
		function ( value, element, param ) {
1602
			$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message;
1603
			return lthis.validerMinMax( element ).cond;
1604
		},
1605
		$.validator.messages.minMaxOk
1606
	);
1607
 
1608
	$.extend( $.validator.defaults, {
1609
		errorElement: 'span',
1610
		errorPlacement: function( error, element ) {
1611
			if ( 'checkbox' === element.attr( 'type' ) || 'radio' === element.attr( 'type' ) ) {
1612
				error.appendTo( element.closest( '.list' ) );
1613
			} else {
1614
				element.after( error );
1615
			}
1616
		},
1617
		onfocusout: function( element ) {
1618
			if ( $( element ).valid() ) {
1619
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1620
			} else {
1621
				$( element ).closest( '.control-group' ).addClass( 'error' );
1622
			}
1623
		},
1624
		onkeyup : function( element ) {
1625
			if ( $( element ).valid() ) {
1626
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1627
			} else {
1628
				$( element ).closest( '.control-group' ).addClass( 'error' );
1629
			}
1630
		},
1631
		unhighlight: function( element ) {
1632
			$( element ).closest( '.control-group' ).removeClass( 'error' );
1633
		},
1634
		highlight: function( element ) {
1635
			$( element ).closest( '.control-group' ).addClass( 'error' );
1636
		}
1637
	});
1638
};
1639
 
1640
ReleveStreets.prototype.validerMinMax = function( element ) {
1641
	var mMCond      = new Boolean(),
1642
		minCond     = parseFloat( element.value ) >= parseFloat( element.min ),
1643
		maxCond     = parseFloat( element.value ) <= parseFloat( element.max ),
1644
		messageMnMx = 'La valeur entrée doit être',
1645
		returnMnMx  = { cond : true , message : '' };
1646
 
1647
	if (
1648
			( this.utils.valOk( element.type, true, 'number' ) || this.utils.valOk( element.type, true, 'range' ) ) &&
1649
			( this.utils.valOk( element.min ) || this.utils.valOk( element.max ) )
1650
		) {
1651
 
1652
		if ( element.min && element.max ) {
1653
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
1654
			mnMxCond     = ( minCond && maxCond );
1655
		} else if ( element.min ) {
1656
			messageMnMx += ' supérieure à ' + element.min;
1657
			mnMxCond     = minCond;
1658
		} else {
1659
			messageMnMx += ' inférieure à ' + element.max;
1660
			mnMxCond     = maxCond;
1661
		}
1662
		returnMnMx.cond    = mnMxCond;
1663
		returnMnMx.message = messageMnMx;
1664
	}
1665
 
1666
	return returnMnMx;
1667
};
1668
 
1669
/**
1670
 * Valider date/rue/commune par rapport aux relevés précédents
1671
 */
1672
ReleveStreets.prototype.validerDateRueCommune = function( valeurDate, valeurRue, valeurCmn ) {
1673
	var valide = true;
1674
 
1675
	if (
1676
		this.utils.valOk( $( '#dates-rues-communes' ).val() ) &&
1677
		this.utils.valOk( valeurDate ) &&
1678
		this.utils.valOk( valeurRue ) &&
1679
		this.utils.valOk( valeurCmn )
1680
	) {
1681
		var valsEltDRC = $.parseJSON( $( '#dates-rues-communes' ).val() ),
1682
			valeurDRC = valeurDate + valeurRue + valeurCmn;
1683
		valide = ( -1 === valsEltDRC.indexOf( valeurDRC ) );
1684
 
1685
	}
1686
	return valide;
1687
};
1688
 
1689
/**
1690
 * FormValidator pour les champs date/rue/Commune
1691
 */
1692
ReleveStreets.prototype.dateRueCommuneFormValidator = function() {
1693
	var dateValid    = ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( $( '#releve-date' ).val() ) ),
1694
		geolocValid  = ( this.utils.valOk( $( '#commune-nom' ).val() ) && this.utils.valOk( $( '#rue' ).val() ) );
1695
	const errorDateRue =
1696
			'<span id="error-drc" class="error">'+
1697
				this.utils.msgTraduction( 'date-rue' )+
1698
			'</span> ';
1699
 
1700
	if( this.validerDateRueCommune( $( '#releve-date' ).val(), $( '#rue' ).val(), $( '#commune-nom' ).val()  ) ) {
1701
		$( '#releve-date' )
1702
			.removeClass( 'erreur' )
1703
			.closest( '.control-group' )
1704
				.removeClass( 'error' )
1705
				.find( '#error-drc' )
1706
					.remove();
1707
		if ( geolocValid ) {
1708
			$( '#geoloc' )
1709
			.closest( '.control-group' )
1710
				.removeClass( 'error' );
1711
		}
1712
		$( '#geoloc #error-drc' ).remove();
1713
	} else {
1714
		$( '#releve-date' )
1715
			.addClass( 'erreur' )
1716
			.closest( '.control-group' )
1717
				.addClass( 'error' );
1718
		if ( !this.utils.valOk( $( '#releve-date' ).closest( '.control-group' ).find( '#error-drc' ) ) ) {
1719
			$( '#releve-date' ).after( errorDateRue );
1720
		}
1721
		$( '#geoloc' ).closest( '.control-group' ).addClass( 'error' );
1722
		if ( !this.utils.valOk( $( '#geoloc' ).find( '#error-drc' ) ) ) {
1723
			$( '#geoloc' ).prepend( errorDateRue );
1724
		}
1725
	}
1726
	if ( dateValid ) {
1727
		$( '#releve-date' ).closest( '.control-group span.error' ).not( '#error-drc' ).remove();
1728
	}
1729
};
1730
 
1731
ReleveStreets.prototype.definirReglesFormValidator = function() {
1732
	const lthis = this;
1733
 
1734
	$( '#form-observation' ).validate({
1735
		rules : {
1736
			'zone-pietonne' : {
1737
				required : true,
1738
				minlength : 1
1739
			},
1740
			latitude : {
1741
				required : true,
1742
				minlength : 1,
1743
				range : [-90, 90]
1744
			},
1745
			longitude : {
1746
				required : true,
1747
				minlength : 1,
1748
				range : [-180, 180]
1749
			}
1750
		}
1751
	});
1752
	$( 'input[type=date]' ).not( '#releve-date' ).on( 'input', function() {
1753
		$( this ).valid();
1754
	});
1755
	// validation date/rue/commune au démarage
1756
	this.dateRueCommuneFormValidator();
1757
	// validation date/rue/commune sur event
1758
	$( '#releve-date,#rue,#commune-nom' ).on( 'change input focusout', this.dateRueCommuneFormValidator.bind( this ) );
1759
	$( '#form-arbre' ).validate({
1760
		rules : {
1761
			taxon : {
1762
				required : true,
1763
				minlength : 1
1764
			},
1765
			certitude : {
1766
				required : true,
1767
				minlength : 1
1768
			},
1769
			'latitude-arbres' : {
1770
				required : true,
1771
				minlength : 1,
1772
				range : [-90, 90]
1773
			},
1774
			'longitude-arbres' : {
1775
				required : true,
1776
				minlength : 1,
1777
				range : [-180, 180]
1778
			}
1779
		}
1780
	});
1781
	$( '#form-arbre-fs' ).validate({
1782
		onkeyup : false,
1783
		onclick : false,
1784
		rules : {
1785
			circonference : {
1786
				required : true,
1787
				minlength : 1//,
1788
				//'minMaxOk' : true
1789
			},
1790
			'surface-pied' : {
1791
				required : true,
1792
				minlength : 1,
1793
				'minMaxOk' : true
1794
			},
1795
			'equipement-pied-arbre' : {
1796
				required : true,
1797
				minlength : 1
1798
			}
1799
		}
1800
	});
1801
	$( '#equipement-pied-arbre' ).change( function() {
1802
		if ( lthis.utils.valOk( $( this ).val(), false, 'other' ) ) {
1803
			$( this )
1804
				.closest( '.control-group' )
1805
					.removeClass( 'error' )
1806
					.find( 'span.error' )
1807
						.addClass( 'hidden' );
1808
		}
1809
	});
1810
	$( '#form-observateur' ).validate({
1811
		rules : {
1812
			courriel : {
1813
				required : true,
1814
				minlength : 1,
1815
				email : true,
1816
				'userEmailOk' : true
1817
			},
1818
			mdp : {
1819
				required : true,
1820
				minlength : 1
1821
			}
1822
		}
1823
	});
1824
	$( '#connexion,#inscription,#oublie' ).click( function() {
1825
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
1826
	});
1827
};
1828
 
1829
/**
1830
 * Valide le formulaire Relevé (= étape 1) au click sur un bouton "enregistrer"
1831
 */
1832
ReleveStreets.prototype.validerReleve = function() {
1833
	const observateur = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() )
1834
	const obs         = $( '#form-observation' ).valid();
1835
	const geoloc      = (
1836
		this.utils.valOk( $( '#latitude' ).val() ) &&
1837
		this.utils.valOk( $( '#longitude' ).val() ) &&
1838
		this.utils.valOk( $( '#rue' ).val() ) &&
1839
		this.utils.valOk( $( '#commune-nom' ).val() )
1840
	) ;
1841
	var dateRue = true;
1842
	if ( this.utils.valOk( $( '#dates-rues-communes' ).val() ) ) {
1843
		dateRue = (
1844
			this.utils.valOk( $( '#releve-date' ).val() ) &&
1845
			this.utils.valOk( $( '#rue' ).val() ) &&
1846
			this.validerDateRueCommune( $( '#releve-date' ).val(), $( '#rue' ).val(), $( '#commune-nom' ).val() )
1847
		);
1848
	}
1849
	if ( !obs ) {
1850
		$( 'html, body' ).stop().animate({
1851
			scrollTop: $( '#zone-observation' ).offset().top
1852
		}, 300 );
1853
	}
1854
	// panneau observateur
1855
	if ( observateur ) {
1856
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
1857
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
1858
	} else {
1859
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
1860
		$( '#tb-observateur .control-group' ).addClass( 'error' );
1861
	}
1862
	if ( dateRue && geoloc ) {
1863
		this.masquerPanneau( '#dialogue-date-rue-ko' );
1864
		$( '#geoloc-datas' ).closest( '.control-group' ).removeClass( 'error' );
1865
	} else {
1866
		if (
1867
			this.utils.valOk( $( '#releve-date' ).val() ) &&
1868
			this.utils.valOk( $( '#rue' ).val() ) &&
1869
			this.utils.valOk( $( '#dates-rues-communes' ).val() )
1870
		) {
1871
			this.afficherPanneau( '#dialogue-date-rue-ko' );
1872
		}
1873
		$( '#geoloc-datas' ).closest( '.control-group' ).addClass( 'error' );
1874
	}
1875
	if (
1876
		!this.utils.valOk( $( '#releve-date' ).val() ) ||
1877
		!this.utils.valOk( $( '#rue' ).val() ) ||
1878
		!this.utils.valOk( $( '#dates-rues-communes' ).val() )
1879
	) {
1880
		this.masquerPanneau( '#dialogue-date-rue-ko' );
1881
	}
1882
	if ( geoloc ) {
1883
		this.masquerPanneau( '#dialogue-geoloc-ko' );
1884
		if ( dateRue ) {
3324 idir 1885
			$( '#geoloc' ).closest( '.control-group' ).removeClass( 'error' );
3318 idir 1886
		}
1887
	} else {
1888
		this.afficherPanneau( '#dialogue-geoloc-ko' );
3324 idir 1889
		$( '#geoloc' ).closest( '.control-group' ).addClass( 'error' );
3318 idir 1890
	}
1891
 
3324 idir 1892
	return ( observateur && obs && geoloc && dateRue );
3318 idir 1893
};
1894
 
1895
/**
1896
 * Valide le formulaire Arbres (= étape 2) au click sur un bouton "suivant"
1897
 */
3324 idir 1898
ReleveStreets.prototype.validerArbres = function() {
1899
	const validerReleve = this.validerReleve();
3318 idir 1900
	const geoloc      = (
1901
		this.utils.valOk( $( '#latitude-arbres' ).val() ) &&
3324 idir 1902
		this.utils.valOk( $( '#longitude-arbres' ).val() )
3318 idir 1903
	);
1904
	const piedArbre = this.utils.valOk( $( '#equipement-pied-arbre' ).val(), false, 'other' );
1905
	const taxon = this.utils.valOk( $( '#taxon' ).val() );
1906
	const obs   = (
1907
		$( '#form-arbre' ).valid() &&
1908
		$( '#form-arbre-fs' ).valid() &&
1909
		piedArbre
1910
	);
1911
 
1912
	if ( piedArbre ) {
1913
		$( '#equipement-pied-arbre' )
1914
			.closest( '.control-group' )
1915
				.removeClass( 'error' )
1916
				.find( 'span.error' )
1917
					.addClass( 'hidden' );
1918
	} else {
1919
		$( '#equipement-pied-arbre' )
1920
			.closest( '.control-group' )
1921
				.addClass( 'error' )
1922
				.find( 'span.error' )
1923
					.removeClass( 'hidden' );
1924
	}
1925
	if ( geoloc ) {
1926
		this.masquerPanneau( '#dialogue-geoloc-ko' );
3324 idir 1927
		$( '#geoloc-arbres' ).closest( '.control-group' ).removeClass( 'error' );
3318 idir 1928
	} else {
1929
		this.afficherPanneau( '#dialogue-geoloc-ko' );
3324 idir 1930
		$( '#geoloc-arbres' ).closest( '.control-group' ).addClass( 'error' );
3318 idir 1931
	}
1932
 
3324 idir 1933
	return ( validerReleve && obs && geoloc && taxon );
3318 idir 1934
};
1935
 
1936
// Controle des panneaux d'infos **********************************************/
1937
 
1938
ReleveStreets.prototype.afficherPanneau = function( selecteur ) {
1939
	$( selecteur )
1940
		.removeClass( 'hidden' )
1941
		.hide()
1942
		.show( 600 )
1943
		.delay( this.dureeMessage )
1944
		.hide( 600 );
1945
	$( 'html, body' ).stop().animate({scrollTop: $( selecteur ).offset().top}, 300);
1946
};
1947
 
1948
ReleveStreets.prototype.masquerPanneau = function( selecteur ) {
1949
	$( selecteur ).addClass( 'hidden' );
1950
};
1951
 
1952
ReleveStreets.prototype.fermerPanneauAlert = function() {
1953
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
1954
};
1955
 
1956
// lib hors objet --
1957
 
1958
/**
1959
* Stope l'évènement courant quand on clique sur un lien.
1960
* Utile pour Chrome, Safari...
1961
*/
1962
function arreter( event ) {
1963
	if ( event.stopPropagation ) {
1964
		event.stopPropagation();
1965
	}
1966
	if ( event.preventDefault ) {
1967
		event.preventDefault();
1968
	}
1969
 
1970
	return false;
1971
}
1972
 
1973
/**
1974
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1975
 * @param jqXHR
1976
 * @returns {String}
1977
 */
1978
function extraireEnteteDebug( jqXHR ) {
1979
	var msgDebug = '';
1980
 
1981
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
1982
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
1983
		if ( null !== debugInfos ) {
1984
			$.each( debugInfos, function( cle, valeur ) {
1985
				msgDebug += valeur + '\n';
1986
			});
1987
		}
1988
	}
1989
 
1990
	return msgDebug;
1991
}
1992
 
1993
/*
1994
 * jQuery UI Autocomplete HTML Extension
1995
 *
1996
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1997
 * Dual licensed under the MIT or GPL Version 2 licenses.
1998
 *
1999
 * http://github.com/scottgonzalez/jquery-ui-extensions
2000
 *
2001
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
2002
 */
2003
( function( $ ) {
2004
	var proto      = $.ui.autocomplete.prototype,
2005
		initSource = proto._initSource;
2006
 
2007
	ReleveStreets.prototype.filter = function( array, term ) {
2008
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
2009
 
2010
		return $.grep( array, function( value ) {
2011
 
2012
			return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
2013
		});
2014
	}
2015
	$.extend( proto, {
2016
		_initSource: function() {
2017
			if ( this.options.html && $.isArray( this.options.source ) ) {
2018
				this.source = function( request, response ) {
2019
					response( filter( this.options.source, request.term ) );
2020
				};
2021
			} else {
2022
				initSource.call( this );
2023
			}
2024
		},
2025
		_renderItem: function( ul, item) {
2026
			if ( item.retenu ) {
2027
				item.label = '<strong>' + item.label + '</strong>';
2028
			}
2029
 
2030
			return $( '<li></li>' )
2031
				.data( 'item.autocomplete', item )
2032
				.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
2033
				.appendTo( ul );
2034
		}
2035
	});
2036
})( jQuery );