Subversion Repositories eFlore/Applications.cel

Rev

Rev 1056 | Rev 1073 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1056 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
			},
1070 jpm 187
			rue : "required",
188
			rue_num_debut : {
189
				required : true,
190
				digits : true,
191
				min : 1},
192
			rue_num_fin : {
193
				required : true,
194
				digits : true,
195
				min : 1},
196
			rue_cote : "required",
1056 jpm 197
			milieu : "required",
198
			adresse : "required",
199
			latitude : {
200
				required: true,
201
				range: [-90, 90]},
202
			longitude : {
203
				required: true,
204
				range: [-180, 180]},
205
			date : {
206
				required: true,
207
				date: true},
208
			taxon : "required"
209
		}
210
	});
211
 
212
	$("#date").datepicker($.datepicker.regional['fr']);
213
 
214
	$("#courriel_confirmation").bind('paste', function(e) {
215
		$("#dialogue-bloquer-copier-coller").dialog();
216
		return false;
217
	});
218
 
219
	/*---Afficher/cacher les coordonnees geographiques----*/
220
 
221
	var showText=" -Afficher-";
222
	var hideText=" -Masquer- ";
223
 
224
	//créer le lien afficher/masquer
225
	$("#coordonnees-geo").before("<a href='#' id='toogle_link'>"+showText+"</a>")
226
	//masquer le contenu
227
	$("#masque").hide();
228
	//bascule le texte d'afficher à masquer
229
	$("a#toogle_link").click(function() {
230
		//changer le texte du lien
231
		if($('a#toogle_link').text()==showText){
232
			$('a#toogle_link').text(hideText);
233
		} else{
234
			$('a#toogle_link').text(showText);
235
		}
236
	//basuler l'affichage
237
	$('#masque').toggle('slow');
238
	//valeur false pour que le lien ne soit pas suivi
239
	return false
240
	});
241
 
242
	/*------obs-----------*/
243
 
244
	var obsNumero = 0;
245
	$("#ajouter-obs").bind('click', function(e) {
246
		if ($("#saisie-obs").valid() == false) {
247
			$("#dialogue-form-invalide").dialog();
248
		} else {
249
			//rassemble les obs dans un tableau html
250
			obsNumero = obsNumero + 1;
251
			$("#liste-obs tbody").append(
252
					'<tr id="obs'+obsNumero+'" class="obs">'+
253
					'<td>'+obsNumero+'</td>'+
254
					'<td>'+$("#date").val()+'</td>'+
255
					'<td>'+$("#adresse").val()+'</td>'+
256
					'<td>'+$("#taxon option:selected").text()+'</td>'+
257
					'<td>'+$('input[name=milieu]:checked').val()+'</td>'+
258
					'<td>'+$("#latitude").val()+'</td>'+
259
					'<td>'+$("#longitude").val()+'</td>'+
260
					//Ajout du champ photo
261
					'<td><img class="miniature" alt="'+$("#miniature-img").attr("alt")+'"src="'+$("#miniature-img").attr("src")+'" /></td>'+
262
					'<td>'+$("#notes").val()+'</td>'+
263
					'<td><button class="supprimer-obs" value="'+obsNumero+'" title="Supprimer l\'observation '+obsNumero+'">'+
264
					'<img src="'+SUPPRIMER_ICONE_URL+'"/></button></td>'+
265
				'</tr>');
266
			//rassemble les obs dans #liste-obs
267
			var numNomSel = $("#taxon").val();
268
			$("#liste-obs").data('obsId'+obsNumero, {
269
				'date' : $("#date").val(),
270
				'num_nom_sel' : numNomSel,
271
				'nom_sel' : taxons[numNomSel]['nom_sel'],
272
				'nom_ret' : taxons[numNomSel]['nom_ret'],
273
				'num_nom_ret' : taxons[numNomSel]['num_nom_ret'],
274
				'num_taxon' : taxons[numNomSel]['num_taxon'],
275
				'famille' : taxons[numNomSel]['famille'],
276
				'nom_fr' : taxons[numNomSel]['nom_fr'],
1070 jpm 277
				'commune' : '',// TODO : utiliser le web service
278
				'lieu_dit' : $("#rue").val(),
279
				'station' : $("#rue_num_debut").val()+'-'+$("#rue_num_fin").val()+'-'+$("#rue_cote").val(),
1056 jpm 280
				'milieu' : $('input[name=milieu]:checked').val(),
281
				'latitude' : $("#latitude").val(),
282
				'longitude' : $("#longitude").val(),
283
				'tag' : 'Sauvages',
1070 jpm 284
				'notes' : $("#notes").val(),
285
				//Ajout des champs images
1056 jpm 286
				'image_nom' : $("#miniature-img").attr('alt'),
1070 jpm 287
				'image_b64' : ''// TODO : ajoute le support HTML5
288
				});
1056 jpm 289
		}
290
	});
291
 
292
	$(".supprimer-obs").live('click', function() {
293
		var obsId = $(this).val();
294
		// Problème avec IE 6 et 7
295
		if (obsId == "Supprimer") {
296
			obsId = $(this).attr("title");
297
		}
298
 
299
		$('#obs'+obsId).remove();
300
		$("#liste-obs").removeData('obsId'+obsId)
301
	});
302
 
303
	$("#effacer-miniature").click(function () {
304
		$("#miniature").empty();
305
	});
306
 
307
	// TODO : remplacer par du jquery
308
	//document.getElementById('image_file').addEventListener('change', handleFileSelect, false);
309
 
310
	$("#transmettre-obs").click(function(e) {
311
		var observations = $("#liste-obs").data();
312
		if (observations == undefined || jQuery.isEmptyObject(observations)) {
313
			$("#dialogue-zero-obs").dialog();
314
		} else if ($("#saisie-obs").valid() == false) {
315
			$("#dialogue-form-invalide").dialog();
316
		} else {
317
			var utilisateur = new Object();
318
			utilisateur.prenom = $("#prenom").val();
319
			utilisateur.nom = $("#nom").val();
320
			utilisateur.courriel = $("#courriel").val();
321
			observations['utilisateur'] = utilisateur;
322
					$.ajax({
323
						url : SERVICE_SAISIE_URL,
324
						type : "POST",
325
						data : observations,
326
						context : document.body,
327
						beforeSend : function() {
328
							$("#msg").remove();
329
							$("#msg-erreur").remove();
330
							$("#msg-debug").remove();
331
						},
332
						statusCode : {
333
						    500 : function(jqXHR, textStatus, errorThrown) {
334
								$("#dialogue-obs-transaction").append('<p id="msg">Un problème est survenu lors de la transmission de vos observations.</p>');
335
								reponse = jQuery.parseJSON(jqXHR.responseText);
336
								var erreurMsg = "";
337
								if (reponse != null) {
338
									$.each(reponse, function (cle, valeur) {
339
										erreurMsg += valeur + "<br />";
340
									});
341
								}
342
 
343
								$("#dialogue-obs-transaction").append('<p id="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
344
						    }
345
						},
346
						success : function(data, textStatus, jqXHR) {
347
							$("#dialogue-obs-transaction").append('<p id="msg">Vos observations ont bien été transmises.</p>');
348
						},
349
						complete : function(jqXHR, textStatus) {
350
							var debugMsg = "";
351
							if (DEBUG && jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
352
								debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
353
								if (debugInfos != null) {
354
									$.each(debugInfos, function (cle, valeur) {
355
										debugMsg += valeur + "<br />";
356
									});
357
									$("#dialogue-obs-transaction").append('<pre id="msg-debug">Débogage : '+debugMsg+'</pre>');
358
								}
359
							}
360
 
361
							$("#dialogue-obs-transaction").dialog();
362
							$("#liste-obs").removeData();
363
							$('.obs').remove();
364
							obsNumero = 0;
365
						},
366
 
367
					});
368
		}
369
		return false;
370
	});
371
});
372
 
373
 
374
function handleFileSelect(evt) {
375
	// Check for the various File API support.
376
	if (window.File && window.FileReader && window.FileList && window.Blob) {
377
	// Great success! All the File APIs are supported.
378
		var selectedfiles = evt.target.files; // FileList object
379
 
380
		// Loop through the FileList and render image files as thumbnails.
381
		for (var i = 0, f; f = selectedfiles[i]; i++) {
382
 
383
		  // Only process image files.
384
		  if (!f.type.match('image.*')) {
385
		    continue;
386
		  }
387
 
388
		  var reader = new FileReader();
389
 
390
		  // Read in the image file as a data URL.
391
		  reader.readAsDataURL(f);
392
 
393
		  // Closure to capture the file information.
394
		  reader.onload = (function(theFile) {
395
			 return function(e) {
396
		    	// Render thumbnail.
397
		    	document.getElementById('image').src = e.target.result;
398
		    	//document.getElementById('list').insertBefore(img, null);
399
		    };
400
		  })(f);
401
		}
402
 
403
	}
404
	else {
405
	  alert('The File APIs are not fully supported in this browser.');
406
	}
407
}