Subversion Repositories eFlore/Applications.cel

Rev

Rev 3844 | Rev 3851 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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