Subversion Repositories eFlore/Applications.cel

Rev

Rev 841 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*+--------------------------------------------------------------------------------------------------------+*/
// PARAMÊTRES et CONSTANTES
var pointImageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=FFFFFF,008CFF,000000&ext=.png';
var pointsOrigine = null;
var boundsOrigine = null;
var markerClusterer = null;
var map = null;
var infoBulle = new google.maps.InfoWindow();
var pointClique = null;
var carteCentre = new google.maps.LatLng(46.4, 3.10);
var carteOptions = {
        zoom: 6,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControlOptions: {
                mapTypeIds: ['OSM', 
                             google.maps.MapTypeId.ROADMAP, 
                             google.maps.MapTypeId.HYBRID, 
                             google.maps.MapTypeId.SATELLITE, 
                             google.maps.MapTypeId.TERRAIN]
        }
};                      
var ctaLayer = null;
var osmMapType = new google.maps.ImageMapType({
        getTileUrl: function(coord, zoom) {
                return "http://tile.openstreetmap.org/" +
                zoom + "/" + coord.x + "/" + coord.y + ".png";
        },
        tileSize: new google.maps.Size(256, 256),
        isPng: true,
        alt: "OpenStreetMap",
        name: "OSM",
        maxZoom: 19
});

/*+--------------------------------------------------------------------------------------------------------+*/
// INITIALISATION DU CODE


//Déclenchement d'actions quand JQuery et le document HTML sont OK
$(document).ready(function() {
        initialiserWidget();
});
/*+--------------------------------------------------------------------------------------------------------+*/
// FONCTIONS

function initialiserWidget() {
        afficherStats();
        initialiserAffichageCarte();
        initialiserAffichagePanneauLateral();
        
        initialiserCarte();
        initialiserInfoBulle();
        chargerLimitesCommunales();
        rafraichirCarte();
}

function afficherStats() {
        // Ajout du nombre de communes où des observations ont eu lieu
        $('#commune-nbre').append(obs.stats.communes.formaterNombre());
        // Ajout du nombre d'observations
        $('#obs-nbre').append(obs.stats.observations.formaterNombre());
        // Ajout du nombre de plantes
        $('.plantes-nbre').append(plantesNbre.formaterNombre());
}

function initialiserAffichageCarte() {
        $('#carte').height($(window).height() - 35);
        $('#carte').width($(window).width() - 24);
        
        if (nt != '*') {
                $('#carte').css('left', 0);
        }
}

function initialiserAffichagePanneauLateral() {
        $('#panneau-lateral').height($(window).height() - 35);
        
        if (nt == '*') {
                $('#pl-ouverture').bind('click', afficher);
                $('#pl-fermeture').bind('click', cacher);
                $('.taxon').live('click', filtrerParTaxon);
        }
}

function initialiserCarte() {
        map = new google.maps.Map(document.getElementById('carte'), carteOptions);
        // Ajout de la couche OSM à la carte
        map.mapTypes.set('OSM', osmMapType);
}

function initialiserInfoBulle() {
        google.maps.event.addListener(infoBulle, 'domready', modifierContenuInfoBulle);
        google.maps.event.addListener(infoBulle, 'closeclick', deplacerCartePointClique);
}

function chargerLimitesCommunales() {
        if (urlsLimitesCommunales != null) {
                for (urlId in urlsLimitesCommunales) { 
                        var url = urlsLimitesCommunales[urlId];
                        ctaLayer = new google.maps.KmlLayer(url, {preserveViewport: true});
                        ctaLayer.setMap(map);
                }
        }
}

function rafraichirCarte() {
        var points = [];
        var bounds = new google.maps.LatLngBounds();
        for (var i = 0; i < obs.stats.communes; ++i) {
                var maLatLng = new google.maps.LatLng(obs.points[i].coord_x, obs.points[i].coord_y);
                var pointImage = new google.maps.MarkerImage(pointImageUrl, new google.maps.Size(24, 32));
                var point = new google.maps.Marker({
                        position: maLatLng,
                        map: map,
                        icon: pointImage,
                        stationId: obs.points[i].id
                });

                bounds.extend(maLatLng);
                
                google.maps.event.addListener(point, 'click', function() {
                        pointClique =  this;
                        
                        infoBulle.open(map, this);
                        
                        var limites = map.getBounds();
                        var centre = limites.getCenter();
                        var nordEst = limites.getNorthEast();
                        var centreSudLatLng = new google.maps.LatLng(nordEst.lat(), centre.lng());
                        map.panTo(centreSudLatLng);
                        
                        afficherMsgChargement();
                        chargerFormatObs(this.stationId, '*');
                });
                
                points.push(point);
        }

        if (pointsOrigine == null && boundsOrigine == null) {
                pointsOrigine = points;
                boundsOrigine = bounds;
        }
        
        executerMarkerClusterer(points, bounds);
}

function modifierContenuInfoBulle() {
        // Onglet Tableau : Jquery => TableSorter
        if ($("#observations table").get() != '') {
                ajouterTableauTriable("#observations table");
        }
        // Onglet Liste : Jquery => FancyBox
        if ($("#observations ol").get() != '') {
                ajouterGaleriePhoto("a.cel-img");
        }
}

function ajouterTableauTriable(element) {
        // add parser through the tablesorter addParser method 
        $.tablesorter.addParser({ 
                // Définition d'un id unique pour ce parsseur 
                id: 'date_cel', 
                is: function(s) { 
                        // retourne false si le parsseur n'est pas autodétecté 
                        return false; 
                }, 
                format: function(s) { 
                        // Transformation date jj/mm/aaaa en aaaa/mm/jj
                        s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$2/$1");
                        // Remplace la date par un nombre de millisecondes pour trier numériquement
                        return $.tablesorter.formatFloat(new Date(s).getTime());
                }, 
                // set type, either numeric or text 
                type: 'numeric' 
        });
        $(element).tablesorter({ 
        headers: { 
            1: { 
                sorter:'date_cel' 
            } 
        } 
    });
}

function ajouterGaleriePhoto(element) {
        $(element).fancybox({
                transitionIn : 'elastic',
                transitionOut : 'elastic',
                speedIn  : 600, 
                speedOut : 200, 
                overlayShow : true
        }).live('click', function(e) {
                if (e.stopPropagation) {
                        e.stopPropagation();
                }
                return false;
        });
}

function deplacerCartePointClique() {
        map.panTo(pointClique.position);
}

function executerMarkerClusterer(points, bounds) {
        if (markerClusterer) {
                markerClusterer.clearMarkers();
        }
        markerClusterer = new MarkerClusterer(map, points);
        map.fitBounds(bounds);
}

function afficherMsgChargement() {
        var chargement = document.getElementById('chargement').cloneNode(true);
        chargement.setAttribute('id', 'chargement-copie');
        infoBulle.setContent(chargement);
}

function chargerFormatObs(stationId, format) {
        var url = urlObsStation+
                '&format='+format+'&'+
                'station='+stationId;
        $.get(url, function(observations){
                infoBulle.setContent(observations);
        });
}

function arreter(event) {
        if (event.stopPropagation) {
                event.stopPropagation();
        } else if (window.event) {
                window.event.cancelBubble = true;
        }
        return false;
}

function afficher() {
        $('#panneau-lateral').width(300);
        $('#pl-contenu').css('display', 'block');
        $('#pl-ouverture').css('display', 'none');
        $('#pl-fermeture').css('display', 'block');
        $('#carte').css('left', '300px');

        google.maps.event.trigger(map, 'resize');
};

function cacher() {
        $('#panneau-lateral').width(24);
        $('#pl-contenu').css('display', 'none');
        $('#pl-ouverture').css('display', 'block');
        $('#pl-fermeture').css('display', 'none');
        $('#carte').css('left', '24px');
        
        google.maps.event.trigger(map, 'resize');
};

function ouvrirPopUp(url, nom) {
        window.open(url, nom, 'scrollbars=yes,width=650,height=600,directories=no,location=no,menubar=no,status=no,toolbar=no');
};

function filtrerParTaxon() {
        var ntAFiltrer = $('.nt', this).text();
        infoBulle.close();
        $('#taxon-'+nt).removeClass('taxon-actif');
        if (nt == ntAFiltrer) {
                nt = '*';
                executerMarkerClusterer(pointsOrigine, boundsOrigine);
        } else {
                var url = urlObsCarte+'&'+
                        'num_taxon='+ntAFiltrer+'&'+
                        'formatRetour=jsonp'+'&'+
                        'callback=?';
                $.getJSON(url, function (observations) {
                        obs = observations;
                        nt = ntAFiltrer;
                        $('#taxon-'+nt).addClass('taxon-actif');
                        rafraichirCarte();
                });
        }
};

/**
 * +-------------------------------------+
 * Number.prototype.formaterNombre
 * +-------------------------------------+
 * Params (facultatifs):
 * - Int decimales: nombre de decimales (exemple: 2)
 * - String signe: le signe precedent les decimales (exemple: "," ou ".")
 * - String separateurMilliers: comme son nom l'indique
 * Returns:
 * - String chaine formatee
 * @author      ::mastahbenus::
 * @author      Jean-Pascal MILCENT <jpm@tela-botanica.org> : ajout détection auto entier/flotant
 * @souce       http://www.javascriptfr.com/codes/FORMATER-NOMBRE-FACON-NUMBER-FORMAT-PHP_40060.aspx
 */
Number.prototype.formaterNombre = function (decimales, signe, separateurMilliers) {
        var _sNombre = String(this), i, _sRetour = "", _sDecimales = "";
        
        function is_int(nbre) {
                nbre = nbre.replace(',', '.');
                return !(parseFloat(nbre)-parseInt(nbre) > 0);
        }

        if (decimales == undefined) {
                if (is_int(_sNombre)) {
                        decimales = 0;
                } else {
                        decimales = 2;
                }
        }
        if (signe == undefined) {
                if (is_int(_sNombre)) {
                        signe = '';
                } else {
                        signe = '.';
                }
        }
        if (separateurMilliers == undefined) {
                separateurMilliers = ' ';
        }
        
        function separeMilliers (sNombre) {
                var sRetour = "";
                while (sNombre.length % 3 != 0) {
                        sNombre = "0"+sNombre;
                }
                for (i = 0; i < sNombre.length; i += 3) {
                        if (i == sNombre.length-1) separateurMilliers = '';
                        sRetour += sNombre.substr(i, 3) + separateurMilliers;
                }
                while (sRetour.substr(0, 1) == "0") {
                        sRetour = sRetour.substr(1);
                }
                return sRetour.substr(0, sRetour.lastIndexOf(separateurMilliers));
        }
        
        if (_sNombre.indexOf('.') == -1) {
                for (i = 0; i < decimales; i++) {
                        _sDecimales += "0";
                }
                _sRetour = separeMilliers(_sNombre) + signe + _sDecimales;
        } else {
                var sDecimalesTmp = (_sNombre.substr(_sNombre.indexOf('.')+1));
                if (sDecimalesTmp.length > decimales) {
                        var nDecimalesManquantes = sDecimalesTmp.length - decimales;
                        var nDiv = 1;
                        for (i = 0; i < nDecimalesManquantes; i++) {
                                nDiv *= 10;
                        }
                        _sDecimales = Math.round(Number(sDecimalesTmp) / nDiv);
                }
                _sRetour = separeMilliers(_sNombre.substr(0, _sNombre.indexOf('.')))+String(signe)+_sDecimales;
        }
        return _sRetour;
}