Subversion Repositories eFlore/Applications.cel

Rev

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

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