Subversion Repositories eFlore/Applications.cel

Rev

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