Subversion Repositories eFlore/Applications.cel

Rev

Rev 3844 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
3638 delphine 1
"use strict";
2
 
3
function Utils(){
4
  this.cheminFichiers = $( '#zone-appli' ).data( 'url-fichiers' );
5
  // système de traduction minimaliste
6
  this.msgs                 = {
7
    fr: {
8
      'arbre'                             : 'Arbre',
9
      'dupliquer'                         : 'Dupliquer',
10
      'saisir-plantes'                    : 'Saisir les plantes',
11
      'saisir-lichens'                    : 'Saisir les lichens',
12
      'upload-non-suppote'                : 'Votre navigateur ne permet pas le téléchargement de fichiers.',
13
      'format-non-supporte'               : 'Le format de fichier n\'est pas supporté, les formats acceptés sont',
14
      'image-deja-chargee'                : 'Cette image a déjà été utilisée',
15
      'date-incomplete'                   : 'Format : jj/mm/aaaa.',
16
      'observations-transmises'           : 'observations transmises',
17
      'supprimer-observation-liste'       : 'Supprimer cette observation de la liste à transmettre',
18
      'confirmation-suppression'          : 'Êtes-vous sûr de vouloir supprimer cette observation',
19
      'milieu'                            : 'Milieu',
20
      'commentaires'                      : 'Commentaires',
21
      'non-lie-au-ref'                    : 'non lié au référentiel',
22
      'obs-le'                            : 'le',
23
      'non-connexion'                     : 'Veuillez entrer votre login et votre mot de passe',
24
      'obs-numero'                        : 'Observation n°',
25
      'erreur'                            : 'Erreur',
26
      'erreur-inconnue'                   : 'Erreur inconnue',
27
      'erreur-image'                      : 'Erreur lors du chargement des images',
28
      'erreur-ajax'                       : 'Erreur Ajax',
29
      'erreur-chargement'                 : 'Erreur lors du chargement de l\'observation',
30
      'erreur-chargement-obs-utilisateur' : 'Erreur lors du chargement des observations de cet utilisateur',
31
      'erreur-formulaire'                 : 'Erreur: impossible de charger le formulaire',
32
      'lieu-obs'                          : 'observé à',
33
      'lieu-dit'                          : 'Lieu-dit',
34
      'taxon-ou-image'                     : 'Veuillez transmettre au moins, soit une image, soit une espèce',
35
      'station'                           : 'Station',
36
      'date-rue'                          : 'Un releve existe dejà à cette date pour cette rue.',
37
      'rechargement-page'                 : 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.',
38
      'courriel-connu'                    : 'Un compte existe pour ce courriel, connectez-vous pour saisir votre observation'
39
    },
40
    en: {
41
      'arbre'                             : 'Tree',
42
      'dupliquer'                         : 'Duplicate',
43
      'saisir-plantes'                    : 'Enter the plants',
44
      'saisir-lichens'                    : 'Enter the lichens',
45
      'upload-non-suppote'                : 'Your browser does not support file upload.',
46
      'format-non-supporte'               : 'The file format is not supported, the accepted formats are',
47
      'image-deja-chargee'                : 'This image has already been used',
48
      'date-incomplete'                   : 'Format: dd/mm/yyyy.',
49
      'observations-transmises'           : 'observations transmitted',
50
      'supprimer-observation-liste'       : 'Delete this observation from the list to be transmitted',
51
      'confirmation-suppression'          : 'Are you sure you want to delete this observation',
52
      'milieu'                            : 'Environment',
53
      'commentaires'                      : 'Comments',
54
      'non-lie-au-ref'                    : 'unrelated to the referencial ',
55
      'obs-le'                            : 'the',
56
      'non-connexion'                     : 'Please enter your login and password',
57
      'obs-numero'                        : 'Observation number ',
58
      'erreur'                            : 'Error',
59
      'erreur-inconnue'                   : 'Unknown error',
60
      'erreur-image'                      : 'Error loading the images',
61
      'erreur-ajax'                       : 'Ajax Error',
62
      'erreur-chargement'                 : 'Error loading the observation',
63
      'erreur-chargement-obs-utilisateur' : 'Error loading this user\'s observations',
64
      'erreur-formulaire'                 : 'Error: couldn\'t load form',
65
      'lieu-obs'                          : 'observed at',
66
      'lieu-dit'                          : 'Locality',
67
      'taxon-ou-image'                    : 'Please transmit at least one image or one species',
68
      'station'                           : 'Place',
69
      'date-rue'                          : 'A record already exists on this date for this street',
70
      'rechargement-page'                 : 'Are you sure you want to leave the page?\nAll untransmitted observations will be lost.',
71
      'courriel-connu'                    : 'An account exists for this email, log in to enter your observation'
72
    }
73
  };
74
};
75
 
76
var lthis = Utils.prototype;
77
 
78
Utils.prototype.init = function() {
79
  // Modale "aide" du projet
80
  this.projetHelpModale();
81
  // Affichage input file
82
  this.inputFile();
83
  // Affichage des List-checkbox
84
  this.inputListCheckbox();
85
  // Affichage des Range
86
  this.inputRangeDisplayNumber()
87
  // Modale "aide"
88
  this.newFieldsHelpModal();
89
  // Ajout/suppression d'un champ texte "Autre"
90
  this.onOtherOption();
91
  // Récupérer les données entrées dans "Autre"
92
  this.collectOtherOption();
93
};
94
 
95
/**
96
* Permet à la fois de vérifier qu'une valeur ou objet existe et n'est pas vide
97
* et de comparer à une autre valeur :
98
* Vérifie qu'une variable ou objet n'est pas : vide, null, undefined, NaN
99
* Si comparer est défini on le compare à valeur en fonction de sensComparaison
100
* Un booléen est une variable valide : on retourne true
101
* @param { string || number || object || undefined } valeur
102
* @param { boolean } sensComparaison : true = rechercher, false = refuser
103
* @param { string || number || object || undefined || boolean } comparer :valeur à comparer
104
* @returns {boolean}
105
*/
106
Utils.prototype.valOk = function (valeur, sensComparaison = true, comparer = undefined ) {
107
	var retour = true;
108
	if ( 'boolean' !== typeof valeur ) {
109
		switch( typeof valeur ) {
110
			case 'string' :
111
				retour = ( '' !== valeur );
112
			 break;
113
			case 'number' :
114
					retour = ( NaN !== valeur );
115
				break;
116
			case 'object' :
117
					retour = ( null !== valeur && undefined !== valeur && !$.isEmptyObject( valeur ) );
118
					if (  null !== valeur && undefined !== valeur.length ) {
119
						retour = ( retour  && 0 < valeur.length );
120
					}
121
				break;
122
			case 'undefined' :
123
			default :
124
				retour = false;
125
		}
126
		if ( retour && comparer !== undefined ) {
127
			var resultComparaison = ( comparer === valeur );
128
			retour = ( sensComparaison ) ? resultComparaison : !resultComparaison ;
129
		}
130
 
131
		return retour;
132
 
133
	} else {
134
		// Un booléen est une valeur valable
135
		return true;
136
	}
137
};
138
 
139
/*************************************
140
 *  Fonctions de Style et Affichage  *
141
 *      des éléments "spéciaux"      *
142
 *************************************/
143
 
144
// Logique d'affichage pour le input type=file
145
Utils.prototype.inputFile = function() {
146
  // Initialisation des variables
147
  var $fileInput  = $( '.input-file' ),
148
      $button     = $( '.label-file' );
149
 
150
  // Action lorsque la "barre d'espace" ou "Entrée" est pressée
151
  $( '#formulaire' ).on( 'keydown', '.label-file', function( event ) {
152
    if ( event.keyCode == 13 || event.keyCode == 32 ) {
153
      $( '#' + $( this ).attr( 'for' ) + '.input-file' ).click();
154
    }
155
  });
156
};
157
 
158
// Style et affichage des list-checkboxes
159
Utils.prototype.inputListCheckbox = function() {
160
  // On écoute le click sur une list-checkbox ('.selectBox')
161
  // à tout moment de son insertion dans le dom
162
  // _ S'assurer de bien viser la bonne list-checkbox
163
  // _ Au click sur un autre champ remballer la list-checkbox
164
  $( document ).click( function( event ) {
165
    var target = event.target;
166
 
167
    if ( !$( target ).is( '.overSelect' ) && 0 === $( target ).closest( '.checkboxes' ).length ) {
168
      $( '.checkboxes' ).each( function () {
169
        $( this ).addClass( 'hidden' );
170
      });
171
      $( '.selectBox select.focus', '#zone-appli' ).each( function() {
172
        $( this ).removeClass( 'focus' );
173
      });
174
    }
175
  });
176
  $( '#zone-appli' ).on( 'click' , '.selectBox' , function() {
177
    // afficher/cacher le volet des checkboxes et focus
178
    $( this ).next().toggleClass( 'hidden' );
179
    $( this ).find( 'select' ).toggleClass( 'focus' );
180
 
181
    // Cacher le volet des autres checkboxes et retirer leur focus
182
    var $checkboxes = $( this ).next(),
183
        count = $( '.checkboxes' ).length;
184
 
185
    for ( var i = 0; i < count; i++ ) {
186
      if ( $( '.checkboxes' )[i] !== $checkboxes[0] && !$checkboxes.hasClass( 'hidden' ) ) {
187
        var $otherListCheckboxes = $( '.checkboxes' )[i];
188
        if ( !$otherListCheckboxes.classList.contains( 'hidden' ) ) {
189
          $otherListCheckboxes.classList.add( 'hidden' );
190
        }
191
        if( $otherListCheckboxes.previousElementSibling.firstElementChild.classList.contains( 'focus' ) ) {
192
          $otherListCheckboxes.previousElementSibling.firstElementChild.classList.remove( 'focus' );
193
        }
194
      }
195
    }
196
  });
197
};
198
 
199
// Style et affichage des input type="range"
200
Utils.prototype.inputRangeDisplayNumber = function() {
201
  $( 'input[type="range"]' ).each( function() {
202
    $( this ).siblings( '.range-live-value' ).text( $( this ).val() );
203
  });
204
  $( '#top' ).on( 'input' , 'input[type="range"]' , function () {
205
    $( this ).siblings( '.range-live-value' ).text( $( this ).val() );
206
  });
207
  $( '#top' ).on( 'click', '#ajouter-obs', function() {
208
    $( '.range-live-value' ).each( function() {
209
      var $this = $( this );
210
 
211
      $this.text( '' );
212
    });
213
  });
214
};
215
 
216
// Activation/Desactivation et contenu de la modale Bootstrap
217
// https://getbootstrap.com/docs/3.3/javascript/#modals
218
Utils.prototype.newFieldsHelpModal = function() {
219
  const lthis = this;
220
 
221
  $( '#zone-appli' ).on( 'click' , '.help-button' , function ( event ) {
222
    var thisFieldKey = $( this ).data( 'key' ),
223
        fileMimeType = $( this ).data( 'mime-type' ),
224
        label = 'Aide pour : ' +  $( this ).data( 'name' );
225
 
226
    if( fileMimeType.match( 'image' ) ) {
227
      var extention = fileMimeType.replace( /(?:imag)?e\/?/g , '' ),
228
          content = '<img id="modale-aide-img" src="' + lthis.cheminFichiers + thisFieldKey + '.' + extention + '" style="" alt="' + thisFieldKey + '" />';
229
    }
230
    lthis.activerModale( label, content );
231
  });
232
};
233
 
234
// aide dans le titre du projet
235
Utils.prototype.projetHelpModale = function() {
236
  const lthis = this;
237
 
238
  $( '#top' ).on ( 'click', '#info-button', function ( event ) {
239
    var fileMimeType = $( this ).data( 'mime-info' ),
240
        label        = 'Aide du projet : ' +  $( '#titre-projet' ).text();
241
 
242
    if( fileMimeType.match( 'image' ) ) {
243
      var extention = fileMimeType.replace( /(?:imag)?e\/?/g , '' ),
244
          content   = '<img id="modale-aide-img" src="' + lthis.cheminFichiers + 'info.' + extention + '" style="" alt="info projet" />';
245
    }
246
    lthis.activerModale( label, content );
247
  });
248
};
249
 
250
 
251
// Activation/Desactivation et contenu de la modale Bootstrap
252
// https://getbootstrap.com/docs/3.3/javascript/#modals
253
Utils.prototype.activerModale = function( label, content = '', buttons = [] ) {
254
  var dismiss         = '',
255
      buttonsHtmlBase = '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>',
256
      buttonsHtml     = buttonsHtmlBase;
257
 
258
  // Titre
259
  $( '#fenetre-modal-label' ).text( label );
260
  if ( '' !== content ) {
261
    $( '#print_content' ).append( content );
262
  }
263
  // Sortie avec la touche escape
264
  $( '#fenetre-modal' ).modal( { keyboard : true } );
265
  // Affichage
266
  $( '#fenetre-modal' ).modal({ show: true });
267
  // Remplacer l'autofocus qui ne fonctionne plus en HTML5
268
  // Message dans la doc de bootstrap :
269
  // Due to how HTML5 defines its semantics,
270
  // the autofocus HTML attribute has no effect in Bootstrap modals.
271
  // To achieve the same effect, use some custom JavaScript
272
  $( '#fenetre-modal' ).off( 'shown.bs.modal' ).on( 'shown.bs.modal' , function () {
273
    $( '#myInput' ).trigger( 'focus' );
274
    if( lthis.valOk( $( '#modale-aide-img' ) ) ) {
275
      lthis.redimentionnerImgAide();
276
      $( window ).on( 'resize', lthis.redimentionnerImgAide.bind( lthis ) );
277
    }
278
  });
279
  if ( this.valOk( buttons ) ) {
280
    buttonsHtml = '';
281
    $.each( buttons, function( i, button ) {
282
      dismiss = button.dismiss ? 'data-dismiss="modal"' : '';
283
      buttonsHtml += '<button type="button" class="btn ' + button.class + '" ' + dismiss + '>' + button.label + '</button>';
284
    });
285
  }
286
  $( '.modal-footer' ).html( buttonsHtml );
287
  // Réinitialisation
288
  $( '#fenetre-modal' ).on( 'hidden.bs.modal' , function () {
289
    $( '#confirm-modal-label' ).text();
290
    $( '#print_content' ).empty();
291
    $( '.modal-footer' ).html( buttonsHtmlBase );
292
  });
293
};
294
 
295
Utils.prototype.redimentionnerImgAide = function() {
296
  var espHorizDisp = $( '.modal-dialog' ).innerWidth() <= 1200 ? $( '.modal-dialog' ).innerWidth() - 30 : 1200,
297
      cssImg       = {
298
        'width': espHorizDisp,
299
        'height' : 'auto'
300
      };
301
 
302
  $( '#modale-aide-img' ).css(cssImg).show(50);
303
};
304
 
305
// Faire apparaitre un champ text "Autre"
306
Utils.prototype.onOtherOption = function() {
307
  const PREFIX = 'collect-other-';
308
 
309
  // Ajouter un champ texte pour "Autre"
310
  function optionAdd( otherId, $target, element, dataName, dataLabel ) {
311
    $target.after(
312
      '<div class="control-group">'+
313
        '<label'+
314
          ' for="' + otherId + '"'+
315
          ' class="' + otherId + '"'+
316
        '>'+
317
          'Autre option "' + dataLabel.toLowerCase() + '" :'+
318
        '</label>'+
319
        '<input'+
320
          ' type="text"'+
321
          ' id="' + otherId + '"'+
322
          ' name="' + otherId + '"'+
323
          ' class="collect-other form-control"'+
324
          ' data-name="' + dataName + '"'+
325
          ' data-element="' + element + '"'+
326
        '>'+
327
      '</div>'
328
    );
329
    $( '#' + otherId ).focus();
330
  }
331
 
332
  // Supprimer un champ texte pour "Autre"
333
  function optionRemove( otherId ) {
334
    $( '#' + otherId ).closest('.control-group').remove();
335
  }
336
 
337
  $( '.other', '#formulaire' ).each( function() {
338
    if( $( this ).hasClass( 'is-select' ) ) {
339
      var dataName = $( this ).data( 'name' ),
340
          otherId  = PREFIX + dataName,
341
          dataLabel = $( '.select' ).data( 'label' );
342
 
343
      // Insertion du champ "Autre" après les boutons
344
      if ( !lthis.valOk( $( '#'+otherId ) ) ) {
345
        optionAdd( otherId, $( this ).parent( '.add-field-select' ), 'select', dataName, dataLabel );
346
      }
347
    } else if ( $( this ).is( ':checked' ) ) {
348
      var dataName = $( this ).data( 'name' ),
349
          otherId  = PREFIX + dataName,
350
          element = $( this ).data( 'element' ),
351
          dataLabel = $( this ).data( 'label' );
352
 
353
      // Insertion du champ "Autre" après les boutons
354
      if ( !lthis.valOk( $( '#'+ otherId ) ) ) {
355
        optionAdd( otherId, $( this ).parent( 'label' ), element, dataName, dataLabel );
356
      }
357
    }
358
  });
359
 
360
  $( '#formulaire' ).on( 'change', '.select', function () {
361
    var dataName = $( this ).data( 'name' ),
362
        otherId  = PREFIX + dataName,
363
        dataLabel = $( this ).data( 'label' );
364
 
365
    if( 'other' === $( this ).val() ) {
366
        // Insertion du champ "Autre" après les boutons
367
        if ( !lthis.valOk( $( '#'+otherId ) ) ) {
368
          optionAdd( otherId, $( this ).parent( '.add-field-select' ), 'select', dataName, dataLabel );
369
        }
370
      } else {
371
        // Suppression du champ autre
372
        optionRemove( otherId );
373
        $( this ).find( '.other' ).val( 'other' );
374
      }
375
  });
376
 
377
  $( '#formulaire' ).on( 'change', 'input[type=radio]', function () {
378
    var dataName = $( this ).data( 'name' ),
379
        otherId  = PREFIX + dataName,
380
        dataLabel = $( this ).data( 'label' );
381
 
382
    if( 'other' === $( this ).val() ) {
383
      // Insertion du champ "Autre" après les boutons
384
      if ( !lthis.valOk( $( '#'+otherId ) ) ) {
385
        optionAdd( otherId, $( this ).parent( 'label' ), 'radio', dataName, dataLabel );
386
      }
387
    } else {
388
      // Suppression du champ autre
389
      optionRemove( otherId );
390
      $( this ).closest( '.radio' ).find( '.other' ).val( 'other' );
391
    }
392
  });
393
 
394
  $( '#formulaire' ).on( 'click', '.list-checkbox .other,.checkbox .other', function () {
395
    var dataName = $( this ).data( 'name' ),
396
        otherId  = PREFIX + dataName,
397
        element = $( this ).data( 'element' ),
398
        dataLabel = $( this ).data( 'label' );
399
 
400
    if( $( this ).is( ':checked' ) ) {
401
        // Insertion du champ "Autre" après les boutons
402
        if ( !lthis.valOk( $( '#'+otherId ) ) ) {
403
          optionAdd( otherId, $( this ).parent( 'label' ), element, dataName, dataLabel );
404
        }
405
      } else {
406
        // Suppression du champ autre
407
        optionRemove( otherId );
408
        $( this ).val( 'other' );
409
      }
410
  });
411
};
412
 
413
Utils.prototype.collectOtherOption = function() {
414
  $( '#formulaire' ).on( 'change', '.collect-other', function () {
415
    var otherIdSuffix = $( this ).data( 'name' ).replace( '[]', '' );
416
    var element = $( this ).data( 'element' );
417
 
418
    if ( '' === $( this ).val() ){
419
      if ( 'select' === element ) {
420
        $( '#' + otherIdSuffix ).find( '.other' ).prop( 'selected', false ).val( 'other' );
421
      } else {
422
        $( '#other-' + otherIdSuffix ).prop( 'checked', false ).val( 'other' );
423
      }
424
      $( 'label.collect-other-' + otherIdSuffix ).remove();
425
      $( this ).remove();
426
    } else {
427
      if ( 'select' === element ) {
428
        $( '#' +  otherIdSuffix ).find( '.other' ).val( $( this ).val() );
429
        $( '#' +  otherIdSuffix ).val( $( this ).val() );
430
        $( '#' +  otherIdSuffix + ' option').not( '.other' ).prop( 'selected', false );
431
        $( '#' +  otherIdSuffix ).find( '.other' ).prop( 'selected', true );
432
      } else {
433
        if ( 'radio' === element ) {
434
          $( 'input[name=' + otherIdSuffix + ']' ).not( '#other-' + otherIdSuffix ).prop( 'checked', false );
435
        }
436
        $( '#other-' + otherIdSuffix ).val( $( this ).val() );
437
        $( '#other-' + otherIdSuffix ).prop( 'checked', true );
438
      }
439
    }
440
  });
441
};
442