Subversion Repositories eFlore/Applications.cel

Rev

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

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