Subversion Repositories eFlore/Applications.cel

Rev

Rev 1344 | Go to most recent revision | Blame | Last modification | View Log | RSS feed

//+----------------------------------------------------------------------------------------------------------+
// Initialisation de Jquery mobile
$(document).bind('mobileinit', function() {
        $.mobile.defaultPageTransition = 'fade';
});
$(document).on('online', function(event) {
        console.log('online');
        miseAJourObs();
});
//+----------------------------------------------------------------------------------------------------------+
// Gestion des paramètres URL
$.urlParam = function(name){
        var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
        return decodeURIComponent(results[1]) || 0;
}
function recupererParametresUrl() {
        $('#referentiel').val($.urlParam('ref'));
        $('#nom').val($.urlParam('nom_sci'));
        $('#nom-sci-select').val($.urlParam('nom_sci'));
        $('#num-nom-select').val($.urlParam('num_nom'));
}
$(document).ready(function() {
        $('body').on('pageshow', '#saisie', function(event) {
                obtenirPosition(event);
                recupererParametresUrl();
        });
        $('#geolocaliser').on('click', obtenirPosition);
        
        $('body').on('pageshow', '#infos', obtenirDate);
});
//+----------------------------------------------------------------------------------------------------------+
// Géolocalisation et date du jour
var gps = navigator.geolocation;

function obtenirPosition(event) {
        event.stopImmediatePropagation();
        event.stopPropagation();
        event.preventDefault();
        
        obtenirDate();
        geolocaliser();
}
function geolocaliser() {
        if (gps) {
            navigator.geolocation.getCurrentPosition(surSuccesGeoloc, surErreurGeoloc);
        } else {
            var erreur = {code:'0', message: 'Géolocalisation non supportée par le navigateur'};
            surErreurGeoloc(erreur);
        }
}
function surSuccesGeoloc(position){
        if (position) {
                var lat = position.coords.latitude;
                var lng = position.coords.longitude;
                $('#lat').html(lat);
                $('#lng').html(lng);

                console.log('Geolocation SUCCESS');
                var url_service = SERVICE_NOM_COMMUNE_URL;
                var urlNomCommuneFormatee = url_service.replace('{lat}', lat).replace('{lon}', lng);
                var jqxhr = $.getJSON(urlNomCommuneFormatee, function(data) {
                        console.log('NOM_COMMUNE found.');
                        $('#location').html(data['nom']);
                        $('#code_insee').val(data['codeINSEE']);
                })
                .complete(function() { 
                        var texte = ($('#location').html() == '') ? TEXTE_HORS_LIGNE : $('#location').html();
                        $('#location').html(texte);
                })
                ;
        }
}
function surErreurGeoloc(error){
        alert('Echec de la géolocalisation, code: ' + error.code + ' message: '+ error.message);
}

function obtenirDate() {
        var d = new Date();
        var jour = d.getDate();
        var mois = d.getMonth()+1;
        var annee = d.getFullYear();
        var aujourdhui = 
                ( (''+jour).length < 2 ? '0' : '') + jour + '/' +
                ( (''+mois).length < 2 ? '0' : '') + mois + '/' +
                annee;
        $('#date').val(aujourdhui);
        $('#annee').html(annee);
} 
//+----------------------------------------------------------------------------------------------------------+
// Local Storage
$(document).ready(function() {
        $('#sauver-obs').on('click', ajouterObs);
        $('#valider_photos').on('click', ajoutPhoto);
        $('body').on('pageshow', '#liste', chargerListeObs);
        $('body').on('pageshow', '#transmission', miseAJourObs);
});

var bdd = window.localStorage,
        index_obs = (bdd.getItem('index_obs') == null) ? 1 : bdd.getItem('index_obs'),
        index_photos = (bdd.getItem('index_photos') == null) ? 1 : bdd.getItem('index_photos');
alert('space used:'+JSON.stringify(bdd).length);
//bdd.clear();

console.log(bdd);
function ajouterObs(event) {
        if ($('#nom').val() != '') {
                var obs = {
                        num:TEXTE_OBS, 
                        maj:0,
                        date:'', 
                        referentiel:'',
                        lat:'', lng:'', 
                        commune:'', code_insee: 0,
                        nom:'', 
                        nom_sci_selec:'', 
                        nn_select:'',
                        nom_sci_retenu:'',
                        nn_retenu:'',
                        num_taxon:'', 
                        famille:''
                };
                
                obs.num += index_obs++;
                obs.date = $('#date').val();
                obs.referentiel = $('#referentiel').val();
                obs.lat = $('#lat').html();
                obs.lng = $('#lng').html();
                obs.commune = $('#location').html();
                obs.code_insee = $('#code_insee').val();
                obs.nom = $('#nom').val();
                obs.referentiel = $('#referentiel').val();
                obs.nom_sci_selec = $('#nom_sci_select').val();
                obs.nn_select = $('#num_nom_select').val();
                
                var cle = obs.num;
                sauvegarderObs(cle, obs);
                bdd.setItem('index_obs', index_obs);
        /*      
                var txt = 'Observation n°'+obs.num+'/'+bdd.length+' créée';
                $('#obs-saisie-infos').html('<p class="reponse ui-btn-inner ui-btn-corner-all">'+txt+'</p>')
                        .fadeIn("slow")
                        .delay(1600)
                        .fadeOut("slow");
        */      
                $.mobile.changePage('#liste');
                effacerFormulaire();
                event.stopPropagation();
                event.preventDefault();
        } else {
                $.mobile.changePage('#saisie');
                event.stopPropagation();
                event.preventDefault();
        }
}

function sauvegarderObs(cle, obs) {
        var val = JSON.stringify(obs);

        alert('space used:'+JSON.stringify(bdd).length+'_'+(JSON.stringify(bdd).length+val.length));
        bdd.setItem(cle, val);
}

function effacerFormulaire() {
        $('#lat').html('');
        $('#lng').html('');
        $('#location').html('');
}

function chargerListeObs() {
        $('#liste_obs').empty();
        
        var nbre = bdd.length;
        for (var i = 0; i < nbre; i++) {
                var cle = bdd.key(i);
                if (cle.indexOf(TEXTE_OBS) !== -1) {
                        var obs = JSON.parse(bdd.getItem(cle));
                        console.log(obs);
                        $('#liste_obs').prepend(
                                '<li>'+
                                        obs.num + ' (Nbre photos : ' + compterPhotos(obs.num) + ')<br />' + 
                                        '<a href="#" onclick="detailsObs(this);" data-split-icon="next" data-split-theme="a" title="Voir la fiche" data-obs-num="'+obs.num+'">'+
                                                '<strong>'+obs.nom+'</strong> <br />'+obs.date+' à '+obs.commune+
                                        '</a>'+
                                        '<a href="#" onclick="supprimerObs(this);" title="Supprimer l\'observation" ' +
                                                'data-obs-num="'+obs.num+'">'+
                                                'Supprimer'+
                                        '</a>'+
                                '</li>'
                        );
                }
                $('#liste_obs').listview('refresh');
        }
}

function compterPhotos(num_obs) {
        var compteur = 0;
        if (num_obs != '') {
                var nbre = bdd.length;
                for (var i = 0; i < nbre; i++) {
                        var cle = bdd.key(i);
                        if (cle.indexOf(TEXTE_PHOTO) !== -1) {
                                var photo = JSON.parse(bdd.getItem(cle));
                                if (photo.parent == num_obs) {
                                        compteur++;
                                }
                        }
                }
        }
        return compteur;
}

function supprimerObs(data) {
        var cle_obs = data.getAttribute('data-obs-num'),
                obs = JSON.parse(bdd.getItem(cle_obs)),
                nbre = bdd.length,
                a_supprimer = new Array();
        for (var i = 0; i < nbre; i++) {
                var cle = bdd.key(i);
                if (cle.indexOf(TEXTE_PHOTO) !== -1) {
                        var photo = JSON.parse(bdd.getItem(cle));
                        if (photo.parent == obs.num) {
                                a_supprimer.push(photo.num);
                        }
                }
        }
        for (var c = 0; c < a_supprimer.length; c++) {
                bdd.removeItem(a_supprimer[c]);
        }
        bdd.removeItem(cle_obs);
        
        var txt = obs.num + ' supprimée.';
        $('#obs-suppression-infos').html('<p class="reponse ui-btn-inner ui-btn-corner-all">'+txt+'</p>')
                .fadeIn(0)
                .delay(1600)
                .fadeOut('slow');
        
        chargerListeObs();
}

function detailsObs(data) {
        var num_obs = data.getAttribute('data-obs-num');
        var obs = JSON.parse(bdd.getItem(num_obs));
        $('#id_obs').html(obs.num);
        
        var texte = '<strong>' + obs.nom + '</strong> vue le ' + obs.date;
        texte += (obs.commune == TEXTE_HORS_LIGNE ||  obs.commune == '') ? '' :  ' <br /> à ' + obs.commune;
        $('#details_obs').html(texte);
        $.mobile.changePage('#observation');
        afficherPhotos(obs.num);
}

function ajoutPhoto() {
        var id_obs = $('#id_obs').html();
        if (id_obs != '') {
                $.each($('#pic').get(0).files, function(index, valeur) {
                        var reader = new FileReader(),
                                binary, base64;
                        reader.addEventListener('loadend', function (evt) {
                                binary = reader.result; // binary data (stored as string), unsafe for most actions
                                base64 = btoa(binary);  // base64 data, safer but takes up more memory
                                
                                var photo = {
                                        num:TEXTE_PHOTO, 
                                        nom: '',
                                        parent:'',
                                        base64:0
                                };
                                photo.num += index_photos++;
                                photo.nom = valeur.name;
                                photo.parent = id_obs;
                                photo.base64 = base64;
                                
                                var cle = photo.num;
                                sauvegarderObs(cle, photo);
                                bdd.setItem('index_photos', index_photos);
                                afficherPhotos(id_obs);
                        }, false);
                        reader.readAsBinaryString(valeur);
                });
        }
}

function afficherPhotos(num_obs) {
        $('#pic').val('');
        $('#photos_obs').empty();
        if (num_obs != '') {
                var nbre = bdd.length;
                for (var i = 0; i < nbre; i++) {
                        var cle = bdd.key(i);
                        if (cle.indexOf(TEXTE_PHOTO) !== -1) {
                                var photo = JSON.parse(bdd.getItem(cle));
                                if (photo.parent == num_obs) {
                                        $('#photos_obs').prepend(
                                                '<li>'+
                                                        '<a href="#'+photo.num+'" data-rel="popup" data-role="button" data-inline="true">' +
                                                                '<img src="data:image/png;base64,' + photo.base64 + '" />' +
                                                                photo.nom + 
                                                        '</a>' +
                                                        '<a href="#" onclick="supprimerPhoto(this);" title="Supprimer la photo" ' +
                                                                'data-icon="delete" data-photo-num="' + photo.num + '"' + 
                                                                'data-photo-parent="' + num_obs + '" data-theme="c">'+
                                                                'Supprimer cette photo'+
                                                        '</a>'+
                                                '</li>'
                                        );
                                }
                        }
                        $('#photos_obs').listview('refresh');
                }
        }
}

function compterPhotos(num_obs) {
        var compteur = 0;
        if (num_obs != '') {
                var nbre = bdd.length;
                for (var i = 0; i < nbre; i++) {
                        var cle = bdd.key(i);
                        if (cle.indexOf(TEXTE_PHOTO) !== -1) {
                                var photo = JSON.parse(bdd.getItem(cle));
                                if (photo.parent == num_obs) {
                                        compteur++;
                                }
                        }
                }
        }
        return compteur;
}

function supprimerPhoto(data) {
        var cle_photo = data.getAttribute('data-photo-num'),
                parent = data.getAttribute('data-photo-parent'),
                photo = JSON.parse(bdd.getItem(cle_photo));
        bdd.removeItem(cle_photo);
        
        var txt = photo.num + ' supprimée.';
        $('#photo-suppression-infos').html('<p class="reponse ui-btn-inner ui-btn-corner-all">'+txt+'</p>')
                .fadeIn(0)
                .delay(1600)
                .fadeOut('slow');
        
        afficherPhotos(parent);
}

function miseAJourObs() {
        console.log('majObs');
        var nbre = bdd.length;
        for (var i = 0; i < nbre; i++) {
                var cle = bdd.key(i);
                if (cle.indexOf(TEXTE_OBS) !== -1) {
                        var obs = JSON.parse(bdd.getItem(cle));
                        
                        if (obs.maj == 0) {
                                var maj = 1;
                                
                                if (obs.commune == TEXTE_HORS_LIGNE ||  obs.commune == '') {
                                        var url_service = SERVICE_NOM_COMMUNE_URL;
                                        var urlNomCommuneFormatee = url_service.replace('{lat}', lat).replace('{lon}', lng);
                                        jQuery.ajax({
                                                url: urlNomCommuneFormatee,
                                                success: function(data) {
                                                        obs.commune = data['nom'];
                                                        obs.code_insee = data['codeINSEE'];
                                                 },
                                                 error: function() {
                                                         maj = 0;
                                                 },
                                                async: false
                                   });
                                }
                                
                                if (obs.nom_sci_retenu == '') {
                                        jQuery.ajax({
                                                url:    '/service:eflore:0.1/' + obs.referentiel + '/noms?'
                                                                 + 'masque.nn=' + obs.nn_select
                                                                 + '&retour.champs=num_taxonomique',
                                                success: function(data) {
                                                        var cle = '',
                                                                compteur = 0;
                                                        for (name in data['resultat']) {
                                                                if (compteur == 0) {
                                                                        cle = name;
                                                                }
                                                                compteur++;
                                                        }
                                                        obs.num_taxon = data['resultat'][cle]['num_taxonomique'];
                                                        jQuery.ajax({
                                                                url:    '/service:eflore:0.1/' + obs.referentiel + '/noms?'
                                                                                 + 'masque.nt=' + obs.num_taxon
                                                                                 + '&retour.champs=famille'
                                                                                 + '&retour.tri=retenu',
                                                                success: function(data) {
                                                                        var cle = '',
                                                                                compteur = 0;
                                                                        for (name in data['resultat']) {
                                                                                if (compteur == 0) {
                                                                                        cle = name;
                                                                                }
                                                                                compteur++;
                                                                        }
                                                                        obs.famille = data['resultat'][cle]['famille'];
                                                                        obs.nom_sci_retenu = data['resultat'][cle]['nom_sci'];
                                                                        obs.nn_retenu = cle;
                                                                 },
                                                                 error: function() {
                                                                         maj = 0;
                                                                 },
                                                                async:   false
                                                        });
                                                 },
                                                async:   false
                                        });
                                }
                                
                                obs.maj = maj;
                        }
                        
                        sauvegarderObs(obs.num, obs);
                }
        }
}

function transmettreObs() {
        if ($('#courriel').val() == $('#courriel_confirmation').val() && $('#courriel').val() != '') {
                var nbre = bdd.length;
                for (var i = 0; i < nbre; i++) {
                        var cle = bdd.key(i);
                        if (cle.indexOf('obs') !== -1) {
                                var obs = JSON.parse(bdd.getItem(cle));
                                stockerObsData(obs);
                        }
                }
                var observations = $('#details_obs').data();
                console.log(observations);
                
                if (observations == undefined || jQuery.isEmptyObject(observations)) {
                        //afficherPanneau("#dialogue-zero-obs");
                } else {
                        observations['projet'] = TAG_PROJET;
                        observations['tag-obs'] = '';
                        observations['tag-img'] = '';
                        
                        var utilisateur = new Object();
                        utilisateur.id_utilisateur = $('#id_utilisateur').val();
                        utilisateur.prenom = $('#prenom_utilisateur').val();
                        utilisateur.nom = $('#nom_utilisateur').val();
                        utilisateur.courriel = $('#courriel').val();
                        observations['utilisateur'] = utilisateur;
                        envoyerObsAuCel(observations);
                }
        }
}

function stockerObsData(obs) {
        var nbre = bdd.length,
                img_noms = new Array(),
                img_codes = new Array();
        for (var i = 0; i < nbre; i++) {
                var cle = bdd.key(i);
                if (cle.indexOf(TEXTE_PHOTO) !== -1) {
                        var photo = JSON.parse(bdd.getItem(cle));
                        if (photo.parent == obs.num) {
                                img_noms.push(photo.nom);
                                img_codes.push(photo.base64);
                        }
                }
        }
        
        $('#details_obs').data(obs.num, {
                'date' : obs.date, 
                'notes' : '',
                
                'nom_sel' : obs.nom,
                'num_nom_sel' : obs.nn_select,
                'nom_ret' : obs.nom_sci_retenu,
                'num_nom_ret' : obs.nn_retenu,
                'num_taxon' : obs.num_taxon,
                'famille' : obs.famille,
                'referentiel' : obs.referentiel,
                
                'latitude' : obs.lat,
                'longitude' : obs.lng,
                'commune_nom' : obs.commune,
                'commune_code_insee' : obs.code_insee,
                'lieudit' : '',
                'station' : '',
                'milieu' : '',
                
                //Ajout des champs images
                'image_nom' : img_noms,
                'image_b64' : img_codes 
        });
}


function envoyerObsAuCel(observations) {
/*
        var erreurMsg = "";
        $.ajax({
                url : SERVICE_SAISIE_URL,
                type : "POST",
                data : observations,
                dataType : "json",
                beforeSend : function() {
                        $("#dialogue-obs-transaction-ko").hide();
                        $("#dialogue-obs-transaction-ok").hide();
                        $(".alert-txt .msg").remove();  
                        $(".alert-txt .msg-erreur").remove();
                        $(".alert-txt .msg-debug").remove();
                        $("#chargement").show();
                },
                success : function(data, textStatus, jqXHR) {
                        $('#dialogue-obs-transaction-ok .alert-txt').append($("#tpl-transmission-ok").clone().html());
                        supprimerMiniatures();
                },
                statusCode : {
                        500 : function(jqXHR, textStatus, errorThrown) {
                                erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
                    }
                },
                error : function(jqXHR, textStatus, errorThrown) {
                        erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
                        try {
                                reponse = jQuery.parseJSON(jqXHR.responseText);
                                if (reponse != null) {
                                        $.each(reponse, function (cle, valeur) {
                                                erreurMsg += valeur + "\n";
                                        });
                                }
                        } catch(e) {
                                erreurMsg += "L'erreur n'était pas en JSON.";
                        }
                },
                complete : function(jqXHR, textStatus) {
                        $("#chargement").hide();
                        var debugMsg = extraireEnteteDebug(jqXHR);
                        
                        if (erreurMsg != '') {
                                if (DEBUG) {
                                        $("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
                                        $("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
                                }
                                var hrefCourriel = "mailto:cel@tela-botanica.org?"+
                                        "subject=Disfonctionnement du widget de saisie "+TAG_PROJET+
                                        "&body="+erreurMsg+"\nDébogage :\n"+debugMsg;
                                
                                $('#dialogue-obs-transaction-ko .alert-txt').append($("#tpl-transmission-ko").clone()
                                        .find('.courriel-erreur')
                                        .attr('href', hrefCourriel)
                                        .end()
                                        .html());
                                $("#dialogue-obs-transaction-ko").show();
                        } else {
                                if (DEBUG) {
                                        $("#dialogue-obs-transaction-ok .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
                                }
                                $("#dialogue-obs-transaction-ok").show();
                        }
                        initialiserObs();
                }
        });
*/
}

//+----------------------------------------------------------------------------------------------------------+
// Manifest Cache
var appCache = window.applicationCache;
$(document).ready(function() {
        appCache.addEventListener('updateready', function() {
                alert('Mise à jour :'+appCache.status);
        });
        if (appCache.status === appCache.UPDATEREADY) {  
                surMiseAJourCache();
        }
});

function surMiseAJourCache() {  
        // Browser downloaded a new app cache.
        // Swap it in and reload the page to get the new hotness.
        appCache.swapCache();
        if (confirm('A new version of this site is available. Load it ?')) {
                window.location.reload();
        }
}


//+----------------------------------------------------------------------------------------------------------+
//Transmission données
function verifierConnexion() {
        return ( ('onLine' in navigator) && (navigator.onLine));
}

//+---------------------------------------------------------------------------------------------------------+
//IDENTITÉ
$(document).ready(function() {
        $('#courriel').on('blur', requeterIdentite);
        $('#courriel').on('keypress', function(event) {
                if (event.which == 13) {
                        testerLancementRequeteIdentite(event);
                }
        });
        $('#valider_courriel').on('vmousedown', testerLancementRequeteIdentite);
        $('body').on('pageshow', '#transmission', testerLancementRequeteIdentite);
});

function testerLancementRequeteIdentite(event) {        
        if (bdd.getItem('courriel') != null) {
                $('#courriel').val(bdd.getItem('courriel'));
        }
        
        requeterIdentite();
        event.preventDefault();
        event.stopPropagation();
}

function requeterIdentite() {
        var courriel = $('#courriel').val();
        if (courriel != '') {
                miseAJourCourriel();
                var urlAnnuaire = SERVICE_ANNUAIRE + courriel;  //http://localhost/applications/annuaire/jrest/
                $.ajax({
                        url : urlAnnuaire,
                        type : 'GET',
                        success : function(data, textStatus, jqXHR) {
                                console.log('Annuaire SUCCESS : ' + textStatus);
                                if (data != undefined && data[courriel] != undefined) {
                                        var infos = data[courriel];
                                        $('#id_utilisateur').val(infos.id);
                                        $('#prenom_utilisateur').val(infos.prenom);
                                        $('#nom_utilisateur').val(infos.nom);
                                        $('#courriel_confirmation').val(courriel);
                                        $('#prenom_utilisateur, #nom_utilisateur, #courriel_confirmation').attr('disabled', 'disabled');
                                } else {
                                        surErreurCompletionCourriel();
                                }
                        },
                        error : function(jqXHR, textStatus, errorThrown) {
                                console.log('Annuaire ERREUR : ' + textStatus);
                                surErreurCompletionCourriel();
                        },
                        complete : function(jqXHR, textStatus) {
                                console.log('Annuaire COMPLETE : ' + textStatus);
                                $('#zone_prenom_nom').removeClass('hidden');
                                $('#zone_courriel_confirmation').removeClass('hidden');
                        }
                });
        }
}

function surErreurCompletionCourriel() {
        $('#prenom_utilisateur, #nom_utilisateur, #courriel_confirmation').val('');
        $('#prenom_utilisateur, #nom_utilisateur, #courriel_confirmation').removeAttr('disabled');
}

function miseAJourCourriel() {
        if ($('#courriel_memoire').is(':checked')) {
                bdd.setItem('courriel',  $("#courriel").val());
        }
}