Subversion Repositories eFlore/Applications.cel

Rev

Rev 1054 | Rev 1346 | Go to most recent revision | Details | Compare with Previous | 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
1055 jpm 273
				'image_nom' : $("#miniature-img").attr('alt'),
274
				//'image_b64' : $("#miniature-img").attr('alt'),
1054 jpm 275
				'notes' : $("#notes").val()});
276
		}
277
	});
278
 
279
	$(".supprimer-obs").live('click', function() {
280
		var obsId = $(this).val();
281
		// Problème avec IE 6 et 7
282
		if (obsId == "Supprimer") {
283
			obsId = $(this).attr("title");
284
		}
285
 
286
		$('#obs'+obsId).remove();
287
		$("#liste-obs").removeData('obsId'+obsId)
288
	});
289
 
290
	$("#effacer-miniature").click(function () {
291
		$("#miniature").empty();
292
	});
293
 
294
	// TODO : remplacer par du jquery
295
	//document.getElementById('image_file').addEventListener('change', handleFileSelect, false);
296
 
297
	$("#transmettre-obs").click(function(e) {
298
		var observations = $("#liste-obs").data();
299
		if (observations == undefined || jQuery.isEmptyObject(observations)) {
300
			$("#dialogue-zero-obs").dialog();
301
		} else if ($("#saisie-obs").valid() == false) {
302
			$("#dialogue-form-invalide").dialog();
303
		} else {
304
			var utilisateur = new Object();
305
			utilisateur.prenom = $("#prenom").val();
306
			utilisateur.nom = $("#nom").val();
307
			utilisateur.courriel = $("#courriel").val();
308
			observations['utilisateur'] = utilisateur;
309
					$.ajax({
310
						url : SERVICE_SAISIE_URL,
311
						type : "POST",
312
						data : observations,
313
						context : document.body,
314
						beforeSend : function() {
315
							$("#msg").remove();
316
							$("#msg-erreur").remove();
317
							$("#msg-debug").remove();
318
						},
319
						statusCode : {
320
						    500 : function(jqXHR, textStatus, errorThrown) {
321
								$("#dialogue-obs-transaction").append('<p id="msg">Un problème est survenu lors de la transmission de vos observations.</p>');
322
								reponse = jQuery.parseJSON(jqXHR.responseText);
323
								var erreurMsg = "";
324
								if (reponse != null) {
325
									$.each(reponse, function (cle, valeur) {
326
										erreurMsg += valeur + "<br />";
327
									});
328
								}
329
 
330
								$("#dialogue-obs-transaction").append('<p id="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
331
						    }
332
						},
333
						success : function(data, textStatus, jqXHR) {
334
							$("#dialogue-obs-transaction").append('<p id="msg">Vos observations ont bien été transmises.</p>');
335
						},
336
						complete : function(jqXHR, textStatus) {
337
							var debugMsg = "";
338
							if (DEBUG && jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
339
								debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
340
								if (debugInfos != null) {
341
									$.each(debugInfos, function (cle, valeur) {
342
										debugMsg += valeur + "<br />";
343
									});
344
									$("#dialogue-obs-transaction").append('<pre id="msg-debug">Débogage : '+debugMsg+'</pre>');
345
								}
346
							}
347
 
348
							$("#dialogue-obs-transaction").dialog();
349
							$("#liste-obs").removeData();
350
							$('.obs').remove();
351
							obsNumero = 0;
352
						},
353
 
354
					});
355
		}
356
		return false;
357
	});
358
});
359
 
360
 
361
function handleFileSelect(evt) {
362
	// Check for the various File API support.
363
	if (window.File && window.FileReader && window.FileList && window.Blob) {
364
	// Great success! All the File APIs are supported.
365
		var selectedfiles = evt.target.files; // FileList object
366
 
367
		// Loop through the FileList and render image files as thumbnails.
368
		for (var i = 0, f; f = selectedfiles[i]; i++) {
369
 
370
		  // Only process image files.
371
		  if (!f.type.match('image.*')) {
372
		    continue;
373
		  }
374
 
375
		  var reader = new FileReader();
376
 
377
		  // Read in the image file as a data URL.
378
		  reader.readAsDataURL(f);
379
 
380
		  // Closure to capture the file information.
381
		  reader.onload = (function(theFile) {
382
			 return function(e) {
383
		    	// Render thumbnail.
384
		    	document.getElementById('image').src = e.target.result;
385
		    	//document.getElementById('list').insertBefore(img, null);
386
		    };
387
		  })(f);
388
		}
389
 
390
	}
391
	else {
392
	  alert('The File APIs are not fully supported in this browser.');
393
	}
394
}