Subversion Repositories eFlore/Applications.cel

Rev

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