Subversion Repositories eFlore/Applications.cel

Rev

Rev 3211 | Rev 3230 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3120 delphine 1
/**
2
 * Constructeur WidgetSaisie par défaut
3
 */
4
function WidgetSaisie() {
3208 idir 5
  this.langue = 'fr';
6
  this.obsNbre = 0;
7
  this.nbObsEnCours = 1;
8
  this.totalObsATransmettre = 0;
9
  this.nbObsTransmises = 0;
10
  this.debug = null;
11
  this.html5 = null;
12
  this.tagProjet = null;
13
  this.tagImg = null;
14
  this.tagObs = null;
15
  this.separationTagImg = null;
16
  this.separationTagObs = null;
17
  this.obsId = null;
18
  this.serviceSaisieUrl = null;
19
  this.serviceObsUrl = null;
20
  this.nomSciReferentiel = null;
21
  this.especeImposee = false;
22
  this.infosEspeceImposee = null;
23
  this.autocompletionElementsNbre = null;
24
  this.referentielImpose = null;
25
  this.serviceAutocompletionNomSciUrl = null;
26
  this.serviceAutocompletionNomSciUrlTpl = null;
27
  this.obsMaxNbre = null;
28
  this.dureeMessage = null;
29
  this.serviceAnnuaireIdUrl = null;
30
  this.serviceNomCommuneUrl = null;
31
  this.serviceNomCommuneUrlAlt = null;
32
  this.chargementIconeUrl = null;
33
  this.chargementImageIconeUrl = null;
34
  this.calendrierIconeUrl = null;
35
  this.pasDePhotoIconeUrl = null;
3120 delphine 36
}
37
 
38
/**
39
 * Initialisation du widget
40
 */
41
WidgetSaisie.prototype.init = function() {
3208 idir 42
  this.initForm();
43
  this.initEvts();
3217 idir 44
  // Auth.js s'en occuppe
45
  if ( '' === $( '#nom-complet').text() && '' !== $( '#courriel' ).val() ) {
3208 idir 46
    this.requeterIdentite();
47
  }
3120 delphine 48
};
49
 
50
/**
51
 * Initialise le formulaire, les validateurs, les listes de complétion...
52
 */
53
WidgetSaisie.prototype.initForm = function() {
3208 idir 54
  if ( '' !== this.obsId ) {
55
    this.chargerInfoObs();
56
  }
3120 delphine 57
 
3208 idir 58
  this.configurerDatePicker( '.date' );
59
  this.ajouterAutocompletionNoms();
60
  this.configurerFormValidator();
61
  this.definirReglesFormValidator();
3120 delphine 62
 
3208 idir 63
  if( this.especeImposee ) {
64
    $( '#taxon' ).attr( 'disabled', 'disabled' );
65
    $( '#taxon-input-groupe' ).attr( 'title', '' );
66
    // Bricolage cracra pour avoir le nom retenu avec auteur (nom_retenu.libelle ne le mentionne pas)
67
    var nomRetenuComplet = this.infosEspeceImposee['nom_retenu_complet'],
68
      debutAnneRefBiblio = nomRetenuComplet.indexOf( ' [' );
69
    if ( -1 !== debutAnneRefBiblio ) {
70
      nomRetenuComplet = nomRetenuComplet.substr( 0, debutAnneRefBiblio );
71
    }
72
    // fin bricolage cracra
73
    var infosAssociee = {
74
      label : this.infosEspeceImposee.nom_sci_complet,
75
      value : this.infosEspeceImposee.nom_sci_complet,
76
      nt : this.infosEspeceImposee.num_taxonomique,
77
      nomSel : this.infosEspeceImposee.nom_sci,
78
      nomSelComplet : this.infosEspeceImposee.nom_sci_complet,
79
      numNomSel : this.infosEspeceImposee.id,
80
      nomRet : nomRetenuComplet,
81
      numNomRet : this.infosEspeceImposee['nom_retenu.id'],
82
      famille : this.infosEspeceImposee.famille,
83
      retenu : ( 'false' === this.infosEspeceImposee.retenu ) ? false : true
84
    };
85
    $( '#taxon' ).data( infosAssociee );
86
  }
3120 delphine 87
};
88
 
89
/**
90
 * Initialise les écouteurs d'événements
91
 */
92
WidgetSaisie.prototype.initEvts = function() {
3208 idir 93
  var lthis = this;
3120 delphine 94
 
3208 idir 95
  // console.log($( '#taxon' ).data('label') );
3120 delphine 96
 
3208 idir 97
  $( 'body' ).on( 'click', '.effacer-miniature', function() {
98
    $( this ).parent().remove();
99
  });
3120 delphine 100
 
3208 idir 101
  $( '#bouton-anonyme' ).on( 'click', function() {
102
    $( this ).css({
103
      'background-color': 'rgba(0, 159, 184, 0.7)',
104
      'color': '#fff'
105
    });
106
    $( '#anonyme' ).removeClass( 'hidden' );
107
    $( '#courriel' ).focus();
108
  });
109
 
110
  $( '#fichier' ).bind( 'change', function ( e ) {
111
    arreter( e );
112
    var options = {
113
      success: lthis.afficherMiniature.bind( lthis ), // post-submit callback
114
      dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
115
      resetForm: true // reset the form after successful submit
116
    };
117
    $( '#miniature' ).append( '<img id="miniature-chargement" class="miniature" alt="chargement" src="' + this.chargementImageIconeUrl + '">' );
118
    $( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
119
    if( lthis.verifierFormat( $( '#fichier' ).val() ) ) {
120
      $( '#form-upload' ).ajaxSubmit( options );
121
    } else {
122
      $( '#form-upload' )[0].reset();
123
      window.alert( 'Le format de fichier n\'est pas supporté, les formats acceptés sont ' + $( '#fichier' ).attr( 'accept' ) );
124
    }
125
    return false;
126
  });
127
 
128
  // identité
3217 idir 129
  if ( '' === $( '#nom-complet').text() ) {
3208 idir 130
    $( '#courriel' ).on( 'blur', this.requeterIdentite.bind( this ) );
131
    $( '#courriel' ).on( 'keypress', this.testerLancementRequeteIdentite.bind( this ) );
132
  }
133
  $( '.alert .close' ).on( 'click', this.fermerPanneauAlert );
134
  $( '.has-tooltip' ).tooltip( 'enable' );
135
  $( '#btn-aide' ).on( 'click', this.basculerAffichageAide);
136
  $( '#prenom' ).on( 'change', this.formaterPrenom );
137
  $( '#nom' ).on( 'change', this.formaterNom );
138
 
139
  $( '#courriel_confirmation' ).on( 'paste', this.bloquerCopierCollerCourriel.bind( this ) );
140
  $( '#ajouter-obs' ).on( 'click', this.ajouterObs.bind( this ) );
141
  $( '.obs-nbre' ).on( 'changement', this.surChangementNbreObs.bind( this ) );
142
  $( 'body' ).on( 'click', '.supprimer-obs', function() {
143
   var that = this,
144
      suppObs = lthis.supprimerObs.bind( lthis );
145
   // bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
146
   suppObs( that );
147
  });
148
 
149
  $( '#transmettre-obs' ).on( 'click', this.transmettreObs.bind( this ) );
150
  $( '#referentiel' ).on( 'change', this.surChangementReferentiel.bind( this ) );
151
 
152
  $( 'body' ).on( 'click', '.defilement-miniatures-gauche', function( event ) {
153
    event.preventDefault();
154
    lthis.defilerMiniatures( $( this ) );
155
  });
156
  $( 'body' ).on( 'click', '.defilement-miniatures-droite', function( event ) {
157
    event.preventDefault();
158
    lthis.defilerMiniatures( $( this ) );
159
  });
160
 
161
  // fermeture fenêtre
3211 idir 162
  if ( !this.debug && 0 < $( '.obs' ).length ) {
3208 idir 163
    $( window ).on( 'beforeunload', function( event ) {
164
      return 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.';
165
    });
166
  }
167
 
3120 delphine 168
};
169
 
170
/**
3208 idir 171
 * Retourne true si l'extension de l'image 'nom' est .jpg ou .jpeg
3120 delphine 172
 */
3208 idir 173
WidgetSaisie.prototype.verifierFormat = function( nom ) {
174
  var parts = nom.split( '.' );
175
  extension = parts[ parts.length - 1 ];
176
  return ( 'jpeg' === extension.toLowerCase() || 'jpg' === extension.toLowerCase() );
3120 delphine 177
};
178
 
179
/**
180
 * Affiche la miniature d'une image temporaire (formulaire) qu'on a ajoutée à l'obs
181
 */
3208 idir 182
WidgetSaisie.prototype.afficherMiniature = function( reponse ) {
183
  if ( this.debug ) {
184
    var debogage = $( 'debogage', reponse ).text();
185
    //console.log( 'Débogage upload : '+debogage);
186
  }
187
  var message = $( 'message', reponse ).text();
188
  if ( '' !== message ) {
189
    $( '#miniature-msg' ).append( message );
190
  } else {
191
    $( '#miniatures' ).append( this.creerWidgetMiniature( reponse ) );
192
  }
193
  $( '#ajouter-obs' ).removeAttr( 'disabled' );
3120 delphine 194
};
195
 
196
/**
197
 * Crée la miniature d'une image temporaire (formulaire), avec le bouton pour l'effacer
198
 */
3208 idir 199
WidgetSaisie.prototype.creerWidgetMiniature = function( reponse ) {
200
  var miniatureUrl = $( 'miniature-url', reponse ).text();
201
  var imgNom = $( 'image-nom', reponse ).text();
202
  var html =
203
    '<div class="miniature mb-3 mr-3">'+
204
      '<img class="miniature-img" class="miniature img-rounded" alt="' + imgNom + '" src="' + miniatureUrl + '">'+
205
      '<a class="effacer-miniature"><i class="far fa-trash-alt"></i></a>'+
206
    '</div>'
207
  return html;
3120 delphine 208
};
209
 
210
/**
211
 * Efface une miniature (formulaire)
212
 */
3208 idir 213
WidgetSaisie.prototype.supprimerMiniature = function( miniature ) {
214
  miniature.parents( '.miniature' ).remove();
3120 delphine 215
};
216
 
217
/**
218
 * Efface toutes les miniatures (formulaire)
219
 */
220
WidgetSaisie.prototype.supprimerMiniatures = function() {
3208 idir 221
  $( '#miniatures' ).empty();
222
  $( '#miniature-msg' ).empty();
3120 delphine 223
};
224
 
225
/* Observateur */
3208 idir 226
WidgetSaisie.prototype.testerLancementRequeteIdentite = function( event ) {
227
  if ( 13 == event.which ) {
228
    this.requeterIdentite();
229
    event.preventDefault();
230
    event.stopPropagation();
231
  }
3120 delphine 232
};
233
 
234
WidgetSaisie.prototype.requeterIdentite = function() {
3208 idir 235
  var lthis = this;
236
  var courriel = $( '#courriel' ).val();
237
  var urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;
238
  // console.log(urlAnnuaire);
239
  if ( '' !== courriel ) {
240
    $.ajax({
241
      url : urlAnnuaire,
242
      type : 'GET',
243
      success : function( data, textStatus, jqXHR ) {
244
        if ( lthis.debug ) {
245
          console.log( 'SUCCESS: ' + textStatus );
246
        }
247
        if ( undefined != data && undefined != data[courriel] ) {
248
          var infos = data[courriel];
249
          lthis.surSuccesCompletionCourriel( infos, courriel );
250
        } else {
251
          lthis.surErreurCompletionCourriel();
252
        }
253
      },
254
      error : function( jqXHR, textStatus, errorThrown ) {
255
        if ( lthis.debug ) {
256
          console.log( 'ERREUR: '+ textStatus );
257
        }
258
        lthis.surErreurCompletionCourriel();
259
      },
260
      complete : function( jqXHR, textStatus ) {
261
        if ( lthis.debug ) {
262
          console.log( 'COMPLETE: '+ textStatus );
263
        }
264
      }
265
    });
266
  }
3120 delphine 267
};
268
 
3208 idir 269
WidgetSaisie.prototype.surSuccesCompletionCourriel = function( infos, courriel ) {
270
  $( '#zone-courriel' ).before( '<p class="warning"><i class="fas fa-exclamation-triangle"></i> Un compte existe pour ce courriel, connectez-vous pour saisir votre observation</p>' );
3217 idir 271
  $( '#bouton-inscription, #zone-prenom-nom, #zone-courriel-confirmation' ).addClass( 'hidden' );
272
  $( '#prenom, #nom, #courriel_confirmation' ).attr( 'disabled', 'disabled' );
3208 idir 273
  $( '#bouton-connexion a' ).css( 'box-shadow', '0 0 1.5px 1px red' );
274
  // // Traité par auth.js :
275
  // $( '#id_utilisateur' ).val(infos.id);
276
  // // console.log(infos);
277
  // $( '#prenom' ).val(infos.prenom);
278
  // $( '#nom' ).val(infos.nom);
279
  // $( '#courriel_confirmation' ).val(courriel);
280
  // this.focusChampFormulaire();
281
  // // todo function masquerPanneau
282
  // this.masquerPanneau( '#dialogue-courriel-introuvable' );
3120 delphine 283
};
284
 
285
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
3208 idir 286
  $( '#creation-compte, #zone-prenom-nom, #zone-courriel-confirmation' ).removeClass( 'hidden' );
287
  $( '.warning' ).remove();
288
  $( '#bouton-connexion a' ).css( 'box-shadow', '' );
289
 
290
  $( '#prenom, #nom, #courriel_confirmation' ).val( '' );
291
  $( '#prenom, #nom, #courriel_confirmation' ).removeAttr( 'disabled' );
292
  // // Traité par auth.js :
293
  // // todo function afficherPanneau
294
  // this.afficherPanneau( '#dialogue-courriel-introuvable' );
3120 delphine 295
};
296
 
3208 idir 297
WidgetSaisie.prototype.fermerPanneauAlert = function() {
298
  $( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
299
};
300
 
3120 delphine 301
WidgetSaisie.prototype.formaterNom = function() {
3208 idir 302
  $( this ).val( $( this ).val().toUpperCase() );
3120 delphine 303
};
304
 
305
WidgetSaisie.prototype.formaterPrenom = function() {
3208 idir 306
  var prenom = new Array(),
307
      mots = $( this ).val().split( ' ' ),
308
      motsLength = mots.length;
309
 
310
 
311
  for ( var i = 0; i < motsLength; i++ ) {
312
    var mot = mots[i];
313
 
314
    if ( 0 <= mot.indexOf( '-' ) ) {
315
      var prenomCompose = new Array(),
316
          motsComposes = mot.split( '-' )
317
          motsComposesLength = motsComposes.length;
318
 
319
        for ( var j = 0; j < motsComposesLength; j++ ) {
320
          var motSimple = motsComposes[j],
321
              motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
322
 
323
          prenomCompose.push( motMajuscule );
324
        }
325
        prenom.push( prenomCompose.join( '-' ) );
326
    } else {
327
      var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
328
 
329
      prenom.push( motMajuscule );
330
    }
331
  }
332
  $( this ).val( prenom.join( ' ' ) );
3120 delphine 333
};
334
 
335
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
3208 idir 336
  this.afficherPanneau( '#dialogue-bloquer-copier-coller' );
337
  return false;
3120 delphine 338
};
339
 
3208 idir 340
/**
341
 * Ajoute une observation saisie dans le formulaire à la liste des observations à transmettre
342
 */
343
WidgetSaisie.prototype.ajouterObs = function() {
344
  // Fermeture automatique des dialogue de transmission de données
345
  // @WARNING TEST
346
  $( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
347
  $( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
348
 
349
  if ( this.validerFormulaire() ) {
350
    this.masquerPanneau( '#dialogue-form-invalide' );
351
    this.obsNbre = this.obsNbre + 1;
352
    $( '.obs-nbre' ).text( this.obsNbre );
353
    $( '.obs-nbre' ).triggerHandler( 'changement' );
354
    this.afficherObs();
355
    this.stockerObsData();
356
    this.supprimerMiniatures();
357
    if( !this.especeImposee ) {
358
      $( '#taxon' ).val( '' );
359
      $( '#taxon' ).data( 'numNomSel', undefined );
360
    }
361
    $( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre );
362
    $( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' observations transmises' );
363
  } else {
364
    this.afficherPanneau( '#dialogue-form-invalide' );
365
  }
3120 delphine 366
};
367
 
3208 idir 368
/**
369
 * Affiche une observation dans la liste des observations à transmettre
370
 */
371
WidgetSaisie.prototype.afficherObs = function() {
372
 
373
  // var commune = $( '#commune-nom' ).text();
374
  // commune = ( '' !== commune.trim() ) ? commune : $( '#carte-recherche' ).val();
375
 
376
  // var code_insee = $('#commune-code-insee').text();
377
  // code_insee = ( '' !== code_insee.trim() ) ? '(' + code_insee + ')' : '';
378
 
379
  // if ( this.debug ) {
380
  //   console.log( commune + '  -  ' + code_insee );
381
  // }
382
 
383
  $( '#liste-obs' ).prepend(
384
    '<div id="obs' + this.obsNbre + '" class="obs obs' + this.obsNbre + ' mb-2">'+
385
 
386
      '<div '+
387
        'class="obs-action droite" '+
388
        'title="Supprimer cette observation de la liste à transmettre"'+
389
      '>'+
390
        '<button class="btn btn-danger supprimer-obs" value="'+ this.obsNbre + '" title="Observation n°' + this.obsNbre + '">'+
391
          '<i class="far fa-trash-alt"></i>'+
392
        '</button>'+
393
      '</div> '+
394
 
395
      '<div class="row">'+
396
        '<div class="thumbnail col-md-2">'+
397
          this.ajouterImgMiniatureAuTransfert()+
398
        '</div>'+
399
        '<div class="col-md-9">'+
400
          '<ul class="unstyled">'+
401
            '<li>'+
402
              '<span class="nom-sci">' + $( '#taxon' ).val() + '</span> '+
403
              this.ajouterNumNomSel() + '<span class="referentiel-obs">'+
404
              ( ( undefined == $('#taxon').data( 'numNomSel' ) ) ? '' : '[' + this.nomSciReferentiel + ']' ) + '</span>'+
405
              // ' observé à '+
406
              // '<span class="commune">' + commune + '</span> '+
407
              // code_insee + ' [' + $( '#latitude' ).val() + ' / ' + $( '#longitude' ).val() + ']'+
408
              // ' le '+
409
              // '<span class="date">' + $( '#date' ).val() + '</span>'+
410
            '</li>'+
411
            '<li>'+
412
            //   '<span>Lieu-dit :</span> ' + $( '#lieudit' ).val() + ' '+
413
            //   '<span>Station :</span> ' + $( '#station' ).val() + ' '+
414
              '<span>Milieu :</span> '+ $ ( '#milieu' ).val() + ' '+
415
            '</li>'+
416
            // '<li>'+
417
            //   'Commentaires : <span class="discretion">' + $( '#notes' ).val() + '</span>'+
418
            // '</li>'+
419
          '</ul>'+
420
        '</div>'+
421
      '</div>'+
422
 
423
    '</div>'
424
  );
425
 
426
  $( '#zone-liste-obs' ).removeClass( 'hidden' );
427
};
428
 
429
WidgetSaisie.prototype.stockerObsData = function() {
430
  var lthis = this;
431
 
432
  // var commune = $( '#commune-nom' ).text();
433
  // commune = ( '' === commune.trim() ) ? commune : $( '#carte-recherche' ).val();
434
 
435
  $( '#liste-obs' ).data( 'obsId' + this.obsNbre, {
436
    'date' : $( '#date' ).val(),
437
    // 'notes' : $( '#notes' ).val().trim(),
438
    'nom_sel' : $( '#taxon' ).val(),
439
    'num_nom_sel' : $( '#taxon' ).data( 'numNomSel' ),
440
    'nom_ret' : $( '#taxon' ).data( 'nomRet' ),
441
    'num_nom_ret' : $( '#taxon' ).data( 'numNomRet' ),
442
    'num_taxon' : $( '#taxon' ).data( 'nt' ),
443
    'famille' : $( '#taxon' ).data( 'famille' ),
444
    'referentiel' : ( ( undefined === $( '#taxon' ).data( 'numNomSel' ) ) ? '' : lthis.nomSciReferentiel ),
445
    // 'latitude' : $( '#latitude' ).val(),
446
    // 'longitude' : $( '#longitude' ).val(),
447
    // 'commune_nom' : commune,
448
    // 'commune_code_insee' : $( '#commune-code-insee' ).text(),
449
    // 'lieudit' : $( '#lieudit' ).val(),
450
    // 'station' : $( '#station' ).val(),
451
    'milieu' : $( '#milieu' ).val(),
452
 
453
    //Ajout des champs images
454
    'image_nom' : lthis.getNomsImgsOriginales(),
455
    'image_b64' : lthis.getB64ImgsOriginales(),
456
 
457
    // Ajout des champs étendus de l'obs
458
    'obs_etendue': lthis.getObsChpEtendus()
459
  });
460
};
461
 
462
/**
463
 * Retourne un Array contenant les valeurs des champs étendus
464
 */
465
WidgetSaisie.prototype.getObsChpEtendus = function() {
466
  var champs = [],
467
      $thisForm = $( '#form-supp' ),
468
      elements =
469
        'input[type=text]:not(.collect-other),'+
470
        'input[type=checkbox]:checked,'+
471
        'input[type=radio]:checked,'+
472
        'input[type=email],'+
473
        'input[type=number],'+
474
        'input[type=range]'+
475
        'input[type=date],'+
476
        'textarea,'+
477
        'select';
478
 
479
  $( elements, $thisForm ).each( function() {
480
    var valeur = $( this ).val(),
481
        cle = $( this ).attr( 'name' ),
482
        label = $( this ).data( 'label' );
483
    if ( '' !== valeur ) {
484
      var chpEtendu = {
485
        cle: cle,
486
        label: label,
487
        valeur: valeur
488
      };
489
      champs.push( chpEtendu );
490
    }
491
  });
492
  return champs;
493
};
494
 
495
WidgetSaisie.prototype.surChangementReferentiel = function() {
496
  this.nomSciReferentiel = $( '#referentiel' ).val();
497
  $( '#taxon' ).val( '' );
498
  this.initialiserAutocompleteCommune();
499
  this.initialiserGoogleMap( false );
500
};
501
 
502
WidgetSaisie.prototype.surChangementNbreObs = function() {
503
  if ( 0 === this.obsNbre ) {
504
    $( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
505
    $( '#ajouter-obs' ).removeAttr( 'disabled' );
506
  } else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
507
    $( '#transmettre-obs' ).removeAttr( 'disabled' );
508
    $( '#ajouter-obs' ).removeAttr( 'disabled' );
509
  } else if ( this.obsNbre >= this.obsMaxNbre ) {
510
    $( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
511
    this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
512
  }
513
};
514
 
515
WidgetSaisie.prototype.transmettreObs = function() {
516
  var observations = $( '#liste-obs' ).data();
517
  if ( this.debug ) {
518
    console.log( observations );
519
  }
520
  if ( undefined == observations  || jQuery.isEmptyObject( observations ) ) {
521
    this.afficherPanneau( '#dialogue-zero-obs' );
522
  } else {
523
    this.nbObsEnCours = 1;
524
    this.nbObsTransmises = 0;
525
    this.totalObsATransmettre = $.map( observations, function( n, i ) {
526
      return i;
527
    }).length;
528
    this.depilerObsPourEnvoi();
529
  }
530
  return false;
531
};
532
 
533
WidgetSaisie.prototype.depilerObsPourEnvoi = function() {
534
  var observations = $( '#liste-obs' ).data();
535
  // la boucle est factice car on utilise un tableau
536
  // dont on a besoin de n'extraire que le premier élément
537
  // or javascript n'a pas de méthode cross browsers pour extraire les clés
538
  // TODO: utiliser var.keys quand ça sera plus répandu
539
  // ou bien utiliser un vrai tableau et pas un objet
540
  for ( var obsNum in observations ) {
541
    var obsATransmettre = {
542
      'projet' : this.tagProjet,
543
      'tag-obs' : this.tagObs,
544
      'tag-img' : this.tagImg
545
    };
546
    var utilisateur = {
547
      id_utilisateur : $( '#id_utilisateur' ).val(),
548
      prenom : $( '#prenom' ).val(),
549
      nom : $( '#nom' ).val(),
550
      courriel : $( '#courriel' ).val()
551
    };
552
    obsATransmettre['utilisateur'] = utilisateur;
553
    obsATransmettre[obsNum] = observations[obsNum];
554
    var idObsNumerique = obsNum.replace( 'obsId', '' );
555
    if( '' !== idObsNumerique ) {
556
      this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
557
    }
558
    break;
559
  }
560
};
561
 
562
WidgetSaisie.prototype.envoyerObsAuCel = function( idObs, observation ) {
563
  var lthis = this;
564
  var erreurMsg = '';
565
  $.ajax({
566
    url : lthis.serviceSaisieUrl,
567
    type : 'POST',
568
    data : observation,
569
    dataType : 'json',
570
    beforeSend : function() {
571
      $( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
572
      $( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
573
      $( '.alert-txt' ).empty();
574
      $( '.alert-txt .msg-erreur' ).remove();
575
      $( '.alert-txt .msg-debug' ).remove();
576
      $( '#chargement' ).removeClass( 'hidden' );
577
    },
578
    success : function( data, textStatus, jqXHR ) {
579
      // mise à jour du nombre d'obs à transmettre
580
      // et suppression de l'obs
581
      lthis.supprimerObsParId( idObs );
582
      lthis.nbObsEnCours++;
583
      // mise à jour du statut
584
      lthis.mettreAJourProgression();
585
      if( 0 < lthis.obsNbre ) {
586
        // dépilement de la suivante
587
        lthis.depilerObsPourEnvoi();
588
      }
589
    },
590
    statusCode : {
591
      500 : function( jqXHR, textStatus, errorThrown ) {
592
        erreurMsg += 'Erreur 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
593
        }
594
    },
595
    error : function( jqXHR, textStatus, errorThrown ) {
596
      erreurMsg += 'Erreur Ajax :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
597
      try {
598
        reponse = jQuery.parseJSON( jqXHR.responseText );
599
        if ( null !== reponse ) {
600
          $.each( reponse, function( cle, valeur ) {
601
            erreurMsg += valeur + '\n';
602
          });
603
        }
604
      } catch( e ) {
605
        erreurMsg += 'Erreur inconnue: ' + jqXHR.responseText;
606
      }
607
    },
608
    complete : function( jqXHR, textStatus ) {
609
      var debugMsg = extraireEnteteDebug( jqXHR );
610
 
611
      if ( '' !== erreurMsg ) {
612
        if ( this.debug ) {
613
          $( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
614
          $( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
615
        }
616
        var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
617
          'subject=Dysfonctionnement du widget de saisie ' + this.tagProjet+
618
          '&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
619
 
620
        // mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
621
        $( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
622
        window.location.hash = 'obs' + idObs;
623
 
624
        $( '#dialogue-obs-transaction-ko .alert-txt' ).append( $( '#tpl-transmission-ko' ).clone()
625
          .find( '.courriel-erreur' )
626
          .attr( 'href', hrefCourriel )
627
          .end()
628
          .html()
629
        );
630
        $( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
631
        $( '#chargement' ).addClass( 'hidden' );
632
        lthis.initialiserBarreProgression();
633
      } else {
634
        if ( lthis.debug ) {
635
          $( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
636
        }
637
        if( 0 === lthis.obsNbre ) {
638
          setTimeout( function() {
639
            $( '#chargement' ).addClass( 'hidden' );
640
            $( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html());
641
            $( '#dialogue-obs-transaction-ok' ).removeClass( 'hidden' );
642
            window.location.hash = 'dialogue-obs-transaction-ok';
643
            lthis.initialiserObs();
644
          }, 1500 );
645
 
646
        }
647
      }
648
    }
649
  });
650
};
651
 
652
WidgetSaisie.prototype.mettreAJourProgression = function() {
653
  this.nbObsTransmises++;
654
  var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
655
  $( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
656
  $( '#barre-progression-upload' ).attr( 'style', 'width: ' + pct + '%' );
657
  $( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' observations transmises' );
658
 
659
  if( 0 === this.obsNbre ) {
660
    $( '.progress' ).removeClass( 'active' );
661
    $( '.progress' ).removeClass( 'progress-striped' );
662
  }
663
};
664
 
665
WidgetSaisie.prototype.validerFormulaire = function() {
666
  observateur = $( '#form-observateur' ).valid();
667
  // station = $( '#form-station' ).valid();
668
  obs = ( '' !== $( '#nom-complet' ).text() || ( $( '#form-observation' ).valid() && !$( '#anonyme' ).hasClass( 'hidden' ) ) ) ? true : false;
669
  ( obs ) ? this.masquerPanneau( '#dialogue-utilisateur-non-identifie' ) : this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
670
 
671
  return ( observateur /*&& station */&& obs ) ? true : false;
672
};
673
 
674
WidgetSaisie.prototype.getNomsImgsOriginales = function() {
675
  var noms = new Array();
676
  $( '.miniature-img' ).each( function() {
677
    noms.push( $( this ).attr( 'alt' ) );
678
  });
679
  return noms;
680
};
681
 
682
WidgetSaisie.prototype.getB64ImgsOriginales = function() {
683
  var b64 = new Array();
684
  $( '.miniature-img' ).each( function() {
685
    if ( $( this ).hasClass( 'b64' ) ) {
686
      b64.push( $( this ).attr( 'src' ) );
687
    } else if ( $( this ).hasClass( 'b64-canvas' ) ) {
688
      b64.push( $( this ).data( 'b64' ) );
689
    }
690
  });
691
  return b64;
692
};
693
 
694
WidgetSaisie.prototype.supprimerObs = function( selector ) {
695
  var obsId = $( selector ).val();
696
  // Problème avec IE 6 et 7
697
  if ( 'Supprimer' === obsId ) {
698
    obsId = $( selector ).attr( 'title' );
699
  }
700
  this.supprimerObsParId( obsId );
701
};
702
 
703
WidgetSaisie.prototype.supprimerObsParId = function( obsId ) {
704
  this.obsNbre = this.obsNbre - 1;
705
  $( '.obs-nbre' ).text( this.obsNbre );
706
  $( '.obs-nbre' ).triggerHandler( 'changement' );
707
  $( '.obs' + obsId ).remove();
708
  $( '#liste-obs' ).removeData( 'obsId' + obsId );
709
};
710
 
711
WidgetSaisie.prototype.initialiserBarreProgression = function() {
712
  $( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
713
  $( '#barre-progression-upload' ).attr( 'style', 'width: 0%' );
714
  $( '#barre-progression-upload .sr-only' ).text( '0/0 observations transmises' );
715
  $( '.progress' ).addClass( 'active' );
716
  $( '.progress' ).addClass( 'progress-striped' );
717
};
718
 
719
WidgetSaisie.prototype.initialiserObs = function() {
720
  this.obsNbre = 0;
721
  this.nbObsTransmises = 0;
722
  this.nbObsEnCours = 0;
723
  this.totalObsATransmettre = 0;
724
  this.initialiserBarreProgression();
725
  $( '.obs-nbre' ).text( this.obsNbre );
726
  $( '.obs-nbre' ).triggerHandler( 'changement' );
727
  $( '#liste-obs' ).removeData();
728
  $( '.obs' ).remove();
729
  $( '#dialogue-bloquer-creer-obs' ).addClass( 'hidden' );
730
};
731
 
732
/**
733
 * Ajoute une boîte de miniatures avec défilement des images,
734
 * pour une obs de la liste des obs à transmettre
735
 */
736
WidgetSaisie.prototype.ajouterImgMiniatureAuTransfert = function() {
737
  var html =
738
        '<div class="defilement-miniatures">'+
739
          '<figure class="centre">'+
740
            '<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
741
          '</figure>'+
742
        '</div>',
743
      miniatures = '',
744
      premiere = true,
745
      centre = '';
746
      defilVisible = '';
747
 
748
  if ( 0 < $( '#miniatures img' ).length ) {
749
    $( '#miniatures img' ).each( function() {
750
      var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
751
      premiere = false;
752
 
753
      var css = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
754
          src = $( this ).attr( 'src' ),
755
          alt = $( this ).attr( 'alt' ),
756
          miniature = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
757
          // miniature = '<div class="' + css + ' ' + imgVisible + '"  alt="' + alt + '" style="background-image: url(' + src + ')" ></div>';
758
 
759
      miniatures += miniature;
760
    });
761
 
762
 
763
    if ( 1 === $( '#miniatures img' ).length ) {
764
      centre = 'centre';
765
      defilVisible = ' defilement-miniatures-cache';
766
    }
767
 
768
    html =
769
      '<div class="defilement-miniatures">'+
770
        '<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
771
        '<figure class="' + centre + '">'+
772
          miniatures+
773
        '</figure>'+
774
        '<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
775
      '</div>';
776
  }
777
  return html;
778
};
779
 
780
WidgetSaisie.prototype.defilerMiniatures = function( element ) {
781
 
782
 
783
  var miniatureSelectionne = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
784
  miniatureSelectionne.removeClass( 'miniature-selectionnee' );
785
  miniatureSelectionne.addClass( 'miniature-cachee' );
786
 
787
  var miniatureAffichee = miniatureSelectionne;
788
 
789
  if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
790
    if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
791
      miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
792
    } else {
793
      miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
794
    }
795
  } else {
796
    if( 0 !== miniatureSelectionne.next('.miniature').length ) {
797
      miniatureAffichee = miniatureSelectionne.next( '.miniature' );
798
    } else {
799
      miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
800
    }
801
  }
802
  miniatureAffichee.addClass( 'miniature-selectionnee' );
803
  miniatureAffichee.removeClass( 'miniature-cachee' );
804
};
805
 
806
WidgetSaisie.prototype.ajouterNumNomSel = function() {
807
  var nn = '<span class="nn">[nn' + $( '#taxon' ).data( 'numNomSel' ) + ']</span>';
808
  if ( undefined == $( '#taxon' ).data( 'numNomSel' ) ) {
809
    nn = '<span class="alert-error">[non lié au référentiel]</span>';
810
  }
811
  return nn;
812
};
813
 
814
WidgetSaisie.prototype.ajouterAutocompletionNoms = function() {
815
  var lthis = this;
816
  $( '#taxon' ).autocomplete({
817
    source: function( requete, add ) {
818
      // la variable de requête doit être vidée car sinon le parametre "term" est ajouté
819
      requete = '';
820
      if( 'autre' !== $( '#referentiel' ).val() ) {
821
        var url = lthis.getUrlAutocompletionNomsSci();
822
        $.getJSON( url, requete, function( data ) {
823
          var suggestions = lthis.traiterRetourNomsSci( data );
824
          add( suggestions );
825
        });
826
      }
827
    },
828
    html: true
829
  });
830
 
831
  $( '#taxon' ).bind( 'autocompleteselect', this.surAutocompletionTaxon );
832
};
833
 
3217 idir 834
// /* auto completion nom sci */
835
// WidgetSaisie.prototype.ajouterAutocompletionNoms = function() {
836
//   var lthis = this;
837
//   $( '#taxon' ).autocomplete({
838
//     source: function( requete, add ) {
839
//       // la variable de requête doit être vidée car sinon le parametre 'term' est ajouté
840
//       requete = '';
841
//       if( 'autre' !== $( '#referentiel' ).val() ) {
842
//         var url = lthis.getUrlAutocompletionNomsSci();
843
//         // console.log( url );
844
//         $.getJSON( url, requete, function( data ) {
845
//           var suggestions = lthis.traiterRetourNomsSci( data );
846
//           add( suggestions );
847
//         });
848
//       }
849
//     },
850
//     html: true,
851
//     position : {
852
//         my : 'top',
853
//         at : 'top'
854
//     }
855
//   });
856
 
857
//   $( '#taxon' ).bind( 'autocompleteselect', this.surAutocompletionTaxon );
858
// };
859
 
3208 idir 860
// WidgetSaisie.prototype.focusChampFormulaire = function() {
861
//  $( '#date_releve' ).focus();
862
// };
863
 
864
WidgetSaisie.prototype.chargerInfoObs = function() {
865
  var urlObs = this.serviceObsUrl + '/' + this.obsId;
866
  var lthis = this;
867
  $.ajax({
868
    url: urlObs,
869
    type: 'GET',
870
    success: function( data, textStatus, jqXHR ) {
871
      if ( undefined != data && '' !== data ) {
872
        lthis.prechargerForm( data );
873
      } else {
874
        lthis.surErreurChargementInfosObs();
875
      }
876
    },
877
    error: function( jqXHR, textStatus, errorThrown ) {
878
      lthis.surErreurChargementInfosObs();
879
    }
880
  });
881
};
882
 
883
// @TODO faire mieux que ça !
884
WidgetSaisie.prototype.surErreurChargementInfosObs = function() {
885
  alert( 'Erreur lors du chargement de l\'observation' );
886
};
887
 
888
WidgetSaisie.prototype.prechargerForm = function( data ) {
889
 
890
  $( '#milieu' ).val( data.milieu );
891
 
892
  // $( '#carte-recherche' ).val( data.zoneGeo );
893
  // $( '#commune-nom' ).text( data.zoneGeo );
894
 
895
  // if( data.hasOwnProperty( 'codeZoneGeo' ) ) {
896
  //   // TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
897
  //   $( '#commune-code-insee' ).text( data.codeZoneGeo.replace( 'INSEE-C:', '' ) );
898
  // }
899
 
900
  // if( data.hasOwnProperty( 'latitude' ) && data.hasOwnProperty( 'longitude' ) ) {
901
  //   var latLng = new google.maps.LatLng( data.latitude, data.longitude );
902
  //   this.mettreAJourMarkerPosition( latLng );
903
  //   this.marker.setPosition( latLng );
904
  //   this.map.setCenter( latLng );
905
  //   this.map.setZoom( 16 );
906
  // }
907
};
908
 
909
WidgetSaisie.prototype.configurerFormValidator = function() {
910
    var lthis = this;
911
  $.validator.addMethod(
912
    'dateCel',
913
    function ( value, element ) {
914
      return ( '' === value || ( /(^(((0[1-9]|1[0-9]|2[0-8])[\/](0[1-9]|1[012]))|((29|30|31)[\/](0[13578]|1[02]))|((29|30)[\/](0[4,6,9]|11)))[\/](19|[2-9][0-9])\d\d$)|(^29[\/]02[\/](19|[2-9][0-9])(00|04|08|12|16|20|24|28|32|36|40|44|48|52|56|60|64|68|72|76|80|84|88|92|96)$)/.test( value ) ) );
915
    },
916
    'Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.'
917
  );
918
 
919
  $.validator.addMethod(
920
      'userEmailOk',
921
      function ( value, element ) {
922
        return ( '' !== value );
923
      },
924
      ''
925
    );
926
 
927
  $.extend( $.validator.defaults, {
928
    errorElement: 'span',
929
 
930
    onfocusout: function( element ){
931
      if ( $( element ).valid() ) {
932
        $( element ).closest( '.control-group' ).removeClass( 'error' );
933
      } else {
934
        $( element ).closest( '.control-group' ).addClass( 'error' );
935
      }
936
    },
937
    onkeyup : function( element ){
938
      if ( $( element ).valid() ) {
939
        $( element ).closest( '.control-group' ).removeClass( 'error' );
940
      } else {
941
        $( element ).closest( '.control-group' ).addClass( 'error' );
942
      }
943
    },
944
    onclick : function( element ){
945
      if ( $( element ).valid() ) {
946
        $( element ).closest( '.control-group' ).removeClass( 'error' );
947
      } else {
948
        $( element ).closest( '.control-group' ).addClass( 'error' );
949
      }
950
    },
951
 
952
    highlight: function( element ) {
953
      $( element ).closest( '.control-group' ).addClass( 'error' );
954
    },
955
 
956
    unhighlight: function( element ) {
957
      if ( 'taxon' === $( element ).attr( 'id' ) ) {
958
        if ( '' !== $( '#taxon' ).val() ) {
959
          // Si le taxon n'est pas lié au référentiel, on vide le data associé
960
          if ( $( '#taxon' ).data( 'value' ) != $( '#taxon' ).val() ) {
961
            $( '#taxon' ).data( 'numNomSel', '' );
962
            $( '#taxon' ).data( 'nomRet','' );
963
            $( '#taxon' ).data( 'numNomRet', '' );
964
            $( '#taxon' ).data( 'nt', '' );
965
            $( '#taxon' ).data( 'famille', '' );
966
          }
967
          $( '#taxon-input-groupe' ).removeClass( 'error' );
968
          $( element ).next( 'span.help-inline' ).remove();
969
        }
970
      } else {
971
        $( element ).closest( '.control-group' ).removeClass( 'error' );
972
        $( element ).next( 'span.help-inline' ).remove();
973
      }
974
    }
975
 
976
  });
977
};
978
 
979
WidgetSaisie.prototype.definirReglesFormValidator = function() {
980
 
981
  $( '#form-observateur' ).validate({
982
    rules : {
983
      courriel : {
984
        required : true,
985
        email : true,
986
        'userEmailOk' : true
987
      },
988
      courriel_confirmation : {
989
        required : true,
990
        equalTo : '#courriel'
991
      }
992
    }
993
  });
994
  // $( '#form-station' ).validate({
995
  //   rules: {
996
  //     latitude : {
997
  //       range: [-90, 90]
998
  //     },
999
  //     longitude : {
1000
  //       range: [-180, 180]
1001
  //     }
1002
  //   }
1003
  // });
1004
  $( '#form-observation' ).validate({
1005
    rules : {
1006
      date_releve : {
1007
        required : true,
1008
        'dateCel' : true
1009
      },
1010
      taxon : 'required'
1011
    }
1012
  });
1013
};
1014
 
3120 delphine 1015
/* calendrier */
3208 idir 1016
WidgetSaisie.prototype.configurerDatePicker = function( selector ) {
1017
  $.datepicker.setDefaults( $.datepicker.regional[ this.langue ] );
1018
  $( selector ).datepicker({
1019
    dateFormat: 'dd/mm/yy',
1020
    maxDate: new Date,
1021
    onSelect: function( date ) {
1022
      $( this ).valid();
1023
    }
1024
  });
1025
  $( selector + ' + img.ui-datepicker-trigger' ).appendTo( selector + '-icone.add-on' );
3120 delphine 1026
};
1027
 
3208 idir 1028
WidgetSaisie.prototype.surAutocompletionTaxon = function( event, ui ) {
1029
  $( '#taxon' ).data( ui.item );
1030
  if ( ui.item.retenu ) {
1031
    $( '#taxon' ).addClass( 'ns-retenu' );
1032
  } else {
1033
    $( '#taxon' ).removeClass( 'ns-retenu' );
1034
  }
3120 delphine 1035
};
1036
 
1037
WidgetSaisie.prototype.getUrlAutocompletionNomsSci = function() {
3208 idir 1038
  var mots = $( '#taxon' ).val();
1039
  var url = this.serviceAutocompletionNomSciUrlTpl.replace( '{referentiel}', this.nomSciReferentiel );
1040
  url = url.replace( '{masque}', mots );
1041
  return url;
3120 delphine 1042
};
1043
 
3208 idir 1044
WidgetSaisie.prototype.traiterRetourNomsSci = function( data ) {
1045
  var suggestions = [];
1046
  if ( undefined != data.resultat ) {
1047
    $.each( data.resultat, function( i, val ) {
1048
      val.nn = i;
1049
      var nom = {
1050
        label : '',
1051
        value : '',
1052
        nt : '',
1053
        nomSel : '',
1054
        nomSelComplet : '',
1055
        numNomSel : '',
1056
        nomRet : '',
1057
        numNomRet : '',
1058
        famille : '',
1059
        retenu : false
1060
      };
1061
      if ( suggestions.length >= this.autocompletionElementsNbre ) {
1062
        nom.label = '...';
1063
        nom.value = $( '#taxon' ).val();
1064
        suggestions.push( nom );
1065
        return false;
1066
      } else {
1067
        nom.label = val.nom_sci_complet;
1068
        nom.value = val.nom_sci_complet;
1069
        nom.nt = val.num_taxonomique;
1070
        nom.nomSel = val.nom_sci;
1071
        nom.nomSelComplet = val.nom_sci_complet;
1072
        nom.numNomSel = val.nn;
1073
        nom.nomRet = val.nom_retenu_complet;
1074
        nom.numNomRet = val['nom_retenu.id'];
1075
        nom.famille = val.famille;
1076
        // Tester dans ce sens, permet de considérer 'absent' comme 'false' => est-ce opportun ?
1077
        // en tout cas c'est harmonisé avec le CeL
1078
        nom.retenu = ( 'true' == val.retenu ) ? true : false;
3120 delphine 1079
 
3208 idir 1080
        suggestions.push( nom );
1081
      }
1082
    });
1083
  }
3120 delphine 1084
 
3208 idir 1085
  return suggestions;
3120 delphine 1086
};
1087
 
3208 idir 1088
WidgetSaisie.prototype.afficherPanneau = function( selecteur ) {
1089
  $( selecteur )
1090
    .removeClass( 'hidden')
1091
    .hide()
1092
    .show( 600 )
1093
    .delay( this.dureeMessage )
1094
    .hide( 600 );
3120 delphine 1095
};
1096
 
3208 idir 1097
WidgetSaisie.prototype.masquerPanneau = function( selecteur ) {
1098
  $( selecteur ).addClass( 'hidden' );
1099
};
1100
 
1101
// lib hors objet --
1102
 
1103
/**
1104
* Stope l'évènement courant quand on clique sur un lien.
1105
* Utile pour Chrome, Safari...
1106
*/
1107
function arreter( evenement ) {
1108
  if ( evenement.stopPropagation ) {
1109
    evenement.stopPropagation();
1110
  }
1111
  if ( evenement.preventDefault ) {
1112
    evenement.preventDefault();
1113
  }
1114
  return false;
1115
}
1116
 
1117
/**
1118
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1119
 * @param jqXHR
1120
 * @returns {String}
1121
 */
1122
function extraireEnteteDebug( jqXHR ) {
1123
  var msgDebug = '';
1124
  if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
1125
    var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
1126
    if ( null !== debugInfos ) {
1127
      $.each( debugInfos, function( cle, valeur ) {
1128
        msgDebug += valeur + '\n';
1129
      });
1130
    }
1131
  }
1132
  return msgDebug;
1133
}
1134
 
1135
/*
1136
 * jQuery UI Autocomplete HTML Extension
1137
 *
1138
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1139
 * Dual licensed under the MIT or GPL Version 2 licenses.
1140
 *
1141
 * http://github.com/scottgonzalez/jquery-ui-extensions
1142
 *
1143
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1144
 */
1145
( function( $ ) {
1146
  var proto = $.ui.autocomplete.prototype,
1147
    initSource = proto._initSource;
1148
 
1149
  WidgetSaisie.prototype.filter = function( array, term ) {
1150
    var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
1151
    return $.grep( array, function( value ) {
1152
      return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
1153
    });
1154
  }
1155
 
1156
  $.extend( proto, {
1157
    _initSource: function() {
1158
      if ( this.options.html && $.isArray( this.options.source ) ) {
1159
        this.source = function( request, response ) {
1160
          response( filter( this.options.source, request.term ) );
1161
        };
1162
      } else {
1163
        initSource.call( this );
1164
      }
1165
    },
1166
    _renderItem: function( ul, item) {
1167
      if ( item.retenu ) {
1168
        item.label = '<strong>' + item.label + '</strong>';
1169
      }
1170
 
1171
      return $( '<li></li>' )
1172
        .data( 'item.autocomplete', item )
1173
        .append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
1174
        .appendTo( ul );
1175
    }
1176
  });
1177
})( jQuery );