Subversion Repositories eFlore/Applications.cel

Rev

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

Rev Author Line No. Line
836 jpm 1
/*+--------------------------------------------------------------------------------------------------------+*/
2
// PARAMÊTRES et CONSTANTES
941 jpm 3
// Mettre à true pour afficher les messages de débogage
950 jpm 4
var DEBUG = false;
1041 aurelien 5
/**
6
 * Indication de certaines variables ajoutée par php
7
* var communeImageUrl ;
8
* var pointImageUrl ;
9
* var groupeImageUrlTpl ;
10
*/
836 jpm 11
var pointsOrigine = null;
12
var boundsOrigine = null;
13
var markerClusterer = null;
14
var map = null;
15
var infoBulle = new google.maps.InfoWindow();
980 jpm 16
var stations = null;
836 jpm 17
var pointClique = null;
980 jpm 18
var carteCentre = new google.maps.LatLng(25, 10);
836 jpm 19
var carteOptions = {
980 jpm 20
	zoom: 3,
21
	center:carteCentre,
836 jpm 22
	mapTypeId: google.maps.MapTypeId.ROADMAP,
23
	mapTypeControlOptions: {
24
		mapTypeIds: ['OSM',
25
		             google.maps.MapTypeId.ROADMAP,
26
		             google.maps.MapTypeId.HYBRID,
27
		             google.maps.MapTypeId.SATELLITE,
28
		             google.maps.MapTypeId.TERRAIN]
1438 aurelien 29
	},
30
	zoomControlOptions: {
31
        style: google.maps.ZoomControlStyle.LARGE,
32
        position: google.maps.ControlPosition.LEFT_CENTER
33
    },
34
    panControl: false
836 jpm 35
};
36
var osmMapType = new google.maps.ImageMapType({
37
	getTileUrl: function(coord, zoom) {
38
		return "http://tile.openstreetmap.org/" +
39
		zoom + "/" + coord.x + "/" + coord.y + ".png";
40
	},
41
	tileSize: new google.maps.Size(256, 256),
42
	isPng: true,
43
	alt: "OpenStreetMap",
44
	name: "OSM",
45
	maxZoom: 19
46
});
980 jpm 47
var ctaLayer = null;
1271 aurelien 48
var pagineur = {'limite':300, 'start':0, 'total':0, 'stationId':null, 'format':'tableau'};
915 jpm 49
var station = {'commune':'', 'obsNbre':0};
50
var obsStation = new Array();
51
var obsPage = new Array();
939 jpm 52
var taxonsCarte = new Array();
980 jpm 53
var mgr = null;
54
var marqueursCache = new Array();
55
var zonesCache = new Array();
1035 aurelien 56
var requeteChargementPoints;
1142 aurelien 57
var urlVars = null;
836 jpm 58
/*+--------------------------------------------------------------------------------------------------------+*/
59
// INITIALISATION DU CODE
60
 
61
//Déclenchement d'actions quand JQuery et le document HTML sont OK
62
$(document).ready(function() {
63
	initialiserWidget();
64
});
65
 
66
function initialiserWidget() {
1142 aurelien 67
	urlVars = getUrlVars();
980 jpm 68
	definirTailleTitre();
1438 aurelien 69
	centrerTitreEtStats();
836 jpm 70
	initialiserAffichageCarte();
71
	initialiserAffichagePanneauLateral();
72
	initialiserCarte();
980 jpm 73
	initialiserGestionnaireMarqueurs()
836 jpm 74
	initialiserInfoBulle();
941 jpm 75
	initialiserFormulaireContact();
836 jpm 76
	chargerLimitesCommunales();
1032 aurelien 77
	attribuerListenerCarte();
78
	programmerRafraichissementCarte();
836 jpm 79
}
80
 
1142 aurelien 81
function getUrlVars()
82
{
83
    var vars = [], hash;
1151 aurelien 84
    if(window.location.href.indexOf('?') != -1) {
85
	    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
86
	    for(var i = 0; i < hashes.length; i++)
87
	    {
88
	        hash = hashes[i].split('=');
89
	        vars.push(hash[0]);
90
	        vars[hash[0]] = hash[1];
91
	    }
1142 aurelien 92
    }
93
    return vars;
94
}
95
 
915 jpm 96
/*+--------------------------------------------------------------------------------------------------------+*/
97
// AFFICHAGE GÉNÉRAL
98
 
1438 aurelien 99
function afficherTitreCarteEtStats() {
980 jpm 100
	if (stations != null && taxonsCarte.length > 0) {
1039 aurelien 101
		var obsNbre = stations.stats.observations;
1173 aurelien 102
		var obsNbreFormate = obsNbre;
103
		if(obsNbre != 0) {
104
		    obsNbreFormate = stations.stats.observations.formaterNombre();
105
		}
1039 aurelien 106
		var plteNbre = taxonsCarte.length;
1173 aurelien 107
		var plteNbreFormate = plteNbre;
108
		if(plteNbre != 0) {
109
		    plteNbreFormate = taxonsCarte.length.formaterNombre();
110
		}
1039 aurelien 111
		var communeNbre = stations.stats.communes;
1173 aurelien 112
		var communeNbreFormate = communeNbre;
113
		if(communeNbre != 0) {
114
		   communeNbreFormate = stations.stats.communes.formaterNombre();
115
		}
1172 aurelien 116
		var stationNbre = stations.stats.stations;
1173 aurelien 117
		var stationNbreFormate = stationNbre;
118
		if(stationNbre != 0) {
119
		  	stationNbreFormate = stations.stats.stations.formaterNombre();
120
		}
980 jpm 121
 
1438 aurelien 122
		var stats = obsNbreFormate+' observation';
123
		stats += (obsNbre > 1) ? 's' : '' ;
1434 aurelien 124
 
1438 aurelien 125
		if(photos != null && photos == 1) {
126
			stats += ' avec photos ';
1434 aurelien 127
		}
980 jpm 128
 
1438 aurelien 129
		stats += ' sur '+(stationNbre+ communeNbre)+' station';
130
		stats += (stationNbre > 1) ? 's' : '' ;
1430 aurelien 131
 
980 jpm 132
		if (nt == '*') {
1438 aurelien 133
			stats += ' parmi '+plteNbreFormate+' plante';
134
			stats += (plteNbre > 1) ? 's' : '' ;
980 jpm 135
		} else {
1430 aurelien 136
			if($('.taxon-actif .taxon').text() != '') {
137
				var element = $('.taxon-actif .taxon').clone();
138
				element.children().remove();
139
		        var taxon = element.text();
1438 aurelien 140
		        stats += ' pour '+taxon;
1430 aurelien 141
			} else {
142
				if (taxonsCarte[0]) {
143
					var taxon = taxonsCarte[0];
1438 aurelien 144
					stats += ' pour '+taxon.nom;
1430 aurelien 145
				}
980 jpm 146
			}
147
		}
148
 
1438 aurelien 149
		$('#pl-indication-filtre').html('Filtrer parmi <br />'+plteNbre+'<br />plantes');
150
		$('#zone-stats').show();
151
		$('#zone-stats > h1').text(stats);
980 jpm 152
	}
1438 aurelien 153
	centrerTitreEtStats();
836 jpm 154
}
155
 
1438 aurelien 156
var tailleTitreOriginelle = null;
980 jpm 157
function definirTailleTitre() {
158
	var largeurViewPort = $(window).width();
159
	var taille = null;
160
	if (largeurViewPort < 400) {
161
		taille = '0.8';
162
	} else if (largeurViewPort >= 400 && largeurViewPort < 800) {
163
		taille = '1.0';
164
	} else if (largeurViewPort >= 800) {
165
		taille = '1.6';
166
	}
1438 aurelien 167
 
168
	// Aménagement de la taille de police selon l'écran
980 jpm 169
	$("#carte-titre").css('font-size', taille+'em');
1438 aurelien 170
	$("#zone-stats h1").css('font-size', taille+'em');
171
 
172
	// Dimensionnement du titre et du logo
173
	if(urlLogo != "null") {
174
		hauteurLogo = $('#logo img').height();
175
		// Redimensionnement du logo s'il est trop grand
176
		// on perd en qualité mais ça vaut mieux que de casser l'affichage
177
		if(hauteurLogo > 60) {
178
			hauteurLogo = 60;
179
			$('#logo img').height(60);
180
		}
181
 
182
		if(hauteurLogo == 0) {
183
			$('#logo img').load(function(event) {
184
				definirTailleTitre();
185
			});
186
			return;
187
		}
188
 
189
		largeurLogo = $('#logo img').width();
190
		largeurTitre = $('#carte-titre-infos').width();
191
 
192
		$('#zone-titre').css("height", (hauteurLogo)+"px");
193
		$('#zone-titre').css("width", (largeurLogo+largeurTitre+16)+"px");
194
 
195
		if(titreCarte != 'null' && titreCarte != 0) {
196
			$('#carte-titre-infos').css("position", "absolute");
197
			$('#carte-titre-infos').css("left", (largeurLogo+16)+"px");
198
			$('#carte-titre-infos').css("top", (hauteurLogo/2 - 8)+"px");
199
		}
200
	}
980 jpm 201
}
202
 
1438 aurelien 203
function centrerTitreEtStats() {
204
	var largeurViewPort = $(window).width();
205
	var largeurTitre = $('#zone-titre').width();
206
	var marge = (largeurViewPort - largeurTitre)/2;
207
	$('#zone-titre').css("margin-left",marge);
208
 
209
	var largeurStats = $('#zone-stats').width();
210
	var marge = (largeurViewPort - largeurStats)/2;
211
	$('#zone-stats').css("left",marge);
212
}
213
 
915 jpm 214
/*+--------------------------------------------------------------------------------------------------------+*/
215
// CARTE
216
 
836 jpm 217
function initialiserAffichageCarte() {
1438 aurelien 218
	$('#carte').height($(window).height());
219
	$('#carte').width($(window).width());
836 jpm 220
}
221
 
222
function initialiserCarte() {
223
	map = new google.maps.Map(document.getElementById('carte'), carteOptions);
224
	// Ajout de la couche OSM à la carte
225
	map.mapTypes.set('OSM', osmMapType);
226
}
227
 
980 jpm 228
function initialiserGestionnaireMarqueurs() {
229
	mgr = new MarkerManager(map);
230
}
836 jpm 231
 
232
function chargerLimitesCommunales() {
233
	if (urlsLimitesCommunales != null) {
234
		for (urlId in urlsLimitesCommunales) {
235
			var url = urlsLimitesCommunales[urlId];
1107 aurelien 236
			ctaLayer = new google.maps.KmlLayer(url, {preserveViewport: true});
836 jpm 237
			ctaLayer.setMap(map);
238
		}
239
	}
240
}
1039 aurelien 241
 
980 jpm 242
var listener = null;
243
var timer = null;
1032 aurelien 244
function attribuerListenerCarte() {
980 jpm 245
	listener = google.maps.event.addListener(map, 'bounds_changed', function(){
1032 aurelien 246
		programmerRafraichissementCarte();
980 jpm 247
	});
1032 aurelien 248
	listener = google.maps.event.addListener(map, 'zoom_changed', function(){
249
		programmerRafraichissementCarte();
250
	});
980 jpm 251
}
1032 aurelien 252
function programmerRafraichissementCarte() {
253
	if(timer != null) {
254
        window.clearTimeout(timer);
1035 aurelien 255
    }
256
	if(requeteChargementPoints != null) {
257
		requeteChargementPoints.abort();
258
	}
1032 aurelien 259
	timer = window.setTimeout(function() {
1342 aurelien 260
		if(map.getBounds() != undefined) {
261
			var zoom = map.getZoom();
1434 aurelien 262
			var lngNE = map.getBounds().getNorthEast().lng();
263
			var lngSW = map.getBounds().getSouthWest().lng()
264
			if(map.getBounds().getNorthEast().lng() < map.getBounds().getSouthWest().lng()) {
265
				lngNE = 176;
266
				lngSW = -156;
267
			}
268
			var NELatLng = (map.getBounds().getNorthEast().lat())+'|'+(lngNE);
269
			var SWLatLng = (map.getBounds().getSouthWest().lat())+'|'+(lngSW);
1342 aurelien 270
			chargerMarqueurs(zoom, NELatLng, SWLatLng);
271
		} else {
272
			programmerRafraichissementCarte();
273
		}
1032 aurelien 274
    }, 400);
275
}
836 jpm 276
 
980 jpm 277
var marqueurs = new Array();
278
function chargerMarqueurs(zoom, NELatLng, SWLatLng) {
279
	var url = stationsUrl+
280
		'&zoom='+zoom+
281
		'&ne='+NELatLng+
282
		'&sw='+SWLatLng;
283
 
1032 aurelien 284
	if(infoBulleOuverte) {
285
		return;
286
	}
287
 
1035 aurelien 288
	if(requeteChargementPoints != null) {
289
		requeteChargementPoints.abort();
1037 aurelien 290
		cacherMessageChargementPoints();
1035 aurelien 291
	}
292
 
293
	afficherMessageChargementPoints();
294
	requeteChargementPoints = $.getJSON(url, function(data) {
295
		rafraichirMarqueurs(data);
296
		cacherMessageChargementPoints();
980 jpm 297
	});
298
}
299
 
1035 aurelien 300
function afficherMessageChargementPoints() {
301
	$('#zone-chargement-point').css('display','block');
302
}
303
 
304
function cacherMessageChargementPoints() {
305
	$('#zone-chargement-point').css('display','none');
306
}
307
 
1107 aurelien 308
premierChargement = true;
1142 aurelien 309
function doitCentrerCarte() {
310
	return premierChargement && urlVars != null && urlVars.length > 0;
311
}
1107 aurelien 312
 
1035 aurelien 313
function rafraichirMarqueurs(data) {
314
	$.each(marqueurs, function(index, marqueur) {
315
		marqueur.setMap(null);
316
	});
317
	marqueurs = new Array();
318
 
319
	stations = data;
1438 aurelien 320
	afficherTitreCarteEtStats();
1035 aurelien 321
 
322
	$.each(stations.points, function (index, station) {
323
		if(station != null) {
1039 aurelien 324
			var nouveauMarqueur = creerMarqueur(station);
325
			marqueurs.push(nouveauMarqueur);
1035 aurelien 326
		}
327
	});
1107 aurelien 328
 
1142 aurelien 329
	if(doitCentrerCarte()) {
1107 aurelien 330
		premierChargement = false;
331
		var bounds = new google.maps.LatLngBounds();
332
		var latMax = new google.maps.LatLng(data.stats.coordmax.latMax, data.stats.coordmax.lngMax);
333
		var latMin = new google.maps.LatLng(data.stats.coordmax.latMin, data.stats.coordmax.lngMin);
334
		bounds.extend(latMax);
335
		bounds.extend(latMin);
336
		rendrePointsVisibles(bounds);
337
	}
1035 aurelien 338
}
339
 
980 jpm 340
function creerMarqueur(station) {
1037 aurelien 341
	var titre = '';
342
	if(station.nbreMarqueur) {
343
		titre = station.nbreMarqueur+' points renseignés';
344
	} else {
345
		if(station.nom) {
346
			titre = station.nom;
347
		}
348
	}
1434 aurelien 349
 
980 jpm 350
	var icone = attribuerImageMarqueur(station['id'], station['nbreMarqueur']);
351
	var latLng = new google.maps.LatLng(station['lat'], station['lng']);
352
	var marqueur = new google.maps.Marker({
353
		position: latLng,
354
		icon: icone,
355
		title: ''+titre,
356
		map: map,
357
		stationInfos: station
358
	});
359
	attribuerListenerClick(marqueur, station['id']);
360
	marqueur.setMap(map);
361
    return marqueur;
362
}
363
 
1039 aurelien 364
function rendrePointsVisibles(bounds) {
365
	map.setCenter(bounds.getCenter());
366
	map.fitBounds(bounds);
367
}
368
 
980 jpm 369
function attribuerImageMarqueur(id, nbreMarqueur) {
370
	var marqueurImage = null;
371
	if (etreMarqueurCommune(id)) {
372
		marqueurImage = new google.maps.MarkerImage(communeImageUrl, new google.maps.Size(24, 32));
373
	} else if (etreMarqueurStation(id)) {
374
		marqueurImage = new google.maps.MarkerImage(pointImageUrl, new google.maps.Size(16, 16));
375
	} else if (etreMarqueurGroupe(id)) {
376
		var type = 0;
377
		var largeur = 0;
378
		var hauteur = 0;
379
		if (nbreMarqueur != null) {
380
			if (nbreMarqueur >= 2 && nbreMarqueur < 100 ) {
381
				type = '1';
382
				largeur = 53;
383
				hauteur = 52;
384
			} else if (nbreMarqueur >= 100 && nbreMarqueur < 1000 ) {
385
				type = '2';
386
				largeur = 56;
387
				hauteur = 55;
388
			} else if (nbreMarqueur >= 1000 && nbreMarqueur < 10000 ) {
389
				type = '3';
390
				largeur = 66;
391
				hauteur = 65;
392
			} else if (nbreMarqueur >= 10000 && nbreMarqueur < 20000 ) {
393
				type = '4';
394
				largeur = 78;
395
				hauteur = 77;
396
			} else if (nbreMarqueur >= 20000) {
397
				type = '5';
398
				largeur = 66;
399
				hauteur = 65;
400
			}
401
		}
402
		groupeImageUrl = groupeImageUrlTpl.replace(/\{type\}/, type);
403
		groupeImageUrl = groupeImageUrl.replace(/\{nbre\}/, nbreMarqueur);
404
		marqueurImage = new google.maps.MarkerImage(groupeImageUrl, new google.maps.Size(largeur, hauteur));
405
	}
406
	return marqueurImage
407
}
408
 
409
function attribuerListenerClick(marqueur, id) {
410
	if (etreMarqueurCommune(id) || etreMarqueurStation(id)) {
411
		google.maps.event.addListener(marqueur, 'click', surClickMarqueur);
412
	} else if (etreMarqueurGroupe(id)) {
413
		google.maps.event.addListener(marqueur, 'click', surClickGroupe);
414
	}
415
}
416
 
1032 aurelien 417
function surClickMarqueur(event) {
1039 aurelien 418
 
419
	if(infoBulleOuverte) {
420
	    infoBulle.close();
421
	}
422
 
1035 aurelien 423
	pointClique = this;
980 jpm 424
	infoBulle.open(map, this);
425
	actualiserPagineur();
1035 aurelien 426
 
427
	var limites = map.getBounds();
428
	var centre = limites.getCenter();
429
	var nordEst = limites.getNorthEast();
430
	var centreSudLatLng = new google.maps.LatLng(nordEst.lat(), centre.lng());
431
	map.panTo(centreSudLatLng);
432
 
980 jpm 433
	afficherInfoBulle();
434
}
435
 
436
function surClickGroupe() {
437
	map.setCenter(this.getPosition());
438
	var nouveauZoom = map.getZoom() + 2;
439
	map.setZoom(nouveauZoom);
440
	mgr.clearMarkers();
441
}
442
 
443
function etreMarqueurGroupe(id) {
444
	var groupe = false;
445
	var motif = /^GROUPE/;
446
	if (motif.test(id)) {
447
		groupe = true;
448
	}
449
	return groupe;
450
}
451
 
452
function etreMarqueurCommune(id) {
453
	var commune = false;
454
	var motif = /^COMMUNE:/;
455
	if (motif.test(id)) {
456
		commune = true;
457
	}
458
	return commune;
459
}
460
 
461
function etreMarqueurStation(id) {
462
	var station = false;
463
	var motif = /^STATION:/;
464
	if (motif.test(id)) {
465
		station = true;
466
	}
467
	return station;
468
}
469
 
470
function deplacerCarteSurPointClique() {
915 jpm 471
	map.panTo(pointClique.position);
472
}
473
 
474
/*+--------------------------------------------------------------------------------------------------------+*/
475
// INFO BULLE
1032 aurelien 476
var infoBulleOuverte = false;
915 jpm 477
function initialiserInfoBulle() {
478
	google.maps.event.addListener(infoBulle, 'domready', initialiserContenuInfoBulle);
980 jpm 479
	google.maps.event.addListener(infoBulle, 'closeclick', surFermetureInfoBulle);
480
	google.maps.event.addListener(infoBulle, 'content_changed', definirLargeurInfoBulle);
915 jpm 481
}
482
 
980 jpm 483
function surFermetureInfoBulle() {
1032 aurelien 484
	infoBulleOuverte = false;
485
	programmerRafraichissementCarte();
980 jpm 486
}
487
 
488
function centrerInfoBulle() {
489
	var limites = map.getBounds();
490
	var centre = limites.getCenter();
491
	var nordEst = limites.getNorthEast();
492
	var centreSudLatLng = new google.maps.LatLng(nordEst.lat(), centre.lng());
493
	map.panTo(centreSudLatLng);
494
}
495
 
915 jpm 496
function afficherInfoBulle() {
497
	var obsHtml = $("#tpl-obs").html();
980 jpm 498
	var largeur = definirLargeurInfoBulle();
499
	obsHtml = obsHtml.replace(/\{largeur\}/, largeur);
915 jpm 500
	infoBulle.setContent(obsHtml);
1035 aurelien 501
	chargerObs(0, 0);
1032 aurelien 502
	infoBulleOuverte = true;
915 jpm 503
}
504
 
980 jpm 505
function definirLargeurInfoBulle() {
506
	var largeurViewPort = $(window).width();
507
	var lageurInfoBulle = null;
508
	if (largeurViewPort < 800) {
509
		largeurInfoBulle = 400;
510
	} else if (largeurViewPort >= 800 && largeurViewPort < 1200) {
511
		largeurInfoBulle = 500;
512
	} else if (largeurViewPort >= 1200) {
513
		largeurInfoBulle = 600;
514
	}
515
	return largeurInfoBulle;
516
}
517
 
915 jpm 518
function afficherMessageChargement(element) {
519
	if ($('#chargement').get() == '') {
520
		$('#tpl-chargement').tmpl().appendTo(element);
521
	}
522
}
523
 
1035 aurelien 524
function afficherMessageChargementTitreInfoBulle() {
525
	$("#obs-station-titre").text("Chargement des observations");
526
}
527
 
915 jpm 528
function supprimerMessageChargement() {
529
	$('#chargement').remove();
530
}
531
 
532
function chargerObs(depart, total) {
939 jpm 533
	if (depart == 0 || depart < total) {
915 jpm 534
		var limite = 300;
535
		if (depart == 0) {
1036 aurelien 536
			viderTableauObs();
915 jpm 537
		}
1035 aurelien 538
 
939 jpm 539
		var urlObs = observationsUrl+'&start={start}&limit='+limite;
1166 aurelien 540
		urlObs = urlObs.replace(/\{stationId\}/g, encodeURIComponent(pointClique.stationInfos.id));
1044 aurelien 541
		if (pointClique.stationInfos.type_emplacement == 'communes') {
1342 aurelien 542
			urlObs = urlObs.replace(/commune=%2A/g, formaterParametreCommunePourRequete(pointClique.stationInfos.nom));
1042 aurelien 543
		}
939 jpm 544
		urlObs = urlObs.replace(/\{nt\}/g, nt);
915 jpm 545
		urlObs = urlObs.replace(/\{start\}/g, depart);
546
 
547
		$.getJSON(urlObs, function(observations){
1036 aurelien 548
			surRetourChargementObs(observations, depart, total);
1035 aurelien 549
			chargerObs(depart+limite, observations.total);
915 jpm 550
		});
1036 aurelien 551
	}
552
}
553
 
1342 aurelien 554
function formaterParametreCommunePourRequete(nomCommune) {
555
	var chaineRequete = "";
556
	if(nomCommune.indexOf("(", 0) !== false) {
557
		var infosCommune = nomCommune.split("(");
558
		var commune = infosCommune[0];
559
		chaineRequete = 'commune='+encodeURIComponent($.trim(commune));
560
	} else {
561
		chaineRequete = 'commune='+encodeURIComponent($.trim(nomCommune));
562
	}
563
	return chaineRequete;
564
}
565
 
1036 aurelien 566
function viderTableauObs() {
567
	obsStation = new Array();
568
	surClicPagePagination(0, null);
569
}
570
 
571
function surRetourChargementObs(observations, depart, total) {
572
	obsStation = obsStation.concat(observations.observations);
573
	if (depart == 0) {
574
		actualiserInfosStation(observations);
575
		creerTitreInfoBulle();
1041 aurelien 576
		surClicPagePagination(0, null);
915 jpm 577
	}
1036 aurelien 578
 
1039 aurelien 579
	afficherPagination();
1036 aurelien 580
	actualiserPagineur();
1041 aurelien 581
	selectionnerOnglet("#obs-vue-"+pagineur.format);
915 jpm 582
}
583
 
1035 aurelien 584
function actualiserInfosStation(infos) {
585
	pointClique.stationInfos.commune = infos.commune;
586
	pointClique.stationInfos.obsNbre = infos.total;
587
}
588
 
589
function creerTitreInfoBulle() {
590
	$("#obs-total").text(station.obsNbre);
591
	$("#obs-commune").text(station.commune);
592
	var titre = '';
593
	titre += pointClique.stationInfos.obsNbre+' observation';
594
	titre += (pointClique.stationInfos.obsNbre > 1) ? 's': '' ;
595
	titre += ' pour ';
596
	if (etreMarqueurCommune(pointClique.stationInfos.id)) {
597
		nomStation = 'la commune : ';
598
	} else {
599
		nomStation = 'la station : ';
600
	}
601
	titre += pointClique.stationInfos.nom;
602
	$("#obs-station-titre").text(titre);
603
}
604
 
939 jpm 605
function actualiserPagineur() {
980 jpm 606
	pagineur.stationId = pointClique.stationInfos.id;
1035 aurelien 607
	pagineur.total = pointClique.stationInfos.obsNbre;
1435 aurelien 608
	// Si on est en mode photo on reste en mode liste quelque soit le
609
	// nombre de résultats
1438 aurelien 610
	if (pagineur.total > 4 && photos != 1) {
939 jpm 611
		pagineur.format = 'tableau';
612
	} else {
613
		pagineur.format = 'liste';
614
	}
615
}
616
 
915 jpm 617
function afficherPagination(observations) {
618
	$(".navigation").pagination(pagineur.total, {
619
		items_per_page:pagineur.limite,
620
		callback:surClicPagePagination,
621
		next_text:'Suivant',
622
		prev_text:'Précédent',
623
		prev_show_always:false,
624
		num_edge_entries:1,
953 jpm 625
		num_display_entries:4,
915 jpm 626
		load_first_page:true
627
	});
628
}
629
 
630
function surClicPagePagination(pageIndex, paginationConteneur) {
631
	var index = pageIndex * pagineur.limite;
632
	var indexMax = index + pagineur.limite;
633
	pagineur.depart = index;
634
	obsPage = new Array();
635
    for(index; index < indexMax; index++) {
636
    	obsPage.push(obsStation[index]);
637
    }
638
 
639
    supprimerMessageChargement();
640
    mettreAJourObservations();
641
	return false;
642
}
643
 
644
function mettreAJourObservations() {
645
	$("#obs-"+pagineur.format+"-lignes").empty();
646
   	$("#obs-vue-"+pagineur.format).css('display', 'block');
647
   	$(".obs-conteneur").css('counter-reset', 'item '+pagineur.depart);
648
	$("#tpl-obs-"+pagineur.format).tmpl(obsPage).appendTo("#obs-"+pagineur.format+"-lignes");
649
 
650
	// Actualisation de Fancybox
1414 aurelien 651
	ajouterFormulaireContact("a.contact");
915 jpm 652
	if (pagineur.format == 'liste') {
836 jpm 653
		ajouterGaleriePhoto("a.cel-img");
654
	}
655
}
656
 
915 jpm 657
function initialiserContenuInfoBulle() {
980 jpm 658
	afficherMessageChargement('#observations');
659
	cacherContenuOnglets();
915 jpm 660
	afficherOnglets();
661
	ajouterTableauTriable("#obs-tableau");
662
	afficherTextStationId();
663
	corrigerLargeurInfoWindow();
664
}
665
 
980 jpm 666
function cacherContenuOnglets() {
667
	$("#obs-vue-tableau").css("display", "none");
668
	$("#obs-vue-liste").css("display", "none");
669
}
670
 
915 jpm 671
function afficherOnglets() {
672
	var $tabs = $('#obs').tabs();
673
	$('#obs').bind('tabsselect', function(event, ui) {
674
		if (ui.panel.id == 'obs-vue-tableau') {
675
			surClicAffichageTableau();
676
		} else if (ui.panel.id == 'obs-vue-liste') {
677
			surClicAffichageListe();
678
		}
679
	});
980 jpm 680
	if (pointClique.stationInfos.nbre > 4) {
681
		$tabs.tabs('select', "#obs-vue-tableau");
682
	} else {
683
		$tabs.tabs('select', "#obs-vue-liste");
684
	}
685
 
915 jpm 686
}
687
 
939 jpm 688
function selectionnerOnglet(onglet) {
980 jpm 689
	$(onglet).css('display', 'block');
939 jpm 690
	$('#obs').tabs('select', onglet);
691
}
692
 
915 jpm 693
function afficherTextStationId() {
980 jpm 694
	$('#obs-station-id').text(pointClique.stationInfos.id);
915 jpm 695
}
696
 
697
function corrigerLargeurInfoWindow() {
953 jpm 698
	$("#info-bulle").width($("#info-bulle").width() - 17);
915 jpm 699
}
700
 
701
function surClicAffichageTableau(event) {
702
	pagineur.format = 'tableau';
703
	mettreAJourObservations();
704
	mettreAJourTableauTriable("#obs-tableau");
705
}
706
 
707
function surClicAffichageListe(event) {
708
	pagineur.format = 'liste';
709
	mettreAJourObservations();
710
	ajouterGaleriePhoto("a.cel-img");
711
}
712
 
836 jpm 713
function ajouterTableauTriable(element) {
714
	// add parser through the tablesorter addParser method
715
	$.tablesorter.addParser({
716
		// Définition d'un id unique pour ce parsseur
717
		id: 'date_cel',
718
		is: function(s) {
915 jpm 719
			// doit retourner false si le parsseur n'est pas autodétecté
720
			return /^\s*\d{2}[\/-]\d{2}[\/-]\d{4}\s*$/.test(s);
836 jpm 721
		},
915 jpm 722
		format: function(date) {
836 jpm 723
			// Transformation date jj/mm/aaaa en aaaa/mm/jj
915 jpm 724
			date = date.replace(/^\s*(\d{2})[\/-](\d{2})[\/-](\d{4})\s*$/, "$3/$2/$1");
836 jpm 725
			// Remplace la date par un nombre de millisecondes pour trier numériquement
915 jpm 726
			return $.tablesorter.formatFloat(new Date(date).getTime());
836 jpm 727
		},
728
		// set type, either numeric or text
729
		type: 'numeric'
730
	});
731
	$(element).tablesorter({
732
        headers: {
915 jpm 733
			1: {
734
            	sorter:'date_cel'
735
        	}
736
    	}
737
	});
836 jpm 738
}
739
 
915 jpm 740
function mettreAJourTableauTriable(element) {
741
	$(element).trigger('update');
742
}
743
 
836 jpm 744
function ajouterGaleriePhoto(element) {
745
	$(element).fancybox({
915 jpm 746
		transitionIn:'elastic',
747
		transitionOut:'elastic',
748
		speedIn	:600,
749
		speedOut:200,
750
		overlayShow:true,
751
		titleShow:true,
752
		titlePosition:'inside',
753
		titleFormat:function (titre, currentArray, currentIndex, currentOpts) {
754
			var motif = /urn:lsid:tela-botanica[.]org:cel:img([0-9]+)$/;
755
			motif.exec(titre);
756
			var id = RegExp.$1;
757
			var info = $('#cel-info-'+id).clone().html();
758
			var tpl =
759
				'<div class="cel-legende">'+
760
				'<p class="cel-legende-vei">'+'Image n°' + (currentIndex + 1) + ' sur ' + currentArray.length +'<\/p>'+
761
				(titre && titre.length ? '<p>'+info+'<\/p>' : '' )+
762
				'<\/div>';
763
			return tpl;
836 jpm 764
		}
1032 aurelien 765
	}).live('click', function(e) {
766
		if (e.stopPropagation) {
767
			e.stopPropagation();
768
		}
769
		return false;
770
	});
836 jpm 771
}
772
 
1414 aurelien 773
function ajouterFormulaireContact(element) {
941 jpm 774
	$(element).fancybox({
775
		transitionIn:'elastic',
776
		transitionOut:'elastic',
777
		speedIn	:600,
778
		speedOut:200,
779
		scrolling: 'no',
780
		titleShow: false,
781
		onStart: function(selectedArray, selectedIndex, selectedOpts) {
782
			var element = selectedArray[selectedIndex];
783
 
784
			var motif = / contributeur-([0-9]+)$/;
785
			motif.exec($(element).attr('class'));
786
			var id = RegExp.$1;
950 jpm 787
			//console.log('Destinataire id : '+id);
941 jpm 788
			$("#fc_destinataire_id").attr('value', id);
789
 
790
			var motif = / obs-([0-9]+) /;
791
			motif.exec($(element).attr('class'));
792
			var id = RegExp.$1;
950 jpm 793
			//console.log('Obs id : '+id);
941 jpm 794
			chargerInfoObsPourMessage(id);
795
		},
796
		onCleanup: function() {
950 jpm 797
			//console.log('Avant fermeture fancybox');
941 jpm 798
			$("#fc_destinataire_id").attr('value', '');
799
			$("#fc_sujet").attr('value', '');
800
			$("#fc_message").text('');
801
		},
802
		onClosed: function(e) {
950 jpm 803
			//console.log('Fermeture fancybox');
941 jpm 804
			if (e.stopPropagation) {
805
				e.stopPropagation();
806
			}
807
			return false;
808
		}
809
	});
810
}
811
 
812
function chargerInfoObsPourMessage(idObs) {
980 jpm 813
	var nomSci = jQuery.trim($(".cel-obs-"+idObs+" .nom-sci:eq(0)").text());
814
	var date = jQuery.trim($(".cel-obs-"+idObs+" .date:eq(0)").text());
815
	var lieu = jQuery.trim($(".cel-obs-"+idObs+" .lieu:eq(0)").text());
953 jpm 816
	var sujet = "Observation #"+idObs+" de "+nomSci;
817
	var message = "\n\n\n\n\n\n\n\n--\nConcerne l'observation de \""+nomSci+'" du "'+date+'" au lieu "'+lieu+'".';
941 jpm 818
	$("#fc_sujet").attr('value', sujet);
819
	$("#fc_message").text(message);
820
}
821
 
822
function initialiserFormulaireContact() {
950 jpm 823
	//console.log('Initialisation du form contact');
941 jpm 824
	$("#form-contact").validate({
825
		rules: {
826
			fc_sujet : "required",
827
			fc_message : "required",
953 jpm 828
			fc_utilisateur_courriel : {
829
				required : true,
830
				email : true}
941 jpm 831
		}
832
	});
833
	$("#form-contact").bind("submit", envoyerCourriel);
950 jpm 834
	$("#fc_annuler").bind("click", function() {$.fancybox.close();});
941 jpm 835
 
836
}
837
 
838
function envoyerCourriel() {
950 jpm 839
	//console.log('Formulaire soumis');
941 jpm 840
	if ($("#form-contact").valid()) {
950 jpm 841
		//console.log('Formulaire valide');
941 jpm 842
		//$.fancybox.showActivity();
843
		var destinataireId = $("#fc_destinataire_id").attr('value');
844
		var urlMessage = "http://www.tela-botanica.org/service:annuaire:Utilisateur/"+destinataireId+"/message"
845
		var erreurMsg = "";
846
		var donnees = new Array();
847
		$.each($(this).serializeArray(), function (index, champ) {
848
			var cle = champ.name;
849
			cle = cle.replace(/^fc_/, '');
953 jpm 850
 
980 jpm 851
			if (cle == 'sujet') {
953 jpm 852
				champ.value += " - Carnet en ligne - Tela Botanica";
853
			}
854
			if (cle == 'message') {
855
				champ.value += "\n--\n"+
980 jpm 856
					"Ce message vous est envoyé par l'intermédiaire du widget carto "+
953 jpm 857
					"du Carnet en Ligne du réseau Tela Botanica.\n"+
858
					"http://www.tela-botanica.org/widget:cel:carto";
859
			}
860
 
941 jpm 861
			donnees[index] = {'name':cle,'value':champ.value};
862
		});
863
		$.ajax({
864
			type : "POST",
865
			cache : false,
866
			url : urlMessage,
867
			data : donnees,
868
			beforeSend : function() {
869
				$(".msg").remove();
870
			},
871
			success : function(data) {
872
				$("#fc-zone-dialogue").append('<pre class="msg info">'+data.message+'</pre>');
873
			},
874
			error : function(jqXHR, textStatus, errorThrown) {
875
				erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
876
				reponse = jQuery.parseJSON(jqXHR.responseText);
877
				if (reponse != null) {
878
					$.each(reponse, function (cle, valeur) {
879
						erreurMsg += valeur + "\n";
880
					});
881
				}
882
			},
883
			complete : function(jqXHR, textStatus) {
884
				var debugMsg = '';
885
				if (jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
886
					debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
887
					if (debugInfos != null) {
888
						$.each(debugInfos, function (cle, valeur) {
889
							debugMsg += valeur + "\n";
890
						});
891
					}
892
				}
893
				if (erreurMsg != '') {
894
					$("#fc-zone-dialogue").append('<p class="msg">'+
895
							'Une erreur est survenue lors de la transmission de votre message.'+'<br />'+
896
							'Vous pouvez signaler le disfonctionnement à <a href="'+
897
							'mailto:cel@tela-botanica.org'+'?'+
980 jpm 898
							'subject=Disfonctionnement du widget carto'+
941 jpm 899
							"&body="+erreurMsg+"\nDébogage :\n"+debugMsg+
900
							'">cel@tela-botanica.org</a>.'+
901
							'</p>');
902
				}
903
				if (DEBUG) {
904
					console.log('Débogage : '+debugMsg);
905
				}
950 jpm 906
				//console.log('Débogage : '+debugMsg);
907
				//console.log('Erreur : '+erreurMsg);
941 jpm 908
			}
909
		});
910
	}
911
	return false;
912
}
915 jpm 913
/*+--------------------------------------------------------------------------------------------------------+*/
914
// PANNEAU LATÉRAL
836 jpm 915
 
1438 aurelien 916
function initialiserAffichagePanneauLateral() {
915 jpm 917
	if (nt == '*') {
918
		$('#pl-ouverture').bind('click', afficherPanneauLateral);
919
		$('#pl-fermeture').bind('click', cacherPanneauLateral);
1430 aurelien 920
	} else {
921
		$('#panneau-lateral').width(0);
922
		$('#carte').width('100%');
836 jpm 923
	}
939 jpm 924
	chargerTaxons(0, 0);
836 jpm 925
}
926
 
939 jpm 927
function chargerTaxons(depart, total) {
928
	if (depart == 0 || depart < total) {
929
		var limite = 7000;
950 jpm 930
		//console.log("Chargement des taxons de "+depart+" à "+(depart+limite));
939 jpm 931
		var urlTax = taxonsUrl+'&start={start}&limit='+limite;
932
		urlTax = urlTax.replace(/\{start\}/g, depart);
933
		$.getJSON(urlTax, function(infos) {
934
			taxonsCarte = taxonsCarte.concat(infos.taxons);
950 jpm 935
			//console.log("Nbre taxons :"+taxonsCarte.length);
939 jpm 936
			chargerTaxons(depart+limite, infos.total);
937
		});
938
	} else {
939
		if (nt == '*') {
940
			afficherTaxons();
941
		}
1438 aurelien 942
		afficherTitreCarteEtStats();
939 jpm 943
	}
944
}
945
 
946
function afficherTaxons() {
980 jpm 947
	$(".plantes-nbre").text(taxonsCarte.length);
939 jpm 948
	$("#tpl-taxons-liste").tmpl({'taxons':taxonsCarte}).appendTo("#pl-corps");
949
	$('.taxon').live('click', filtrerParTaxon);
950
}
951
 
952
 
915 jpm 953
function afficherPanneauLateral() {
1438 aurelien 954
	$('#panneau-lateral').height($(window).height());
836 jpm 955
	$('#panneau-lateral').width(300);
956
	$('#pl-contenu').css('display', 'block');
957
	$('#pl-ouverture').css('display', 'none');
958
	$('#pl-fermeture').css('display', 'block');
1438 aurelien 959
	$('#panneau-lateral').css("top","0");
836 jpm 960
 
961
	google.maps.event.trigger(map, 'resize');
962
};
963
 
915 jpm 964
function cacherPanneauLateral() {
1438 aurelien 965
	$('#panneau-lateral').height("60px");
966
	$('#panneau-lateral').width("83px");
836 jpm 967
	$('#pl-contenu').css('display', 'none');
968
	$('#pl-ouverture').css('display', 'block');
969
	$('#pl-fermeture').css('display', 'none');
970
 
971
	google.maps.event.trigger(map, 'resize');
972
};
973
 
974
function filtrerParTaxon() {
975
	var ntAFiltrer = $('.nt', this).text();
976
	infoBulle.close();
1037 aurelien 977
	var zoom = map.getZoom();
978
	var NELatLng = map.getBounds().getNorthEast().lat()+'|'+map.getBounds().getNorthEast().lng();
979
	var SWLatLng = map.getBounds().getSouthWest().lat()+'|'+map.getBounds().getSouthWest().lng();
980
 
836 jpm 981
	$('#taxon-'+nt).removeClass('taxon-actif');
982
	if (nt == ntAFiltrer) {
983
		nt = '*';
1037 aurelien 984
		stationsUrl = stationsUrl.replace(/num_taxon=[*0-9]+/, 'num_taxon='+nt);
985
		chargerMarqueurs(zoom, NELatLng, SWLatLng);
836 jpm 986
	} else {
1035 aurelien 987
		stationsUrl = stationsUrl.replace(/num_taxon=[*0-9]+/, 'num_taxon='+ntAFiltrer);
988
		url = stationsUrl;
989
		url += '&zoom='+zoom+
990
			'&ne='+NELatLng+
991
			'&sw='+SWLatLng;
992
		requeteChargementPoints = $.getJSON(url, function (stationsFiltrees) {
939 jpm 993
			stations = stationsFiltrees;
836 jpm 994
			nt = ntAFiltrer;
995
			$('#taxon-'+nt).addClass('taxon-actif');
1035 aurelien 996
			rafraichirMarqueurs(stations);
836 jpm 997
		});
998
	}
999
};
1000
 
915 jpm 1001
/*+--------------------------------------------------------------------------------------------------------+*/
1002
// FONCTIONS UTILITAIRES
1003
 
980 jpm 1004
function ouvrirPopUp(element, nomPopUp, event) {
1005
	var options =
1006
		'width=650,'+
1007
		'height=600,'+
1008
		'scrollbars=yes,'+
1009
		'directories=no,'+
1010
		'location=no,'+
1011
		'menubar=no,'+
1012
		'status=no,'+
1013
		'toolbar=no';
1014
	var popUp = window.open(element.href, nomPopUp, options);
1015
	if (window.focus) {
1016
		popUp.focus();
1017
	}
1018
	return arreter(event);
1019
};
1020
 
1021
function ouvrirNouvelleFenetre(element, event) {
1022
	window.open(element.href);
1023
	return arreter(event);
1024
}
1025
 
915 jpm 1026
function arreter(event) {
1027
	if (event.stopPropagation) {
1028
		event.stopPropagation();
1029
	} else if (window.event) {
1030
		window.event.cancelBubble = true;
1031
	}
980 jpm 1032
	if (event.preventDefault) {
1033
		event.preventDefault();
1034
	}
1035
	event.returnValue = false;
915 jpm 1036
	return false;
1037
}
1038
 
836 jpm 1039
/**
1040
 * +-------------------------------------+
1041
 * Number.prototype.formaterNombre
1042
 * +-------------------------------------+
1043
 * Params (facultatifs):
1044
 * - Int decimales: nombre de decimales (exemple: 2)
1045
 * - String signe: le signe precedent les decimales (exemple: "," ou ".")
1046
 * - String separateurMilliers: comme son nom l'indique
1047
 * Returns:
1048
 * - String chaine formatee
1049
 * @author	::mastahbenus::
1050
 * @author	Jean-Pascal MILCENT <jpm@tela-botanica.org> : ajout détection auto entier/flotant
1051
 * @souce	http://www.javascriptfr.com/codes/FORMATER-NOMBRE-FACON-NUMBER-FORMAT-PHP_40060.aspx
1052
 */
1053
Number.prototype.formaterNombre = function (decimales, signe, separateurMilliers) {
1054
	var _sNombre = String(this), i, _sRetour = "", _sDecimales = "";
1055
 
1056
	function is_int(nbre) {
1057
		nbre = nbre.replace(',', '.');
1058
		return !(parseFloat(nbre)-parseInt(nbre) > 0);
1059
	}
1060
 
1061
	if (decimales == undefined) {
1062
		if (is_int(_sNombre)) {
1063
			decimales = 0;
1064
		} else {
1065
			decimales = 2;
1066
		}
1067
	}
1068
	if (signe == undefined) {
1069
		if (is_int(_sNombre)) {
1070
			signe = '';
1071
		} else {
1072
			signe = '.';
1073
		}
1074
	}
1075
	if (separateurMilliers == undefined) {
1076
		separateurMilliers = ' ';
1077
	}
1078
 
1079
	function separeMilliers (sNombre) {
1080
		var sRetour = "";
1081
		while (sNombre.length % 3 != 0) {
1082
			sNombre = "0"+sNombre;
1083
		}
1084
		for (i = 0; i < sNombre.length; i += 3) {
1085
			if (i == sNombre.length-1) separateurMilliers = '';
1086
			sRetour += sNombre.substr(i, 3) + separateurMilliers;
1087
		}
1088
		while (sRetour.substr(0, 1) == "0") {
1089
			sRetour = sRetour.substr(1);
1090
		}
1091
		return sRetour.substr(0, sRetour.lastIndexOf(separateurMilliers));
1092
	}
1093
 
1094
	if (_sNombre.indexOf('.') == -1) {
1095
		for (i = 0; i < decimales; i++) {
1096
			_sDecimales += "0";
1097
		}
1098
		_sRetour = separeMilliers(_sNombre) + signe + _sDecimales;
1099
	} else {
1100
		var sDecimalesTmp = (_sNombre.substr(_sNombre.indexOf('.')+1));
1101
		if (sDecimalesTmp.length > decimales) {
1102
			var nDecimalesManquantes = sDecimalesTmp.length - decimales;
1103
			var nDiv = 1;
1104
			for (i = 0; i < nDecimalesManquantes; i++) {
1105
				nDiv *= 10;
1106
			}
1107
			_sDecimales = Math.round(Number(sDecimalesTmp) / nDiv);
1108
		}
1109
		_sRetour = separeMilliers(_sNombre.substr(0, _sNombre.indexOf('.')))+String(signe)+_sDecimales;
1110
	}
1111
	return _sRetour;
915 jpm 1112
}
1113
 
1114
function debug(objet) {
1115
	var msg = '';
1116
	if (objet != null) {
1117
		$.each(objet, function (cle, valeur) {
1118
			msg += cle+":"+valeur + "\n";
1119
		});
1120
	} else {
1121
		msg = "La variable vaut null.";
1122
	}
1123
	console.log(msg);
836 jpm 1124
}