Subversion Repositories eFlore/Applications.cel

Rev

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

Rev 3851 Rev 3853
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
			rue        = ( valOk( locDatas.osmRoad ) ) ? locDatas.osmRoad : '';
374
		let latitude      = '',
374
		let latitude      = '',
375
			longitude     = '',
375
			longitude     = '',
376
			coordLineaire = '',
376
			coordLineaire = '',
377
			nomCommune    = '',
377
			nomCommune    = '',
378
			communeInsee  = '';
378
			communeInsee  = '';
379
 
379
 
380
		if ( valOk( locDatas.geometry.coordinates ) &&
380
		if ( valOk( locDatas.geometry.coordinates ) &&
381
			valOk( locDatas.centroid.coordinates ) &&
381
			valOk( locDatas.centroid.coordinates ) &&
382
			valOk( locDatas.centroid.coordinates[0] ) &&
382
			valOk( locDatas.centroid.coordinates[0] ) &&
383
			valOk( locDatas.centroid.coordinates[1] )
383
			valOk( locDatas.centroid.coordinates[1] )
384
		) {
384
		) {
385
			latitude = locDatas.centroid.coordinates[0];
385
			latitude = locDatas.centroid.coordinates[0];
386
			longitude = locDatas.centroid.coordinates[1];
386
			longitude = locDatas.centroid.coordinates[1];
387
		}
387
		}
388
		if ( valOk( locDatas.inseeData ) ) {
388
		if ( valOk( locDatas.inseeData ) ) {
389
			nomCommune = locDatas.inseeData.nom;
389
			nomCommune = locDatas.inseeData.nom;
390
			communeInsee = ( valOk( locDatas.inseeData.code ) ) ? locDatas.inseeData.code : '';
390
			communeInsee = ( valOk( locDatas.inseeData.code ) ) ? locDatas.inseeData.code : '';
391
		} else if ( valOk( locDatas.locality ) ) {
391
		} else if ( valOk( locDatas.locality ) ) {
392
			nomCommune = locDatas.locality;
392
			nomCommune = locDatas.locality;
393
		} else if ( valOk( locDatas.locality ) ) {
393
		} else if ( valOk( locDatas.locality ) ) {
394
			nomCommune = locDatas.osmCounty;
394
			nomCommune = locDatas.osmCounty;
395
		}
395
		}
396
		$( '#geometry' ).val( geometry );
396
		$( '#geometry' ).val( geometry );
397
		$( '#coord-lineaire' ).val( coordLineaire );
397
		$( '#coord-lineaire' ).val( coordLineaire );
398
		$( '#latitude' ).val( latitude );
398
		$( '#latitude' ).val( latitude );
399
		$( '#longitude' ).val( longitude );
399
		$( '#longitude' ).val( longitude );
400
		$( '#commune-nom' ).val( nomCommune );
400
		$( '#commune-nom' ).val( nomCommune );
401
		$( '#commune-insee' ).val( communeInsee );
401
		$( '#commune-insee' ).val( communeInsee );
402
		$( '#altitude' ).val( altitude );
402
		$( '#altitude' ).val( altitude );
403
		$( '#pays' ).val( pays );
403
		$( '#pays' ).val( pays );
404
		$( '#station' ).val( rue );
404
		$( '#station' ).val( rue );
-
 
405
		$( '#latitude, #longitude' ).valid();
405
		if ( valOk( $( '#latitude' ).val() ) && valOk( $( '#longitude' ).val() ) ) {
406
		if ( valOk( $( '#latitude' ).val() ) && valOk( $( '#longitude' ).val() ) ) {
406
			$( '#geoloc' ).closest( '.control-group' ).removeClass( 'error' );
407
			$( '#geoloc' ).closest( '.control-group' ).removeClass( 'error' );
407
		} else {
408
		} else {
408
			$( '#geoloc' ).closest( '.control-group' ).addClass( 'error' );
409
			$( '#geoloc' ).closest( '.control-group' ).addClass( 'error' );
409
		}
410
		}
410
	} else {
411
	} else {
411
		console.warn( 'Error location' );
412
		console.warn( 'Error location' );
412
	}
413
	}
413
}
414
}
414
 
415
 
415
// Form Validator *************************************************************/
416
// Form Validator *************************************************************/
416
WidgetSaisie.prototype.chpEtendusValidation = function() {
417
WidgetSaisie.prototype.chpEtendusValidation = function() {
417
	const lthis = this,
418
	const lthis = this,
418
		$thisForm = $( '#form-supp' ),
419
		$thisForm = $( '#form-supp' ),
419
		elements  =
420
		elements  =
420
			'.checkbox,'+
421
			'.checkbox,'+
421
			'.radio,'+
422
			'.radio,'+
422
			'.checkboxes,'+
423
			'.checkboxes,'+
423
			'.select,'+
424
			'.select,'+
424
			'textarea,'+
425
			'textarea,'+
425
			'input[type=text]:not(.collect-other),'+
426
			'input[type=text]:not(.collect-other),'+
426
			'input[type=email],'+
427
			'input[type=email],'+
427
			'input[type=number],'+
428
			'input[type=number],'+
428
			'input[type=range],'+
429
			'input[type=range],'+
429
			'input[type=date]',
430
			'input[type=date]',
430
		speFields = ['checkbox','radio','checkboxes','select'],
431
		speFields = ['checkbox','radio','checkboxes','select'],
431
		spefieldsCount = speFields.length,
432
		spefieldsCount = speFields.length,
432
		chpSuppValidation = {
433
		chpSuppValidation = {
433
			rules : {},
434
			rules : {},
434
			messages : {},
435
			messages : {},
435
			minmax : []
436
			minmax : []
436
		},
437
		},
437
		errors = {},
438
		errors = {},
438
		namesListFields = [];
439
		namesListFields = [];
439
	let picked = '';
440
	let picked = '';
440
 
441
 
441
	$( elements, $thisForm ).each( function() {
442
	$( elements, $thisForm ).each( function() {
442
		for( let fieldsClass = 0; spefieldsCount > fieldsClass; fieldsClass++ ) {
443
		for( let fieldsClass = 0; spefieldsCount > fieldsClass; fieldsClass++ ) {
443
				const dataName = $( this ).data( 'name' );
444
				const dataName = $( this ).data( 'name' );
444
 
445
 
445
			if ( valOk( $( this ).attr( 'required' ) ) && $( this ).hasClass( speFields[fieldsClass] ) && !valOk( chpSuppValidation.rules[ dataName ] ) ) {
446
			if ( valOk( $( this ).attr( 'required' ) ) && $( this ).hasClass( speFields[fieldsClass] ) && !valOk( chpSuppValidation.rules[ dataName ] ) ) {
446
				namesListFields.push( dataName );
447
				namesListFields.push( dataName );
447
				chpSuppValidation.rules[ dataName ] = { required : true };
448
				chpSuppValidation.rules[ dataName ] = { required : true };
448
				if ( valOk( $( '.other', $( this ) ) ) ) {
449
				if ( valOk( $( '.other', $( this ) ) ) ) {
449
					picked = ( 'select' === speFields[fieldsClass] ) ? ':selected' : ':checked';
450
					picked = ( 'select' === speFields[fieldsClass] ) ? ':selected' : ':checked';
450
					chpSuppValidation.rules[ 'collect-other-' + dataName.replace( '[]', '' ) ] = {
451
					chpSuppValidation.rules[ 'collect-other-' + dataName.replace( '[]', '' ) ] = {
451
						required : '#other-' + dataName.replace( '[]', '' ) + picked,
452
						required : '#other-' + dataName.replace( '[]', '' ) + picked,
452
						minlength: 1
453
						minlength: 1
453
					};
454
					};
454
					chpSuppValidation.messages[ 'collect-other-' + dataName.replace( '[]', '' ) ] = false;
455
					chpSuppValidation.messages[ 'collect-other-' + dataName.replace( '[]', '' ) ] = false;
455
				}
456
				}
456
				chpSuppValidation.rules[ dataName ]['listFields'] = true;
457
				chpSuppValidation.rules[ dataName ]['listFields'] = true;
457
				chpSuppValidation.messages[ dataName ] = 'Ce champ est requis :\nVeuillez choisir une option, ou entrer une valeur autre valide.';
458
				chpSuppValidation.messages[ dataName ] = 'Ce champ est requis :\nVeuillez choisir une option, ou entrer une valeur autre valide.';
458
				errors[dataName] = '.' + speFields[fieldsClass];
459
				errors[dataName] = '.' + speFields[fieldsClass];
459
			}
460
			}
460
		}
461
		}
461
		if ( valOk( $( this ).attr( 'name' ) ) && valOk ( $( this ).attr( 'required' ) ) && 0 > $.inArray( $( this ).attr( 'name' ) , namesListFields ) ) {
462
		if ( valOk( $( this ).attr( 'name' ) ) && valOk ( $( this ).attr( 'required' ) ) && 0 > $.inArray( $( this ).attr( 'name' ) , namesListFields ) ) {
462
			chpSuppValidation.rules[ $( this ).attr( 'name' ) ] = { required : true, minlength: 1 };
463
			chpSuppValidation.rules[ $( this ).attr( 'name' ) ] = { required : true, minlength: 1 };
463
			if(
464
			if(
464
				( valOk( $( this ).attr( 'type' ), true, 'number' ) || valOk( $( this ).attr( 'type' ), true, 'range' ) ) &&
465
				( valOk( $( this ).attr( 'type' ), true, 'number' ) || valOk( $( this ).attr( 'type' ), true, 'range' ) ) &&
465
				( valOk( $( this )[0].min ) || valOk( $( this )[0].max ) )
466
				( valOk( $( this )[0].min ) || valOk( $( this )[0].max ) )
466
			) {
467
			) {
467
				chpSuppValidation.rules[ $( this ).attr('name') ]['minMaxOk'] = true;
468
				chpSuppValidation.rules[ $( this ).attr('name') ]['minMaxOk'] = true;
468
				chpSuppValidation.messages[ $( this ).attr('name') ] = lthis.validerMinMax( $( this )[0] ).message;
469
				chpSuppValidation.messages[ $( this ).attr('name') ] = lthis.validerMinMax( $( this )[0] ).message;
469
			}
470
			}
470
		}
471
		}
471
	});
472
	});
472
	if ( valOk( chpSuppValidation.rules ) ) {
473
	if ( valOk( chpSuppValidation.rules ) ) {
473
		$.each( chpSuppValidation.rules, function( key ) {
474
		$.each( chpSuppValidation.rules, function( key ) {
474
			if ( !valOk( chpSuppValidation.messages[key] ) ) {
475
			if ( !valOk( chpSuppValidation.messages[key] ) ) {
475
				chpSuppValidation.messages[key] = 'Ce champ est requis :\nVeuillez entrer une valeur valide.';
476
				chpSuppValidation.messages[key] = 'Ce champ est requis :\nVeuillez entrer une valeur valide.';
476
			}
477
			}
477
		});
478
		});
478
		if ( 0 < Object.keys( errors ).length ) {
479
		if ( 0 < Object.keys( errors ).length ) {
479
			chpSuppValidation['errors'] = errors;
480
			chpSuppValidation['errors'] = errors;
480
		}
481
		}
481
	}
482
	}
482
	return chpSuppValidation;
483
	return chpSuppValidation;
483
};
484
};
484
 
485
 
485
WidgetSaisie.prototype.validerMinMax = function( element ) {
486
WidgetSaisie.prototype.validerMinMax = function( element ) {
486
	const minCond  = parseFloat( element.value ) >= parseFloat( element.min ),
487
	const minCond  = parseFloat( element.value ) >= parseFloat( element.min ),
487
		maxCond    = parseFloat( element.value ) <= parseFloat( element.max ),
488
		maxCond    = parseFloat( element.value ) <= parseFloat( element.max ),
488
		returnMnMx = { cond : true , message : '' };
489
		returnMnMx = { cond : true , message : '' };
489
	let mnMxCond    = new Boolean(),
490
	let mnMxCond    = new Boolean(),
490
		messageMnMx = 'La valeur entrée doit être';
491
		messageMnMx = 'La valeur entrée doit être';
491
 
492
 
492
	if(
493
	if(
493
		( valOk( element.type, true, 'number' ) || valOk( element.type, true, 'range' ) ) &&
494
		( valOk( element.type, true, 'number' ) || valOk( element.type, true, 'range' ) ) &&
494
		( valOk( element.min ) || valOk( element.max ) )
495
		( valOk( element.min ) || valOk( element.max ) )
495
	) {
496
	) {
496
		if ( element.min && element.max ) {
497
		if ( element.min && element.max ) {
497
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
498
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
498
			mnMxCond     = ( minCond && maxCond );
499
			mnMxCond     = ( minCond && maxCond );
499
		} else if ( element.min ) {
500
		} else if ( element.min ) {
500
			messageMnMx += ' supérieure à ' + element.min;
501
			messageMnMx += ' supérieure à ' + element.min;
501
			mnMxCond     = minCond;
502
			mnMxCond     = minCond;
502
		} else {
503
		} else {
503
			messageMnMx += ' inférieure à ' + element.max;
504
			messageMnMx += ' inférieure à ' + element.max;
504
			mnMxCond     = maxCond;
505
			mnMxCond     = maxCond;
505
		}
506
		}
506
		returnMnMx.cond    = mnMxCond;
507
		returnMnMx.cond    = mnMxCond;
507
		returnMnMx.message = messageMnMx;
508
		returnMnMx.message = messageMnMx;
508
	}
509
	}
509
	return returnMnMx;
510
	return returnMnMx;
510
 
511
 
511
};
512
};
512
 
513
 
513
WidgetSaisie.prototype.definirReglesFormValidator = function() {
514
WidgetSaisie.prototype.definirReglesFormValidator = function() {
514
	const lthis = this,
515
	const lthis = this,
515
		formSuppValidation = this.chpEtendusValidation();
516
		formSuppValidation = this.chpEtendusValidation();
516
 
517
 
517
	$( '#form-supp' ).validate({
518
	$( '#form-supp' ).validate({
518
		onclick : function( element ) {
519
		onclick : function( element ) {
519
			if (
520
			if (
520
				(
521
				(
521
					valOk( element.type, true, 'checkbox' ) ||
522
					valOk( element.type, true, 'checkbox' ) ||
522
					valOk( element.type, true, 'radio' )
523
					valOk( element.type, true, 'radio' )
523
				) &&
524
				) &&
524
				(
525
				(
525
					!valOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':checked' ) ) ||
526
					!valOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':checked' ) ) ||
526
					valOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':not(.other):checked' ) ) ||
527
					valOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':not(.other):checked' ) ) ||
527
					!valOk( $( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ) ) ||
528
					!valOk( $( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ) ) ||
528
					$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) ||
529
					$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) ||
529
					(
530
					(
530
						$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) &&
531
						$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) &&
531
						$( element ).closest( '.control-group' ).hasClass('error')
532
						$( element ).closest( '.control-group' ).hasClass('error')
532
					)
533
					)
533
				)
534
				)
534
			) {
535
			) {
535
				$( element ).valid();
536
				$( element ).valid();
536
				if ( $( element ).valid() ) {
537
				if ( $( element ).valid() ) {
537
					$( element ).closest( '.control-group' ).removeClass( 'error' );
538
					$( element ).closest( '.control-group' ).removeClass( 'error' );
538
					$( element ).next( $( 'span.error' ) ).remove();
539
					$( element ).next( $( 'span.error' ) ).remove();
539
				} else {
540
				} else {
540
					$( element ).closest( '.control-group' ).addClass( 'error' );
541
					$( element ).closest( '.control-group' ).addClass( 'error' );
541
				}
542
				}
542
			}
543
			}
543
			return false;
544
			return false;
544
		},
545
		},
545
		rules : formSuppValidation.rules,
546
		rules : formSuppValidation.rules,
546
		messages : formSuppValidation.messages,
547
		messages : formSuppValidation.messages,
547
		errorPlacement : function( error , element ) {
548
		errorPlacement : function( error , element ) {
548
			if ( 0 < Object.keys( formSuppValidation.errors ).length ) {
549
			if ( 0 < Object.keys( formSuppValidation.errors ).length ) {
549
				const errorsKeys = Object.keys( formSuppValidation.errors );
550
				const errorsKeys = Object.keys( formSuppValidation.errors );
550
				let thisKey    = '',
551
				let thisKey    = '',
551
					errorsFlag = true;
552
					errorsFlag = true;
552
 
553
 
553
				for ( let i = 0 ; i < errorsKeys.length ; i++ ) {
554
				for ( let i = 0 ; i < errorsKeys.length ; i++ ) {
554
					thisKey = errorsKeys[i];
555
					thisKey = errorsKeys[i];
555
					if( $( element ).attr( 'name' ) === thisKey ) {
556
					if( $( element ).attr( 'name' ) === thisKey ) {
556
						$( formSuppValidation.errors[thisKey] ).append( error );
557
						$( formSuppValidation.errors[thisKey] ).append( error );
557
						errorsFlag = false;
558
						errorsFlag = false;
558
					}
559
					}
559
				}
560
				}
560
				if ( errorsFlag ) {
561
				if ( errorsFlag ) {
561
					error.insertAfter( element );
562
					error.insertAfter( element );
562
				}
563
				}
563
			} else {
564
			} else {
564
				error.insertAfter( element );
565
				error.insertAfter( element );
565
			}
566
			}
566
		}
567
		}
567
	});
568
	});
568
	$( '#form-supp .select' ).change( function() {
569
	$( '#form-supp .select' ).change( function() {
569
		$( this ).valid();
570
		$( this ).valid();
570
	});
571
	});
571
	$( 'input[type=date]' ).on( 'input', function() {
572
	$( 'input[type=date]' ).on( 'input', function() {
572
		$( this ).valid();
573
		$( this ).valid();
573
	});
574
	});
574
	// Validation taxon
575
	// Validation taxon
575
	// et gestion des messages d'erreur taxon et images en fonction de la certitude
576
	// et gestion des messages d'erreur taxon et images en fonction de la certitude
576
	$( '#taxon, #certitude' ).on( 'change', function() {
577
	$( '#taxon, #certitude' ).on( 'change', function() {
577
		lthis.validerTaxonRequis( valOk( $( '#taxon' ).val() ) );
578
		lthis.validerTaxonRequis( valOk( $( '#taxon' ).val() ) );
578
	});
579
	});
579
	// Validation miniatures avec MutationObserver
580
	// Validation miniatures avec MutationObserver
580
	this.surPresenceAbsenceMiniature();
581
	this.surPresenceAbsenceMiniature();
581
	$( '#form-observation' ).validate({
582
	$( '#form-observation' ).validate({
582
		rules : {
583
		rules : {
583
			date_releve : {
584
			date_releve : {
584
				required : true,
585
				required : true,
585
				'dateCel' : true
586
				'dateCel' : true
586
			},
587
			},
587
			latitude : {
588
			latitude : {
588
				required : true,
589
				required : true,
589
				minlength : 1,
590
				minlength : 1,
590
				range : [-90, 90]
591
				range : [-90, 90]
591
			},
592
			},
592
			longitude : {
593
			longitude : {
593
				required : true,
594
				required : true,
594
				minlength : 1,
595
				minlength : 1,
595
				range : [-180, 180]
596
				range : [-180, 180]
596
			}
597
			}
597
		}
598
		}
598
	});
599
	});
599
	$( '#form-observateur' ).validate({
600
	$( '#form-observateur' ).validate({
600
		rules : {
601
		rules : {
601
			courriel : {
602
			courriel : {
602
				required : true,
603
				required : true,
603
				email : true,
604
				email : true,
604
				'userEmailOk' : true
605
				'userEmailOk' : true
605
			},
606
			},
606
			courriel_confirmation : {
607
			courriel_confirmation : {
607
				required : true,
608
				required : true,
608
				equalTo : '#courriel'
609
				equalTo : '#courriel'
609
			}
610
			}
610
		}
611
		}
611
	});
612
	});
612
	$( '#connexion,#inscription,#bouton-anonyme' ).on( 'click', function( event ) {
613
	$( '#connexion,#inscription,#bouton-anonyme' ).on( 'click', function( event ) {
613
		$( '.nav.control-group' ).removeClass( 'error' );
614
		$( '.nav.control-group' ).removeClass( 'error' );
614
	});
615
	});
615
};
616
};
616
 
617
 
617
 
618
 
618
WidgetSaisie.prototype.validerCertitudeTaxonImage = function( hasTaxon = false, hasImages = false ) {
619
WidgetSaisie.prototype.validerCertitudeTaxonImage = function( hasTaxon = false, hasImages = false ) {
619
	if( 'certain' === $( '#certitude' ).val() ) {
620
	if( 'certain' === $( '#certitude' ).val() ) {
620
		return this.validerTaxonRequis( hasTaxon );
621
		return this.validerTaxonRequis( hasTaxon );
621
	} else {
622
	} else {
622
		return this.validerImageRequise( hasImages );
623
		return this.validerImageRequise( hasImages );
623
	}
624
	}
624
};
625
};
625
 
626
 
626
WidgetSaisie.prototype.validerTaxonRequis = function( hasTaxon = false ) {
627
WidgetSaisie.prototype.validerTaxonRequis = function( hasTaxon = false ) {
627
	const taxonEstRequis = 'certain' === $( '#certitude' ).val();
628
	const taxonEstRequis = 'certain' === $( '#certitude' ).val();
628
 
629
 
629
	$( '#photos-conteneur').removeClass( 'error' )
630
	$( '#photos-conteneur').removeClass( 'error' )
630
		.find( 'span.error' ).hide();
631
		.find( 'span.error' ).hide();
631
 
632
 
632
	if ( !hasTaxon && taxonEstRequis ) {
633
	if ( !hasTaxon && taxonEstRequis ) {
633
		this.afficherPanneau( '#dialogue-taxon-or-image' );
634
		this.afficherPanneau( '#dialogue-taxon-or-image' );
634
		$( '#bloc-taxon' ).addClass( 'error' )
635
		$( '#bloc-taxon' ).addClass( 'error' )
635
			.find( 'span.error' ).show();
636
			.find( 'span.error' ).show();
636
	} else {
637
	} else {
637
		this.masquerPanneau( '#dialogue-taxon-or-image' );
638
		this.masquerPanneau( '#dialogue-taxon-or-image' );
638
		$( '#bloc-taxon' ).removeClass( 'error' )
639
		$( '#bloc-taxon' ).removeClass( 'error' )
639
			.find( 'span.error' ).hide();
640
			.find( 'span.error' ).hide();
640
	}
641
	}
641
 
642
 
642
	if ( taxonEstRequis ) {
643
	if ( taxonEstRequis ) {
643
		return hasTaxon;
644
		return hasTaxon;
644
	}
645
	}
645
};
646
};
646
 
647
 
647
WidgetSaisie.prototype.validerImageRequise = function( hasImages = false ) {
648
WidgetSaisie.prototype.validerImageRequise = function( hasImages = false ) {
648
	$( '#bloc-taxon' ).removeClass( 'error' )
649
	$( '#bloc-taxon' ).removeClass( 'error' )
649
			.find( 'span.error' ).hide();
650
			.find( 'span.error' ).hide();
650
 
651
 
651
	if ( hasImages ) {
652
	if ( hasImages ) {
652
		this.masquerPanneau( '#dialogue-taxon-or-image' );
653
		this.masquerPanneau( '#dialogue-taxon-or-image' );
653
		$( '#fichier' ).parent( 'label.label-file' ).removeClass( 'error' );
654
		$( '#fichier' ).parent( 'label.label-file' ).removeClass( 'error' );
654
		$( '#photos-conteneur').removeClass( 'error' ).find( 'span.error' ).hide();
655
		$( '#photos-conteneur').removeClass( 'error' ).find( 'span.error' ).hide();
655
	} else {
656
	} else {
656
		this.afficherPanneau( '#dialogue-taxon-or-image' );
657
		this.afficherPanneau( '#dialogue-taxon-or-image' );
657
		$( '#fichier' ).parent( 'label.label-file' ).addClass( 'error' );
658
		$( '#fichier' ).parent( 'label.label-file' ).addClass( 'error' );
658
		$( '#photos-conteneur').addClass( 'error' ).find( 'span.error' ).show();
659
		$( '#photos-conteneur').addClass( 'error' ).find( 'span.error' ).show();
659
	}
660
	}
660
	return hasImages;
661
	return hasImages;
661
};
662
};
662
 
663
 
663
WidgetSaisie.prototype.surPresenceAbsenceMiniature = function() {
664
WidgetSaisie.prototype.surPresenceAbsenceMiniature = function() {
664
	const lthis = this;
665
	const lthis = this;
665
	// voir : https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/disconnect
666
	// voir : https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/disconnect
666
	// Selectionne le noeud dont les mutations seront observées
667
	// Selectionne le noeud dont les mutations seront observées
667
	const targetNode = document.getElementById( 'miniatures' );
668
	const targetNode = document.getElementById( 'miniatures' );
668
	// Fonction callback à éxécuter quand une mutation est observée
669
	// Fonction callback à éxécuter quand une mutation est observée
669
	const callback = mutationsList => {
670
	const callback = mutationsList => {
670
		for( let mutation of mutationsList ) {
671
		for( let mutation of mutationsList ) {
671
			lthis.validerCertitudeTaxonImage(
672
			lthis.validerCertitudeTaxonImage(
672
				valOk( $( '#taxon' ).val() ),
673
				valOk( $( '#taxon' ).val() ),
673
				0 < mutation.target.childElementCount
674
				0 < mutation.target.childElementCount
674
			);
675
			);
675
		}
676
		}
676
	};
677
	};
677
	// Créé une instance de l'observateur lié à la fonction de callback
678
	// Créé une instance de l'observateur lié à la fonction de callback
678
	this.observer = new MutationObserver( callback );
679
	this.observer = new MutationObserver( callback );
679
	// Commence à observer le noeud cible pour les mutations précédemment configurées
680
	// Commence à observer le noeud cible pour les mutations précédemment configurées
680
	this.observer.observe( targetNode, { childList: true } );
681
	this.observer.observe( targetNode, { childList: true } );
681
};
682
};
682
 
683
 
683
WidgetSaisie.prototype.validerForm = function() {
684
WidgetSaisie.prototype.validerForm = function() {
684
	const observateur = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() && $( '#courriel_confirmation' ).valid() ),
685
	const observateur = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() && $( '#courriel_confirmation' ).valid() ),
685
		obs           = $( '#form-observation' ).valid(),
686
		obs           = $( '#form-observation' ).valid(),
686
		geoloc        = ( valOk( $( '#latitude' ).val() ) && valOk( $( '#longitude' ).val() ) ) ,
687
		geoloc        = ( valOk( $( '#latitude' ).val() ) && valOk( $( '#longitude' ).val() ) ) ,
687
		// validation et panneau taxon/images
688
		// validation et panneau taxon/images
688
		certitudeTaxonImage  = this.validerCertitudeTaxonImage(
689
		certitudeTaxonImage  = this.validerCertitudeTaxonImage(
689
			valOk( $( '#taxon' ).val() ),
690
			valOk( $( '#taxon' ).val() ),
690
			valOk( $( '#miniatures .miniature' ) )
691
			valOk( $( '#miniatures .miniature' ) )
691
		);
692
		);
692
	let chpsSupp = true;
693
	let chpsSupp = true;
693
 
694
 
694
	if ( valOk( $( '#form-supp' ) ) ) {
695
	if ( valOk( $( '#form-supp' ) ) ) {
695
		chpsSupp = ( function () {
696
		chpsSupp = ( function () {
696
			let otherFlag = $( '#form-supp' ).valid();
697
			let otherFlag = $( '#form-supp' ).valid();
697
 
698
 
698
			if( valOk( $( '.other', $( '#form-supp' ) ) ) ) {
699
			if( valOk( $( '.other', $( '#form-supp' ) ) ) ) {
699
				$( '.other', $( '#form-supp' ) ).each( function() {
700
				$( '.other', $( '#form-supp' ) ).each( function() {
700
					const picked = ( $( this ).data( 'element' ) !== 'select' ) ? ':checked' : ':selected';
701
					const picked = ( $( this ).data( 'element' ) !== 'select' ) ? ':checked' : ':selected';
701
 
702
 
702
						if ( $( this ).is( picked ) && valOk( $( this ).val(), true, 'other' ) ) {
703
						if ( $( this ).is( picked ) && valOk( $( this ).val(), true, 'other' ) ) {
703
							otherFlag = false;
704
							otherFlag = false;
704
						}
705
						}
705
				});
706
				});
706
			}
707
			}
707
 
708
 
708
			return otherFlag;
709
			return otherFlag;
709
		})();
710
		})();
710
	}
711
	}
711
	// panneau geoloc
712
	// panneau geoloc
712
	if ( geoloc ) {
713
	if ( geoloc ) {
713
		this.masquerPanneau( '#dialogue-geoloc-ko' );
714
		this.masquerPanneau( '#dialogue-geoloc-ko' );
714
		$( '#geoloc-datas' ).closest( '.control-group' ).removeClass( 'error' );
715
		$( '#geoloc-datas' ).closest( '.control-group' ).removeClass( 'error' );
715
	} else{
716
	} else{
716
		this.afficherPanneau( '#dialogue-geoloc-ko' );
717
		this.afficherPanneau( '#dialogue-geoloc-ko' );
717
		$( '#geoloc-datas' ).closest( '.control-group' ).addClass( 'error' );
718
		$( '#geoloc-datas' ).closest( '.control-group' ).addClass( 'error' );
718
	}
719
	}
719
	// panneau observateur
720
	// panneau observateur
720
	if ( observateur ) {
721
	if ( observateur ) {
721
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
722
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
722
		$( '.nav.control-group' ).removeClass( 'error' );
723
		$( '.nav.control-group' ).removeClass( 'error' );
723
	} else {
724
	} else {
724
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
725
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
725
		$( '.nav.control-group' ).addClass( 'error' );
726
		$( '.nav.control-group' ).addClass( 'error' );
726
	}
727
	}
727
	return ( observateur && obs && geoloc && certitudeTaxonImage && chpsSupp );
728
	return ( observateur && obs && geoloc && certitudeTaxonImage && chpsSupp );
728
};
729
};
729
 
730
 
730
// Referentiel ****************************************************************/
731
// Referentiel ****************************************************************/
731
// N'est pas utilisé en cas de taxon-liste
732
// N'est pas utilisé en cas de taxon-liste
732
WidgetSaisie.prototype.surChangementReferentiel = function() {
733
WidgetSaisie.prototype.surChangementReferentiel = function() {
733
	this.nomSciReferentiel = $( '#referentiel' ).val();
734
	this.nomSciReferentiel = $( '#referentiel' ).val();
734
	//réinitialise taxon.val
735
	//réinitialise taxon.val
735
	$( '#taxon' ).val( '' );
736
	$( '#taxon' ).val( '' );
736
	$( '#taxon' ).data( 'numNomSel', '' );
737
	$( '#taxon' ).data( 'numNomSel', '' );
737
};
738
};
738
 
739
 
739
 
740
 
740
$( document ).ready( function() {
741
$( document ).ready( function() {
741
	const widget = new WidgetSaisie();
742
	const widget = new WidgetSaisie();
742
	widget.init();
743
	widget.init();
743
	// Fonctions de Style et Affichage des éléments "spéciaux"
744
	// Fonctions de Style et Affichage des éléments "spéciaux"
744
	utils.init();
745
	utils.init();
745
});
746
});