Subversion Repositories eFlore/Applications.cel

Rev

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

Rev 2707 Rev 2709
1
/**
1
/**
2
 * Constructeur WidgetSaisie par défaut
2
 * Constructeur WidgetSaisie par défaut
3
 */
3
 */
4
function WidgetSaisie() {
4
function WidgetSaisie() {
5
	this.obsNbre = 0;
5
	this.obsNbre = 0;
6
	this.nbObsEnCours = 1;
6
	this.nbObsEnCours = 1;
7
	this.totalObsATransmettre = 0;
7
	this.totalObsATransmettre = 0;
8
	this.nbObsTransmises = 0;
8
	this.nbObsTransmises = 0;
9
	this.map = null;
9
	this.map = null;
10
	this.marker = null;
10
	this.marker = null;
11
	this.latLng = null;
11
	this.latLng = null;
12
	this.geocoder = null;
12
	this.geocoder = null;
13
	this.debug = null;
13
	this.debug = null;
14
	this.html5 = null;
14
	this.html5 = null;
15
	this.tagProjet = null;
15
	this.tagProjet = null;
16
	this.tagImg = null;
16
	this.tagImg = null;
17
	this.tagObs = null;
17
	this.tagObs = null;
18
	this.separationTagImg = null;
18
	this.separationTagImg = null;
19
	this.separationTagObs = null;
19
	this.separationTagObs = null;
20
	this.obsId = null;
20
	this.obsId = null;
21
	this.serviceSaisieUrl = null;
21
	this.serviceSaisieUrl = null;
22
	this.serviceObsUrl = null;
22
	this.serviceObsUrl = null;
23
	this.nomSciReferentiel = null;
23
	this.nomSciReferentiel = null;
24
	this.especeImposee = false;
24
	this.especeImposee = false;
25
	this.infosEspeceImposee = null;
25
	this.infosEspeceImposee = null;
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.googleMapMarqueurUrl = null;
35
	this.googleMapMarqueurUrl = null;
36
	this.chargementIconeUrl = null;
36
	this.chargementIconeUrl = null;
37
	this.chargementImageIconeUrl = null;
37
	this.chargementImageIconeUrl = null;
38
	this.calendrierIconeUrl = null;
38
	this.calendrierIconeUrl = null;
39
	this.pasDePhotoIconeUrl = null;
39
	this.pasDePhotoIconeUrl = null;
40
}
40
}
41
 
41
 
42
/**
42
/**
43
 * Initialisation du widget
43
 * Initialisation du widget
44
 */
44
 */
45
WidgetSaisie.prototype.init = function() {
45
WidgetSaisie.prototype.init = function() {
46
	this.initCarto();
46
	this.initCarto();
47
	this.initForm();
47
	this.initForm();
48
	this.initEvts();
48
	this.initEvts();
49
	this.requeterIdentite();
49
	this.requeterIdentite();
50
};
50
};
51
 
51
 
52
/**
52
/**
53
 * Initialise la cartographie
53
 * Initialise la cartographie
54
 */
54
 */
55
WidgetSaisie.prototype.initCarto = function() {
55
WidgetSaisie.prototype.initCarto = function() {
56
	this.initialiserGoogleMap();
56
	this.initialiserGoogleMap();
57
	this.initialiserAutocompleteCommune();
57
	this.initialiserAutocompleteCommune();
58
 
-
 
59
	$("#carte-recherche").autocomplete({
-
 
60
		//Cette partie utilise geocoder pour extraire des valeurs d'adresse
-
 
61
		source: function(request, response) {
-
 
62
			geocoderOptions.address = request.term + addressSuffix;
-
 
63
			console.log('Geocoder options', geocoderOptions);
-
 
64
			lthis.geocoder.geocode( geocoderOptions, function(results, status) {
-
 
65
				if (status == google.maps.GeocoderStatus.OK) {
-
 
66
					response($.map(results, function(item) {
-
 
67
						var retour = {
-
 
68
							label: item.formatted_address,
-
 
69
							value: item.formatted_address,
-
 
70
							latitude: item.geometry.location.lat(),
-
 
71
							longitude: item.geometry.location.lng()
-
 
72
						};
-
 
73
						return retour;
-
 
74
					}));
-
 
75
				} else {
-
 
76
					lthis.afficherErreurGoogleMap(status);
-
 
77
				}
-
 
78
			});
-
 
79
		},
-
 
80
		// Cette partie est executee a la selection d'une adresse
-
 
81
		select: function(event, ui) {
-
 
82
			var latLng = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
-
 
83
			lthis.deplacerMarker(latLng);
-
 
84
		}
-
 
85
	});
-
 
86
}
58
}
87
 
59
 
88
/**
60
/**
89
 * Initialise le formulaire, les validateurs, les listes de complétion...
61
 * Initialise le formulaire, les validateurs, les listes de complétion...
90
 */
62
 */
91
WidgetSaisie.prototype.initForm = function() {
63
WidgetSaisie.prototype.initForm = function() {
92
	if (this.obsId != '') {
64
	if (this.obsId != '') {
93
		console.log('obsId: (' + typeof obsId + ') : ' + obsId);
65
		console.log('obsId: (' + typeof obsId + ') : ' + obsId);
94
		this.chargerInfoObs();
66
		this.chargerInfoObs();
95
	}
67
	}
96
 
68
 
97
	this.configurerDatePicker('#date');
69
	this.configurerDatePicker('#date');
98
	this.ajouterAutocompletionNoms();
70
	this.ajouterAutocompletionNoms();
99
	this.configurerFormValidator();
71
	this.configurerFormValidator();
100
	this.definirReglesFormValidator();
72
	this.definirReglesFormValidator();
101
 
73
 
102
	if(this.especeImposee) {
74
	if(this.especeImposee) {
103
		$("#taxon").attr("disabled", "disabled");
75
		$("#taxon").attr("disabled", "disabled");
104
		$("#taxon-input-groupe").attr("title","");
76
		$("#taxon-input-groupe").attr("title","");
105
		var infosAssociee = {
77
		var infosAssociee = {
106
			label : this.infosEspeceImposee.nom_sci_complet,
78
			label : this.infosEspeceImposee.nom_sci_complet,
107
			value : this.infosEspeceImposee.nom_sci_complet,
79
			value : this.infosEspeceImposee.nom_sci_complet,
108
			nt : this.infosEspeceImposee.num_taxonomique,
80
			nt : this.infosEspeceImposee.num_taxonomique,
109
			nomSel : this.infosEspeceImposee.nom_sci,
81
			nomSel : this.infosEspeceImposee.nom_sci,
110
			nomSelComplet : this.infosEspeceImposee.nom_sci_complet,
82
			nomSelComplet : this.infosEspeceImposee.nom_sci_complet,
111
			numNomSel : this.infosEspeceImposee.id,
83
			numNomSel : this.infosEspeceImposee.id,
112
			nomRet : this.infosEspeceImposee["nom_retenu.libelle"],
84
			nomRet : this.infosEspeceImposee["nom_retenu.libelle"],
113
			numNomRet : this.infosEspeceImposee["nom_retenu.id"],
85
			numNomRet : this.infosEspeceImposee["nom_retenu.id"],
114
			famille : this.infosEspeceImposee.famille,
86
			famille : this.infosEspeceImposee.famille,
115
			retenu : (this.infosEspeceImposee.retenu == 'false') ? false : true
87
			retenu : (this.infosEspeceImposee.retenu == 'false') ? false : true
116
		};
88
		};
117
		$("#taxon").data(infosAssociee);
89
		$("#taxon").data(infosAssociee);
118
	}
90
	}
119
}
91
}
120
 
92
 
121
/**
93
/**
122
 * Initialise les écouteurs d'événements
94
 * Initialise les écouteurs d'événements
123
 */
95
 */
124
WidgetSaisie.prototype.initEvts = function() {
96
WidgetSaisie.prototype.initEvts = function() {
125
	var lthis = this;
97
	var lthis = this;
126
	$('body').on('click', '.effacer-miniature', function() {
98
	$('body').on('click', '.effacer-miniature', function() {
127
		$(this).parent().remove();
99
		$(this).parent().remove();
128
	});
100
	});
129
	$("#fichier").bind('change', function (e) {
101
	$("#fichier").bind('change', function (e) {
130
		arreter(e);
102
		arreter(e);
131
		var options = {
103
		var options = {
132
			success: lthis.afficherMiniature.bind(lthis), // post-submit callback
104
			success: lthis.afficherMiniature.bind(lthis), // post-submit callback
133
			dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
105
			dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
134
			resetForm: true // reset the form after successful submit
106
			resetForm: true // reset the form after successful submit
135
		};
107
		};
136
		$("#miniature").append('<img id="miniature-chargement" class="miniature" alt="chargement" src="'+this.chargementImageIconeUrl+'"/>');
108
		$("#miniature").append('<img id="miniature-chargement" class="miniature" alt="chargement" src="'+this.chargementImageIconeUrl+'"/>');
137
		$("#ajouter-obs").attr('disabled', 'disabled');
109
		$("#ajouter-obs").attr('disabled', 'disabled');
138
		if(lthis.verifierFormat($("#fichier").val())) {
110
		if(lthis.verifierFormat($("#fichier").val())) {
139
			$("#form-upload").ajaxSubmit(options);
111
			$("#form-upload").ajaxSubmit(options);
140
		} else {
112
		} else {
141
			$('#form-upload')[0].reset();
113
			$('#form-upload')[0].reset();
142
			window.alert("Le format de fichier n'est pas supporté, les formats acceptés sont "+	$("#fichier").attr("accept"));
114
			window.alert("Le format de fichier n'est pas supporté, les formats acceptés sont "+	$("#fichier").attr("accept"));
143
		}
115
		}
144
		return false;
116
		return false;
145
	});
117
	});
146
	// identité
118
	// identité
147
	$("#courriel").on('blur', this.requeterIdentite.bind(this));
119
	$("#courriel").on('blur', this.requeterIdentite.bind(this));
148
	$("#courriel").on('keypress', this.testerLancementRequeteIdentite.bind(this));
120
	$("#courriel").on('keypress', this.testerLancementRequeteIdentite.bind(this));
149
	$(".alert .close").on('click', this.fermerPanneauAlert);
121
	$(".alert .close").on('click', this.fermerPanneauAlert);
150
	$(".has-tooltip").tooltip('enable');
122
	$(".has-tooltip").tooltip('enable');
151
	$("#btn-aide").on('click', this.basculerAffichageAide);
123
	$("#btn-aide").on('click', this.basculerAffichageAide);
152
	$("#prenom").on("change", this.formaterPrenom.bind(this));
124
	$("#prenom").on("change", this.formaterPrenom.bind(this));
153
	$("#nom").on("change", this.formaterNom.bind(this));
125
	$("#nom").on("change", this.formaterNom.bind(this));
154
 
126
 
155
	$("#courriel_confirmation").on('paste', this.bloquerCopierCollerCourriel.bind(this));
127
	$("#courriel_confirmation").on('paste', this.bloquerCopierCollerCourriel.bind(this));
156
	$("a.afficher-coord").on('click', this.basculerAffichageCoord.bind(this));
128
	$("a.afficher-coord").on('click', this.basculerAffichageCoord.bind(this));
157
	$("#ajouter-obs").on('click', this.ajouterObs.bind(this));
129
	$("#ajouter-obs").on('click', this.ajouterObs.bind(this));
158
	$(".obs-nbre").on('changement', this.surChangementNbreObs.bind(this));
130
	$(".obs-nbre").on('changement', this.surChangementNbreObs.bind(this));
159
	$("body").on('click', ".supprimer-obs", function() {
131
	$("body").on('click', ".supprimer-obs", function() {
160
		var that = this,
132
		var that = this,
161
			suppObs = lthis.supprimerObs.bind(lthis);
133
			suppObs = lthis.supprimerObs.bind(lthis);
162
		// bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
134
		// bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
163
		suppObs(that);
135
		suppObs(that);
164
	});
136
	});
165
	$("#transmettre-obs").on('click', this.transmettreObs.bind(this));
137
	$("#transmettre-obs").on('click', this.transmettreObs.bind(this));
166
	$("#referentiel").on('change', this.surChangementReferentiel.bind(this));
138
	$("#referentiel").on('change', this.surChangementReferentiel.bind(this));
167
 
139
 
168
	$("body").on('click', ".defilement-miniatures-gauche", function(event) {
140
	$("body").on('click', ".defilement-miniatures-gauche", function(event) {
169
		event.preventDefault();
141
		event.preventDefault();
170
		lthis.defilerMiniatures($(this));
142
		lthis.defilerMiniatures($(this));
171
	});
143
	});
172
	$("body").on('click', ".defilement-miniatures-droite", function(event) {
144
	$("body").on('click', ".defilement-miniatures-droite", function(event) {
173
		event.preventDefault();
145
		event.preventDefault();
174
		lthis.defilerMiniatures($(this));
146
		lthis.defilerMiniatures($(this));
175
	});
147
	});
176
 
148
 
177
	// fermeture fenêtre
149
	// fermeture fenêtre
178
	if (this.debug == false) {
150
	if (this.debug == false) {
179
		$(window).on('beforeunload', function(event) {
151
		$(window).on('beforeunload', function(event) {
180
			return 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.';
152
			return 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.';
181
		});
153
		});
182
	}
154
	}
183
 
155
 
184
	// Autocompletion du champ adresse
156
	// Autocompletion du champ adresse
185
	$("#carte-recherche").on('focus', function() {
157
	$("#carte-recherche").on('focus', function() {
186
		$(this).select();
158
		$(this).select();
187
	});
159
	});
188
	$("#carte-recherche").on('mouseup', function(event) {// Pour Safari...
160
	$("#carte-recherche").on('mouseup', function(event) {// Pour Safari...
189
		event.preventDefault();
161
		event.preventDefault();
190
	});
162
	});
191
	$("#carte-recherche").keypress(function(e) {
163
	$("#carte-recherche").keypress(function(e) {
192
		if (e.which == 13) {
164
		if (e.which == 13) {
193
			e.preventDefault();
165
			e.preventDefault();
194
		}
166
		}
195
	});
167
	});
196
}
168
}
197
 
169
 
198
/**
170
/**
199
 * Retourne true si l'extension de l'image "nom" est .jpg ou .jpeg
171
 * Retourne true si l'extension de l'image "nom" est .jpg ou .jpeg
200
 */
172
 */
201
WidgetSaisie.prototype.verifierFormat = function(nom) {
173
WidgetSaisie.prototype.verifierFormat = function(nom) {
202
	var parts = nom.split('.');
174
	var parts = nom.split('.');
203
	extension = parts[parts.length - 1];
175
	extension = parts[parts.length - 1];
204
	return (extension.toLowerCase() == 'jpeg' || extension.toLowerCase() == 'jpg');
176
	return (extension.toLowerCase() == 'jpeg' || extension.toLowerCase() == 'jpg');
205
};
177
};
206
 
178
 
207
/**
179
/**
208
 * Affiche la miniature d'une image temporaire (formulaire) qu'on a ajoutée à l'obs
180
 * Affiche la miniature d'une image temporaire (formulaire) qu'on a ajoutée à l'obs
209
 */
181
 */
210
WidgetSaisie.prototype.afficherMiniature = function(reponse) {
182
WidgetSaisie.prototype.afficherMiniature = function(reponse) {
211
	if (this.debug) {
183
	if (this.debug) {
212
		var debogage = $("debogage", reponse).text();
184
		var debogage = $("debogage", reponse).text();
213
		//console.log("Débogage upload : "+debogage);
185
		//console.log("Débogage upload : "+debogage);
214
	}
186
	}
215
	var message = $("message", reponse).text();
187
	var message = $("message", reponse).text();
216
	if (message != '') {
188
	if (message != '') {
217
		$("#miniature-msg").append(message);
189
		$("#miniature-msg").append(message);
218
	} else {
190
	} else {
219
		$("#miniatures").append(this.creerWidgetMiniature(reponse));
191
		$("#miniatures").append(this.creerWidgetMiniature(reponse));
220
	}
192
	}
221
	$('#ajouter-obs').removeAttr('disabled');
193
	$('#ajouter-obs').removeAttr('disabled');
222
};
194
};
223
 
195
 
224
/**
196
/**
225
 * Crée la miniature d'une image temporaire (formulaire), avec le bouton pour l'effacer
197
 * Crée la miniature d'une image temporaire (formulaire), avec le bouton pour l'effacer
226
 */
198
 */
227
WidgetSaisie.prototype.creerWidgetMiniature = function(reponse) {
199
WidgetSaisie.prototype.creerWidgetMiniature = function(reponse) {
228
	var miniatureUrl = $("miniature-url", reponse).text();
200
	var miniatureUrl = $("miniature-url", reponse).text();
229
	var imgNom = $("image-nom", reponse).text();
201
	var imgNom = $("image-nom", reponse).text();
230
	var html =
202
	var html =
231
		'<div class="miniature">'+
203
		'<div class="miniature">'+
232
			'<img class="miniature-img" class="miniature" alt="'+imgNom+'" src="'+miniatureUrl+'"/>'+
204
			'<img class="miniature-img" class="miniature" alt="'+imgNom+'" src="'+miniatureUrl+'"/>'+
233
			'<button class="effacer-miniature" type="button">Effacer</button>'+
205
			'<button class="effacer-miniature" type="button">Effacer</button>'+
234
		'</div>'
206
		'</div>'
235
	return html;
207
	return html;
236
};
208
};
237
 
209
 
238
/**
210
/**
239
 * Efface une miniature (formulaire)
211
 * Efface une miniature (formulaire)
240
 */
212
 */
241
WidgetSaisie.prototype.supprimerMiniature = function(miniature) {
213
WidgetSaisie.prototype.supprimerMiniature = function(miniature) {
242
	miniature.parents('.miniature').remove();
214
	miniature.parents('.miniature').remove();
243
}
215
}
244
 
216
 
245
/**
217
/**
246
 * Efface toutes les miniatures (formulaire)
218
 * Efface toutes les miniatures (formulaire)
247
 */
219
 */
248
WidgetSaisie.prototype.supprimerMiniatures = function() {
220
WidgetSaisie.prototype.supprimerMiniatures = function() {
249
	$("#miniatures").empty();
221
	$("#miniatures").empty();
250
	$("#miniature-msg").empty();
222
	$("#miniature-msg").empty();
251
};
223
};
252
 
224
 
253
/**
225
/**
254
 * Initialise l'autocomplétion de la commune, en fonction du référentiel
226
 * Initialise l'autocomplétion de la commune, en fonction du référentiel
255
 */
227
 */
256
WidgetSaisie.prototype.initialiserAutocompleteCommune = function() {
228
WidgetSaisie.prototype.initialiserAutocompleteCommune = function() {
257
	var geocoderOptions = {
229
	var geocoderOptions = {
258
	},
230
	},
259
	addressSuffix = '',
231
	addressSuffix = '',
260
	lthis = this;
232
	lthis = this;
261
 
233
 
262
	switch(this.nomSciReferentiel) {
234
	switch(this.nomSciReferentiel) {
263
		case 'isfan':
235
		case 'isfan':
264
			// Si des résultats se trouvent dans ce rectangle, ils apparaîtront en premier.
236
			// Si des résultats se trouvent dans ce rectangle, ils apparaîtront en premier.
265
			// Ça marche moyen...
237
			// Ça marche moyen...
266
			geocoderOptions.bounds = new google.maps.LatLngBounds(
238
			geocoderOptions.bounds = new google.maps.LatLngBounds(
267
				new google.maps.LatLng(20.756114, -22.023927),
239
				new google.maps.LatLng(20.756114, -22.023927),
268
				new google.maps.LatLng(38.065392, 33.78662)
240
				new google.maps.LatLng(38.065392, 33.78662)
269
			);
241
			);
270
			break;
242
			break;
271
		case 'apd':
243
		case 'apd':
272
			geocoderOptions.bounds = new google.maps.LatLngBounds(
244
			geocoderOptions.bounds = new google.maps.LatLngBounds(
273
					new google.maps.LatLng(-6.708254, -26.154786),
245
					new google.maps.LatLng(-6.708254, -26.154786),
274
					new google.maps.LatLng(27.488781, 30.490722)
246
					new google.maps.LatLng(27.488781, 30.490722)
275
				);
247
				);
276
			break;
248
			break;
277
		case 'bdtfx':
249
		case 'bdtfx':
278
		case 'bdtxa':
250
		case 'bdtxa':
279
			geocoderOptions.region = 'fr';
251
			geocoderOptions.region = 'fr';
280
			addressSuffix = ', France';
252
			addressSuffix = ', France';
281
	}
253
	}
-
 
254
 
-
 
255
	$("#carte-recherche").autocomplete({
-
 
256
		//Cette partie utilise geocoder pour extraire des valeurs d'adresse
-
 
257
		source: function(request, response) {
-
 
258
			geocoderOptions.address = request.term + addressSuffix;
-
 
259
			lthis.geocoder.geocode( geocoderOptions, function(results, status) {
-
 
260
				if (status == google.maps.GeocoderStatus.OK) {
-
 
261
					response($.map(results, function(item) {
-
 
262
						var retour = {
-
 
263
							label: item.formatted_address,
-
 
264
							value: item.formatted_address,
-
 
265
							latitude: item.geometry.location.lat(),
-
 
266
							longitude: item.geometry.location.lng()
-
 
267
						};
-
 
268
						return retour;
-
 
269
					}));
-
 
270
				} else {
-
 
271
					lthis.afficherErreurGoogleMap(status);
-
 
272
				}
-
 
273
			});
-
 
274
		},
-
 
275
		// Cette partie est executee a la selection d'une adresse
-
 
276
		select: function(event, ui) {
-
 
277
			var latLng = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
-
 
278
			lthis.deplacerMarker(latLng);
-
 
279
		}
-
 
280
	});
282
};
281
};
283
 
282
 
284
WidgetSaisie.prototype.afficherErreurGoogleMap = function(status) {
283
WidgetSaisie.prototype.afficherErreurGoogleMap = function(status) {
285
	if (this.debug) {
284
	if (this.debug) {
286
		$('#dialogue-google-map .contenu').empty().append(
285
		$('#dialogue-google-map .contenu').empty().append(
287
			'<pre class="msg-erreur">'+
286
			'<pre class="msg-erreur">'+
288
			"Le service de Géocodage de Google Map a échoué à cause de l'erreur : "+status+
287
			"Le service de Géocodage de Google Map a échoué à cause de l'erreur : "+status+
289
			'</pre>');
288
			'</pre>');
290
		this.afficherPanneau('#dialogue-google-map');
289
		this.afficherPanneau('#dialogue-google-map');
291
	}
290
	}
292
};
291
};
293
 
292
 
294
WidgetSaisie.prototype.surDeplacementMarker = function() {
293
WidgetSaisie.prototype.surDeplacementMarker = function() {
295
	this.trouverCommune(this.marker.getPosition());
294
	this.trouverCommune(this.marker.getPosition());
296
	this.mettreAJourMarkerPosition(this.marker.getPosition());
295
	this.mettreAJourMarkerPosition(this.marker.getPosition());
297
};
296
};
298
 
297
 
299
WidgetSaisie.prototype.surClickDansCarte = function(event) {
298
WidgetSaisie.prototype.surClickDansCarte = function(event) {
300
	this.deplacerMarker(event.latLng);
299
	this.deplacerMarker(event.latLng);
301
};
300
};
302
 
301
 
303
/**
302
/**
304
 * Place le marqueur aux coordonnées indiquées dans les champs "latitude" et "longitude"
303
 * Place le marqueur aux coordonnées indiquées dans les champs "latitude" et "longitude"
305
 */
304
 */
306
WidgetSaisie.prototype.geolocaliser = function() {
305
WidgetSaisie.prototype.geolocaliser = function() {
307
	var latitude = $('#latitude').val();
306
	var latitude = $('#latitude').val();
308
	var longitude = $('#longitude').val();
307
	var longitude = $('#longitude').val();
309
	this.latLng = new google.maps.LatLng(latitude, longitude);
308
	this.latLng = new google.maps.LatLng(latitude, longitude);
310
	this.deplacerMarker(this.latLng);
309
	this.deplacerMarker(this.latLng);
311
};
310
};
312
 
311
 
313
WidgetSaisie.prototype.initialiserGoogleMap = function() {
312
WidgetSaisie.prototype.initialiserGoogleMap = function() {
314
	var latLng,
313
	var latLng,
315
		zoomDefaut;
314
		zoomDefaut;
316
	// Carte @TODO mettre ça dans la config
315
	// Carte @TODO mettre ça dans la config
317
	if(this.nomSciReferentiel == 'bdtre') {
316
	if(this.nomSciReferentiel == 'bdtre') {
318
		latLng = new google.maps.LatLng(-21.10, 55.30);// Réunion
317
		latLng = new google.maps.LatLng(-21.10, 55.30);// Réunion
319
		zoomDefaut = 7;
318
		zoomDefaut = 7;
320
	} else if(this.nomSciReferentiel == 'lbf') {
319
	} else if(this.nomSciReferentiel == 'lbf') {
321
		latLng = new google.maps.LatLng(33.72211, 35.8603);// Liban
320
		latLng = new google.maps.LatLng(33.72211, 35.8603);// Liban
322
		zoomDefaut = 7;
321
		zoomDefaut = 7;
323
	} else if(this.nomSciReferentiel == 'bdtxa') {
322
	} else if(this.nomSciReferentiel == 'bdtxa') {
324
		latLng = new google.maps.LatLng(14.6, -61.08334);// Fort-De-France
323
		latLng = new google.maps.LatLng(14.6, -61.08334);// Fort-De-France
325
		zoomDefaut = 8;
324
		zoomDefaut = 8;
326
	} else if(this.nomSciReferentiel == 'isfan') {
325
	} else if(this.nomSciReferentiel == 'isfan') {
327
		latLng = new google.maps.LatLng(29.28358, 10.21884);// Afrique du Nord
326
		latLng = new google.maps.LatLng(29.28358, 10.21884);// Afrique du Nord
328
		zoomDefaut = 4;
327
		zoomDefaut = 4;
329
	} else if(this.nomSciReferentiel == 'apd') {
328
	} else if(this.nomSciReferentiel == 'apd') {
330
		latLng = new google.maps.LatLng(8.75624, 1.80176);// Afrique de l'Ouest et du Centre
329
		latLng = new google.maps.LatLng(8.75624, 1.80176);// Afrique de l'Ouest et du Centre
331
		zoomDefaut = 4;
330
		zoomDefaut = 4;
332
	} else {
331
	} else {
333
		latLng = new google.maps.LatLng(46.30871, 2.54395);// Centre de la France
332
		latLng = new google.maps.LatLng(46.30871, 2.54395);// Centre de la France
334
		zoomDefaut = 5;
333
		zoomDefaut = 5;
335
	}
334
	}
336
 
335
 
337
	var options = {
336
	var options = {
338
		zoom: zoomDefaut,
337
		zoom: zoomDefaut,
339
		center: latLng,
338
		center: latLng,
340
		mapTypeId: google.maps.MapTypeId.HYBRID,
339
		mapTypeId: google.maps.MapTypeId.HYBRID,
341
		mapTypeControlOptions: {
340
		mapTypeControlOptions: {
342
			mapTypeIds: ['OSM', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]}
341
			mapTypeIds: ['OSM', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]}
343
	};
342
	};
344
 
343
 
345
	// Ajout de la couche OSM à la carte
344
	// Ajout de la couche OSM à la carte
346
	osmMapType = new google.maps.ImageMapType({
345
	osmMapType = new google.maps.ImageMapType({
347
		getTileUrl: function(coord, zoom) {
346
		getTileUrl: function(coord, zoom) {
348
			return "http://tile.openstreetmap.org/" +
347
			return "http://tile.openstreetmap.org/" +
349
			zoom + "/" + coord.x + "/" + coord.y + ".png";
348
			zoom + "/" + coord.x + "/" + coord.y + ".png";
350
		},
349
		},
351
		tileSize: new google.maps.Size(256, 256),
350
		tileSize: new google.maps.Size(256, 256),
352
		isPng: true,
351
		isPng: true,
353
		alt: 'OpenStreetMap',
352
		alt: 'OpenStreetMap',
354
		name: 'OSM',
353
		name: 'OSM',
355
		maxZoom: 19
354
		maxZoom: 19
356
	});
355
	});
357
 
356
 
358
	// Création de la carte Google
357
	// Création de la carte Google
359
	this.map = new google.maps.Map(document.getElementById('map-canvas'), options); //affiche la google map dans la div map_canvas
358
	this.map = new google.maps.Map(document.getElementById('map-canvas'), options); //affiche la google map dans la div map_canvas
360
	this.map.mapTypes.set('OSM', osmMapType);
359
	this.map.mapTypes.set('OSM', osmMapType);
361
 
360
 
362
	// Création du Geocoder
361
	// Création du Geocoder
363
	this.geocoder = new google.maps.Geocoder();
362
	this.geocoder = new google.maps.Geocoder();
364
 
363
 
365
	// Marqueur google draggable
364
	// Marqueur google draggable
366
	this.marker = new google.maps.Marker({
365
	this.marker = new google.maps.Marker({
367
		map: this.map,
366
		map: this.map,
368
		draggable: true,
367
		draggable: true,
369
		title: 'Ma station',
368
		title: 'Ma station',
370
		icon: this.googleMapMarqueurUrl,
369
		icon: this.googleMapMarqueurUrl,
371
		position: latLng
370
		position: latLng
372
	});
371
	});
373
 
372
 
374
	this.initialiserMarker(latLng);
373
	this.initialiserMarker(latLng);
375
 
374
 
376
	// Tentative de geocalisation
375
	// Tentative de geocalisation
377
	if (navigator.geolocation) {
376
	if (navigator.geolocation) {
378
		navigator.geolocation.getCurrentPosition(function(position) {
377
		navigator.geolocation.getCurrentPosition(function(position) {
379
			var latitude = position.coords.latitude;
378
			var latitude = position.coords.latitude;
380
			var longitude = position.coords.longitude;
379
			var longitude = position.coords.longitude;
381
			this.latLng = new google.maps.LatLng(latitude, longitude);
380
			this.latLng = new google.maps.LatLng(latitude, longitude);
382
			this.deplacerMarker(this.latLng);
381
			this.deplacerMarker(this.latLng);
383
		});
382
		});
384
	}
383
	}
385
 
384
 
386
	// intéraction carte
385
	// intéraction carte
387
	$("#geolocaliser").on('click', this.geolocaliser.bind(this));
386
	$("#geolocaliser").on('click', this.geolocaliser.bind(this));
388
	google.maps.event.addListener(this.marker, 'dragend', this.surDeplacementMarker.bind(this));
387
	google.maps.event.addListener(this.marker, 'dragend', this.surDeplacementMarker.bind(this));
389
	google.maps.event.addListener(this.map, 'click', this.surClickDansCarte.bind(this));
388
	google.maps.event.addListener(this.map, 'click', this.surClickDansCarte.bind(this));
390
};
389
};
391
 
390
 
392
WidgetSaisie.prototype.initialiserMarker = function(latLng) {
391
WidgetSaisie.prototype.initialiserMarker = function(latLng) {
393
	if (this.marker != undefined) {
392
	if (this.marker != undefined) {
394
		this.marker.setPosition(latLng);
393
		this.marker.setPosition(latLng);
395
		this.map.setCenter(latLng);
394
		this.map.setCenter(latLng);
396
	}
395
	}
397
};
396
};
398
 
397
 
399
WidgetSaisie.prototype.deplacerMarker = function(latLng) {
398
WidgetSaisie.prototype.deplacerMarker = function(latLng) {
400
	if (this.marker != undefined) {
399
	if (this.marker != undefined) {
401
		this.marker.setPosition(latLng);
400
		this.marker.setPosition(latLng);
402
		this.map.setCenter(latLng);
401
		this.map.setCenter(latLng);
403
		this.mettreAJourMarkerPosition(latLng);
402
		this.mettreAJourMarkerPosition(latLng);
404
		this.trouverCommune(latLng);
403
		this.trouverCommune(latLng);
405
	}
404
	}
406
};
405
};
407
 
406
 
408
WidgetSaisie.prototype.mettreAJourMarkerPosition = function(latLng) {
407
WidgetSaisie.prototype.mettreAJourMarkerPosition = function(latLng) {
409
	var lat = latLng.lat().toFixed(5);
408
	var lat = latLng.lat().toFixed(5);
410
	var lng = latLng.lng().toFixed(5);
409
	var lng = latLng.lng().toFixed(5);
411
	this.remplirChampLatitude(lat);
410
	this.remplirChampLatitude(lat);
412
	this.remplirChampLongitude(lng);
411
	this.remplirChampLongitude(lng);
413
};
412
};
414
 
413
 
415
WidgetSaisie.prototype.remplirChampLatitude = function(latDecimale) {
414
WidgetSaisie.prototype.remplirChampLatitude = function(latDecimale) {
416
	var lat = Math.round(latDecimale * 100000) / 100000;
415
	var lat = Math.round(latDecimale * 100000) / 100000;
417
	$('#latitude').val(lat);
416
	$('#latitude').val(lat);
418
};
417
};
419
 
418
 
420
WidgetSaisie.prototype.remplirChampLongitude = function(lngDecimale) {
419
WidgetSaisie.prototype.remplirChampLongitude = function(lngDecimale) {
421
	var lng = Math.round(lngDecimale * 100000) / 100000;
420
	var lng = Math.round(lngDecimale * 100000) / 100000;
422
	$('#longitude').val(lng);
421
	$('#longitude').val(lng);
423
};
422
};
424
 
423
 
425
WidgetSaisie.prototype.trouverCommune = function(pos) {
424
WidgetSaisie.prototype.trouverCommune = function(pos) {
426
	var lthis = this;
425
	var lthis = this;
427
	$(function() {
426
	$(function() {
428
 
427
 
429
		var url_service = lthis.serviceNomCommuneUrl;
428
		var url_service = lthis.serviceNomCommuneUrl;
430
 
429
 
431
		var urlNomCommuneFormatee = url_service.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
430
		var urlNomCommuneFormatee = url_service.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
432
		$.ajax({
431
		$.ajax({
433
			url : urlNomCommuneFormatee,
432
			url : urlNomCommuneFormatee,
434
			type : "GET",
433
			type : "GET",
435
			dataType : "jsonp",
434
			dataType : "jsonp",
436
			beforeSend : function() {
435
			beforeSend : function() {
437
				$(".commune-info").empty();
436
				$(".commune-info").empty();
438
				$("#dialogue-erreur .alert-txt").empty();
437
				$("#dialogue-erreur .alert-txt").empty();
439
			},
438
			},
440
			success : function(data, textStatus, jqXHR) {
439
			success : function(data, textStatus, jqXHR) {
441
				$(".commune-info").empty();
440
				$(".commune-info").empty();
442
				$("#commune-nom").append(data.nom);
441
				$("#commune-nom").append(data.nom);
443
				$("#commune-code-insee").append(data.codeINSEE);
442
				$("#commune-code-insee").append(data.codeINSEE);
444
				$("#marqueur-commune").data('commune', {'nom' : data.nom, 'codeInsee' : data.codeINSEE});
443
				$("#marqueur-commune").data('commune', {'nom' : data.nom, 'codeInsee' : data.codeINSEE});
445
			},
444
			},
446
			statusCode : {
445
			statusCode : {
447
			    500 : function(jqXHR, textStatus, errorThrown) {
446
			    500 : function(jqXHR, textStatus, errorThrown) {
448
					if (this.debug) {
447
					if (this.debug) {
449
						$("#dialogue-erreur .alert-txt").append('<p id="msg">Un problème est survenu lors de l\'appel au service fournissante le nom des communes.</p>');
448
						$("#dialogue-erreur .alert-txt").append('<p id="msg">Un problème est survenu lors de l\'appel au service fournissante le nom des communes.</p>');
450
						reponse = jQuery.parseJSON(jqXHR.responseText);
449
						reponse = jQuery.parseJSON(jqXHR.responseText);
451
						var erreurMsg = "";
450
						var erreurMsg = "";
452
						if (reponse != null) {
451
						if (reponse != null) {
453
							$.each(reponse, function (cle, valeur) {
452
							$.each(reponse, function (cle, valeur) {
454
								erreurMsg += valeur + "<br />";
453
								erreurMsg += valeur + "<br />";
455
							});
454
							});
456
						}
455
						}
457
 
456
 
458
						$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
457
						$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
459
					}
458
					}
460
			    }
459
			    }
461
			},
460
			},
462
			error : function(jqXHR, textStatus, errorThrown) {
461
			error : function(jqXHR, textStatus, errorThrown) {
463
				if (this.debug) {
462
				if (this.debug) {
464
					$("#dialogue-erreur .alert-txt").append('<p class="msg">Une erreur Ajax est survenue lors de la recherche de la commune.</p>');
463
					$("#dialogue-erreur .alert-txt").append('<p class="msg">Une erreur Ajax est survenue lors de la recherche de la commune.</p>');
465
					reponse = jQuery.parseJSON(jqXHR.responseText);
464
					reponse = jQuery.parseJSON(jqXHR.responseText);
466
					var erreurMsg = "";
465
					var erreurMsg = "";
467
					if (reponse != null) {
466
					if (reponse != null) {
468
						$.each(reponse, function (cle, valeur) {
467
						$.each(reponse, function (cle, valeur) {
469
							erreurMsg += valeur + "<br />";
468
							erreurMsg += valeur + "<br />";
470
						});
469
						});
471
					}
470
					}
472
 
471
 
473
					$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
472
					$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
474
				}
473
				}
475
			},
474
			},
476
			complete : function(jqXHR, textStatus) {
475
			complete : function(jqXHR, textStatus) {
477
				var debugMsg = extraireEnteteDebug(jqXHR);
476
				var debugMsg = extraireEnteteDebug(jqXHR);
478
				if (debugMsg != '') {
477
				if (debugMsg != '') {
479
					if (this.debug) {
478
					if (this.debug) {
480
						$("#dialogue-erreur .alert-txt").append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
479
						$("#dialogue-erreur .alert-txt").append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
481
					}
480
					}
482
				}
481
				}
483
				if ($("#dialogue-erreur .msg").length > 0) {
482
				if ($("#dialogue-erreur .msg").length > 0) {
484
					$("#dialogue-erreur").show();
483
					$("#dialogue-erreur").show();
485
				}
484
				}
486
			}
485
			}
487
		});
486
		});
488
	});
487
	});
489
};
488
};
490
 
489
 
491
WidgetSaisie.prototype.testerLancementRequeteIdentite = function(event) {
490
WidgetSaisie.prototype.testerLancementRequeteIdentite = function(event) {
492
	if (event.which == 13) {
491
	if (event.which == 13) {
493
		this.requeterIdentite();
492
		this.requeterIdentite();
494
		this.event.preventDefault();
493
		this.event.preventDefault();
495
		this.event.stopPropagation();
494
		this.event.stopPropagation();
496
	}
495
	}
497
};
496
};
498
 
497
 
499
WidgetSaisie.prototype.requeterIdentite = function() {
498
WidgetSaisie.prototype.requeterIdentite = function() {
500
	var lthis = this;
499
	var lthis = this;
501
	var courriel = $("#courriel").val();
500
	var courriel = $("#courriel").val();
502
	var urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;
501
	var urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;
-
 
502
	if (courriel != '') {
503
	$.ajax({
503
		$.ajax({
504
		url : urlAnnuaire,
504
			url : urlAnnuaire,
505
		type : "GET",
505
			type : "GET",
506
		success : function(data, textStatus, jqXHR) {
506
			success : function(data, textStatus, jqXHR) {
507
			//console.log('SUCCESS:'+textStatus);
507
				//console.log('SUCCESS:'+textStatus);
508
			if (data != undefined && data[courriel] != undefined) {
508
				if (data != undefined && data[courriel] != undefined) {
509
				var infos = data[courriel];
509
					var infos = data[courriel];
510
				$("#id_utilisateur").val(infos.id);
510
					$("#id_utilisateur").val(infos.id);
511
				$("#prenom").val(infos.prenom);
511
					$("#prenom").val(infos.prenom);
512
				$("#nom").val(infos.nom);
512
					$("#nom").val(infos.nom);
513
				$("#courriel_confirmation").val(courriel);
513
					$("#courriel_confirmation").val(courriel);
514
				$("#prenom, #nom, #courriel_confirmation").attr('disabled', 'disabled');
514
					$("#prenom, #nom, #courriel_confirmation").attr('disabled', 'disabled');
515
				lthis.focusChampFormulaire();
515
					lthis.focusChampFormulaire();
516
				lthis.masquerPanneau("#dialogue-courriel-introuvable");
516
					lthis.masquerPanneau("#dialogue-courriel-introuvable");
517
			} else {
517
				} else {
-
 
518
					lthis.surErreurCompletionCourriel();
-
 
519
				}
-
 
520
			},
-
 
521
			error : function(jqXHR, textStatus, errorThrown) {
-
 
522
				//console.log('ERREUR :'+textStatus);
518
				lthis.surErreurCompletionCourriel();
523
				lthis.surErreurCompletionCourriel();
-
 
524
			},
-
 
525
			complete : function(jqXHR, textStatus) {
-
 
526
				//console.log('COMPLETE :'+textStatus);
-
 
527
				// @TODO harmoniser class="hidden" VS style="display:none;"
-
 
528
				$("#zone-prenom-nom").removeClass("hidden").show();
-
 
529
				$("#zone-courriel-confirmation").removeClass("hidden").show();
-
 
530
				
519
			}
531
			}
520
		},
532
		});
521
		error : function(jqXHR, textStatus, errorThrown) {
-
 
522
			//console.log('ERREUR :'+textStatus);
-
 
523
			lthis.surErreurCompletionCourriel();
-
 
524
		},
-
 
525
		complete : function(jqXHR, textStatus) {
-
 
526
			//console.log('COMPLETE :'+textStatus);
-
 
527
			// @TODO harmoniser class="hidden" VS style="display:none;"
-
 
528
			$("#zone-prenom-nom").removeClass("hidden").show();
-
 
529
			$("#zone-courriel-confirmation").removeClass("hidden").show();
-
 
530
			
-
 
531
		}
533
	}
532
	});
-
 
533
};
534
};
534
 
535
 
535
WidgetSaisie.prototype.focusChampFormulaire = function() {
536
WidgetSaisie.prototype.focusChampFormulaire = function() {
536
	$("#date").focus();
537
	$("#date").focus();
537
}
538
}
538
 
539
 
539
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
540
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
540
	$("#prenom, #nom, #courriel_confirmation").val('');
541
	$("#prenom, #nom, #courriel_confirmation").val('');
541
	$("#prenom, #nom, #courriel_confirmation").removeAttr('disabled');
542
	$("#prenom, #nom, #courriel_confirmation").removeAttr('disabled');
542
	this.afficherPanneau("#dialogue-courriel-introuvable");
543
	this.afficherPanneau("#dialogue-courriel-introuvable");
543
};
544
};
544
 
545
 
545
WidgetSaisie.prototype.chargerInfoObs = function() {
546
WidgetSaisie.prototype.chargerInfoObs = function() {
546
	var urlObs = this.serviceObsUrl + '/' + this.obsId;
547
	var urlObs = this.serviceObsUrl + '/' + this.obsId;
547
	var lthis = this;
548
	var lthis = this;
548
	$.ajax({
549
	$.ajax({
549
		url: urlObs,
550
		url: urlObs,
550
		type: 'GET',
551
		type: 'GET',
551
		success: function(data, textStatus, jqXHR) {
552
		success: function(data, textStatus, jqXHR) {
552
			if (data != undefined && data != "") {
553
			if (data != undefined && data != "") {
553
				this.prechargerForm(data);
554
				this.prechargerForm(data);
554
			} else {
555
			} else {
555
				lthis.surErreurChargementInfosObs();
556
				lthis.surErreurChargementInfosObs();
556
			}
557
			}
557
		},
558
		},
558
		error: function(jqXHR, textStatus, errorThrown) {
559
		error: function(jqXHR, textStatus, errorThrown) {
559
			lthis.surErreurChargementInfosObs();
560
			lthis.surErreurChargementInfosObs();
560
		}
561
		}
561
	});
562
	});
562
};
563
};
563
 
564
 
564
// @TODO faire mieux que ça !
565
// @TODO faire mieux que ça !
565
WidgetSaisie.prototype.surErreurChargementInfosObs = function() {
566
WidgetSaisie.prototype.surErreurChargementInfosObs = function() {
566
	alert("Erreur lors du chargement de l'observation");
567
	alert("Erreur lors du chargement de l'observation");
567
}
568
}
568
 
569
 
569
WidgetSaisie.prototype.prechargerForm = function(data) {
570
WidgetSaisie.prototype.prechargerForm = function(data) {
570
 
571
 
571
	$("#milieu").val(data.milieu);
572
	$("#milieu").val(data.milieu);
572
 
573
 
573
	$("#carte-recherche").val(data.zoneGeo);
574
	$("#carte-recherche").val(data.zoneGeo);
574
	$("#commune-nom").text(data.zoneGeo);
575
	$("#commune-nom").text(data.zoneGeo);
575
 
576
 
576
	if(data.hasOwnProperty("codeZoneGeo")) {
577
	if(data.hasOwnProperty("codeZoneGeo")) {
577
		// TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
578
		// TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
578
		$("#commune-code-insee").text(data.codeZoneGeo.replace('INSEE-C:', ''));
579
		$("#commune-code-insee").text(data.codeZoneGeo.replace('INSEE-C:', ''));
579
	}
580
	}
580
 
581
 
581
	if(data.hasOwnProperty("latitude") && data.hasOwnProperty("longitude")) {
582
	if(data.hasOwnProperty("latitude") && data.hasOwnProperty("longitude")) {
582
		var latLng = new google.maps.LatLng(data.latitude, data.longitude);
583
		var latLng = new google.maps.LatLng(data.latitude, data.longitude);
583
		this.mettreAJourMarkerPosition(latLng);
584
		this.mettreAJourMarkerPosition(latLng);
584
		this.marker.setPosition(latLng);
585
		this.marker.setPosition(latLng);
585
		this.map.setCenter(latLng);
586
		this.map.setCenter(latLng);
586
		this.map.setZoom(16);
587
		this.map.setZoom(16);
587
	}
588
	}
588
};
589
};
589
 
590
 
590
WidgetSaisie.prototype.configurerFormValidator = function() {
591
WidgetSaisie.prototype.configurerFormValidator = function() {
591
	$.validator.addMethod(
592
	$.validator.addMethod(
592
		"dateCel",
593
		"dateCel",
593
		function (value, element) {
594
		function (value, element) {
594
			return value == "" || (/^[0-9]{2}[-\/][0-9]{2}[-\/][0-9]{4}$/.test(value));
595
			return value == "" || (/^[0-9]{2}[-\/][0-9]{2}[-\/][0-9]{4}$/.test(value));
595
		},
596
		},
596
		"Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.");
597
		"Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.");
597
	$.extend($.validator.defaults, {
598
	$.extend($.validator.defaults, {
598
		errorClass: "control-group error",
599
		errorClass: "control-group error",
599
		validClass: "control-group success",
600
		validClass: "control-group success",
600
		errorElement: "span",
601
		errorElement: "span",
601
		highlight: function(element, errorClass, validClass) {
602
		highlight: function(element, errorClass, validClass) {
602
			if (element.type === 'radio') {
603
			if (element.type === 'radio') {
603
				this.findByName(element.name).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
604
				this.findByName(element.name).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
604
			} else {
605
			} else {
605
				$(element).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
606
				$(element).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
606
			}
607
			}
607
		},
608
		},
608
		unhighlight: function(element, errorClass, validClass) {
609
		unhighlight: function(element, errorClass, validClass) {
609
			if (element.type === 'radio') {
610
			if (element.type === 'radio') {
610
				this.findByName(element.name).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
611
				this.findByName(element.name).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
611
			} else {
612
			} else {
612
				if ($(element).attr('id') == 'taxon') {
613
				if ($(element).attr('id') == 'taxon') {
613
					if ($("#taxon").val() != '') {
614
					if ($("#taxon").val() != '') {
614
						// Si le taxon n'est pas lié au référentiel, on vide le data associé
615
						// Si le taxon n'est pas lié au référentiel, on vide le data associé
615
						if ($("#taxon").data("value") != $("#taxon").val()) {
616
						if ($("#taxon").data("value") != $("#taxon").val()) {
616
							$("#taxon").data("numNomSel","");
617
							$("#taxon").data("numNomSel","");
617
							$("#taxon").data("nomRet","");
618
							$("#taxon").data("nomRet","");
618
							$("#taxon").data("numNomRet","");
619
							$("#taxon").data("numNomRet","");
619
							$("#taxon").data("nt","");
620
							$("#taxon").data("nt","");
620
							$("#taxon").data("famille","");
621
							$("#taxon").data("famille","");
621
						}
622
						}
622
						$("#taxon-input-groupe").removeClass(errorClass).addClass(validClass);
623
						$("#taxon-input-groupe").removeClass(errorClass).addClass(validClass);
623
						$(element).next(" span.help-inline").remove();
624
						$(element).next(" span.help-inline").remove();
624
					}
625
					}
625
				} else {
626
				} else {
626
					$(element).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
627
					$(element).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
627
					$(element).next(" span.help-inline").remove();
628
					$(element).next(" span.help-inline").remove();
628
				}
629
				}
629
			}
630
			}
630
		}
631
		}
631
	});
632
	});
632
};
633
};
633
 
634
 
634
WidgetSaisie.prototype.definirReglesFormValidator = function() {
635
WidgetSaisie.prototype.definirReglesFormValidator = function() {
635
	$("#form-observateur").validate({
636
	$("#form-observateur").validate({
636
		rules: {
637
		rules: {
637
			courriel : {
638
			courriel : {
638
				required : true,
639
				required : true,
639
				email : true},
640
				email : true},
640
			courriel_confirmation : {
641
			courriel_confirmation : {
641
				required : true,
642
				required : true,
642
				equalTo: "#courriel"}
643
				equalTo: "#courriel"}
643
		}
644
		}
644
	});
645
	});
645
	$("#form-station").validate({
646
	$("#form-station").validate({
646
		rules: {
647
		rules: {
647
			latitude : {
648
			latitude : {
648
				range: [-90, 90]},
649
				range: [-90, 90]},
649
			longitude : {
650
			longitude : {
650
				range: [-180, 180]}
651
				range: [-180, 180]}
651
		}
652
		}
652
	});
653
	});
653
	$("#form-obs").validate({
654
	$("#form-obs").validate({
654
		rules: {
655
		rules: {
655
			date : "dateCel",
656
			date : "dateCel",
656
			taxon : "required"
657
			taxon : "required"
657
		}
658
		}
658
	});
659
	});
659
};
660
};
660
 
661
 
661
WidgetSaisie.prototype.configurerDatePicker = function(selector) {
662
WidgetSaisie.prototype.configurerDatePicker = function(selector) {
662
	$.datepicker.setDefaults($.datepicker.regional["fr"]);
663
	$.datepicker.setDefaults($.datepicker.regional["fr"]);
663
	$(selector).datepicker({
664
	$(selector).datepicker({
664
		dateFormat: "dd/mm/yy",
665
		dateFormat: "dd/mm/yy",
665
		maxDate: new Date,
666
		maxDate: new Date,
666
		showOn: "button",
667
		showOn: "button",
667
		buttonImageOnly: true,
668
		buttonImageOnly: true,
668
		buttonImage: this.calendrierIconeUrl,
669
		buttonImage: this.calendrierIconeUrl,
669
		buttonText: "Afficher le calendrier pour saisir la date.",
670
		buttonText: "Afficher le calendrier pour saisir la date.",
670
		showButtonPanel: true,
671
		showButtonPanel: true,
671
		onSelect: function(date) {
672
		onSelect: function(date) {
672
			$(this).valid();
673
			$(this).valid();
673
		}
674
		}
674
	});
675
	});
675
	$(selector + ' + img.ui-datepicker-trigger').appendTo(selector + '-icone.add-on');
676
	$(selector + ' + img.ui-datepicker-trigger').appendTo(selector + '-icone.add-on');
676
};
677
};
677
 
678
 
678
WidgetSaisie.prototype.fermerPanneauAlert = function() {
679
WidgetSaisie.prototype.fermerPanneauAlert = function() {
679
	$(this).parentsUntil(".zone-alerte", ".alert").hide();
680
	$(this).parentsUntil(".zone-alerte", ".alert").hide();
680
};
681
};
681
 
682
 
682
WidgetSaisie.prototype.formaterNom = function() {
683
WidgetSaisie.prototype.formaterNom = function() {
683
	$(this).val($(this).val().toUpperCase());
684
	$(this).val($(this).val().toUpperCase());
684
};
685
};
685
 
686
 
686
WidgetSaisie.prototype.formaterPrenom = function() {
687
WidgetSaisie.prototype.formaterPrenom = function() {
687
	var prenom = new Array();
688
	var prenom = new Array();
688
	var mots = $(this).val().split(' ');
689
	var mots = $(this).val().split(' ');
689
	for (var i = 0; i < mots.length; i++) {
690
	for (var i = 0; i < mots.length; i++) {
690
		var mot = mots[i];
691
		var mot = mots[i];
691
		if (mot.indexOf('-') >= 0) {
692
		if (mot.indexOf('-') >= 0) {
692
			var prenomCompose = new Array();
693
			var prenomCompose = new Array();
693
			var motsComposes = mot.split('-');
694
			var motsComposes = mot.split('-');
694
		    for (var j = 0; j < motsComposes.length; j++) {
695
		    for (var j = 0; j < motsComposes.length; j++) {
695
		    	var motSimple = motsComposes[j];
696
		    	var motSimple = motsComposes[j];
696
		    	var motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
697
		    	var motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
697
		    	prenomCompose.push(motMajuscule);
698
		    	prenomCompose.push(motMajuscule);
698
		    }
699
		    }
699
		    prenom.push(prenomCompose.join('-'));
700
		    prenom.push(prenomCompose.join('-'));
700
		} else {
701
		} else {
701
			var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
702
			var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
702
			prenom.push(motMajuscule);
703
			prenom.push(motMajuscule);
703
		}
704
		}
704
	}
705
	}
705
	$(this).val(prenom.join(' '));
706
	$(this).val(prenom.join(' '));
706
};
707
};
707
 
708
 
708
WidgetSaisie.prototype.basculerAffichageAide = function()  {
709
WidgetSaisie.prototype.basculerAffichageAide = function()  {
709
	if ($(this).hasClass('btn-warning')) {
710
	if ($(this).hasClass('btn-warning')) {
710
		$(".has-tooltip").tooltip('enable');
711
		$(".has-tooltip").tooltip('enable');
711
		$(this).removeClass('btn-warning').addClass('btn-success');
712
		$(this).removeClass('btn-warning').addClass('btn-success');
712
		$('#btn-aide-txt', this).text("Désactiver l'aide");
713
		$('#btn-aide-txt', this).text("Désactiver l'aide");
713
	} else {
714
	} else {
714
		$(".has-tooltip").tooltip('disable');
715
		$(".has-tooltip").tooltip('disable');
715
		$(this).removeClass('btn-success').addClass('btn-warning');
716
		$(this).removeClass('btn-success').addClass('btn-warning');
716
		$('#btn-aide-txt', this).text("Activer l'aide");
717
		$('#btn-aide-txt', this).text("Activer l'aide");
717
	}
718
	}
718
};
719
};
719
 
720
 
720
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
721
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
721
	this.afficherPanneau("#dialogue-bloquer-copier-coller");
722
	this.afficherPanneau("#dialogue-bloquer-copier-coller");
722
	return false;
723
	return false;
723
};
724
};
724
 
725
 
725
WidgetSaisie.prototype.basculerAffichageCoord = function() {
726
WidgetSaisie.prototype.basculerAffichageCoord = function() {
726
	$("a.afficher-coord").toggle();
727
	$("a.afficher-coord").toggle();
727
	$("#coordonnees-geo").toggle('slow');
728
	$("#coordonnees-geo").toggle('slow');
728
	//valeur false pour que le lien ne soit pas suivi
729
	//valeur false pour que le lien ne soit pas suivi
729
	return false;
730
	return false;
730
};
731
};
731
 
732
 
732
/**
733
/**
733
 * Ajoute une observation saisie dans le formulaire à la liste des observations à transmettre
734
 * Ajoute une observation saisie dans le formulaire à la liste des observations à transmettre
734
 */
735
 */
735
WidgetSaisie.prototype.ajouterObs = function() {
736
WidgetSaisie.prototype.ajouterObs = function() {
736
	if (this.validerFormulaire() == true) {
737
	if (this.validerFormulaire() == true) {
737
		this.obsNbre = this.obsNbre + 1;
738
		this.obsNbre = this.obsNbre + 1;
738
		$(".obs-nbre").text(this.obsNbre);
739
		$(".obs-nbre").text(this.obsNbre);
739
		$(".obs-nbre").triggerHandler('changement');
740
		$(".obs-nbre").triggerHandler('changement');
740
		this.afficherObs();
741
		this.afficherObs();
741
		this.stockerObsData();
742
		this.stockerObsData();
742
		this.supprimerMiniatures();
743
		this.supprimerMiniatures();
743
		if(! this.especeImposee) {
744
		if(! this.especeImposee) {
744
			$("#taxon").val("");
745
			$("#taxon").val("");
745
			$("#taxon").data("numNomSel",undefined);
746
			$("#taxon").data("numNomSel",undefined);
746
		}
747
		}
747
		$('#barre-progression-upload').attr('aria-valuemax', this.obsNbre);
748
		$('#barre-progression-upload').attr('aria-valuemax', this.obsNbre);
748
		$('#barre-progression-upload .sr-only').text('0/'+this.obsNbre+" observations transmises");
749
		$('#barre-progression-upload .sr-only').text('0/'+this.obsNbre+" observations transmises");
749
	} else {
750
	} else {
750
		this.afficherPanneau('#dialogue-form-invalide');
751
		this.afficherPanneau('#dialogue-form-invalide');
751
	}
752
	}
752
};
753
};
753
 
754
 
754
/**
755
/**
755
 * Affiche une observation dans la liste des observations à transmettre
756
 * Affiche une observation dans la liste des observations à transmettre
756
 */
757
 */
757
WidgetSaisie.prototype.afficherObs = function() {
758
WidgetSaisie.prototype.afficherObs = function() {
758
	$("#liste-obs").prepend(
759
	$("#liste-obs").prepend(
759
		'<div id="obs'+this.obsNbre+'" class="row-fluid obs obs'+this.obsNbre+'">'+
760
		'<div id="obs'+this.obsNbre+'" class="row-fluid obs obs'+this.obsNbre+'">'+
760
			'<div class="span12">'+
761
			'<div class="span12">'+
761
				'<div class="well">'+
762
				'<div class="well">'+
762
					'<div class="obs-action pull-right has-tooltip" data-placement="bottom" '+
763
					'<div class="obs-action pull-right has-tooltip" data-placement="bottom" '+
763
						'title="Supprimer cette observation de la liste à transmettre">'+
764
						'title="Supprimer cette observation de la liste à transmettre">'+
764
						'<button class="btn btn-danger supprimer-obs" value="'+this.obsNbre+'" title="'+this.obsNbre+'">'+
765
						'<button class="btn btn-danger supprimer-obs" value="'+this.obsNbre+'" title="'+this.obsNbre+'">'+
765
							'<i class="icon-trash icon-white"></i>'+
766
							'<i class="icon-trash icon-white"></i>'+
766
						'</button>'+
767
						'</button>'+
767
					'</div> '+
768
					'</div> '+
768
					'<div class="row-fluid">'+
769
					'<div class="row-fluid">'+
769
						'<div class="thumbnail span2">'+
770
						'<div class="thumbnail span2">'+
770
						this.ajouterImgMiniatureAuTransfert()+
771
						this.ajouterImgMiniatureAuTransfert()+
771
						'</div>'+
772
						'</div>'+
772
						'<div class="span9">'+
773
						'<div class="span9">'+
773
							'<ul class="unstyled">'+
774
							'<ul class="unstyled">'+
774
								'<li>'+
775
								'<li>'+
775
									'<span class="nom-sci">'+$("#taxon").val()+'</span> '+
776
									'<span class="nom-sci">'+$("#taxon").val()+'</span> '+
776
									this.ajouterNumNomSel()+'<span class="referentiel-obs">'+
777
									this.ajouterNumNomSel()+'<span class="referentiel-obs">'+
777
									($("#taxon").data("numNomSel") == undefined ? '' : '['+ this.nomSciReferentiel +']')+'</span>'+
778
									($("#taxon").data("numNomSel") == undefined ? '' : '['+ this.nomSciReferentiel +']')+'</span>'+
778
									' observé à '+
779
									' observé à '+
779
									'<span class="commune">'+$('#commune-nom').text()+'</span> '+
780
									'<span class="commune">'+$('#commune-nom').text()+'</span> '+
780
									'('+$('#commune-code-insee').text()+') ['+$("#latitude").val()+' / '+$("#longitude").val()+']'+
781
									'('+$('#commune-code-insee').text()+') ['+$("#latitude").val()+' / '+$("#longitude").val()+']'+
781
									' le '+
782
									' le '+
782
									'<span class="date">'+$("#date").val()+'</span>'+
783
									'<span class="date">'+$("#date").val()+'</span>'+
783
								'</li>'+
784
								'</li>'+
784
								'<li>'+
785
								'<li>'+
785
									'<span>Lieu-dit :</span> '+$('#lieudit').val()+' '+
786
									'<span>Lieu-dit :</span> '+$('#lieudit').val()+' '+
786
									'<span>Station :</span> '+$('#station').val()+' '+
787
									'<span>Station :</span> '+$('#station').val()+' '+
787
									'<span>Milieu :</span> '+$('#milieu').val()+' '+
788
									'<span>Milieu :</span> '+$('#milieu').val()+' '+
788
								'</li>'+
789
								'</li>'+
789
								'<li>'+
790
								'<li>'+
790
									'Commentaires : <span class="discretion">'+$("#notes").val()+'</span>'+
791
									'Commentaires : <span class="discretion">'+$("#notes").val()+'</span>'+
791
								'</li>'+
792
								'</li>'+
792
							'</ul>'+
793
							'</ul>'+
793
						'</div>'+
794
						'</div>'+
794
					'</div>'+
795
					'</div>'+
795
				'</div>'+
796
				'</div>'+
796
			'</div>'+
797
			'</div>'+
797
		'</div>');
798
		'</div>');
798
	$('#zone-liste-obs').removeClass("hidden").show();
799
	$('#zone-liste-obs').removeClass("hidden").show();
799
};
800
};
800
 
801
 
801
WidgetSaisie.prototype.stockerObsData = function() {
802
WidgetSaisie.prototype.stockerObsData = function() {
802
	var lthis = this;
803
	var lthis = this;
803
	$("#liste-obs").data('obsId'+this.obsNbre, {
804
	$("#liste-obs").data('obsId'+this.obsNbre, {
804
		'date' : $("#date").val(),
805
		'date' : $("#date").val(),
805
		'notes' : $("#notes").val(),
806
		'notes' : $("#notes").val(),
806
 
807
 
807
		'nom_sel' : $("#taxon").val(),
808
		'nom_sel' : $("#taxon").val(),
808
		'num_nom_sel' : $("#taxon").data("numNomSel"),
809
		'num_nom_sel' : $("#taxon").data("numNomSel"),
809
		'nom_ret' : $("#taxon").data("nomRet"),
810
		'nom_ret' : $("#taxon").data("nomRet"),
810
		'num_nom_ret' : $("#taxon").data("numNomRet"),
811
		'num_nom_ret' : $("#taxon").data("numNomRet"),
811
		'num_taxon' : $("#taxon").data("nt"),
812
		'num_taxon' : $("#taxon").data("nt"),
812
		'famille' : $("#taxon").data("famille"),
813
		'famille' : $("#taxon").data("famille"),
813
		'referentiel' : ($("#taxon").data("numNomSel") == undefined ? '' : lthis.nomSciReferentiel),
814
		'referentiel' : ($("#taxon").data("numNomSel") == undefined ? '' : lthis.nomSciReferentiel),
814
 
815
 
815
		'latitude' : $("#latitude").val(),
816
		'latitude' : $("#latitude").val(),
816
		'longitude' : $("#longitude").val(),
817
		'longitude' : $("#longitude").val(),
817
		'commune_nom' : $("#commune-nom").text(),
818
		'commune_nom' : $("#commune-nom").text(),
818
		'commune_code_insee' : $("#commune-code-insee").text(),
819
		'commune_code_insee' : $("#commune-code-insee").text(),
819
		'lieudit' : $("#lieudit").val(),
820
		'lieudit' : $("#lieudit").val(),
820
		'station' : $("#station").val(),
821
		'station' : $("#station").val(),
821
		'milieu' : $("#milieu").val(),
822
		'milieu' : $("#milieu").val(),
822
 
823
 
823
		//Ajout des champs images
824
		//Ajout des champs images
824
		'image_nom' : lthis.getNomsImgsOriginales(),
825
		'image_nom' : lthis.getNomsImgsOriginales(),
825
		'image_b64' : lthis.getB64ImgsOriginales()
826
		'image_b64' : lthis.getB64ImgsOriginales(),
-
 
827
 
-
 
828
		// Ajout des champs étendus de l'obs
-
 
829
		'obs_etendue': lthis.getObsChpEtendus()
826
	});
830
	});
827
};
831
};
-
 
832
 
-
 
833
/**
-
 
834
 * Retourne un Array contenant les valeurs des champs étendus
-
 
835
 */
-
 
836
WidgetSaisie.prototype.getObsChpEtendus = function() {
-
 
837
	var champs = [];
-
 
838
 
-
 
839
	$('.obs-chp-etendu').each(function() {
-
 
840
		var valeur = $(this).val(),
-
 
841
			cle = $(this).attr('name'),
-
 
842
			label = $(this).data('label');
-
 
843
		if (valeur != '') {
-
 
844
			var chpEtendu = {cle: cle, label: label, valeur: valeur};
-
 
845
			champs.push(chpEtendu);
-
 
846
		}
-
 
847
	});
-
 
848
	return champs;
-
 
849
}
828
 
850
 
829
WidgetSaisie.prototype.surChangementReferentiel = function() {
851
WidgetSaisie.prototype.surChangementReferentiel = function() {
830
	this.nomSciReferentiel = $('#referentiel').val();
852
	this.nomSciReferentiel = $('#referentiel').val();
831
	$('#taxon').val('');
853
	$('#taxon').val('');
832
	this.initialiserAutocompleteCommune();
854
	this.initialiserAutocompleteCommune();
833
	this.initialiserGoogleMap();
855
	this.initialiserGoogleMap();
834
};
856
};
835
 
857
 
836
WidgetSaisie.prototype.surChangementNbreObs = function() {
858
WidgetSaisie.prototype.surChangementNbreObs = function() {
837
	if (this.obsNbre == 0) {
859
	if (this.obsNbre == 0) {
838
		$("#transmettre-obs").attr('disabled', 'disabled');
860
		$("#transmettre-obs").attr('disabled', 'disabled');
839
		$("#ajouter-obs").removeAttr('disabled');
861
		$("#ajouter-obs").removeAttr('disabled');
840
	} else if (this.obsNbre > 0 && this.obsNbre < this.obsMaxNbre) {
862
	} else if (this.obsNbre > 0 && this.obsNbre < this.obsMaxNbre) {
841
		$("#transmettre-obs").removeAttr('disabled');
863
		$("#transmettre-obs").removeAttr('disabled');
842
		$("#ajouter-obs").removeAttr('disabled');
864
		$("#ajouter-obs").removeAttr('disabled');
843
	} else if (this.obsNbre >= this.obsMaxNbre) {
865
	} else if (this.obsNbre >= this.obsMaxNbre) {
844
		$("#ajouter-obs").attr('disabled', 'disabled');
866
		$("#ajouter-obs").attr('disabled', 'disabled');
845
		this.afficherPanneau("#dialogue-bloquer-creer-obs");
867
		this.afficherPanneau("#dialogue-bloquer-creer-obs");
846
	}
868
	}
847
};
869
};
848
 
870
 
849
WidgetSaisie.prototype.transmettreObs = function() {
871
WidgetSaisie.prototype.transmettreObs = function() {
850
	var observations = $("#liste-obs").data();
872
	var observations = $("#liste-obs").data();
851
	if (observations == undefined || jQuery.isEmptyObject(observations)) {
873
	if (observations == undefined || jQuery.isEmptyObject(observations)) {
852
		this.afficherPanneau("#dialogue-zero-obs");
874
		this.afficherPanneau("#dialogue-zero-obs");
853
	} else {
875
	} else {
854
		this.nbObsEnCours = 1;
876
		this.nbObsEnCours = 1;
855
		this.nbObsTransmises = 0;
877
		this.nbObsTransmises = 0;
856
		this.totalObsATransmettre = $.map(observations, function(n, i) { return i; }).length;
878
		this.totalObsATransmettre = $.map(observations, function(n, i) { return i; }).length;
857
		this.depilerObsPourEnvoi();
879
		this.depilerObsPourEnvoi();
858
	}
880
	}
859
	return false;
881
	return false;
860
};
882
};
861
 
883
 
862
WidgetSaisie.prototype.depilerObsPourEnvoi = function() {
884
WidgetSaisie.prototype.depilerObsPourEnvoi = function() {
863
	var observations = $("#liste-obs").data();
885
	var observations = $("#liste-obs").data();
864
	// la boucle est factice car on utilise un tableau
886
	// la boucle est factice car on utilise un tableau
865
	// dont on a besoin de n'extraire que le premier élément
887
	// dont on a besoin de n'extraire que le premier élément
866
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
888
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
867
	// TODO: utiliser var.keys quand ça sera plus répandu
889
	// TODO: utiliser var.keys quand ça sera plus répandu
868
	// ou bien utiliser un vrai tableau et pas un objet
890
	// ou bien utiliser un vrai tableau et pas un objet
869
	for (var obsNum in observations) {
891
	for (var obsNum in observations) {
870
		var obsATransmettre = {
892
		var obsATransmettre = {
871
			'projet' : this.tagProjet,
893
			'projet' : this.tagProjet,
872
			'tag-obs' : this.tagObs,
894
			'tag-obs' : this.tagObs,
873
			'tag-img' : this.tagImg
895
			'tag-img' : this.tagImg
874
		};
896
		};
875
		var utilisateur = {
897
		var utilisateur = {
876
			id_utilisateur : $("#id_utilisateur").val(),
898
			id_utilisateur : $("#id_utilisateur").val(),
877
			prenom : $("#prenom").val(),
899
			prenom : $("#prenom").val(),
878
			nom : $("#nom").val(),
900
			nom : $("#nom").val(),
879
			courriel : $("#courriel").val()
901
			courriel : $("#courriel").val()
880
		};
902
		};
881
		obsATransmettre['utilisateur'] = utilisateur;
903
		obsATransmettre['utilisateur'] = utilisateur;
882
		obsATransmettre[obsNum] = observations[obsNum];
904
		obsATransmettre[obsNum] = observations[obsNum];
883
		var idObsNumerique = obsNum.replace('obsId', '');
905
		var idObsNumerique = obsNum.replace('obsId', '');
884
		if(idObsNumerique != "") {
906
		if(idObsNumerique != "") {
885
			this.envoyerObsAuCel(idObsNumerique, obsATransmettre);
907
			this.envoyerObsAuCel(idObsNumerique, obsATransmettre);
886
		}
908
		}
887
 
909
 
888
		break;
910
		break;
889
	}
911
	}
890
};
912
};
891
 
913
 
892
WidgetSaisie.prototype.mettreAJourProgression = function() {
914
WidgetSaisie.prototype.mettreAJourProgression = function() {
893
	this.nbObsTransmises++;
915
	this.nbObsTransmises++;
894
	var pct = (this.nbObsTransmises/this.totalObsATransmettre)*100;
916
	var pct = (this.nbObsTransmises/this.totalObsATransmettre)*100;
895
	$('#barre-progression-upload').attr('aria-valuenow', this.nbObsTransmises);
917
	$('#barre-progression-upload').attr('aria-valuenow', this.nbObsTransmises);
896
	$('#barre-progression-upload').attr('style', "width: "+pct+"%");
918
	$('#barre-progression-upload').attr('style', "width: "+pct+"%");
897
	$('#barre-progression-upload .sr-only').text(this.nbObsTransmises+"/"+this.totalObsATransmettre+" observations transmises");
919
	$('#barre-progression-upload .sr-only').text(this.nbObsTransmises+"/"+this.totalObsATransmettre+" observations transmises");
898
 
920
 
899
	if(this.obsNbre == 0) {
921
	if(this.obsNbre == 0) {
900
		$('.progress').removeClass('active');
922
		$('.progress').removeClass('active');
901
		$('.progress').removeClass('progress-striped');
923
		$('.progress').removeClass('progress-striped');
902
	}
924
	}
903
};
925
};
904
 
926
 
905
WidgetSaisie.prototype.envoyerObsAuCel = function(idObs, observation) {
927
WidgetSaisie.prototype.envoyerObsAuCel = function(idObs, observation) {
906
	var lthis = this;
928
	var lthis = this;
907
	var erreurMsg = "";
929
	var erreurMsg = "";
908
	$.ajax({
930
	$.ajax({
909
		url : lthis.serviceSaisieUrl,
931
		url : lthis.serviceSaisieUrl,
910
		type : "POST",
932
		type : "POST",
911
		data : observation,
933
		data : observation,
912
		dataType : "json",
934
		dataType : "json",
913
		beforeSend : function() {
935
		beforeSend : function() {
914
			$("#dialogue-obs-transaction-ko").hide();
936
			$("#dialogue-obs-transaction-ko").hide();
915
			$("#dialogue-obs-transaction-ok").hide();
937
			$("#dialogue-obs-transaction-ok").hide();
916
			$('.alert-txt').empty();
938
			$('.alert-txt').empty();
-
 
939
			$(".alert-txt .msg-erreur").remove();
-
 
940
			$(".alert-txt .msg-debug").remove();
917
			$("#chargement").show();
941
			$("#chargement").show();
918
		},
942
		},
919
		success : function(data, textStatus, jqXHR) {
943
		success : function(data, textStatus, jqXHR) {
920
			// mise à jour du nombre d'obs à transmettre
944
			// mise à jour du nombre d'obs à transmettre
921
			// et suppression de l'obs
945
			// et suppression de l'obs
922
			lthis.supprimerObsParId(idObs);
946
			lthis.supprimerObsParId(idObs);
923
			lthis.nbObsEnCours++;
947
			lthis.nbObsEnCours++;
924
			// mise à jour du statut
948
			// mise à jour du statut
925
			lthis.mettreAJourProgression();
949
			lthis.mettreAJourProgression();
926
			if(lthis.obsNbre > 0) {
950
			if(lthis.obsNbre > 0) {
927
				// dépilement de la suivante
951
				// dépilement de la suivante
928
				lthis.depilerObsPourEnvoi();
952
				lthis.depilerObsPourEnvoi();
929
			}
953
			}
930
		},
954
		},
931
		statusCode : {
955
		statusCode : {
932
			500 : function(jqXHR, textStatus, errorThrown) {
956
			500 : function(jqXHR, textStatus, errorThrown) {
933
				erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
957
				erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
934
		    }
958
		    }
935
		},
959
		},
936
		error : function(jqXHR, textStatus, errorThrown) {
960
		error : function(jqXHR, textStatus, errorThrown) {
937
			erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
961
			erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
938
			try {
962
			try {
939
				reponse = jQuery.parseJSON(jqXHR.responseText);
963
				reponse = jQuery.parseJSON(jqXHR.responseText);
940
				if (reponse != null) {
964
				if (reponse != null) {
941
					$.each(reponse, function (cle, valeur) {
965
					$.each(reponse, function (cle, valeur) {
942
						erreurMsg += valeur + "\n";
966
						erreurMsg += valeur + "\n";
943
					});
967
					});
944
				}
968
				}
945
			} catch(e) {
969
			} catch(e) {
946
				erreurMsg += "Erreur inconnue: " + jqXHR.responseText;
970
				erreurMsg += "Erreur inconnue: " + jqXHR.responseText;
947
			}
971
			}
948
		},
972
		},
949
		complete : function(jqXHR, textStatus) {
973
		complete : function(jqXHR, textStatus) {
950
			var debugMsg = extraireEnteteDebug(jqXHR);
974
			var debugMsg = extraireEnteteDebug(jqXHR);
951
 
975
 
952
			if (erreurMsg != '') {
976
			if (erreurMsg != '') {
953
				if (this.debug) {
977
				if (this.debug) {
954
					$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
978
					$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
955
					$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
979
					$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
956
				}
980
				}
957
				var hrefCourriel = "mailto:cel_remarques@tela-botanica.org?"+
981
				var hrefCourriel = "mailto:cel_remarques@tela-botanica.org?"+
958
					"subject=Dysfonctionnement du widget de saisie "+ this.tagProjet +
982
					"subject=Dysfonctionnement du widget de saisie "+ this.tagProjet +
959
					"&body="+erreurMsg+"%0D%0ADébogage :%0D%0A"+debugMsg;
983
					"&body="+erreurMsg+"%0D%0ADébogage :%0D%0A"+debugMsg;
960
 
984
 
961
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
985
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
962
				$('#obs'+idObs+' div div').addClass('obs-erreur');
986
				$('#obs'+idObs+' div div').addClass('obs-erreur');
963
				window.location.hash = "obs"+idObs;
987
				window.location.hash = "obs"+idObs;
964
 
988
 
965
				$('#dialogue-obs-transaction-ko .alert-txt').append($("#tpl-transmission-ko").clone()
989
				$('#dialogue-obs-transaction-ko .alert-txt').append($("#tpl-transmission-ko").clone()
966
					.find('.courriel-erreur')
990
					.find('.courriel-erreur')
967
					.attr('href', hrefCourriel)
991
					.attr('href', hrefCourriel)
968
					.end()
992
					.end()
969
					.html());
993
					.html());
970
				$("#dialogue-obs-transaction-ko").show();
994
				$("#dialogue-obs-transaction-ko").show();
971
				$("#chargement").hide();
995
				$("#chargement").hide();
972
				lthis.initialiserBarreProgression();
996
				lthis.initialiserBarreProgression();
973
			} else {
997
			} else {
974
				if (lthis.debug) {
998
				if (lthis.debug) {
975
					$("#dialogue-obs-transaction-ok .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
999
					$("#dialogue-obs-transaction-ok .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
976
				}
1000
				}
977
				if(lthis.obsNbre == 0) {
1001
				if(lthis.obsNbre == 0) {
978
					setTimeout(function() {
1002
					setTimeout(function() {
979
						$("#chargement").hide();
1003
						$("#chargement").hide();
980
						$('#dialogue-obs-transaction-ok .alert-txt').append($('#tpl-transmission-ok').clone().html());
1004
						$('#dialogue-obs-transaction-ok .alert-txt').append($('#tpl-transmission-ok').clone().html());
981
						$("#dialogue-obs-transaction-ok").show();
1005
						$("#dialogue-obs-transaction-ok").show();
982
						window.location.hash = "dialogue-obs-transaction-ok";
1006
						window.location.hash = "dialogue-obs-transaction-ok";
983
						lthis.initialiserObs();
1007
						lthis.initialiserObs();
984
					}, 1500);
1008
					}, 1500);
985
 
1009
 
986
				}
1010
				}
987
			}
1011
			}
988
		}
1012
		}
989
	});
1013
	});
990
};
1014
};
991
 
1015
 
992
WidgetSaisie.prototype.validerFormulaire = function() {
1016
WidgetSaisie.prototype.validerFormulaire = function() {
993
	$observateur = $("#form-observateur").valid();
1017
	$observateur = $("#form-observateur").valid();
994
	$station = $("#form-station").valid();
1018
	$station = $("#form-station").valid();
995
	$obs = $("#form-obs").valid();
1019
	$obs = $("#form-obs").valid();
996
	return ($observateur == true && $station == true && $obs == true) ? true : false;
1020
	return ($observateur == true && $station == true && $obs == true) ? true : false;
997
};
1021
};
998
 
1022
 
999
WidgetSaisie.prototype.getNomsImgsOriginales = function() {
1023
WidgetSaisie.prototype.getNomsImgsOriginales = function() {
1000
	var noms = new Array();
1024
	var noms = new Array();
1001
	$(".miniature-img").each(function() {
1025
	$(".miniature-img").each(function() {
1002
		noms.push($(this).attr('alt'));
1026
		noms.push($(this).attr('alt'));
1003
	});
1027
	});
1004
	return noms;
1028
	return noms;
1005
};
1029
};
1006
 
1030
 
1007
WidgetSaisie.prototype.getB64ImgsOriginales = function() {
1031
WidgetSaisie.prototype.getB64ImgsOriginales = function() {
1008
	var b64 = new Array();
1032
	var b64 = new Array();
1009
	$(".miniature-img").each(function() {
1033
	$(".miniature-img").each(function() {
1010
		if ($(this).hasClass('b64')) {
1034
		if ($(this).hasClass('b64')) {
1011
			b64.push($(this).attr('src'));
1035
			b64.push($(this).attr('src'));
1012
		} else if ($(this).hasClass('b64-canvas')) {
1036
		} else if ($(this).hasClass('b64-canvas')) {
1013
			b64.push($(this).data('b64'));
1037
			b64.push($(this).data('b64'));
1014
		}
1038
		}
1015
	});
1039
	});
1016
 
1040
 
1017
	return b64;
1041
	return b64;
1018
};
1042
};
1019
 
1043
 
1020
WidgetSaisie.prototype.supprimerObs = function(selector) {
1044
WidgetSaisie.prototype.supprimerObs = function(selector) {
1021
	var obsId = $(selector).val();
1045
	var obsId = $(selector).val();
1022
	// Problème avec IE 6 et 7
1046
	// Problème avec IE 6 et 7
1023
	if (obsId == "Supprimer") {
1047
	if (obsId == "Supprimer") {
1024
		obsId = $(selector).attr("title");
1048
		obsId = $(selector).attr("title");
1025
	}
1049
	}
1026
	this.supprimerObsParId(obsId);
1050
	this.supprimerObsParId(obsId);
1027
};
1051
};
1028
 
1052
 
1029
WidgetSaisie.prototype.supprimerObsParId = function(obsId) {
1053
WidgetSaisie.prototype.supprimerObsParId = function(obsId) {
1030
	this.obsNbre = this.obsNbre - 1;
1054
	this.obsNbre = this.obsNbre - 1;
1031
	$(".obs-nbre").text(this.obsNbre);
1055
	$(".obs-nbre").text(this.obsNbre);
1032
	$(".obs-nbre").triggerHandler('changement');
1056
	$(".obs-nbre").triggerHandler('changement');
1033
	$('.obs'+obsId).remove();
1057
	$('.obs'+obsId).remove();
1034
	$("#liste-obs").removeData('obsId'+obsId);
1058
	$("#liste-obs").removeData('obsId'+obsId);
1035
};
1059
};
1036
 
1060
 
1037
WidgetSaisie.prototype.initialiserBarreProgression = function() {
1061
WidgetSaisie.prototype.initialiserBarreProgression = function() {
1038
	$('#barre-progression-upload').attr('aria-valuenow', 0);
1062
	$('#barre-progression-upload').attr('aria-valuenow', 0);
1039
	$('#barre-progression-upload').attr('style', "width: 0%");
1063
	$('#barre-progression-upload').attr('style', "width: 0%");
1040
	$('#barre-progression-upload .sr-only').text("0/0 observations transmises");
1064
	$('#barre-progression-upload .sr-only').text("0/0 observations transmises");
1041
	$('.progress').addClass('active');
1065
	$('.progress').addClass('active');
1042
	$('.progress').addClass('progress-striped');
1066
	$('.progress').addClass('progress-striped');
1043
};
1067
};
1044
 
1068
 
1045
WidgetSaisie.prototype.initialiserObs = function() {
1069
WidgetSaisie.prototype.initialiserObs = function() {
1046
	this.obsNbre = 0;
1070
	this.obsNbre = 0;
1047
	this.nbObsTransmises = 0;
1071
	this.nbObsTransmises = 0;
1048
	this.nbObsEnCours = 0;
1072
	this.nbObsEnCours = 0;
1049
	this.totalObsATransmettre = 0;
1073
	this.totalObsATransmettre = 0;
1050
	this.initialiserBarreProgression();
1074
	this.initialiserBarreProgression();
1051
	$(".obs-nbre").text(this.obsNbre);
1075
	$(".obs-nbre").text(this.obsNbre);
1052
	$(".obs-nbre").triggerHandler('changement');
1076
	$(".obs-nbre").triggerHandler('changement');
1053
	$("#liste-obs").removeData();
1077
	$("#liste-obs").removeData();
1054
	$('.obs').remove();
1078
	$('.obs').remove();
1055
	$("#dialogue-bloquer-creer-obs").hide();
1079
	$("#dialogue-bloquer-creer-obs").hide();
1056
};
1080
};
1057
 
1081
 
1058
/**
1082
/**
1059
 * Ajoute une boîte de miniatures avec défilement des images,
1083
 * Ajoute une boîte de miniatures avec défilement des images,
1060
 * pour une obs de la liste des obs à transmettre
1084
 * pour une obs de la liste des obs à transmettre
1061
 */
1085
 */
1062
WidgetSaisie.prototype.ajouterImgMiniatureAuTransfert = function() {
1086
WidgetSaisie.prototype.ajouterImgMiniatureAuTransfert = function() {
1063
	var html = '',
1087
	var html = '',
1064
		miniatures = '',
1088
		miniatures = '',
1065
		premiere = true;
1089
		premiere = true;
1066
	if ($("#miniatures img").length >= 1) {
1090
	if ($("#miniatures img").length >= 1) {
1067
		$("#miniatures img").each(function() {
1091
		$("#miniatures img").each(function() {
1068
			var visible = premiere ? 'miniature-selectionnee' : 'miniature-cachee';
1092
			var visible = premiere ? 'miniature-selectionnee' : 'miniature-cachee';
1069
			premiere = false;
1093
			premiere = false;
1070
			var css = $(this).hasClass('b64') ? 'miniature b64' : 'miniature',
1094
			var css = $(this).hasClass('b64') ? 'miniature b64' : 'miniature',
1071
				src = $(this).attr("src"),
1095
				src = $(this).attr("src"),
1072
				alt = $(this).attr("alt"),
1096
				alt = $(this).attr("alt"),
1073
				//miniature = '<img class="'+css+' '+visible+'"  alt="'+alt+'"src="'+src+'" />';
1097
				//miniature = '<img class="'+css+' '+visible+'"  alt="'+alt+'"src="'+src+'" />';
1074
				miniature = '<div class="'+css+' '+visible+'"  alt="'+alt+'" style="background-image: url('+src+')" ></div>';
1098
				miniature = '<div class="'+css+' '+visible+'"  alt="'+alt+'" style="background-image: url('+src+')" ></div>';
1075
			miniatures += miniature;
1099
			miniatures += miniature;
1076
		});
1100
		});
1077
		visible = ($("#miniatures img").length > 1) ? '' : 'defilement-miniatures-cache';
1101
		visible = ($("#miniatures img").length > 1) ? '' : 'defilement-miniatures-cache';
1078
		var html =
1102
		var html =
1079
			'<div class="defilement-miniatures">'+
1103
			'<div class="defilement-miniatures">'+
1080
				'<a href="#" class="defilement-miniatures-gauche '+visible+'">&#60;</a>'+
1104
				'<a href="#" class="defilement-miniatures-gauche '+visible+'">&#60;</a>'+
1081
				miniatures+
1105
				miniatures+
1082
				'<a href="#" class="defilement-miniatures-droite '+visible+'">&#62;</a>'+
1106
				'<a href="#" class="defilement-miniatures-droite '+visible+'">&#62;</a>'+
1083
			'</div>';
1107
			'</div>';
1084
	} else {
1108
	} else {
1085
		html = '<img class="miniature" alt="Aucune photo"src="'+ this.pasDePhotoIconeUrl +'" />';
1109
		html = '<img class="miniature" alt="Aucune photo"src="'+ this.pasDePhotoIconeUrl +'" />';
1086
	}
1110
	}
1087
	return html;
1111
	return html;
1088
};
1112
};
1089
 
1113
 
1090
WidgetSaisie.prototype.defilerMiniatures = function(element) {
1114
WidgetSaisie.prototype.defilerMiniatures = function(element) {
1091
 
1115
 
1092
	var miniatureSelectionne = element.siblings("div.miniature-selectionnee");
1116
	var miniatureSelectionne = element.siblings("div.miniature-selectionnee");
1093
	miniatureSelectionne.removeClass('miniature-selectionnee');
1117
	miniatureSelectionne.removeClass('miniature-selectionnee');
1094
	miniatureSelectionne.addClass('miniature-cachee');
1118
	miniatureSelectionne.addClass('miniature-cachee');
1095
	var miniatureAffichee = miniatureSelectionne;
1119
	var miniatureAffichee = miniatureSelectionne;
1096
 
1120
 
1097
	if(element.hasClass('defilement-miniatures-gauche')) {
1121
	if(element.hasClass('defilement-miniatures-gauche')) {
1098
		if(miniatureSelectionne.prev('.miniature').length != 0) {
1122
		if(miniatureSelectionne.prev('.miniature').length != 0) {
1099
			miniatureAffichee = miniatureSelectionne.prev('.miniature');
1123
			miniatureAffichee = miniatureSelectionne.prev('.miniature');
1100
		} else {
1124
		} else {
1101
			miniatureAffichee = miniatureSelectionne.siblings(".miniature").last();
1125
			miniatureAffichee = miniatureSelectionne.siblings(".miniature").last();
1102
		}
1126
		}
1103
	} else {
1127
	} else {
1104
		if(miniatureSelectionne.next('.miniature').length != 0) {
1128
		if(miniatureSelectionne.next('.miniature').length != 0) {
1105
			miniatureAffichee = miniatureSelectionne.next('.miniature');
1129
			miniatureAffichee = miniatureSelectionne.next('.miniature');
1106
		} else {
1130
		} else {
1107
			miniatureAffichee = miniatureSelectionne.siblings(".miniature").first();
1131
			miniatureAffichee = miniatureSelectionne.siblings(".miniature").first();
1108
		}
1132
		}
1109
	}
1133
	}
1110
	//console.log(miniatureAffichee);
1134
	//console.log(miniatureAffichee);
1111
	miniatureAffichee.addClass('miniature-selectionnee');
1135
	miniatureAffichee.addClass('miniature-selectionnee');
1112
	miniatureAffichee.removeClass('miniature-cachee');
1136
	miniatureAffichee.removeClass('miniature-cachee');
1113
};
1137
};
1114
 
1138
 
1115
WidgetSaisie.prototype.ajouterNumNomSel = function() {
1139
WidgetSaisie.prototype.ajouterNumNomSel = function() {
1116
	var nn = '';
1140
	var nn = '';
1117
	if ($("#taxon").data("numNomSel") == undefined) {
1141
	if ($("#taxon").data("numNomSel") == undefined) {
1118
		nn = '<span class="alert-error">[non lié au référentiel]</span>';
1142
		nn = '<span class="alert-error">[non lié au référentiel]</span>';
1119
	} else {
1143
	} else {
1120
		nn = '<span class="nn">[nn'+$("#taxon").data("numNomSel")+']</span>';
1144
		nn = '<span class="nn">[nn'+$("#taxon").data("numNomSel")+']</span>';
1121
	}
1145
	}
1122
	return nn;
1146
	return nn;
1123
};
1147
};
1124
 
1148
 
1125
WidgetSaisie.prototype.ajouterAutocompletionNoms = function() {
1149
WidgetSaisie.prototype.ajouterAutocompletionNoms = function() {
1126
	var lthis = this;
1150
	var lthis = this;
1127
	$('#taxon').autocomplete({
1151
	$('#taxon').autocomplete({
1128
		source: function(requete, add){
1152
		source: function(requete, add){
1129
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
1153
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
1130
			requete = "";
1154
			requete = "";
1131
			if($("#referentiel").val() != "autre") {
1155
			if($("#referentiel").val() != "autre") {
1132
				var url = lthis.getUrlAutocompletionNomsSci();
1156
				var url = lthis.getUrlAutocompletionNomsSci();
1133
				$.getJSON(url, requete, function(data) {
1157
				$.getJSON(url, requete, function(data) {
1134
					var suggestions = lthis.traiterRetourNomsSci(data);
1158
					var suggestions = lthis.traiterRetourNomsSci(data);
1135
					add(suggestions);
1159
					add(suggestions);
1136
	            });
1160
	            });
1137
			}
1161
			}
1138
        },
1162
        },
1139
        html: true
1163
        html: true
1140
	});
1164
	});
1141
 
1165
 
1142
	$( "#taxon" ).bind("autocompleteselect", function(event, ui) {
1166
	$( "#taxon" ).bind("autocompleteselect", function(event, ui) {
1143
		$("#taxon").data(ui.item);
1167
		$("#taxon").data(ui.item);
1144
		if (ui.item.retenu == true) {
1168
		if (ui.item.retenu == true) {
1145
			$("#taxon").addClass('ns-retenu');
1169
			$("#taxon").addClass('ns-retenu');
1146
		} else {
1170
		} else {
1147
			$("#taxon").removeClass('ns-retenu');
1171
			$("#taxon").removeClass('ns-retenu');
1148
		}
1172
		}
1149
	});
1173
	});
1150
};
1174
};
1151
 
1175
 
1152
WidgetSaisie.prototype.getUrlAutocompletionNomsSci = function() {
1176
WidgetSaisie.prototype.getUrlAutocompletionNomsSci = function() {
1153
	var mots = $('#taxon').val();
1177
	var mots = $('#taxon').val();
1154
	var url = this.serviceAutocompletionNomSciUrlTpl.replace('{referentiel}', this.nomSciReferentiel);
1178
	var url = this.serviceAutocompletionNomSciUrlTpl.replace('{referentiel}', this.nomSciReferentiel);
1155
	url = url.replace('{masque}', mots);
1179
	url = url.replace('{masque}', mots);
1156
	return url;
1180
	return url;
1157
};
1181
};
1158
 
1182
 
1159
WidgetSaisie.prototype.traiterRetourNomsSci = function(data) {
1183
WidgetSaisie.prototype.traiterRetourNomsSci = function(data) {
1160
	var suggestions = [];
1184
	var suggestions = [];
1161
	if (data.resultat != undefined) {
1185
	if (data.resultat != undefined) {
1162
		$.each(data.resultat, function(i, val) {
1186
		$.each(data.resultat, function(i, val) {
1163
			val.nn = i;
1187
			val.nn = i;
1164
			var nom = {label : '', value : '', nt : '', nomSel : '', nomSelComplet : '', numNomSel : '',
1188
			var nom = {label : '', value : '', nt : '', nomSel : '', nomSelComplet : '', numNomSel : '',
1165
				nomRet : '', numNomRet : '', famille : '', retenu : false
1189
				nomRet : '', numNomRet : '', famille : '', retenu : false
1166
			};
1190
			};
1167
			if (suggestions.length >= this.autocompletionElementsNbre) {
1191
			if (suggestions.length >= this.autocompletionElementsNbre) {
1168
				nom.label = "...";
1192
				nom.label = "...";
1169
				nom.value = $('#taxon').val();
1193
				nom.value = $('#taxon').val();
1170
				suggestions.push(nom);
1194
				suggestions.push(nom);
1171
				return false;
1195
				return false;
1172
			} else {
1196
			} else {
1173
				nom.label = val.nom_sci_complet;
1197
				nom.label = val.nom_sci_complet;
1174
				nom.value = val.nom_sci_complet;
1198
				nom.value = val.nom_sci_complet;
1175
				nom.nt = val.num_taxonomique;
1199
				nom.nt = val.num_taxonomique;
1176
				nom.nomSel = val.nom_sci;
1200
				nom.nomSel = val.nom_sci;
1177
				nom.nomSelComplet = val.nom_sci_complet;
1201
				nom.nomSelComplet = val.nom_sci_complet;
1178
				nom.numNomSel = val.nn;
1202
				nom.numNomSel = val.nn;
1179
				nom.nomRet = val.nom_retenu_complet;
1203
				nom.nomRet = val.nom_retenu_complet;
1180
				nom.numNomRet = val["nom_retenu.id"];
1204
				nom.numNomRet = val["nom_retenu.id"];
1181
				nom.famille = val.famille;
1205
				nom.famille = val.famille;
1182
				// Tester dans ce sens, permet de considérer "absent" comme "false" => est-ce opportun ?
1206
				// Tester dans ce sens, permet de considérer "absent" comme "false" => est-ce opportun ?
1183
				// en tout cas c'est harmonisé avec le CeL
1207
				// en tout cas c'est harmonisé avec le CeL
1184
				nom.retenu = (val.retenu == 'true') ? true : false;
1208
				nom.retenu = (val.retenu == 'true') ? true : false;
1185
 
1209
 
1186
				suggestions.push(nom);
1210
				suggestions.push(nom);
1187
			}
1211
			}
1188
		});
1212
		});
1189
	}
1213
	}
1190
 
1214
 
1191
	return suggestions;
1215
	return suggestions;
1192
};
1216
};
1193
 
1217
 
1194
WidgetSaisie.prototype.afficherPanneau = function(selecteur) {
1218
WidgetSaisie.prototype.afficherPanneau = function(selecteur) {
1195
	$(selecteur).fadeIn("slow").delay(this.dureeMessage).fadeOut("slow");
1219
	$(selecteur).fadeIn("slow").delay(this.dureeMessage).fadeOut("slow");
1196
};
1220
};
1197
 
1221
 
1198
WidgetSaisie.prototype.masquerPanneau = function(selecteur) {
1222
WidgetSaisie.prototype.masquerPanneau = function(selecteur) {
1199
	$(selecteur).hide();
1223
	$(selecteur).hide();
1200
};
1224
};
1201
 
1225
 
1202
// lib hors objet --
1226
// lib hors objet --
1203
 
1227
 
1204
/**
1228
/**
1205
* Stope l'évènement courant quand on clique sur un lien.
1229
* Stope l'évènement courant quand on clique sur un lien.
1206
* Utile pour Chrome, Safari...
1230
* Utile pour Chrome, Safari...
1207
*/
1231
*/
1208
function arreter(evenement) {
1232
function arreter(evenement) {
1209
	if (evenement.stopPropagation) {
1233
	if (evenement.stopPropagation) {
1210
		evenement.stopPropagation();
1234
		evenement.stopPropagation();
1211
	}
1235
	}
1212
	if (evenement.preventDefault) {
1236
	if (evenement.preventDefault) {
1213
		evenement.preventDefault();
1237
		evenement.preventDefault();
1214
	}
1238
	}
1215
	return false;
1239
	return false;
1216
}
1240
}
1217
 
1241
 
1218
/**
1242
/**
1219
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1243
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1220
 * @param jqXHR
1244
 * @param jqXHR
1221
 * @returns {String}
1245
 * @returns {String}
1222
 */
1246
 */
1223
function extraireEnteteDebug(jqXHR) {
1247
function extraireEnteteDebug(jqXHR) {
1224
	var msgDebug = '';
1248
	var msgDebug = '';
1225
	if (jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
1249
	if (jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
1226
		var debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
1250
		var debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
1227
		if (debugInfos != null) {
1251
		if (debugInfos != null) {
1228
			$.each(debugInfos, function (cle, valeur) {
1252
			$.each(debugInfos, function (cle, valeur) {
1229
				msgDebug += valeur + "\n";
1253
				msgDebug += valeur + "\n";
1230
			});
1254
			});
1231
		}
1255
		}
1232
	}
1256
	}
1233
	return msgDebug;
1257
	return msgDebug;
1234
}
1258
}
1235
 
1259
 
1236
/*
1260
/*
1237
 * jQuery UI Autocomplete HTML Extension
1261
 * jQuery UI Autocomplete HTML Extension
1238
 *
1262
 *
1239
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1263
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1240
 * Dual licensed under the MIT or GPL Version 2 licenses.
1264
 * Dual licensed under the MIT or GPL Version 2 licenses.
1241
 *
1265
 *
1242
 * http://github.com/scottgonzalez/jquery-ui-extensions
1266
 * http://github.com/scottgonzalez/jquery-ui-extensions
1243
 *
1267
 *
1244
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1268
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1245
 */
1269
 */
1246
(function( $ ) {
1270
(function( $ ) {
1247
	var proto = $.ui.autocomplete.prototype,
1271
	var proto = $.ui.autocomplete.prototype,
1248
		initSource = proto._initSource;
1272
		initSource = proto._initSource;
1249
 
1273
 
1250
	WidgetSaisie.prototype.filter = function( array, term ) {
1274
	WidgetSaisie.prototype.filter = function( array, term ) {
1251
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1275
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1252
		return $.grep( array, function(value) {
1276
		return $.grep( array, function(value) {
1253
			return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1277
			return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1254
		});
1278
		});
1255
	}
1279
	}
1256
 
1280
 
1257
	$.extend( proto, {
1281
	$.extend( proto, {
1258
		_initSource: function() {
1282
		_initSource: function() {
1259
			if ( this.options.html && $.isArray(this.options.source) ) {
1283
			if ( this.options.html && $.isArray(this.options.source) ) {
1260
				this.source = function( request, response ) {
1284
				this.source = function( request, response ) {
1261
					response( filter( this.options.source, request.term ) );
1285
					response( filter( this.options.source, request.term ) );
1262
				};
1286
				};
1263
			} else {
1287
			} else {
1264
				initSource.call( this );
1288
				initSource.call( this );
1265
			}
1289
			}
1266
		},
1290
		},
1267
		_renderItem: function( ul, item) {
1291
		_renderItem: function( ul, item) {
1268
			if (item.retenu == true) {
1292
			if (item.retenu == true) {
1269
				item.label = "<strong>"+item.label+"</strong>";
1293
				item.label = "<strong>"+item.label+"</strong>";
1270
			}
1294
			}
1271
 
1295
 
1272
			return $( "<li></li>" )
1296
			return $( "<li></li>" )
1273
				.data( "item.autocomplete", item )
1297
				.data( "item.autocomplete", item )
1274
				.append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1298
				.append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1275
				.appendTo( ul );
1299
				.appendTo( ul );
1276
		}
1300
		}
1277
	});
1301
	});
1278
})( jQuery );
1302
})( jQuery );