Subversion Repositories eFlore/Applications.cel

Rev

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

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