Subversion Repositories eFlore/Applications.cel

Rev

Rev 3287 | Rev 3291 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 3287 Rev 3290
1
/**
1
/**
2
 * Constructeur WidgetSaisie par défaut
2
 * Constructeur WidgetSaisie par défaut
3
 */
3
 */
4
function WidgetSaisie() {
4
function WidgetSaisie() {
5
	this.urlBaseAuth = window.location.origin + '/service:annuaire:auth';
5
	this.urlBaseAuth = window.location.origin + '/service:annuaire:auth';
6
	this.mode = 'prod';
6
	this.mode = 'prod';
7
	this.langue = 'fr';
7
	this.langue = 'fr';
8
	this.obsNbre = 0;
8
	this.obsNbre = 0;
9
	this.nbObsEnCours = 1;
9
	this.nbObsEnCours = 1;
10
	this.totalObsATransmettre = 0;
10
	this.totalObsATransmettre = 0;
11
	this.nbObsTransmises = 0;
11
	this.nbObsTransmises = 0;
12
	this.debug = null;
12
	this.debug = null;
13
	this.html5 = null;
13
	this.html5 = null;
14
	this.tagProjet = null;
14
	this.tagProjet = null;
15
	this.tagImg = null;
15
	this.tagImg = null;
16
	this.tagObs = null;
16
	this.tagObs = null;
17
	this.separationTagImg = null;
17
	this.separationTagImg = null;
18
	this.separationTagObs = null;
18
	this.separationTagObs = null;
19
	this.obsId = null;
19
	this.obsId = null;
20
	this.serviceSaisieUrl = null;
20
	this.serviceSaisieUrl = null;
21
	this.serviceObsUrl = null;
21
	this.serviceObsUrl = null;
22
	this.nomSciReferentiel = null;
22
	this.nomSciReferentiel = null;
23
	this.especeImposee = false;
23
	this.especeImposee = false;
24
	this.infosEspeceImposee = null;
24
	this.infosEspeceImposee = null;
25
	this.isTaxonListe = false;
25
	this.isTaxonListe = false;
26
	this.autocompletionElementsNbre = null;
26
	this.autocompletionElementsNbre = null;
27
	this.referentielImpose = null;
27
	this.referentielImpose = null;
28
	this.serviceAutocompletionNomSciUrl = null;
28
	this.serviceAutocompletionNomSciUrl = null;
29
	this.serviceAutocompletionNomSciUrlTpl = null;
29
	this.serviceAutocompletionNomSciUrlTpl = null;
30
	this.obsMaxNbre = null;
30
	this.obsMaxNbre = null;
31
	this.dureeMessage = null;
31
	this.dureeMessage = null;
32
	this.serviceAnnuaireIdUrl = null;
32
	this.serviceAnnuaireIdUrl = null;
33
	this.serviceNomCommuneUrl = null;
33
	this.serviceNomCommuneUrl = null;
34
	this.serviceNomCommuneUrlAlt = null;
34
	this.serviceNomCommuneUrlAlt = null;
35
	this.chargementImageIconeUrl = null;
35
	this.chargementImageIconeUrl = null;
36
	this.pasDePhotoIconeUrl = null;
36
	this.pasDePhotoIconeUrl = null;
37
	this.observer = null;
37
	this.observer = null;
38
 
38
 
39
	// système de traduction minimaliste
39
	// système de traduction minimaliste
40
	this.msgs = {
40
	this.msgs = {
41
		fr: {
41
		fr: {
42
			'format-non-supporte': 'Le format de fichier n\'est pas supporté, les formats acceptés sont',
42
			'format-non-supporte': 'Le format de fichier n\'est pas supporté, les formats acceptés sont',
43
			'date-incomplete': 'Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.',
43
			'date-incomplete': 'Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.',
44
			'observations-transmises': 'observations transmises',
44
			'observations-transmises': 'observations transmises',
45
			'taxon-ou-image' : 'Veuillez transmettre au moins, soit une image, soit une espèce',
45
			'taxon-ou-image' : 'Veuillez transmettre au moins, soit une image, soit une espèce',
46
			'supprimer-observation-liste': 'Supprimer cette observation de la liste à transmettre',
46
			'supprimer-observation-liste': 'Supprimer cette observation de la liste à transmettre',
47
			'milieu': 'Milieu',
47
			'milieu': 'Milieu',
48
			'commentaires': 'Commentaires',
48
			'commentaires': 'Commentaires',
49
			'erreur-inconnue': 'Erreur inconnue',
49
			'erreur-inconnue': 'Erreur inconnue',
50
			'non-lie-au-ref': 'non lié au référentiel',
50
			'non-lie-au-ref': 'non lié au référentiel',
51
			'obs-le': 'le',
51
			'obs-le': 'le',
52
			'quitter-page' : 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.',
52
			'quitter-page' : 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.',
53
			'courriel-connu' : 'Un compte existe pour ce courriel, connectez-vous pour saisir votre observation',
53
			'courriel-connu' : 'Un compte existe pour ce courriel, connectez-vous pour saisir votre observation',
54
			'obs-numero' : 'Observation n°',
54
			'obs-numero' : 'Observation n°',
55
			'erreur-ajax' : 'Erreur Ajax',
55
			'erreur-ajax' : 'Erreur Ajax',
56
			'erreur' : 'Erreur',
56
			'erreur' : 'Erreur',
57
			'erreur-chargement' : 'Erreur lors du chargement de l\'observation',
57
			'erreur-chargement' : 'Erreur lors du chargement de l\'observation',
58
			'lieu-obs' : 'observé à',
58
			'lieu-obs' : 'observé à',
59
			'lieu-dit' : 'Lieu-dit',
59
			'lieu-dit' : 'Lieu-dit',
60
			'station' : 'Station'
60
			'station' : 'Station'
61
		},
61
		},
62
		en: {
62
		en: {
63
			'format-non-supporte': 'The file format is not supported, the accepted formats are',
63
			'format-non-supporte': 'The file format is not supported, the accepted formats are',
64
			'date-incomplete': 'Format: dd / mm / yyyy. Incomplete date, use 0, example: 00/12/2011.',
64
			'date-incomplete': 'Format: dd / mm / yyyy. Incomplete date, use 0, example: 00/12/2011.',
65
			'observations-transmises': 'observations transmitted',
65
			'observations-transmises': 'observations transmitted',
66
			'taxon-ou-image' : 'Please transmit at least one image or one species',
66
			'taxon-ou-image' : 'Please transmit at least one image or one species',
67
			'supprimer-observation-liste': 'Delete this observation from the list to be transmitted',
67
			'supprimer-observation-liste': 'Delete this observation from the list to be transmitted',
68
			'milieu': 'Environment',
68
			'milieu': 'Environment',
69
			'commentaires': 'Comments',
69
			'commentaires': 'Comments',
70
			'erreur-inconnue': 'Unknown error',
70
			'erreur-inconnue': 'Unknown error',
71
			'non-lie-au-ref': 'unrelated to the referencial ',
71
			'non-lie-au-ref': 'unrelated to the referencial ',
72
			'obs-le': 'the',
72
			'obs-le': 'the',
73
			'quitter-page' : 'Are you sure you want to leave the page?\nThe observations entered but not transmitted will be lost.',
73
			'quitter-page' : 'Are you sure you want to leave the page?\nThe observations entered but not transmitted will be lost.',
74
			'courriel-connu' : 'An account exists for this email, log in to enter your observation',
74
			'courriel-connu' : 'An account exists for this email, log in to enter your observation',
75
			'obs-numero' : 'Observation number ',
75
			'obs-numero' : 'Observation number ',
76
			'erreur-ajax' : 'Ajax Error',
76
			'erreur-ajax' : 'Ajax Error',
77
			'erreur' : 'Error',
77
			'erreur' : 'Error',
78
			'erreur-chargement' : 'Error loading the observation',
78
			'erreur-chargement' : 'Error loading the observation',
79
			'lieu-obs' : 'observed at',
79
			'lieu-obs' : 'observed at',
80
			'lieu-dit' : 'Locality',
80
			'lieu-dit' : 'Locality',
81
			'station' : 'Place'
81
			'station' : 'Place'
82
		}
82
		}
83
	};
83
	};
84
}
84
}
85
 
85
 
86
/**
86
/**
87
 * Initialisation du widget
87
 * Initialisation du widget
88
 */
88
 */
89
WidgetSaisie.prototype.init = function() {
89
WidgetSaisie.prototype.init = function() {
90
	this.initForm();
90
	this.initForm();
91
	this.initEvts();
91
	this.initEvts();
92
};
92
};
93
 
93
 
94
/**
94
/**
95
 * Initialise le formulaire, les validateurs, les listes de complétion...
95
 * Initialise le formulaire, les validateurs, les listes de complétion...
96
 */
96
 */
97
WidgetSaisie.prototype.initForm = function() {
97
WidgetSaisie.prototype.initForm = function() {
98
 
98
 
99
	var lthis = this;
99
	var lthis = this;
100
 
100
 
101
	this.chargerStatutSSO();
101
	this.chargerStatutSSO();
102
 
102
 
103
	if ( valeurOk( this.obsId ) ) {
103
	if ( valeurOk( this.obsId ) ) {
104
		this.chargerInfoObs();
104
		this.chargerInfoObs();
105
	}
105
	}
106
 
106
 
107
	if( this.isTaxonListe ) {
107
	if( this.isTaxonListe ) {
108
		this.surChangementTaxonListe();
108
		this.surChangementTaxonListe();
109
		$( '#taxon-liste' ).on( 'change', lthis.surChangementTaxonListe );
109
		$( '#taxon-liste' ).on( 'change', lthis.surChangementTaxonListe );
110
		$( '#taxon-liste' ).on( 'change', lthis.surChangementValeurTaxon.bind( lthis ) );
110
		$( '#taxon-liste' ).on( 'change', lthis.surChangementValeurTaxon.bind( lthis ) );
111
		if ( this.debug ) {
111
		if ( this.debug ) {
112
			console.log( 'Selected taxon:' + $( '#taxon-liste option:selected' ).val());
112
			console.log( 'Selected taxon:' + $( '#taxon-liste option:selected' ).val());
113
		}
113
		}
114
	} else {
114
	} else {
115
		this.ajouterAutocompletionNoms();
115
		this.ajouterAutocompletionNoms();
116
	}
116
	}
117
	// au rafraichissement de la page,
117
	// au rafraichissement de la page,
118
	// les input date semblent conserver la valeur entrée précedemment
118
	// les input date semblent conserver la valeur entrée précedemment
119
	// c'est voulu après la création d'un obs mais pas quand la page est actualisée
119
	// c'est voulu après la création d'un obs mais pas quand la page est actualisée
120
	// Déjà tenté: onbeforeunload avec un location.reload(true) n'a pas permis de le faire
120
	// Déjà tenté: onbeforeunload avec un location.reload(true) n'a pas permis de le faire
121
	$( 'input[type=date]' ).each( function () {
121
	$( 'input[type=date]' ).each( function () {
122
		( valeurOk( $( this ).data( 'default' ) ) ) ? $( this ).val( $( this ).data( 'default' ) ) : $( this ).val( '' );
122
		( valeurOk( $( this ).data( 'default' ) ) ) ? $( this ).val( $( this ).data( 'default' ) ) : $( this ).val( '' );
123
	});
123
	});
124
	this.configurerFormValidator();
124
	this.configurerFormValidator();
125
	this.definirReglesFormValidator();
125
	this.definirReglesFormValidator();
126
 
126
 
127
	if( this.especeImposee ) {
127
	if( this.especeImposee ) {
128
		$( '#taxon' ).attr( 'disabled', 'disabled' );
128
		$( '#taxon' ).attr( 'disabled', 'disabled' );
129
		$( '#taxon-input-groupe' ).attr( 'title', '' );
129
		$( '#taxon-input-groupe' ).attr( 'title', '' );
130
		// Bricolage cracra pour avoir le nom retenu avec auteur (nom_retenu.libelle ne le mentionne pas)
130
		// Bricolage cracra pour avoir le nom retenu avec auteur (nom_retenu.libelle ne le mentionne pas)
131
		var infosEspeceImposee = $.parseJSON( this.infosEspeceImposee );
131
		var infosEspeceImposee = $.parseJSON( this.infosEspeceImposee );
132
			nomRetenuComplet   = infosEspeceImposee.nom_retenu_complet,
132
			nomRetenuComplet   = infosEspeceImposee.nom_retenu_complet,
133
			debutAnneRefBiblio = nomRetenuComplet.indexOf( ' [' );
133
			debutAnneRefBiblio = nomRetenuComplet.indexOf( ' [' );
134
		if ( -1 !== debutAnneRefBiblio ) {
134
		if ( -1 !== debutAnneRefBiblio ) {
135
			nomRetenuComplet = nomRetenuComplet.substr( 0, debutAnneRefBiblio );
135
			nomRetenuComplet = nomRetenuComplet.substr( 0, debutAnneRefBiblio );
136
		}
136
		}
137
		// fin bricolage cracra
137
		// fin bricolage cracra
138
		var infosAssociee = {
138
		var infosAssociee = {
139
			label : infosEspeceImposee.nom_sci_complet,
139
			label : infosEspeceImposee.nom_sci_complet,
140
			value : infosEspeceImposee.nom_sci_complet,
140
			value : infosEspeceImposee.nom_sci_complet,
141
			nt : infosEspeceImposee.num_taxonomique,
141
			nt : infosEspeceImposee.num_taxonomique,
142
			nomSel : infosEspeceImposee.nom_sci,
142
			nomSel : infosEspeceImposee.nom_sci,
143
			nomSelComplet : infosEspeceImposee.nom_sci_complet,
143
			nomSelComplet : infosEspeceImposee.nom_sci_complet,
144
			numNomSel : infosEspeceImposee.id,
144
			numNomSel : infosEspeceImposee.id,
145
			nomRet : nomRetenuComplet,
145
			nomRet : nomRetenuComplet,
146
			numNomRet : infosEspeceImposee['nom_retenu.id'],
146
			numNomRet : infosEspeceImposee['nom_retenu.id'],
147
			famille : infosEspeceImposee.famille,
147
			famille : infosEspeceImposee.famille,
148
			retenu : ( 'false' === infosEspeceImposee.retenu ) ? false : true
148
			retenu : ( 'false' === infosEspeceImposee.retenu ) ? false : true
149
		};
149
		};
150
		$( '#taxon' ).data( infosAssociee );
150
		$( '#taxon' ).data( infosAssociee );
151
	}
151
	}
152
};
152
};
153
 
153
 
154
/**
154
/**
155
 * Initialise les écouteurs d'événements
155
 * Initialise les écouteurs d'événements
156
 */
156
 */
157
WidgetSaisie.prototype.initEvts = function() {
157
WidgetSaisie.prototype.initEvts = function() {
158
	var lthis = this;
158
	var lthis = this;
159
	// Empêcher que le module carto ne bind ses events partout
159
	// Empêcher que le module carto ne bind ses events partout
160
	$( '#tb-geolocation' ).on( 'submit blur click focus mousedown mouseleave mouseup touchend touchstart change', '.mat-icon-button', function( event ) {
160
	$( '#tb-geolocation' ).on( 'submit blur click focus mousedown mouseleave mouseup touchend touchstart change', '*', function( event ) {
161
		event.preventDefault();
161
		event.preventDefault();
162
		return false;
162
		return false;
163
	});
163
	});
164
 
-
 
165
 
164
 
166
	// identité
165
	// identité
167
	$( '#deconnexion a' ).click( function( event ) {
166
	$( '#deconnexion a' ).click( function( event ) {
168
		event.preventDefault();
167
		event.preventDefault();
169
		lthis.deconnecterUtilisateur();
168
		lthis.deconnecterUtilisateur();
170
	});
169
	});
171
	$( '#bouton-anonyme' ).on( 'click', function( event ) {
170
	$( '#bouton-anonyme' ).on( 'click', function( event ) {
172
		arreter( event );
171
		arreter( event );
173
		$( this ).css({
172
		$( this ).css({
174
			'background-color': 'rgba(0, 159, 184, 0.7)',
173
			'background-color': 'rgba(0, 159, 184, 0.7)',
175
			'color': '#fff'
174
			'color': '#fff'
176
		});
175
		});
177
		$( '#anonyme' ).removeClass( 'hidden' );
176
		$( '#anonyme' ).removeClass( 'hidden' );
178
		$( '#courriel' ).focus();
177
		$( '#courriel' ).focus();
179
	});
178
	});
180
	if ( '' === $( '#nom-complet').text() ) {
179
	if ( '' === $( '#nom-complet').text() ) {
181
		$( '#courriel' ).on( 'blur', this.requeterIdentiteCourriel.bind( this ) );
180
		$( '#courriel' ).on( 'blur', this.requeterIdentiteCourriel.bind( this ) );
182
		$( '#courriel' ).on( 'keypress', this.testerLancementRequeteIdentite.bind( this ) );
181
		$( '#courriel' ).on( 'keypress', this.testerLancementRequeteIdentite.bind( this ) );
183
	}
182
	}
184
	$( '#prenom' ).on( 'change', this.formaterPrenom );
183
	$( '#prenom' ).on( 'change', this.formaterPrenom );
185
	$( '#nom' ).on( 'change', this.formaterNom );
184
	$( '#nom' ).on( 'change', this.formaterNom );
186
	$( '#courriel_confirmation' ).on( 'paste', this.bloquerCopierCollerCourriel.bind( this ) );
185
	$( '#courriel_confirmation' ).on( 'paste', this.bloquerCopierCollerCourriel.bind( this ) );
187
 
186
 
188
	// Sur téléchargement image
187
	// Sur téléchargement image
189
	$( '#fichier' ).on( 'change', function ( e ) {
188
	$( '#fichier' ).on( 'change', function ( e ) {
190
		arreter( e );
189
		arreter( e );
191
		var options = {
190
		var options = {
192
			success: lthis.afficherMiniature.bind( lthis ), // post-submit callback
191
			success: lthis.afficherMiniature.bind( lthis ), // post-submit callback
193
			dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
192
			dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
194
			resetForm: true // reset the form after successful submit
193
			resetForm: true // reset the form after successful submit
195
		};
194
		};
196
		$( '#miniature' ).append( '<img id="miniature-chargement" class="miniature" alt="chargement" src="' + this.chargementImageIconeUrl + '"/>' );
195
		$( '#miniature' ).append( '<img id="miniature-chargement" class="miniature" alt="chargement" src="' + this.chargementImageIconeUrl + '"/>' );
197
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
196
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
198
		if( lthis.verifierFormat( $( '#fichier' ).val() ) ) {
197
		if( lthis.verifierFormat( $( '#fichier' ).val() ) ) {
199
			$( '#form-upload' ).ajaxSubmit( options );
198
			$( '#form-upload' ).ajaxSubmit( options );
200
		} else {
199
		} else {
201
			$( '#form-upload' )[0].reset();
200
			$( '#form-upload' )[0].reset();
202
			window.alert( lthis.msgTraduction( 'format-non-supporte' ) + ' ' + $( '#fichier' ).attr( 'accept' ) );
201
			window.alert( lthis.msgTraduction( 'format-non-supporte' ) + ' ' + $( '#fichier' ).attr( 'accept' ) );
203
		}
202
		}
204
		return false;
203
		return false;
205
	});
204
	});
206
 
205
 
207
	$( 'body' ).on( 'click', '.effacer-miniature', function() {
206
	$( 'body' ).on( 'click', '.effacer-miniature', function() {
208
		$( this ).parent().remove();
207
		$( this ).parent().remove();
209
	});
208
	});
210
 
209
 
211
	$( '#referentiel' ).on( 'change', this.surChangementReferentiel.bind( this ) );
210
	$( '#referentiel' ).on( 'change', this.surChangementReferentiel.bind( this ) );
212
 
211
 
213
	$( '#ajouter-obs' ).on( 'click', this.ajouterObs.bind( this ) );
212
	$( '#ajouter-obs' ).on( 'click', this.ajouterObs.bind( this ) );
214
	$( '.obs-nbre' ).on( 'changement', this.surChangementNbreObs.bind( this ) );
213
	$( '.obs-nbre' ).on( 'changement', this.surChangementNbreObs.bind( this ) );
215
 
214
 
216
	$( 'body' ).on( 'click', '.defilement-miniatures-gauche', function( event ) {
215
	$( 'body' ).on( 'click', '.defilement-miniatures-gauche', function( event ) {
217
		event.preventDefault();
216
		event.preventDefault();
218
		lthis.defilerMiniatures( $( this ) );
217
		lthis.defilerMiniatures( $( this ) );
219
	});
218
	});
220
	$( 'body' ).on( 'click', '.defilement-miniatures-droite', function( event ) {
219
	$( 'body' ).on( 'click', '.defilement-miniatures-droite', function( event ) {
221
		event.preventDefault();
220
		event.preventDefault();
222
		lthis.defilerMiniatures( $( this ) );
221
		lthis.defilerMiniatures( $( this ) );
223
	});
222
	});
224
	$( 'body' ).on( 'click', '.supprimer-obs', function() {
223
	$( 'body' ).on( 'click', '.supprimer-obs', function() {
225
	 var that = this,
224
	 var that = this,
226
			suppObs = lthis.supprimerObs.bind( lthis );
225
			suppObs = lthis.supprimerObs.bind( lthis );
227
	 // bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
226
	 // bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
228
	 suppObs( that );
227
	 suppObs( that );
229
	});
228
	});
230
 
229
 
231
	$( '#transmettre-obs' ).on( 'click', this.transmettreObs.bind( this ) );
230
	$( '#transmettre-obs' ).on( 'click', this.transmettreObs.bind( this ) );
232
 
231
 
233
	// Alertes et tooltips
232
	// Alertes et tooltips
234
	$( '.alert .close' ).on( 'click', this.fermerPanneauAlert );
233
	$( '.alert .close' ).on( 'click', this.fermerPanneauAlert );
235
	$( '#btn-aide' ).on( 'click', this.basculerAffichageAide );
234
	$( '#btn-aide' ).on( 'click', this.basculerAffichageAide );
236
	$( '.has-tooltip' ).tooltip( 'enable' );
235
	$( '.has-tooltip' ).tooltip( 'enable' );
237
};
236
};
238
 
237
 
239
// Identité Observateur *******************************************************/
238
// Identité Observateur *******************************************************/
240
/**
239
/**
241
 * Interroge le SSO pour connaître le statut de l'utilisateur, et change le menu
240
 * Interroge le SSO pour connaître le statut de l'utilisateur, et change le menu
242
 * à droite de la barre en fonction
241
 * à droite de la barre en fonction
243
 */
242
 */
244
WidgetSaisie.prototype.chargerStatutSSO = function() {
243
WidgetSaisie.prototype.chargerStatutSSO = function() {
245
	$( '#form-observateur' )[0].reset();
244
	$( '#form-observateur' )[0].reset();
246
	var lthis = this;
245
	var lthis = this;
247
 
246
 
248
	var urlAuth = this.urlBaseAuth + '/identite';
247
	var urlAuth = this.urlBaseAuth + '/identite';
249
 
248
 
250
	if( 'local' !== this.mode ) {
249
	if( 'local' !== this.mode ) {
251
		this.connexion( urlAuth, true );
250
		this.connexion( urlAuth, true );
252
	} else {
251
	} else {
253
		urlAuth = window.location.origin + '/widget:cel:modules/saisie2/test-token.json';
252
		urlAuth = window.location.origin + '/widget:cel:modules/saisie2/test-token.json';
254
		$( '#connexion' ).click( function( event ) {
253
		$( '#connexion' ).click( function( event ) {
255
			event.preventDefault();
254
			event.preventDefault();
256
			lthis.connexion( urlAuth, true );
255
			lthis.connexion( urlAuth, true );
257
		});
256
		});
258
	}
257
	}
259
};
258
};
260
 
259
 
261
/**
260
/**
262
 * Déconnecte l'utilisateur du SSO
261
 * Déconnecte l'utilisateur du SSO
263
 */
262
 */
264
WidgetSaisie.prototype.deconnecterUtilisateur = function() {
263
WidgetSaisie.prototype.deconnecterUtilisateur = function() {
265
  if( 'local' === this.mode ) {
264
  if( 'local' === this.mode ) {
266
	this.definirUtilisateur();
265
	this.definirUtilisateur();
267
	window.location.reload();
266
	window.location.reload();
268
	return;
267
	return;
269
  }
268
  }
270
 
269
 
271
  var urlAuth = this.urlBaseAuth + '/deconnexion';
270
  var urlAuth = this.urlBaseAuth + '/deconnexion';
272
 
271
 
273
  this.connexion( urlAuth, false );
272
  this.connexion( urlAuth, false );
274
};
273
};
275
 
274
 
276
WidgetSaisie.prototype.connexion = function( urlAuth, connexionOnOff ) {
275
WidgetSaisie.prototype.connexion = function( urlAuth, connexionOnOff ) {
277
	var lthis = this;
276
	var lthis = this;
278
	console.log(urlAuth);
-
 
279
  $.ajax({
277
  $.ajax({
280
	url: urlAuth,
278
	url: urlAuth,
281
	type: "GET",
279
	type: "GET",
282
	dataType: 'json',
280
	dataType: 'json',
283
	xhrFields: {
281
	xhrFields: {
284
	  withCredentials: true
282
	  withCredentials: true
285
	}
283
	}
286
  })
284
  })
287
  .done( function( data ) {
285
  .done( function( data ) {
288
	if( connexionOnOff ) {
286
	if( connexionOnOff ) {
289
	  // connecté
287
	  // connecté
290
	  lthis.definirUtilisateur( data.token );
288
	  lthis.definirUtilisateur( data.token );
291
	} else {
289
	} else {
292
	  lthis.definirUtilisateur();
290
	  lthis.definirUtilisateur();
293
	  window.location.reload();
291
	  window.location.reload();
294
	}
292
	}
295
  })
293
  })
296
  .fail( function( error ) {
294
  .fail( function( error ) {
297
	// @TODO gérer l'affichage de l'erreur, mais pas facile à placer
295
	// @TODO gérer l'affichage de l'erreur, mais pas facile à placer
298
	// dans l'interface actuelle sans que ce soit moche
296
	// dans l'interface actuelle sans que ce soit moche
299
	//afficherErreurServeur();
297
	//afficherErreurServeur();
300
  });
298
  });
301
}
299
}
302
 
300
 
303
WidgetSaisie.prototype.definirUtilisateur = function( jeton ) {
301
WidgetSaisie.prototype.definirUtilisateur = function( jeton ) {
304
  var idUtilisateur = '',
302
  var idUtilisateur = '',
305
	  nomComplet    = '',
303
	  nomComplet    = '',
306
	  courriel      = '',
304
	  courriel      = '',
307
	  pseudo        = '',
305
	  pseudo        = '',
308
	  prenom        = '',
306
	  prenom        = '',
309
	  nom           = '';
307
	  nom           = '';
310
 
308
 
311
  // affichage
309
  // affichage
312
  if ( undefined !== jeton ) {
310
  if ( undefined !== jeton ) {
313
	// décodage jeton
311
	// décodage jeton
314
	var jetonDecode = this.decoderJeton( jeton );
312
	var jetonDecode = this.decoderJeton( jeton );
315
	// console.log(jetonDecode);
313
	// console.log(jetonDecode);
316
 
314
 
317
	idUtilisateur = jetonDecode.id;
315
	idUtilisateur = jetonDecode.id;
318
	nomComplet    = jetonDecode.intitule;
316
	nomComplet    = jetonDecode.intitule;
319
	courriel      = jetonDecode.sub;
317
	courriel      = jetonDecode.sub;
320
	pseudo        = jetonDecode.pseudo;
318
	pseudo        = jetonDecode.pseudo;
321
	prenom        = jetonDecode.prenom;
319
	prenom        = jetonDecode.prenom;
322
	nom           = jetonDecode.nom;
320
	nom           = jetonDecode.nom;
323
	$( '#courriel, #courriel_confirmation' ).attr( 'disabled', 'disabled' );
321
	$( '#courriel, #courriel_confirmation' ).attr( 'disabled', 'disabled' );
324
	$( '#prenom' ).attr( 'disabled', 'disabled' );
322
	$( '#prenom' ).attr( 'disabled', 'disabled' );
325
	$( '#nom' ).attr( 'disabled', 'disabled' );
323
	$( '#nom' ).attr( 'disabled', 'disabled' );
326
	$( '#bouton-connexion, #creation-compte' ).addClass( 'hidden' );
324
	$( '#bouton-connexion, #creation-compte' ).addClass( 'hidden' );
327
	$( '#utilisateur-connecte, #anonyme, #zone-courriel-confirmation, #zone-prenom-nom' ).removeClass( 'hidden' );
325
	$( '#utilisateur-connecte, #anonyme, #zone-courriel-confirmation, #zone-prenom-nom' ).removeClass( 'hidden' );
328
	$( '#date-releve' ).focus();
326
	$( '#date-releve' ).focus();
329
  }
327
  }
330
  $( '.warning' ).remove();
328
  $( '.warning' ).remove();
331
  $( '#nom-complet' ).html( nomComplet );
329
  $( '#nom-complet' ).html( nomComplet );
332
  $( '#courriel, #courriel_confirmation' ).val( courriel );
330
  $( '#courriel, #courriel_confirmation' ).val( courriel );
333
  $( '#profil-utilisateur a' ).attr( 'href', this.urlProfilUtilisateur( pseudo ) );
331
  $( '#profil-utilisateur a' ).attr( 'href', this.urlProfilUtilisateur( pseudo ) );
334
  $( '#id_utilisateur' ).val( idUtilisateur );
332
  $( '#id_utilisateur' ).val( idUtilisateur );
335
  $( '#prenom' ).val( prenom );
333
  $( '#prenom' ).val( prenom );
336
  $( '#nom' ).val( nom );
334
  $( '#nom' ).val( nom );
337
};
335
};
338
 
336
 
339
/**
337
/**
340
 * Décodage à l'arrache d'un jeton JWT, ATTENTION CONSIDERE QUE LE
338
 * Décodage à l'arrache d'un jeton JWT, ATTENTION CONSIDERE QUE LE
341
 * JETON EST VALIDE, ne pas décoder n'importe quoi - pas trouvé de lib simple
339
 * JETON EST VALIDE, ne pas décoder n'importe quoi - pas trouvé de lib simple
342
 */
340
 */
343
WidgetSaisie.prototype.decoderJeton = function( jeton ) {
341
WidgetSaisie.prototype.decoderJeton = function( jeton ) {
344
  parts = jeton.split( '.' );
342
  parts = jeton.split( '.' );
345
  payload = parts[1];
343
  payload = parts[1];
346
  payload = this.b64d( payload );
344
  payload = this.b64d( payload );
347
  payload = JSON.parse( payload, true );
345
  payload = JSON.parse( payload, true );
348
  return payload;
346
  return payload;
349
};
347
};
350
 
348
 
351
/**
349
/**
352
 * Décodage "url-safe" des chaînes base64 retournées par le SSO (lib jwt)
350
 * Décodage "url-safe" des chaînes base64 retournées par le SSO (lib jwt)
353
 */
351
 */
354
WidgetSaisie.prototype.b64d = function( input ) {
352
WidgetSaisie.prototype.b64d = function( input ) {
355
  var remainder = input.length % 4;
353
  var remainder = input.length % 4;
356
 
354
 
357
  if ( 0 !== remainder ) {
355
  if ( 0 !== remainder ) {
358
	var padlen = 4 - remainder;
356
	var padlen = 4 - remainder;
359
 
357
 
360
	for ( var i = 0; i < padlen; i++ ) {
358
	for ( var i = 0; i < padlen; i++ ) {
361
	  input += '=';
359
	  input += '=';
362
	}
360
	}
363
  }
361
  }
364
  input = input.replace( '-', '+' );
362
  input = input.replace( '-', '+' );
365
  input = input.replace( '_', '/' );
363
  input = input.replace( '_', '/' );
366
  return atob( input );
364
  return atob( input );
367
};
365
};
368
 
366
 
369
WidgetSaisie.prototype.urlProfilUtilisateur = function( pseudo ) {
367
WidgetSaisie.prototype.urlProfilUtilisateur = function( pseudo ) {
370
  var urlPart = ( 'prod' === this.mode ) ? 'www.tela-botanica.org/' : 'beta.tela-botanica.org/test/';
368
  var urlPart = ( 'test' === this.mode ) ? '/test/' : '';
371
 
369
 
372
  return 'https://' + urlPart + 'membres/' + pseudo.toLowerCase().replace( ' ', '-' );
370
  return window.location.origin + urlPart + 'membres/' + pseudo.toLowerCase().replace( ' ', '-' );
373
};
371
};
374
 
372
 
375
// Identité Observateur par courriel
373
// Identité Observateur par courriel
376
WidgetSaisie.prototype.requeterIdentiteCourriel = function() {
374
WidgetSaisie.prototype.requeterIdentiteCourriel = function() {
377
	var lthis = this;
375
	var lthis = this;
378
	var courriel = $( '#courriel' ).val();
376
	var courriel = $( '#courriel' ).val();
379
	var urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;
377
	var urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;
380
	if ( valeurOk( courriel ) ) {
378
	if ( valeurOk( courriel ) ) {
381
		$.ajax({
379
		$.ajax({
382
			url : urlAnnuaire,
380
			url : urlAnnuaire,
383
			type : 'GET',
381
			type : 'GET',
384
			success : function( data, textStatus, jqXHR ) {
382
			success : function( data, textStatus, jqXHR ) {
385
				if ( lthis.debug ) {
383
				if ( lthis.debug ) {
386
					console.log( 'SUCCESS: ' + textStatus );
384
					console.log( 'SUCCESS: ' + textStatus );
387
				}
385
				}
388
				if ( valeurOk( data ) && valeurOk( data[courriel] ) ) {
386
				if ( valeurOk( data ) && valeurOk( data[courriel] ) ) {
389
					var infos = data[courriel];
387
					var infos = data[courriel];
390
					lthis.surSuccesCompletionCourriel( infos, courriel );
388
					lthis.surSuccesCompletionCourriel( infos, courriel );
391
				} else {
389
				} else {
392
					lthis.surErreurCompletionCourriel();
390
					lthis.surErreurCompletionCourriel();
393
				}
391
				}
394
			},
392
			},
395
			error : function( jqXHR, textStatus, errorThrown ) {
393
			error : function( jqXHR, textStatus, errorThrown ) {
396
				if ( lthis.debug ) {
394
				if ( lthis.debug ) {
397
					console.log( 'ERREUR: '+ textStatus );
395
					console.log( 'ERREUR: '+ textStatus );
398
				}
396
				}
399
				lthis.surErreurCompletionCourriel();
397
				lthis.surErreurCompletionCourriel();
400
			},
398
			},
401
			complete : function( jqXHR, textStatus ) {
399
			complete : function( jqXHR, textStatus ) {
402
				if ( lthis.debug ) {
400
				if ( lthis.debug ) {
403
					console.log( 'COMPLETE: '+ textStatus );
401
					console.log( 'COMPLETE: '+ textStatus );
404
				}
402
				}
405
			}
403
			}
406
		});
404
		});
407
	}
405
	}
408
};
406
};
409
 
407
 
410
// se déclanche quand on choisit "Observation sans inscription" mais que le mail entré est incrit à Tela
408
// se déclanche quand on choisit "Observation sans inscription" mais que le mail entré est incrit à Tela
411
WidgetSaisie.prototype.surSuccesCompletionCourriel = function( infos, courriel ) {
409
WidgetSaisie.prototype.surSuccesCompletionCourriel = function( infos, courriel ) {
412
	if ( $( '#utilisateur-connecte' ).hasClass( 'hidden' ) ) {// si quelque chose a foiré après actualisation
410
	if ( $( '#utilisateur-connecte' ).hasClass( 'hidden' ) ) {// si quelque chose a foiré après actualisation
413
		if ( !valeurOk( $( '#warning-identite' ) ) ) {
411
		if ( !valeurOk( $( '#warning-identite' ) ) ) {
414
			$( '#zone-courriel' ).before( '<p id="warning-identite" class="warning"><i class="fas fa-exclamation-triangle"></i> ' + this.msgTraduction( 'courriel-connu' ) + '</p>' );
412
			$( '#zone-courriel' ).before( '<p id="warning-identite" class="warning"><i class="fas fa-exclamation-triangle"></i> ' + this.msgTraduction( 'courriel-connu' ) + '</p>' );
415
		}
413
		}
416
		$( '#bouton-inscription, #zone-prenom-nom, #zone-courriel-confirmation' ).addClass( 'hidden' );
414
		$( '#bouton-inscription, #zone-prenom-nom, #zone-courriel-confirmation' ).addClass( 'hidden' );
417
		$( '#prenom, #nom, #courriel_confirmation' ).attr( 'disabled', 'disabled' );
415
		$( '#prenom, #nom, #courriel_confirmation' ).attr( 'disabled', 'disabled' );
418
		$( '.nav.control-group' ).addClass( 'error' );
416
		$( '.nav.control-group' ).addClass( 'error' );
419
	}
417
	}
420
};
418
};
421
 
419
 
422
// se déclanche quand on choisit "Observation sans inscription" et qu'effectivement le mail n'est pas connu de Tela
420
// se déclanche quand on choisit "Observation sans inscription" et qu'effectivement le mail n'est pas connu de Tela
423
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
421
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
424
	$( '#creation-compte, #zone-prenom-nom, #zone-courriel-confirmation' ).removeClass( 'hidden' );
422
	$( '#creation-compte, #zone-prenom-nom, #zone-courriel-confirmation' ).removeClass( 'hidden' );
425
	$( '#warning-identite' ).remove();
423
	$( '#warning-identite' ).remove();
426
	$( '.nav.control-group' ).removeClass( 'error' );
424
	$( '.nav.control-group' ).removeClass( 'error' );
427
 
425
 
428
	$( '#prenom, #nom, #courriel_confirmation' ).val( '' );
426
	$( '#prenom, #nom, #courriel_confirmation' ).val( '' );
429
	$( '#prenom, #nom, #courriel_confirmation' ).removeAttr( 'disabled' );
427
	$( '#prenom, #nom, #courriel_confirmation' ).removeAttr( 'disabled' );
430
};
428
};
431
 
429
 
432
WidgetSaisie.prototype.testerLancementRequeteIdentite = function( event ) {
430
WidgetSaisie.prototype.testerLancementRequeteIdentite = function( event ) {
433
	if ( valeurOk( event.which, true, 13 ) ) {
431
	if ( valeurOk( event.which, true, 13 ) ) {
434
		this.requeterIdentiteCourriel();
432
		this.requeterIdentiteCourriel();
435
		event.preventDefault();
433
		event.preventDefault();
436
		event.stopPropagation();
434
		event.stopPropagation();
437
	}
435
	}
438
};
436
};
439
 
437
 
440
WidgetSaisie.prototype.formaterNom = function() {
438
WidgetSaisie.prototype.formaterNom = function() {
441
	$( this ).val( $( this ).val().toUpperCase() );
439
	$( this ).val( $( this ).val().toUpperCase() );
442
};
440
};
443
 
441
 
444
WidgetSaisie.prototype.formaterPrenom = function() {
442
WidgetSaisie.prototype.formaterPrenom = function() {
445
	var prenom = new Array(),
443
	var prenom = new Array(),
446
			mots = $( this ).val().split( ' ' ),
444
			mots = $( this ).val().split( ' ' ),
447
			motsLength = mots.length;
445
			motsLength = mots.length;
448
 
446
 
449
	for ( var i = 0; i < motsLength; i++ ) {
447
	for ( var i = 0; i < motsLength; i++ ) {
450
		var mot = mots[i];
448
		var mot = mots[i];
451
		if ( 0 <= mot.indexOf( '-' ) ) {
449
		if ( 0 <= mot.indexOf( '-' ) ) {
452
			var prenomCompose = new Array(),
450
			var prenomCompose = new Array(),
453
					motsComposes = mot.split( '-' )
451
					motsComposes = mot.split( '-' )
454
					motsComposesLength = motsComposes.length;
452
					motsComposesLength = motsComposes.length;
455
			for ( var j = 0; j < motsComposesLength; j++ ) {
453
			for ( var j = 0; j < motsComposesLength; j++ ) {
456
				var motSimple = motsComposes[j],
454
				var motSimple = motsComposes[j],
457
						motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
455
						motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
458
 
456
 
459
				prenomCompose.push( motMajuscule );
457
				prenomCompose.push( motMajuscule );
460
			}
458
			}
461
			prenom.push( prenomCompose.join( '-' ) );
459
			prenom.push( prenomCompose.join( '-' ) );
462
		} else {
460
		} else {
463
			var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
461
			var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
464
			prenom.push( motMajuscule );
462
			prenom.push( motMajuscule );
465
		}
463
		}
466
	}
464
	}
467
	$( this ).val( prenom.join( ' ' ) );
465
	$( this ).val( prenom.join( ' ' ) );
468
};
466
};
469
 
467
 
470
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
468
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
471
	this.afficherPanneau( '#dialogue-bloquer-copier-coller' );
469
	this.afficherPanneau( '#dialogue-bloquer-copier-coller' );
472
	return false;
470
	return false;
473
};
471
};
474
 
472
 
475
// Préchargement des infos-obs ************************************************/
473
// Préchargement des infos-obs ************************************************/
476
WidgetSaisie.prototype.chargerInfoObs = function() {
474
WidgetSaisie.prototype.chargerInfoObs = function() {
477
	var urlObs = this.serviceObsUrl + '/' + this.obsId;
475
	var urlObs = this.serviceObsUrl + '/' + this.obsId;
478
	var lthis = this;
476
	var lthis = this;
479
	$.ajax({
477
	$.ajax({
480
		url: urlObs,
478
		url: urlObs,
481
		type: 'GET',
479
		type: 'GET',
482
		success: function( data, textStatus, jqXHR ) {
480
		success: function( data, textStatus, jqXHR ) {
483
			if ( valeurOk( data ) ) {
481
			if ( valeurOk( data ) ) {
484
				lthis.prechargerForm( data );
482
				lthis.prechargerForm( data );
485
			} else {
483
			} else {
486
				lthis.surErreurChargementInfosObs.bind( lthis );
484
				lthis.surErreurChargementInfosObs.bind( lthis );
487
			}
485
			}
488
		},
486
		},
489
		error: function( jqXHR, textStatus, errorThrown ) {
487
		error: function( jqXHR, textStatus, errorThrown ) {
490
			lthis.surErreurChargementInfosObs();
488
			lthis.surErreurChargementInfosObs();
491
		}
489
		}
492
	});
490
	});
493
};
491
};
494
 
492
 
495
// @TODO faire mieux que ça !
493
// @TODO faire mieux que ça !
496
WidgetSaisie.prototype.surErreurChargementInfosObs = function() {
494
WidgetSaisie.prototype.surErreurChargementInfosObs = function() {
497
	alert( this.msgTraduction( 'erreur-chargement' ) );
495
	alert( this.msgTraduction( 'erreur-chargement' ) );
498
};
496
};
499
 
497
 
500
WidgetSaisie.prototype.prechargerForm = function( data ) {
498
WidgetSaisie.prototype.prechargerForm = function( data ) {
501
 
499
 
502
	$( '#milieu' ).val( data.milieu );
500
	$( '#milieu' ).val( data.milieu );
503
 
501
 
504
	// $( '#carte-recherche' ).val( data.zoneGeo );
502
	// $( '#carte-recherche' ).val( data.zoneGeo );
505
	// $( '#commune-nom' ).text( data.zoneGeo );
503
	// $( '#commune-nom' ).text( data.zoneGeo );
506
 
504
 
507
	// if( data.hasOwnProperty( 'codeZoneGeo' ) ) {
505
	// if( data.hasOwnProperty( 'codeZoneGeo' ) ) {
508
	//   // TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
506
	//   // TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
509
	//   $( '#commune-code-insee' ).text( data.codeZoneGeo.replace( 'INSEE-C:', '' ) );
507
	//   $( '#commune-code-insee' ).text( data.codeZoneGeo.replace( 'INSEE-C:', '' ) );
510
	// }
508
	// }
511
 
509
 
512
	// if( data.hasOwnProperty( 'latitude' ) && data.hasOwnProperty( 'longitude' ) ) {
510
	// if( data.hasOwnProperty( 'latitude' ) && data.hasOwnProperty( 'longitude' ) ) {
513
	//   var latLng = new google.maps.LatLng( data.latitude, data.longitude );
511
	//   var latLng = new google.maps.LatLng( data.latitude, data.longitude );
514
	//   this.mettreAJourMarkerPosition( latLng );
512
	//   this.mettreAJourMarkerPosition( latLng );
515
	//   this.marker.setPosition( latLng );
513
	//   this.marker.setPosition( latLng );
516
	//   this.map.setCenter( latLng );
514
	//   this.map.setCenter( latLng );
517
	//   this.map.setZoom( 16 );
515
	//   this.map.setZoom( 16 );
518
	// }
516
	// }
519
};
517
};
520
 
518
 
521
// uniquement utilisé si taxon-liste ******************************************/
519
// uniquement utilisé si taxon-liste ******************************************/
522
// Affiche/Cache le champ taxon
520
// Affiche/Cache le champ taxon
523
WidgetSaisie.prototype.surChangementTaxonListe = function() {
521
WidgetSaisie.prototype.surChangementTaxonListe = function() {
524
	if ( valeurOk( $( '#taxon-liste' ).val() ) ) {
522
	if ( valeurOk( $( '#taxon-liste' ).val() ) ) {
525
		if ( 'autre' !== $( '#taxon-liste' ).val() ) {
523
		if ( 'autre' !== $( '#taxon-liste' ).val() ) {
526
			$( '#taxon-input-groupe' )
524
			$( '#taxon-input-groupe' )
527
				.hide( 200, function () {
525
				.hide( 200, function () {
528
					$( this ).addClass( 'hidden' ).show();
526
					$( this ).addClass( 'hidden' ).show();
529
				})
527
				})
530
				.find( '#taxon-autre' ).val( '' );
528
				.find( '#taxon-autre' ).val( '' );
531
		} else {
529
		} else {
532
			$( '#taxon-input-groupe' )
530
			$( '#taxon-input-groupe' )
533
				.hide()
531
				.hide()
534
				.removeClass( 'hidden' )
532
				.removeClass( 'hidden' )
535
				.show(200)
533
				.show(200)
536
				.find( '#taxon-autre' )
534
				.find( '#taxon-autre' )
537
					.on( 'change', function() {
535
					.on( 'change', function() {
538
						if( !valeurOk( $( '#taxon-autre' ).data( 'numNomSel' ) ) ) {
536
						if( !valeurOk( $( '#taxon-autre' ).data( 'numNomSel' ) ) ) {
539
							$( '#taxon' ).val( $( '#taxon-autre' ).val() );
537
							$( '#taxon' ).val( $( '#taxon-autre' ).val() );
540
							$( '#taxon' ).data( 'numNomSel', '' )
538
							$( '#taxon' ).data( 'numNomSel', '' )
541
								.data( 'nomRet','' )
539
								.data( 'nomRet','' )
542
								.data( 'numNomRet', '' )
540
								.data( 'numNomRet', '' )
543
								.data( 'nt', '' )
541
								.data( 'nt', '' )
544
								.data( 'famille', '' );
542
								.data( 'famille', '' );
545
						}
543
						}
546
						$( '#taxon' ).trigger( 'change' );
544
						$( '#taxon' ).trigger( 'change' );
547
					});
545
					});
548
		}
546
		}
549
	}
547
	}
550
};
548
};
551
 
549
 
552
 
550
 
553
WidgetSaisie.prototype.surChangementValeurTaxon = function() {
551
WidgetSaisie.prototype.surChangementValeurTaxon = function() {
554
	var numNomSel = 0;
552
	var numNomSel = 0;
555
 
553
 
556
	if( valeurOk( $( '#taxon-liste' ).val() ) ) {
554
	if( valeurOk( $( '#taxon-liste' ).val() ) ) {
557
		if( 'autre' === $( '#taxon-liste' ).val() ) {
555
		if( 'autre' === $( '#taxon-liste' ).val() ) {
558
			this.ajouterAutocompletionNoms();
556
			this.ajouterAutocompletionNoms();
559
		} else {
557
		} else {
560
			var optionRetenue = $( '#taxon-liste' ).find( 'option[value="' + $( '#taxon-liste' ).val() + '"]' );
558
			var optionRetenue = $( '#taxon-liste' ).find( 'option[value="' + $( '#taxon-liste' ).val() + '"]' );
561
			// $( '#taxon' ).val( $( '#taxon-liste' ).val() );
559
			// $( '#taxon' ).val( $( '#taxon-liste' ).val() );
562
			$( '#taxon' ).val( $( '#taxon-liste' ).val() )
560
			$( '#taxon' ).val( $( '#taxon-liste' ).val() )
563
				.data( 'value', $( '#taxon-liste' ).val() )
561
				.data( 'value', $( '#taxon-liste' ).val() )
564
				.data( 'numNomSel', optionRetenue.data( 'num-nom-sel' ) )
562
				.data( 'numNomSel', optionRetenue.data( 'num-nom-sel' ) )
565
				.data( 'nomRet', optionRetenue.data( 'nom-ret' ) )
563
				.data( 'nomRet', optionRetenue.data( 'nom-ret' ) )
566
				.data( 'numNomRet', optionRetenue.data( 'num-nom-ret' ) )
564
				.data( 'numNomRet', optionRetenue.data( 'num-nom-ret' ) )
567
				.data( 'nt', optionRetenue.data( 'nt' ) )
565
				.data( 'nt', optionRetenue.data( 'nt' ) )
568
				.data( 'famille', optionRetenue.data( 'famille' ) );
566
				.data( 'famille', optionRetenue.data( 'famille' ) );
569
			$( '#taxon' ).trigger( 'change' );
567
			$( '#taxon' ).trigger( 'change' );
570
 
568
 
571
			numNomSel = $( '#taxon' ).data( 'numNomSel' );
569
			numNomSel = $( '#taxon' ).data( 'numNomSel' );
572
			// Si l'espèce est mal déterminée la certitude est "à déterminer"
570
			// Si l'espèce est mal déterminée la certitude est "à déterminer"
573
			if( !valeurOk( numNomSel ) ) {
571
			if( !valeurOk( numNomSel ) ) {
574
				$( '#certitude' ).find( 'option' ).each( function() {
572
				$( '#certitude' ).find( 'option' ).each( function() {
575
					if ( $( this ).hasClass( 'aDeterminer' ) ) {
573
					if ( $( this ).hasClass( 'aDeterminer' ) ) {
576
						$( this ).attr( 'selected', true );
574
						$( this ).attr( 'selected', true );
577
					} else {
575
					} else {
578
						$( this ).attr( 'selected', false );
576
						$( this ).attr( 'selected', false );
579
					}
577
					}
580
				});
578
				});
581
			}
579
			}
582
		}
580
		}
583
	}
581
	}
584
};
582
};
585
 
583
 
586
// Autocompletion taxons ******************************************************/
584
// Autocompletion taxons ******************************************************/
587
WidgetSaisie.prototype.ajouterAutocompletionNoms = function() {
585
WidgetSaisie.prototype.ajouterAutocompletionNoms = function() {
588
	var lthis = this;
586
	var lthis = this;
589
 
587
 
590
	var taxonSelecteur = '#taxon';
588
	var taxonSelecteur = '#taxon';
591
	if ( valeurOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
589
	if ( valeurOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
592
		taxonSelecteur += '-autre';
590
		taxonSelecteur += '-autre';
593
	}
591
	}
594
	$( taxonSelecteur ).autocomplete({
592
	$( taxonSelecteur ).autocomplete({
595
		source: function( requete, add ) {
593
		source: function( requete, add ) {
596
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
594
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
597
			requete = '';
595
			requete = '';
598
			if( valeurOk( $( '#referentiel' ).val(), false, 'autre' ) ) {
596
			if( valeurOk( $( '#referentiel' ).val(), false, 'autre' ) ) {
599
				var url = lthis.getUrlAutocompletionNomsSci();
597
				var url = lthis.getUrlAutocompletionNomsSci();
600
				$.getJSON( url, requete, function( data ) {
598
				$.getJSON( url, requete, function( data ) {
601
					var suggestions = lthis.traiterRetourNomsSci( data );
599
					var suggestions = lthis.traiterRetourNomsSci( data );
602
					add( suggestions );
600
					add( suggestions );
603
				})
601
				})
604
				.fail( function() {
602
				.fail( function() {
605
					$( '#certitude' ).find( 'option' ).each( function() {
603
					$( '#certitude' ).find( 'option' ).each( function() {
606
						if ( $( this ).hasClass( 'aDeterminer' ) ) {
604
						if ( $( this ).hasClass( 'aDeterminer' ) ) {
607
							$( this ).attr( 'selected', true );
605
							$( this ).attr( 'selected', true );
608
						} else {
606
						} else {
609
							$( this ).attr( 'selected', false );
607
							$( this ).attr( 'selected', false );
610
						}
608
						}
611
					});
609
					});
612
				});
610
				});
613
			}
611
			}
614
		},
612
		},
615
		html: true
613
		html: true
616
	});
614
	});
617
	$( taxonSelecteur ).on( 'autocompleteselect', this.surAutocompletionTaxon );
615
	$( taxonSelecteur ).on( 'autocompleteselect', this.surAutocompletionTaxon );
618
};
616
};
619
 
617
 
620
WidgetSaisie.prototype.getUrlAutocompletionNomsSci = function() {
618
WidgetSaisie.prototype.getUrlAutocompletionNomsSci = function() {
621
	var taxonSelecteur = '#taxon';
619
	var taxonSelecteur = '#taxon';
622
	if ( valeurOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
620
	if ( valeurOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
623
		taxonSelecteur += '-autre';
621
		taxonSelecteur += '-autre';
624
	}
622
	}
625
	var mots = $( taxonSelecteur ).val();
623
	var mots = $( taxonSelecteur ).val();
626
	var url = this.serviceAutocompletionNomSciUrlTpl.replace( '{referentiel}', this.nomSciReferentiel );
624
	var url = this.serviceAutocompletionNomSciUrlTpl.replace( '{referentiel}', this.nomSciReferentiel );
627
	url = url.replace( '{masque}', mots );
625
	url = url.replace( '{masque}', mots );
628
	return url;
626
	return url;
629
};
627
};
630
 
628
 
631
WidgetSaisie.prototype.traiterRetourNomsSci = function( data ) {
629
WidgetSaisie.prototype.traiterRetourNomsSci = function( data ) {
632
 
630
 
633
	var taxonSelecteur = '#taxon';
631
	var taxonSelecteur = '#taxon';
634
	if ( valeurOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
632
	if ( valeurOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
635
		taxonSelecteur += '-autre';
633
		taxonSelecteur += '-autre';
636
	}
634
	}
637
	var suggestions = [];
635
	var suggestions = [];
638
	if ( undefined != data.resultat ) {
636
	if ( undefined != data.resultat ) {
639
		$.each( data.resultat, function( i, val ) {
637
		$.each( data.resultat, function( i, val ) {
640
			val.nn = i;
638
			val.nn = i;
641
			var nom = {
639
			var nom = {
642
				label : '',
640
				label : '',
643
				value : '',
641
				value : '',
644
				nt : 0,
642
				nt : 0,
645
				nomSel : '',
643
				nomSel : '',
646
				nomSelComplet : '',
644
				nomSelComplet : '',
647
				numNomSel : 0,
645
				numNomSel : 0,
648
				nomRet : '',
646
				nomRet : '',
649
				numNomRet : 0,
647
				numNomRet : 0,
650
				famille : '',
648
				famille : '',
651
				retenu : false
649
				retenu : false
652
			};
650
			};
653
			if ( suggestions.length >= this.autocompletionElementsNbre ) {
651
			if ( suggestions.length >= this.autocompletionElementsNbre ) {
654
				nom.label = '...';
652
				nom.label = '...';
655
				nom.value = $( taxonSelecteur ).val();
653
				nom.value = $( taxonSelecteur ).val();
656
				suggestions.push( nom );
654
				suggestions.push( nom );
657
				return false;
655
				return false;
658
			} else {
656
			} else {
659
				nom.label = val.nom_sci_complet;
657
				nom.label = val.nom_sci_complet;
660
				nom.value = val.nom_sci_complet;
658
				nom.value = val.nom_sci_complet;
661
				nom.nt = val.num_taxonomique;
659
				nom.nt = val.num_taxonomique;
662
				nom.nomSel = val.nom_sci;
660
				nom.nomSel = val.nom_sci;
663
				nom.nomSelComplet = val.nom_sci_complet;
661
				nom.nomSelComplet = val.nom_sci_complet;
664
				nom.numNomSel = val.nn;
662
				nom.numNomSel = val.nn;
665
				nom.nomRet = val.nom_retenu_complet;
663
				nom.nomRet = val.nom_retenu_complet;
666
				nom.numNomRet = val['nom_retenu.id'];
664
				nom.numNomRet = val['nom_retenu.id'];
667
				nom.famille = val.famille;
665
				nom.famille = val.famille;
668
				// Tester dans ce sens, permet de considérer 'absent' comme 'false' => est-ce opportun ?
666
				// Tester dans ce sens, permet de considérer 'absent' comme 'false' => est-ce opportun ?
669
				// en tout cas c'est harmonisé avec le CeL
667
				// en tout cas c'est harmonisé avec le CeL
670
				nom.retenu = ( 'true' == val.retenu );
668
				nom.retenu = ( 'true' == val.retenu );
671
 
669
 
672
				suggestions.push( nom );
670
				suggestions.push( nom );
673
			}
671
			}
674
		});
672
		});
675
	}
673
	}
676
	return suggestions;
674
	return suggestions;
677
};
675
};
678
 
676
 
679
WidgetSaisie.prototype.surAutocompletionTaxon = function( event, ui ) {
677
WidgetSaisie.prototype.surAutocompletionTaxon = function( event, ui ) {
680
	if ( valeurOk( ui ) ) {
678
	if ( valeurOk( ui ) ) {
681
		$( '#taxon' ).val( ui.item.value );
679
		$( '#taxon' ).val( ui.item.value );
682
		$( '#taxon' ).data( 'value', ui.item.value )
680
		$( '#taxon' ).data( 'value', ui.item.value )
683
			.data( 'numNomSel', ui.item.numNomSel )
681
			.data( 'numNomSel', ui.item.numNomSel )
684
			.data( 'nomRet', ui.item.nomRet )
682
			.data( 'nomRet', ui.item.nomRet )
685
			.data( 'numNomRet', ui.item.numNomRet )
683
			.data( 'numNomRet', ui.item.numNomRet )
686
			.data( 'nt', ui.item.nt )
684
			.data( 'nt', ui.item.nt )
687
			.data( 'famille', ui.item.famille );
685
			.data( 'famille', ui.item.famille );
688
		if ( ui.item.retenu ) {
686
		if ( ui.item.retenu ) {
689
			$( '#taxon' ).addClass( 'ns-retenu' );
687
			$( '#taxon' ).addClass( 'ns-retenu' );
690
		} else {
688
		} else {
691
			$( '#taxon' ).removeClass( 'ns-retenu' );
689
			$( '#taxon' ).removeClass( 'ns-retenu' );
692
		}
690
		}
693
 
691
 
694
		// Si l'espèce est mal déterminée la certitude est "à déterminer"
692
		// Si l'espèce est mal déterminée la certitude est "à déterminer"
695
		if( !valeurOk( $( '#taxon' ).data( 'numNomSel' ) ) ) {
693
		if( !valeurOk( $( '#taxon' ).data( 'numNomSel' ) ) ) {
696
			$( '#certitude' ).find( 'option' ).each( function() {
694
			$( '#certitude' ).find( 'option' ).each( function() {
697
				if ( $( this ).hasClass( 'aDeterminer' ) ) {
695
				if ( $( this ).hasClass( 'aDeterminer' ) ) {
698
					$( this ).attr( 'selected', true );
696
					$( this ).attr( 'selected', true );
699
				} else {
697
				} else {
700
					$( this ).attr( 'selected', false );
698
					$( this ).attr( 'selected', false );
701
				}
699
				}
702
			});
700
			});
703
		}
701
		}
704
	}
702
	}
705
	$( '#taxon' ).trigger( 'change' );
703
	$( '#taxon' ).trigger( 'change' );
706
};
704
};
707
 
705
 
708
// Form Validator *************************************************************/
706
// Form Validator *************************************************************/
709
WidgetSaisie.prototype.configurerFormValidator = function() {
707
WidgetSaisie.prototype.configurerFormValidator = function() {
710
	var lthis = this;
708
	var lthis = this;
711
 
709
 
712
	$.validator.addMethod(
710
	$.validator.addMethod(
713
		'dateCel',
711
		'dateCel',
714
		function ( value, element ) {
712
		function ( value, element ) {
715
			return ( valeurOk( value ) && ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) ) );
713
			return ( valeurOk( value ) && ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) ) );
716
		},
714
		},
717
		lthis.msgTraduction( 'date-incomplete' )
715
		lthis.msgTraduction( 'date-incomplete' )
718
	);
716
	);
719
 
717
 
720
	$.validator.addMethod(
718
	$.validator.addMethod(
721
		'userEmailOk',
719
		'userEmailOk',
722
		function ( value, element ) {
720
		function ( value, element ) {
723
			return ( valeurOk( value ) );
721
			return ( valeurOk( value ) );
724
		},
722
		},
725
		''
723
		''
726
	);
724
	);
727
 
725
 
728
	$.validator.addMethod(
726
	$.validator.addMethod(
729
		'minMaxOk',
727
		'minMaxOk',
730
		function ( value, element, param ) {
728
		function ( value, element, param ) {
731
			$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message;
729
			$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message;
732
			return lthis.validerMinMax( element ).cond;
730
			return lthis.validerMinMax( element ).cond;
733
		},
731
		},
734
		$.validator.messages.minMaxOk
732
		$.validator.messages.minMaxOk
735
	);
733
	);
736
 
734
 
737
	$.validator.addMethod(
735
	$.validator.addMethod(
738
		'listFields',
736
		'listFields',
739
		function ( value, element ) {
737
		function ( value, element ) {
740
			return ( valeurOk( value ) );
738
			return ( valeurOk( value ) );
741
		},
739
		},
742
		''
740
		''
743
	);
741
	);
744
 
742
 
745
	$.extend( $.validator.defaults, {
743
	$.extend( $.validator.defaults, {
746
		errorElement: 'span',
744
		errorElement: 'span',
747
		onfocusout: function( element ) {
745
		onfocusout: function( element ) {
748
			if( valeurOk( element.id, false, 'taxon' ) ) {
746
			if( valeurOk( element.id, false, 'taxon' ) ) {
749
				if ( $( element ).valid() ) {
747
				if ( $( element ).valid() ) {
750
					$( element ).closest( '.control-group' ).removeClass( 'error' );
748
					$( element ).closest( '.control-group' ).removeClass( 'error' );
751
				} else {
749
				} else {
752
					$( element ).closest( '.control-group' ).addClass( 'error' );
750
					$( element ).closest( '.control-group' ).addClass( 'error' );
753
				}
751
				}
754
			}
752
			}
755
		},
753
		},
756
		onkeyup : function( element ) {
754
		onkeyup : function( element ) {
757
			if( valeurOk( element.id, false, 'taxon' ) ) {
755
			if( valeurOk( element.id, false, 'taxon' ) ) {
758
				if ( $( element ).valid() ) {
756
				if ( $( element ).valid() ) {
759
					$( element ).closest( '.control-group' ).removeClass( 'error' );
757
					$( element ).closest( '.control-group' ).removeClass( 'error' );
760
				} else {
758
				} else {
761
					$( element ).closest( '.control-group' ).addClass( 'error' );
759
					$( element ).closest( '.control-group' ).addClass( 'error' );
762
				}
760
				}
763
			}
761
			}
764
		},
762
		},
765
		unhighlight: function( element ) {
763
		unhighlight: function( element ) {
766
			if( valeurOk( element.id, false, 'taxon' ) ) {
764
			if( valeurOk( element.id, false, 'taxon' ) ) {
767
				$( element ).closest( '.control-group' ).removeClass( 'error' );
765
				$( element ).closest( '.control-group' ).removeClass( 'error' );
768
			}
766
			}
769
		},
767
		},
770
		highlight: function( element ) {
768
		highlight: function( element ) {
771
			$( element ).closest( '.control-group' ).addClass( 'error' );
769
			$( element ).closest( '.control-group' ).addClass( 'error' );
772
		}
770
		}
773
	});
771
	});
774
};
772
};
775
 
773
 
776
WidgetSaisie.prototype.chpEtendusValidation = function() {
774
WidgetSaisie.prototype.chpEtendusValidation = function() {
777
	var lthis = this;
775
	var lthis = this;
778
	var $thisForm = $( '#form-supp' ),
776
	var $thisForm = $( '#form-supp' ),
779
			elements  =
777
			elements  =
780
				'.checkbox,'+
778
				'.checkbox,'+
781
				'.radio,'+
779
				'.radio,'+
782
				'.checkboxes,'+
780
				'.checkboxes,'+
783
				'.select,'+
781
				'.select,'+
784
				'textarea,'+
782
				'textarea,'+
785
				'input[type=text]:not(.collect-other),'+
783
				'input[type=text]:not(.collect-other),'+
786
				'input[type=email],'+
784
				'input[type=email],'+
787
				'input[type=number],'+
785
				'input[type=number],'+
788
				'input[type=range],'+
786
				'input[type=range],'+
789
				'input[type=date]',
787
				'input[type=date]',
790
			speFields = ['checkbox','radio','checkboxes','select'],
788
			speFields = ['checkbox','radio','checkboxes','select'],
791
			spefieldsCount = speFields.length,
789
			spefieldsCount = speFields.length,
792
			chpSuppValidation = {
790
			chpSuppValidation = {
793
				rules : {},
791
				rules : {},
794
				messages : {},
792
				messages : {},
795
				minmax : []
793
				minmax : []
796
			},
794
			},
797
			errors = {},
795
			errors = {},
798
			namesListFields = [],
796
			namesListFields = [],
799
			picked = '';
797
			picked = '';
800
 
798
 
801
	$( elements, $thisForm ).each( function() {
799
	$( elements, $thisForm ).each( function() {
802
		for( var fieldsClass = 0; spefieldsCount > fieldsClass; fieldsClass++ ) {
800
		for( var fieldsClass = 0; spefieldsCount > fieldsClass; fieldsClass++ ) {
803
			if ( valeurOk( $( this ).attr( 'required' ) ) && $( this ).hasClass( speFields[fieldsClass] ) && !valeurOk( chpSuppValidation.rules[ dataName ] ) ) {
801
			if ( valeurOk( $( this ).attr( 'required' ) ) && $( this ).hasClass( speFields[fieldsClass] ) && !valeurOk( chpSuppValidation.rules[ dataName ] ) ) {
804
				var dataName = $( this ).data( 'name' );
802
				var dataName = $( this ).data( 'name' );
805
 
803
 
806
				namesListFields.push( dataName );
804
				namesListFields.push( dataName );
807
				chpSuppValidation.rules[ dataName ] = { required : true };
805
				chpSuppValidation.rules[ dataName ] = { required : true };
808
 
806
 
809
				if ( valeurOk( $( '.other', $( this ) ) ) ) {
807
				if ( valeurOk( $( '.other', $( this ) ) ) ) {
810
					picked = ( 'select' === speFields[fieldsClass] ) ? ':selected' : ':checked';
808
					picked = ( 'select' === speFields[fieldsClass] ) ? ':selected' : ':checked';
811
					chpSuppValidation.rules[ 'collect-other-' + dataName.replace( '[]', '' ) ] = {
809
					chpSuppValidation.rules[ 'collect-other-' + dataName.replace( '[]', '' ) ] = {
812
						required : '#other-' + dataName.replace( '[]', '' ) + picked,
810
						required : '#other-' + dataName.replace( '[]', '' ) + picked,
813
						minlength: 1
811
						minlength: 1
814
					};
812
					};
815
					chpSuppValidation.messages[ 'collect-other-' + dataName.replace( '[]', '' ) ] = false;
813
					chpSuppValidation.messages[ 'collect-other-' + dataName.replace( '[]', '' ) ] = false;
816
				}
814
				}
817
				chpSuppValidation.rules[ dataName ]['listFields'] = true;
815
				chpSuppValidation.rules[ dataName ]['listFields'] = true;
818
				chpSuppValidation.messages[ dataName ] = 'Ce champ est requis :\nVeuillez choisir une option, ou entrer une valeur autre valide.';
816
				chpSuppValidation.messages[ dataName ] = 'Ce champ est requis :\nVeuillez choisir une option, ou entrer une valeur autre valide.';
819
				errors[dataName] = '.' + speFields[fieldsClass];
817
				errors[dataName] = '.' + speFields[fieldsClass];
820
			}
818
			}
821
		}
819
		}
822
		if ( valeurOk( $( this ).attr( 'name' ) ) && valeurOk ( $( this ).attr( 'required' ) ) && 0 > $.inArray( $( this ).attr( 'name' ) , namesListFields ) ) {
820
		if ( valeurOk( $( this ).attr( 'name' ) ) && valeurOk ( $( this ).attr( 'required' ) ) && 0 > $.inArray( $( this ).attr( 'name' ) , namesListFields ) ) {
823
			chpSuppValidation.rules[ $( this ).attr( 'name' ) ] = { required : true, minlength: 1 };
821
			chpSuppValidation.rules[ $( this ).attr( 'name' ) ] = { required : true, minlength: 1 };
824
			if(
822
			if(
825
					( valeurOk( $( this ).attr( 'type' ), true, 'number' ) || valeurOk( $( this ).attr( 'type' ), true, 'range' ) ) &&
823
					( valeurOk( $( this ).attr( 'type' ), true, 'number' ) || valeurOk( $( this ).attr( 'type' ), true, 'range' ) ) &&
826
					( valeurOk( $( this )[0].min ) || valeurOk( $( this )[0].max ) )
824
					( valeurOk( $( this )[0].min ) || valeurOk( $( this )[0].max ) )
827
				) {
825
				) {
828
				chpSuppValidation.rules[ $( this ).attr('name') ]['minMaxOk'] = true;
826
				chpSuppValidation.rules[ $( this ).attr('name') ]['minMaxOk'] = true;
829
				chpSuppValidation.messages[ $( this ).attr('name') ] = lthis.validerMinMax( $( this )[0] ).message;
827
				chpSuppValidation.messages[ $( this ).attr('name') ] = lthis.validerMinMax( $( this )[0] ).message;
830
			}
828
			}
831
		}
829
		}
832
	});
830
	});
833
	if ( valeurOk( chpSuppValidation.rules ) ) {
831
	if ( valeurOk( chpSuppValidation.rules ) ) {
834
		$.each( chpSuppValidation.rules, function( key ) {
832
		$.each( chpSuppValidation.rules, function( key ) {
835
			if ( !valeurOk( chpSuppValidation.messages[key] ) ) {
833
			if ( !valeurOk( chpSuppValidation.messages[key] ) ) {
836
				chpSuppValidation.messages[key] = 'Ce champ est requis :\nVeuillez entrer une valeur valide.';
834
				chpSuppValidation.messages[key] = 'Ce champ est requis :\nVeuillez entrer une valeur valide.';
837
			}
835
			}
838
		});
836
		});
839
		if ( 0 < Object.keys( errors ).length ) {
837
		if ( 0 < Object.keys( errors ).length ) {
840
			chpSuppValidation['errors'] = errors;
838
			chpSuppValidation['errors'] = errors;
841
		}
839
		}
842
	}
840
	}
843
	return chpSuppValidation;
841
	return chpSuppValidation;
844
};
842
};
845
 
843
 
846
WidgetSaisie.prototype.validerMinMax = function( element ) {
844
WidgetSaisie.prototype.validerMinMax = function( element ) {
847
 
845
 
848
	var mMCond      = new Boolean(),
846
	var mMCond      = new Boolean(),
849
			minCond     = parseFloat( element.value ) >= parseFloat( element.min ),
847
			minCond     = parseFloat( element.value ) >= parseFloat( element.min ),
850
			maxCond     = parseFloat( element.value ) <= parseFloat( element.max ),
848
			maxCond     = parseFloat( element.value ) <= parseFloat( element.max ),
851
			messageMnMx = 'La valeur entrée doit être',
849
			messageMnMx = 'La valeur entrée doit être',
852
			returnMnMx  = { cond : true , message : '' };
850
			returnMnMx  = { cond : true , message : '' };
853
 
851
 
854
	if(
852
	if(
855
			( valeurOk( element.type, true, 'number' ) || valeurOk( element.type, true, 'range' ) ) &&
853
			( valeurOk( element.type, true, 'number' ) || valeurOk( element.type, true, 'range' ) ) &&
856
			( valeurOk( element.min ) || valeurOk( element.max ) )
854
			( valeurOk( element.min ) || valeurOk( element.max ) )
857
		) {
855
		) {
858
		if ( element.min && element.max ) {
856
		if ( element.min && element.max ) {
859
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
857
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
860
			mnMxCond     = ( minCond && maxCond );
858
			mnMxCond     = ( minCond && maxCond );
861
		} else if ( element.min ) {
859
		} else if ( element.min ) {
862
			messageMnMx += ' supérieure à ' + element.min;
860
			messageMnMx += ' supérieure à ' + element.min;
863
			mnMxCond     = minCond;
861
			mnMxCond     = minCond;
864
		} else {
862
		} else {
865
			messageMnMx += ' inférieure à ' + element.max;
863
			messageMnMx += ' inférieure à ' + element.max;
866
			mnMxCond     = maxCond;
864
			mnMxCond     = maxCond;
867
		}
865
		}
868
		returnMnMx.cond    = mnMxCond;
866
		returnMnMx.cond    = mnMxCond;
869
		returnMnMx.message = messageMnMx;
867
		returnMnMx.message = messageMnMx;
870
	}
868
	}
871
	return returnMnMx;
869
	return returnMnMx;
872
 
870
 
873
};
871
};
874
 
872
 
875
 
873
 
876
WidgetSaisie.prototype.definirReglesFormValidator = function() {
874
WidgetSaisie.prototype.definirReglesFormValidator = function() {
877
	var formSuppValidation = this.chpEtendusValidation(),
875
	var formSuppValidation = this.chpEtendusValidation(),
878
		lthis = this;
876
		lthis = this;
879
 
877
 
880
	$( '#form-supp' ).validate({
878
	$( '#form-supp' ).validate({
881
		onclick : function( element ) {
879
		onclick : function( element ) {
882
			if (
880
			if (
883
				(
881
				(
884
					valeurOk( element.type, true, 'checkbox' ) ||
882
					valeurOk( element.type, true, 'checkbox' ) ||
885
					valeurOk( element.type, true, 'radio' )
883
					valeurOk( element.type, true, 'radio' )
886
				) &&
884
				) &&
887
				(
885
				(
888
					!valeurOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':checked' ) ) ||
886
					!valeurOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':checked' ) ) ||
889
					valeurOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':not(.other):checked' ) ) ||
887
					valeurOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':not(.other):checked' ) ) ||
890
					!valeurOk( $( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ) ) ||
888
					!valeurOk( $( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ) ) ||
891
					$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) ||
889
					$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) ||
892
					(
890
					(
893
						$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) &&
891
						$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) &&
894
						$( element ).closest( '.control-group' ).hasClass('error')
892
						$( element ).closest( '.control-group' ).hasClass('error')
895
					)
893
					)
896
				)
894
				)
897
			) {
895
			) {
898
				$( element ).valid();
896
				$( element ).valid();
899
				if ( $( element ).valid() ) {
897
				if ( $( element ).valid() ) {
900
					$( element ).closest( '.control-group' ).removeClass( 'error' );
898
					$( element ).closest( '.control-group' ).removeClass( 'error' );
901
					$( element ).next( $( 'span.error' ) ).remove();
899
					$( element ).next( $( 'span.error' ) ).remove();
902
				} else {
900
				} else {
903
					$( element ).closest( '.control-group' ).addClass( 'error' );
901
					$( element ).closest( '.control-group' ).addClass( 'error' );
904
				}
902
				}
905
			}
903
			}
906
			return false;
904
			return false;
907
		},
905
		},
908
		rules : formSuppValidation.rules,
906
		rules : formSuppValidation.rules,
909
		messages : formSuppValidation.messages,
907
		messages : formSuppValidation.messages,
910
		errorPlacement : function( error , element ) {
908
		errorPlacement : function( error , element ) {
911
			if ( 0 < Object.keys( formSuppValidation.errors ).length ) {
909
			if ( 0 < Object.keys( formSuppValidation.errors ).length ) {
912
				var errorsKeys = Object.keys( formSuppValidation.errors ),
910
				var errorsKeys = Object.keys( formSuppValidation.errors ),
913
						thisKey = '',
911
						thisKey = '',
914
						errorsFlag = true;
912
						errorsFlag = true;
915
				for ( i = 0 ; i < errorsKeys.length ; i++ ) {
913
				for ( i = 0 ; i < errorsKeys.length ; i++ ) {
916
					thisKey = errorsKeys[i];
914
					thisKey = errorsKeys[i];
917
					if( $( element ).attr( 'name' ) === thisKey ) {
915
					if( $( element ).attr( 'name' ) === thisKey ) {
918
						$( formSuppValidation.errors[thisKey] ).append( error );
916
						$( formSuppValidation.errors[thisKey] ).append( error );
919
						errorsFlag = false;
917
						errorsFlag = false;
920
					}
918
					}
921
				}
919
				}
922
				if ( errorsFlag ) {
920
				if ( errorsFlag ) {
923
					error.insertAfter( element );
921
					error.insertAfter( element );
924
				}
922
				}
925
			} else {
923
			} else {
926
				error.insertAfter( element );
924
				error.insertAfter( element );
927
			}
925
			}
928
		}
926
		}
929
	});
927
	});
930
 
928
 
931
	$( '#form-supp .select' ).change( function() {
929
	$( '#form-supp .select' ).change( function() {
932
		$( this ).valid();
930
		$( this ).valid();
933
	});
931
	});
934
 
932
 
935
	$( 'input[type=date]' ).on( 'input', function() {
933
	$( 'input[type=date]' ).on( 'input', function() {
936
		$( this ).valid();
934
		$( this ).valid();
937
	});
935
	});
938
 
936
 
939
	// Validation Taxon si pas de miniature
937
	// Validation Taxon si pas de miniature
940
	$( '#taxon' ).on( 'change', function() {
938
	$( '#taxon' ).on( 'change', function() {
941
		var images = valeurOk( $( '#miniatures .miniature' ) );
939
		var images = valeurOk( $( '#miniatures .miniature' ) );
942
		lthis.validerTaxonImage( valeurOk( $( this ).val() ), images );
940
		lthis.validerTaxonImage( valeurOk( $( this ).val() ), images );
943
	});
941
	});
944
 
942
 
945
	// Validation miniatures avec MutationObserver
943
	// Validation miniatures avec MutationObserver
946
	this.surPresenceAbsenceMiniature();
944
	this.surPresenceAbsenceMiniature();
947
 
945
 
948
	$( '#form-observation' ).validate({
946
	$( '#form-observation' ).validate({
949
		rules : {
947
		rules : {
950
			date_releve : {
948
			date_releve : {
951
				required : true,
949
				required : true,
952
				'dateCel' : true
950
				'dateCel' : true
953
			},
951
			},
954
			latitude : {
952
			latitude : {
955
				required : true,
953
				required : true,
956
				minlength : 1,
954
				minlength : 1,
957
				range : [-90, 90]
955
				range : [-90, 90]
958
			},
956
			},
959
			longitude : {
957
			longitude : {
960
				required : true,
958
				required : true,
961
				minlength : 1,
959
				minlength : 1,
962
				range : [-180, 180]
960
				range : [-180, 180]
963
			}
961
			}
964
		}
962
		}
965
	});
963
	});
966
 
964
 
967
	$( '#form-observateur' ).validate({
965
	$( '#form-observateur' ).validate({
968
		rules : {
966
		rules : {
969
			courriel : {
967
			courriel : {
970
				required : true,
968
				required : true,
971
				email : true,
969
				email : true,
972
				'userEmailOk' : true
970
				'userEmailOk' : true
973
			},
971
			},
974
			courriel_confirmation : {
972
			courriel_confirmation : {
975
				required : true,
973
				required : true,
976
				equalTo : '#courriel'
974
				equalTo : '#courriel'
977
			}
975
			}
978
		}
976
		}
979
	});
977
	});
980
 
978
 
981
	$( '#connexion,#bouton-inscription,#bouton-anonyme' ).click( function( event ) {
979
	$( '#connexion,#bouton-inscription,#bouton-anonyme' ).click( function( event ) {
982
		$( '.nav.control-group' ).removeClass( 'error' );
980
		$( '.nav.control-group' ).removeClass( 'error' );
983
	});
981
	});
984
};
982
};
985
 
983
 
986
WidgetSaisie.prototype.validerTaxonImage = function( taxon = false, images = false ) {
984
WidgetSaisie.prototype.validerTaxonImage = function( taxon = false, images = false ) {
987
	var taxonOuImage = ( images || taxon );
985
	var taxonOuImage = ( images || taxon );
988
	if ( images || taxon ) {
986
	if ( images || taxon ) {
989
		this.masquerPanneau( '#dialogue-taxon-or-image' );
987
		this.masquerPanneau( '#dialogue-taxon-or-image' );
990
		$( '#bloc-taxon' ).removeClass( 'error' )
988
		$( '#bloc-taxon' ).removeClass( 'error' )
991
			.find( 'span.error' ).hide();
989
			.find( 'span.error' ).hide();
992
		$( '#fichier' ).parent( 'label.label-file' ).removeClass( 'error' );
990
		$( '#fichier' ).parent( 'label.label-file' ).removeClass( 'error' );
993
		$( '#photos-conteneur').removeClass( 'error' ).find( 'span.error' ).hide();
991
		$( '#photos-conteneur').removeClass( 'error' ).find( 'span.error' ).hide();
994
	} else {
992
	} else {
995
		this.afficherPanneau( '#dialogue-taxon-or-image' );
993
		this.afficherPanneau( '#dialogue-taxon-or-image' );
996
		$( '#bloc-taxon' ).addClass( 'error' )
994
		$( '#bloc-taxon' ).addClass( 'error' )
997
			.find( 'span.error' ).show();
995
			.find( 'span.error' ).show();
998
		$( '#fichier' ).parent( 'label.label-file' ).addClass( 'error' );
996
		$( '#fichier' ).parent( 'label.label-file' ).addClass( 'error' );
999
		$( '#photos-conteneur').addClass( 'error' ).find( 'span.error' ).show();
997
		$( '#photos-conteneur').addClass( 'error' ).find( 'span.error' ).show();
1000
	}
998
	}
1001
	return ( images || taxon );
999
	return ( images || taxon );
1002
};
1000
};
1003
 
1001
 
1004
WidgetSaisie.prototype.surPresenceAbsenceMiniature = function() {
1002
WidgetSaisie.prototype.surPresenceAbsenceMiniature = function() {
1005
	var lthis = this;
1003
	var lthis = this;
1006
 
1004
 
1007
	// voir : https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/disconnect
1005
	// voir : https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/disconnect
1008
	// Selectionne le noeud dont les mutations seront observées
1006
	// Selectionne le noeud dont les mutations seront observées
1009
	var targetNode = document.getElementById( 'miniatures' );
1007
	var targetNode = document.getElementById( 'miniatures' );
1010
	// Fonction callback à éxécuter quand une mutation est observée
1008
	// Fonction callback à éxécuter quand une mutation est observée
1011
	var callback = function( mutationsList ) {
1009
	var callback = function( mutationsList ) {
1012
		for( var mutation of mutationsList ) {
1010
		for( var mutation of mutationsList ) {
1013
			var taxon = valeurOk( $( '#taxon' ).val() );
1011
			var taxon = valeurOk( $( '#taxon' ).val() );
1014
			images = ( 0 < mutation.target.childElementCount );
1012
			images = ( 0 < mutation.target.childElementCount );
1015
			lthis.validerTaxonImage( taxon, images );
1013
			lthis.validerTaxonImage( taxon, images );
1016
		}
1014
		}
1017
	};
1015
	};
1018
	// Créé une instance de l'observateur lié à la fonction de callback
1016
	// Créé une instance de l'observateur lié à la fonction de callback
1019
	this.observer = new MutationObserver( callback );
1017
	this.observer = new MutationObserver( callback );
1020
	// Commence à observer le noeud cible pour les mutations précédemment configurées
1018
	// Commence à observer le noeud cible pour les mutations précédemment configurées
1021
	this.observer.observe( targetNode, { childList: true } );
1019
	this.observer.observe( targetNode, { childList: true } );
1022
};
1020
};
1023
 
1021
 
1024
WidgetSaisie.prototype.validerFormulaire = function() {
1022
WidgetSaisie.prototype.validerFormulaire = function() {
1025
	var observateur  = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() && $( '#courriel_confirmation' ).valid() )
1023
	var observateur  = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() && $( '#courriel_confirmation' ).valid() )
1026
	var obs          = $( '#form-observation' ).valid();
1024
	var obs          = $( '#form-observation' ).valid();
1027
	var geoloc       = ( valeurOk( $( '#latitude' ).val() ) && valeurOk( $( '#longitude' ).val() ) ) ;
1025
	var geoloc       = ( valeurOk( $( '#latitude' ).val() ) && valeurOk( $( '#longitude' ).val() ) ) ;
1028
	var images       = valeurOk( $( '#miniatures .miniature' ) );
1026
	var images       = valeurOk( $( '#miniatures .miniature' ) );
1029
	var taxon        = valeurOk( $( '#taxon' ).val() );
1027
	var taxon        = valeurOk( $( '#taxon' ).val() );
1030
	// validation et panneau taxon/images
1028
	// validation et panneau taxon/images
1031
	var taxonOuImage = this.validerTaxonImage( taxon, images );
1029
	var taxonOuImage = this.validerTaxonImage( taxon, images );
1032
	// console.log(taxonOuImage);
1030
	// console.log(taxonOuImage);
1033
	var chpsSupp     = new Boolean();
1031
	var chpsSupp     = new Boolean();
1034
	if ( valeurOk( $( '#form-supp' ) ) ) {
1032
	if ( valeurOk( $( '#form-supp' ) ) ) {
1035
		chpsSupp = ( function () {
1033
		chpsSupp = ( function () {
1036
			var otherFlag = $( '#form-supp' ).valid();
1034
			var otherFlag = $( '#form-supp' ).valid();
1037
			if( valeurOk( $( '.other', $( '#form-supp' ) ) ) ) {
1035
			if( valeurOk( $( '.other', $( '#form-supp' ) ) ) ) {
1038
				$( '.other', $( '#form-supp' ) ).each( function() {
1036
				$( '.other', $( '#form-supp' ) ).each( function() {
1039
					var picked = ( $( this ).data( 'element' ) !== 'select' ) ? ':checked' : ':selected';
1037
					var picked = ( $( this ).data( 'element' ) !== 'select' ) ? ':checked' : ':selected';
1040
						if ( $( this ).is( picked ) && valeurOk( $( this ).val(), true, 'other' ) ) {
1038
						if ( $( this ).is( picked ) && valeurOk( $( this ).val(), true, 'other' ) ) {
1041
							otherFlag = false;
1039
							otherFlag = false;
1042
						}
1040
						}
1043
				});
1041
				});
1044
			}
1042
			}
1045
			return otherFlag;
1043
			return otherFlag;
1046
		})();
1044
		})();
1047
	} else {
1045
	} else {
1048
		chpsSupp = true;
1046
		chpsSupp = true;
1049
	}
1047
	}
1050
	// panneau geoloc
1048
	// panneau geoloc
1051
	if ( geoloc ) {
1049
	if ( geoloc ) {
1052
		this.masquerPanneau( '#dialogue-geoloc-ko' );
1050
		this.masquerPanneau( '#dialogue-geoloc-ko' );
1053
		$( '#geoloc-datas' ).closest( '.control-group' ).removeClass( 'error' );
1051
		$( '#geoloc-datas' ).closest( '.control-group' ).removeClass( 'error' );
1054
	} else{
1052
	} else{
1055
		this.afficherPanneau( '#dialogue-geoloc-ko' );
1053
		this.afficherPanneau( '#dialogue-geoloc-ko' );
1056
		$( '#geoloc-datas' ).closest( '.control-group' ).addClass( 'error' );
1054
		$( '#geoloc-datas' ).closest( '.control-group' ).addClass( 'error' );
1057
	}
1055
	}
1058
	// panneau observateur
1056
	// panneau observateur
1059
	if ( observateur ) {
1057
	if ( observateur ) {
1060
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
1058
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
1061
		$( '.nav.control-group' ).removeClass( 'error' );
1059
		$( '.nav.control-group' ).removeClass( 'error' );
1062
	} else {
1060
	} else {
1063
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
1061
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
1064
		$( '.nav.control-group' ).addClass( 'error' );
1062
		$( '.nav.control-group' ).addClass( 'error' );
1065
	}
1063
	}
1066
 
1064
 
1067
	return ( observateur && obs && geoloc && taxonOuImage && chpsSupp );
1065
	return ( observateur && obs && geoloc && taxonOuImage && chpsSupp );
1068
};
1066
};
1069
 
1067
 
1070
// Fichier Images *************************************************************/
1068
// Fichier Images *************************************************************/
1071
/**
1069
/**
1072
 * Affiche la miniature d'une image temporaire (formulaire) qu'on a ajoutée à l'obs
1070
 * Affiche la miniature d'une image temporaire (formulaire) qu'on a ajoutée à l'obs
1073
 */
1071
 */
1074
WidgetSaisie.prototype.afficherMiniature = function( reponse ) {
1072
WidgetSaisie.prototype.afficherMiniature = function( reponse ) {
1075
	if ( this.debug ) {
1073
	if ( this.debug ) {
1076
		var debogage = $( 'debogage', reponse ).text();
1074
		var debogage = $( 'debogage', reponse ).text();
1077
		//console.log( 'Débogage upload : '+debogage);
1075
		//console.log( 'Débogage upload : '+debogage);
1078
	}
1076
	}
1079
	var message = $( 'message', reponse ).text();
1077
	var message = $( 'message', reponse ).text();
1080
	if ( valeurOk( message ) ) {
1078
	if ( valeurOk( message ) ) {
1081
		$( '#miniature-msg' ).append( message );
1079
		$( '#miniature-msg' ).append( message );
1082
	} else {
1080
	} else {
1083
		$( '#miniatures' ).append( this.creerWidgetMiniature( reponse ) );
1081
		$( '#miniatures' ).append( this.creerWidgetMiniature( reponse ) );
1084
	}
1082
	}
1085
	$( '#ajouter-obs' ).removeAttr( 'disabled' );
1083
	$( '#ajouter-obs' ).removeAttr( 'disabled' );
1086
};
1084
};
1087
 
1085
 
1088
/**
1086
/**
1089
 * Crée la miniature d'une image temporaire (formulaire), avec le bouton pour l'effacer
1087
 * Crée la miniature d'une image temporaire (formulaire), avec le bouton pour l'effacer
1090
 */
1088
 */
1091
WidgetSaisie.prototype.creerWidgetMiniature = function( reponse ) {
1089
WidgetSaisie.prototype.creerWidgetMiniature = function( reponse ) {
1092
	var miniatureUrl = $( 'miniature-url', reponse ).text();
1090
	var miniatureUrl = $( 'miniature-url', reponse ).text();
1093
	var imgNom = $( 'image-nom', reponse ).text();
1091
	var imgNom = $( 'image-nom', reponse ).text();
1094
	var html =
1092
	var html =
1095
		'<div class="miniature mb-3 mr-3">'+
1093
		'<div class="miniature mb-3 mr-3">'+
1096
			'<img class="miniature-img" class="miniature img-rounded" alt="' + imgNom + '" src="' + miniatureUrl + '"/>'+
1094
			'<img class="miniature-img" class="miniature img-rounded" alt="' + imgNom + '" src="' + miniatureUrl + '"/>'+
1097
			'<a class="effacer-miniature"><i class="far fa-trash-alt"></i></a>'+
1095
			'<a class="effacer-miniature"><i class="far fa-trash-alt"></i></a>'+
1098
		'</div>';
1096
		'</div>';
1099
	return html;
1097
	return html;
1100
};
1098
};
1101
 
1099
 
1102
/**
1100
/**
1103
 * Retourne true si l'extension de l'image 'nom' est .jpg ou .jpeg
1101
 * Retourne true si l'extension de l'image 'nom' est .jpg ou .jpeg
1104
 */
1102
 */
1105
WidgetSaisie.prototype.verifierFormat = function( nom ) {
1103
WidgetSaisie.prototype.verifierFormat = function( nom ) {
1106
	var parts = nom.split( '.' );
1104
	var parts = nom.split( '.' );
1107
	extension = parts[ parts.length - 1 ];
1105
	extension = parts[ parts.length - 1 ];
1108
	return ( 'jpeg' === extension.toLowerCase() || 'jpg' === extension.toLowerCase() );
1106
	return ( 'jpeg' === extension.toLowerCase() || 'jpg' === extension.toLowerCase() );
1109
};
1107
};
1110
 
1108
 
1111
/**
1109
/**
1112
 * Efface une miniature (formulaire)
1110
 * Efface une miniature (formulaire)
1113
 */
1111
 */
1114
WidgetSaisie.prototype.supprimerMiniature = function( miniature ) {
1112
WidgetSaisie.prototype.supprimerMiniature = function( miniature ) {
1115
	miniature.parents( '.miniature' ).remove();
1113
	miniature.parents( '.miniature' ).remove();
1116
};
1114
};
1117
 
1115
 
1118
// Referentiel ****************************************************************/
1116
// Referentiel ****************************************************************/
1119
// N'est pas utilisé en cas de taxon-liste
1117
// N'est pas utilisé en cas de taxon-liste
1120
WidgetSaisie.prototype.surChangementReferentiel = function() {
1118
WidgetSaisie.prototype.surChangementReferentiel = function() {
1121
	this.nomSciReferentiel = $( '#referentiel' ).val();
1119
	this.nomSciReferentiel = $( '#referentiel' ).val();
1122
	//réinitialise taxon.val
1120
	//réinitialise taxon.val
1123
	$( '#taxon' ).val( '' );
1121
	$( '#taxon' ).val( '' );
1124
	$( '#taxon' ).data( 'numNomSel', '' );
1122
	$( '#taxon' ).data( 'numNomSel', '' );
1125
	// this.initialiserAutocompleteCommune();
1123
	// this.initialiserAutocompleteCommune();
1126
	// this.initialiserGoogleMap( false );
1124
	// this.initialiserGoogleMap( false );
1127
};
1125
};
1128
 
1126
 
1129
// Ajouter Obs ****************************************************************/
1127
// Ajouter Obs ****************************************************************/
1130
/**
1128
/**
1131
 * Ajoute une observation saisie dans le formulaire à la liste des observations à transmettre
1129
 * Ajoute une observation saisie dans le formulaire à la liste des observations à transmettre
1132
 */
1130
 */
1133
WidgetSaisie.prototype.ajouterObs = function() {
1131
WidgetSaisie.prototype.ajouterObs = function() {
1134
	// Fermeture automatique des dialogue de transmission de données
1132
	// Fermeture automatique des dialogue de transmission de données
1135
	// @WARNING TEST
1133
	// @WARNING TEST
1136
	$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
1134
	$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
1137
	$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1135
	$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1138
 
1136
 
1139
	if ( this.validerFormulaire() ) {
1137
	if ( this.validerFormulaire() ) {
1140
		this.masquerPanneau( '#dialogue-form-invalide' );
1138
		this.masquerPanneau( '#dialogue-form-invalide' );
1141
		this.obsNbre = this.obsNbre + 1;
1139
		this.obsNbre = this.obsNbre + 1;
1142
		$( '.obs-nbre' ).text( this.obsNbre );
1140
		$( '.obs-nbre' ).text( this.obsNbre );
1143
		$( '.obs-nbre' ).triggerHandler( 'changement' );
1141
		$( '.obs-nbre' ).triggerHandler( 'changement' );
1144
		this.afficherObs();
1142
		this.afficherObs();
1145
		this.stockerObsData();
1143
		this.stockerObsData();
1146
		this.supprimerMiniatures();
1144
		this.supprimerMiniatures();
1147
		if( !this.especeImposee ) {
1145
		if( !this.especeImposee ) {
1148
			$( '#taxon' ).val( '' );
1146
			$( '#taxon' ).val( '' );
1149
			$( '#taxon' ).data( 'numNomSel', '' )
1147
			$( '#taxon' ).data( 'numNomSel', '' )
1150
				.data( 'nomRet','' )
1148
				.data( 'nomRet','' )
1151
				.data( 'numNomRet', '' )
1149
				.data( 'numNomRet', '' )
1152
				.data( 'nt', '' )
1150
				.data( 'nt', '' )
1153
				.data( 'famille', '' );
1151
				.data( 'famille', '' );
1154
			if( this.isTaxonListe ) {
1152
			if( this.isTaxonListe ) {
1155
				$( '#taxon-liste' ).find( 'option' ).each( function() {
1153
				$( '#taxon-liste' ).find( 'option' ).each( function() {
1156
					if ( $( this ).hasClass( 'choisir' ) ) {
1154
					if ( $( this ).hasClass( 'choisir' ) ) {
1157
						$( this ).attr( 'selected', true );
1155
						$( this ).attr( 'selected', true );
1158
					} else {
1156
					} else {
1159
						$( this ).attr( 'selected', false );
1157
						$( this ).attr( 'selected', false );
1160
					}
1158
					}
1161
				});
1159
				});
1162
				$( '#taxon-input-groupe' ).addClass( 'hidden' );
1160
				$( '#taxon-input-groupe' ).addClass( 'hidden' );
1163
				$('#taxon-autre').val('');
1161
				$('#taxon-autre').val('');
1164
			}
1162
			}
1165
		}
1163
		}
1166
		if ( valeurOk( $( '#form-supp' ) ) ) {
1164
		if ( valeurOk( $( '#form-supp' ) ) ) {
1167
			$( '#form-supp' ).validate().resetForm();
1165
			$( '#form-supp' ).validate().resetForm();
1168
			// if ( valeurOk( $( '#form-supp' ) ) ) {
1166
			// if ( valeurOk( $( '#form-supp' ) ) ) {
1169
		}
1167
		}
1170
		$( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre );
1168
		$( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre );
1171
		$( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' ' + this.msgTraduction( 'observations-transmises' ) );
1169
		$( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' ' + this.msgTraduction( 'observations-transmises' ) );
1172
	} else {
1170
	} else {
1173
		this.afficherPanneau( '#dialogue-form-invalide' );
1171
		this.afficherPanneau( '#dialogue-form-invalide' );
1174
	}
1172
	}
1175
};
1173
};
1176
 
1174
 
1177
/**
1175
/**
1178
 * Affiche une observation dans la liste des observations à transmettre
1176
 * Affiche une observation dans la liste des observations à transmettre
1179
 */
1177
 */
1180
WidgetSaisie.prototype.afficherObs = function() {
1178
WidgetSaisie.prototype.afficherObs = function() {
1181
 
1179
 
1182
	var numNomSel = $( '#taxon' ).data( 'numNomSel' ),
1180
	var numNomSel = $( '#taxon' ).data( 'numNomSel' ),
1183
			taxon = $( '#taxon' ).val(),
1181
			taxon = $( '#taxon' ).val(),
1184
			referentiel = '',
1182
			referentiel = '',
1185
			commune = '',
1183
			commune = '',
1186
			inseeLatitudeLongitude = '',
1184
			inseeLatitudeLongitude = '',
1187
			lieudit = '',
1185
			lieudit = '',
1188
			station = '',
1186
			station = '',
1189
			milieu = '',
1187
			milieu = '',
1190
			commentaires = '';
1188
			commentaires = '';
1191
 
1189
 
1192
	if ( valeurOk( numNomSel ) ) {
1190
	if ( valeurOk( numNomSel ) ) {
1193
		referentiel = '<span class="referentiel-obs">' + '[' + this.nomSciReferentiel + ']' + '</span>';
1191
		referentiel = '<span class="referentiel-obs">' + '[' + this.nomSciReferentiel + ']' + '</span>';
1194
	}
1192
	}
1195
	if ( valeurOk( $( '#commune-nom' ).val() ) ) {
1193
	if ( valeurOk( $( '#commune-nom' ).val() ) ) {
1196
		commune = ' '  + this.msgTraduction( 'lieu-obs' ) + ' <span class="commune">' + $( '#commune-nom' ).val() + '</span> ';
1194
		commune = ' '  + this.msgTraduction( 'lieu-obs' ) + ' <span class="commune">' + $( '#commune-nom' ).val() + '</span> ';
1197
	}
1195
	}
1198
	if ( valeurOk( $( '#commune-insee' ).val() ) &&  valeurOk( $( '#latitude' ).val() ) && valeurOk( $( '#longitude' ).val() ) ) {
1196
	if ( valeurOk( $( '#commune-insee' ).val() ) &&  valeurOk( $( '#latitude' ).val() ) && valeurOk( $( '#longitude' ).val() ) ) {
1199
		inseeLatitudeLongitude = '(INSEE Commune:' + $('#commune-insee').val() + ') [' + $( '#latitude' ).val() + ' / ' + $( '#longitude' ).val() + ']';
1197
		inseeLatitudeLongitude = '(INSEE Commune:' + $('#commune-insee').val() + ') [' + $( '#latitude' ).val() + ' / ' + $( '#longitude' ).val() + ']';
1200
	}
1198
	}
1201
	if ( valeurOk( $( '#lieudit' ).val() ) ) {
1199
	if ( valeurOk( $( '#lieudit' ).val() ) ) {
1202
		lieudit = '<span>' + this.msgTraduction( 'lieu-dit' ) + ' :</span> ' + $( '#lieudit' ).val() + ' ';
1200
		lieudit = '<span>' + this.msgTraduction( 'lieu-dit' ) + ' :</span> ' + $( '#lieudit' ).val() + ' ';
1203
	}
1201
	}
1204
	if ( valeurOk( $( '#station' ).val() ) ) {
1202
	if ( valeurOk( $( '#station' ).val() ) ) {
1205
		station = '<span>' + this.msgTraduction( 'station' ) + ' :</span> ' + $( '#station' ).val() + ' ';
1203
		station = '<span>' + this.msgTraduction( 'station' ) + ' :</span> ' + $( '#station' ).val() + ' ';
1206
	}
1204
	}
1207
	if ( valeurOk( $( '#milieu' ).val() ) ) {
1205
	if ( valeurOk( $( '#milieu' ).val() ) ) {
1208
		milieu = '<span>' + this.msgTraduction( 'milieu' ) + ' :</span> ' + $( '#milieu' ).val() + ' ';
1206
		milieu = '<span>' + this.msgTraduction( 'milieu' ) + ' :</span> ' + $( '#milieu' ).val() + ' ';
1209
	}
1207
	}
1210
	if ( valeurOk( $( '#notes' ).val() ) ) {
1208
	if ( valeurOk( $( '#notes' ).val() ) ) {
1211
		commentaires = this.msgTraduction( 'commentaires' ) + ' : <span class="discretion">' + $( '#notes' ).val() + '</span>' + ' ';
1209
		commentaires = this.msgTraduction( 'commentaires' ) + ' : <span class="discretion">' + $( '#notes' ).val() + '</span>' + ' ';
1212
	}
1210
	}
1213
 
1211
 
1214
	var responsivDiff1 = '',
1212
	var responsivDiff1 = '',
1215
			responsivDiff2 = '',
1213
			responsivDiff2 = '',
1216
			responsivDiff3 = '',
1214
			responsivDiff3 = '',
1217
			responsivDiff4 = '',
1215
			responsivDiff4 = '',
1218
			responsivDiff5 = '',
1216
			responsivDiff5 = '',
1219
			responsivDiff6 = '';
1217
			responsivDiff6 = '';
1220
	if ( window.matchMedia( '(min-width: 576px)' ).matches ) {
1218
	if ( window.matchMedia( '(min-width: 576px)' ).matches ) {
1221
		/* La largeur minimum de l'affichage est 600 px inclus */
1219
		/* La largeur minimum de l'affichage est 600 px inclus */
1222
		responsivDiff1 = ' droite';
1220
		responsivDiff1 = ' droite';
1223
		responsivDiff2 = '<div></div>';
1221
		responsivDiff2 = '<div></div>';
1224
		responsivDiff3 = '<div class="row">';
1222
		responsivDiff3 = '<div class="row">';
1225
		responsivDiff4 = ' col-md-2 col-sm-4';
1223
		responsivDiff4 = ' col-md-2 col-sm-4';
1226
		responsivDiff5 = ' class="col-md-9 col-sm-7"';
1224
		responsivDiff5 = ' class="col-md-9 col-sm-7"';
1227
		responsivDiff6 = '</div>';
1225
		responsivDiff6 = '</div>';
1228
	}
1226
	}
1229
 
1227
 
1230
 
1228
 
1231
		$( '#liste-obs' ).prepend(
1229
		$( '#liste-obs' ).prepend(
1232
			'<div id="obs' + this.obsNbre + '" class="obs obs' + this.obsNbre + ' mb-2">'+
1230
			'<div id="obs' + this.obsNbre + '" class="obs obs' + this.obsNbre + ' mb-2">'+
1233
 
1231
 
1234
				'<div '+
1232
				'<div '+
1235
					'class="obs-action" '+
1233
					'class="obs-action" '+
1236
					'title="' + this.msgTraduction( 'supprimer-observation-liste' ) + '"'+
1234
					'title="' + this.msgTraduction( 'supprimer-observation-liste' ) + '"'+
1237
				'>'+
1235
				'>'+
1238
					'<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ this.obsNbre + '" title="' + this.msgTraduction( 'obs-numero' ) + this.obsNbre + '">'+
1236
					'<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ this.obsNbre + '" title="' + this.msgTraduction( 'obs-numero' ) + this.obsNbre + '">'+
1239
					'<i class="far fa-trash-alt"></i>'+
1237
					'<i class="far fa-trash-alt"></i>'+
1240
					'</button>'+
1238
					'</button>'+
1241
					responsivDiff2 +
1239
					responsivDiff2 +
1242
				'</div> '+
1240
				'</div> '+
1243
 
1241
 
1244
				responsivDiff3 +
1242
				responsivDiff3 +
1245
					'<div class="thumbnail' + responsivDiff4 + '">'+
1243
					'<div class="thumbnail' + responsivDiff4 + '">'+
1246
						this.ajouterImgMiniatureAuTransfert()+
1244
						this.ajouterImgMiniatureAuTransfert()+
1247
					'</div>'+
1245
					'</div>'+
1248
					'<div' + responsivDiff5 + '>'+
1246
					'<div' + responsivDiff5 + '>'+
1249
						'<ul class="unstyled">'+
1247
						'<ul class="unstyled">'+
1250
							'<li>'+
1248
							'<li>'+
1251
								'<span class="nom-sci">' + taxon + '</span> '+
1249
								'<span class="nom-sci">' + taxon + '</span> '+
1252
								this.ajouterNumNomSel( numNomSel ) +
1250
								this.ajouterNumNomSel( numNomSel ) +
1253
								referentiel +
1251
								referentiel +
1254
								commune +
1252
								commune +
1255
								inseeLatitudeLongitude +
1253
								inseeLatitudeLongitude +
1256
								' ' + this.msgTraduction( 'obs-le' ) + ' ' +
1254
								' ' + this.msgTraduction( 'obs-le' ) + ' ' +
1257
								'<span class="date">' + this.fournirDate( $( '#date_releve' ).val() ) + '</span>'+
1255
								'<span class="date">' + this.fournirDate( $( '#date_releve' ).val() ) + '</span>'+
1258
							'</li>'+
1256
							'</li>'+
1259
							'<li>'+
1257
							'<li>'+
1260
								lieudit +
1258
								lieudit +
1261
								station +
1259
								station +
1262
								milieu +
1260
								milieu +
1263
							'</li>'+
1261
							'</li>'+
1264
							'<li>'+
1262
							'<li>'+
1265
								commentaires +
1263
								commentaires +
1266
							'</li>'+
1264
							'</li>'+
1267
						'</ul>'+
1265
						'</ul>'+
1268
					'</div>'+
1266
					'</div>'+
1269
				responsivDiff6+
1267
				responsivDiff6+
1270
			'</div>'
1268
			'</div>'
1271
		);
1269
		);
1272
 
1270
 
1273
	$( '#zone-liste-obs' ).removeClass( 'hidden' );
1271
	$( '#zone-liste-obs' ).removeClass( 'hidden' );
1274
};
1272
};
1275
 
1273
 
1276
/**
1274
/**
1277
 * Ajoute une boîte de miniatures avec défilement des images,
1275
 * Ajoute une boîte de miniatures avec défilement des images,
1278
 * pour une obs de la liste des obs à transmettre
1276
 * pour une obs de la liste des obs à transmettre
1279
 */
1277
 */
1280
WidgetSaisie.prototype.ajouterImgMiniatureAuTransfert = function() {
1278
WidgetSaisie.prototype.ajouterImgMiniatureAuTransfert = function() {
1281
	var html        =
1279
	var html        =
1282
				'<div class="defilement-miniatures">'+
1280
				'<div class="defilement-miniatures">'+
1283
					'<figure class="centre">'+
1281
					'<figure class="centre">'+
1284
						'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
1282
						'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
1285
					'</figure>'+
1283
					'</figure>'+
1286
				'</div>',
1284
				'</div>',
1287
			miniatures   = '',
1285
			miniatures   = '',
1288
			premiere     = true,
1286
			premiere     = true,
1289
			centre       = '';
1287
			centre       = '';
1290
			defilVisible = '';
1288
			defilVisible = '';
1291
 
1289
 
1292
	if ( valeurOk( $( '#miniatures img' ) ) ) {
1290
	if ( valeurOk( $( '#miniatures img' ) ) ) {
1293
		$( '#miniatures img' ).each( function() {
1291
		$( '#miniatures img' ).each( function() {
1294
			var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
1292
			var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
1295
			premiere = false;
1293
			premiere = false;
1296
 
1294
 
1297
			var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
1295
			var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
1298
					src        = $( this ).attr( 'src' ),
1296
					src        = $( this ).attr( 'src' ),
1299
					alt        = $( this ).attr( 'alt' ),
1297
					alt        = $( this ).attr( 'alt' ),
1300
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1298
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1301
 
1299
 
1302
			miniatures += miniature;
1300
			miniatures += miniature;
1303
		});
1301
		});
1304
		if ( 1 === $( '#miniatures img' ).length ) {
1302
		if ( 1 === $( '#miniatures img' ).length ) {
1305
			centre       = 'centre';
1303
			centre       = 'centre';
1306
			defilVisible = ' defilement-miniatures-cache';
1304
			defilVisible = ' defilement-miniatures-cache';
1307
		}
1305
		}
1308
		html             =
1306
		html             =
1309
			'<div class="defilement-miniatures">'+
1307
			'<div class="defilement-miniatures">'+
1310
				'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
1308
				'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
1311
				'<figure class="' + centre + '">'+
1309
				'<figure class="' + centre + '">'+
1312
					miniatures+
1310
					miniatures+
1313
				'</figure>'+
1311
				'</figure>'+
1314
				'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
1312
				'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
1315
			'</div>';
1313
			'</div>';
1316
	}
1314
	}
1317
	return html;
1315
	return html;
1318
};
1316
};
1319
 
1317
 
1320
WidgetSaisie.prototype.fournirDate = function( dateObs ) {
1318
WidgetSaisie.prototype.fournirDate = function( dateObs ) {
1321
	if ( /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/.test( dateObs ) ) {
1319
	if ( /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/.test( dateObs ) ) {
1322
		return dateObs;
1320
		return dateObs;
1323
	} else if ( /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test( dateObs ) ) {
1321
	} else if ( /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test( dateObs ) ) {
1324
		var dateArray = dateObs.split( '-' );
1322
		var dateArray = dateObs.split( '-' );
1325
		return dateArray[2] + '/' + dateArray[1] + '/' + dateArray[0]
1323
		return dateArray[2] + '/' + dateArray[1] + '/' + dateArray[0]
1326
	} else {
1324
	} else {
1327
		console.log( 'erreur date : ' + dateObs )
1325
		console.log( 'erreur date : ' + dateObs )
1328
	}
1326
	}
1329
}
1327
}
1330
 
1328
 
1331
WidgetSaisie.prototype.ajouterNumNomSel = function( numNomSel ) {
1329
WidgetSaisie.prototype.ajouterNumNomSel = function( numNomSel ) {
1332
	var nn = '<span class="nn">[nn' + numNomSel + ']</span>';
1330
	var nn = '<span class="nn">[nn' + numNomSel + ']</span>';
1333
	if ( !valeurOk( numNomSel ) ) {
1331
	if ( !valeurOk( numNomSel ) ) {
1334
		nn = '<span class="alert-error">[' + this.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
1332
		nn = '<span class="alert-error">[' + this.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
1335
	}
1333
	}
1336
	return nn;
1334
	return nn;
1337
};
1335
};
1338
 
1336
 
1339
 
1337
 
1340
WidgetSaisie.prototype.stockerObsData = function() {
1338
WidgetSaisie.prototype.stockerObsData = function() {
1341
	var lthis = this;
1339
	var lthis = this;
1342
 
1340
 
1343
	var numNomSel   = $( '#taxon' ).data( 'numNomSel' ),
1341
	var numNomSel   = $( '#taxon' ).data( 'numNomSel' ),
1344
			nomSel      = $( '#taxon' ).val(),
1342
			nomSel      = $( '#taxon' ).val(),
1345
			nomRet      = $( '#taxon' ).data( 'nomRet' ),
1343
			nomRet      = $( '#taxon' ).data( 'nomRet' ),
1346
			numNomRet   = $( '#taxon' ).data( 'numNomRet' ),
1344
			numNomRet   = $( '#taxon' ).data( 'numNomRet' ),
1347
			numTaxon    = $( '#taxon' ).data( 'nt' ),
1345
			numTaxon    = $( '#taxon' ).data( 'nt' ),
1348
			famille     = $( '#taxon' ).data( 'famille' ),
1346
			famille     = $( '#taxon' ).data( 'famille' ),
1349
			referentiel = ( !valeurOk( numNomSel ) ) ? 'autre' : this.nomSciReferentiel;
1347
			referentiel = ( !valeurOk( numNomSel ) ) ? 'autre' : this.nomSciReferentiel;
1350
 
1348
 
1351
	$( '#liste-obs' ).data( 'obsId' + this.obsNbre, {
1349
	$( '#liste-obs' ).data( 'obsId' + this.obsNbre, {
1352
		'num_nom_sel'        : numNomSel,
1350
		'num_nom_sel'        : numNomSel,
1353
		'nom_sel'            : nomSel,
1351
		'nom_sel'            : nomSel,
1354
		'nom_ret'            : nomRet,
1352
		'nom_ret'            : nomRet,
1355
		'num_nom_ret'        : numNomRet,
1353
		'num_nom_ret'        : numNomRet,
1356
		'num_taxon'          : numTaxon,
1354
		'num_taxon'          : numTaxon,
1357
		'famille'            : famille,
1355
		'famille'            : famille,
1358
		'referentiel'        : referentiel,
1356
		'referentiel'        : referentiel,
1359
		'certitude'          : $( '#certitude' ).val(),
1357
		'certitude'          : $( '#certitude' ).val(),
1360
		'date'               : lthis.fournirDate( $( '#date_releve' ).val() ),
1358
		'date'               : lthis.fournirDate( $( '#date_releve' ).val() ),
1361
		'notes'              : $( '#notes' ).val().trim(),
1359
		'notes'              : $( '#notes' ).val().trim(),
1362
		'pays'               : $( '#pays' ).val(),
1360
		'pays'               : $( '#pays' ).val(),
1363
		'commune_nom'        : $( '#commune-nom' ).val(),
1361
		'commune_nom'        : $( '#commune-nom' ).val(),
1364
		'commune_code_insee' : $( '#commune-insee' ).val(),
1362
		'commune_code_insee' : $( '#commune-insee' ).val(),
1365
		'latitude'           : $( '#latitude' ).val(),
1363
		'latitude'           : $( '#latitude' ).val(),
1366
		'longitude'          : $( '#longitude' ).val(),
1364
		'longitude'          : $( '#longitude' ).val(),
1367
		'altitude'           : $( '#altitude' ).val(),
1365
		'altitude'           : $( '#altitude' ).val(),
1368
// début valeurs pour test:
1366
// début valeurs pour test:
1369
		// 'commune_nom'        : 'Montpellier',
1367
		// 'commune_nom'        : 'Montpellier',
1370
		// 'commune_code_insee' : '34172',
1368
		// 'commune_code_insee' : '34172',
1371
		// 'latitude'           : '43.608320',
1369
		// 'latitude'           : '43.608320',
1372
		// 'longitude'          : '3.880196',
1370
		// 'longitude'          : '3.880196',
1373
		// 'altitude'           : '0',
1371
		// 'altitude'           : '0',
1374
//fin valeurs pour test
1372
//fin valeurs pour test
1375
		'lieudit'            : $( '#lieudit' ).val(),
1373
		'lieudit'            : $( '#lieudit' ).val(),
1376
		'station'            : $( '#station' ).val(),
1374
		'station'            : $( '#station' ).val(),
1377
		'milieu'             : $( '#milieu' ).val(),
1375
		'milieu'             : $( '#milieu' ).val(),
1378
		//Ajout des champs images
1376
		//Ajout des champs images
1379
		'image_nom'          : lthis.getNomsImgsOriginales(),
1377
		'image_nom'          : lthis.getNomsImgsOriginales(),
1380
		'image_b64'          : lthis.getB64ImgsOriginales(),
1378
		'image_b64'          : lthis.getB64ImgsOriginales(),
1381
		// Ajout des champs étendus de l'obs
1379
		// Ajout des champs étendus de l'obs
1382
		'obs_etendue'        : lthis.getObsChpEtendus()
1380
		'obs_etendue'        : lthis.getObsChpEtendus()
1383
	});
1381
	});
1384
};
1382
};
1385
 
1383
 
1386
WidgetSaisie.prototype.getNomsImgsOriginales = function() {
1384
WidgetSaisie.prototype.getNomsImgsOriginales = function() {
1387
	var noms = new Array();
1385
	var noms = new Array();
1388
	$( '.miniature-img' ).each( function() {
1386
	$( '.miniature-img' ).each( function() {
1389
		noms.push( $( this ).attr( 'alt' ) );
1387
		noms.push( $( this ).attr( 'alt' ) );
1390
	});
1388
	});
1391
	return noms;
1389
	return noms;
1392
};
1390
};
1393
 
1391
 
1394
WidgetSaisie.prototype.getB64ImgsOriginales = function() {
1392
WidgetSaisie.prototype.getB64ImgsOriginales = function() {
1395
	var b64 = new Array();
1393
	var b64 = new Array();
1396
	$( '.miniature-img' ).each( function() {
1394
	$( '.miniature-img' ).each( function() {
1397
		if ( $( this ).hasClass( 'b64' ) ) {
1395
		if ( $( this ).hasClass( 'b64' ) ) {
1398
			b64.push( $( this ).attr( 'src' ) );
1396
			b64.push( $( this ).attr( 'src' ) );
1399
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
1397
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
1400
			b64.push( $( this ).data( 'b64' ) );
1398
			b64.push( $( this ).data( 'b64' ) );
1401
		}
1399
		}
1402
	});
1400
	});
1403
	return b64;
1401
	return b64;
1404
};
1402
};
1405
 
1403
 
1406
/**
1404
/**
1407
 * Retourne un Array contenant les valeurs des champs étendus
1405
 * Retourne un Array contenant les valeurs des champs étendus
1408
 */
1406
 */
1409
WidgetSaisie.prototype.getObsChpEtendus = function() {
1407
WidgetSaisie.prototype.getObsChpEtendus = function() {
1410
	var champs    = new Array(),
1408
	var champs    = new Array(),
1411
			$thisForm = $( '#form-supp' ),
1409
			$thisForm = $( '#form-supp' ),
1412
			elements  =
1410
			elements  =
1413
				'input[type=text]:not(.collect-other),'+
1411
				'input[type=text]:not(.collect-other),'+
1414
				'input[type=checkbox]:checked,'+
1412
				'input[type=checkbox]:checked,'+
1415
				'input[type=radio]:checked,'+
1413
				'input[type=radio]:checked,'+
1416
				'input[type=email],'+
1414
				'input[type=email],'+
1417
				'input[type=number],'+
1415
				'input[type=number],'+
1418
				'input[type=range],'+
1416
				'input[type=range],'+
1419
				'input[type=date],'+
1417
				'input[type=date],'+
1420
				'textarea,'+
1418
				'textarea,'+
1421
				'.select',
1419
				'.select',
1422
			retour    = new Array();
1420
			retour    = new Array();
1423
 
1421
 
1424
	$( elements, $thisForm ).each( function() {
1422
	$( elements, $thisForm ).each( function() {
1425
		if ( valeurOk( $( this ).val() ) && ( valeurOk( $( this ).attr( 'name' ) ) || valeurOk( $( this ).data( 'name' ) ) ) ) {
1423
		if ( valeurOk( $( this ).val() ) && ( valeurOk( $( this ).attr( 'name' ) ) || valeurOk( $( this ).data( 'name' ) ) ) ) {
1426
			var valeur = $( this ).val(),
1424
			var valeur = $( this ).val(),
1427
					cle    = ( valeurOk( $( this ).attr( 'name' ) ) ) ? $( this ).attr( 'name' ) : $( this ).data( 'name' );
1425
					cle    = ( valeurOk( $( this ).attr( 'name' ) ) ) ? $( this ).attr( 'name' ) : $( this ).data( 'name' );
1428
			if ( cle in champs ) {
1426
			if ( cle in champs ) {
1429
				champs[cle] += ';' + valeur;
1427
				champs[cle] += ';' + valeur;
1430
			} else {
1428
			} else {
1431
				champs[cle] = valeur;
1429
				champs[cle] = valeur;
1432
			}
1430
			}
1433
		}
1431
		}
1434
	});
1432
	});
1435
	for( var key in champs ) {
1433
	for( var key in champs ) {
1436
		retour.push({ 'cle' : key , 'valeur' : champs[key] });
1434
		retour.push({ 'cle' : key , 'valeur' : champs[key] });
1437
	};
1435
	};
1438
	return retour;
1436
	return retour;
1439
};
1437
};
1440
 
1438
 
1441
/**
1439
/**
1442
 * Efface toutes les miniatures (formulaire)
1440
 * Efface toutes les miniatures (formulaire)
1443
 */
1441
 */
1444
WidgetSaisie.prototype.supprimerMiniatures = function() {
1442
WidgetSaisie.prototype.supprimerMiniatures = function() {
1445
	// Déconnection MutationObserver miniatures
1443
	// Déconnection MutationObserver miniatures
1446
	// Sinon on a une erreur avant la création d'une nouvelle obs
1444
	// Sinon on a une erreur avant la création d'une nouvelle obs
1447
	this.observer.disconnect();
1445
	this.observer.disconnect();
1448
	$( '#miniatures' ).empty();
1446
	$( '#miniatures' ).empty();
1449
	// Validation miniatures reprend à 0 pour une nouvelle obs
1447
	// Validation miniatures reprend à 0 pour une nouvelle obs
1450
	this.surPresenceAbsenceMiniature();
1448
	this.surPresenceAbsenceMiniature();
1451
	$( '#miniature-msg' ).empty();
1449
	$( '#miniature-msg' ).empty();
1452
};
1450
};
1453
 
1451
 
1454
WidgetSaisie.prototype.surChangementNbreObs = function() {
1452
WidgetSaisie.prototype.surChangementNbreObs = function() {
1455
	if ( 0 === this.obsNbre ) {
1453
	if ( 0 === this.obsNbre ) {
1456
		$( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
1454
		$( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
1457
	} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1455
	} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1458
		$( '#transmettre-obs' ).removeAttr( 'disabled' );
1456
		$( '#transmettre-obs' ).removeAttr( 'disabled' );
1459
		$( '#ajouter-obs' ).removeAttr( 'disabled' );
1457
		$( '#ajouter-obs' ).removeAttr( 'disabled' );
1460
	} else if ( this.obsNbre >= this.obsMaxNbre ) {
1458
	} else if ( this.obsNbre >= this.obsMaxNbre ) {
1461
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1459
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1462
		this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
1460
		this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
1463
	}
1461
	}
1464
};
1462
};
1465
 
1463
 
1466
WidgetSaisie.prototype.defilerMiniatures = function( element ) {
1464
WidgetSaisie.prototype.defilerMiniatures = function( element ) {
1467
 
1465
 
1468
	var miniatureSelectionne = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
1466
	var miniatureSelectionne = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
1469
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
1467
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
1470
	miniatureSelectionne.addClass( 'miniature-cachee' );
1468
	miniatureSelectionne.addClass( 'miniature-cachee' );
1471
 
1469
 
1472
	var miniatureAffichee    = miniatureSelectionne;
1470
	var miniatureAffichee    = miniatureSelectionne;
1473
 
1471
 
1474
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
1472
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
1475
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
1473
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
1476
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
1474
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
1477
		} else {
1475
		} else {
1478
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
1476
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
1479
		}
1477
		}
1480
	} else {
1478
	} else {
1481
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
1479
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
1482
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
1480
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
1483
		} else {
1481
		} else {
1484
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
1482
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
1485
		}
1483
		}
1486
	}
1484
	}
1487
	miniatureAffichee.addClass( 'miniature-selectionnee' );
1485
	miniatureAffichee.addClass( 'miniature-selectionnee' );
1488
	miniatureAffichee.removeClass( 'miniature-cachee' );
1486
	miniatureAffichee.removeClass( 'miniature-cachee' );
1489
};
1487
};
1490
 
1488
 
1491
WidgetSaisie.prototype.supprimerObs = function( selector ) {
1489
WidgetSaisie.prototype.supprimerObs = function( selector ) {
1492
	var obsId = $( selector ).val();
1490
	var obsId = $( selector ).val();
1493
	// Problème avec IE 6 et 7
1491
	// Problème avec IE 6 et 7
1494
	if ( 'Supprimer' === obsId ) {
1492
	if ( 'Supprimer' === obsId ) {
1495
		obsId = $( selector ).attr( 'title' );
1493
		obsId = $( selector ).attr( 'title' );
1496
	}
1494
	}
1497
	this.supprimerObsParId( obsId );
1495
	this.supprimerObsParId( obsId );
1498
};
1496
};
1499
 
1497
 
1500
WidgetSaisie.prototype.supprimerObsParId = function( obsId ) {
1498
WidgetSaisie.prototype.supprimerObsParId = function( obsId ) {
1501
	this.obsNbre = this.obsNbre - 1;
1499
	this.obsNbre = this.obsNbre - 1;
1502
	$( '.obs-nbre' ).text( this.obsNbre );
1500
	$( '.obs-nbre' ).text( this.obsNbre );
1503
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1501
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1504
	$( '.obs' + obsId ).remove();
1502
	$( '.obs' + obsId ).remove();
1505
	$( '#liste-obs' ).removeData( 'obsId' + obsId );
1503
	$( '#liste-obs' ).removeData( 'obsId' + obsId );
1506
};
1504
};
1507
 
1505
 
1508
WidgetSaisie.prototype.transmettreObs = function() {
1506
WidgetSaisie.prototype.transmettreObs = function() {
1509
	var observations = $( '#liste-obs' ).data();
1507
	var observations = $( '#liste-obs' ).data();
1510
	if ( this.debug ) {
1508
	if ( this.debug ) {
1511
		console.log( observations );
1509
		console.log( observations );
1512
	}
1510
	}
1513
	if ( !valeurOk( typeof observations, true, 'object' ) ) {
1511
	if ( !valeurOk( typeof observations, true, 'object' ) ) {
1514
		this.afficherPanneau( '#dialogue-zero-obs' );
1512
		this.afficherPanneau( '#dialogue-zero-obs' );
1515
	} else {
1513
	} else {
1516
		this.nbObsEnCours = 1;
1514
		this.nbObsEnCours = 1;
1517
		this.nbObsTransmises = 0;
1515
		this.nbObsTransmises = 0;
1518
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
1516
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
1519
			return i;
1517
			return i;
1520
		}).length;
1518
		}).length;
1521
		this.depilerObsPourEnvoi();
1519
		this.depilerObsPourEnvoi();
1522
	}
1520
	}
1523
	return false;
1521
	return false;
1524
};
1522
};
1525
 
1523
 
1526
WidgetSaisie.prototype.depilerObsPourEnvoi = function() {
1524
WidgetSaisie.prototype.depilerObsPourEnvoi = function() {
1527
	var observations = $( '#liste-obs' ).data();
1525
	var observations = $( '#liste-obs' ).data();
1528
	// la boucle est factice car on utilise un tableau
1526
	// la boucle est factice car on utilise un tableau
1529
	// dont on a besoin de n'extraire que le premier élément
1527
	// dont on a besoin de n'extraire que le premier élément
1530
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1528
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1531
	// TODO: utiliser var.keys quand ça sera plus répandu
1529
	// TODO: utiliser var.keys quand ça sera plus répandu
1532
	// ou bien utiliser un vrai tableau et pas un objet
1530
	// ou bien utiliser un vrai tableau et pas un objet
1533
	for ( var obsNum in observations ) {
1531
	for ( var obsNum in observations ) {
1534
		var obsATransmettre = {
1532
		var obsATransmettre = {
1535
			'projet'  : this.tagProjet,
1533
			'projet'  : this.tagProjet,
1536
			'tag-obs' : this.tagObs,
1534
			'tag-obs' : this.tagObs,
1537
			'tag-img' : this.tagImg
1535
			'tag-img' : this.tagImg
1538
		};
1536
		};
1539
		var utilisateur = {
1537
		var utilisateur = {
1540
			id_utilisateur : $( '#id_utilisateur' ).val(),
1538
			id_utilisateur : $( '#id_utilisateur' ).val(),
1541
			prenom         : $( '#prenom' ).val(),
1539
			prenom         : $( '#prenom' ).val(),
1542
			nom            : $( '#nom' ).val(),
1540
			nom            : $( '#nom' ).val(),
1543
			courriel       : $( '#courriel' ).val()
1541
			courriel       : $( '#courriel' ).val()
1544
		};
1542
		};
1545
		obsATransmettre['utilisateur'] = utilisateur;
1543
		obsATransmettre['utilisateur'] = utilisateur;
1546
		obsATransmettre[obsNum] = observations[obsNum];
1544
		obsATransmettre[obsNum] = observations[obsNum];
1547
		var idObsNumerique = obsNum.replace( 'obsId', '' );
1545
		var idObsNumerique = obsNum.replace( 'obsId', '' );
1548
		if( '' !== idObsNumerique ) {
1546
		if( '' !== idObsNumerique ) {
1549
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
1547
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
1550
		}
1548
		}
1551
		break;
1549
		break;
1552
	}
1550
	}
1553
};
1551
};
1554
 
1552
 
1555
WidgetSaisie.prototype.envoyerObsAuCel = function( idObs, observation ) {
1553
WidgetSaisie.prototype.envoyerObsAuCel = function( idObs, observation ) {
1556
	var lthis = this;
1554
	var lthis = this;
1557
 
1555
 
1558
	var erreurMsg = '';
1556
	var erreurMsg = '';
1559
	$.ajax({
1557
	$.ajax({
1560
		url        : lthis.serviceSaisieUrl,
1558
		url        : lthis.serviceSaisieUrl,
1561
		type       : 'POST',
1559
		type       : 'POST',
1562
		data       : observation,
1560
		data       : observation,
1563
		dataType   : 'json',
1561
		dataType   : 'json',
1564
		beforeSend : function() {
1562
		beforeSend : function() {
1565
			$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
1563
			$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
1566
			$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1564
			$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1567
			$( '.alert-txt' ).empty();
1565
			$( '.alert-txt' ).empty();
1568
			$( '.alert-txt .msg-erreur' ).remove();
1566
			$( '.alert-txt .msg-erreur' ).remove();
1569
			$( '.alert-txt .msg-debug' ).remove();
1567
			$( '.alert-txt .msg-debug' ).remove();
1570
			$( '#chargement' ).removeClass( 'hidden' );
1568
			$( '#chargement' ).removeClass( 'hidden' );
1571
		},
1569
		},
1572
		success    : function( data, textStatus, jqXHR ) {
1570
		success    : function( data, textStatus, jqXHR ) {
1573
			// mise à jour du nombre d'obs à transmettre
1571
			// mise à jour du nombre d'obs à transmettre
1574
			// et suppression de l'obs
1572
			// et suppression de l'obs
1575
			lthis.supprimerObsParId( idObs );
1573
			lthis.supprimerObsParId( idObs );
1576
			lthis.nbObsEnCours++;
1574
			lthis.nbObsEnCours++;
1577
			// mise à jour du statut
1575
			// mise à jour du statut
1578
			lthis.mettreAJourProgression();
1576
			lthis.mettreAJourProgression();
1579
			if( 0 < lthis.obsNbre ) {
1577
			if( 0 < lthis.obsNbre ) {
1580
				// dépilement de la suivante
1578
				// dépilement de la suivante
1581
				lthis.depilerObsPourEnvoi();
1579
				lthis.depilerObsPourEnvoi();
1582
			}
1580
			}
1583
		},
1581
		},
1584
		statusCode  : {
1582
		statusCode  : {
1585
			500 : function( jqXHR, textStatus, errorThrown ) {
1583
			500 : function( jqXHR, textStatus, errorThrown ) {
1586
				erreurMsg += lthis.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1584
				erreurMsg += lthis.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1587
				}
1585
				}
1588
		},
1586
		},
1589
		error        : function( jqXHR, textStatus, errorThrown ) {
1587
		error        : function( jqXHR, textStatus, errorThrown ) {
1590
			erreurMsg += lthis.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1588
			erreurMsg += lthis.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1591
			try {
1589
			try {
1592
				reponse = jQuery.parseJSON( jqXHR.responseText );
1590
				reponse = jQuery.parseJSON( jqXHR.responseText );
1593
				if ( null !== reponse ) {
1591
				if ( null !== reponse ) {
1594
					$.each( reponse, function( cle, valeur ) {
1592
					$.each( reponse, function( cle, valeur ) {
1595
						erreurMsg += valeur + '\n';
1593
						erreurMsg += valeur + '\n';
1596
					});
1594
					});
1597
				}
1595
				}
1598
			} catch( e ) {
1596
			} catch( e ) {
1599
				erreurMsg += lthis.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
1597
				erreurMsg += lthis.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
1600
			}
1598
			}
1601
		},
1599
		},
1602
		complete      : function( jqXHR, textStatus ) {
1600
		complete      : function( jqXHR, textStatus ) {
1603
			var debugMsg = extraireEnteteDebug( jqXHR );
1601
			var debugMsg = extraireEnteteDebug( jqXHR );
1604
 
1602
 
1605
			if ( '' !== erreurMsg ) {
1603
			if ( '' !== erreurMsg ) {
1606
				if ( lthis.debug ) {
1604
				if ( lthis.debug ) {
1607
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
1605
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
1608
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1606
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1609
				}
1607
				}
1610
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1608
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1611
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagProjet+
1609
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagProjet+
1612
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
1610
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
1613
 
1611
 
1614
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
1612
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
1615
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
1613
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
1616
				window.location.hash = 'obs' + idObs;
1614
				window.location.hash = 'obs' + idObs;
1617
 
1615
 
1618
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
1616
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
1619
					$( '#tpl-transmission-ko' ).clone()
1617
					$( '#tpl-transmission-ko' ).clone()
1620
						.find( '.courriel-erreur' )
1618
						.find( '.courriel-erreur' )
1621
						.attr( 'href', hrefCourriel )
1619
						.attr( 'href', hrefCourriel )
1622
						.end()
1620
						.end()
1623
						.html()
1621
						.html()
1624
				);
1622
				);
1625
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
1623
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
1626
				$( '#chargement' ).addClass( 'hidden' );
1624
				$( '#chargement' ).addClass( 'hidden' );
1627
				lthis.initialiserBarreProgression;
1625
				lthis.initialiserBarreProgression;
1628
			} else {
1626
			} else {
1629
				if ( lthis.debug ) {
1627
				if ( lthis.debug ) {
1630
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1628
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1631
				}
1629
				}
1632
				if( 0 === lthis.obsNbre ) {
1630
				if( 0 === lthis.obsNbre ) {
1633
					setTimeout( function() {
1631
					setTimeout( function() {
1634
						$( '#chargement' ).addClass( 'hidden' );
1632
						$( '#chargement' ).addClass( 'hidden' );
1635
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
1633
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
1636
						$( '#dialogue-obs-transaction-ok' ).removeClass( 'hidden' );
1634
						$( '#dialogue-obs-transaction-ok' ).removeClass( 'hidden' );
1637
						window.location.hash = 'dialogue-obs-transaction-ok';
1635
						window.location.hash = 'dialogue-obs-transaction-ok';
1638
						lthis.initialiserObs.bind( lthis );
1636
						lthis.initialiserObs.bind( lthis );
1639
					}, 1500 );
1637
					}, 1500 );
1640
				}
1638
				}
1641
			}
1639
			}
1642
		}
1640
		}
1643
	});
1641
	});
1644
};
1642
};
1645
 
1643
 
1646
WidgetSaisie.prototype.mettreAJourProgression = function() {
1644
WidgetSaisie.prototype.mettreAJourProgression = function() {
1647
	this.nbObsTransmises++;
1645
	this.nbObsTransmises++;
1648
 
1646
 
1649
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
1647
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
1650
 
1648
 
1651
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
1649
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
1652
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
1650
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
1653
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.msgTraduction( 'observations-transmises' ) );
1651
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.msgTraduction( 'observations-transmises' ) );
1654
	if( 0 === this.obsNbre ) {
1652
	if( 0 === this.obsNbre ) {
1655
		$( '.progress' ).removeClass( 'active' );
1653
		$( '.progress' ).removeClass( 'active' );
1656
		$( '.progress' ).removeClass( 'progress-bar-striped' );
1654
		$( '.progress' ).removeClass( 'progress-bar-striped' );
1657
	}
1655
	}
1658
};
1656
};
1659
 
1657
 
1660
WidgetSaisie.prototype.initialiserBarreProgression = function() {
1658
WidgetSaisie.prototype.initialiserBarreProgression = function() {
1661
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
1659
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
1662
	$( '#barre-progression-upload' ).css( 'width', '0%' );
1660
	$( '#barre-progression-upload' ).css( 'width', '0%' );
1663
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.msgTraduction( 'observations-transmises' ) );
1661
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.msgTraduction( 'observations-transmises' ) );
1664
	$( '.progress' ).addClass( 'active' );
1662
	$( '.progress' ).addClass( 'active' );
1665
	$( '.progress' ).addClass( 'progress-bar-striped' );
1663
	$( '.progress' ).addClass( 'progress-bar-striped' );
1666
};
1664
};
1667
 
1665
 
1668
WidgetSaisie.prototype.initialiserObs = function() {
1666
WidgetSaisie.prototype.initialiserObs = function() {
1669
	this.obsNbre = 0;
1667
	this.obsNbre = 0;
1670
	this.nbObsTransmises = 0;
1668
	this.nbObsTransmises = 0;
1671
	this.nbObsEnCours = 0;
1669
	this.nbObsEnCours = 0;
1672
	this.totalObsATransmettre = 0;
1670
	this.totalObsATransmettre = 0;
1673
	this.initialiserBarreProgression();
1671
	this.initialiserBarreProgression();
1674
	$( '.obs-nbre' ).text( this.obsNbre );
1672
	$( '.obs-nbre' ).text( this.obsNbre );
1675
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1673
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1676
	$( '#liste-obs' ).removeData();
1674
	$( '#liste-obs' ).removeData();
1677
	$( '.obs' ).remove();
1675
	$( '.obs' ).remove();
1678
	$( '#dialogue-bloquer-creer-obs' ).addClass( 'hidden' );
1676
	$( '#dialogue-bloquer-creer-obs' ).addClass( 'hidden' );
1679
};
1677
};
1680
 
1678
 
1681
WidgetSaisie.prototype.afficherPanneau = function( selecteur ) {
1679
WidgetSaisie.prototype.afficherPanneau = function( selecteur ) {
1682
	$( selecteur )
1680
	$( selecteur )
1683
		.removeClass( 'hidden')
1681
		.removeClass( 'hidden')
1684
		.hide()
1682
		.hide()
1685
		.show( 600 )
1683
		.show( 600 )
1686
		.delay( this.dureeMessage )
1684
		.delay( this.dureeMessage )
1687
		.hide( 600 );
1685
		.hide( 600 );
1688
};
1686
};
1689
 
1687
 
1690
WidgetSaisie.prototype.masquerPanneau = function( selecteur ) {
1688
WidgetSaisie.prototype.masquerPanneau = function( selecteur ) {
1691
	$( selecteur ).addClass( 'hidden' );
1689
	$( selecteur ).addClass( 'hidden' );
1692
};
1690
};
1693
 
1691
 
1694
WidgetSaisie.prototype.fermerPanneauAlert = function() {
1692
WidgetSaisie.prototype.fermerPanneauAlert = function() {
1695
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
1693
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
1696
};
1694
};
1697
 
1695
 
1698
/**
1696
/**
1699
 * Si la langue est définie dans this.langue, et si des messages sont définis
1697
 * Si la langue est définie dans this.langue, et si des messages sont définis
1700
 * dans this.msgs, tente de trouver le message dont la clé est [cle] dans la
1698
 * dans this.msgs, tente de trouver le message dont la clé est [cle] dans la
1701
 * langue en cours. S'il n'est pas trouvé, retourne la version française (par
1699
 * langue en cours. S'il n'est pas trouvé, retourne la version française (par
1702
 * défaut); si celle-ci n'exite pas, retourne "N/A".
1700
 * défaut); si celle-ci n'exite pas, retourne "N/A".
1703
 */
1701
 */
1704
WidgetSaisie.prototype.msgTraduction = function( cle ) {
1702
WidgetSaisie.prototype.msgTraduction = function( cle ) {
1705
	var msg = 'N/A';
1703
	var msg = 'N/A';
1706
	if ( this.msgs ) {
1704
	if ( this.msgs ) {
1707
		if ( this.langue in this.msgs && cle in this.msgs[this.langue] ) {
1705
		if ( this.langue in this.msgs && cle in this.msgs[this.langue] ) {
1708
			msg = this.msgs[this.langue][cle];
1706
			msg = this.msgs[this.langue][cle];
1709
		} else if ( cle in this.msgs['fr'] ) {
1707
		} else if ( cle in this.msgs['fr'] ) {
1710
			msg = this.msgs['fr'][cle];
1708
			msg = this.msgs['fr'][cle];
1711
		}
1709
		}
1712
	}
1710
	}
1713
	return msg;
1711
	return msg;
1714
};
1712
};
1715
 
1713
 
1716
// lib hors objet --
1714
// lib hors objet --
1717
 
1715
 
1718
/**
1716
/**
1719
* Permet à la fois de vérifier qu'une valeur ou objet existe et n'est pas vide
1717
* Permet à la fois de vérifier qu'une valeur ou objet existe et n'est pas vide
1720
* et de comparer à une autre valeur :
1718
* et de comparer à une autre valeur :
1721
* Vérifie qu'une variable ou objet n'est pas : vide, null, undefined, NaN
1719
* Vérifie qu'une variable ou objet n'est pas : vide, null, undefined, NaN
1722
* Si comparer est défini on le compare à valeur en fonction de sensComparaison
1720
* Si comparer est défini on le compare à valeur en fonction de sensComparaison
1723
* Un booléen est une variable valide : on retourne true
1721
* Un booléen est une variable valide : on retourne true
1724
* @param { string || number || object || undefined } valeur
1722
* @param { string || number || object || undefined } valeur
1725
* @param { boolean } sensComparaison : true = rechercher, false = refuser
1723
* @param { boolean } sensComparaison : true = rechercher, false = refuser
1726
* @param { string || number || object || undefined || boolean } comparer :valeur à comparer
1724
* @param { string || number || object || undefined || boolean } comparer :valeur à comparer
1727
* @returns {boolean}
1725
* @returns {boolean}
1728
*/
1726
*/
1729
function valeurOk( valeur, sensComparaison = true, comparer = undefined ) {
1727
function valeurOk( valeur, sensComparaison = true, comparer = undefined ) {
1730
 
1728
 
1731
	if ( 'boolean' !== typeof valeur ) {
1729
	if ( 'boolean' !== typeof valeur ) {
1732
		switch( typeof valeur ) {
1730
		switch( typeof valeur ) {
1733
			case 'string' :
1731
			case 'string' :
1734
				retour = ( '' !== valeur );
1732
				retour = ( '' !== valeur );
1735
			 break;
1733
			 break;
1736
			case 'number' :
1734
			case 'number' :
1737
					retour = ( NaN !== valeur );
1735
					retour = ( NaN !== valeur );
1738
				break;
1736
				break;
1739
			case 'object' :
1737
			case 'object' :
1740
					retour = ( null !== valeur && undefined !== valeur && !$.isEmptyObject( valeur ) );
1738
					retour = ( null !== valeur && undefined !== valeur && !$.isEmptyObject( valeur ) );
1741
					if ( undefined !== valeur.length ) {
1739
					if ( undefined !== valeur.length ) {
1742
						retour = ( retour  && 0 < valeur.length );
1740
						retour = ( retour  && 0 < valeur.length );
1743
					}
1741
					}
1744
				break;
1742
				break;
1745
			case 'undefined' :
1743
			case 'undefined' :
1746
			default :
1744
			default :
1747
				retour = false;
1745
				retour = false;
1748
		}
1746
		}
1749
		if ( retour && comparer !== undefined ) {
1747
		if ( retour && comparer !== undefined ) {
1750
			var resultComparaison = ( comparer === valeur );
1748
			var resultComparaison = ( comparer === valeur );
1751
			retour = ( sensComparaison ) ? resultComparaison : !resultComparaison ;
1749
			retour = ( sensComparaison ) ? resultComparaison : !resultComparaison ;
1752
		}
1750
		}
1753
		return retour;
1751
		return retour;
1754
	} else {
1752
	} else {
1755
		// Un booléen est une valeur valable
1753
		// Un booléen est une valeur valable
1756
		return true;
1754
		return true;
1757
	}
1755
	}
1758
}
1756
}
1759
 
1757
 
1760
/**
1758
/**
1761
* Stope l'évènement courant quand on clique sur un lien.
1759
* Stope l'évènement courant quand on clique sur un lien.
1762
* Utile pour Chrome, Safari...
1760
* Utile pour Chrome, Safari...
1763
*/
1761
*/
1764
function arreter( evenement ) {
1762
function arreter( evenement ) {
1765
	if ( evenement.stopPropagation ) {
1763
	if ( evenement.stopPropagation ) {
1766
		evenement.stopPropagation();
1764
		evenement.stopPropagation();
1767
	}
1765
	}
1768
	if ( evenement.preventDefault ) {
1766
	if ( evenement.preventDefault ) {
1769
		evenement.preventDefault();
1767
		evenement.preventDefault();
1770
	}
1768
	}
1771
	return false;
1769
	return false;
1772
}
1770
}
1773
 
1771
 
1774
/**
1772
/**
1775
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1773
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1776
 * @param jqXHR
1774
 * @param jqXHR
1777
 * @returns {String}
1775
 * @returns {String}
1778
 */
1776
 */
1779
function extraireEnteteDebug( jqXHR ) {
1777
function extraireEnteteDebug( jqXHR ) {
1780
	var msgDebug = '';
1778
	var msgDebug = '';
1781
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
1779
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
1782
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
1780
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
1783
		if ( null !== debugInfos ) {
1781
		if ( null !== debugInfos ) {
1784
			$.each( debugInfos, function( cle, valeur ) {
1782
			$.each( debugInfos, function( cle, valeur ) {
1785
				msgDebug += valeur + '\n';
1783
				msgDebug += valeur + '\n';
1786
			});
1784
			});
1787
		}
1785
		}
1788
	}
1786
	}
1789
	return msgDebug;
1787
	return msgDebug;
1790
}
1788
}
1791
 
1789
 
1792
/*
1790
/*
1793
 * jQuery UI Autocomplete HTML Extension
1791
 * jQuery UI Autocomplete HTML Extension
1794
 *
1792
 *
1795
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1793
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1796
 * Dual licensed under the MIT or GPL Version 2 licenses.
1794
 * Dual licensed under the MIT or GPL Version 2 licenses.
1797
 *
1795
 *
1798
 * http://github.com/scottgonzalez/jquery-ui-extensions
1796
 * http://github.com/scottgonzalez/jquery-ui-extensions
1799
 *
1797
 *
1800
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1798
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1801
 */
1799
 */
1802
( function( $ ) {
1800
( function( $ ) {
1803
	var proto = $.ui.autocomplete.prototype,
1801
	var proto = $.ui.autocomplete.prototype,
1804
		initSource = proto._initSource;
1802
		initSource = proto._initSource;
1805
 
1803
 
1806
	WidgetSaisie.prototype.filter = function( array, term ) {
1804
	WidgetSaisie.prototype.filter = function( array, term ) {
1807
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
1805
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
1808
		return $.grep( array, function( value ) {
1806
		return $.grep( array, function( value ) {
1809
			return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
1807
			return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
1810
		});
1808
		});
1811
	}
1809
	}
1812
	$.extend( proto, {
1810
	$.extend( proto, {
1813
		_initSource: function() {
1811
		_initSource: function() {
1814
			if ( this.options.html && $.isArray( this.options.source ) ) {
1812
			if ( this.options.html && $.isArray( this.options.source ) ) {
1815
				this.source = function( request, response ) {
1813
				this.source = function( request, response ) {
1816
					response( filter( this.options.source, request.term ) );
1814
					response( filter( this.options.source, request.term ) );
1817
				};
1815
				};
1818
			} else {
1816
			} else {
1819
				initSource.call( this );
1817
				initSource.call( this );
1820
			}
1818
			}
1821
		},
1819
		},
1822
		_renderItem: function( ul, item) {
1820
		_renderItem: function( ul, item) {
1823
			if ( item.retenu ) {
1821
			if ( item.retenu ) {
1824
				item.label = '<strong>' + item.label + '</strong>';
1822
				item.label = '<strong>' + item.label + '</strong>';
1825
			}
1823
			}
1826
 
1824
 
1827
			return $( '<li></li>' )
1825
			return $( '<li></li>' )
1828
				.data( 'item.autocomplete', item )
1826
				.data( 'item.autocomplete', item )
1829
				.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
1827
				.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
1830
				.appendTo( ul );
1828
				.appendTo( ul );
1831
		}
1829
		}
1832
	});
1830
	});
1833
})( jQuery );
1831
})( jQuery );