Subversion Repositories eFlore/Applications.cel

Rev

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