Subversion Repositories eFlore/Applications.cel

Rev

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

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