Subversion Repositories eFlore/Applications.eflore-consultation

Rev

Rev 1301 | Blame | Compare with Previous | Last modification | View Log | RSS feed

/**-------------------------- Objets globaux -----------------------------------*/
/*
 * Les variables suivantes sont ajoutée automatiquement dans le squelette du moteur de
 * recherche par php, elles sont commentées ici pour qu'elles n'aient pas l'air 
 * de sortir de la cuisse de Jupiter
 * 
 * var AUTOCOMPLETION_ELEMENTS_NBRE : indique le nombre d'éléments à afficher dans la liste d'autocomplétion.
 * 
 * var URL_SERVICE_AUTOCOMPLETION_NOM_SCI : url de base du service de complétion de noms scientifiques
 * pour le projet en cours de consultation. 
 * Exemple : http://localhost/service:eflore:0.1/bdtfx/noms?recherche=etendue&retour.format=min&masque=Ace%mo
 * 
 * var URL_SERVICE_AUTOCOMPLETION_NOM_VERNA : url de base du service de complétion de noms vernaculaires
 * pour le projet en cours de consultation. 
 * Exemple : http://localhost/service:eflore:0.1/nvjfl/noms-vernaculaires?recherche=etendue&retour.format=oss&masque=aca&masque.lg=fra 
 * 
 * var VALEUR_DEFAUT_NOM_SCI : Contient la valeur par défaut affichée dans le formulaire en mode sci
 * Exemple: Rechercher un nom scientifique
 * 
 * var VALEUR_DEFAUT_NOM_VERNA : Contient la valeur par défaut affichée dans le formulaire en mode verna
 * Exemple: Recherche un nom commun
 * 
 * var URL_BASE_POPUP : url de base pour les popup contenant du code un peu complexe
 */

var champs_ts = ["#au","#and","#anf","#nom","#bib"];
var autocompletionFicheOuverte = false;
var elementAutocompletionSelectionne = null;
var nomRechercheEnCours = null;

$(document).ready(function() {
        initialiserMoteur();
});

function initialiserMoteur() {
        ajouterAutocompletion();
        gererAffichageValeursParDefaut();
        gererAccesFicheFlecheDroite();
        gererClicIllustrationsResultats();
        gererAccesFicheBouton();
}

/**------------------- Fonctions de gestion de l'autocompletion ---------------------------------*/
function ajouterAutocompletion(){
        ajouterAutocompletionNoms();
        $('.champ_autocomplete').each(function(index) {
                ajouterAutocompletionAvancee($(this));
        });
}

function ajouterAutocompletionAvancee(champs){
        champs.autocomplete({                   
                source: function(requete, add){  
                // la variable de requête doit être vidée car sinon le parametre "term" est ajouté
                        requete = "";
                        var id = champs.attr('id');
                        var url = encodeURI(getUrlAutocompletionAvancee(id));
                                $.getJSON(url, requete, function(data) { 
                        var suggestions = [];
                        suggestions = traiterRetourAvance(data,champs);
                        add(suggestions);  
                        });
                },
        html: true
        });
}

function ajouterAutocompletionNoms() {
        $('#nom').autocomplete({
                source: function(requete, add){  
                        // la variable de requête doit être vidée car sinon le parametre "term" est ajouté
                        requete = "";
                        var url = encodeURI(getUrlAppelCompletion());
                        $.getJSON(url, requete, function(data) {
                                var suggestions = [];
                                if (nomVernaculaireEstDemande()) {
                                        suggestions = traiterRetourNomsVerna(data);
                                } else if (nomSciEstDemande()) {
                                        suggestions = traiterRetourNomsSci(data);
                                }
                                add(suggestions);  
            });
        },
        search: function(event, ui) {
                nomRechercheEnCours = 'nom_sci';
        },
        focus: function(event, ui) {
                elementAutocompletionSelectionne = ui.item;
        },
        open: function(event, ui) { 
                autocompletionFicheOuverte = true;
                var parent = $('.autocompletion_nom.ui-menu-item').parent();
                parent.width(parent.width() + 10);
        },
        close: function(event, ui) {
                autocompletionFicheFermee = false;
                nomRechercheEnCours = null;
        },
        html: true
        });
        
        $("#nom").bind("autocompleteselect", function(event, ui) {
                if (ui.item.retenu == true) {
                        $("#nom").addClass('ns-retenu');
                } else {
                        $("#nom").removeClass('ns-retenu');
                }
        });
}

// gére l'acces direct à une fiche par l'appui sur droite
// dans la liste d'autocompletion des noms scientifiques
function gererAccesFicheFlecheDroite() {
        $(document).keypress(function(event) {
                // flèche droite
                if(event.keyCode == 39) {
                        if(autocompletionFicheOuverte && elementAutocompletionSelectionne != null && nomSciEstDemande()) {
                                $('#nom').val(elementAutocompletionSelectionne.value);
                                if(elementAutocompletionSelectionne.nn != undefined && elementAutocompletionSelectionne.nn != null) {
                                        var url_fiche_taxon = URL_BASE_FICHE_TAXON.replace('{num_taxon}',elementAutocompletionSelectionne.nn);
                                        window.location.href = url_fiche_taxon; 
                                }
                                $('#nom').autocomplete( "disable" );
                                //TODO : ajout d'un message de chargement ?
                        }
                }
                
                if(event.keyCode == 13) {
                        if(autocompletionFicheOuverte && elementAutocompletionSelectionne == null && $('#nom').is(":focus")) {
                                $('#eflore_nomenclature_submit').click();
                        }
                }
        });
}

function gererAccesFicheBouton() {
        $('#eflore_nomenclature_fiche').click(function(event) {
                if(elementAutocompletionSelectionne != null && nomSciEstDemande()) {
                        $('#nom').val(elementAutocompletionSelectionne.value);
                        if(elementAutocompletionSelectionne.nn != undefined && elementAutocompletionSelectionne.nn != null) {
                                var url_fiche_taxon = URL_BASE_FICHE_TAXON.replace('{num_taxon}',elementAutocompletionSelectionne.nn);
                                window.location.href = url_fiche_taxon; 
                        }
                        event.preventDefault();
                }
        });
}

function traiterRetourNomsSci(data) {
        var suggestions = [];  
        if (data.resultat != undefined) {
                $.each(data.resultat, function(i, val) {
                        val.nn = i;
                        var nom = {label : '', value : '', retenu : false};
                        if (suggestions.length >= AUTOCOMPLETION_ELEMENTS_NBRE) {
                                nom.label = "...";
                                nom.value = $('#nom').val();
                                suggestions.push(nom);
                                return false;
                        } else {
                                nom.label = val.nom_sci_complet;
                                nom.value = val.nom_sci;
                                nom.nn = val.nn;
                                if(val.retenu != "absent") {
                                        nom.retenu = (val.retenu == 'true') ? true : false;
                                        suggestions.push(nom);
                                }
                        }
                });
        }
        return suggestions;
}


function traiterRetourAvance(data, champs) {
        var suggestions = [];  
        if (jQuery.type(data) == "array") { 
                $.each(data[1], function(i, val) {
                        var ch = {label : '', value : ''};
                        if (suggestions.length >= AUTOCOMPLETION_ELEMENTS_NBRE) {
                                ch.label = "...";
                                ch.value = champs.val();
                                suggestions.push(ch);
                                return false;
                        } else {
                                ch.label = val;
                                ch.value = val;
                                suggestions.push(ch);
                        }
                });
        }
        return suggestions;
}

function traiterRetourNomsVerna(data) {
        var suggestions = [];
        if (jQuery.type(data) == "array") {
                $.each(data[1], function(i, val){
                        var nom = {label : '', value : ''};
                        if (suggestions.length >= AUTOCOMPLETION_ELEMENTS_NBRE) {
                                nom.label = "...";
                                nom.value = $('#nom').val();
                                suggestions.push(nom);
                                return false;
                        } else {
                                nom.label = val;
                                nom.value = val;
                                suggestions.push(val);
                        }
                });
        }
        return suggestions;
}


/**------------ Fonctions de gestion des urls d'autocompletion et des fiches ------------------*/

function getUrlAutocompletionAvancee(parametre) {
        var valeur = getValeurMasque(parametre);
        var ns_str = getValeurNsStructure(parametre);
        var url = URL_SERVICE_AUTOCOMPLETION_NOM_SCI+"?recherche=etendue&"+
        "navigation.limite="+AUTOCOMPLETION_ELEMENTS_NBRE +'&masque.'+parametre+'='+valeur+
        '&retour.format=oss&distinct=1&ns.structure='+ns_str;
        return url;
}

function getValeurMasque(parametre) {
        var valeur = $('#'+parametre).val();
        if (parametre == 'au' ){
                valeur = valeur +',(' + valeur + ')';
        } else if (parametre == 'bib' ){
                valeur = valeur +', %; ' + valeur ;
        }
        return valeur;
}

function getValeurNsStructure(parametre) {
        var ns = '';
        if (parametre == 'au' || parametre == 'bib'){
                ns = parametre +'_ss';
        } else {
                ns = parametre;
        }
        return ns;
}


function getUrlAppelCompletion() {
        var url = '';
        var mots = $('#nom').val();
        if (nomSciEstDemande()) {
                url = getUrlAutocompletionNomsSci(mots);
        } else if (nomVernaculaireEstDemande()) {
                mots = mots.replace('  ',' ');
                mots = mots.replace(' ','_');
                url = getUrlAutocompletionNomsVerna(mots);
        }
        return url;
}

function getUrlAutocompletionNomsSci(requete) {
        var url = getUrlAutocompletion(URL_SERVICE_AUTOCOMPLETION_NOM_SCI, requete, 'min')+
                "&ns.structure=au,an"+
                "&retour.tri=retenu";
        return url;
}

function getUrlAutocompletionNomsVerna(requete) {
        var url = getUrlAutocompletion(URL_SERVICE_AUTOCOMPLETION_NOM_VERNA, requete, 'oss')+
                "&masque.lg=fra";
        return url;
}

function getUrlAutocompletion(baseUrl, requete, format) {
        var url = baseUrl+"?"+
                "masque="+requete+"&"+
                "recherche=etendue&"+
                "retour.format="+format+"&"+
                "navigation.limite="+AUTOCOMPLETION_ELEMENTS_NBRE;
        return url;
}

/**------------ Fonctions de détection de l'état du formulaire ------------------*/
function nomSciEstDemande()  {
        var boutonRadioNomSci = $('#type_nom_scientifique');
        return (($('#type_nom_vernaculaire').length <= 0) || (boutonRadioNomSci != null && boutonRadioNomSci.attr("checked") != "undefined" && boutonRadioNomSci.attr("checked") == "checked"));
}

function nomVernaculaireEstDemande()  {
        var boutonRadioNomSci = $('#type_nom_vernaculaire');
        return (boutonRadioNomSci.length > 0 && boutonRadioNomSci.attr("checked") != "undefined" && boutonRadioNomSci.attr("checked") == "checked");
}

/**------------ Fonctions de gestion de l'affichage des valeurs par defaut ----------------------*/
function gererAffichageValeursParDefaut() {
                $('input[name="type_nom"]').click(function() {
                        changerPlaceHolderNom();
                });
                changerPlaceHolderNom();
                $('input').click(function() {
                        $(this).attr('placeholder', '');                        
                });
}

function changerPlaceHolderNom() {
        if(nomSciEstDemande()) {
                $('#nom').attr('placeholder',VALEUR_DEFAUT_NOM_SCI);
        } else {
                $('#nom').attr('placeholder',VALEUR_DEFAUT_NOM_VERNA);
        }
}

/**------------ Fonctions de gestion du zoom sur les images affichées dans les résultats de recherche ----------------------*/
function gererClicIllustrationsResultats() {
        $('.illustration_resultat_cel').click(function() {
                var url = $(this).attr('src');
                var titre = trouverNomTaxon($(this));
                var url = URL_BASE_POPUP+"?module=popup-galerie&action=fiche&num_nom="+$(this).attr('data-num-nom')+"&titre="+titre+"&referentiel="+REFERENTIEL;
                window.open(url, '', 'directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no, width='+(700)+', height='+(650));
        }); 
        
        $('.illustration_resultat_choro').click(function() {
                var url = $(this).attr('src').replace('108x101','432x404');
                var titre = 'Chorologie du taxon '+trouverNomTaxon($(this));
                ouvrirFenetreIllustrationResultat(url, titre, 432, 404);
        }); 
        
        $('.illustration_resultat_coste').click(function() {
                var url = $(this).attr('src');
                var titre = 'Illustration de Coste du taxon '+trouverNomTaxon($(this));
                ouvrirFenetreIllustrationResultat(url, titre, 400, 400);
        }); 
}

function trouverNomTaxon(objet) {
        nom = "";
        if(nomVernaculaireEstDemande()) {
                nom = objet.parent().parent().find('a.lien_fiche_eflore').text();
        } else {
                nom = objet.parent().find('.nom-sci a.lien_fiche_eflore').text();
        }
        return nom;
}

function ouvrirFenetreIllustrationResultat(url, titre, hauteur, largeur) {
        var fenetre = window.open('_blank', '','directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no, width='+(largeur+17)+', height='+(hauteur+17));
        var tmp = fenetre.document;
        tmp.write('<html><head><title>'+titre+'</title>');
        tmp.write('</head><body>');
        tmp.write('<p style="height='+hauteur+'px;text-align:center;line-height='+hauteur+'px;"><img id="image_agrandie" height="'+hauteur+'" width="'+largeur+'" style="vertical-align:middle;" src="'+url+'" /></p>');
        tmp.write('</body></html>');
        tmp.close();
}

/*
 * jQuery UI Autocomplete HTML Extension
 *
 * Copyright 2010, Scott González (http://scottgonzalez.com)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * http://github.com/scottgonzalez/jquery-ui-extensions
 * 
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
 */
(function( $ ) {
        var proto = $.ui.autocomplete.prototype,
                initSource = proto._initSource;
        
        function filter( array, term ) {
                var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
                return $.grep( array, function(value) {
                        return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
                });
        }
        
        $.extend( proto, {
                _initSource: function() {
                        if (this.options.html && $.isArray(this.options.source) ) {
                                this.source = function( request, response ) {
                                        response( filter( this.options.source, request.term ) );
                                };
                        } else {
                                initSource.call( this );
                        }
                },
                _renderItem: function( ul, item) {
                        if (item.retenu == true) {
                                item.label = "<strong>"+item.label+"</strong>";
                        }
                        var classe = (nomRechercheEnCours == 'nom_sci' && nomSciEstDemande()) ? 'class="autocompletion_nom"' : '';
                        return $("<li "+classe+"></li>")
                                .data("item.autocomplete", item)
                                .append( $("<a></a>")[ this.options.html ? "html" : "text" ](item.label))
                                .appendTo(ul);
                }
        });
})( jQuery );