Subversion Repositories eFlore/Applications.cel

Rev

Rev 1055 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1054 jpm 1
//+---------------------------------------------------------------------------------------------------------+
2
// GÉNÉRAL
3
/**
4
 * Stope l'évènement courrant quand on clique sur un lien.
5
 * Utile pour Chrome, Safari...
6
 * @param evenement
7
 * @return
8
 */
9
function arreter(evenement) {
10
	if (evenement.stopPropagation) {
11
		evenement.stopPropagation();
12
	}
13
	return false;
14
}
15
// TODO : voir si cette fonction est bien utile. Résoud le pb d'un warning sous chrome.
16
(function(){
17
    // remove layerX and layerY
18
    var all = $.event.props,
19
        len = all.length,
20
        res = [];
21
    while (len--) {
22
      var el = all[len];
23
      if (el != 'layerX' && el != 'layerY') res.push(el);
24
    }
25
    $.event.props = res;
26
}());
27
 
28
//+----------------------------------------------------------------------------------------------------------+
29
//UPLOAD PHOTO : Traitement de l'image
30
$(document).ready(function() {
31
	//prepare the form when the DOM is ready
32
	//create service object(proxy) using SMD (generated by the json result)
33
	var options = {
34
		success: afficherMiniature, // post-submit callback
35
		dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
36
		resetForm: true // reset the form after successful submit
37
	};
38
 
39
	// post-submit callback
40
	function afficherMiniature(reponse) {
41
		// 'responseXML' is the XML document returned by the server; we use
42
		// jQuery to extract the content of the message node from the XML doc
43
		var miniatureUrl = $("miniature-url", reponse).text();
44
		var imgNom = $("image-nom", reponse).text();
45
		$("#miniature").empty();
46
		$("#miniature").append('<img id="miniature-img" class="miniature" alt="'+imgNom+'" src="'+miniatureUrl+'"/>');
47
		console.log(imgNom);
48
		console.log(miniatureUrl);
49
	};
50
 
51
	$("#form-upload").submit(function() {
52
		// inside event callbacks 'this' is the DOM element so we first
53
		// wrap it in a jQuery object and then invoke ajaxSubmit
54
		$(this).ajaxSubmit(options);
55
 
56
		// !!! Important !!!
57
		// always return false to prevent standard browser submit and page navigation
58
		return false;
59
	});
60
});
61
 
62
//+----------------------------------------------------------------------------------------------------------+
63
// GOOGLE MAP
64
var geocoder;
65
var map;
66
var marker;
67
var latLng;
68
 
69
function initialize(){
70
	// Carte
71
	var latLng = new google.maps.LatLng(43.29545, 5.37458);
72
	$('#adresse').val('1 rue de la canebiere, 13001');
73
	$('#latitude').val('43.29545');
74
	$('#longitude').val('5.37458');
75
	var options = {
76
		zoom: 16,
77
		center: latLng,
78
		mapTypeId: google.maps.MapTypeId.SATELLITE
79
	};
80
 
81
	map = new google.maps.Map(document.getElementById("map_canvas"), options); //affiche la google map dans la div map_canvas
82
 
83
	// Geocodeur
84
	geocoder = new google.maps.Geocoder();
85
	console.log(GOOGLE_MAP_MARQUEUR_URL);
86
 
87
	// Marqueur google draggable
88
	marker = new google.maps.Marker({
89
		map: map,
90
		draggable: true,
91
		title: 'Ma station',
92
		icon: GOOGLE_MAP_MARQUEUR_URL,
93
		position: latLng
94
	});
95
}
96
 
97
$(document).ready(function() {
98
	initialize();
99
 
100
	$(function() {
101
		// Tentative de geocalisation
102
		if (navigator.geolocation) {
103
			navigator.geolocation.getCurrentPosition(function(position) {
104
				var latitude = position.coords.latitude;
105
				var longitude = position.coords.longitude;
106
				var altitude = position.coords.altitude;
107
				var geocalisation = new google.maps.LatLng(latitude, longitude);
108
				marker.setPosition(geocalisation);
109
				map.setCenter(geocalisation);
110
				$('#latitude').val(marker.getPosition().lat());
111
				$('#longitude').val(marker.getPosition().lng());
112
				$('#adresse').val(codeLatLng(marker.getPosition()));
113
			});
114
		}
115
 
116
		// Autocompletion du champ adresse
117
		$("#adresse").autocomplete({
118
			//Cette partie utilise geocoder pour extraire des valeurs d'adresse
119
			source: function(request, response) {
120
				geocoder.geocode( {'address': request.term }, function(results, status) {
121
					response($.map(results, function(item) {
122
						return {
123
							label:  item.formatted_address,
124
							value: item.formatted_address,
125
							latitude: item.geometry.location.lat(),
126
							longitude: item.geometry.location.lng()
127
						}
128
					}));
129
				})
130
			},
131
			// Cette partie est executee a la selection d'une adresse
132
			select: function(event, ui) {
133
				$("#latitude").val(ui.item.latitude);
134
				$("#longitude").val(ui.item.longitude);
135
				var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
136
				marker.setPosition(location);
137
				map.setCenter(location);
138
				map.setZoom(20);
139
			}
140
		});
141
 
142
		// Ajoute un ecouteur sur le marker pour le reverse geocoding
143
		google.maps.event.addListener(marker, 'drag', function() {
144
			geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
145
				if (status == google.maps.GeocoderStatus.OK) {
146
					if (results[0]) {
147
						$('#adresse').val(results[0].formatted_address);
148
						$('#latitude').val(Math.round(marker.getPosition().lat()*100000)/100000);
149
						$('#longitude').val(Math.round(marker.getPosition().lng()*100000)/100000);
150
					}
151
				}
152
			});
153
		});
154
	});
155
});
156
 
157
// Transforme les coordonnés en adresse (reverse geocoder)
158
function codeLatLng() {
159
	var lat = parseFloat(document.getElementById("latitude").value);
160
	var lng = parseFloat(document.getElementById("longitude").value);
161
	var latlng = new google.maps.LatLng(lat, lng);
162
	geocoder.geocode({'latLng': latlng}, function(results, status) {
163
		if (status == google.maps.GeocoderStatus.OK) {
164
			if (results[0]) {
165
				marker.setPosition(latlng);
166
				map.setCenter(latlng);
167
				$('#adresse').val(results[0].formatted_address);
168
			}
169
		} else {
170
			alert("Geocoder failed due to: " + status);
171
		}
172
	});
173
}
174
 
175
//+---------------------------------------------------------------------------------------------------------+
176
// FORMULAIRE
177
$(document).ready(function() {
178
	$("form#saisie-obs").validate({
179
		rules: {
180
			courriel : {
181
				required : true,
182
				email : true},
183
			courriel_confirmation : {
184
				required : true,
185
				equalTo: "#courriel"
186
			},
187
			milieu : "required",
188
			adresse : "required",
189
			latitude : {
190
				required: true,
191
				range: [-90, 90]},
192
			longitude : {
193
				required: true,
194
				range: [-180, 180]},
195
			date : {
196
				required: true,
197
				date: true},
198
			taxon : "required"
199
		}
200
	});
201
 
202
	$("#date").datepicker($.datepicker.regional['fr']);
203
 
204
	$("#courriel_confirmation").bind('paste', function(e) {
205
		$("#dialogue-bloquer-copier-coller").dialog();
206
		return false;
207
	});
208
 
209
	/*---Afficher/cacher les coordonnees geographiques----*/
210
 
211
	var showText=" -Afficher-";
212
	var hideText=" -Masquer- ";
213
 
214
	//créer le lien afficher/masquer
215
	$("#coordonnees-geo").before("<a href='#' id='toogle_link'>"+showText+"</a>")
216
	//masquer le contenu
217
	$("#masque").hide();
218
	//bascule le texte d'afficher à masquer
219
	$("a#toogle_link").click(function() {
220
		//changer le texte du lien
221
		if($('a#toogle_link').text()==showText){
222
			$('a#toogle_link').text(hideText);
223
		} else{
224
			$('a#toogle_link').text(showText);
225
		}
226
	//basuler l'affichage
227
	$('#masque').toggle('slow');
228
	//valeur false pour que le lien ne soit pas suivi
229
	return false
230
	});
231
 
232
	/*------obs-----------*/
233
 
234
	var obsNumero = 0;
235
	$("#ajouter-obs").bind('click', function(e) {
236
		if ($("#saisie-obs").valid() == false) {
237
			$("#dialogue-form-invalide").dialog();
238
		} else {
239
			//rassemble les obs dans un tableau html
240
			obsNumero = obsNumero + 1;
241
			$("#liste-obs tbody").append(
242
					'<tr id="obs'+obsNumero+'" class="obs">'+
243
					'<td>'+obsNumero+'</td>'+
244
					'<td>'+$("#date").val()+'</td>'+
245
					'<td>'+$("#adresse").val()+'</td>'+
246
					'<td>'+$("#taxon option:selected").text()+'</td>'+
247
					'<td>'+$('input[name=milieu]:checked').val()+'</td>'+
248
					'<td>'+$("#latitude").val()+'</td>'+
249
					'<td>'+$("#longitude").val()+'</td>'+
250
					//Ajout du champ photo
251
					'<td><img class="miniature" alt="'+$("#miniature-img").attr("alt")+'"src="'+$("#miniature-img").attr("src")+'" /></td>'+
252
					'<td>'+$("#notes").val()+'</td>'+
253
					'<td><button class="supprimer-obs" value="'+obsNumero+'" title="Supprimer l\'observation '+obsNumero+'">'+
254
					'<img src="'+SUPPRIMER_ICONE_URL+'"/></button></td>'+
255
				'</tr>');
256
			//rassemble les obs dans #liste-obs
257
			var numNomSel = $("#taxon").val();
258
			$("#liste-obs").data('obsId'+obsNumero, {
259
				'date' : $("#date").val(),
260
				'num_nom_sel' : numNomSel,
261
				'nom_sel' : taxons[numNomSel]['nom_sel'],
262
				'nom_ret' : taxons[numNomSel]['nom_ret'],
263
				'num_nom_ret' : taxons[numNomSel]['num_nom_ret'],
264
				'num_taxon' : taxons[numNomSel]['num_taxon'],
265
				'famille' : taxons[numNomSel]['famille'],
266
				'nom_fr' : taxons[numNomSel]['nom_fr'],
267
				'station' : $("#adresse").val(),
268
				'milieu' : $('input[name=milieu]:checked').val(),
269
				'latitude' : $("#latitude").val(),
270
				'longitude' : $("#longitude").val(),
271
				'tag' : 'Sauvages',
272
				//Ajout du champ photo
273
				'image' : $("#miniature-img").attr('src'),
274
				'notes' : $("#notes").val()});
275
		}
276
	});
277
 
278
	$(".supprimer-obs").live('click', function() {
279
		var obsId = $(this).val();
280
		// Problème avec IE 6 et 7
281
		if (obsId == "Supprimer") {
282
			obsId = $(this).attr("title");
283
		}
284
 
285
		$('#obs'+obsId).remove();
286
		$("#liste-obs").removeData('obsId'+obsId)
287
	});
288
 
289
	$("#effacer-miniature").click(function () {
290
		$("#miniature").empty();
291
	});
292
 
293
	// TODO : remplacer par du jquery
294
	//document.getElementById('image_file').addEventListener('change', handleFileSelect, false);
295
 
296
	$("#transmettre-obs").click(function(e) {
297
		var observations = $("#liste-obs").data();
298
		if (observations == undefined || jQuery.isEmptyObject(observations)) {
299
			$("#dialogue-zero-obs").dialog();
300
		} else if ($("#saisie-obs").valid() == false) {
301
			$("#dialogue-form-invalide").dialog();
302
		} else {
303
			var utilisateur = new Object();
304
			utilisateur.prenom = $("#prenom").val();
305
			utilisateur.nom = $("#nom").val();
306
			utilisateur.courriel = $("#courriel").val();
307
			observations['utilisateur'] = utilisateur;
308
					$.ajax({
309
						url : SERVICE_SAISIE_URL,
310
						type : "POST",
311
						data : observations,
312
						context : document.body,
313
						beforeSend : function() {
314
							$("#msg").remove();
315
							$("#msg-erreur").remove();
316
							$("#msg-debug").remove();
317
						},
318
						statusCode : {
319
						    500 : function(jqXHR, textStatus, errorThrown) {
320
								$("#dialogue-obs-transaction").append('<p id="msg">Un problème est survenu lors de la transmission de vos observations.</p>');
321
								reponse = jQuery.parseJSON(jqXHR.responseText);
322
								var erreurMsg = "";
323
								if (reponse != null) {
324
									$.each(reponse, function (cle, valeur) {
325
										erreurMsg += valeur + "<br />";
326
									});
327
								}
328
 
329
								$("#dialogue-obs-transaction").append('<p id="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
330
						    }
331
						},
332
						success : function(data, textStatus, jqXHR) {
333
							$("#dialogue-obs-transaction").append('<p id="msg">Vos observations ont bien été transmises.</p>');
334
						},
335
						complete : function(jqXHR, textStatus) {
336
							var debugMsg = "";
337
							if (DEBUG && jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
338
								debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
339
								if (debugInfos != null) {
340
									$.each(debugInfos, function (cle, valeur) {
341
										debugMsg += valeur + "<br />";
342
									});
343
									$("#dialogue-obs-transaction").append('<pre id="msg-debug">Débogage : '+debugMsg+'</pre>');
344
								}
345
							}
346
 
347
							$("#dialogue-obs-transaction").dialog();
348
							$("#liste-obs").removeData();
349
							$('.obs').remove();
350
							obsNumero = 0;
351
						},
352
 
353
					});
354
		}
355
		return false;
356
	});
357
});
358
 
359
 
360
function handleFileSelect(evt) {
361
	// Check for the various File API support.
362
	if (window.File && window.FileReader && window.FileList && window.Blob) {
363
	// Great success! All the File APIs are supported.
364
		var selectedfiles = evt.target.files; // FileList object
365
 
366
		// Loop through the FileList and render image files as thumbnails.
367
		for (var i = 0, f; f = selectedfiles[i]; i++) {
368
 
369
		  // Only process image files.
370
		  if (!f.type.match('image.*')) {
371
		    continue;
372
		  }
373
 
374
		  var reader = new FileReader();
375
 
376
		  // Read in the image file as a data URL.
377
		  reader.readAsDataURL(f);
378
 
379
		  // Closure to capture the file information.
380
		  reader.onload = (function(theFile) {
381
			 return function(e) {
382
		    	// Render thumbnail.
383
		    	document.getElementById('image').src = e.target.result;
384
		    	//document.getElementById('list').insertBefore(img, null);
385
		    };
386
		  })(f);
387
		}
388
 
389
	}
390
	else {
391
	  alert('The File APIs are not fully supported in this browser.');
392
	}
393
}