Subversion Repositories eFlore/Applications.cel

Rev

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