Subversion Repositories eFlore/Applications.cel

Rev

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

Rev 1130 Rev 1187
1
//+---------------------------------------------------------------------------------------------------------+
1
//+---------------------------------------------------------------------------------------------------------+
2
// GÉNÉRAL
2
// GÉNÉRAL
3
/**
3
/**
4
 * Stope l'évènement courrant quand on clique sur un lien.
4
 * Stope l'évènement courrant quand on clique sur un lien.
5
 * Utile pour Chrome, Safari...
5
 * Utile pour Chrome, Safari...
6
 * @param evenement
6
 * @param evenement
7
 * @return
7
 * @return
8
 */
8
 */
9
function arreter(evenement) {
9
function arreter(evenement) {
10
	if (evenement.stopPropagation) {
10
	if (evenement.stopPropagation) {
11
		evenement.stopPropagation();
11
		evenement.stopPropagation();
12
	}
12
	}
13
	return false;
13
	return false;
14
}
14
}
15
 
15
 
16
// TODO : voir si cette fonction est bien utile. Résoud le pb d'un warning sous chrome.
16
// TODO : voir si cette fonction est bien utile. Résoud le pb d'un warning sous chrome.
17
(function(){
17
(function(){
18
    // remove layerX and layerY
18
    // remove layerX and layerY
19
    var all = $.event.props,
19
    var all = $.event.props,
20
        len = all.length,
20
        len = all.length,
21
        res = [];
21
        res = [];
22
    while (len--) {
22
    while (len--) {
23
      var el = all[len];
23
      var el = all[len];
24
      if (el != 'layerX' && el != 'layerY') res.push(el);
24
      if (el != 'layerX' && el != 'layerY') res.push(el);
25
    }
25
    }
26
    $.event.props = res;
26
    $.event.props = res;
27
}());
27
}());
28
 
28
 
29
//+----------------------------------------------------------------------------------------------------------+
29
//+----------------------------------------------------------------------------------------------------------+
30
//UPLOAD PHOTO : Traitement de l'image 
30
//UPLOAD PHOTO : Traitement de l'image 
31
$(document).ready(function() {	
31
$(document).ready(function() {	
32
	
32
	
33
	$("#effacer-miniature").click(function () {
33
	$("#effacer-miniature").click(function () {
34
		supprimerMiniature();
34
		supprimerMiniature();
35
	});
35
	});
36
	
36
	
37
	if (HTML5 && window.File && window.FileReader && isCanvasSupported()) {
37
	if (HTML5 && window.File && window.FileReader && isCanvasSupported()) {
38
		if (DEBUG) {
38
		if (DEBUG) {
39
			console.log("Support OK pour : API File et Canvas.");
39
			console.log("Support OK pour : API File et Canvas.");
40
		}
40
		}
41
		$('#fichier').bind('change', function(e) {
41
		$('#fichier').bind('change', function(e) {
42
			afficherMiniatureHtml5(e);
42
			afficherMiniatureHtml5(e);
43
		});	
43
		});	
44
	} else {
44
	} else {
45
		$("#fichier").bind('change', function (e) {
45
		$("#fichier").bind('change', function (e) {
46
			arreter(e);
46
			arreter(e);
47
			var options = { 
47
			var options = { 
48
				success: afficherMiniature, // post-submit callback 
48
				success: afficherMiniature, // post-submit callback 
49
				dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type) 
49
				dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type) 
50
				resetForm: true // reset the form after successful submit 
50
				resetForm: true // reset the form after successful submit 
51
			};
51
			};
52
			$("#form-upload").ajaxSubmit(options);
52
			$("#form-upload").ajaxSubmit(options);
53
			return false;
53
			return false;
54
		});
54
		});
55
	}	
55
	}	
56
});
56
});
57
function isCanvasSupported(){
57
function isCanvasSupported(){
58
	var elem = document.createElement('canvas');
58
	var elem = document.createElement('canvas');
59
	return !!(elem.getContext && elem.getContext('2d'));
59
	return !!(elem.getContext && elem.getContext('2d'));
60
}
60
}
61
 
61
 
62
function afficherMiniatureHtml5(evt) {
62
function afficherMiniatureHtml5(evt) {
63
	supprimerMiniature();
63
	supprimerMiniature();
64
	
64
	
65
	var selectedfiles = evt.target.files;
65
	var selectedfiles = evt.target.files;
66
	var f = selectedfiles[0];// Nous récupérons seulement le premier fichier.
66
	var f = selectedfiles[0];// Nous récupérons seulement le premier fichier.
67
	if (f.type != 'image/jpeg') {
67
	if (f.type != 'image/jpeg') {
68
		var message = "Seule les images JPEG sont supportées.";
68
		var message = "Seule les images JPEG sont supportées.";
69
		$("#miniature-msg").append(message);
69
		$("#miniature-msg").append(message);
70
	} else if (f.size > 5242880) {
70
	} else if (f.size > 5242880) {
71
		var message = "Votre image à un poids supérieur à 5Mo.";
71
		var message = "Votre image à un poids supérieur à 5Mo.";
72
		$("#miniature-msg").append(message);
72
		$("#miniature-msg").append(message);
73
	} else {
73
	} else {
74
		var reader = new FileReader();
74
		var reader = new FileReader();
75
		// Lit le fichier image commune url de données
75
		// Lit le fichier image commune url de données
76
		reader.readAsDataURL(f);
76
		reader.readAsDataURL(f);
77
		var imgNom = f.name;
77
		var imgNom = f.name;
78
	
78
	
79
		// Closure pour capturer les infos du fichier
79
		// Closure pour capturer les infos du fichier
80
		reader.onload = (function(theFile) {
80
		reader.onload = (function(theFile) {
81
			return function(e) {
81
			return function(e) {
82
				// Rendre la miniature
82
				// Rendre la miniature
83
				var imageBase64 = e.target.result;
83
				var imageBase64 = e.target.result;
84
				//$("#miniature").append('<img id="miniature-img" class="miniature b64" src="'+imageBase64+'" alt="'+imgNom+'"/>');
84
				//$("#miniature").append('<img id="miniature-img" class="miniature b64" src="'+imageBase64+'" alt="'+imgNom+'"/>');
85
				
85
				
86
				// HTML5 Canvas
86
				// HTML5 Canvas
87
				var img = new Image();
87
				var img = new Image();
88
			    img.src = imageBase64;
88
			    img.src = imageBase64;
89
			    img.alt = imgNom;
89
			    img.alt = imgNom;
90
			    img.onload = function() {
90
			    img.onload = function() {
91
			    	transformerImgEnCanvas(this, 100, 100, false, 'white');
91
			    	transformerImgEnCanvas(this, 100, 100, false, 'white');
92
			    };
92
			    };
93
			};
93
			};
94
		})(f);
94
		})(f);
95
	}
95
	}
96
	$("#effacer-miniature").show();
96
	$("#effacer-miniature").show();
97
}
97
}
98
function transformerImgEnCanvas(img, thumbwidth, thumbheight, crop, background) {
98
function transformerImgEnCanvas(img, thumbwidth, thumbheight, crop, background) {
99
	var canvas = document.createElement('canvas');
99
	var canvas = document.createElement('canvas');
100
	canvas.width = thumbwidth;
100
	canvas.width = thumbwidth;
101
	canvas.height = thumbheight;
101
	canvas.height = thumbheight;
102
	var dimensions = calculerDimenssions(img.width, img.height, thumbwidth, thumbheight);
102
	var dimensions = calculerDimenssions(img.width, img.height, thumbwidth, thumbheight);
103
	if (crop) {
103
	if (crop) {
104
		canvas.width = dimensions.w;
104
		canvas.width = dimensions.w;
105
		canvas.height = dimensions.h;
105
		canvas.height = dimensions.h;
106
		dimensions.x = 0;
106
		dimensions.x = 0;
107
		dimensions.y = 0;
107
		dimensions.y = 0;
108
	}
108
	}
109
	cx = canvas.getContext('2d');
109
	cx = canvas.getContext('2d');
110
	if (background !== 'transparent') {
110
	if (background !== 'transparent') {
111
		cx.fillStyle = background;
111
		cx.fillStyle = background;
112
		cx.fillRect(0, 0, thumbwidth, thumbheight);
112
		cx.fillRect(0, 0, thumbwidth, thumbheight);
113
	}
113
	}
114
	cx.drawImage(img, dimensions.x, dimensions.y, dimensions.w, dimensions.h);
114
	cx.drawImage(img, dimensions.x, dimensions.y, dimensions.w, dimensions.h);
115
	afficherMiniatureCanvas(img, canvas);
115
	afficherMiniatureCanvas(img, canvas);
116
}
116
}
117
 
117
 
118
function calculerDimenssions(imagewidth, imageheight, thumbwidth, thumbheight) {
118
function calculerDimenssions(imagewidth, imageheight, thumbwidth, thumbheight) {
119
	var w = 0, h = 0, x = 0, y = 0,
119
	var w = 0, h = 0, x = 0, y = 0,
120
	    widthratio = imagewidth / thumbwidth,
120
	    widthratio = imagewidth / thumbwidth,
121
	    heightratio = imageheight / thumbheight,
121
	    heightratio = imageheight / thumbheight,
122
	    maxratio = Math.max(widthratio, heightratio);
122
	    maxratio = Math.max(widthratio, heightratio);
123
	if (maxratio > 1) {
123
	if (maxratio > 1) {
124
	    w = imagewidth / maxratio;
124
	    w = imagewidth / maxratio;
125
	    h = imageheight / maxratio;
125
	    h = imageheight / maxratio;
126
	} else {
126
	} else {
127
	    w = imagewidth;
127
	    w = imagewidth;
128
	    h = imageheight;
128
	    h = imageheight;
129
	}
129
	}
130
	x = (thumbwidth - w) / 2;
130
	x = (thumbwidth - w) / 2;
131
	y = (thumbheight - h) / 2;
131
	y = (thumbheight - h) / 2;
132
	return {w:w, h:h, x:x, y:y};
132
	return {w:w, h:h, x:x, y:y};
133
}
133
}
134
 
134
 
135
function afficherMiniatureCanvas(imgB64, canvas) {
135
function afficherMiniatureCanvas(imgB64, canvas) {
136
	var url = canvas.toDataURL('image/jpeg' , 0.8);
136
	var url = canvas.toDataURL('image/jpeg' , 0.8);
137
	var alt = imgB64.alt;
137
	var alt = imgB64.alt;
138
	var title = Math.round(url.length / 1000 * 100) / 100 + ' KB';
138
	var title = Math.round(url.length / 1000 * 100) / 100 + ' KB';
139
	var miniature = '<img id="miniature-img" class="miniature b64-canvas" src="'+url+'" alt="'+alt+'" title="'+title+'" />';
139
	var miniature = '<img id="miniature-img" class="miniature b64-canvas" src="'+url+'" alt="'+alt+'" title="'+title+'" />';
140
	$("#miniature").append(miniature);
140
	$("#miniature").append(miniature);
141
	$("#miniature-img").data('b64', imgB64.src);
141
	$("#miniature-img").data('b64', imgB64.src);
142
}
142
}
143
 
143
 
144
function afficherMiniature(reponse) { 
144
function afficherMiniature(reponse) { 
145
	supprimerMiniature();
145
	supprimerMiniature();
146
	if (DEBUG) {
146
	if (DEBUG) {
147
		var debogage = $("debogage", reponse).text();
147
		var debogage = $("debogage", reponse).text();
148
		console.log("Débogage upload : "+debogage);
148
		console.log("Débogage upload : "+debogage);
149
	}
149
	}
150
	var message = $("message", reponse).text();
150
	var message = $("message", reponse).text();
151
	if (message != '') {
151
	if (message != '') {
152
		$("#miniature-msg").append(message);
152
		$("#miniature-msg").append(message);
153
	} else {
153
	} else {
154
		var miniatureUrl = $("miniature-url", reponse).text();
154
		var miniatureUrl = $("miniature-url", reponse).text();
155
		var imgNom = $("image-nom", reponse).text();
155
		var imgNom = $("image-nom", reponse).text();
156
		$("#miniature").append('<img id="miniature-img" class="miniature" alt="'+imgNom+'" src="'+miniatureUrl+'"/>');
156
		$("#miniature").append('<img id="miniature-img" class="miniature" alt="'+imgNom+'" src="'+miniatureUrl+'"/>');
157
	}
157
	}
158
	$("#effacer-miniature").show();		
158
	$("#effacer-miniature").show();		
159
}
159
}
160
 
160
 
161
function supprimerMiniature() {
161
function supprimerMiniature() {
162
	$("#miniature").empty();
162
	$("#miniature").empty();
163
	$("#miniature-msg").empty();
163
	$("#miniature-msg").empty();
164
	$("#effacer-miniature").hide();
164
	$("#effacer-miniature").hide();
165
}
165
}
166
 
166
 
167
//+----------------------------------------------------------------------------------------------------------+
167
//+----------------------------------------------------------------------------------------------------------+
168
// GOOGLE MAP
168
// GOOGLE MAP
169
var geocoder;
169
var geocoder;
170
var map;
170
var map;
171
var marker;
171
var marker;
172
var latLng;
172
var latLng;
173
 
173
 
174
function initialiserGoogleMap(){
174
function initialiserGoogleMap(){
175
	// Carte
175
	// Carte
-
 
176
	var latLng = new google.maps.LatLng(48.8543, 2.3483);// Paris
-
 
177
	if (VILLE == 'Marseille') {
176
	var latLng = new google.maps.LatLng(43.29545, 5.37458);
178
		latLng = new google.maps.LatLng(43.29545, 5.37458);
177
	if (VILLE == 'Montpellier') {
179
	} else if (VILLE == 'Montpellier') {
178
		latLng = new google.maps.LatLng(43.61077, 3.87672);
180
		latLng = new google.maps.LatLng(43.61077, 3.87672);
179
	} else {
-
 
180
		//console.log('Ville:'+VILLE);
-
 
181
	}
181
	}
182
	
-
 
183
	// Tentative de geocalisation
-
 
184
	if (navigator.geolocation) {
-
 
185
		navigator.geolocation.getCurrentPosition(function(position) {
-
 
186
			var latitude = position.coords.latitude;
-
 
187
			var longitude = position.coords.longitude;
-
 
188
			latLng = new google.maps.LatLng(latitude, longitude);
-
 
189
		});
-
 
190
	}
-
 
191
 
182
	
192
	var options = {
183
	var options = {
193
		zoom: 16,
184
		zoom: 16,
194
		center: latLng,
185
		center: latLng,
195
		mapTypeId: google.maps.MapTypeId.HYBRID,
186
		mapTypeId: google.maps.MapTypeId.HYBRID,
196
		mapTypeControlOptions: {
187
		mapTypeControlOptions: {
197
			mapTypeIds: ['OSM', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]}
188
			mapTypeIds: ['OSM', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]}
198
	};
189
	};
199
 
190
 
200
	// Ajout de la couche OSM à la carte
191
	// Ajout de la couche OSM à la carte
201
	osmMapType = new google.maps.ImageMapType({
192
	osmMapType = new google.maps.ImageMapType({
202
		getTileUrl: function(coord, zoom) {
193
		getTileUrl: function(coord, zoom) {
203
			return "http://tile.openstreetmap.org/" +
194
			return "http://tile.openstreetmap.org/" +
204
			zoom + "/" + coord.x + "/" + coord.y + ".png";
195
			zoom + "/" + coord.x + "/" + coord.y + ".png";
205
		},
196
		},
206
		tileSize: new google.maps.Size(256, 256),
197
		tileSize: new google.maps.Size(256, 256),
207
		isPng: true,
198
		isPng: true,
208
		alt: 'OpenStreetMap',
199
		alt: 'OpenStreetMap',
209
		name: 'OSM',
200
		name: 'OSM',
210
		maxZoom: 19
201
		maxZoom: 19
211
	});
202
	});
212
	
203
	
213
	// Création de la carte Google
204
	// Création de la carte Google
214
	map = new google.maps.Map(document.getElementById('map-canvas'), options); //affiche la google map dans la div map_canvas
205
	map = new google.maps.Map(document.getElementById('map-canvas'), options); //affiche la google map dans la div map_canvas
215
	map.mapTypes.set('OSM', osmMapType);
206
	map.mapTypes.set('OSM', osmMapType);
216
	
207
	
217
	// Geocodeur
208
	// Geocodeur
218
	geocoder = new google.maps.Geocoder();
209
	geocoder = new google.maps.Geocoder();
219
 
210
 
220
	// Marqueur google draggable
211
	// Marqueur google draggable
221
	marker = new google.maps.Marker({
212
	marker = new google.maps.Marker({
222
		map: map,
213
		map: map,
223
		draggable: true,
214
		draggable: true,
224
		title: 'Ma station',
215
		title: 'Ma station',
225
		icon: GOOGLE_MAP_MARQUEUR_URL,
216
		icon: GOOGLE_MAP_MARQUEUR_URL,
226
		position: latLng
217
		position: latLng
227
	});
218
	});
228
	
219
	
229
	deplacerMarker(latLng);
220
	deplacerMarker(latLng);
-
 
221
	
-
 
222
	// Tentative de geocalisation
-
 
223
	if (navigator.geolocation) {
-
 
224
		navigator.geolocation.getCurrentPosition(function(position) {
-
 
225
			var latitude = position.coords.latitude;
-
 
226
			var longitude = position.coords.longitude;
-
 
227
			latLng = new google.maps.LatLng(latitude, longitude);
-
 
228
			deplacerMarker(latLng);
-
 
229
		});
-
 
230
	}
230
}
231
}
231
 
232
 
232
$(document).ready(function() {
233
$(document).ready(function() {
233
	
234
	
234
	initialiserGoogleMap();
235
	initialiserGoogleMap();
235
	
236
	
236
	// Autocompletion du champ adresse
237
	// Autocompletion du champ adresse
237
	$("#rue").autocomplete({
238
	$("#rue").autocomplete({
238
		//Cette partie utilise geocoder pour extraire des valeurs d'adresse
239
		//Cette partie utilise geocoder pour extraire des valeurs d'adresse
239
		source: function(request, response) {
240
		source: function(request, response) {
240
			geocoder.geocode( {'address': request.term+', France', 'region' : 'fr' }, function(results, status) {
241
			geocoder.geocode( {'address': request.term+', France', 'region' : 'fr' }, function(results, status) {
241
				if (status == google.maps.GeocoderStatus.OK) {
242
				if (status == google.maps.GeocoderStatus.OK) {
242
					response($.map(results, function(item) {
243
					response($.map(results, function(item) {
243
						var rue = "";
244
						var rue = "";
244
						$.each(item.address_components, function(){
245
						$.each(item.address_components, function(){
245
							if (this.types[0] == "route" || this.types[0] == "street_address" ) {
246
							if (this.types[0] == "route" || this.types[0] == "street_address" ) {
246
								rue = this.short_name;
247
								rue = this.short_name;
247
							}
248
							}
248
						});
249
						});
249
						var retour = {
250
						var retour = {
250
							label: item.formatted_address,
251
							label: item.formatted_address,
251
							value: rue,
252
							value: rue,
252
							latitude: item.geometry.location.lat(),
253
							latitude: item.geometry.location.lat(),
253
							longitude: item.geometry.location.lng()
254
							longitude: item.geometry.location.lng()
254
						};
255
						};
255
						return retour;
256
						return retour;
256
					}));
257
					}));
257
				} else {
258
				} else {
258
					afficherErreurGoogleMap(status);
259
					afficherErreurGoogleMap(status);
259
				}
260
				}
260
			});
261
			});
261
		},
262
		},
262
		// Cette partie est executee a la selection d'une adresse
263
		// Cette partie est executee a la selection d'une adresse
263
		select: function(event, ui) {
264
		select: function(event, ui) {
264
			var latLng = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
265
			var latLng = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
265
			deplacerMarker(latLng);
266
			deplacerMarker(latLng);
266
		}
267
		}
267
	});
268
	});
268
	
269
	
269
	$("#geolocaliser").click(function() {
270
	$("#geolocaliser").click(function() {
270
		var latitude = $('#latitude').val();
271
		var latitude = $('#latitude').val();
271
		var longitude = $('#longitude').val();
272
		var longitude = $('#longitude').val();
272
		latLng = new google.maps.LatLng(latitude, longitude);
273
		latLng = new google.maps.LatLng(latitude, longitude);
273
		deplacerMarker(latLng);
274
		deplacerMarker(latLng);
274
	});
275
	});
275
	
276
	
276
	google.maps.event.addListener(marker, 'dragend', function() {
277
	google.maps.event.addListener(marker, 'dragend', function() {
277
		trouverCommune(marker.getPosition());
278
		trouverCommune(marker.getPosition());
278
		mettreAJourMarkerPosition(marker.getPosition());
279
		mettreAJourMarkerPosition(marker.getPosition());
279
	});
280
	});
280
	
281
	
281
	google.maps.event.addListener(map, 'click', function(event) {
282
	google.maps.event.addListener(map, 'click', function(event) {
282
		deplacerMarker(event.latLng);
283
		deplacerMarker(event.latLng);
283
	});
284
	});
284
});
285
});
285
 
286
 
286
function afficherErreurGoogleMap(status) {
287
function afficherErreurGoogleMap(status) {
287
	if (DEBUG) {
288
	if (DEBUG) {
288
		$("#dialogue-google-map").empty();
289
		$("#dialogue-google-map").empty();
289
		$("#dialogue-google-map").append('<pre class="msg-erreur">'+
290
		$("#dialogue-google-map").append('<pre class="msg-erreur">'+
290
			"Le service de Géocodage de Google Map a échoué à cause de l'erreur : "+status+
291
			"Le service de Géocodage de Google Map a échoué à cause de l'erreur : "+status+
291
			'</pre>');
292
			'</pre>');
292
		$("#dialogue-google-map").dialog();
293
		$("#dialogue-google-map").dialog();
293
	}
294
	}
294
}
295
}
295
 
296
 
296
function deplacerMarker(latLng) {
297
function deplacerMarker(latLng) {
297
	if (marker != undefined) {
298
	if (marker != undefined) {
298
		marker.setPosition(latLng);
299
		marker.setPosition(latLng);
299
		map.setCenter(latLng);
300
		map.setCenter(latLng);
300
		//map.setZoom(18);
301
		//map.setZoom(18);
301
		mettreAJourMarkerPosition(latLng);
302
		mettreAJourMarkerPosition(latLng);
302
		trouverCommune(latLng);
303
		trouverCommune(latLng);
303
	}
304
	}
304
}
305
}
305
 
306
 
306
function mettreAJourMarkerPosition(latLng) {
307
function mettreAJourMarkerPosition(latLng) {
307
	var lat = latLng.lat().toFixed(5);
308
	var lat = latLng.lat().toFixed(5);
308
	var lng = latLng.lng().toFixed(5); 
309
	var lng = latLng.lng().toFixed(5); 
309
	remplirChampLatitude(lat);
310
	remplirChampLatitude(lat);
310
	remplirChampLongitude(lng);
311
	remplirChampLongitude(lng);
311
}
312
}
312
 
313
 
313
function remplirChampLatitude(latDecimale) {
314
function remplirChampLatitude(latDecimale) {
314
	var lat = Math.round(latDecimale*100000)/100000;
315
	var lat = Math.round(latDecimale*100000)/100000;
315
	$('#latitude').val(lat);
316
	$('#latitude').val(lat);
316
}
317
}
317
 
318
 
318
function remplirChampLongitude(lngDecimale) {
319
function remplirChampLongitude(lngDecimale) {
319
	var lng = Math.round(lngDecimale*100000)/100000;
320
	var lng = Math.round(lngDecimale*100000)/100000;
320
	$('#longitude').val(lng);
321
	$('#longitude').val(lng);
321
}
322
}
322
 
323
 
323
function trouverCommune(pos) {
324
function trouverCommune(pos) {
324
	$(function() {
325
	$(function() {
325
		var urlNomCommuneFormatee = SERVICE_NOM_COMMUNE_URL.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
326
		var urlNomCommuneFormatee = SERVICE_NOM_COMMUNE_URL.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
326
		$.ajax({
327
		$.ajax({
327
			url : urlNomCommuneFormatee,
328
			url : urlNomCommuneFormatee,
328
			type : "GET",
329
			type : "GET",
329
			dataType : "jsonp",
330
			dataType : "jsonp",
330
			beforeSend : function() {
331
			beforeSend : function() {
331
				$(".commune-info").empty();	
332
				$(".commune-info").empty();	
332
				$("#dialogue-erreur").empty();
333
				$("#dialogue-erreur").empty();
333
			},
334
			},
334
			success : function(data, textStatus, jqXHR) {
335
			success : function(data, textStatus, jqXHR) {
335
				$(".commune-info").empty();
336
				$(".commune-info").empty();
336
				$("#commune-nom").append(data.nom);
337
				$("#commune-nom").append(data.nom);
337
				$("#commune-code-insee").append(data.codeINSEE);
338
				$("#commune-code-insee").append(data.codeINSEE);
338
				$("#marqueur-commune").data('commune', {'nom' : data.nom, 'codeInsee' : data.codeINSEE});
339
				$("#marqueur-commune").data('commune', {'nom' : data.nom, 'codeInsee' : data.codeINSEE});
339
			},
340
			},
340
			statusCode : {
341
			statusCode : {
341
			    500 : function(jqXHR, textStatus, errorThrown) {
342
			    500 : function(jqXHR, textStatus, errorThrown) {
342
					if (DEBUG) {	
343
					if (DEBUG) {	
343
						$("#dialogue-erreur").append('<p id="msg">Un problème est survenu lors de l\'appel au service fournissante le nom des communes.</p>');
344
						$("#dialogue-erreur").append('<p id="msg">Un problème est survenu lors de l\'appel au service fournissante le nom des communes.</p>');
344
						reponse = jQuery.parseJSON(jqXHR.responseText);
345
						reponse = jQuery.parseJSON(jqXHR.responseText);
345
						var erreurMsg = "";
346
						var erreurMsg = "";
346
						if (reponse != null) {
347
						if (reponse != null) {
347
							$.each(reponse, function (cle, valeur) {
348
							$.each(reponse, function (cle, valeur) {
348
								erreurMsg += valeur + "<br />";
349
								erreurMsg += valeur + "<br />";
349
							});
350
							});
350
						}
351
						}
351
						
352
						
352
						$("#dialogue-erreur").append('<p class="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
353
						$("#dialogue-erreur").append('<p class="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
353
					}
354
					}
354
			    }
355
			    }
355
			},
356
			},
356
			error : function(jqXHR, textStatus, errorThrown) {
357
			error : function(jqXHR, textStatus, errorThrown) {
357
				if (DEBUG) {
358
				if (DEBUG) {
358
					$("#dialogue-erreur").append('<p class="msg">Une erreur Ajax est survenue lors de la transmission de vos observations.</p>');
359
					$("#dialogue-erreur").append('<p class="msg">Une erreur Ajax est survenue lors de la transmission de vos observations.</p>');
359
					reponse = jQuery.parseJSON(jqXHR.responseText);
360
					reponse = jQuery.parseJSON(jqXHR.responseText);
360
					var erreurMsg = "";
361
					var erreurMsg = "";
361
					if (reponse != null) {
362
					if (reponse != null) {
362
						$.each(reponse, function (cle, valeur) {
363
						$.each(reponse, function (cle, valeur) {
363
							erreurMsg += valeur + "<br />";
364
							erreurMsg += valeur + "<br />";
364
						});
365
						});
365
					}
366
					}
366
					
367
					
367
					$("#dialogue-erreur").append('<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
368
					$("#dialogue-erreur").append('<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
368
				}
369
				}
369
			},
370
			},
370
			complete : function(jqXHR, textStatus) {
371
			complete : function(jqXHR, textStatus) {
371
				if (DEBUG && jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
372
				if (DEBUG && jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
372
					var debugMsg = "";
373
					var debugMsg = "";
373
					debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
374
					debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
374
					if (debugInfos != null) {
375
					if (debugInfos != null) {
375
						$.each(debugInfos, function (cle, valeur) {
376
						$.each(debugInfos, function (cle, valeur) {
376
							debugMsg += valeur + "<br />";
377
							debugMsg += valeur + "<br />";
377
						});
378
						});
378
						$("#dialogue-erreur").append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
379
						$("#dialogue-erreur").append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
379
					}
380
					}
380
				}
381
				}
381
				if ($("#dialogue-erreur .msg").length > 0) {
382
				if ($("#dialogue-erreur .msg").length > 0) {
382
					$("#dialogue-erreur").dialog();
383
					$("#dialogue-erreur").dialog();
383
				}
384
				}
384
			}
385
			}
385
		});
386
		});
386
	});
387
	});
387
}
388
}
388
 
389
 
389
//+---------------------------------------------------------------------------------------------------------+
390
//+---------------------------------------------------------------------------------------------------------+
390
// FORMULAIRE
391
// FORMULAIRE
391
$(document).ready(function() {
392
$(document).ready(function() {
392
	$("#date").datepicker($.datepicker.regional['fr']);
393
	$("#date").datepicker($.datepicker.regional['fr']);
393
	
394
	
394
	$("form#saisie-obs").validate({
395
	$("form#saisie-obs").validate({
395
		rules: {
396
		rules: {
396
			courriel : {
397
			courriel : {
397
				required : true,
398
				required : true,
398
				email : true},
399
				email : true},
399
			courriel_confirmation : {
400
			courriel_confirmation : {
400
				required : true,
401
				required : true,
401
				equalTo: "#courriel"
402
				equalTo: "#courriel"
402
			},
403
			},
403
			rue : "required",
404
			rue : "required",
404
			rue_num_debut : {
405
			rue_num_debut : {
405
				required : true,
406
				required : true,
406
				digits : true,
407
				digits : true,
407
				min : 1},
408
				min : 1},
408
			rue_num_fin : {
409
			rue_num_fin : {
409
				required : true,
410
				required : true,
410
				digits : true,
411
				digits : true,
411
				min : 1},
412
				min : 1},
412
			rue_cote : "required",
413
			rue_cote : "required",
413
			milieu : "required",
414
			milieu : "required",
414
			latitude : {
415
			latitude : {
415
				required: true,
416
				required: true,
416
				range: [-90, 90]},
417
				range: [-90, 90]},
417
			longitude : {
418
			longitude : {
418
				required: true,
419
				required: true,
419
				range: [-180, 180]},
420
				range: [-180, 180]},
420
			date : {
421
			date : {
421
				required: true,
422
				required: true,
422
				date: true},
423
				date: true},
423
			taxon : "required"
424
			taxon : "required"
424
		}
425
		}
425
	});
426
	});
426
	
427
	
427
	$("#courriel_confirmation").bind('paste', function(e) {
428
	$("#courriel_confirmation").bind('paste', function(e) {
428
		$("#dialogue-bloquer-copier-coller").dialog();
429
		$("#dialogue-bloquer-copier-coller").dialog();
429
		return false;
430
		return false;
430
	});
431
	});
431
		
432
		
432
	//bascule le texte d'afficher à masquer
433
	//bascule le texte d'afficher à masquer
433
	$("a.afficher-coord").click(function() {
434
	$("a.afficher-coord").click(function() {
434
		$("a.afficher-coord").toggle();
435
		$("a.afficher-coord").toggle();
435
		$("#coordonnees-geo").toggle('slow');
436
		$("#coordonnees-geo").toggle('slow');
436
		//valeur false pour que le lien ne soit pas suivi
437
		//valeur false pour que le lien ne soit pas suivi
437
		return false;
438
		return false;
438
	});
439
	});
439
	
440
	
440
	var obsNumero = 0;
441
	var obsNumero = 0;
441
	$("#ajouter-obs").bind('click', function(e) {
442
	$("#ajouter-obs").bind('click', function(e) {
442
		if ($("#saisie-obs").valid() == false) {
443
		if ($("#saisie-obs").valid() == false) {
443
			$("#dialogue-form-invalide").dialog();
444
			$("#dialogue-form-invalide").dialog();
444
		} else {
445
		} else {
445
			//rassemble les obs dans un tableau html
446
			//rassemble les obs dans un tableau html
446
			obsNumero = obsNumero + 1;
447
			obsNumero = obsNumero + 1;
447
			$("#liste-obs tbody").append(
448
			$("#liste-obs tbody").append(
448
					'<tr id="obs'+obsNumero+'" class="obs">'+
449
					'<tr id="obs'+obsNumero+'" class="obs">'+
449
					'<td>'+obsNumero+'</td>'+
450
					'<td>'+obsNumero+'</td>'+
450
					'<td>'+$("#date").val()+'</td>'+
451
					'<td>'+$("#date").val()+'</td>'+
451
					'<td>'+$("#rue").val()+'</td>'+
452
					'<td>'+$("#rue").val()+'</td>'+
452
					'<td>'+$("#taxon option:selected").text()+'</td>'+
453
					'<td>'+$("#taxon option:selected").text()+'</td>'+
453
					'<td>'+$('input[name=milieu]:checked').val()+'</td>'+
454
					'<td>'+$('input[name=milieu]:checked').val()+'</td>'+
454
					'<td>'+$("#latitude").val()+' / '+$("#longitude").val()+'</td>'+
455
					'<td>'+$("#latitude").val()+' / '+$("#longitude").val()+'</td>'+
455
					//Ajout du champ photo
456
					//Ajout du champ photo
456
					'<td class="obs-miniature">'+ajouterImgMiniatureAuTransfert()+'</td>'+
457
					'<td class="obs-miniature">'+ajouterImgMiniatureAuTransfert()+'</td>'+
457
					'<td>'+$("#notes").val()+'</td>'+
458
					'<td>'+$("#notes").val()+'</td>'+
458
					'<td><button class="supprimer-obs" value="'+obsNumero+'" title="Supprimer l\'observation '+obsNumero+'">'+
459
					'<td><button class="supprimer-obs" value="'+obsNumero+'" title="Supprimer l\'observation '+obsNumero+'">'+
459
					'<img src="'+SUPPRIMER_ICONE_URL+'"/></button></td>'+
460
					'<img src="'+SUPPRIMER_ICONE_URL+'"/></button></td>'+
460
				'</tr>');
461
				'</tr>');
461
			//rassemble les obs dans #liste-obs
462
			//rassemble les obs dans #liste-obs
462
			var numNomSel = $("#taxon").val();
463
			var numNomSel = $("#taxon").val();
463
			$("#liste-obs").data('obsId'+obsNumero, {
464
			$("#liste-obs").data('obsId'+obsNumero, {
464
				'date' : $("#date").val(), 
465
				'date' : $("#date").val(), 
465
				'num_nom_sel' : numNomSel,
466
				'num_nom_sel' : numNomSel,
466
				'nom_sel' : taxons[numNomSel]['nom_sel'],
467
				'nom_sel' : taxons[numNomSel]['nom_sel'],
467
				'nom_ret' : taxons[numNomSel]['nom_ret'],
468
				'nom_ret' : taxons[numNomSel]['nom_ret'],
468
				'num_nom_ret' : taxons[numNomSel]['num_nom_ret'],
469
				'num_nom_ret' : taxons[numNomSel]['num_nom_ret'],
469
				'num_taxon' : taxons[numNomSel]['num_taxon'],
470
				'num_taxon' : taxons[numNomSel]['num_taxon'],
470
				'famille' : taxons[numNomSel]['famille'],
471
				'famille' : taxons[numNomSel]['famille'],
471
				'nom_fr' : taxons[numNomSel]['nom_fr'],
472
				'nom_fr' : taxons[numNomSel]['nom_fr'],
472
				'milieu' : $('input[name=milieu]:checked').val(),
473
				'milieu' : $('input[name=milieu]:checked').val(),
473
				'latitude' : $("#latitude").val(),
474
				'latitude' : $("#latitude").val(),
474
				'longitude' : $("#longitude").val(),
475
				'longitude' : $("#longitude").val(),
475
				'commune_nom' : $("#commune-nom").text(),
476
				'commune_nom' : $("#commune-nom").text(),
476
				'commune_code_insee' : $("#commune-code-insee").text(),
477
				'commune_code_insee' : $("#commune-code-insee").text(),
477
				'lieu_dit' : $("#rue").val(),
478
				'lieu_dit' : $("#rue").val(),
478
				'station' : $("#rue_num_debut").val()+'-'+$("#rue_num_fin").val()+'-'+$("#rue_cote").val(),
479
				'station' : $("#rue_num_debut").val()+'-'+$("#rue_num_fin").val()+'-'+$("#rue_cote").val(),
479
				'notes' : $("#notes").val(),
480
				'notes' : $("#notes").val(),
480
				//Ajout des champs images
481
				//Ajout des champs images
481
				'image_nom' : $("#miniature-img").attr('alt'),
482
				'image_nom' : $("#miniature-img").attr('alt'),
482
				'image_b64' : getB64ImgOriginal()
483
				'image_b64' : getB64ImgOriginal()
483
			});
484
			});
484
		}
485
		}
485
	});
486
	});
486
	
487
	
487
	$(".supprimer-obs").live('click', supprimerObs);
488
	$(".supprimer-obs").live('click', supprimerObs);
488
	
489
	
489
	$("#transmettre-obs").click(function(e) {
490
	$("#transmettre-obs").click(function(e) {
490
		var observations = $("#liste-obs").data();
491
		var observations = $("#liste-obs").data();
491
		
492
		
492
		if (observations == undefined || jQuery.isEmptyObject(observations)) {
493
		if (observations == undefined || jQuery.isEmptyObject(observations)) {
493
			$("#dialogue-zero-obs").dialog();
494
			$("#dialogue-zero-obs").dialog();
494
		} else if ($("#saisie-obs").valid() == false) {
495
		} else if ($("#saisie-obs").valid() == false) {
495
			$("#dialogue-form-invalide").dialog();
496
			$("#dialogue-form-invalide").dialog();
496
		} else {
497
		} else {
497
			observations['projet'] = 'Sauvages';
498
			observations['projet'] = 'Sauvages';
498
			
499
			
499
			var utilisateur = new Object();
500
			var utilisateur = new Object();
500
			utilisateur.prenom = $("#prenom").val();
501
			utilisateur.prenom = $("#prenom").val();
501
			utilisateur.nom = $("#nom").val();
502
			utilisateur.nom = $("#nom").val();
502
			utilisateur.courriel = $("#courriel").val();
503
			utilisateur.courriel = $("#courriel").val();
503
			observations['utilisateur'] = utilisateur;
504
			observations['utilisateur'] = utilisateur;
504
			
505
			
505
			var erreurMsg = "";
506
			var erreurMsg = "";
506
			$.ajax({
507
			$.ajax({
507
				url : SERVICE_SAISIE_URL,
508
				url : SERVICE_SAISIE_URL,
508
				type : "POST",
509
				type : "POST",
509
				data : observations,
510
				data : observations,
510
				dataType : "json",
511
				dataType : "json",
511
				beforeSend : function() {
512
				beforeSend : function() {
512
					$(".msg").remove();	
513
					$(".msg").remove();	
513
					$(".msg-erreur").remove();
514
					$(".msg-erreur").remove();
514
					$(".msg-debug").remove();
515
					$(".msg-debug").remove();
515
					$("#chargement").show();
516
					$("#chargement").show();
516
				},
517
				},
517
				success : function(data, textStatus, jqXHR) {
518
				success : function(data, textStatus, jqXHR) {
518
					$("#dialogue-obs-transaction").append('<p class="msg">Vos observations ont bien été transmises.</p>');
519
					$("#dialogue-obs-transaction").append('<p class="msg">Vos observations ont bien été transmises.</p>');
519
					supprimerMiniature();
520
					supprimerMiniature();
520
				},
521
				},
521
				statusCode : {
522
				statusCode : {
522
					500 : function(jqXHR, textStatus, errorThrown) {
523
					500 : function(jqXHR, textStatus, errorThrown) {
523
						$("#chargement").hide();
524
						$("#chargement").hide();
524
						erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
525
						erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
525
						if (DEBUG) {
526
						if (DEBUG) {
526
							$("#dialogue-obs-transaction").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
527
							$("#dialogue-obs-transaction").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
527
						}
528
						}
528
				    }
529
				    }
529
				},
530
				},
530
				error : function(jqXHR, textStatus, errorThrown) {
531
				error : function(jqXHR, textStatus, errorThrown) {
531
					erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
532
					erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
532
					try {
533
					try {
533
						reponse = jQuery.parseJSON(jqXHR.responseText);
534
						reponse = jQuery.parseJSON(jqXHR.responseText);
534
						if (reponse != null) {
535
						if (reponse != null) {
535
							$.each(reponse, function (cle, valeur) {
536
							$.each(reponse, function (cle, valeur) {
536
								erreurMsg += valeur + "\n";
537
								erreurMsg += valeur + "\n";
537
							});
538
							});
538
						}
539
						}
539
					} catch(e) {
540
					} catch(e) {
540
						erreurMsg += "L'erreur n'était pas en JSON.";
541
						erreurMsg += "L'erreur n'était pas en JSON.";
541
					}
542
					}
542
					
543
					
543
					if (DEBUG) {
544
					if (DEBUG) {
544
						$("#dialogue-obs-transaction").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
545
						$("#dialogue-obs-transaction").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
545
					}
546
					}
546
				},
547
				},
547
				complete : function(jqXHR, textStatus) {
548
				complete : function(jqXHR, textStatus) {
548
					$("#chargement").hide();
549
					$("#chargement").hide();
549
					var debugMsg = '';
550
					var debugMsg = '';
550
					if (jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
551
					if (jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
551
						debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
552
						debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
552
						if (debugInfos != null) {
553
						if (debugInfos != null) {
553
							$.each(debugInfos, function (cle, valeur) {
554
							$.each(debugInfos, function (cle, valeur) {
554
								debugMsg += valeur + "\n";
555
								debugMsg += valeur + "\n";
555
							});
556
							});
556
						}
557
						}
557
					}
558
					}
558
					if (erreurMsg != '') {
559
					if (erreurMsg != '') {
559
						$("#dialogue-obs-transaction").append('<p class="msg">'+
560
						$("#dialogue-obs-transaction").append('<p class="msg">'+
560
								'Une erreur est survenue lors de la transmission de vos observations.'+'<br />'+
561
								'Une erreur est survenue lors de la transmission de vos observations.'+'<br />'+
561
								'Vous pouvez signaler le disfonctionnement à <a href="'+
562
								'Vous pouvez signaler le disfonctionnement à <a href="'+
562
								'mailto:cel@tela-botanica.org'+'?'+
563
								'mailto:cel@tela-botanica.org'+'?'+
563
								'subject=Disfonctionnement du widget de saisie Biodiversite34'+
564
								'subject=Disfonctionnement du widget de saisie Biodiversite34'+
564
								"&body="+erreurMsg+"\nDébogage :\n"+debugMsg+
565
								"&body="+erreurMsg+"\nDébogage :\n"+debugMsg+
565
								'">cel@tela-botanica.org</a>.'+
566
								'">cel@tela-botanica.org</a>.'+
566
								'</p>');
567
								'</p>');
567
					}
568
					}
568
					if (DEBUG) {
569
					if (DEBUG) {
569
						$("#dialogue-obs-transaction").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
570
						$("#dialogue-obs-transaction").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
570
					}
571
					}
571
					
572
					
572
					$("#dialogue-obs-transaction").dialog();
573
					$("#dialogue-obs-transaction").dialog();
573
					$("#liste-obs").removeData();
574
					$("#liste-obs").removeData();
574
					$('.obs').remove();
575
					$('.obs').remove();
575
					obsNumero = 0;
576
					obsNumero = 0;
576
				}
577
				}
577
			});
578
			});
578
		}
579
		}
579
		return false;
580
		return false;
580
	});
581
	});
581
});
582
});
582
 
583
 
583
function getB64ImgOriginal() {
584
function getB64ImgOriginal() {
584
	var b64 = '';
585
	var b64 = '';
585
	if ($("#miniature-img").hasClass('b64')) {
586
	if ($("#miniature-img").hasClass('b64')) {
586
		b64 = $("#miniature-img").attr('src');
587
		b64 = $("#miniature-img").attr('src');
587
	} else if ($("#miniature-img").hasClass('b64-canvas')) {
588
	} else if ($("#miniature-img").hasClass('b64-canvas')) {
588
		b64 = $("#miniature-img").data('b64');
589
		b64 = $("#miniature-img").data('b64');
589
	}
590
	}
590
	return b64;
591
	return b64;
591
}
592
}
592
 
593
 
593
function supprimerObs() {
594
function supprimerObs() {
594
	var obsId = $(this).val();
595
	var obsId = $(this).val();
595
	// Problème avec IE 6 et 7
596
	// Problème avec IE 6 et 7
596
	if (obsId == "Supprimer") {
597
	if (obsId == "Supprimer") {
597
		obsId = $(this).attr("title");
598
		obsId = $(this).attr("title");
598
	}
599
	}
599
	
600
	
600
	$('#obs'+obsId).remove();
601
	$('#obs'+obsId).remove();
601
	$("#liste-obs").removeData('obsId'+obsId);
602
	$("#liste-obs").removeData('obsId'+obsId);
602
}
603
}
603
 
604
 
604
function ajouterImgMiniatureAuTransfert() {
605
function ajouterImgMiniatureAuTransfert() {
605
	var miniature = '';
606
	var miniature = '';
606
	if ($("#miniature img").length == 1) {
607
	if ($("#miniature img").length == 1) {
607
		var css = $("#miniature-img").hasClass('b64') ? 'miniature b64' : 'miniature';
608
		var css = $("#miniature-img").hasClass('b64') ? 'miniature b64' : 'miniature';
608
		var src = $("#miniature-img").attr("src");
609
		var src = $("#miniature-img").attr("src");
609
		var alt = $("#miniature-img").attr("alt");
610
		var alt = $("#miniature-img").attr("alt");
610
		miniature = '<img class="'+css+'" alt="'+alt+'"src="'+src+'" />';
611
		miniature = '<img class="'+css+'" alt="'+alt+'"src="'+src+'" />';
611
	}
612
	}
612
	return miniature;
613
	return miniature;
613
}
614
}