Subversion Repositories eFlore/Applications.cel

Rev

Rev 939 | Rev 950 | 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
4
var DEBUG = true;
836 jpm 5
var pointImageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=FFFFFF,008CFF,000000&ext=.png';
6
var pointsOrigine = null;
7
var boundsOrigine = null;
8
var markerClusterer = null;
9
var map = null;
10
var infoBulle = new google.maps.InfoWindow();
11
var pointClique = null;
12
var carteCentre = new google.maps.LatLng(46.4, 3.10);
13
var carteOptions = {
14
	zoom: 6,
15
	mapTypeId: google.maps.MapTypeId.ROADMAP,
16
	mapTypeControlOptions: {
17
		mapTypeIds: ['OSM',
18
		             google.maps.MapTypeId.ROADMAP,
19
		             google.maps.MapTypeId.HYBRID,
20
		             google.maps.MapTypeId.SATELLITE,
21
		             google.maps.MapTypeId.TERRAIN]
22
	}
23
};
24
var ctaLayer = null;
25
var osmMapType = new google.maps.ImageMapType({
26
	getTileUrl: function(coord, zoom) {
27
		return "http://tile.openstreetmap.org/" +
28
		zoom + "/" + coord.x + "/" + coord.y + ".png";
29
	},
30
	tileSize: new google.maps.Size(256, 256),
31
	isPng: true,
32
	alt: "OpenStreetMap",
33
	name: "OSM",
34
	maxZoom: 19
35
});
915 jpm 36
var pagineur = {'limite':50, 'start':0, 'total':0, 'stationId':null, 'format':'tableau'};
37
var station = {'commune':'', 'obsNbre':0};
38
var obsStation = new Array();
39
var obsPage = new Array();
939 jpm 40
var taxonsCarte = new Array();
836 jpm 41
/*+--------------------------------------------------------------------------------------------------------+*/
42
// INITIALISATION DU CODE
43
 
44
//Déclenchement d'actions quand JQuery et le document HTML sont OK
45
$(document).ready(function() {
46
	initialiserWidget();
47
});
48
 
49
function initialiserWidget() {
50
	afficherStats();
51
	initialiserAffichageCarte();
52
	initialiserAffichagePanneauLateral();
53
 
54
	initialiserCarte();
55
	initialiserInfoBulle();
941 jpm 56
	initialiserFormulaireContact();
836 jpm 57
	chargerLimitesCommunales();
58
	rafraichirCarte();
59
}
60
 
915 jpm 61
/*+--------------------------------------------------------------------------------------------------------+*/
62
// AFFICHAGE GÉNÉRAL
63
 
836 jpm 64
function afficherStats() {
65
	// Ajout du nombre de communes où des observations ont eu lieu
939 jpm 66
	$('#commune-nbre').text(stations.stats.communes.formaterNombre());
836 jpm 67
	// Ajout du nombre d'observations
939 jpm 68
	$('#obs-nbre').text(stations.stats.observations.formaterNombre());
836 jpm 69
}
70
 
915 jpm 71
/*+--------------------------------------------------------------------------------------------------------+*/
72
// CARTE
73
 
836 jpm 74
function initialiserAffichageCarte() {
75
	$('#carte').height($(window).height() - 35);
76
	$('#carte').width($(window).width() - 24);
77
 
78
	if (nt != '*') {
79
		$('#carte').css('left', 0);
80
	}
81
}
82
 
83
function initialiserCarte() {
84
	map = new google.maps.Map(document.getElementById('carte'), carteOptions);
85
	// Ajout de la couche OSM à la carte
86
	map.mapTypes.set('OSM', osmMapType);
87
}
88
 
89
 
90
function chargerLimitesCommunales() {
91
	if (urlsLimitesCommunales != null) {
92
		for (urlId in urlsLimitesCommunales) {
93
			var url = urlsLimitesCommunales[urlId];
94
			ctaLayer = new google.maps.KmlLayer(url, {preserveViewport: true});
95
			ctaLayer.setMap(map);
96
		}
97
	}
98
}
99
 
100
function rafraichirCarte() {
101
	var points = [];
102
	var bounds = new google.maps.LatLngBounds();
939 jpm 103
	for (var i = 0; i < stations.stats.communes; ++i) {
104
		var maLatLng = new google.maps.LatLng(stations.points[i].coord_x, stations.points[i].coord_y);
836 jpm 105
		var pointImage = new google.maps.MarkerImage(pointImageUrl, new google.maps.Size(24, 32));
106
		var point = new google.maps.Marker({
107
			position: maLatLng,
108
			map: map,
109
			icon: pointImage,
939 jpm 110
			stationId: stations.points[i].id
836 jpm 111
		});
112
 
113
		bounds.extend(maLatLng);
114
 
115
		google.maps.event.addListener(point, 'click', function() {
116
			pointClique =  this;
117
			infoBulle.open(map, this);
118
 
119
			var limites = map.getBounds();
120
			var centre = limites.getCenter();
121
			var nordEst = limites.getNorthEast();
122
			var centreSudLatLng = new google.maps.LatLng(nordEst.lat(), centre.lng());
123
			map.panTo(centreSudLatLng);
124
 
915 jpm 125
			afficherInfoBulle();
939 jpm 126
			chargerObs(0, 0);
836 jpm 127
		});
128
 
129
		points.push(point);
130
	}
131
 
132
	if (pointsOrigine == null && boundsOrigine == null) {
133
		pointsOrigine = points;
134
		boundsOrigine = bounds;
135
	}
136
 
137
	executerMarkerClusterer(points, bounds);
138
}
139
 
915 jpm 140
function deplacerCartePointClique() {
141
	map.panTo(pointClique.position);
142
}
143
 
144
function executerMarkerClusterer(points, bounds) {
145
	if (markerClusterer) {
146
		markerClusterer.clearMarkers();
836 jpm 147
	}
915 jpm 148
	markerClusterer = new MarkerClusterer(map, points);
149
	map.fitBounds(bounds);
150
}
151
 
152
/*+--------------------------------------------------------------------------------------------------------+*/
153
// INFO BULLE
154
 
155
function initialiserInfoBulle() {
156
	google.maps.event.addListener(infoBulle, 'domready', initialiserContenuInfoBulle);
157
	google.maps.event.addListener(infoBulle, 'closeclick', deplacerCartePointClique);
158
}
159
 
160
function afficherInfoBulle() {
161
	var obsHtml = $("#tpl-obs").html();
162
	infoBulle.setContent(obsHtml);
163
}
164
 
165
function afficherMessageChargement(element) {
166
	if ($('#chargement').get() == '') {
167
		$('#tpl-chargement').tmpl().appendTo(element);
168
	}
169
}
170
 
171
function supprimerMessageChargement() {
172
	$('#chargement').remove();
173
}
174
 
175
function chargerObs(depart, total) {
939 jpm 176
	if (depart == 0 || depart < total) {
915 jpm 177
		var limite = 300;
178
		if (depart == 0) {
179
			obsStation = new Array();
180
		}
181
		console.log("Chargement de "+depart+" à "+(depart+limite));
939 jpm 182
		var urlObs = observationsUrl+'&start={start}&limit='+limite;
915 jpm 183
		urlObs = urlObs.replace(/\{stationId\}/g, pointClique.stationId);
939 jpm 184
		urlObs = urlObs.replace(/\{nt\}/g, nt);
915 jpm 185
		urlObs = urlObs.replace(/\{start\}/g, depart);
186
 
187
		$.getJSON(urlObs, function(observations){
188
			obsStation = obsStation.concat(observations.observations);
939 jpm 189
			if (depart == 0) {
190
				actualiserInfosStation(observations);
191
				actualiserPagineur();
192
				creerTitreInfoBulle();
193
			}
915 jpm 194
			console.log("Chargement ok");
939 jpm 195
			chargerObs(depart+limite, station.obsNbre);
915 jpm 196
		});
197
	} else {
198
		if (pagineur.limite < total) {
199
			afficherPagination();
200
		} else {
201
			surClicPagePagination(0, null);
939 jpm 202
			selectionnerOnglet("#obs-vue-"+pagineur.format);
915 jpm 203
		}
204
	}
205
}
206
 
939 jpm 207
function actualiserInfosStation(infos) {
208
	station.commune = infos.commune;
209
	station.obsNbre = infos.total;
210
}
915 jpm 211
 
939 jpm 212
function actualiserPagineur() {
213
	pagineur.stationId = pointClique.stationId;
214
	pagineur.total = station.obsNbre;
215
	console.log("Total pagineur: "+pagineur.total);
216
	if (pagineur.total > 4) {
217
		pagineur.format = 'tableau';
218
	} else {
219
		pagineur.format = 'liste';
220
	}
221
}
222
 
915 jpm 223
function afficherPagination(observations) {
224
	$(".navigation").pagination(pagineur.total, {
225
		items_per_page:pagineur.limite,
226
		callback:surClicPagePagination,
227
		next_text:'Suivant',
228
		prev_text:'Précédent',
229
		prev_show_always:false,
230
		num_edge_entries:1,
231
		num_display_entries:5,
232
		load_first_page:true
233
	});
234
}
235
 
236
function surClicPagePagination(pageIndex, paginationConteneur) {
237
	var index = pageIndex * pagineur.limite;
238
	var indexMax = index + pagineur.limite;
239
	pagineur.depart = index;
240
	obsPage = new Array();
241
    for(index; index < indexMax; index++) {
242
    	obsPage.push(obsStation[index]);
243
    }
244
 
245
    supprimerMessageChargement();
246
    mettreAJourObservations();
247
	return false;
248
}
249
 
250
function mettreAJourObservations() {
251
	$("#obs-"+pagineur.format+"-lignes").empty();
252
   	$("#obs-vue-"+pagineur.format).css('display', 'block');
253
   	$(".obs-conteneur").css('counter-reset', 'item '+pagineur.depart);
254
	$("#tpl-obs-"+pagineur.format).tmpl(obsPage).appendTo("#obs-"+pagineur.format+"-lignes");
255
 
256
	// Actualisation de Fancybox
941 jpm 257
	ajouterFomulaireContact("a.contact");
915 jpm 258
	if (pagineur.format == 'liste') {
836 jpm 259
		ajouterGaleriePhoto("a.cel-img");
260
	}
261
}
262
 
915 jpm 263
function creerTitreInfoBulle() {
264
	$("#obs-total").append(station.obsNbre);
265
	$("#obs-commune").append(station.commune);
266
}
267
 
268
function initialiserContenuInfoBulle() {
269
	afficherOnglets();
270
	afficherMessageChargement('#observations');
271
	ajouterTableauTriable("#obs-tableau");
272
	afficherTextStationId();
273
	corrigerLargeurInfoWindow();
274
}
275
 
276
function afficherOnglets() {
277
	var $tabs = $('#obs').tabs();
278
	$('#obs').bind('tabsselect', function(event, ui) {
279
		if (ui.panel.id == 'obs-vue-tableau') {
280
			surClicAffichageTableau();
281
		} else if (ui.panel.id == 'obs-vue-liste') {
282
			surClicAffichageListe();
283
		}
284
	});
285
	$tabs.tabs('select', "#obs-vue-"+pagineur.format);
286
}
287
 
939 jpm 288
function selectionnerOnglet(onglet) {
289
	$('#obs').tabs('select', onglet);
290
}
291
 
915 jpm 292
function afficherTextStationId() {
293
	$('#obs-station-id').text(pointClique.stationId);
294
}
295
 
296
function corrigerLargeurInfoWindow() {
297
	$("#info-bulle").width($("#info-bulle").width() - 16);
298
}
299
 
300
function surClicAffichageTableau(event) {
301
	console.log('tableau');
302
	pagineur.format = 'tableau';
303
	mettreAJourObservations();
304
	mettreAJourTableauTriable("#obs-tableau");
305
}
306
 
307
function surClicAffichageListe(event) {
308
	console.log('liste');
309
	pagineur.format = 'liste';
310
	mettreAJourObservations();
311
	ajouterGaleriePhoto("a.cel-img");
312
}
313
 
836 jpm 314
function ajouterTableauTriable(element) {
315
	// add parser through the tablesorter addParser method
316
	$.tablesorter.addParser({
317
		// Définition d'un id unique pour ce parsseur
318
		id: 'date_cel',
319
		is: function(s) {
915 jpm 320
			// doit retourner false si le parsseur n'est pas autodétecté
321
			return /^\s*\d{2}[\/-]\d{2}[\/-]\d{4}\s*$/.test(s);
836 jpm 322
		},
915 jpm 323
		format: function(date) {
836 jpm 324
			// Transformation date jj/mm/aaaa en aaaa/mm/jj
915 jpm 325
			date = date.replace(/^\s*(\d{2})[\/-](\d{2})[\/-](\d{4})\s*$/, "$3/$2/$1");
836 jpm 326
			// Remplace la date par un nombre de millisecondes pour trier numériquement
915 jpm 327
			return $.tablesorter.formatFloat(new Date(date).getTime());
836 jpm 328
		},
329
		// set type, either numeric or text
330
		type: 'numeric'
331
	});
332
	$(element).tablesorter({
333
        headers: {
915 jpm 334
			1: {
335
            	sorter:'date_cel'
336
        	}
337
    	}
338
	});
836 jpm 339
}
340
 
915 jpm 341
function mettreAJourTableauTriable(element) {
342
	$(element).trigger('update');
343
}
344
 
836 jpm 345
function ajouterGaleriePhoto(element) {
346
	$(element).fancybox({
915 jpm 347
		transitionIn:'elastic',
348
		transitionOut:'elastic',
349
		speedIn	:600,
350
		speedOut:200,
351
		overlayShow:true,
352
		titleShow:true,
353
		titlePosition:'inside',
354
		titleFormat:function (titre, currentArray, currentIndex, currentOpts) {
355
			var motif = /urn:lsid:tela-botanica[.]org:cel:img([0-9]+)$/;
356
			motif.exec(titre);
357
			var id = RegExp.$1;
358
			var info = $('#cel-info-'+id).clone().html();
359
			var tpl =
360
				'<div class="cel-legende">'+
361
				'<p class="cel-legende-vei">'+'Image n°' + (currentIndex + 1) + ' sur ' + currentArray.length +'<\/p>'+
362
				(titre && titre.length ? '<p>'+info+'<\/p>' : '' )+
363
				'<\/div>';
364
			return tpl;
836 jpm 365
		}
915 jpm 366
		}).live('click', function(e) {
367
			if (e.stopPropagation) {
368
				e.stopPropagation();
369
			}
370
			return false;
371
		});
836 jpm 372
}
373
 
941 jpm 374
function ajouterFomulaireContact(element) {
375
	$(element).fancybox({
376
		transitionIn:'elastic',
377
		transitionOut:'elastic',
378
		speedIn	:600,
379
		speedOut:200,
380
		scrolling: 'no',
381
		titleShow: false,
382
		onStart: function(selectedArray, selectedIndex, selectedOpts) {
383
			var element = selectedArray[selectedIndex];
384
 
385
			var motif = / contributeur-([0-9]+)$/;
386
			motif.exec($(element).attr('class'));
387
			var id = RegExp.$1;
388
			console.log('Destinataire id : '+id);
389
			$("#fc_destinataire_id").attr('value', id);
390
 
391
			var motif = / obs-([0-9]+) /;
392
			motif.exec($(element).attr('class'));
393
			var id = RegExp.$1;
394
			console.log('Obs id : '+id);
395
			chargerInfoObsPourMessage(id);
396
		},
397
		onCleanup: function() {
398
			console.log('Avant fermeture fancybox');
399
			$("#fc_destinataire_id").attr('value', '');
400
			$("#fc_sujet").attr('value', '');
401
			$("#fc_message").text('');
402
		},
403
		onClosed: function(e) {
404
			console.log('Fermeture fancybox');
405
			if (e.stopPropagation) {
406
				e.stopPropagation();
407
			}
408
			return false;
409
		}
410
	});
411
}
412
 
413
function chargerInfoObsPourMessage(idObs) {
414
	var sujet = "Remarque sur l'observation #"+idObs;
415
	var message = "--\nConcerne l'observation de "+
416
		' "'+trim($("#cel-obs-"+idObs+" .nom-sci").text())+'" '+
417
		'du "'+trim($("#cel-obs-"+idObs+" .date").text())+'" '+
418
		'au lieu "'+trim($("#cel-obs-"+idObs+" .lieu").text())+'".';
419
	$("#fc_sujet").attr('value', sujet);
420
	$("#fc_message").text(message);
421
}
422
 
423
function initialiserFormulaireContact() {
424
	console.log('Initialisation du form contact');
425
	$("#form-contact").validate({
426
		rules: {
427
			fc_sujet : "required",
428
			fc_message : "required",
429
			fc_courriel : {
430
			required : true,
431
			email : true}
432
		}
433
	});
434
	$("#form-contact").bind("submit", envoyerCourriel);
435
	$("#fc_annuler").bind("click", function() {console.log('clic annuler');$.fancybox.close();});
436
 
437
}
438
 
439
function envoyerCourriel() {
440
	console.log('Formulaire soumis');
441
	if ($("#form-contact").valid()) {
442
		console.log('Formulaire valide');
443
		//$.fancybox.showActivity();
444
		var destinataireId = $("#fc_destinataire_id").attr('value');
445
		var urlMessage = "http://www.tela-botanica.org/service:annuaire:Utilisateur/"+destinataireId+"/message"
446
		var erreurMsg = "";
447
		var donnees = new Array();
448
		$.each($(this).serializeArray(), function (index, champ) {
449
			var cle = champ.name;
450
			cle = cle.replace(/^fc_/, '');
451
			console.log('Clé:'+cle);
452
			donnees[index] = {'name':cle,'value':champ.value};
453
		});
454
		$.ajax({
455
			type : "POST",
456
			cache : false,
457
			url : urlMessage,
458
			data : donnees,
459
			beforeSend : function() {
460
				$(".msg").remove();
461
			},
462
			success : function(data) {
463
				$("#fc-zone-dialogue").append('<pre class="msg info">'+data.message+'</pre>');
464
			},
465
			error : function(jqXHR, textStatus, errorThrown) {
466
				erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
467
				reponse = jQuery.parseJSON(jqXHR.responseText);
468
				if (reponse != null) {
469
					$.each(reponse, function (cle, valeur) {
470
						erreurMsg += valeur + "\n";
471
					});
472
				}
473
			},
474
			complete : function(jqXHR, textStatus) {
475
				var debugMsg = '';
476
				if (jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
477
					debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
478
					if (debugInfos != null) {
479
						$.each(debugInfos, function (cle, valeur) {
480
							debugMsg += valeur + "\n";
481
						});
482
					}
483
				}
484
				if (erreurMsg != '') {
485
					$("#fc-zone-dialogue").append('<p class="msg">'+
486
							'Une erreur est survenue lors de la transmission de votre message.'+'<br />'+
487
							'Vous pouvez signaler le disfonctionnement à <a href="'+
488
							'mailto:cel@tela-botanica.org'+'?'+
489
							'subject=Disfonctionnement du widget de Cartographie'+
490
							"&body="+erreurMsg+"\nDébogage :\n"+debugMsg+
491
							'">cel@tela-botanica.org</a>.'+
492
							'</p>');
493
				}
494
				if (DEBUG) {
495
					console.log('Débogage : '+debugMsg);
496
				}
497
				console.log('Débogage : '+debugMsg);
498
				console.log('Erreur : '+erreurMsg);
499
			}
500
		});
501
	}
502
	return false;
503
}
915 jpm 504
/*+--------------------------------------------------------------------------------------------------------+*/
505
// PANNEAU LATÉRAL
836 jpm 506
 
915 jpm 507
function initialiserAffichagePanneauLateral() {
508
	$('#panneau-lateral').height($(window).height() - 35);
841 jpm 509
 
915 jpm 510
	if (nt == '*') {
511
		$('#pl-ouverture').bind('click', afficherPanneauLateral);
512
		$('#pl-fermeture').bind('click', cacherPanneauLateral);
836 jpm 513
	}
939 jpm 514
	chargerTaxons(0, 0);
836 jpm 515
}
516
 
939 jpm 517
function chargerTaxons(depart, total) {
518
	if (depart == 0 || depart < total) {
519
		var limite = 7000;
520
		console.log("Chargement des taxons de "+depart+" à "+(depart+limite));
521
		var urlTax = taxonsUrl+'&start={start}&limit='+limite;
522
		urlTax = urlTax.replace(/\{start\}/g, depart);
523
		$.getJSON(urlTax, function(infos) {
524
			taxonsCarte = taxonsCarte.concat(infos.taxons);
525
			console.log("Nbre taxons :"+taxonsCarte.length);
526
			chargerTaxons(depart+limite, infos.total);
527
		});
528
	} else {
529
		if (nt == '*') {
530
			afficherTaxons();
531
		} else {
532
			afficherNomPlante();
533
		}
534
	}
535
}
536
 
537
function afficherTaxons() {
538
	// Ajout du nombre de plantes au titre
539
	$('.plantes-nbre').text(taxonsCarte.length.formaterNombre());
540
 
541
	$("#tpl-taxons-liste").tmpl({'taxons':taxonsCarte}).appendTo("#pl-corps");
542
	$('.taxon').live('click', filtrerParTaxon);
543
}
544
 
545
function afficherNomPlante() {
546
	if (nt != '*') {
547
		var taxon = taxonsCarte[0];
548
		$('.plante-titre').text('pour '+taxon.nom);
549
	}
550
}
551
 
915 jpm 552
function afficherPanneauLateral() {
836 jpm 553
	$('#panneau-lateral').width(300);
554
	$('#pl-contenu').css('display', 'block');
555
	$('#pl-ouverture').css('display', 'none');
556
	$('#pl-fermeture').css('display', 'block');
557
	$('#carte').css('left', '300px');
558
 
559
	google.maps.event.trigger(map, 'resize');
560
};
561
 
915 jpm 562
function cacherPanneauLateral() {
836 jpm 563
	$('#panneau-lateral').width(24);
564
	$('#pl-contenu').css('display', 'none');
565
	$('#pl-ouverture').css('display', 'block');
566
	$('#pl-fermeture').css('display', 'none');
567
	$('#carte').css('left', '24px');
568
 
569
	google.maps.event.trigger(map, 'resize');
570
};
571
 
572
function ouvrirPopUp(url, nom) {
573
	window.open(url, nom, 'scrollbars=yes,width=650,height=600,directories=no,location=no,menubar=no,status=no,toolbar=no');
574
};
575
 
576
function filtrerParTaxon() {
577
	var ntAFiltrer = $('.nt', this).text();
578
	infoBulle.close();
579
	$('#taxon-'+nt).removeClass('taxon-actif');
580
	if (nt == ntAFiltrer) {
581
		nt = '*';
582
		executerMarkerClusterer(pointsOrigine, boundsOrigine);
583
	} else {
939 jpm 584
		var url = stationsUrl+'&'+
836 jpm 585
			'num_taxon='+ntAFiltrer+'&'+
939 jpm 586
			'formatRetour=jsonP'+'&'+
836 jpm 587
			'callback=?';
939 jpm 588
		$.getJSON(url, function (stationsFiltrees) {
589
			stations = stationsFiltrees;
836 jpm 590
			nt = ntAFiltrer;
591
			$('#taxon-'+nt).addClass('taxon-actif');
592
			rafraichirCarte();
593
		});
594
	}
595
};
596
 
915 jpm 597
/*+--------------------------------------------------------------------------------------------------------+*/
598
// FONCTIONS UTILITAIRES
599
 
600
function arreter(event) {
601
	if (event.stopPropagation) {
602
		event.stopPropagation();
603
	} else if (window.event) {
604
		window.event.cancelBubble = true;
605
	}
606
	return false;
607
}
608
 
836 jpm 609
/**
610
 * +-------------------------------------+
611
 * Number.prototype.formaterNombre
612
 * +-------------------------------------+
613
 * Params (facultatifs):
614
 * - Int decimales: nombre de decimales (exemple: 2)
615
 * - String signe: le signe precedent les decimales (exemple: "," ou ".")
616
 * - String separateurMilliers: comme son nom l'indique
617
 * Returns:
618
 * - String chaine formatee
619
 * @author	::mastahbenus::
620
 * @author	Jean-Pascal MILCENT <jpm@tela-botanica.org> : ajout détection auto entier/flotant
621
 * @souce	http://www.javascriptfr.com/codes/FORMATER-NOMBRE-FACON-NUMBER-FORMAT-PHP_40060.aspx
622
 */
623
Number.prototype.formaterNombre = function (decimales, signe, separateurMilliers) {
624
	var _sNombre = String(this), i, _sRetour = "", _sDecimales = "";
625
 
626
	function is_int(nbre) {
627
		nbre = nbre.replace(',', '.');
628
		return !(parseFloat(nbre)-parseInt(nbre) > 0);
629
	}
630
 
631
	if (decimales == undefined) {
632
		if (is_int(_sNombre)) {
633
			decimales = 0;
634
		} else {
635
			decimales = 2;
636
		}
637
	}
638
	if (signe == undefined) {
639
		if (is_int(_sNombre)) {
640
			signe = '';
641
		} else {
642
			signe = '.';
643
		}
644
	}
645
	if (separateurMilliers == undefined) {
646
		separateurMilliers = ' ';
647
	}
648
 
649
	function separeMilliers (sNombre) {
650
		var sRetour = "";
651
		while (sNombre.length % 3 != 0) {
652
			sNombre = "0"+sNombre;
653
		}
654
		for (i = 0; i < sNombre.length; i += 3) {
655
			if (i == sNombre.length-1) separateurMilliers = '';
656
			sRetour += sNombre.substr(i, 3) + separateurMilliers;
657
		}
658
		while (sRetour.substr(0, 1) == "0") {
659
			sRetour = sRetour.substr(1);
660
		}
661
		return sRetour.substr(0, sRetour.lastIndexOf(separateurMilliers));
662
	}
663
 
664
	if (_sNombre.indexOf('.') == -1) {
665
		for (i = 0; i < decimales; i++) {
666
			_sDecimales += "0";
667
		}
668
		_sRetour = separeMilliers(_sNombre) + signe + _sDecimales;
669
	} else {
670
		var sDecimalesTmp = (_sNombre.substr(_sNombre.indexOf('.')+1));
671
		if (sDecimalesTmp.length > decimales) {
672
			var nDecimalesManquantes = sDecimalesTmp.length - decimales;
673
			var nDiv = 1;
674
			for (i = 0; i < nDecimalesManquantes; i++) {
675
				nDiv *= 10;
676
			}
677
			_sDecimales = Math.round(Number(sDecimalesTmp) / nDiv);
678
		}
679
		_sRetour = separeMilliers(_sNombre.substr(0, _sNombre.indexOf('.')))+String(signe)+_sDecimales;
680
	}
681
	return _sRetour;
915 jpm 682
}
683
 
684
function debug(objet) {
685
	var msg = '';
686
	if (objet != null) {
687
		$.each(objet, function (cle, valeur) {
688
			msg += cle+":"+valeur + "\n";
689
		});
690
	} else {
691
		msg = "La variable vaut null.";
692
	}
693
	console.log(msg);
941 jpm 694
}
695
 
696
function trim (chaine) {
697
	return chaine.replace(/^\s+/g, '').replace(/\s+$/g, '');
836 jpm 698
}