Subversion Repositories eFlore/Applications.cel

Rev

Rev 3881 | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 3881 Rev 3901
1
import {WidgetsSaisiesCommun,utils} from './WidgetsSaisiesCommun.js';
1
import {WidgetsSaisiesCommun,utils} from './WidgetsSaisiesCommun.js';
2
import {valOk} from './Utils.js';
2
import {valOk,tryParseJson} from './Utils.js';
3
 
3
 
4
/**
4
/**
5
 * Constructeur WidgetSaisie par défaut
5
 * Constructeur WidgetSaisie par défaut
6
 */
6
 */
7
function WidgetSaisie(  ) {
7
function WidgetSaisie(  ) {
8
	if  ( valOk(widgetProp) ) {
8
	if  ( valOk(widgetProp) ) {
9
		this.urlWidgets                        = widgetProp.urlWidgets;
9
		this.urlWidgets                        = widgetProp.urlWidgets;
10
		this.projet                            = widgetProp.projet;
10
		this.projet                            = widgetProp.projet;
11
		this.idProjet                          = widgetProp.idProjet;
11
		this.idProjet                          = widgetProp.idProjet;
12
		this.tagsMotsCles                      = widgetProp.tagsMotsCles;
12
		this.tagsMotsCles                      = widgetProp.tagsMotsCles;
13
		this.mode                              = widgetProp.mode;
13
		this.mode                              = widgetProp.mode;
14
		this.langue                            = widgetProp.langue;
14
		this.langue                            = widgetProp.langue;
15
		this.serviceAnnuaireIdUrl              = widgetProp.serviceAnnuaireIdUrl;
15
		this.serviceAnnuaireIdUrl              = widgetProp.serviceAnnuaireIdUrl;
16
		this.serviceNomCommuneUrl              = widgetProp.serviceNomCommuneUrl;
16
		this.serviceNomCommuneUrl              = widgetProp.serviceNomCommuneUrl;
17
		this.serviceNomCommuneUrlAlt           = widgetProp.serviceNomCommuneUrlAlt;
17
		this.serviceNomCommuneUrlAlt           = widgetProp.serviceNomCommuneUrlAlt;
18
		this.debug                             = widgetProp.debug;
18
		this.debug                             = widgetProp.debug;
19
		this.html5                             = widgetProp.html5;
19
		this.html5                             = widgetProp.html5;
20
		this.serviceSaisieUrl                  = widgetProp.serviceSaisieUrl;
20
		this.serviceSaisieUrl                  = widgetProp.serviceSaisieUrl;
21
		this.serviceObsUrl                     = widgetProp.serviceObsUrl;
21
		this.serviceObsUrl                     = widgetProp.serviceObsUrl;
22
		this.chargementImageIconeUrl           = widgetProp.chargementImageIconeUrl;
22
		this.chargementImageIconeUrl           = widgetProp.chargementImageIconeUrl;
23
		this.pasDePhotoIconeUrl                = widgetProp.pasDePhotoIconeUrl;
23
		this.pasDePhotoIconeUrl                = widgetProp.pasDePhotoIconeUrl;
24
		this.autocompletionElementsNbre        = widgetProp.autocompletionElementsNbre;
24
		this.autocompletionElementsNbre        = widgetProp.autocompletionElementsNbre;
25
		this.serviceAutocompletionNomSciUrl    = widgetProp.serviceAutocompletionNomSciUrl;
25
		this.serviceAutocompletionNomSciUrl    = widgetProp.serviceAutocompletionNomSciUrl;
26
		this.serviceAutocompletionNomSciUrlTpl = widgetProp.serviceAutocompletionNomSciUrlTpl;
26
		this.serviceAutocompletionNomSciUrlTpl = widgetProp.serviceAutocompletionNomSciUrlTpl;
27
		this.dureeMessage                      = widgetProp.dureeMessage;
27
		this.dureeMessage                      = widgetProp.dureeMessage;
28
		this.obsMaxNbre                        = widgetProp.obsMaxNbre;
28
		this.obsMaxNbre                        = widgetProp.obsMaxNbre;
29
		this.tagImg                            = widgetProp.tagImg;
29
		this.tagImg                            = widgetProp.tagImg;
30
		this.tagObs                            = widgetProp.tagObs;
30
		this.tagObs                            = widgetProp.tagObs;
31
		this.obsId                             = widgetProp.obsId;
31
		this.obsId                             = widgetProp.obsId;
32
		this.nomSciReferentiel                 = widgetProp.nomSciReferentiel;
32
		this.nomSciReferentiel                 = widgetProp.nomSciReferentiel;
33
		this.especeImposee                     = widgetProp.especeImposee;
33
		this.especeImposee                     = widgetProp.especeImposee;
34
		this.infosEspeceImposee                = widgetProp.infosEspeceImposee;
34
		this.infosEspeceImposee                = widgetProp.infosEspeceImposee;
35
		this.referentielImpose                 = widgetProp.referentielImpose;
35
		this.referentielImpose                 = widgetProp.referentielImpose;
36
		this.isTaxonListe                      = widgetProp.isTaxonListe;
36
		this.isTaxonListe                      = widgetProp.isTaxonListe;
37
		this.photoObligatoire                  = widgetProp.photoObligatoire;
37
		this.photoObligatoire                  = widgetProp.photoObligatoire;
38
	}
38
	}
39
	this.urlRacine            = window.location.origin;
39
	this.urlRacine            = window.location.origin;
40
	this.obsNbre              = 0;
40
	this.obsNbre              = 0;
41
	this.nbObsEnCours         = 1;
41
	this.nbObsEnCours         = 1;
42
	this.totalObsATransmettre = 0;
42
	this.totalObsATransmettre = 0;
43
	this.nbObsTransmises      = 0;
43
	this.nbObsTransmises      = 0;
44
	this.observer             = null;
44
	this.observer             = null;
45
	this.isASL                = false;
45
	this.isASL                = false;
46
	this.geoloc               = {};
46
	this.geoloc               = {};
47
}
47
}
48
WidgetSaisie.prototype = new WidgetsSaisiesCommun();
48
WidgetSaisie.prototype = new WidgetsSaisiesCommun();
49
 
49
 
50
/**
50
/**
51
 * Initialise le formulaire, les validateurs, les listes de complétion...
51
 * Initialise le formulaire, les validateurs, les listes de complétion...
52
 */
52
 */
53
WidgetSaisie.prototype.initForm = function() {
53
WidgetSaisie.prototype.initForm = function() {
54
	this.initFormConnection();
54
	this.initFormConnection();
55
	if ( valOk( this.obsId ) ) {
55
	if ( valOk( this.obsId ) ) {
56
		this.chargerInfoObs();
56
		this.chargerInfoObs();
57
	}
57
	}
58
	if( this.isTaxonListe ) {
58
	if( this.isTaxonListe ) {
59
		this.initFormTaxonListe();
59
		this.initFormTaxonListe();
60
	} else {
60
	} else {
61
		this.ajouterAutocompletionNoms();
61
		this.ajouterAutocompletionNoms();
62
	}
62
	}
63
	// au rafraichissement de la page,
63
	// au rafraichissement de la page,
64
	// les input date semblent conserver la valeur entrée précedemment
64
	// les input date semblent conserver la valeur entrée précedemment
65
	// c'est voulu après la création d'une obs mais pas quand la page est actualisée
65
	// c'est voulu après la création d'une obs mais pas quand la page est actualisée
66
	// Déjà tenté: onbeforeunload avec un location.reload(true) n'a pas permis de le faire
66
	// Déjà tenté: onbeforeunload avec un location.reload(true) n'a pas permis de le faire
67
	$( 'input[type=date]' ).each( function () {
67
	$( 'input[type=date]' ).each( function () {
68
		( valOk( $( this ).data( 'default' ) ) ) ? $( this ).val( $( this ).data( 'default' ) ) : $( this ).val( '' );
68
		( valOk( $( this ).data( 'default' ) ) ) ? $( this ).val( $( this ).data( 'default' ) ) : $( this ).val( '' );
69
	});
69
	});
70
	this.configurerFormValidator();
70
	this.configurerFormValidator();
71
	this.definirReglesFormValidator();
71
	this.definirReglesFormValidator();
72
 
72
 
73
	if( this.especeImposee ) {
73
	if( this.especeImposee ) {
74
		$( '#taxon' ).attr( 'disabled', 'disabled' );
74
		$( '#taxon' ).attr( 'disabled', 'disabled' );
75
		$( '#taxon-input-groupe' ).attr( 'title', '' );
75
		$( '#taxon-input-groupe' ).attr( 'title', '' );
76
		// Bricolage cracra pour avoir le nom retenu avec auteur (nom_retenu.libelle ne le mentionne pas)
76
		// Bricolage cracra pour avoir le nom retenu avec auteur (nom_retenu.libelle ne le mentionne pas)
77
		const infosEspeceImposee = $.parseJSON( this.infosEspeceImposee );
77
		const infosEspeceImposee = $.parseJSON( this.infosEspeceImposee );
78
		let nomRetenuComplet   = infosEspeceImposee.nom_retenu_complet;
78
		let nomRetenuComplet   = infosEspeceImposee.nom_retenu_complet;
79
		const debutAnneRefBiblio = nomRetenuComplet.indexOf( ' [' );
79
		const debutAnneRefBiblio = nomRetenuComplet.indexOf( ' [' );
80
 
80
 
81
		if ( -1 !== debutAnneRefBiblio ) {
81
		if ( -1 !== debutAnneRefBiblio ) {
82
			nomRetenuComplet = nomRetenuComplet.substr( 0, debutAnneRefBiblio );
82
			nomRetenuComplet = nomRetenuComplet.substr( 0, debutAnneRefBiblio );
83
		}
83
		}
84
		// fin bricolage cracra
84
		// fin bricolage cracra
85
		const infosAssociee = {
85
		const infosAssociee = {
86
			label : infosEspeceImposee.nom_sci_complet,
86
			label : infosEspeceImposee.nom_sci_complet,
87
			value : infosEspeceImposee.nom_sci_complet,
87
			value : infosEspeceImposee.nom_sci_complet,
88
			nt : infosEspeceImposee.num_taxonomique,
88
			nt : infosEspeceImposee.num_taxonomique,
89
			nomSel : infosEspeceImposee.nom_sci,
89
			nomSel : infosEspeceImposee.nom_sci,
90
			nomSelComplet : infosEspeceImposee.nom_sci_complet,
90
			nomSelComplet : infosEspeceImposee.nom_sci_complet,
91
			numNomSel : infosEspeceImposee.id,
91
			numNomSel : infosEspeceImposee.id,
92
			nomRet : nomRetenuComplet,
92
			nomRet : nomRetenuComplet,
93
			numNomRet : infosEspeceImposee['nom_retenu.id'],
93
			numNomRet : infosEspeceImposee['nom_retenu.id'],
94
			famille : infosEspeceImposee.famille,
94
			famille : infosEspeceImposee.famille,
95
			retenu : ( 'false' === infosEspeceImposee.retenu ) ? false : true
95
			retenu : ( 'false' === infosEspeceImposee.retenu ) ? false : true
96
		};
96
		};
97
		$( '#taxon' ).data( infosAssociee );
97
		$( '#taxon' ).data( infosAssociee );
98
	}
98
	}
99
};
99
};
100
 
100
 
101
/**
101
/**
102
 * Initialise les écouteurs d'événements
102
 * Initialise les écouteurs d'événements
103
 */
103
 */
104
WidgetSaisie.prototype.initEvts = function() {
104
WidgetSaisie.prototype.initEvts = function() {
105
	// identité
105
	// identité
106
	this.initEvtsConnection();
106
	this.initEvtsConnection();
107
	// on location, initialisation de la géoloc
107
	// on location, initialisation de la géoloc
108
	this.initEvtsGeoloc();
108
	this.initEvtsGeoloc();
109
	// Sur téléchargement image
109
	// Sur téléchargement image
110
	this.initEvtsFichier();
110
	this.initEvtsFichier();
111
 
111
 
112
	$( '#referentiel' ).on( 'change', this.surChangementReferentiel.bind( this ) );
112
	$( '#referentiel' ).on( 'change', this.surChangementReferentiel.bind( this ) );
113
	// Création / Suppression / Transmission des obs
113
	// Création / Suppression / Transmission des obs
114
	// Défilement des miniatures dans le résumé obs
114
	// Défilement des miniatures dans le résumé obs
115
	this.initEvtsObs();
115
	this.initEvtsObs();
116
	// Alertes et aides
116
	// Alertes et aides
117
	this.initEvtsAlertes();
117
	this.initEvtsAlertes();
118
	// message avant de quitter le formulaire
118
	// message avant de quitter le formulaire
119
	this.confirmerSortie();
119
	this.confirmerSortie();
120
};
120
};
121
 
121
 
122
// Identité Observateur par courriel
122
// Identité Observateur par courriel
123
WidgetSaisie.prototype.requeterIdentiteCourriel = function() {
123
WidgetSaisie.prototype.requeterIdentiteCourriel = function() {
124
	const lthis = this,
124
	const lthis = this,
125
		courriel    = $( '#courriel' ).val(),
125
		courriel    = $( '#courriel' ).val(),
126
		urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;
126
		urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;
127
 
127
 
128
	if ( valOk( courriel ) ) {
128
	if ( valOk( courriel ) ) {
129
		$.ajax({
129
		$.ajax({
130
			url : urlAnnuaire,
130
			url : urlAnnuaire,
131
			type : 'GET',
131
			type : 'GET',
132
			success : function( data, textStatus, jqXHR ) {
132
			success : function( data, textStatus, jqXHR ) {
133
				if ( lthis.debug ) {
133
				if ( lthis.debug ) {
134
					console.log( 'SUCCESS: ' + textStatus );
134
					console.log( 'SUCCESS: ' + textStatus );
135
				}
135
				}
136
				if ( valOk( data ) && valOk( data[courriel] ) ) {
136
				if ( valOk( data ) && valOk( data[courriel] ) ) {
137
					const infos = data[courriel];
137
					const infos = data[courriel];
138
					lthis.surSuccesCompletionCourriel( infos, courriel );
138
					lthis.surSuccesCompletionCourriel( infos, courriel );
139
				} else {
139
				} else {
140
					lthis.surErreurCompletionCourriel();
140
					lthis.surErreurCompletionCourriel();
141
				}
141
				}
142
			},
142
			},
143
			error : function( jqXHR, textStatus, errorThrown ) {
143
			error : function( jqXHR, textStatus, errorThrown ) {
144
				if ( lthis.debug ) {
144
				if ( lthis.debug ) {
145
					console.log( 'ERREUR: '+ textStatus );
145
					console.log( 'ERREUR: '+ textStatus );
146
				}
146
				}
147
				lthis.surErreurCompletionCourriel();
147
				lthis.surErreurCompletionCourriel();
148
			},
148
			},
149
			complete : function( jqXHR, textStatus ) {
149
			complete : function( jqXHR, textStatus ) {
150
				if ( lthis.debug ) {
150
				if ( lthis.debug ) {
151
					console.log( 'COMPLETE: '+ textStatus );
151
					console.log( 'COMPLETE: '+ textStatus );
152
				}
152
				}
153
			}
153
			}
154
		});
154
		});
155
	}
155
	}
156
};
156
};
157
 
157
 
158
// se déclanche quand on choisit "Observation sans inscription" mais que le mail entré est incrit à Tela
158
// se déclanche quand on choisit "Observation sans inscription" mais que le mail entré est incrit à Tela
159
WidgetSaisie.prototype.surSuccesCompletionCourriel = function( infos, courriel ) {
159
WidgetSaisie.prototype.surSuccesCompletionCourriel = function( infos, courriel ) {
160
	if ( $( '#utilisateur-connecte' ).hasClass( 'hidden' ) ) {// si quelque chose a foiré après actualisation
160
	if ( $( '#utilisateur-connecte' ).hasClass( 'hidden' ) ) {// si quelque chose a foiré après actualisation
161
		if ( !valOk( $( '#warning-identite' ) ) ) {
161
		if ( !valOk( $( '#warning-identite' ) ) ) {
162
			$( '#zone-courriel' ).before( '<p id="warning-identite" class="warning"><i class="fas fa-exclamation-triangle"></i> ' + this.msgTraduction( 'courriel-connu' ) + '</p>' );
162
			$( '#zone-courriel' ).before( '<p id="warning-identite" class="warning"><i class="fas fa-exclamation-triangle"></i> ' + this.msgTraduction( 'courriel-connu' ) + '</p>' );
163
		}
163
		}
164
		$( '#inscription, #zone-prenom-nom, #zone-courriel-confirmation' ).addClass( 'hidden' );
164
		$( '#inscription, #zone-prenom-nom, #zone-courriel-confirmation' ).addClass( 'hidden' );
165
		$( '#prenom, #nom, #courriel_confirmation' ).attr( 'disabled', 'disabled' );
165
		$( '#prenom, #nom, #courriel_confirmation' ).attr( 'disabled', 'disabled' );
166
		$( '.nav.control-group' ).addClass( 'error' );
166
		$( '.nav.control-group' ).addClass( 'error' );
167
	}
167
	}
168
};
168
};
169
 
169
 
170
// se déclanche quand on choisit "Observation sans inscription" et qu'effectivement le mail n'est pas connu de Tela
170
// se déclanche quand on choisit "Observation sans inscription" et qu'effectivement le mail n'est pas connu de Tela
171
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
171
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
172
	$( '#creation-compte, #zone-prenom-nom, #zone-courriel-confirmation' ).removeClass( 'hidden' );
172
	$( '#creation-compte, #zone-prenom-nom, #zone-courriel-confirmation' ).removeClass( 'hidden' );
173
	$( '#warning-identite' ).remove();
173
	$( '#warning-identite' ).remove();
174
	$( '.nav.control-group' ).removeClass( 'error' );
174
	$( '.nav.control-group' ).removeClass( 'error' );
175
	$( '#prenom, #nom, #courriel_confirmation' ).val( '' ).removeAttr( 'disabled' );
175
	$( '#prenom, #nom, #courriel_confirmation' ).val( '' ).removeAttr( 'disabled' );
176
};
176
};
177
 
177
 
178
WidgetSaisie.prototype.testerLancementRequeteIdentite = function( event ) {
178
WidgetSaisie.prototype.testerLancementRequeteIdentite = function( event ) {
179
	if ( valOk( event.which, true, 13 ) ) {
179
	if ( valOk( event.which, true, 13 ) ) {
180
		this.requeterIdentiteCourriel();
180
		this.requeterIdentiteCourriel();
181
		event.preventDefault();
181
		event.preventDefault();
182
		event.stopPropagation();
182
		event.stopPropagation();
183
	}
183
	}
184
};
184
};
185
 
185
 
186
WidgetSaisie.prototype.reduireVoletIdentite = function() {
186
WidgetSaisie.prototype.reduireVoletIdentite = function() {
187
	if ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() && $( '#courriel_confirmation' ).valid() ) {
187
	if ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() && $( '#courriel_confirmation' ).valid() ) {
188
		$( '#bouton-connexion, #creation-compte' ).addClass( 'hidden' );
188
		$( '#bouton-connexion, #creation-compte' ).addClass( 'hidden' );
189
		$( '#bienvenue').removeClass( 'hidden' );
189
		$( '#bienvenue').removeClass( 'hidden' );
190
		$( '#inscription, #zone-courriel' ).addClass( 'hidden' );
190
		$( '#inscription, #zone-courriel' ).addClass( 'hidden' );
191
		if ( valOk( $( '#nom' ).val() ) && valOk( $( '#prenom' ).val() ) ) {
191
		if ( valOk( $( '#nom' ).val() ) && valOk( $( '#prenom' ).val() ) ) {
192
			$( '#zone-prenom-nom' ).addClass( 'hidden' );
192
			$( '#zone-prenom-nom' ).addClass( 'hidden' );
193
			$( '#bienvenue-prenom' ).text( ' ' + $( '#prenom' ).val() );
193
			$( '#bienvenue-prenom' ).text( ' ' + $( '#prenom' ).val() );
194
			$( '#bienvenue-nom' ).text( ' ' + $( '#nom' ).val() );
194
			$( '#bienvenue-nom' ).text( ' ' + $( '#nom' ).val() );
195
		} else {
195
		} else {
196
			$( '#zone-prenom-nom' ).removeClass( 'hidden' );
196
			$( '#zone-prenom-nom' ).removeClass( 'hidden' );
197
			$( '#bienvenue-prenom,#bienvenue-nom' ).text( '' );
197
			$( '#bienvenue-prenom,#bienvenue-nom' ).text( '' );
198
		}
198
		}
199
	} else {
199
	} else {
200
		$( '#bouton-connexion, #creation-compte' ).removeClass( 'hidden' );
200
		$( '#bouton-connexion, #creation-compte' ).removeClass( 'hidden' );
201
		$( '#bienvenue').addClass( 'hidden' );
201
		$( '#bienvenue').addClass( 'hidden' );
202
	}
202
	}
203
};
203
};
204
 
204
 
205
 
205
 
206
WidgetSaisie.prototype.formaterNom = function() {
206
WidgetSaisie.prototype.formaterNom = function() {
207
	$( '#nom' ).val( $( '#nom' ).val().toUpperCase() );
207
	$( '#nom' ).val( $( '#nom' ).val().toUpperCase() );
208
};
208
};
209
 
209
 
210
WidgetSaisie.prototype.formaterPrenom = function() {
210
WidgetSaisie.prototype.formaterPrenom = function() {
211
	const prenom   = [],
211
	const prenom   = [],
212
		mots       = $( '#prenom' ).val().split( ' ' ),
212
		mots       = $( '#prenom' ).val().split( ' ' ),
213
		motsLength = mots.length;
213
		motsLength = mots.length;
214
 
214
 
215
	for ( let i = 0; i < motsLength; i++ ) {
215
	for ( let i = 0; i < motsLength; i++ ) {
216
		let mot          = mots[i],
216
		let mot          = mots[i],
217
			motMajuscule = '';
217
			motMajuscule = '';
218
 
218
 
219
		if ( 0 <= mot.indexOf( '-' ) ) {
219
		if ( 0 <= mot.indexOf( '-' ) ) {
220
			const prenomCompose    = new Array(),
220
			const prenomCompose    = new Array(),
221
				motsComposes       = mot.split( '-' ),
221
				motsComposes       = mot.split( '-' ),
222
				motsComposesLength = motsComposes.length;
222
				motsComposesLength = motsComposes.length;
223
 
223
 
224
			for ( let j = 0; j < motsComposesLength; j++ ) {
224
			for ( let j = 0; j < motsComposesLength; j++ ) {
225
				const motSimple    = motsComposes[j];
225
				const motSimple    = motsComposes[j];
226
 
226
 
227
				motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
227
				motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
228
				prenomCompose.push( motMajuscule );
228
				prenomCompose.push( motMajuscule );
229
			}
229
			}
230
			prenom.push( prenomCompose.join( '-' ) );
230
			prenom.push( prenomCompose.join( '-' ) );
231
		} else {
231
		} else {
232
			motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
232
			motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
233
			prenom.push( motMajuscule );
233
			prenom.push( motMajuscule );
234
		}
234
		}
235
	}
235
	}
236
	$( '#prenom' ).val( prenom.join( ' ' ) );
236
	$( '#prenom' ).val( prenom.join( ' ' ) );
237
};
237
};
238
 
238
 
239
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
239
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
240
	this.afficherPanneau( '#dialogue-bloquer-copier-coller' );
240
	this.afficherPanneau( '#dialogue-bloquer-copier-coller' );
241
 
241
 
242
	return false;
242
	return false;
243
};
243
};
244
 
244
 
245
// Préchargement des infos-obs ************************************************/
245
// Préchargement des infos-obs ************************************************/
246
WidgetSaisie.prototype.chargerInfoObs = function() {
246
WidgetSaisie.prototype.chargerInfoObs = function() {
247
	const lthis = this,
247
	const lthis = this,
248
		urlObs  = this.serviceObsUrl + '/' + this.obsId;
248
		urlObs  = this.serviceObsUrl + '/' + this.obsId;
249
 
249
 
250
	$.ajax({
250
	$.ajax({
251
		url: urlObs,
251
		url: urlObs,
252
		type: 'GET',
252
		type: 'GET',
253
		success: function( data, textStatus, jqXHR ) {
253
		success: function( data, textStatus, jqXHR ) {
254
			if ( valOk( data ) ) {
254
			if ( valOk( data ) ) {
255
				lthis.prechargerForm( data );
255
				lthis.prechargerForm( data );
256
			} else {
256
			} else {
257
				lthis.surErreurChargementInfosObs.bind( lthis );
257
				lthis.surErreurChargementInfosObs.bind( lthis );
258
			}
258
			}
259
		},
259
		},
260
		error: function( jqXHR, textStatus, errorThrown ) {
260
		error: function( jqXHR, textStatus, errorThrown ) {
261
			lthis.surErreurChargementInfosObs();
261
			lthis.surErreurChargementInfosObs();
262
		}
262
		}
263
	});
263
	});
264
};
264
};
265
 
265
 
266
// @TODO faire mieux que ça !
266
// @TODO faire mieux que ça !
267
WidgetSaisie.prototype.surErreurChargementInfosObs = function() {
267
WidgetSaisie.prototype.surErreurChargementInfosObs = function() {
268
	utils.activerModale( this.msgTraduction( 'erreur-chargement' ) );
268
	utils.activerModale( this.msgTraduction( 'erreur-chargement' ) );
269
};
269
};
270
 
270
 
271
WidgetSaisie.prototype.prechargerForm = function( data ) {
271
WidgetSaisie.prototype.prechargerForm = function( data ) {
272
	$( '#milieu' ).val( data.milieu );
272
	$( '#milieu' ).val( data.milieu );
273
	$( '#commune-nom' ).text( data.zoneGeo );
273
	$( '#commune-nom' ).text( data.zoneGeo );
274
	if( data.hasOwnProperty( 'codeZoneGeo' ) ) {
274
	if( data.hasOwnProperty( 'codeZoneGeo' ) ) {
275
	  // TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
275
	  // TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
276
	  $( '#commune-insee' ).text( data.codeZoneGeo.replace( 'INSEE-C:', '' ) );
276
	  $( '#commune-insee' ).text( data.codeZoneGeo.replace( 'INSEE-C:', '' ) );
277
	}
277
	}
278
 
278
 
279
	if( data.hasOwnProperty( 'latitude' ) && data.hasOwnProperty( 'longitude' ) ) {
279
	if( data.hasOwnProperty( 'latitude' ) && data.hasOwnProperty( 'longitude' ) ) {
280
		// $cartoRemplacee = $( '#tb-geolocation' ),
280
		// $cartoRemplacee = $( '#tb-geolocation' ),
281
		// suffixe = '',
281
		// suffixe = '',
282
		// layer = 'osm',
282
		// layer = 'osm',
283
		// zoomInit = 18
283
		// zoomInit = 18
284
		const typeLocalisation = $( '#top' ).data( 'type-loc' ),
284
		const typeLocalisation = $( '#top' ).data( 'type-loc' ),
285
			donnesResetCarto   = {
285
			donnesResetCarto   = {
286
			latitude         : data.latitude,
286
			latitude         : data.latitude,
287
			longitude        : data.longitude,
287
			longitude        : data.longitude,
288
			typeLocalisation : typeLocalisation,
288
			typeLocalisation : typeLocalisation,
289
			zoom             : 18
289
			zoom             : 18
290
		};
290
		};
291
		this.transfererCarto( donnesResetCarto );
291
		this.transfererCarto( donnesResetCarto );
292
	}
292
	}
293
};
293
};
294
 
294
 
295
// Ajouter Obs ****************************************************************/
295
// Ajouter Obs ****************************************************************/
296
/**
296
/**
297
 * Retourne un Array contenant les valeurs des champs étendus
297
 * Retourne un Array contenant les valeurs des champs étendus
298
 */
298
 */
299
WidgetSaisie.prototype.getObsChpSpecifiques = function() {
299
WidgetSaisie.prototype.getObsChpSpecifiques = function() {
300
	const lthis = this,
300
	const lthis = this,
301
		champs    = [],
301
		champs    = [],
302
		$thisForm = $( '#form-supp' ),
302
		$thisForm = $( '#form-supp' ),
303
		elements  =
303
		elements  =
304
			'input[type=text]:not(.collect-other),'+
304
			'input[type=text]:not(.collect-other),'+
305
			'input[type=checkbox]:checked,'+
305
			'input[type=checkbox]:checked,'+
306
			'input[type=radio]:checked,'+
306
			'input[type=radio]:checked,'+
307
			'input[type=email],'+
307
			'input[type=email],'+
308
			'input[type=number],'+
308
			'input[type=number],'+
309
			'input[type=range],'+
309
			'input[type=range],'+
310
			'input[type=date],'+
310
			'input[type=date],'+
311
			'textarea,'+
311
			'textarea,'+
312
			'.select',
312
			'.select',
313
		retour    = [];
313
		retour    = [];
314
 
314
 
315
	$( elements, $thisForm ).each( function() {
315
	$( elements, $thisForm ).each( function() {
316
		if ( valOk( $( this ).val() ) && ( valOk( $( this ).attr( 'name' ) ) || valOk( $( this ).data( 'name' ) ) ) ) {
316
		if ( valOk( $( this ).val() ) && ( valOk( $( this ).attr( 'name' ) ) || valOk( $( this ).data( 'name' ) ) ) ) {
317
			const valeur = $( this ).val(),
317
			const valeur = $( this ).val(),
318
				cle    = ( valOk( $( this ).attr( 'name' ) ) ) ? $( this ).attr( 'name' ) : $( this ).data( 'name' );
318
				cle    = ( valOk( $( this ).attr( 'name' ) ) ) ? $( this ).attr( 'name' ) : $( this ).data( 'name' );
319
			if ( cle in champs ) {
319
			if ( cle in champs ) {
320
				champs[cle] += ';' + valeur;
320
				champs[cle] += ';' + valeur;
321
			} else {
321
			} else {
322
				champs[cle] = valeur;
322
				champs[cle] = valeur;
323
			}
323
			}
324
		}
324
		}
325
	});
325
	});
326
	for ( let key in champs ) {
326
	for ( let key in champs ) {
327
		retour.push({ 'cle' : key , 'valeur' : champs[key] });
327
		retour.push({ 'cle' : key , 'valeur' : champs[key] });
328
	}
328
	}
329
	if ( valOk( $( '#coord-lineaire' ).val() ) ) {
329
	if ( valOk( $( '#coord-lineaire' ).val() ) ) {
330
		retour.push({ 'cle' : 'coordonnees-rue-ou-lineaire' , 'valeur' : $( '#coord-lineaire' ).val() });
330
		retour.push({ 'cle' : 'coordonnees-rue-ou-lineaire' , 'valeur' : $( '#coord-lineaire' ).val() });
331
	}
331
	}
332
	return retour;
332
	return retour;
333
};
333
};
334
 
334
 
335
WidgetSaisie.prototype.reinitialiserForm = function() {
335
WidgetSaisie.prototype.reinitialiserForm = function() {
336
	this.supprimerMiniatures();
336
	this.supprimerMiniatures();
337
	if( !this.especeImposee ) {
337
	if( !this.especeImposee ) {
338
		$( '#taxon' ).val( '' );
338
		$( '#taxon' ).val( '' );
339
		$( '#taxon' ).data( 'numNomSel', '' )
339
		$( '#taxon' ).data( 'numNomSel', '' )
340
			.data( 'nomRet','' )
340
			.data( 'nomRet','' )
341
			.data( 'numNomRet', '' )
341
			.data( 'numNomRet', '' )
342
			.data( 'nt', '' )
342
			.data( 'nt', '' )
343
			.data( 'famille', '' );
343
			.data( 'famille', '' );
344
		if( this.isTaxonListe ) {
344
		if( this.isTaxonListe ) {
345
			$( '#taxon-liste' ).find( 'option' ).each( function() {
345
			$( '#taxon-liste' ).find( 'option' ).each( function() {
346
				if ( $( this ).hasClass( 'choisir' ) ) {
346
				if ( $( this ).hasClass( 'choisir' ) ) {
347
					$( this ).attr( 'selected', true );
347
					$( this ).attr( 'selected', true );
348
				} else {
348
				} else {
349
					$( this ).attr( 'selected', false );
349
					$( this ).attr( 'selected', false );
350
				}
350
				}
351
			});
351
			});
352
			$( '#taxon-input-groupe' ).addClass( 'hidden' );
352
			$( '#taxon-input-groupe' ).addClass( 'hidden' );
353
			$('#taxon-autre').val('');
353
			$('#taxon-autre').val('');
354
		}
354
		}
355
	}
355
	}
356
	if ( valOk( $( '#form-supp' ) ) ) {
356
	if ( valOk( $( '#form-supp' ) ) ) {
357
		$( '#form-supp' ).validate().resetForm();
357
		$( '#form-supp' ).validate().resetForm();
358
	}
358
	}
359
};
359
};
-
 
360
 
-
 
361
WidgetSaisie.prototype.validateGeometry = function( geometry ) {
-
 
362
	const isLineString = !!geometry && 'LineString' === geometry.type,
-
 
363
		validateTypeOfCoordinates = coordinates => isLineString ? Array.isArray( coordinates ) : ['number','string'].includes( typeof coordinates );
-
 
364
 
-
 
365
	if ( !valOk( geometry.coordinates ) ) {
-
 
366
		return false;
-
 
367
	}
-
 
368
 
-
 
369
	let isValid = true;
-
 
370
 
-
 
371
	$.each(geometry.coordinates, (i, coordinates) => {
-
 
372
		if ( !validateTypeOfCoordinates( coordinates ) ) {
-
 
373
			isValid = false;
-
 
374
		}
-
 
375
	});
-
 
376
 
-
 
377
	const isValidLength = isLineString ? ( geometry.coordinates.length >= 2 ) : ( geometry.coordinates.length === 2 );
-
 
378
 
-
 
379
	return isValid && isValidLength;
-
 
380
}
360
 
381
 
361
// Géolocalisation *************************************************************/
382
// Géolocalisation *************************************************************/
362
/**
383
/**
363
 * Fonction handler de l'évenement location du module tb-geoloc
384
 * Fonction handler de l'évenement location du module tb-geoloc
364
 */
385
 */
365
WidgetSaisie.prototype.locationHandler = function( location ) {
386
WidgetSaisie.prototype.locationHandler = function( location ) {
366
	const locDatas = location.originalEvent.detail;
387
	const locDatas          = location.originalEvent.detail,
-
 
388
		$geolocControlGroup = $( '#geoloc' ).closest( '.control-group' );
367
 
389
 
368
	if ( valOk( locDatas ) ) {
390
	if ( !valOk( locDatas ) ) {
369
		console.log( locDatas );
-
 
370
 
-
 
371
		const geometry = JSON.stringify( locDatas.geometry ),
-
 
372
			altitude   = ( valOk( locDatas.elevation ) ) ? locDatas.elevation : '',
-
 
373
			pays       = ( valOk( locDatas.osmCountryCode ) ) ? locDatas.osmCountryCode.toUpperCase() : 'FR',
-
 
374
			rue        = ( valOk( locDatas.osmRoad ) ) ? locDatas.osmRoad : '';
-
 
375
		let latitude      = '',
-
 
376
			longitude     = '',
-
 
377
			coordLineaire = '',
-
 
378
			nomCommune    = '',
-
 
379
			communeInsee  = '';
-
 
380
 
-
 
381
		if ( valOk( locDatas.geometry.coordinates ) &&
-
 
382
			valOk( locDatas.centroid.coordinates ) &&
-
 
383
			valOk( locDatas.centroid.coordinates[0] ) &&
-
 
384
			valOk( locDatas.centroid.coordinates[1] )
391
		console.warn( 'Error location' );
385
		) {
-
 
386
			longitude = locDatas.centroid.coordinates[0];
-
 
387
			latitude = locDatas.centroid.coordinates[1];
-
 
388
		}
392
	} else {
389
		if ( valOk( locDatas.inseeData ) ) {
-
 
390
			nomCommune = locDatas.inseeData.nom;
-
 
391
			communeInsee = ( valOk( locDatas.inseeData.code ) ) ? locDatas.inseeData.code : '';
-
 
392
		} else if ( valOk( locDatas.locality ) ) {
-
 
393
			nomCommune = locDatas.locality;
-
 
394
		} else if ( valOk( locDatas.locality ) ) {
393
		if ( !this.validateGeometry( locDatas.geometry ) ) {
395
			nomCommune = locDatas.osmCounty;
-
 
396
		}
394
			$geolocControlGroup.addClass( 'error' );
397
		$( '#geometry' ).val( geometry );
-
 
398
		$( '#coord-lineaire' ).val( coordLineaire );
-
 
399
		$( '#latitude' ).val( latitude );
-
 
400
		$( '#longitude' ).val( longitude );
-
 
401
		$( '#commune-nom' ).val( nomCommune );
-
 
402
		$( '#commune-insee' ).val( communeInsee );
-
 
403
		$( '#altitude' ).val( altitude );
-
 
404
		$( '#pays' ).val( pays );
-
 
405
		$( '#station' ).val( rue );
-
 
406
		$( '#latitude, #longitude' ).valid();
-
 
407
		if ( valOk( $( '#latitude' ).val() ) && valOk( $( '#longitude' ).val() ) ) {
-
 
408
			$( '#geoloc' ).closest( '.control-group' ).removeClass( 'error' );
395
			$( '#geometry' ).val( '' );
-
 
396
		} else {
-
 
397
			console.log( locDatas );
-
 
398
 
-
 
399
			const geometry = JSON.stringify( locDatas.geometry ),
-
 
400
				altitude   = ( valOk( locDatas.elevation ) ) ? locDatas.elevation : '',
-
 
401
				pays       = ( valOk( locDatas.osmCountryCode ) ) ? locDatas.osmCountryCode.toUpperCase() : 'FR',
-
 
402
				rue        = ( valOk( locDatas.osmRoad ) ) ? locDatas.osmRoad : '';
-
 
403
			let latitude      = '',
-
 
404
				longitude     = '',
-
 
405
				coordLineaire = '',
-
 
406
				nomCommune    = '',
-
 
407
				communeInsee  = '';
-
 
408
 
-
 
409
			if ( valOk( locDatas.geometry.coordinates ) &&
-
 
410
				valOk( locDatas.centroid.coordinates ) &&
-
 
411
				valOk( locDatas.centroid.coordinates[0] ) &&
-
 
412
				valOk( locDatas.centroid.coordinates[1] )
-
 
413
			) {
-
 
414
				longitude = locDatas.centroid.coordinates[0];
-
 
415
				latitude = locDatas.centroid.coordinates[1];
-
 
416
			}
-
 
417
			if ( valOk( locDatas.inseeData ) ) {
-
 
418
				nomCommune = locDatas.inseeData.nom;
-
 
419
				communeInsee = ( valOk( locDatas.inseeData.code ) ) ? locDatas.inseeData.code : '';
-
 
420
			} else if ( valOk( locDatas.locality ) ) {
-
 
421
				nomCommune = locDatas.locality;
-
 
422
			} else if ( valOk( locDatas.locality ) ) {
-
 
423
				nomCommune = locDatas.osmCounty;
-
 
424
			}
-
 
425
			$( '#geometry' ).val( geometry );
-
 
426
			$( '#coord-lineaire' ).val( coordLineaire );
-
 
427
			$( '#latitude' ).val( latitude );
-
 
428
			$( '#longitude' ).val( longitude );
-
 
429
			$( '#commune-nom' ).val( nomCommune );
-
 
430
			$( '#commune-insee' ).val( communeInsee );
-
 
431
			$( '#altitude' ).val( altitude );
-
 
432
			$( '#pays' ).val( pays );
-
 
433
			$( '#station' ).val( rue );
409
		} else {
434
			$( '#latitude, #longitude' ).valid();
-
 
435
			$geolocControlGroup.toggleClass(
-
 
436
					'error',
-
 
437
					!valOk( $( '#latitude' ).val() ) || !valOk( $( '#longitude' ).val() )
410
			$( '#geoloc' ).closest( '.control-group' ).addClass( 'error' );
438
				);
411
		}
-
 
412
	} else {
-
 
413
		console.warn( 'Error location' );
439
		}
414
	}
440
	}
415
}
441
}
416
 
442
 
417
// Form Validator *************************************************************/
443
// Form Validator *************************************************************/
418
WidgetSaisie.prototype.chpEtendusValidation = function() {
444
WidgetSaisie.prototype.chpEtendusValidation = function() {
419
	const lthis = this,
445
	const lthis = this,
420
		$thisForm = $( '#form-supp' ),
446
		$thisForm = $( '#form-supp' ),
421
		elements  =
447
		elements  =
422
			'.checkbox,'+
448
			'.checkbox,'+
423
			'.radio,'+
449
			'.radio,'+
424
			'.checkboxes,'+
450
			'.checkboxes,'+
425
			'.select,'+
451
			'.select,'+
426
			'textarea,'+
452
			'textarea,'+
427
			'input[type=text]:not(.collect-other),'+
453
			'input[type=text]:not(.collect-other),'+
428
			'input[type=email],'+
454
			'input[type=email],'+
429
			'input[type=number],'+
455
			'input[type=number],'+
430
			'input[type=range],'+
456
			'input[type=range],'+
431
			'input[type=date]',
457
			'input[type=date]',
432
		speFields = ['checkbox','radio','checkboxes','select'],
458
		speFields = ['checkbox','radio','checkboxes','select'],
433
		spefieldsCount = speFields.length,
459
		spefieldsCount = speFields.length,
434
		chpSuppValidation = {
460
		chpSuppValidation = {
435
			rules : {},
461
			rules : {},
436
			messages : {},
462
			messages : {},
437
			minmax : []
463
			minmax : []
438
		},
464
		},
439
		errors = {},
465
		errors = {},
440
		namesListFields = [];
466
		namesListFields = [];
441
	let picked = '';
467
	let picked = '';
442
 
468
 
443
	$( elements, $thisForm ).each( function() {
469
	$( elements, $thisForm ).each( function() {
444
		for( let fieldsClass = 0; spefieldsCount > fieldsClass; fieldsClass++ ) {
470
		for( let fieldsClass = 0; spefieldsCount > fieldsClass; fieldsClass++ ) {
445
				const dataName = $( this ).data( 'name' );
471
				const dataName = $( this ).data( 'name' );
446
 
472
 
447
			if ( valOk( $( this ).attr( 'required' ) ) && $( this ).hasClass( speFields[fieldsClass] ) && !valOk( chpSuppValidation.rules[ dataName ] ) ) {
473
			if ( valOk( $( this ).attr( 'required' ) ) && $( this ).hasClass( speFields[fieldsClass] ) && !valOk( chpSuppValidation.rules[ dataName ] ) ) {
448
				namesListFields.push( dataName );
474
				namesListFields.push( dataName );
449
				chpSuppValidation.rules[ dataName ] = { required : true };
475
				chpSuppValidation.rules[ dataName ] = { required : true };
450
				if ( valOk( $( '.other', $( this ) ) ) ) {
476
				if ( valOk( $( '.other', $( this ) ) ) ) {
451
					picked = ( 'select' === speFields[fieldsClass] ) ? ':selected' : ':checked';
477
					picked = ( 'select' === speFields[fieldsClass] ) ? ':selected' : ':checked';
452
					chpSuppValidation.rules[ 'collect-other-' + dataName.replace( '[]', '' ) ] = {
478
					chpSuppValidation.rules[ 'collect-other-' + dataName.replace( '[]', '' ) ] = {
453
						required : '#other-' + dataName.replace( '[]', '' ) + picked,
479
						required : '#other-' + dataName.replace( '[]', '' ) + picked,
454
						minlength: 1
480
						minlength: 1
455
					};
481
					};
456
					chpSuppValidation.messages[ 'collect-other-' + dataName.replace( '[]', '' ) ] = false;
482
					chpSuppValidation.messages[ 'collect-other-' + dataName.replace( '[]', '' ) ] = false;
457
				}
483
				}
458
				chpSuppValidation.rules[ dataName ]['listFields'] = true;
484
				chpSuppValidation.rules[ dataName ]['listFields'] = true;
459
				chpSuppValidation.messages[ dataName ] = 'Ce champ est requis :\nVeuillez choisir une option, ou entrer une valeur autre valide.';
485
				chpSuppValidation.messages[ dataName ] = 'Ce champ est requis :\nVeuillez choisir une option, ou entrer une valeur autre valide.';
460
				errors[dataName] = '.' + speFields[fieldsClass];
486
				errors[dataName] = '.' + speFields[fieldsClass];
461
			}
487
			}
462
		}
488
		}
463
		if ( valOk( $( this ).attr( 'name' ) ) && valOk ( $( this ).attr( 'required' ) ) && 0 > $.inArray( $( this ).attr( 'name' ) , namesListFields ) ) {
489
		if ( valOk( $( this ).attr( 'name' ) ) && valOk ( $( this ).attr( 'required' ) ) && 0 > $.inArray( $( this ).attr( 'name' ) , namesListFields ) ) {
464
			chpSuppValidation.rules[ $( this ).attr( 'name' ) ] = { required : true, minlength: 1 };
490
			chpSuppValidation.rules[ $( this ).attr( 'name' ) ] = { required : true, minlength: 1 };
465
			if(
491
			if(
466
				( valOk( $( this ).attr( 'type' ), true, 'number' ) || valOk( $( this ).attr( 'type' ), true, 'range' ) ) &&
492
				( valOk( $( this ).attr( 'type' ), true, 'number' ) || valOk( $( this ).attr( 'type' ), true, 'range' ) ) &&
467
				( valOk( $( this )[0].min ) || valOk( $( this )[0].max ) )
493
				( valOk( $( this )[0].min ) || valOk( $( this )[0].max ) )
468
			) {
494
			) {
469
				chpSuppValidation.rules[ $( this ).attr('name') ]['minMaxOk'] = true;
495
				chpSuppValidation.rules[ $( this ).attr('name') ]['minMaxOk'] = true;
470
				chpSuppValidation.messages[ $( this ).attr('name') ] = lthis.validerMinMax( $( this )[0] ).message;
496
				chpSuppValidation.messages[ $( this ).attr('name') ] = lthis.validerMinMax( $( this )[0] ).message;
471
			}
497
			}
472
		}
498
		}
473
	});
499
	});
474
	if ( valOk( chpSuppValidation.rules ) ) {
500
	if ( valOk( chpSuppValidation.rules ) ) {
475
		$.each( chpSuppValidation.rules, function( key ) {
501
		$.each( chpSuppValidation.rules, function( key ) {
476
			if ( !valOk( chpSuppValidation.messages[key] ) ) {
502
			if ( !valOk( chpSuppValidation.messages[key] ) ) {
477
				chpSuppValidation.messages[key] = 'Ce champ est requis :\nVeuillez entrer une valeur valide.';
503
				chpSuppValidation.messages[key] = 'Ce champ est requis :\nVeuillez entrer une valeur valide.';
478
			}
504
			}
479
		});
505
		});
480
		if ( 0 < Object.keys( errors ).length ) {
506
		if ( 0 < Object.keys( errors ).length ) {
481
			chpSuppValidation['errors'] = errors;
507
			chpSuppValidation['errors'] = errors;
482
		}
508
		}
483
	}
509
	}
484
	return chpSuppValidation;
510
	return chpSuppValidation;
485
};
511
};
486
 
512
 
487
WidgetSaisie.prototype.validerMinMax = function( element ) {
513
WidgetSaisie.prototype.validerMinMax = function( element ) {
488
	const minCond  = parseFloat( element.value ) >= parseFloat( element.min ),
514
	const minCond  = parseFloat( element.value ) >= parseFloat( element.min ),
489
		maxCond    = parseFloat( element.value ) <= parseFloat( element.max ),
515
		maxCond    = parseFloat( element.value ) <= parseFloat( element.max ),
490
		returnMnMx = { cond : true , message : '' };
516
		returnMnMx = { cond : true , message : '' };
491
	let mnMxCond    = new Boolean(),
517
	let mnMxCond    = new Boolean(),
492
		messageMnMx = 'La valeur entrée doit être';
518
		messageMnMx = 'La valeur entrée doit être';
493
 
519
 
494
	if(
520
	if(
495
		( valOk( element.type, true, 'number' ) || valOk( element.type, true, 'range' ) ) &&
521
		( valOk( element.type, true, 'number' ) || valOk( element.type, true, 'range' ) ) &&
496
		( valOk( element.min ) || valOk( element.max ) )
522
		( valOk( element.min ) || valOk( element.max ) )
497
	) {
523
	) {
498
		if ( element.min && element.max ) {
524
		if ( element.min && element.max ) {
499
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
525
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
500
			mnMxCond     = ( minCond && maxCond );
526
			mnMxCond     = ( minCond && maxCond );
501
		} else if ( element.min ) {
527
		} else if ( element.min ) {
502
			messageMnMx += ' supérieure à ' + element.min;
528
			messageMnMx += ' supérieure à ' + element.min;
503
			mnMxCond     = minCond;
529
			mnMxCond     = minCond;
504
		} else {
530
		} else {
505
			messageMnMx += ' inférieure à ' + element.max;
531
			messageMnMx += ' inférieure à ' + element.max;
506
			mnMxCond     = maxCond;
532
			mnMxCond     = maxCond;
507
		}
533
		}
508
		returnMnMx.cond    = mnMxCond;
534
		returnMnMx.cond    = mnMxCond;
509
		returnMnMx.message = messageMnMx;
535
		returnMnMx.message = messageMnMx;
510
	}
536
	}
511
	return returnMnMx;
537
	return returnMnMx;
512
 
538
 
513
};
539
};
514
 
540
 
515
WidgetSaisie.prototype.definirReglesFormValidator = function() {
541
WidgetSaisie.prototype.definirReglesFormValidator = function() {
516
	const lthis = this,
542
	const lthis = this,
517
		formSuppValidation = this.chpEtendusValidation();
543
		formSuppValidation = this.chpEtendusValidation();
518
 
544
 
519
	$( '#form-supp' ).validate({
545
	$( '#form-supp' ).validate({
520
		onclick : function( element ) {
546
		onclick : function( element ) {
521
			if (
547
			if (
522
				(
548
				(
523
					valOk( element.type, true, 'checkbox' ) ||
549
					valOk( element.type, true, 'checkbox' ) ||
524
					valOk( element.type, true, 'radio' )
550
					valOk( element.type, true, 'radio' )
525
				) &&
551
				) &&
526
				(
552
				(
527
					!valOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':checked' ) ) ||
553
					!valOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':checked' ) ) ||
528
					valOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':not(.other):checked' ) ) ||
554
					valOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':not(.other):checked' ) ) ||
529
					!valOk( $( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ) ) ||
555
					!valOk( $( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ) ) ||
530
					$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) ||
556
					$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) ||
531
					(
557
					(
532
						$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) &&
558
						$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) &&
533
						$( element ).closest( '.control-group' ).hasClass('error')
559
						$( element ).closest( '.control-group' ).hasClass('error')
534
					)
560
					)
535
				)
561
				)
536
			) {
562
			) {
537
				$( element ).valid();
563
				$( element ).valid();
538
				if ( $( element ).valid() ) {
564
				if ( $( element ).valid() ) {
539
					$( element ).closest( '.control-group' ).removeClass( 'error' );
565
					$( element ).closest( '.control-group' ).removeClass( 'error' );
540
					$( element ).next( $( 'span.error' ) ).remove();
566
					$( element ).next( $( 'span.error' ) ).remove();
541
				} else {
567
				} else {
542
					$( element ).closest( '.control-group' ).addClass( 'error' );
568
					$( element ).closest( '.control-group' ).addClass( 'error' );
543
				}
569
				}
544
			}
570
			}
545
			return false;
571
			return false;
546
		},
572
		},
547
		rules : formSuppValidation.rules,
573
		rules : formSuppValidation.rules,
548
		messages : formSuppValidation.messages,
574
		messages : formSuppValidation.messages,
549
		errorPlacement : function( error , element ) {
575
		errorPlacement : function( error , element ) {
550
			if ( 0 < Object.keys( formSuppValidation.errors ).length ) {
576
			if ( 0 < Object.keys( formSuppValidation.errors ).length ) {
551
				const errorsKeys = Object.keys( formSuppValidation.errors );
577
				const errorsKeys = Object.keys( formSuppValidation.errors );
552
				let thisKey    = '',
578
				let thisKey    = '',
553
					errorsFlag = true;
579
					errorsFlag = true;
554
 
580
 
555
				for ( let i = 0 ; i < errorsKeys.length ; i++ ) {
581
				for ( let i = 0 ; i < errorsKeys.length ; i++ ) {
556
					thisKey = errorsKeys[i];
582
					thisKey = errorsKeys[i];
557
					if( $( element ).attr( 'name' ) === thisKey ) {
583
					if( $( element ).attr( 'name' ) === thisKey ) {
558
						$( formSuppValidation.errors[thisKey] ).append( error );
584
						$( formSuppValidation.errors[thisKey] ).append( error );
559
						errorsFlag = false;
585
						errorsFlag = false;
560
					}
586
					}
561
				}
587
				}
562
				if ( errorsFlag ) {
588
				if ( errorsFlag ) {
563
					error.insertAfter( element );
589
					error.insertAfter( element );
564
				}
590
				}
565
			} else {
591
			} else {
566
				error.insertAfter( element );
592
				error.insertAfter( element );
567
			}
593
			}
568
		}
594
		}
569
	});
595
	});
570
	$( '#form-supp .select' ).change( function() {
596
	$( '#form-supp .select' ).change( function() {
571
		$( this ).valid();
597
		$( this ).valid();
572
	});
598
	});
573
	$( 'input[type=date]' ).on( 'input', function() {
599
	$( 'input[type=date]' ).on( 'input', function() {
574
		$( this ).valid();
600
		$( this ).valid();
575
	});
601
	});
576
	// Validation taxon
602
	// Validation taxon
577
	// et gestion des messages d'erreur taxon et images en fonction de la certitude
603
	// et gestion des messages d'erreur taxon et images en fonction de la certitude
578
	$( '#taxon, #certitude' ).on( 'change', function() {
604
	$( '#taxon, #certitude' ).on( 'change', function() {
579
		lthis.validerTaxonRequis( valOk( $( '#taxon' ).val() ) );
605
		lthis.validerTaxonRequis( valOk( $( '#taxon' ).val() ) );
580
	});
606
	});
581
	// Validation miniatures avec MutationObserver
607
	// Validation miniatures avec MutationObserver
582
	this.surPresenceAbsenceMiniature();
608
	this.surPresenceAbsenceMiniature();
583
	$( '#form-observation' ).validate({
609
	$( '#form-observation' ).validate({
584
		rules : {
610
		rules : {
585
			date_releve : {
611
			date_releve : {
586
				required : true,
612
				required : true,
587
				'dateCel' : true
613
				'dateCel' : true
588
			},
614
			},
589
			latitude : {
615
			latitude : {
590
				required : true,
616
				required : true,
591
				minlength : 1,
617
				minlength : 1,
592
				range : [-90, 90]
618
				range : [-90, 90]
593
			},
619
			},
594
			longitude : {
620
			longitude : {
595
				required : true,
621
				required : true,
596
				minlength : 1,
622
				minlength : 1,
597
				range : [-180, 180]
623
				range : [-180, 180]
598
			}
624
			}
599
		}
625
		}
600
	});
626
	});
601
	$( '#form-observateur' ).validate({
627
	$( '#form-observateur' ).validate({
602
		rules : {
628
		rules : {
603
			courriel : {
629
			courriel : {
604
				required : true,
630
				required : true,
605
				email : true,
631
				email : true,
606
				'userEmailOk' : true
632
				'userEmailOk' : true
607
			},
633
			},
608
			courriel_confirmation : {
634
			courriel_confirmation : {
609
				required : true,
635
				required : true,
610
				equalTo : '#courriel'
636
				equalTo : '#courriel'
611
			}
637
			}
612
		}
638
		}
613
	});
639
	});
614
	$( '#connexion,#inscription,#bouton-anonyme' ).on( 'click', function( event ) {
640
	$( '#connexion,#inscription,#bouton-anonyme' ).on( 'click', function( event ) {
615
		$( '.nav.control-group' ).removeClass( 'error' );
641
		$( '.nav.control-group' ).removeClass( 'error' );
616
	});
642
	});
617
};
643
};
618
 
644
 
619
 
645
 
620
WidgetSaisie.prototype.validerCertitudeTaxonImage = function( hasTaxon = false, hasImages = false ) {
646
WidgetSaisie.prototype.validerCertitudeTaxonImage = function( hasTaxon = false, hasImages = false ) {
621
	const isCertain = 'certain' === $( '#certitude' ).val();
647
	const isCertain = 'certain' === $( '#certitude' ).val();
622
	let isvalide = true ;
648
	let isvalid = true ;
623
 
649
 
624
	if ( this.photoObligatoire || !isCertain ) {
650
	if ( this.photoObligatoire || !isCertain ) {
625
		isvalide = this.validerImageRequise( hasImages );
651
		isvalid = this.validerImageRequise( hasImages );
626
	}
652
	}
627
	if ( isCertain ) {
653
	if ( isCertain ) {
628
		isvalide &= this.validerTaxonRequis( hasTaxon );
654
		isvalid &= this.validerTaxonRequis( hasTaxon );
629
	}
655
	}
630
 
-
 
631
	return isvalide;
-
 
632
 
656
 
633
 
657
	return isvalid;
634
};
658
};
635
 
659
 
636
WidgetSaisie.prototype.validerTaxonRequis = function( hasTaxon = false ) {
660
WidgetSaisie.prototype.validerTaxonRequis = function( hasTaxon = false ) {
637
	const taxonEstRequis = 'certain' === $( '#certitude' ).val();
661
	const taxonEstRequis = 'certain' === $( '#certitude' ).val();
638
 
662
 
639
	if ( !this.photoObligatoire ) {
663
	if ( !this.photoObligatoire ) {
640
		$( '#photos-conteneur').removeClass( 'error' )
664
		$( '#photos-conteneur').removeClass( 'error' )
641
			.find( 'span.error' ).hide();
665
			.find( 'span.error' ).hide();
642
	}
666
	}
643
 
667
 
644
	if ( !hasTaxon && taxonEstRequis ) {
668
	if ( !hasTaxon && taxonEstRequis ) {
645
		this.afficherPanneau( '#dialogue-taxon-or-image' );
669
		this.afficherPanneau( '#dialogue-taxon-or-image' );
646
		$( '#bloc-taxon' ).addClass( 'error' )
670
		$( '#bloc-taxon' ).addClass( 'error' )
647
			.find( 'span.error' ).show();
671
			.find( 'span.error' ).show();
648
	} else {
672
	} else {
649
		this.masquerPanneau( '#dialogue-taxon-or-image' );
673
		this.masquerPanneau( '#dialogue-taxon-or-image' );
650
		$( '#bloc-taxon' ).removeClass( 'error' )
674
		$( '#bloc-taxon' ).removeClass( 'error' )
651
			.find( 'span.error' ).hide();
675
			.find( 'span.error' ).hide();
652
	}
676
	}
653
 
677
 
654
	if ( taxonEstRequis ) {
678
	if ( taxonEstRequis ) {
655
		return hasTaxon;
679
		return hasTaxon;
656
	}
680
	}
657
};
681
};
658
 
682
 
659
WidgetSaisie.prototype.validerImageRequise = function( hasImages = false ) {
683
WidgetSaisie.prototype.validerImageRequise = function( hasImages = false ) {
660
	$( '#bloc-taxon' ).removeClass( 'error' )
684
	$( '#bloc-taxon' ).removeClass( 'error' )
661
			.find( 'span.error' ).hide();
685
			.find( 'span.error' ).hide();
662
 
686
 
663
	if ( hasImages ) {
687
	if ( hasImages ) {
664
		this.masquerPanneau( '#dialogue-taxon-or-image' );
688
		this.masquerPanneau( '#dialogue-taxon-or-image' );
665
		this.masquerPanneau( '#dialogue-image-requise' );
689
		this.masquerPanneau( '#dialogue-image-requise' );
666
		$( '#fichier' ).parent( 'label.label-file' ).removeClass( 'error' );
690
		$( '#fichier' ).parent( 'label.label-file' ).removeClass( 'error' );
667
		$( '#photos-conteneur').removeClass( 'error' ).find( 'span.error' ).hide();
691
		$( '#photos-conteneur').removeClass( 'error' ).find( 'span.error' ).hide();
668
	} else {
692
	} else {
669
		if ( this.photoObligatoire ) {
693
		if ( this.photoObligatoire ) {
670
			this.afficherPanneau( '#dialogue-image-requise' );
694
			this.afficherPanneau( '#dialogue-image-requise' );
671
		} else {
695
		} else {
672
			this.afficherPanneau( '#dialogue-taxon-or-image' );
696
			this.afficherPanneau( '#dialogue-taxon-or-image' );
673
		}
697
		}
674
		$( '#fichier' ).parent( 'label.label-file' ).addClass( 'error' );
698
		$( '#fichier' ).parent( 'label.label-file' ).addClass( 'error' );
675
		$( '#photos-conteneur').addClass( 'error' ).find( 'span.error' ).show();
699
		$( '#photos-conteneur').addClass( 'error' ).find( 'span.error' ).show();
676
	}
700
	}
677
	return hasImages;
701
	return hasImages;
678
};
702
};
679
 
703
 
680
WidgetSaisie.prototype.surPresenceAbsenceMiniature = function() {
704
WidgetSaisie.prototype.surPresenceAbsenceMiniature = function() {
681
	const lthis = this;
705
	const lthis = this;
682
	// voir : https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/disconnect
706
	// voir : https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/disconnect
683
	// Selectionne le noeud dont les mutations seront observées
707
	// Selectionne le noeud dont les mutations seront observées
684
	const targetNode = document.getElementById( 'miniatures' );
708
	const targetNode = document.getElementById( 'miniatures' );
685
	// Fonction callback à éxécuter quand une mutation est observée
709
	// Fonction callback à éxécuter quand une mutation est observée
686
	const callback = mutationsList => {
710
	const callback = mutationsList => {
687
		for( let mutation of mutationsList ) {
711
		for( let mutation of mutationsList ) {
688
			lthis.validerCertitudeTaxonImage(
712
			lthis.validerCertitudeTaxonImage(
689
				valOk( $( '#taxon' ).val() ),
713
				valOk( $( '#taxon' ).val() ),
690
				0 < mutation.target.childElementCount
714
				0 < mutation.target.childElementCount
691
			);
715
			);
692
		}
716
		}
693
	};
717
	};
694
	// Créé une instance de l'observateur lié à la fonction de callback
718
	// Créé une instance de l'observateur lié à la fonction de callback
695
	this.observer = new MutationObserver( callback );
719
	this.observer = new MutationObserver( callback );
696
	// Commence à observer le noeud cible pour les mutations précédemment configurées
720
	// Commence à observer le noeud cible pour les mutations précédemment configurées
697
	this.observer.observe( targetNode, { childList: true } );
721
	this.observer.observe( targetNode, { childList: true } );
698
};
722
};
699
 
723
 
700
WidgetSaisie.prototype.validerForm = function() {
724
WidgetSaisie.prototype.validerForm = function() {
701
	const observateur = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() && $( '#courriel_confirmation' ).valid() ),
725
	const observateur  = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() && $( '#courriel_confirmation' ).valid() ),
702
		obs           = $( '#form-observation' ).valid(),
726
		obs            = $( '#form-observation' ).valid(),
-
 
727
		parsedGeometry = tryParseJson( $( '#geometry' ).val() ),
703
		geoloc        = ( valOk( $( '#latitude' ).val() ) && valOk( $( '#longitude' ).val() ) ) ,
728
		geoloc         = this.validateGeometry( parsedGeometry ) && ( valOk( $( '#latitude' ).val() ) && valOk( $( '#longitude' ).val() ) ) ,
704
		// validation et panneau taxon/images
729
		// validation et panneau taxon/images
705
		certitudeTaxonImage  = this.validerCertitudeTaxonImage(
730
		certitudeTaxonImage  = this.validerCertitudeTaxonImage(
706
			valOk( $( '#taxon' ).val() ),
731
			valOk( $( '#taxon' ).val() ),
707
			valOk( $( '#miniatures .miniature' ) )
732
			valOk( $( '#miniatures .miniature' ) )
708
		);
733
		);
709
	let chpsSupp = true;
734
	let chpsSupp = true;
710
 
735
 
711
	if ( valOk( $( '#form-supp' ) ) ) {
736
	if ( valOk( $( '#form-supp' ) ) ) {
712
		chpsSupp = ( function () {
737
		chpsSupp = ( function () {
713
			let otherFlag = $( '#form-supp' ).valid();
738
			let otherFlag = $( '#form-supp' ).valid();
714
 
739
 
715
			if( valOk( $( '.other', $( '#form-supp' ) ) ) ) {
740
			if( valOk( $( '.other', $( '#form-supp' ) ) ) ) {
716
				$( '.other', $( '#form-supp' ) ).each( function() {
741
				$( '.other', $( '#form-supp' ) ).each( function() {
717
					const picked = ( $( this ).data( 'element' ) !== 'select' ) ? ':checked' : ':selected';
742
					const picked = ( $( this ).data( 'element' ) !== 'select' ) ? ':checked' : ':selected';
718
 
743
 
719
						if ( $( this ).is( picked ) && valOk( $( this ).val(), true, 'other' ) ) {
744
						if ( $( this ).is( picked ) && valOk( $( this ).val(), true, 'other' ) ) {
720
							otherFlag = false;
745
							otherFlag = false;
721
						}
746
						}
722
				});
747
				});
723
			}
748
			}
724
 
749
 
725
			return otherFlag;
750
			return otherFlag;
726
		})();
751
		})();
727
	}
752
	}
728
	// panneau geoloc
753
	// panneau geoloc
729
	if ( geoloc ) {
754
	if ( geoloc ) {
730
		this.masquerPanneau( '#dialogue-geoloc-ko' );
755
		this.masquerPanneau( '#dialogue-geoloc-ko' );
731
		$( '#geoloc-datas' ).closest( '.control-group' ).removeClass( 'error' );
756
		$( '#geoloc-datas' ).closest( '.control-group' ).removeClass( 'error' );
732
	} else{
757
	} else{
733
		this.afficherPanneau( '#dialogue-geoloc-ko' );
758
		this.afficherPanneau( '#dialogue-geoloc-ko' );
734
		$( '#geoloc-datas' ).closest( '.control-group' ).addClass( 'error' );
759
		$( '#geoloc-datas' ).closest( '.control-group' ).addClass( 'error' );
735
	}
760
	}
736
	// panneau observateur
761
	// panneau observateur
737
	if ( observateur ) {
762
	if ( observateur ) {
738
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
763
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
739
		$( '.nav.control-group' ).removeClass( 'error' );
764
		$( '.nav.control-group' ).removeClass( 'error' );
740
	} else {
765
	} else {
741
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
766
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
742
		$( '.nav.control-group' ).addClass( 'error' );
767
		$( '.nav.control-group' ).addClass( 'error' );
743
	}
768
	}
744
	return ( observateur && obs && geoloc && certitudeTaxonImage && chpsSupp );
769
	return ( observateur && obs && geoloc && certitudeTaxonImage && chpsSupp );
745
};
770
};
746
 
771
 
747
// Referentiel ****************************************************************/
772
// Referentiel ****************************************************************/
748
// N'est pas utilisé en cas de taxon-liste
773
// N'est pas utilisé en cas de taxon-liste
749
WidgetSaisie.prototype.surChangementReferentiel = function() {
774
WidgetSaisie.prototype.surChangementReferentiel = function() {
750
	this.nomSciReferentiel = $( '#referentiel' ).val();
775
	this.nomSciReferentiel = $( '#referentiel' ).val();
751
	//réinitialise taxon.val
776
	//réinitialise taxon.val
752
	$( '#taxon' ).val( '' );
777
	$( '#taxon' ).val( '' );
753
	$( '#taxon' ).data( 'numNomSel', '' );
778
	$( '#taxon' ).data( 'numNomSel', '' );
754
};
779
};
755
 
780
 
756
 
781
 
757
$( document ).ready( function() {
782
$( document ).ready( function() {
758
	const widget = new WidgetSaisie();
783
	const widget = new WidgetSaisie();
759
	widget.init();
784
	widget.init();
760
	// Fonctions de Style et Affichage des éléments "spéciaux"
785
	// Fonctions de Style et Affichage des éléments "spéciaux"
761
	utils.init();
786
	utils.init();
762
});
787
});