Subversion Repositories eFlore/Applications.cel

Rev

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