Subversion Repositories eFlore/Applications.cel

Rev

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

Rev 1560 Rev 1562
1
//+---------------------------------------------------------------------------------------------------------+
1
//+---------------------------------------------------------------------------------------------------------+
2
// GÉNÉRAL
2
// GÉNÉRAL
3
$(document).ready(function() {
3
$(document).ready(function() {
4
	if (DEBUG == false) {
4
	if (DEBUG == false) {
5
		$(window).on('beforeunload', function(event) {
5
		$(window).on('beforeunload', function(event) {
6
			return 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.';
6
			return 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.';
7
		});
7
		});
8
	}
8
	}
9
});
9
});
10
//+----------------------------------------------------------------------------------------------------------+
10
//+----------------------------------------------------------------------------------------------------------+
11
// FONCTIONS GÉNÉRIQUES
11
// FONCTIONS GÉNÉRIQUES
12
/**
12
/**
13
 * Stope l'évènement courrant quand on clique sur un lien.
13
 * Stope l'évènement courrant quand on clique sur un lien.
14
 * Utile pour Chrome, Safari...
14
 * Utile pour Chrome, Safari...
15
 * @param evenement
15
 * @param evenement
16
 * @return
16
 * @return
17
 */
17
 */
18
function arreter(evenement) {
18
function arreter(evenement) {
19
	if (evenement.stopPropagation) {
19
	if (evenement.stopPropagation) {
20
		evenement.stopPropagation();
20
		evenement.stopPropagation();
21
	}
21
	}
22
	if (evenement.preventDefault) {
22
	if (evenement.preventDefault) {
23
		evenement.preventDefault();
23
		evenement.preventDefault();
24
	}
24
	}
25
	return false;
25
	return false;
26
}
26
}
27
 
27
 
28
function extraireEnteteDebug(jqXHR) {
28
function extraireEnteteDebug(jqXHR) {
29
	var msgDebug = '';
29
	var msgDebug = '';
30
	if (jqXHR.getResponseHeader('X-DebugJrest-Data') != '') {
30
	if (jqXHR.getResponseHeader('X-DebugJrest-Data') != '') {
31
		var debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader('X-DebugJrest-Data'));
31
		var debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader('X-DebugJrest-Data'));
32
		if (debugInfos != null) {
32
		if (debugInfos != null) {
33
			$.each(debugInfos, function (cle, valeur) {
33
			$.each(debugInfos, function (cle, valeur) {
34
				msgDebug += valeur + "\n";
34
				msgDebug += valeur + "\n";
35
			});
35
			});
36
		}
36
		}
37
	}
37
	}
38
	return msgDebug;
38
	return msgDebug;
39
}
39
}
40
 
40
 
41
function afficherPanneau(selecteur) {
41
function afficherPanneau(selecteur) {
42
	$(selecteur).fadeIn('slow').delay(DUREE_MESSAGE).fadeOut('slow');
42
	$(selecteur).fadeIn('slow').delay(DUREE_MESSAGE).fadeOut('slow');
43
}
43
}
44
 
44
 
45
//+----------------------------------------------------------------------------------------------------------+
45
//+----------------------------------------------------------------------------------------------------------+
46
//UPLOAD PHOTO : Traitement de l'image 
46
//FORM IDENTITE : gestion de l'observateur
-
 
47
 
47
$(document).ready(function() {
48
$(document).ready(function() {
48
	$('.effacer-miniature').click(function () {
49
	$('#courriel').on('blur', requeterIdentite);
49
		supprimerMiniatures($(this));
50
	$('#courriel').on('keypress', testerLancementRequeteIdentite);
50
	});
51
});
51
	
52
 
-
 
53
function testerLancementRequeteIdentite(event) {
52
	$('#photo-placeholder').click(function(event) {
54
	if (event.which == 13) {
-
 
55
		requeterIdentite();
-
 
56
		event.preventDefault();
53
		$('#fichier').click();
57
		event.stopPropagation();
-
 
58
	}
54
	});
59
}
-
 
60
 
-
 
61
function requeterIdentite() {
-
 
62
	var courriel = $('#courriel').val();
55
	
63
	//TODO: mettre ceci en paramètre de config
56
	$('#fichier').bind('change', function (e) {
64
	var urlAnnuaire = SERVICE_ANNUAIRE_ID_URL + courriel;
-
 
65
	$.ajax({
57
		arreter(e);
66
		url: urlAnnuaire,
58
		var options = { 
67
		type: 'GET',
59
			success: afficherMiniature, // post-submit callback 
68
		success: function(data, textStatus, jqXHR) {
60
			dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type) 
69
			console.log('SUCCESS:'+textStatus);
61
			resetForm: true // reset the form after successful submit 
70
			if (data != undefined && data[courriel] != undefined) {
62
		};
71
				var infos = data[courriel];
63
		$('#miniature').append(
72
				$('#id_utilisateur').val(infos.id);
64
			'<img id="miniature-chargement" class="miniature" alt="chargement" src="'+CHARGEMENT_IMAGE_URL+'"/>');
73
				$('#prenom').val(infos.prenom);
-
 
74
				$('#nom').val(infos.nom);
65
		$('#ajouter-obs').attr('disabled', 'disabled');
75
				$('#courriel_confirmation').val(courriel);
66
		if(verifierFormat($('#fichier').val())) {
76
				$('#prenom, #nom, #courriel_confirmation').attr('disabled', 'disabled');
-
 
77
				$('#date').focus();
-
 
78
			} else {
-
 
79
				surErreurCompletionCourriel();
-
 
80
			}
-
 
81
		},
-
 
82
		error: function(jqXHR, textStatus, errorThrown) {
-
 
83
			console.log('ERREUR :'+textStatus);
-
 
84
			surErreurCompletionCourriel();
-
 
85
		},
-
 
86
		complete: function(jqXHR, textStatus) {
67
			$('#form-upload').ajaxSubmit(options);
87
			console.log('COMPLETE :'+textStatus);
68
		} else {
88
			$('#zone-prenom-nom').removeClass('hidden');
69
			window.alert("Le format de fichier n'est pas supporté, les formats acceptés sont "+	$('#fichier').attr('accept'));
-
 
70
		}
89
			$('#zone-courriel-confirmation').removeClass('hidden');
-
 
90
		}
71
		return false;
91
	});
-
 
92
}
-
 
93
 
72
	});
94
function surErreurCompletionCourriel() {
73
	
-
 
74
	$('.effacer-miniature').on('click', function() {
95
	$('#prenom, #nom, #courriel_confirmation').val('');
75
		$(this).parent().remove();
96
	$('#prenom, #nom, #courriel_confirmation').removeAttr('disabled');
76
	});
-
 
77
});
97
	afficherPanneau('#dialogue-courriel-introuvable');
78
 
-
 
79
function verifierFormat(nom) {
98
}
80
	var parts = nom.split('.');
99
 
-
 
100
function formaterNom() {
-
 
101
	$(this).val($(this).val().toUpperCase());
-
 
102
}
-
 
103
 
81
	extension = parts[parts.length - 1];
104
function formaterPrenom() {
-
 
105
	var prenom = new Array(),
-
 
106
		mots = $(this).val().split(' ');
82
	return (extension.toLowerCase() == 'jpeg' || extension.toLowerCase() == 'jpg');
107
	for (var i = 0; i < mots.length; i++) {
-
 
108
		var mot = mots[i];
-
 
109
		if (mot.indexOf('-') >= 0) {
83
}
110
			var prenomCompose = new Array(),
84
 
111
				motsComposes = mot.split('-');
85
function afficherMiniature(reponse) { 
-
 
86
	if (DEBUG) {
-
 
87
		var debogage = $('debogage', reponse).text();
112
			for (var j = 0; j < motsComposes.length; j++) {
88
		console.log('Débogage upload : ' + debogage);
113
				var motSimple = motsComposes[j],
89
	}
114
					motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
90
	var message = $('message', reponse).text();
-
 
91
	if (message != '') {
115
				prenomCompose.push(motMajuscule);
92
		$('#miniature-msg').append(message);
116
			}
93
	} else {
-
 
94
		$('#miniatures').append(creerWidgetMiniature(reponse));
-
 
95
	}
-
 
96
	$('#ajouter-obs').removeAttr('disabled');	
-
 
97
}
-
 
98
 
-
 
99
function creerWidgetMiniature(reponse) {
-
 
100
	var miniatureUrl = $('miniature-url', reponse).text(),
-
 
101
		imgNom = $('image-nom', reponse).text(),
-
 
102
		html = 
-
 
103
			'<div class="miniature">'+
117
			prenom.push(prenomCompose.join('-'));
104
				'<img class="miniature-img" class="miniature" alt="'+imgNom+'" src="'+miniatureUrl+'"/>'+
-
 
105
				'<button class="effacer-miniature" type="button">Effacer</button>'+
-
 
106
			'</div>'
-
 
107
	return html;
118
		} else {
108
}
119
			var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
109
 
120
			prenom.push(motMajuscule);
110
function supprimerMiniatures() {
121
		}
111
	$('#miniatures').empty();
122
	}
112
	$('#miniature-msg').empty();
123
	$(this).val(prenom.join(' '));
113
}
124
}
114
 
125
 
115
//+----------------------------------------------------------------------------------------------------------+
126
//+----------------------------------------------------------------------------------------------------------+
116
// GOOGLE MAP
127
// GOOGLE MAP
-
 
128
 
117
var map,
129
var map,
118
	marker,
130
	marker,
119
	latLng,
131
	latLng,
120
	geocoder;
132
	geocoder;
121
 
133
 
122
$(document).ready(function() {
134
$(document).ready(function() {
123
	initialiserGoogleMap();
135
	initialiserGoogleMap();
124
	
136
	
125
	// Autocompletion du champ adresse
137
	// Autocompletion du champ adresse
126
	$('#carte-recherche').on('focus', function() {
138
	$('#carte-recherche').on('focus', function() {
127
		$(this).select();
139
		$(this).select();
128
	});
140
	});
129
	$('#carte-recherche').on('mouseup', function(event) {// Pour Safari...
141
	$('#carte-recherche').on('mouseup', function(event) {// Pour Safari...
130
		event.preventDefault();
142
		event.preventDefault();
131
	});
143
	});
132
	
144
	
133
	$('#carte-recherche').keypress(function(e) {
145
	$('#carte-recherche').keypress(function(e) {
134
		if (e.which == 13) {
146
		if (e.which == 13) {
135
			e.preventDefault();
147
			e.preventDefault();
136
		}
148
		}
137
	});
149
	});
138
	
150
	
139
	$('#carte-recherche').autocomplete({
151
	$('#carte-recherche').autocomplete({
140
		//Cette partie utilise geocoder pour extraire des valeurs d'adresse
152
		//Cette partie utilise geocoder pour extraire des valeurs d'adresse
141
		source: function(request, response) {
153
		source: function(request, response) {
142
			
154
			
143
			geocoder.geocode( {'address': request.term+', France', 'region' : 'fr' }, function(results, status) {
155
			geocoder.geocode( {'address': request.term+', France', 'region' : 'fr' }, function(results, status) {
144
				if (status == google.maps.GeocoderStatus.OK) {
156
				if (status == google.maps.GeocoderStatus.OK) {
145
					response($.map(results, function(item) {
157
					response($.map(results, function(item) {
146
						var retour = {
158
						var retour = {
147
							label: item.formatted_address,
159
							label: item.formatted_address,
148
							value: item.formatted_address,
160
							value: item.formatted_address,
149
							latitude: item.geometry.location.lat(),
161
							latitude: item.geometry.location.lat(),
150
							longitude: item.geometry.location.lng()
162
							longitude: item.geometry.location.lng()
151
						};
163
						};
152
						return retour;
164
						return retour;
153
					}));
165
					}));
154
				} else {
166
				} else {
155
					afficherErreurGoogleMap(status);
167
					afficherErreurGoogleMap(status);
156
				}
168
				}
157
			});
169
			});
158
		},
170
		},
159
		// Cette partie est executee a la selection d'une adresse
171
		// Cette partie est executee a la selection d'une adresse
160
		select: function(event, ui) {
172
		select: function(event, ui) {
161
			var latLng = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
173
			var latLng = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
162
			deplacerMarker(latLng);
174
			deplacerMarker(latLng);
163
		}
175
		}
164
	});
176
	});
165
	
177
	
166
	$('#geolocaliser').on('click', geolocaliser);
178
	$('#geolocaliser').on('click', geolocaliser);
167
	
179
	
168
	google.maps.event.addListener(marker, 'dragend', surDeplacementMarker);
180
	//google.maps.event.addListener(marker, 'dragend', surDeplacementMarker);
169
	
181
	
170
	google.maps.event.addListener(map, 'click', surClickDansCarte);
182
	//google.maps.event.addListener(map, 'click', surClickDansCarte);
171
});
183
});
172
 
184
 
173
function initialiserGoogleMap(){
185
function initialiserGoogleMap(){
174
	// Carte
186
	// Carte
175
	var latLng = new google.maps.LatLng(46.30871, 2.54395),// Centre de la France
187
	var latLng = new google.maps.LatLng(46.30871, 2.54395),// Centre de la France
176
		zoomDefaut = 5;
188
		zoomDefaut = 5;
177
		options = {
189
		options = {
178
			zoom: zoomDefaut,
190
			zoom: zoomDefaut,
179
			center: latLng,
191
			center: latLng,
180
			mapTypeId: google.maps.MapTypeId.HYBRID,
192
			mapTypeId: google.maps.MapTypeId.HYBRID,
181
			mapTypeControlOptions: {
193
			mapTypeControlOptions: {
182
				mapTypeIds: ['OSM', 
194
				mapTypeIds: ['OSM', 
183
					google.maps.MapTypeId.ROADMAP, 
195
					google.maps.MapTypeId.ROADMAP, 
184
					google.maps.MapTypeId.HYBRID, 
196
					google.maps.MapTypeId.HYBRID, 
185
					google.maps.MapTypeId.SATELLITE, 
197
					google.maps.MapTypeId.SATELLITE, 
186
					google.maps.MapTypeId.TERRAIN]}
198
					google.maps.MapTypeId.TERRAIN]}
187
		};
199
		};
188
 
200
	
189
	// Ajout de la couche OSM à la carte
201
	// Ajout de la couche OSM à la carte
190
	osmMapType = new google.maps.ImageMapType({
202
	osmMapType = new google.maps.ImageMapType({
191
		getTileUrl: function(coord, zoom) {
203
		getTileUrl: function(coord, zoom) {
192
			return 'http://tile.openstreetmap.org/' + zoom + '/' + coord.x + '/' + coord.y + '.png';
204
			return 'http://tile.openstreetmap.org/' + zoom + '/' + coord.x + '/' + coord.y + '.png';
193
		},
205
		},
194
		tileSize: new google.maps.Size(256, 256),
206
		tileSize: new google.maps.Size(256, 256),
195
		isPng: true,
207
		isPng: true,
196
		alt: 'OpenStreetMap',
208
		alt: 'OpenStreetMap',
197
		name: 'OSM',
209
		name: 'OSM',
198
		maxZoom: 19
210
		maxZoom: 19
199
	});
211
	});
200
	
212
	
201
	// Création de la carte Google
213
	// Création de la carte Google
202
	map = new google.maps.Map(document.getElementById('map-canvas'), options); //affiche la google map dans la div map_canvas
214
	map = new google.maps.Map(document.getElementById('map-canvas'), options); //affiche la google map dans la div map_canvas
203
	map.mapTypes.set('OSM', osmMapType);
215
	map.mapTypes.set('OSM', osmMapType);
204
	
216
	
205
	// Création du Geocoder
217
	// Création du Geocoder
206
	geocoder = new google.maps.Geocoder();
218
	geocoder = new google.maps.Geocoder();
207
	
219
	
208
	// Marqueur google draggable
220
	// Marqueur google draggable
209
	marker = new google.maps.Marker({
221
	marker = new google.maps.Marker({
210
		map: map,
222
		map: map,
211
		draggable: true,
223
		draggable: true,
212
		title: 'Ma station',
224
		title: 'Ma station',
213
		icon: GOOGLE_MAP_MARQUEUR_URL,
225
		icon: GOOGLE_MAP_MARQUEUR_URL,
214
		position: latLng
226
		position: latLng
215
	});
227
	});
216
	
228
	
217
	initialiserMarker(latLng);
229
	initialiserMarker(latLng);
218
	
230
	
219
	// Tentative de geocalisation
231
	// Tentative de geocalisation
220
	
232
	
221
	if (navigator.geolocation) {
233
	if (navigator.geolocation) {
222
		navigator.geolocation.getCurrentPosition(function(position) {
234
		navigator.geolocation.getCurrentPosition(function(position) {
223
			var latitude = position.coords.latitude,
235
			var latitude = position.coords.latitude,
224
				longitude = position.coords.longitude;
236
				longitude = position.coords.longitude;
225
			latLng = new google.maps.LatLng(latitude, longitude);
237
			latLng = new google.maps.LatLng(latitude, longitude);
226
			
238
			
227
			deplacerMarker(latLng);
239
			deplacerMarker(latLng);
228
		});
240
		});
229
	}
241
	}
230
}
242
}
231
 
243
 
232
function surDeplacementMarker() {
244
function surDeplacementMarker() {
233
	trouverCommune(marker.getPosition());
245
	trouverCommune(marker.getPosition());
234
	mettreAJourMarkerPosition(marker.getPosition());
246
	mettreAJourMarkerPosition(marker.getPosition());
235
}
247
}
236
 
248
 
237
function surClickDansCarte(event) {
249
function surClickDansCarte(event) {
238
	deplacerMarker(event.latLng);
250
	deplacerMarker(event.latLng);
239
}
251
}
240
 
252
 
241
function geolocaliser(event) {
253
function geolocaliser(event) {
242
	var latitude = $('#latitude').val(),
254
	var latitude = $('#latitude').val(),
243
		longitude = $('#longitude').val();
255
		longitude = $('#longitude').val();
244
	latLng = new google.maps.LatLng(latitude, longitude);
256
	latLng = new google.maps.LatLng(latitude, longitude);
245
	deplacerMarker(latLng);
257
	deplacerMarker(latLng);
246
	arreter(event);
258
	arreter(event);
247
}
259
}
248
 
260
 
249
function initialiserMarker(latLng) {
261
function initialiserMarker(latLng) {
250
	if (marker != undefined) {
262
	if (marker != undefined) {
251
		marker.setPosition(latLng);
263
		marker.setPosition(latLng);
252
		map.setCenter(latLng);
264
		map.setCenter(latLng);
253
		mettreAJourMarkerPosition(latLng);
265
		mettreAJourMarkerPosition(latLng);
254
		trouverCommune(latLng);
266
		trouverCommune(latLng);
255
	}
267
	}
256
}
268
}
257
 
269
 
258
function deplacerMarker(latLng) {
270
function deplacerMarker(latLng) {
259
	if (marker != undefined) {
271
	if (marker != undefined) {
260
		marker.setPosition(latLng);
272
		marker.setPosition(latLng);
261
		map.setCenter(latLng);
273
		map.setCenter(latLng);
262
		mettreAJourMarkerPosition(latLng);
274
		mettreAJourMarkerPosition(latLng);
263
		trouverCommune(latLng);
275
		trouverCommune(latLng);
264
	}
276
	}
265
}
277
}
266
 
278
 
267
function mettreAJourMarkerPosition(latLng) {
279
function mettreAJourMarkerPosition(latLng) {
268
	var lat = latLng.lat().toFixed(5),
280
	var lat = latLng.lat().toFixed(5),
269
		lng = latLng.lng().toFixed(5); 
281
		lng = latLng.lng().toFixed(5); 
270
	remplirChampLatitude(lat);
282
	remplirChampLatitude(lat);
271
	remplirChampLongitude(lng);
283
	remplirChampLongitude(lng);
272
}
284
}
273
 
285
 
274
function remplirChampLatitude(latDecimale) {
286
function remplirChampLatitude(latDecimale) {
275
	var lat = Math.round(latDecimale * 100000) / 100000;
287
	var lat = Math.round(latDecimale * 100000) / 100000;
276
	$('#latitude').val(lat);
288
	$('#latitude').val(lat);
277
}
289
}
278
 
290
 
279
function remplirChampLongitude(lngDecimale) {
291
function remplirChampLongitude(lngDecimale) {
280
	var lng = Math.round(lngDecimale * 100000) / 100000;
292
	var lng = Math.round(lngDecimale * 100000) / 100000;
281
	$('#longitude').val(lng);
293
	$('#longitude').val(lng);
282
}
294
}
283
 
295
 
284
function trouverCommune(pos) {
296
function trouverCommune(pos) {
285
	$(function() {
297
	$(function() {
286
		var url_service = SERVICE_NOM_COMMUNE_URL,
298
		var url_service = SERVICE_NOM_COMMUNE_URL,
287
			urlNomCommuneFormatee = url_service.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
299
			urlNomCommuneFormatee = url_service.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
288
		$.ajax({
300
		$.ajax({
289
			url: urlNomCommuneFormatee,
301
			url: urlNomCommuneFormatee,
290
			type: 'GET',
302
			type: 'GET',
291
			dataType: 'jsonp',
303
			dataType: 'jsonp',
292
			beforeSend: function() {
304
			beforeSend: function() {
293
				$('.commune-info').empty();	
305
				$('.commune-info').empty();	
294
				$('#dialogue-erreur .alert-txt').empty();
306
				$('#dialogue-erreur .alert-txt').empty();
295
			},
307
			},
296
			success: function(data, textStatus, jqXHR) {
308
			success: function(data, textStatus, jqXHR) {
297
				$('.commune-info').empty();
309
				$('.commune-info').empty();
298
				$('#commune-nom').append(data.nom);
310
				$('#commune-nom').append(data.nom);
299
				$('#commune-code-insee').append(data.codeINSEE);
311
				$('#commune-code-insee').append(data.codeINSEE);
300
				$('#marqueur-commune').data('commune', {'nom' : data.nom, 'codeInsee' : data.codeINSEE});
312
				$('#marqueur-commune').data('commune', {'nom' : data.nom, 'codeInsee' : data.codeINSEE});
301
			},
313
			},
302
			statusCode: {
314
			statusCode: {
303
				500: function(jqXHR, textStatus, errorThrown) {
315
				500: function(jqXHR, textStatus, errorThrown) {
304
					if (DEBUG) {	
316
					if (DEBUG) {	
305
						$('#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>');
317
						$('#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>');
306
						reponse = jQuery.parseJSON(jqXHR.responseText);
318
						reponse = jQuery.parseJSON(jqXHR.responseText);
307
						var erreurMsg = "";
319
						var erreurMsg = "";
308
						if (reponse != null) {
320
						if (reponse != null) {
309
							$.each(reponse, function (cle, valeur) {
321
							$.each(reponse, function (cle, valeur) {
310
								erreurMsg += valeur + '<br />';
322
								erreurMsg += valeur + '<br />';
311
							});
323
							});
312
						}
324
						}
313
						
325
						
314
						$('#dialogue-erreur .alert-txt').append(
326
						$('#dialogue-erreur .alert-txt').append(
315
							'<p class="msg-erreur">Erreur 500 : '+errorThrown+'<br />'+erreurMsg+'</p>');
327
							'<p class="msg-erreur">Erreur 500 : '+errorThrown+'<br />'+erreurMsg+'</p>');
316
					}
328
					}
317
				}
329
				}
318
			},
330
			},
319
			error: function(jqXHR, textStatus, errorThrown) {
331
			error: function(jqXHR, textStatus, errorThrown) {
320
				if (DEBUG) {
332
				if (DEBUG) {
321
					$('#dialogue-erreur .alert-txt').append(
333
					$('#dialogue-erreur .alert-txt').append(
322
						'<p class="msg">Une erreur Ajax est survenue lors de la transmission de vos observations.</p>');
334
						'<p class="msg">Une erreur Ajax est survenue lors de la transmission de vos observations.</p>');
323
					reponse = jQuery.parseJSON(jqXHR.responseText);
335
					reponse = jQuery.parseJSON(jqXHR.responseText);
324
					var erreurMsg = '';
336
					var erreurMsg = '';
325
					if (reponse != null) {
337
					if (reponse != null) {
326
						$.each(reponse, function (cle, valeur) {
338
						$.each(reponse, function (cle, valeur) {
327
							erreurMsg += valeur + '<br />';
339
							erreurMsg += valeur + '<br />';
328
						});
340
						});
329
					}
341
					}
330
					
342
					
331
					$('#dialogue-erreur .alert-txt').append(
343
					$('#dialogue-erreur .alert-txt').append(
332
						'<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
344
						'<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
333
				}
345
				}
334
			},
346
			},
335
			complete: function(jqXHR, textStatus) {
347
			complete: function(jqXHR, textStatus) {
336
				var debugMsg = extraireEnteteDebug(jqXHR);
348
				var debugMsg = extraireEnteteDebug(jqXHR);
337
				if (debugMsg != '') {
349
				if (debugMsg != '') {
338
					if (DEBUG) {
350
					if (DEBUG) {
339
						$("#dialogue-erreur .alert-txt").append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
351
						$("#dialogue-erreur .alert-txt").append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
340
					}
352
					}
341
				}
353
				}
342
				if ($("#dialogue-erreur .msg").length > 0) {
354
				if ($("#dialogue-erreur .msg").length > 0) {
343
					$("#dialogue-erreur").show();
355
					$("#dialogue-erreur").show();
344
				}
356
				}
345
			}
357
			}
346
		});
358
		});
347
	});
359
	});
348
}
360
}
-
 
361
 
-
 
362
 
349
//+---------------------------------------------------------------------------------------------------------+
363
//+---------------------------------------------------------------------------------------------------------+
350
// IDENTITÉ
-
 
351
$(document).ready(function() {
364
//AUTO-COMPLÉTION Noms Scientifiques
352
	$('#courriel').on('blur', requeterIdentite);
-
 
353
	$('#courriel').on('keypress', testerLancementRequeteIdentite);
-
 
354
});
-
 
355
 
365
 
356
function testerLancementRequeteIdentite(event) {
366
function ajouterAutocompletionNoms() {
357
	if (event.which == 13) {
367
	$('#taxon').autocomplete({
358
		requeterIdentite();
-
 
359
		event.preventDefault();
368
		source: function(requete, add){  
360
		event.stopPropagation();
-
 
361
	}
-
 
362
}
-
 
363
 
369
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
364
function requeterIdentite() {
-
 
365
	var courriel = $('#courriel').val();
-
 
366
	//TODO: mettre ceci en paramètre de config
-
 
367
	var urlAnnuaire = SERVICE_ANNUAIRE_ID_URL + courriel;
-
 
368
	$.ajax({
-
 
369
		url: urlAnnuaire,
370
			
370
		type: 'GET',
371
			var url = getUrlAutocompletionNomsSci();
371
		success: function(data, textStatus, jqXHR) {
-
 
372
			console.log('SUCCESS:'+textStatus);
372
			$.getJSON(url, function(data) {
373
			if (data != undefined && data[courriel] != undefined) {
-
 
374
				var infos = data[courriel];
-
 
375
				$('#id_utilisateur').val(infos.id);
-
 
376
				$('#prenom').val(infos.prenom);
-
 
377
				$('#nom').val(infos.nom);
-
 
378
				$('#courriel_confirmation').val(courriel);
373
				console.log(data);
379
				$('#prenom, #nom, #courriel_confirmation').attr('disabled', 'disabled');
-
 
380
				$('#date').focus();
-
 
381
			} else {
374
				var suggestions = traiterRetourNomsSci(data);
382
				surErreurCompletionCourriel();
-
 
383
			}
-
 
384
		},
-
 
385
		error: function(jqXHR, textStatus, errorThrown) {
-
 
386
			console.log('ERREUR :'+textStatus);
375
				add(suggestions);  
-
 
376
			});
-
 
377
		},
-
 
378
		html: true
387
			surErreurCompletionCourriel();
379
	});
388
		},
380
	
-
 
381
	$('#taxon').bind('autocompleteselect', function(event, ui) {
389
		complete: function(jqXHR, textStatus) {
382
		$('#taxon').data(ui.item);
-
 
383
		if (ui.item.retenu == true) {
390
			console.log('COMPLETE :'+textStatus);
384
			$('#taxon').addClass('ns-retenu');
391
			$('#zone-prenom-nom').removeClass('hidden');
385
		} else {
392
			$('#zone-courriel-confirmation').removeClass('hidden');
386
			$('#taxon').removeClass('ns-retenu');
393
		}
387
		}
394
	});
388
	});
395
}
389
}
396
 
390
 
397
function surErreurCompletionCourriel() {
391
function getUrlAutocompletionNomsSci() {
398
	$('#prenom, #nom, #courriel_confirmation').val('');
392
	var mots = $('#taxon').val(),
399
	$('#prenom, #nom, #courriel_confirmation').removeAttr('disabled');
393
		url = SERVICE_AUTOCOMPLETION_NOM_SCI_URL_TPL.replace('{referentiel}',NOM_SCI_PROJET);
-
 
394
	url = url.replace('{masque}', mots);
400
	afficherPanneau('#dialogue-courriel-introuvable');
395
	return url;
401
}
-
 
402
//+---------------------------------------------------------------------------------------------------------+
-
 
403
// FORMULAIRE
-
 
404
var obsNbre = 0;
-
 
405
 
-
 
406
$(document).ready(function() {
-
 
407
	// Sliders
-
 
408
	transformerEnSlider('#presence-zone-vegetalise');
-
 
409
	transformerEnSlider('#hauteur-batiment-avoisinant');
-
 
410
	transformerEnSlider('#periodicite-traitement-phyto');
-
 
411
	transformerEnSlider('#resistance-traitement-phyto');
-
 
-
 
396
}
-
 
397
 
-
 
398
function traiterRetourNomsSci(data) {
412
	transformerEnSlider('#vitesse-croissance');
399
	var suggestions = [];
-
 
400
	if (data.resultat != undefined) {
-
 
401
		$.each(data.resultat, function(i, val) {
-
 
402
			val.nn = i;
-
 
403
			var nom = {label: '', value: '', nt: '', nomSel: '', nomSelComplet: '', numNomSel: '',
413
	
404
				nomRet: '', numNomRet: '', famille: '', retenu: false
-
 
405
			};
414
	// Afficher/Cacher champs cachés par défaut
406
			if (suggestions.length >= AUTOCOMPLETION_ELEMENTS_NBRE) {
415
	$('#periodicite-traitement-phyto').on('change', function() {
407
				nom.label = '...';
-
 
408
				nom.value = $('#taxon').val();
416
		if ($(this).val() === 'jamais') {
409
				suggestions.push(nom);
-
 
410
				return false;
-
 
411
			} else {
417
			$('#datp-zone').removeClass('hidden');
412
				nom.label = val.nom_sci_complet;
-
 
413
				nom.value = val.nom_sci_complet;
-
 
414
				nom.nt = val.num_taxonomique;
-
 
415
				nom.nomSel = val.nom_sci;
-
 
416
				nom.nomSelComplet = val.nom_sci_complet;
-
 
417
				nom.numNomSel = val.nn;
-
 
418
				nom.nomRet = val.nom_retenu_complet;
-
 
419
				nom.numNomRet = val['nom_retenu.id'];
-
 
420
				nom.famille = val.famille;
-
 
421
				nom.retenu = (val.retenu == 'false') ? false : true;
418
		} else {
422
				
419
			$('#datp-zone').addClass('hidden');
423
				suggestions.push(nom);
420
		}
-
 
421
	});
-
 
422
	$('#taxon-liste').on('change', function() {
-
 
423
		if ($(this).val() === '?') {
-
 
424
			$('#taxon-input-groupe').removeClass('hidden');
-
 
425
		} else {
424
			}
426
			$('#taxon-input-groupe').addClass('hidden');
425
		});
427
		}
426
	}
428
	});
-
 
-
 
427
	return suggestions;
429
	
428
}
-
 
429
 
-
 
430
/*
-
 
431
* jQuery UI Autocomplete HTML Extension
-
 
432
*
430
	$('.alert .close').on('click', fermerPanneauAlert);
433
* Copyright 2010, Scott González (http://scottgonzalez.com)
-
 
434
* Dual licensed under the MIT or GPL Version 2 licenses.
-
 
435
*
-
 
436
* http://github.com/scottgonzalez/jquery-ui-extensions
-
 
437
* 
-
 
438
* Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
-
 
439
*/
431
	
440
(function($) {
-
 
441
	var proto = $.ui.autocomplete.prototype,
432
	$('[rel=tooltip]').tooltip('enable');
442
		initSource = proto._initSource;
-
 
443
	
-
 
444
	function filter(array, term) {
-
 
445
		var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), 'i');
-
 
446
		return $.grep(array, function(value) {
-
 
447
			return matcher.test($('<div>').html(value.label || value.value || value).text());
-
 
448
		});
-
 
449
	}
-
 
450
	
-
 
451
	$.extend(proto, {
-
 
452
		_initSource: function() {
433
	$('#btn-aide').on('click', basculerAffichageAide);
453
			if (this.options.html && $.isArray(this.options.source)) {
-
 
454
				this.source = function( request, response ) {
-
 
455
					response(filter(this.options.source, request.term));
-
 
456
				};
-
 
457
			} else {
434
	
458
				initSource.call(this);
-
 
459
			}
-
 
460
		},
435
	$('#prenom').on('change', formaterPrenom);
461
		_renderItem: function(ul, item) {
-
 
462
			if (item.retenu == true) {
-
 
463
				item.label = '<strong>'+item.label+'</strong>';
-
 
464
			}
-
 
465
			
-
 
466
			return $('<li></li>')
-
 
467
				.data('item.autocomplete', item)
-
 
468
				.append($('<a></a>')[this.options.html ? 'html' : 'text'](item.label))
436
	$('#nom').on('change', formaterNom);
469
				.appendTo(ul);
-
 
470
		}
437
	
471
	});
-
 
472
})(jQuery);
438
	configurerDatePicker('#date');
473
 
-
 
474
//+----------------------------------------------------------------------------------------------------------+
-
 
475
//UPLOAD PHOTO : Traitement de l'image 
439
	configurerDatePicker('#date-arret-traitement-phyto');
476
$(document).ready(function() {
-
 
477
	$('body').on('click', '.effacer-miniature', function(event) {
-
 
478
		supprimerMiniature($(this));
-
 
479
	});
-
 
480
	
-
 
481
	$('#photo-placeholder').click(function(event) {
-
 
482
		$('#fichier').click();
-
 
483
	});
-
 
484
	
-
 
485
	$('#fichier').bind('change', function (e) {
-
 
486
		arreter(e);
-
 
487
		var options = { 
-
 
488
			success: afficherMiniature, // post-submit callback 
-
 
489
			dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type) 
-
 
490
			resetForm: true // reset the form after successful submit 
-
 
491
		};
-
 
492
		$('#miniature').append(
440
	
493
			'<img id="miniature-chargement" class="miniature" alt="chargement" src="'+CHARGEMENT_IMAGE_URL+'"/>');
-
 
494
		$('#ajouter-obs').attr('disabled', 'disabled');
-
 
495
		if (verifierFormat($('#fichier').val())) {
-
 
496
			$('#form-upload').ajaxSubmit(options);
-
 
497
		} else {
-
 
498
			window.alert("Le format de fichier n'est pas supporté, les formats acceptés sont "+	$('#fichier').attr('accept'));
-
 
499
		}
441
	ajouterAutocompletionNoms();
500
		return false;
-
 
501
	});
-
 
502
	
-
 
503
	$('.effacer-miniature').on('click', function() {
-
 
504
		$(this).parent().remove();
-
 
505
	});
-
 
506
});
-
 
507
 
-
 
508
function verifierFormat(nom) {
-
 
509
	var parts = nom.split('.');
-
 
510
	extension = parts[parts.length - 1];
442
	
511
	return (extension.toLowerCase() == 'jpeg' || extension.toLowerCase() == 'jpg');
-
 
512
}
-
 
513
 
-
 
514
function afficherMiniature(reponse) { 
-
 
515
	if (DEBUG) {
443
	configurerFormValidator();
516
		var debogage = $('debogage', reponse).text();
-
 
517
		console.log('Débogage upload : ' + debogage);
-
 
518
	}
-
 
519
	var message = $('message', reponse).text();
-
 
520
	if (message != '') {
-
 
521
		$('#miniature-msg').append(message);
-
 
522
	} else {
-
 
523
		$('#miniatures').append(creerWidgetMiniature(reponse));
-
 
524
	}
444
	definirReglesFormValidator();
525
	$('#ajouter-obs').removeAttr('disabled');	
445
		
-
 
446
	$('#courriel_confirmation').on('paste', bloquerCopierCollerCourriel);
526
}
447
		
527
 
-
 
528
function creerWidgetMiniature(reponse) {
-
 
529
	var miniatureUrl = $('miniature-url', reponse).text(),
-
 
530
		imgNom = $('image-nom', reponse).text(),
-
 
531
		html = 
-
 
532
			'<div class="miniature">'+
-
 
533
				'<img class="miniature-img" class="miniature" alt="'+imgNom+'" src="'+miniatureUrl+'"/>'+
-
 
534
				'<button class="btn effacer-miniature" type="button">Effacer</button>'+
-
 
535
			'</div>'
-
 
536
	return html;
-
 
537
}
-
 
538
 
-
 
539
function supprimerMiniature(miniature) {
-
 
540
	miniature.parents('.miniature').remove();
-
 
541
}
-
 
542
 
-
 
543
function supprimerMiniatures() {
-
 
544
	$('#miniatures').empty();
-
 
545
	$('#miniature-msg').empty();
448
	$('a.afficher-coord').on('click', basculerAffichageCoord);
546
}
449
	
547
 
-
 
548
 
-
 
549
//+---------------------------------------------------------------------------------------------------------+
450
	$('#ajouter-obs').on('click', ajouterObs);
550
// FORMULAIRE : traitements génériques
-
 
551
 
451
	
552
$(document).ready(function() {
-
 
553
	// Sliders
-
 
554
	transformerEnSlider('#presence-zone-vegetalise');
-
 
555
	transformerEnSlider('#hauteur-batiment-avoisinant');
-
 
556
	transformerEnSlider('#periodicite-traitement-phyto');
-
 
557
	transformerEnSlider('#resistance-traitement-phyto');
-
 
558
	transformerEnSlider('#vitesse-croissance');
-
 
559
	
-
 
560
	// Afficher/Cacher champs cachés par défaut
-
 
561
	$('#periodicite-traitement-phyto').on('change', function() {
-
 
562
		if ($(this).val() === 'jamais') {
-
 
563
			$('#datp-zone').removeClass('hidden');
-
 
564
		} else {
-
 
565
			$('#datp-zone').addClass('hidden');
-
 
566
		}
-
 
567
	});
-
 
568
	$('#taxon-liste').on('change', function() {
-
 
569
		if ($(this).val() === '?') {
-
 
570
			$('#taxon-input-groupe').removeClass('hidden');
-
 
571
		} else {
-
 
572
			$('#taxon-input-groupe').addClass('hidden');
-
 
573
		}
-
 
574
	});
-
 
575
	
452
	$('.obs-nbre').on('changement', surChangementNbreObs);
576
	$('.alert .close').on('click', fermerPanneauAlert);
453
	
577
	
454
	$('body').on('click', '.supprimer-obs', supprimerObs);
578
	$('[rel=tooltip]').tooltip('enable');
455
	
579
	$('#btn-aide').on('click', basculerAffichageAide);
456
	$('#transmettre-obs').on('click', transmettreObs);
580
	
457
	
581
	$('#prenom').on('change', formaterPrenom);
458
	$('body').on('click', '.defilement-miniatures-gauche', function(event) {
582
	$('#nom').on('change', formaterNom);
459
		event.preventDefault();
583
	
460
		defilerMiniatures($(this));
584
	configurerDatePicker('#date');
461
	});
585
	configurerDatePicker('#date-arret-traitement-phyto');
462
	
586
	
463
	$('body').on('click', '.defilement-miniatures-droite', function(event) {
587
	ajouterAutocompletionNoms();
464
		event.preventDefault();
588
	
465
		defilerMiniatures($(this));
589
	configurerFormValidator();
466
	});
590
	definirReglesFormValidator();
467
	
591
	
468
	$('.dropdown-menu input, .dropdown-menu label').on('click', function(event) {
592
	$('.dropdown-menu input, .dropdown-menu label').on('click', function(event) {
469
		event.stopPropagation();
593
		event.stopPropagation();
470
	});
594
	});
-
 
595
	$('.cb-milieux').on('click', function(event) {
-
 
596
		$(this).valid();
-
 
597
		event.stopPropagation();
-
 
598
	});
471
	
599
	
472
	$('input#hauteur-plante').on('blur', function() {
600
	$('input#hauteur-plante').on('blur', function() {
473
		// if there's a bad value
601
		// if there's a bad value
474
		var valeur = $(this).val();
602
		var valeur = $(this).val();
475
		console.log(valeur);
603
		console.log(valeur);
476
		if (! valeur.match(/^[0-9]+$/)) {
604
		if (! valeur.match(/^[0-9]+$/)) {
477
			// replace it with nothing
605
			// replace it with nothing
478
			var nouvelleValeur = valeur.replace(/[^0-9]/g, '');
606
			var nouvelleValeur = valeur.replace(/[^0-9]/g, '');
479
			$(this).val(nouvelleValeur);
607
			$(this).val(nouvelleValeur);
480
		}
608
		}
481
	});
609
	});
-
 
610
	
-
 
611
	$('#courriel_confirmation').on('paste', bloquerCopierCollerCourriel);
-
 
612
		
-
 
613
	$('a.afficher-coord').on('click', basculerAffichageCoord);
-
 
614
	
-
 
615
	$('#ajouter-obs').on('click', ajouterObs);
-
 
616
	
-
 
617
	$('.obs-nbre').on('changement', surChangementNbreObs);
-
 
618
	
-
 
619
	$('body').on('click', '.supprimer-obs', supprimerObs);
-
 
620
	
-
 
621
	$('#transmettre-obs').on('click', transmettreObs);
-
 
622
	
-
 
623
	$('body').on('click', '.defilement-control-zone', function(event) {
-
 
624
		defilerMiniatures($(this));
-
 
625
	});
-
 
626
	$('body').on('mouseover', '.defilement-control-zone', function(event) {
-
 
627
		$('.defilement-control', this).removeClass('hidden');
-
 
628
	});
-
 
629
	$('body').on('mouseout', '.defilement-control-zone', function(event) {
-
 
630
		$('.defilement-control', this).addClass('hidden');
-
 
631
	});
-
 
632
	
482
});
633
});
483
 
634
 
484
function transformerEnSlider(selector) {
635
function transformerEnSlider(selector) {
485
	$(selector).each(function(index, el) {
636
	$(selector).each(function(index, el) {
486
		// hide the element
637
		// hide the element
487
		$(el).addClass('slider-on');
638
		$(el).addClass('slider-on');
488
		
639
		
489
		// add the slider to each element
640
		// add the slider to each element
490
		var slider = $( '<div class="slider-holder"><div class="horizontal-slider"></div></div>' ).
641
		var slider = $( '<div class="slider-holder"><div class="horizontal-slider"></div></div>' ).
491
			insertBefore( el ).find('.horizontal-slider').slider({
642
			insertBefore( el ).find('.horizontal-slider').slider({
492
				min: 1,
643
				min: 1,
493
				max: el.options.length,
644
				max: el.options.length,
494
				range: 'min',
645
				range: 'min',
495
				value: el.selectedIndex + 1,
646
				value: el.selectedIndex + 1,
496
				slide: function( event, ui ) {
647
				slide: function(event, ui) {
497
					el.selectedIndex = ui.value - 1;
648
					el.selectedIndex = ui.value - 1;
498
					slider.find('a').text(el.options[el.selectedIndex].text);
649
					slider.find('a').text(el.options[el.selectedIndex].text);
-
 
650
					
-
 
651
					$(selector + ' option[selected="selected"]').removeAttr('selected');
-
 
652
					$(selector + ' :nth-child('+ui.value+')').attr('selected', 'selected')
-
 
653
					$(selector).valid();
499
				},
654
				},
500
				stop: function() {
655
				stop: function() {
501
					$(el).change();
656
					$(el).change();
502
				}
657
				}
503
			});
658
			});
504
		
659
		
505
		slider.find('a').text(el.options[el.selectedIndex].text);
660
		slider.find('a').text(el.options[el.selectedIndex].text);
506
		
661
		
507
		// Create a legend under the slider so we can see the options
662
		// Create a legend under the slider so we can see the options
508
		var options = [];
663
		var options = [];
509
		for (var option in $(el).children()) {
664
		for (var option in $(el).children()) {
510
			if (!isNaN(parseInt(option))) {
665
			if (!isNaN(parseInt(option))) {
511
				options.push(el.options[option].text);
666
				options.push(el.options[option].text);
512
			}
667
			}
513
		}
668
		}
514
		// the width of each legend/option
669
		// the width of each legend/option
515
		var width = (slider.width() / (options.length - 1));
670
		var width = (slider.width() / (options.length - 1));
516
		
671
		
517
		// Add the legend. Half the width of the first and last options for display consistency.
672
		// Add the legend. Half the width of the first and last options for display consistency.
518
		slider.after('<div class="slider-legend"><p style="width:' + (width / 2) + 'px;text-align:left;">' + 
673
		slider.after('<div class="slider-legend"><p style="width:' + (width / 2) + 'px;text-align:left;">' + 
519
			options.join('</p><p style="width:' + width + 'px;">') +'</p></div>')
674
			options.join('</p><p style="width:' + width + 'px;">') +'</p></div>')
520
			.parent().find('.slider-legend p:last-child').css('width', width / 2)
675
			.parent().find('.slider-legend p:last-child').css('width', width / 2)
521
			.css('text-align', 'right');
676
			.css('text-align', 'right');
522
		
677
		
523
		// if there are too many options so that the text is wider than the width, then hide the text
678
		// if there are too many options so that the text is wider than the width, then hide the text
524
		var lastChild = slider.parent().find('.slider-legend p:last-child');
679
		var lastChild = slider.parent().find('.slider-legend p:last-child');
525
		if (lastChild[0].clientWidth < lastChild[0].scrollWidth) {
680
		if (lastChild[0].clientWidth < lastChild[0].scrollWidth) {
526
			slider.parent().find('.slider-legend p');//.css('text-indent', '200%');
681
			slider.parent().find('.slider-legend p');//.css('text-indent', '200%');
527
		}
682
		}
528
	});
683
	});
529
}
684
}
-
 
685
 
-
 
686
function configurerDatePicker(selector) {
-
 
687
	$.datepicker.setDefaults($.datepicker.regional['fr']);
-
 
688
	$(selector).datepicker({
-
 
689
		dateFormat: 'dd/mm/yy',
-
 
690
		showOn: 'button',
-
 
691
		buttonImageOnly: true,
-
 
692
		buttonImage: CALENDRIER_ICONE_URL,
-
 
693
		buttonText: 'Afficher le calendrier pour saisir la date.',
-
 
694
		showButtonPanel: true,
-
 
695
		onSelect: function(date) {
-
 
696
			$(this).valid();
-
 
697
        }
-
 
698
	});
-
 
699
	$(selector + ' + img.ui-datepicker-trigger').appendTo(selector + '-icone.add-on');
-
 
700
}
530
 
701
 
531
function configurerFormValidator() {
702
function configurerFormValidator() {
532
	$.validator.addMethod(
703
	$.validator.addMethod(
533
		'dateCel', 
704
		'dateCel', 
534
		function (value, element) { 
705
		function (value, element) { 
535
			return value == '' || (/^[0-9]{2}[-\/][0-9]{2}[-\/][0-9]{4}$/.test(value)); 
706
			return value == '' || (/^[0-9]{2}[-\/][0-9]{2}[-\/][0-9]{4}$/.test(value)); 
536
		}, 
707
		}, 
537
		'Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.');
708
		'Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.');
538
	$.validator.addMethod(
-
 
539
		'chckMilieux', 
-
 
540
		function(value, element) { 
-
 
541
			var ok = $('input[name="milieux"]:checked').length > 0 ? true : false;
-
 
542
			console.log('Check Milieux : ' + ok);
-
 
543
			return ok; 
-
 
544
		}, 
-
 
545
		'Veuillez sélectionner au moins une case à cocher.');
-
 
546
	
709
	
-
 
710
	$.extend($.validator.defaults, {
547
	$.extend($.validator.defaults, {
711
		ignore: [],// Forcer Jquery Validate à examiner les éléments avec en display:none;
548
		highlight: function(element) {
712
		highlight: function(element) {
549
			$(element).closest('.control-group').removeClass('success').addClass('error');
-
 
550
			
-
 
551
			console.log('KO:'+$(element).attr('name')+' / nbre: '+$(element).length);
-
 
552
			
713
			$(element).closest('.control-group').removeClass('success').addClass('error');
553
		},
714
		},
554
		success: function(element) {
-
 
555
			console.log('OK:'+element.before+' / nbre: '+$(element).length);
-
 
556
			console.log(element);
-
 
557
			
715
		success: function(element) {
558
			element.text('OK!').addClass('valid');
716
			element.text('OK!').addClass('valid');
559
			element.closest('.control-group').removeClass('error').addClass('success');
717
			element.closest('.control-group').removeClass('error').addClass('success');
560
			
718
			
561
			if (element.attr('id') == 'taxon' && $('#taxon').val() != '') {
719
			if (element.attr('id') == 'taxon' && $('#taxon').val() != '') {
562
				// Si le taxon n'est pas lié au référentiel, on vide le data associé
720
				// Si le taxon n'est pas lié au référentiel, on vide le data associé
563
				if ($('#taxon').data('value') != $('#taxon').val()) {
721
				if ($('#taxon').data('value') != $('#taxon').val()) {
564
					$('#taxon').data('numNomSel', '');
722
					$('#taxon').data('numNomSel', '');
565
					$('#taxon').data('nomRet', '');
723
					$('#taxon').data('nomRet', '');
566
					$('#taxon').data('numNomRet', '');
724
					$('#taxon').data('numNomRet', '');
567
					$('#taxon').data('nt', '');
725
					$('#taxon').data('nt', '');
568
					$('#taxon').data('famille', '');
726
					$('#taxon').data('famille', '');
569
				}
727
				}
570
			}
728
			}
571
		}
729
		}
572
	});
730
	});
573
}
731
}
574
 
732
 
575
function definirReglesFormValidator() {
733
function definirReglesFormValidator() {
576
	$('#form-observateur').validate({
734
	$('#form-observateur').validate({
577
		rules: {
735
		rules: {
578
			courriel: {
736
			courriel: {
579
				required: true,
737
				required: true,
580
				email: true},
738
				email: true},
581
			courriel_confirmation: {
739
			courriel_confirmation: {
582
				required: true,
740
				required: true,
583
				equalTo: '#courriel'},
741
				equalTo: '#courriel'},
584
			prenom: {
742
			prenom: {
585
				required: true},
743
				required: true},
586
			nom: {
744
			nom: {
587
				required: true},
745
				required: true},
588
			personneStructure: {
746
			personneStructure: {
589
				required: true},
747
				required: true},
590
			personneService: {
748
			personneService: {
591
				required: true}
749
				required: true}
592
		}
750
		}
593
	});
751
	});
594
	$('#form-site').validate({
752
	$('#form-site').validate({
595
		rules: {
753
		rules: {
596
			station: {
754
			station: {
597
				required: true},
755
				required: true},
598
			latitude : {
756
			latitude : {
599
				required: true,
757
				required: true,
600
				range: [-90, 90]},
758
				range: [-90, 90]},
601
			longitude: {
759
			longitude: {
602
				required: true,
760
				required: true,
603
				range: [-180, 180]},
761
				range: [-180, 180]},
604
			typoUrbaine: {
762
			typoUrbaine: {
605
				required: true},
763
				required: true},
606
			revetementSol: {
764
			revetementSol: {
607
				required: true},
765
				required: true},
608
			intensiteGestion: {
766
			intensiteGestion: {
609
				required: true},
767
				required: true},
610
			periodiciteTraitementPhyto: {
768
			periodiciteTraitementPhyto: {
611
				required: true},
769
				required: true},
612
			itineraireGestion: {
770
			itineraireGestion: {
613
				required: true}
771
				required: true}
614
		}
772
		}
615
	});
773
	});
616
	$('#form-date').validate({
774
	$('#form-date').validate({
617
		rules: {
775
		rules: {
618
			date: {
776
			date: {
619
				required: true,
777
				required: true,
620
				'dateCel' : true},
778
				'dateCel' : true},
621
			dateDerniereIntervention: {
779
			dateDerniereIntervention: {
622
				required: true}
780
				required: true}
-
 
781
		},
-
 
782
		errorPlacement: function(error, element) {
-
 
783
	        if (element.attr('name') == 'date') {
-
 
784
		        element.parent('.input-prepend').after(error);
-
 
785
	        } else {
-
 
786
	        	error.insertAfter(element);
-
 
787
	        }
623
		}
788
	    }
624
	});
789
	});
625
	$('#form-obs').validate({
790
	$('#form-obs').validate({
626
		rules: {
791
		rules: {
627
			'taxon-liste': {
792
			'taxon-liste': {
628
				required: true},
793
				required: true},
629
			milieux: {
794
			'milieux[]': {
630
				chckMilieux:true},
795
				required: true,
-
 
796
				minlength: 1},
631
			hauteurPlante: {
797
			hauteurPlante: {
632
				required: true,
798
				required: true,
633
				digits: true},
799
				digits: true},
634
			resistanceTraitementPhyto: {
800
			resistanceTraitementPhyto: {
635
				required: true}
801
				required: true}
-
 
802
		},
-
 
803
		errorPlacement: function(error, element) {
-
 
804
	        if (element.attr('name') == 'milieux[]') {
-
 
805
		        error.insertAfter('#milieux-controls');
-
 
806
	        } else {
-
 
807
	        	error.insertAfter(element);
636
		}
808
	        }
637
	});
-
 
638
}
809
	    }
639
 
-
 
640
function configurerDatePicker(selector) {
-
 
641
	$.datepicker.setDefaults($.datepicker.regional['fr']);
-
 
642
	$(selector).datepicker({
-
 
643
		dateFormat: 'dd/mm/yy',
-
 
644
		showOn: 'button',
-
 
645
		buttonImageOnly: true,
-
 
646
		buttonImage: CALENDRIER_ICONE_URL,
-
 
647
		buttonText: 'Afficher le calendrier pour saisir la date.',
-
 
648
		showButtonPanel: true
-
 
649
	});
810
	});
650
	$(selector + ' + img.ui-datepicker-trigger').appendTo(selector + '-icone.add-on');
-
 
651
}
811
}
652
 
812
 
653
function fermerPanneauAlert() {
813
function validerFormulaire() {
-
 
814
	var observateur = $('#form-observateur').valid(),
-
 
815
		station = $('#form-site').valid(),
-
 
816
		date = $('#form-date').valid(),
-
 
817
		obs = $('#form-obs').valid();
654
	$(this).parentsUntil('.zone-alerte', '.alert').hide();
818
	return (observateur == true && station == true && obs == true && date == true) ? true : false;
655
}
-
 
656
 
-
 
657
function formaterNom() {
-
 
658
	$(this).val($(this).val().toUpperCase());
819
}
659
}
-
 
660
 
-
 
661
function formaterPrenom() {
-
 
662
	var prenom = new Array(),
-
 
663
		mots = $(this).val().split(' ');
-
 
664
	for (var i = 0; i < mots.length; i++) {
-
 
665
		var mot = mots[i];
-
 
666
		if (mot.indexOf('-') >= 0) {
-
 
667
			var prenomCompose = new Array(),
-
 
668
				motsComposes = mot.split('-');
-
 
669
			for (var j = 0; j < motsComposes.length; j++) {
-
 
670
				var motSimple = motsComposes[j],
-
 
671
					motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
-
 
672
				prenomCompose.push(motMajuscule);
-
 
673
			}
-
 
674
			prenom.push(prenomCompose.join('-'));
-
 
675
		} else {
-
 
676
			var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
-
 
677
			prenom.push(motMajuscule);
820
 
678
		}
821
 
679
	}
822
function fermerPanneauAlert() {
680
	$(this).val(prenom.join(' '));
823
	$(this).parentsUntil('.zone-alerte', '.alert').hide();
681
}
824
}
682
 
825
 
683
function basculerAffichageAide() {
826
function basculerAffichageAide() {
684
	if ($(this).hasClass('btn-warning')) {
827
	if ($(this).hasClass('btn-warning')) {
685
		$('[rel=tooltip]').tooltip('enable');
828
		$('[rel=tooltip]').tooltip('enable');
686
		$(this).removeClass('btn-warning').addClass('btn-success');
829
		$(this).removeClass('btn-warning').addClass('btn-success');
687
		$('#btn-aide-txt', this).text("Désactiver l'aide");
830
		$('#btn-aide-txt', this).text("Désactiver l'aide");
688
	} else {
831
	} else {
689
		$('[rel=tooltip]').tooltip('disable');
832
		$('[rel=tooltip]').tooltip('disable');
690
		$(this).removeClass('btn-success').addClass('btn-warning');
833
		$(this).removeClass('btn-success').addClass('btn-warning');
691
		$('#btn-aide-txt', this).text("Activer l'aide");
834
		$('#btn-aide-txt', this).text("Activer l'aide");
692
	}
835
	}
693
}
836
}
694
 
837
 
695
function bloquerCopierCollerCourriel() {
838
function bloquerCopierCollerCourriel() {
696
	afficherPanneau('#dialogue-bloquer-copier-coller');
839
	afficherPanneau('#dialogue-bloquer-copier-coller');
697
	return false;
840
	return false;
698
}
841
}
699
 
842
 
700
function basculerAffichageCoord() {
843
function basculerAffichageCoord() {
701
	$('.afficher-coord-action').toggle();
844
	$('.afficher-coord-action').toggle();
702
	$('#coordonnees-geo').toggle('slow');
845
	$('#coordonnees-geo').toggle('slow');
703
	//valeur false pour que le lien ne soit pas suivi
846
	//valeur false pour que le lien ne soit pas suivi
704
	return false;
847
	return false;
705
}
848
}
-
 
849
 
-
 
850
 
-
 
851
//+----------------------------------------------------------------------------------------------------------+
-
 
852
// CRÉER OBS : Gestion des obs
-
 
853
 
-
 
854
var obsNbre = 0;
706
 
855
 
707
function ajouterObs() {
856
function ajouterObs() {
708
	if (validerFormulaire() == true) {
857
	if (validerFormulaire() == true) {
709
		obsNbre = obsNbre + 1;
858
		obsNbre = obsNbre + 1;
710
		$('.obs-nbre').text(obsNbre);
859
		$('.obs-nbre').text(obsNbre);
711
		$('.obs-nbre').triggerHandler('changement');
860
		$('.obs-nbre').triggerHandler('changement');
712
		afficherObs();
861
		afficherObs();
713
		stockerObsData();
862
		stockerObsData();
714
		supprimerMiniatures();
863
		supprimerMiniatures();
715
		$('#taxon').val('').data('numNomSel', undefined).removeClass('ns-retenu');
864
		$('#taxon').val('').data('numNomSel', undefined).removeClass('ns-retenu');
716
	} else {
865
	} else {
717
		afficherPanneau('#dialogue-form-invalide');
866
		afficherPanneau('#dialogue-form-invalide');
718
	}
867
	}
719
}
868
}
720
 
869
 
721
function afficherObs() {
870
function afficherObs() {
722
	var numNomSel = ($('#taxon-liste').val() == '?') ? $('#taxon').data('numNomSel') : $('#taxon-liste').val(),
871
	var numNomSel = ($('#taxon-liste').val() == '?') ? $('#taxon').data('numNomSel') : $('#taxon-liste').val(),
723
		taxon = ($('#taxon-liste').val() == '?') ? $('#taxon').val() : taxons[numNomSel]['nom_sel'],
872
		taxon = ($('#taxon-liste').val() == '?') ? $('#taxon').val() : taxons[numNomSel]['nom_sel'],
724
		referentiel = (numNomSel == undefined) ? '' : '['+NOM_SCI_PROJET+']',
873
		referentiel = (numNomSel == undefined) ? '' : '['+NOM_SCI_PROJET+']',
725
		commune = $('#commune-nom').text(),
874
		commune = $('#commune-nom').text(),
726
		codeInsee = $('#commune-code-insee').text(),
875
		codeInsee = $('#commune-code-insee').text(),
727
		lat = $('input[name="latitude"]').val(),
876
		lat = $('input[name="latitude"]').val(),
728
		lng = $('input[name="longitude"]').val(),
877
		lng = $('input[name="longitude"]').val(),
729
		date = $('#date').val(),
878
		date = $('#date').val(),
730
		site = $('#station').val(),
879
		site = $('#station').val(),
731
		milieux = getMilieux(),
880
		milieux = getMilieux(),
732
		notes = $('#notes').val();
881
		notes = $('#notes').val();
733
	
882
	
734
	$('#liste-obs').prepend(
883
	$('#liste-obs').prepend(
735
		'<div id="obs'+obsNbre+'" class="row-fluid obs obs'+obsNbre+'">'+
884
		'<div id="obs'+obsNbre+'" class="row-fluid obs obs'+obsNbre+'">'+
736
			'<div class="span12">'+
885
			'<div class="span12">'+
737
				'<div class="well">'+
886
				'<div class="well">'+
738
					'<div class="obs-action pull-right" rel="tooltip" data-placement="bottom" '+
887
					'<div class="obs-action pull-right" rel="tooltip" data-placement="bottom" '+
739
						'title="Supprimer cette observation de la liste à transmettre">'+
888
						'title="Supprimer cette observation de la liste à transmettre">'+
740
						'<button class="btn btn-danger supprimer-obs" value="'+obsNbre+'" title="'+obsNbre+'">'+
889
						'<button class="btn btn-danger supprimer-obs" value="'+obsNbre+'" title="'+obsNbre+'">'+
741
							'<i class="icon-trash icon-white"></i>'+
890
							'<i class="icon-trash icon-white"></i>'+
742
						'</button>'+
891
						'</button>'+
743
					'</div> '+		
892
					'</div> '+		
744
					'<div class="row-fluid">'+	
893
					'<div class="row-fluid">'+	
745
						'<div class="thumbnail span2">'+
894
						'<div class="span2 obs-miniatures">'+
746
							ajouterImgMiniatureAuTransfert()+
895
							ajouterImgMiniatureAuTransfert()+
747
						'</div>'+
896
						'</div>'+
748
						'<div class="span9">'+
897
						'<div class="span8">'+
749
							'<ul class="unstyled">'+
898
							'<ul class="unstyled">'+
750
								'<li>'+
899
								'<li>'+
751
									'<span class="nom-sci">' + taxon + '</span> ' +
900
									'<span class="nom-sci">' + taxon + '</span> ' +
752
									formaterNumNomSel(numNomSel)+
901
									formaterNumNomSel(numNomSel)+
753
									'<span class="referentiel-obs">' + referentiel + '</span>' +
902
									'<span class="referentiel-obs">' + referentiel + '</span>' +
754
									' observé à ' +
903
									' observé à ' +
755
									'<span class="commune">' + commune + '</span> ' +
904
									'<span class="commune">' + commune + '</span> ' +
756
									'(' + codeInsee + ') [' + lat +' / ' + lng + ']' +
905
									'(' + codeInsee + ') [' + lat +' / ' + lng + ']' +
757
									' le ' +
906
									' le ' +
758
									'<span class="date">' + date + '</span>' +
907
									'<span class="date">' + date + '</span>' +
759
								'</li>' +
908
								'</li>' +
760
								'<li>' +
909
								'<li>' +
761
									'<span>Site :</span> ' + site + ' ' +
910
									'<span>Site :</span> ' + site + ' ' +  ' ; ' +
762
									'<span>Milieu :</span> ' + milieux + ' ' +
911
									'<span>Milieu :</span> ' + milieux + ' ' +
763
								'</li>' +
912
								'</li>' +
764
								'<li>' +
913
								'<li>' +
765
									'Commentaires : <span class="discretion">' + notes + '</span>'+
914
									'Commentaires : <span class="discretion">' + notes + '</span>'+
766
								'</li>'+
915
								'</li>'+
767
							'</ul>'+
916
							'</ul>'+
768
						'</div>'+
917
						'</div>'+
769
					'</div>'+
918
					'</div>'+
770
				'</div>'+
919
				'</div>'+
771
			'</div>'+
920
			'</div>'+
772
		'</div>');
921
		'</div>');
773
}
922
}
774
 
923
 
775
function getMilieux() {
924
function getMilieux() {
776
	var milieuxStr = '',
925
	var milieuxStr = '',
777
		milieux = [];
926
		milieux = [];
778
	$('input:checkbox[name="milieux"]:checked').each(function() {
927
	$('input:checkbox[name="milieux[]"]:checked').each(function() {
779
		milieux.push($(this).val());
928
		milieux.push($(this).val());
780
	});
929
	});
781
	
930
	
782
	milieuxStr = Array.prototype.slice.call(milieux).join(', ');
931
	milieuxStr = Array.prototype.slice.call(milieux).join(', ');
783
	return milieuxStr;
932
	return milieuxStr;
784
}
933
}
785
 
934
 
786
function ajouterImgMiniatureAuTransfert() {
935
function ajouterImgMiniatureAuTransfert() {
787
	var html = '',
936
	var html = '',
788
		miniatures = '',
937
		miniatures = '',
-
 
938
		indicateurs = '',
789
		premiere = true;
939
		premiere = true,
-
 
940
		numero = 1;
790
	if ($('#miniatures img').length >= 1) {
941
	if ($('#miniatures img').length == 0) {
-
 
942
		html = '<img class="miniature" alt="Aucune photo"src="'+PAS_DE_PHOTO_ICONE_URL+'" />';
-
 
943
	} else if ($('#miniatures img').length >= 1) {
791
		$('#miniatures img').each(function() {
944
		$('#miniatures img').each(function() {
792
			var visible = premiere ? 'miniature-selectionnee' : 'miniature-cachee',
945
			var visible = premiere ? 'miniature-selectionnee' : 'miniature-cachee',
793
				css = $(this).hasClass('b64') ? 'miniature b64' : 'miniature',
946
				css = $(this).hasClass('b64') ? 'miniature b64' : 'miniature',
794
				src = $(this).attr('src'),
947
				src = $(this).attr('src'),
795
				alt = $(this).attr('alt');
948
				alt = $(this).attr('alt');
796
			premiere = false;
-
 
-
 
949
			
797
			miniature = '<img class="'+css+' '+visible+'"  alt="'+alt+'"src="'+src+'" />';
950
			var miniature = '<img class="'+css+' '+visible+'"  alt="'+alt+'"src="'+src+'" />';
798
			miniatures += miniature;
951
			miniatures += miniature;
-
 
952
			
-
 
953
			var indicateurActif = premiere ? 'active' : '';
-
 
954
			var indicateur = '<li class="' + indicateurActif + '" data-numero="' + numero++ + '"></li>';
-
 
955
			indicateurs += indicateur;
-
 
956
		
-
 
957
			premiere = false;
799
		});
958
		});
-
 
959
		
800
		visible = ($('#miniatures img').length > 1) ? '' : 'defilement-miniatures-cache';
960
		if ($('#miniatures img').length == 1) {
-
 
961
			html = miniatures;
-
 
962
		} else {
801
		var html = 
963
			html = 
802
			'<div class="defilement-miniatures">'+
964
				'<div class="defilement">' +
803
				'<a href="#" class="defilement-miniatures-gauche '+visible+'">&#60;</a>'+
-
 
804
				miniatures+
965
					miniatures +
-
 
966
					'<a class="defilement-control-zone gauche">' +
-
 
967
					'	<span class="defilement-control gauche hidden">&#60;</span>' +
-
 
968
					'</a>' +
-
 
969
					'<a class="defilement-control-zone droite">' +
805
				'<a href="#" class="defilement-miniatures-droite '+visible+'">&#62;</a>'+
970
					'	<span class="defilement-control droite hidden">&#62;</span>' +
-
 
971
					'</a>' +
-
 
972
					'<ol class="defilement-indicateurs">' + indicateurs + '</ol>' +
806
			'</div>';
973
				'</div>';
807
	} else {
974
		}
808
		html = '<img class="miniature" alt="Aucune photo"src="'+PAS_DE_PHOTO_ICONE_URL+'" />';
-
 
809
	}
975
	}
810
	return html;
976
	return html;
811
}
977
}
-
 
978
 
-
 
979
function defilerMiniatures(element) {
-
 
980
	var miniatureSelectionne = element.siblings('img.miniature-selectionnee');
-
 
981
	miniatureSelectionne.removeClass('miniature-selectionnee').addClass('miniature-cachee');
-
 
982
	var miniatureAffichee = miniatureSelectionne;
-
 
983
	
-
 
984
	var indicateurActif = element.parent().find('.defilement-indicateurs .active');
-
 
985
	console.log(indicateurActif)
-
 
986
	indicateurActif.removeClass('active');
-
 
987
	
-
 
988
	if (element.hasClass('defilement-control-zone') && element.hasClass('gauche')) {
-
 
989
		if (miniatureSelectionne.prev('.miniature').length != 0) {
-
 
990
			miniatureAffichee = miniatureSelectionne.prev('.miniature');
-
 
991
			indicateurActif.prev().addClass('active');
-
 
992
		} else {
-
 
993
			miniatureAffichee = miniatureSelectionne.siblings('.miniature').last();
-
 
994
			indicateurActif.siblings().last().addClass('active');
-
 
995
		}
-
 
996
	} else {
-
 
997
		if (miniatureSelectionne.next('.miniature').length != 0) {
-
 
998
			miniatureAffichee = miniatureSelectionne.next('.miniature');
-
 
999
			indicateurActif.next().addClass('active');
-
 
1000
		} else {
-
 
1001
			miniatureAffichee = miniatureSelectionne.siblings('.miniature').first();
-
 
1002
			indicateurActif.siblings().first().addClass('active');
-
 
1003
		}
-
 
1004
	}
-
 
1005
	miniatureAffichee.addClass('miniature-selectionnee').removeClass('miniature-cachee');
-
 
1006
}
812
 
1007
 
813
function formaterNumNomSel(numNomSel) {
1008
function formaterNumNomSel(numNomSel) {
814
	var nn = '';
-
 
815
	
1009
	var nn = '';
816
	if (numNomSel == undefined) {
1010
	if (numNomSel == undefined) {
817
		nn = '<span class="alert-error">[non lié au référentiel]</span>';
1011
		nn = '<span class="alert-error">[non lié au référentiel]</span>';
818
	} else {
1012
	} else {
819
		nn = '<span class="nn">[nn'+numNomSel+']</span>';
1013
		nn = '<span class="nn">[nn'+numNomSel+']</span>';
820
	}
1014
	}
821
	return nn;
1015
	return nn;
822
}
1016
}
823
 
1017
 
824
function stockerObsData() {
1018
function stockerObsData() {
825
	$('#liste-obs').data('obsId'+obsNbre, {
1019
	$('#liste-obs').data('obsId'+obsNbre, {
826
		'date' : $('#date').val(), 
1020
		'date' : $('#date').val(), 
827
		'notes' : $('#notes').val(),
1021
		'notes' : $('#notes').val(),
828
		
1022
		
829
		'nom_sel' : $('#taxon').val(),
1023
		'nom_sel' : $('#taxon').val(),
830
		'num_nom_sel' : $('#taxon').data('numNomSel'),
1024
		'num_nom_sel' : $('#taxon').data('numNomSel'),
831
		'nom_ret' : $('#taxon').data('nomRet'),
1025
		'nom_ret' : $('#taxon').data('nomRet'),
832
		'num_nom_ret' : $('#taxon').data('numNomRet'),
1026
		'num_nom_ret' : $('#taxon').data('numNomRet'),
833
		'num_taxon' : $('#taxon').data('nt'),
1027
		'num_taxon' : $('#taxon').data('nt'),
834
		'famille' : $('#taxon').data('famille'),
1028
		'famille' : $('#taxon').data('famille'),
835
		'referentiel' : ($('#taxon').data('numNomSel') == undefined ? '' : NOM_SCI_REFERENTIEL),
1029
		'referentiel' : ($('#taxon').data('numNomSel') == undefined ? '' : NOM_SCI_REFERENTIEL),
836
		
1030
		
837
		'latitude' : $('#latitude').val(),
1031
		'latitude' : $('#latitude').val(),
838
		'longitude' : $('#longitude').val(),
1032
		'longitude' : $('#longitude').val(),
839
		'commune_nom' : $('#commune-nom').text(),
1033
		'commune_nom' : $('#commune-nom').text(),
840
		'commune_code_insee' : $('#commune-code-insee').text(),
1034
		'commune_code_insee' : $('#commune-code-insee').text(),
841
		'lieudit' : $('#lieudit').val(),
1035
		'lieudit' : $('#lieudit').val(),
842
		'station' : $('#station').val(),
1036
		'station' : $('#station').val(),
843
		'milieu' : $('#milieu').val(),
1037
		'milieu' : $('#milieu').val(),
844
		
1038
		
845
		//Ajout des champs images
1039
		//Ajout des champs images
846
		'image_nom' : getNomsImgsOriginales(),
1040
		'image_nom' : getNomsImgsOriginales(),
847
		'image_b64' : getB64ImgsOriginales()
1041
		'image_b64' : getB64ImgsOriginales()
848
	});
1042
	});
849
	console.log($('#liste-obs').data('obsId'+obsNbre));
1043
	console.log($('#liste-obs').data('obsId'+obsNbre));
850
}
1044
}
851
 
1045
 
852
function surChangementReferentiel() {
1046
function surChangementReferentiel() {
853
	NOM_SCI_PROJET = $('#referentiel').val();
1047
	NOM_SCI_PROJET = $('#referentiel').val();
854
	NOM_SCI_REFERENTIEL = NOM_SCI_PROJET+':'+PROJETS_VERSIONS[NOM_SCI_PROJET];
1048
	NOM_SCI_REFERENTIEL = NOM_SCI_PROJET+':'+PROJETS_VERSIONS[NOM_SCI_PROJET];
855
	$('#taxon').val('');
1049
	$('#taxon').val('');
856
}
1050
}
857
 
1051
 
858
function surChangementNbreObs() {
1052
function surChangementNbreObs() {
859
	if (obsNbre == 0) {
1053
	if (obsNbre == 0) {
860
		$('#transmettre-obs').attr('disabled', 'disabled');
1054
		$('#transmettre-obs').attr('disabled', 'disabled');
861
		$('#ajouter-obs').removeAttr('disabled');
1055
		$('#ajouter-obs').removeAttr('disabled');
862
	} else if (obsNbre > 0 && obsNbre < OBS_MAX_NBRE) {
1056
	} else if (obsNbre > 0 && obsNbre < OBS_MAX_NBRE) {
863
		$('#transmettre-obs').removeAttr('disabled');
1057
		$('#transmettre-obs').removeAttr('disabled');
864
		$('#ajouter-obs').removeAttr('disabled');
1058
		$('#ajouter-obs').removeAttr('disabled');
865
	} else if (obsNbre >= OBS_MAX_NBRE) {
1059
	} else if (obsNbre >= OBS_MAX_NBRE) {
866
		$('#ajouter-obs').attr('disabled', 'disabled');
1060
		$('#ajouter-obs').attr('disabled', 'disabled');
867
		afficherPanneau('#dialogue-bloquer-creer-obs');
1061
		afficherPanneau('#dialogue-bloquer-creer-obs');
868
	}
1062
	}
869
}
1063
}
-
 
1064
 
-
 
1065
function supprimerObs() {
-
 
1066
	var obsId = $(this).val();
-
 
1067
	// Problème avec IE 6 et 7
-
 
1068
	if (obsId == 'Supprimer') {
-
 
1069
		obsId = $(this).attr('title');
-
 
1070
	}
-
 
1071
	obsNbre = obsNbre - 1;
-
 
1072
	$('.obs-nbre').text(obsNbre);
-
 
1073
	$('.obs-nbre').triggerHandler('changement');
-
 
1074
	
-
 
1075
	$('.obs'+obsId).remove();
-
 
1076
	$('#liste-obs').removeData('obsId' + obsId);
-
 
1077
}
-
 
1078
 
-
 
1079
function initialiserObs() {
-
 
1080
	obsNbre = 0;
-
 
1081
	$('.obs-nbre').text(obsNbre);
-
 
1082
	$('.obs-nbre').triggerHandler('changement');
-
 
1083
	$('#liste-obs').removeData();
-
 
1084
	$('.obs').remove();
-
 
1085
	$('#dialogue-bloquer-creer-obs').hide();
-
 
1086
}
-
 
1087
 
-
 
1088
function getNomsImgsOriginales() {
-
 
1089
	var noms = new Array();
-
 
1090
	$('.miniature-img').each(function() {
-
 
1091
		noms.push($(this).attr('alt'));
-
 
1092
	});
-
 
1093
	return noms;
-
 
1094
}
-
 
1095
 
-
 
1096
function getB64ImgsOriginales() {
-
 
1097
	var b64 = new Array();
-
 
1098
	$('.miniature-img').each(function() {
-
 
1099
		if ($(this).hasClass('b64')) {
-
 
1100
			b64.push($(this).attr('src'));
-
 
1101
		} else if ($(this).hasClass('b64-canvas')) {
-
 
1102
			b64.push($(this).data('b64'));
-
 
1103
		}
-
 
1104
	});
-
 
1105
	return b64;
-
 
1106
}
-
 
1107
 
-
 
1108
//+----------------------------------------------------------------------------------------------------------+
-
 
1109
// TRANSFERER OBS : envoie des obs au CEL
870
 
1110
 
871
function transmettreObs() {
1111
function transmettreObs() {
872
	var observations = $('#liste-obs').data();
1112
	var observations = $('#liste-obs').data();
873
	console.log(observations);
1113
	console.log(observations);
874
	
1114
	
875
	if (observations == undefined || jQuery.isEmptyObject(observations)) {
1115
	if (observations == undefined || jQuery.isEmptyObject(observations)) {
876
		afficherPanneau('#dialogue-zero-obs');
1116
		afficherPanneau('#dialogue-zero-obs');
877
	} else {
1117
	} else {
878
		observations['projet'] = TAG_PROJET;
1118
		observations['projet'] = TAG_PROJET;
879
		observations['tag-obs'] = TAG_OBS;
1119
		observations['tag-obs'] = TAG_OBS;
880
		observations['tag-img'] = TAG_IMG;
1120
		observations['tag-img'] = TAG_IMG;
881
		
1121
		
882
		var utilisateur = new Object();
1122
		var utilisateur = new Object();
883
		utilisateur.id_utilisateur = $('#id_utilisateur').val();
1123
		utilisateur.id_utilisateur = $('#id_utilisateur').val();
884
		utilisateur.prenom = $('#prenom').val();
1124
		utilisateur.prenom = $('#prenom').val();
885
		utilisateur.nom = $('#nom').val();
1125
		utilisateur.nom = $('#nom').val();
886
		utilisateur.courriel = $('#courriel').val();
1126
		utilisateur.courriel = $('#courriel').val();
887
		observations['utilisateur'] = utilisateur;
1127
		observations['utilisateur'] = utilisateur;
888
		envoyerObsAuCel(observations);
1128
		envoyerObsAuCel(observations);
889
	}
1129
	}
890
	return false;
1130
	return false;
891
}
1131
}
892
 
1132
 
893
function envoyerObsAuCel(observations) {
1133
function envoyerObsAuCel(observations) {
894
	var erreurMsg = '';
1134
	var erreurMsg = '';
895
	$.ajax({
1135
	$.ajax({
896
		url: SERVICE_SAISIE_URL,
1136
		url: SERVICE_SAISIE_URL,
897
		type: 'POST',
1137
		type: 'POST',
898
		data: observations,
1138
		data: observations,
899
		dataType: 'json',
1139
		dataType: 'json',
900
		beforeSend: function() {
1140
		beforeSend: function() {
901
			$('#dialogue-obs-transaction-ko').hide();
1141
			$('#dialogue-obs-transaction-ko').hide();
902
			$('#dialogue-obs-transaction-ok').hide();
1142
			$('#dialogue-obs-transaction-ok').hide();
903
			$('.alert-txt .msg').remove();	
1143
			$('.alert-txt .msg').remove();	
904
			$('.alert-txt .msg-erreur').remove();
1144
			$('.alert-txt .msg-erreur').remove();
905
			$('.alert-txt .msg-debug').remove();
1145
			$('.alert-txt .msg-debug').remove();
906
			$('#chargement').show();
1146
			$('#chargement').show();
907
		},
1147
		},
908
		success: function(data, textStatus, jqXHR) {
1148
		success: function(data, textStatus, jqXHR) {
909
			$('#dialogue-obs-transaction-ok .alert-txt').append($('#tpl-transmission-ok').clone().html());
1149
			$('#dialogue-obs-transaction-ok .alert-txt').append($('#tpl-transmission-ok').clone().html());
910
			supprimerMiniatures();
1150
			supprimerMiniatures();
911
		},
1151
		},
912
		statusCode: {
1152
		statusCode: {
913
			500: function(jqXHR, textStatus, errorThrown) {
1153
			500: function(jqXHR, textStatus, errorThrown) {
914
				erreurMsg += "Erreur 500 :\ntype : " + textStatus + ' ' + errorThrown + "\n";
1154
				erreurMsg += "Erreur 500 :\ntype : " + textStatus + ' ' + errorThrown + "\n";
915
			}
1155
			}
916
		},
1156
		},
917
		error: function(jqXHR, textStatus, errorThrown) {
1157
		error: function(jqXHR, textStatus, errorThrown) {
918
			erreurMsg += "Erreur Ajax :\ntype : " + textStatus + ' ' + errorThrown + "\n";
1158
			erreurMsg += "Erreur Ajax :\ntype : " + textStatus + ' ' + errorThrown + "\n";
919
			try {
1159
			try {
920
				reponse = jQuery.parseJSON(jqXHR.responseText);
1160
				reponse = jQuery.parseJSON(jqXHR.responseText);
921
				if (reponse != null) {
1161
				if (reponse != null) {
922
					$.each(reponse, function (cle, valeur) {
1162
					$.each(reponse, function (cle, valeur) {
923
						erreurMsg += valeur + "\n";
1163
						erreurMsg += valeur + "\n";
924
					});
1164
					});
925
				}
1165
				}
926
			} catch(e) {
1166
			} catch(e) {
927
				erreurMsg += "L'erreur n'était pas en JSON.";
1167
				erreurMsg += "L'erreur n'était pas en JSON.";
928
			}
1168
			}
929
		},
1169
		},
930
		complete: function(jqXHR, textStatus) {
1170
		complete: function(jqXHR, textStatus) {
931
			$('#chargement').hide();
1171
			$('#chargement').hide();
932
			var debugMsg = extraireEnteteDebug(jqXHR);
1172
			var debugMsg = extraireEnteteDebug(jqXHR);
933
			
1173
			
934
			if (erreurMsg != '') {
1174
			if (erreurMsg != '') {
935
				if (DEBUG) {
1175
				if (DEBUG) {
936
					$('#dialogue-obs-transaction-ko .alert-txt').append('<pre class="msg-erreur">' + erreurMsg + '</pre>');
1176
					$('#dialogue-obs-transaction-ko .alert-txt').append('<pre class="msg-erreur">' + erreurMsg + '</pre>');
937
					$('#dialogue-obs-transaction-ko .alert-txt').append('<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>');
1177
					$('#dialogue-obs-transaction-ko .alert-txt').append('<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>');
938
				}
1178
				}
939
				var hrefCourriel = 'mailto:cel@tela-botanica.org?' + 
1179
				var hrefCourriel = 'mailto:cel@tela-botanica.org?' + 
940
					'subject=Disfonctionnement du widget de saisie ' + TAG_PROJET + 
1180
					'subject=Disfonctionnement du widget de saisie ' + TAG_PROJET + 
941
					'&body=' + erreurMsg + "\nDébogage :\n" + debugMsg;
1181
					'&body=' + erreurMsg + "\nDébogage :\n" + debugMsg;
942
				
1182
				
943
				$('#dialogue-obs-transaction-ko .alert-txt').append($('#tpl-transmission-ko').clone()
1183
				$('#dialogue-obs-transaction-ko .alert-txt').append($('#tpl-transmission-ko').clone()
944
					.find('.courriel-erreur')
1184
					.find('.courriel-erreur')
945
					.attr('href', hrefCourriel)
1185
					.attr('href', hrefCourriel)
946
					.end()
1186
					.end()
947
					.html());
1187
					.html());
948
				$('#dialogue-obs-transaction-ko').show();
1188
				$('#dialogue-obs-transaction-ko').show();
949
			} else {
1189
			} else {
950
				if (DEBUG) {
1190
				if (DEBUG) {
951
					$('#dialogue-obs-transaction-ok .alert-txt').append('<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>');
1191
					$('#dialogue-obs-transaction-ok .alert-txt').append('<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>');
952
				}
1192
				}
953
				$('#dialogue-obs-transaction-ok').show();
1193
				$('#dialogue-obs-transaction-ok').show();
954
			}
1194
			}
955
			initialiserObs();
1195
			initialiserObs();
956
		}
1196
		}
957
	});
1197
	});
958
}
1198
}
959
 
-
 
960
function validerFormulaire() {
-
 
961
	var observateur = $('#form-observateur').valid(),
-
 
962
		station = $('#form-site').valid(),
-
 
963
		date = $('#form-date').valid(),
-
 
964
		obs = $('#form-obs').valid();
-
 
965
	return (observateur == true && station == true && obs == true && date == true) ? true : false;
-
 
966
}
-
 
967
 
-
 
968
function getNomsImgsOriginales() {
-
 
969
	var noms = new Array();
-
 
970
	$('.miniature-img').each(function() {
-
 
971
		noms.push($(this).attr('alt'));
-
 
972
	});
-
 
973
	return noms;
-
 
974
}
-
 
975
 
-
 
976
function getB64ImgsOriginales() {
-
 
977
	var b64 = new Array();
-
 
978
	$('.miniature-img').each(function() {
-
 
979
		if ($(this).hasClass('b64')) {
-
 
980
			b64.push($(this).attr('src'));
-
 
981
		} else if ($(this).hasClass('b64-canvas')) {
-
 
982
			b64.push($(this).data('b64'));
-
 
983
		}
-
 
984
	});
-
 
985
	return b64;
-
 
986
}
-
 
987
 
-
 
988
function supprimerObs() {
-
 
989
	var obsId = $(this).val();
-
 
990
	// Problème avec IE 6 et 7
-
 
991
	if (obsId == 'Supprimer') {
-
 
992
		obsId = $(this).attr('title');
-
 
993
	}
-
 
994
	obsNbre = obsNbre - 1;
-
 
995
	$('.obs-nbre').text(obsNbre);
-
 
996
	$('.obs-nbre').triggerHandler('changement');
-
 
997
	
-
 
998
	$('.obs'+obsId).remove();
-
 
999
	$('#liste-obs').removeData('obsId' + obsId);
-
 
1000
}
-
 
1001
 
-
 
1002
function initialiserObs() {
-
 
1003
	obsNbre = 0;
-
 
1004
	$('.obs-nbre').text(obsNbre);
-
 
1005
	$('.obs-nbre').triggerHandler('changement');
-
 
1006
	$('#liste-obs').removeData();
-
 
1007
	$('.obs').remove();
-
 
1008
	$('#dialogue-bloquer-creer-obs').hide();
-
 
1009
}
-
 
1010
 
-
 
1011
 
-
 
1012
function defilerMiniatures(element) {
-
 
1013
	var miniatureSelectionne = element.siblings('img.miniature-selectionnee');
-
 
1014
	miniatureSelectionne.removeClass('miniature-selectionnee');
-
 
1015
	miniatureSelectionne.addClass('miniature-cachee');
-
 
1016
	var miniatureAffichee = miniatureSelectionne;
-
 
1017
	
-
 
1018
	if(element.hasClass('defilement-miniatures-gauche')) {
-
 
1019
		if(miniatureSelectionne.prev('.miniature').length != 0) {
-
 
1020
			miniatureAffichee = miniatureSelectionne.prev('.miniature');
-
 
1021
		} else {
-
 
1022
			miniatureAffichee = miniatureSelectionne.siblings('.miniature').last();
-
 
1023
		}
-
 
1024
	} else {
-
 
1025
		if(miniatureSelectionne.next('.miniature').length != 0) {
-
 
1026
			miniatureAffichee = miniatureSelectionne.next('.miniature');
-
 
1027
		} else {
-
 
1028
			miniatureAffichee = miniatureSelectionne.siblings('.miniature').first();
-
 
1029
		}
-
 
1030
	}
-
 
1031
	miniatureAffichee.addClass('miniature-selectionnee');
-
 
1032
	miniatureAffichee.removeClass('miniature-cachee');
-
 
1033
}
-
 
1034
 
-
 
1035
//+---------------------------------------------------------------------------------------------------------+
-
 
1036
// AUTO-COMPLÉTION Noms Scientifiques
-
 
1037
 
-
 
1038
function ajouterAutocompletionNoms() {
-
 
1039
	$('#taxon').autocomplete({
-
 
1040
		source: function(requete, add){  
-
 
1041
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
-
 
1042
			
-
 
1043
			var url = getUrlAutocompletionNomsSci();
-
 
1044
			$.getJSON(url, function(data) {
-
 
1045
				console.log(data);
-
 
1046
				var suggestions = traiterRetourNomsSci(data);
-
 
1047
				add(suggestions);  
-
 
1048
			});
-
 
1049
		},
-
 
1050
		html: true
-
 
1051
	});
-
 
1052
	
-
 
1053
	$('#taxon').bind('autocompleteselect', function(event, ui) {
-
 
1054
		$('#taxon').data(ui.item);
-
 
1055
		if (ui.item.retenu == true) {
-
 
1056
			$('#taxon').addClass('ns-retenu');
-
 
1057
		} else {
-
 
1058
			$('#taxon').removeClass('ns-retenu');
-
 
1059
		}
-
 
1060
	});
-
 
1061
}
-
 
1062
 
-
 
1063
function getUrlAutocompletionNomsSci() {
-
 
1064
	var mots = $('#taxon').val(),
-
 
1065
		url = SERVICE_AUTOCOMPLETION_NOM_SCI_URL_TPL.replace('{referentiel}',NOM_SCI_PROJET);
-
 
1066
	url = url.replace('{masque}', mots);
-
 
1067
	return url;
-
 
1068
}
-
 
1069
 
-
 
1070
function traiterRetourNomsSci(data) {
-
 
1071
	var suggestions = [];
-
 
1072
	if (data.resultat != undefined) {
-
 
1073
		$.each(data.resultat, function(i, val) {
-
 
1074
			val.nn = i;
-
 
1075
			var nom = {label: '', value: '', nt: '', nomSel: '', nomSelComplet: '', numNomSel: '',
-
 
1076
				nomRet: '', numNomRet: '', famille: '', retenu: false
-
 
1077
			};
-
 
1078
			if (suggestions.length >= AUTOCOMPLETION_ELEMENTS_NBRE) {
-
 
1079
				nom.label = '...';
-
 
1080
				nom.value = $('#taxon').val();
-
 
1081
				suggestions.push(nom);
-
 
1082
				return false;
-
 
1083
			} else {
-
 
1084
				nom.label = val.nom_sci_complet;
-
 
1085
				nom.value = val.nom_sci_complet;
-
 
1086
				nom.nt = val.num_taxonomique;
-
 
1087
				nom.nomSel = val.nom_sci;
-
 
1088
				nom.nomSelComplet = val.nom_sci_complet;
-
 
1089
				nom.numNomSel = val.nn;
-
 
1090
				nom.nomRet = val.nom_retenu_complet;
-
 
1091
				nom.numNomRet = val['nom_retenu.id'];
-
 
1092
				nom.famille = val.famille;
-
 
1093
				nom.retenu = (val.retenu == 'false') ? false : true;
-
 
1094
				
-
 
1095
				suggestions.push(nom);
-
 
1096
			}
-
 
1097
		});
-
 
1098
	}
-
 
1099
	return suggestions;
-
 
1100
}
-
 
1101
 
-
 
1102
/*
-
 
1103
 * jQuery UI Autocomplete HTML Extension
-
 
1104
 *
-
 
1105
 * Copyright 2010, Scott González (http://scottgonzalez.com)
-
 
1106
 * Dual licensed under the MIT or GPL Version 2 licenses.
-
 
1107
 *
-
 
1108
 * http://github.com/scottgonzalez/jquery-ui-extensions
-
 
1109
 * 
-
 
1110
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
-
 
1111
 */
-
 
1112
(function($) {
-
 
1113
	var proto = $.ui.autocomplete.prototype,
-
 
1114
		initSource = proto._initSource;
-
 
1115
	
-
 
1116
	function filter(array, term) {
-
 
1117
		var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), 'i');
-
 
1118
		return $.grep(array, function(value) {
-
 
1119
			return matcher.test($('<div>').html(value.label || value.value || value).text());
-
 
1120
		});
-
 
1121
	}
-
 
1122
	
-
 
1123
	$.extend(proto, {
-
 
1124
		_initSource: function() {
-
 
1125
			if (this.options.html && $.isArray(this.options.source)) {
-
 
1126
				this.source = function( request, response ) {
-
 
1127
					response(filter(this.options.source, request.term));
-
 
1128
				};
-
 
1129
			} else {
-
 
1130
				initSource.call(this);
-
 
1131
			}
-
 
1132
		},
-
 
1133
		_renderItem: function(ul, item) {
-
 
1134
			if (item.retenu == true) {
-
 
1135
				item.label = '<strong>'+item.label+'</strong>';
-
 
1136
			}
-
 
1137
			
-
 
1138
			return $('<li></li>')
-
 
1139
				.data('item.autocomplete', item)
-
 
1140
				.append($('<a></a>')[this.options.html ? 'html' : 'text'](item.label))
-
 
1141
				.appendTo(ul);
-
 
1142
		}
-
 
1143
	});
-
 
1144
})(jQuery);
-
 
1145
1199