Subversion Repositories eFlore/Applications.cel

Rev

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