Subversion Repositories eFlore/Applications.cel

Rev

Rev 3405 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3405 delphine 1
function UtilsStreets() {
2
	// this.infosUtilisateur = null;
3
	this.langue = $( 'body' ).data( 'lang' );
4
	this.urlRacine = window.location.origin;
5
	// système de traduction minimaliste
6
	this.msgs = {
7
		fr: {
8
			'arbre'                             : 'Arbre',
9
			'dupliquer'                         : 'Dupliquer',
10
			'saisir-plantes'                    : 'Saisir les plantes',
11
			'format-non-supporte'               : 'Le format de fichier n\'est pas supporté, les formats acceptés sont',
12
			'image-deja-chargee'                : 'Cette image a déjà été utilisée',
13
			'date-incomplete'                   : 'Format : jj/mm/aaaa.',
14
			'observations-transmises'           : 'observations transmises',
15
			'supprimer-observation-liste'       : 'Supprimer cette observation de la liste à transmettre',
16
			'milieu'                            : 'Milieu',
17
			'commentaires'                      : 'Commentaires',
18
			'non-lie-au-ref'                    : 'non lié au référentiel',
19
			'obs-le'                            : 'le',
20
			'non-connexion'                     : 'Veuillez entrer votre login et votre mot de passe',
21
			'obs-numero'                        : 'Observation n°',
22
			'erreur'                            : 'Erreur',
23
			'erreur-inconnue'                   : 'Erreur inconnue',
24
			'erreur-image'                      : 'Erreur lors du chargement des images',
25
			'erreur-ajax'                       : 'Erreur Ajax',
26
			'erreur-chargement'                 : 'Erreur lors du chargement de l\'observation',
27
			'erreur-chargement-obs-utilisateur' : 'Erreur lors du chargement des observations de cet utilisateur',
28
			'erreur-formulaire'                 : 'Erreur: impossible de charger le formulaire',
29
			'lieu-obs'                          : 'observé à',
30
			'lieu-dit'                          : 'Lieu-dit',
31
			'station'                           : 'Station',
32
			'date-rue'                          : 'Un releve existe dejà à cette date pour cette rue.',
33
			'rechargement-page'                 : 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.'
34
		},
35
		en: {
36
			'arbre'                             : 'Tree',
37
			'dupliquer'                         : 'Duplicate',
38
			'saisir-plantes'                    : 'Enter the plants',
39
			'format-non-supporte'               : 'The file format is not supported, the accepted formats are',
40
			'image-deja-chargee'                : 'This image has already been used',
41
			'date-incomplete'                   : 'Format: dd/mm/yyyy.',
42
			'observations-transmises'           : 'observations transmitted',
43
			'supprimer-observation-liste'       : 'Delete this observation from the list to be transmitted',
44
			'milieu'                            : 'Environment',
45
			'commentaires'                      : 'Comments',
46
			'non-lie-au-ref'                    : 'unrelated to the referencial ',
47
			'obs-le'                            : 'the',
48
			'non-connexion'                     : 'Please enter your login and password',
49
			'obs-numero'                        : 'Observation number ',
50
			'erreur'                            : 'Error',
51
			'erreur-inconnue'                   : 'Unknown error',
52
			'erreur-image'                      : 'Error loading the images',
53
			'erreur-ajax'                       : 'Ajax Error',
54
			'erreur-chargement'                 : 'Error loading the observation',
55
			'erreur-chargement-obs-utilisateur' : 'Error loading this user\'s observations',
56
			'erreur-formulaire'                 : 'Error: couldn\'t load form',
57
			'lieu-obs'                          : 'observed at',
58
			'lieu-dit'                          : 'Locality',
59
			'station'                           : 'Place',
60
			'date-rue'                          : 'A record already exists on this date for this street',
61
			'rechargement-page'                 : 'Are you sure you want to leave the page?\nAll untransmitted observations will be lost.'
62
		}
63
	};
64
}
65
 
66
 
67
UtilsStreets.prototype.chargerForm = function( nomSquelette, streetsFormObj ) {
68
	const lthis = this;
69
	var urlSqueletteArbres = this.urlRacine + '/widget:cel:streets?squelette=' + nomSquelette;
70
 
71
	$.ajax({
72
		url: urlSqueletteArbres,
73
		type: 'get',
74
		success: function( squelette ) {
75
			if ( lthis.valOk( squelette ) ) {
76
				streetsFormObj.chargerSquelette( squelette, nomSquelette );
77
			}
78
		},
79
		error: function() {
80
			$( '#charger-form' ).html( lthis.msgTraduction( 'erreur-formulaire' ) );
81
		}
82
	});
83
};
84
 
85
UtilsStreets.prototype.chargerFormPlantes = function( squelette, nomSquelette ) {
86
	if ( this.valOk( $( '#releve-data' ).val() ) ) {
87
		$( '#charger-form' ).html( squelette );
88
		const releveDatas = $.parseJSON( $( '#releve-data' ).val() );
89
		const nbArbres    = releveDatas.length -1;
90
 
91
		for ( var i = 1; i <= nbArbres ; i++ ) {
92
			$( '#choisir-arbre' ).append(
93
				'<option value="' + i + '">'+
94
					this.msgTraduction( 'arbre' ) + ' ' + i +
95
				'</option>'
96
			);
97
		}
98
	}
99
};
100
 
101
/**
102
 * Stocke en Json les valeurs du relevé dans en value d'un input hidden
103
 */
104
UtilsStreets.prototype.formaterReleveData = function( releveDatas ) {
105
	var releve  = [],
106
		obs  = releveDatas.obs,
107
		obsE = releveDatas.obsE;
108
 
109
	releve[0] = {
110
		utilisateur        : obs.ce_utilisateur,
111
		date               : obs.date_observation,
112
		rue                : obsE.rue,
113
		'commune-nom'      : obs.zone_geo,
114
		'commune-insee'    : obs.ce_zone_geo,
115
		pays               : obs.pays,
3416 idir 116
		'latitude-releve'  : obsE['latitude-releve'],
117
		'longitude-releve' : obsE['longitude-releve'],
118
		'altitude-releve'  : obsE['altitude-releve'],
3405 delphine 119
		'zone-pietonne'    : obsE['zone-pietonne'],
120
		'pres-lampadaires' : obsE['pres-lampadaires'],
121
		commentaires       : obs.commentaire
122
	};
123
	return releve;
124
};
125
 
126
/**
127
 * Stocke en Json les valeurs d'une obs
128
 */
129
UtilsStreets.prototype.formaterArbreData = function( arbresDatas ) {
130
	var retour = {},
131
		obs          = arbresDatas.obs,
132
		obsE         = arbresDatas.obsE,
133
		miniatureImg = [];
134
	if( this.valOk( obs['miniature-img'] ) ) {
135
		miniatureImg = obs['miniature-img'];
136
	} else if ( this.valOk( obsE['miniature-img'] ) ) {
137
		miniatureImg = $.parseJSON( obsE['miniature-img'] );
138
	}
139
 
140
	retour = {
141
		'date_rue_commune'      : obs.date_observation + obsE.rue + obs.zone_geo,
142
		'num-arbre'             : obsE.num_arbre,
143
		'id_observation'        : obs.id_observation,
144
		'taxon'                 : {
145
			'numNomSel' : obs.nom_sel_nn,
146
			'value'     : obs.nom_sel,
147
			'nomRet'    : obs.nom_ret,
148
			'numNomRet' : obs.nom_ret_nn,
149
			'nt'        : obs.nt,
150
			'famille'   : obs.famille,
151
		},
152
		'miniature-img'         : miniatureImg,
153
		'referentiel'           : obs.nom_referentiel,
154
		'certitude'             : obs.certitude,
155
		'rue-arbres'            : obsE['rue-arbres'],
3416 idir 156
		'latitude-arbres'       : obs.latitude,
157
		'longitude-arbres'      : obs.longitude,
158
		'altitude-arbres'       : obs.altitude,
3405 delphine 159
		'circonference'         : obsE.circonference,
160
		'surface-pied'          : obsE['surface-pied'],
161
		'equipement-pied-arbre' : obsE['equipement-pied-arbre'],
162
		'tassement'             : obsE.tassement,
163
		'dejections'            : obsE.dejections,
164
		'com-arbres'            : obsE['com-arbres']
165
	};
166
	return retour;
167
};
168
 
169
UtilsStreets.prototype.fournirDate = function( dateObs ) {
170
	if ( /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/.test( dateObs ) ) {
171
		return dateObs;
172
	} else if ( /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test( dateObs ) ) {
173
		var dateArray = dateObs.split( '-' );
174
		return dateArray[2] + '/' + dateArray[1] + '/' + dateArray[0]
175
	} else {
176
		console.log( 'erreur date : ' + dateObs )
177
	}
178
};
179
 
180
/**
181
 * Si la langue est définie dans this.langue, et si des messages sont définis
182
 * dans this.msgs, tente de trouver le message dont la clé est [cle] dans la
183
 * langue en cours. S'il n'est pas trouvé, retourne la version française (par
184
 * défaut); si celle-ci n'exite pas, retourne "N/A".
185
 */
186
UtilsStreets.prototype.msgTraduction = function( cle ) {
187
	var msg = 'N/A';
188
 
189
	if ( this.msgs ) {
190
		if ( this.langue in this.msgs && cle in this.msgs[this.langue] ) {
191
			msg = this.msgs[this.langue][cle];
192
		} else if ( cle in this.msgs['fr'] ) {
193
			msg = this.msgs['fr'][cle];
194
		}
195
	}
196
	return msg;
197
};
198
 
199
/**
200
* Permet à la fois de vérifier qu'une valeur ou objet existe et n'est pas vide
201
* et de comparer à une autre valeur :
202
* Vérifie qu'une variable ou objet n'est pas : vide, null, undefined, NaN
203
* Si comparer est défini on le compare à valeur en fonction de sensComparaison
204
* Un booléen est une variable valide : on retourne true
205
* @param { string || number || object || undefined } valeur
206
* @param { boolean } sensComparaison : true = rechercher, false = refuser
207
* @param { string || number || object || undefined || boolean } comparer :valeur à comparer
208
* @returns {boolean}
209
*/
210
UtilsStreets.prototype.valOk = function( valeur, sensComparaison = true, comparer = undefined ) {
211
	var retour = true;
212
	if ( 'boolean' !== typeof valeur ) {
213
		switch( typeof valeur ) {
214
			case 'string' :
215
				retour = ( '' !== valeur );
216
			 break;
217
			case 'number' :
218
					retour = ( NaN !== valeur );
219
				break;
220
			case 'object' :
221
					retour = ( null !== valeur && undefined !== valeur && !$.isEmptyObject( valeur ) );
222
					if (  null !== valeur && undefined !== valeur.length ) {
223
						retour = ( retour  && 0 < valeur.length );
224
					}
225
				break;
226
			case 'undefined' :
227
			default :
228
				retour = false;
229
		}
230
		if ( retour && comparer !== undefined ) {
231
			var resultComparaison = ( comparer === valeur );
232
			retour = ( sensComparaison ) ? resultComparaison : !resultComparaison ;
233
		}
234
 
235
		return retour;
236
	} else {
237
		// Un booléen est une valeur valable
238
		return true;
239
	}
240
}
241
 
242
// Lib hors objet
243
 
244
/*************************************
245
 *  Fonctions de Style et Affichage  *
246
 *      des éléments "spéciaux"      *
247
 *************************************/
248
 
249
// Logique d'affichage pour le input type=file
250
function inputFile() {
251
  // Initialisation des variables
252
  var $fileInput  = $( '.input-file' ),
253
      $button     = $( '.label-file' );
254
  // Action lorsque la "barre d'espace" ou "Entrée" est pressée
255
  $( '#charger-form' ).on( 'keydown', '.label-file', function( event ) {
256
    if ( event.keyCode == 13 || event.keyCode == 32 ) {
257
      $( '#' + $( this ).attr( 'for' ) + '.input-file' ).click();
258
    }
259
  });
260
}
261
 
262
// Style et affichage des list-checkboxes
263
function inputListCheckbox() {
264
  // On écoute le click sur une list-checkbox ('.selectBox')
265
  // à tout moment de son insertion dans le dom
266
  // _ S'assurer de bien viser la bonne list-checkbox
267
  // _ Au click sur un autre champ remballer la list-checkbox
268
  $( document ).click( function( event ) {
269
    var target = event.target;
270
 
271
    if ( !$( target ).is( '.overSelect' ) && 0 === $( target ).closest( '.checkboxes' ).length ) {
272
      $( '.checkboxes' ).each( function () {
273
        $( this ).addClass( 'hidden' );
274
      });
275
      $( '.selectBox select.focus', '#zone-appli' ).each( function() {
276
        $( this ).removeClass( 'focus' );
277
      });
278
    }
279
  });
280
  $( '#zone-appli' ).on( 'click' , '.selectBox' , function() {
281
    // afficher/cacher le volet des checkboxes et focus
282
    $( this ).next().toggleClass( 'hidden' );
283
    $( this ).find( 'select' ).toggleClass( 'focus' );
284
 
285
    // Cacher le volet des autres checkboxes et retirer leur focus
286
    var $checkboxes = $( this ).next(),
287
        count = $( '.checkboxes' ).length;
288
 
289
    for ( var i = 0; i < count; i++ ) {
290
      if ( $( '.checkboxes' )[i] !== $checkboxes[0] && !$checkboxes.hasClass( 'hidden' ) ) {
291
        var $otherListCheckboxes = $( '.checkboxes' )[i];
292
        if ( !$otherListCheckboxes.classList.contains( 'hidden' ) ) {
293
          $otherListCheckboxes.classList.add( 'hidden' );
294
        }
295
        if( $otherListCheckboxes.previousElementSibling.firstElementChild.classList.contains( 'focus' ) ) {
296
          $otherListCheckboxes.previousElementSibling.firstElementChild.classList.remove( 'focus' );
297
        }
298
      }
299
    }
300
  });
301
}
302
 
303
// Style et affichage des input type="range"
304
function inputRangeDisplayNumber() {
305
  $( 'input[type="range"]','#charger-form' ).each( function() {
306
    $( this ).siblings( '.range-live-value' ).text( $( this ).val() );
307
  });
308
  $( '#top' ).on( 'input' , 'input[type="range"]' , function () {
309
    $( this ).siblings( '.range-live-value' ).text( $( this ).val() );
310
  });
311
  $( '#top' ).on( 'click', '#ajouter-obs', function() {
312
    $( '.range-live-value' ).each( function() {
313
      var $this = $( this );
314
      $this.text( '' );
315
    });
316
  });
317
}
318
 
319
// Activation/Desactivation et contenu de la modale Bootstrap
320
// https://getbootstrap.com/docs/3.3/javascript/#modals
321
function newFieldsHelpModal() {
322
  $( '#zone-appli' ).on( 'click' , '.help-button' , function ( event ) {
323
    var thisFieldKey = $( this ).data( 'key' ),
324
        fileMimeType = $( this ).data( 'mime-type' );
325
 
326
    // Titre
327
    $( '#help-modal-label' ).text( 'Aide pour : ' +  $( this ).data( 'name' ) );
328
    if( fileMimeType.match( 'image' ) ) {
329
      var extention = fileMimeType.replace( /(?:imag)?e\/?/g , '' );
330
      // var extention = 'jpg';
331
      $( '#print_content' ).append( '<img src="' + CHEMIN_FICHIERS + thisFieldKey + '.' + extention + '" style="max-width:100%" alt="' + thisFieldKey + '" />' );
332
    }
333
    // Sortie avec la touche escape
334
    $( '#help-modal' ).modal( { keyboard : true } );
335
    // Affichage
336
    $( '#help-modal' ).modal({ show: true });
337
    // Remplacer l'autofocus qui ne fonctionne plus en HTML5
338
    // Message dans la doc de bootstrap :
339
    // Due to how HTML5 defines its semantics,
340
    // the autofocus HTML attribute has no effect in Bootstrap modals.
341
    // To achieve the same effect, use some custom JavaScript
342
    $( '#help-modal' ).on( 'shown.bs.modal' , function () {
343
      $( '#myInput' ).trigger( 'focus' );
344
    })
345
    // Réinitialisation
346
    $( '#help-modal' ).on( 'hidden.bs.modal' , function () {
347
      $( '#help-modal-label' ).text();
348
      $( '#print_content' ).empty();
349
    })
350
  });
351
}
352
 
353
// Activation/Desactivation et contenu de la modale Bootstrap
354
// https://getbootstrap.com/docs/3.3/javascript/#modals
355
function projetHelpModale() {
356
  $( '#top' ).on ( 'click', '#info-button', function ( event ) {
357
    var fileMimeType = $( this ).data( 'mime-info' );
358
 
359
    // Titre
360
    $( '#help-modal-label' ).text( 'Aide du projet : ' +  $( '#titre-projet' ).text() );
361
    if( fileMimeType.match( 'image' ) ) {
362
      var extention = fileMimeType.replace( /(?:imag)?e\/?/g , '' );
363
      $( '#print_content' ).append( '<img src="' + CHEMIN_FICHIERS + 'info.' + extention + '" style="max-width:100%" alt="info projet" />' );
364
    }
365
    // Sortie avec la touche escape
366
    $( '#help-modal' ).modal( { keyboard : true } );
367
    // Affichage
368
    $( '#help-modal' ).modal({ show: true });
369
    // Remplacer l'autofocus qui ne fonctionne plus en HTML5
370
    // Message dans la doc de bootstrap :
371
    // Due to how HTML5 defines its semantics,
372
    // the autofocus HTML attribute has no effect in Bootstrap modals.
373
    // To achieve the same effect, use some custom JavaScript
374
    $( '#help-modal' ).on( 'shown.bs.modal' , function () {
375
      $( '#myInput' ).trigger( 'focus' );
376
    })
377
    // Réinitialisation
378
    $( '#help-modal' ).on( 'hidden.bs.modal' , function () {
379
      $( '#help-modal-label' ).text();
380
      $( '#print_content' ).empty();
381
    });
382
 
383
  });
384
}
385
 
386
// Faire apparaitre un champ text "Autre"
387
function onOtherOption() {
388
  const PREFIX = 'collect-other-';
389
 
390
  // Ajouter un champ texte pour "Autre"
391
  function optionAdd( otherId, $target, element, dataName ) {
392
    $target.after(
393
      '<div class="control-group">'+
394
        '<label'+
395
          ' for="' + otherId + '"'+
396
          ' class="' + otherId + '"'+
397
        '>'+
398
          'Autre option :'+
399
        '</label>'+
400
        '<input'+
401
          ' type="text"'+
402
          ' id="' + otherId + '"'+
403
          ' name="' + otherId + '"'+
404
          ' class="collect-other form-control"'+
405
          ' data-name="' + dataName + '"'+
406
          ' data-element="' + element + '"'+
407
        '>'+
408
      '</div>'
409
    );
410
    $( '#' + otherId ).focus();
411
  }
412
 
413
  // Supprimer un champ texte pour "Autre"
414
  function optionRemove( otherId ) {
415
    $( '.' + otherId + ', #' + otherId ).remove();
416
  }
417
 
418
  $( '.other', '#form-arbre' ).each( function() {
419
    if( $( this ).hasClass( 'is-select' ) ) {
420
      var dataName = $( this ).data( 'name' ),
421
          otherId  = PREFIX + dataName;
422
 
423
      // Insertion du champ "Autre" après les boutons
424
      optionAdd( otherId, $( this ).parent( '.add-field-select' ), 'select', dataName );
425
    } else if ( $( this ).is( ':checked' ) ) {
426
      var dataName = $( this ).data( 'name' ),
427
          otherId  = PREFIX + dataName,
428
          element = $( this ).data( 'element' );
429
      // Insertion du champ "Autre" après les boutons
430
      optionAdd( otherId, $( this ).parent( 'label' ), element, dataName );
431
    }
432
  });
433
 
434
  $( '#charger-form' ).on( 'change', '.select', function () {
435
    var dataName = $( this ).data( 'name' ),
436
        otherId  = PREFIX + dataName;
437
 
438
    if( 'other' === $( this ).val() ) {
439
        // Insertion du champ "Autre" après les boutons
440
        optionAdd( otherId, $( this ).parent( '.add-field-select' ), 'select', dataName );
441
      } else {
442
        // Suppression du champ autre
443
        optionRemove( otherId );
444
        $( this ).find( '.other' ).val( 'other' );
445
      }
446
  });
447
 
448
  $( '#charger-form' ).on( 'change', 'input[type=radio]', function () {
449
    var dataName = $( this ).data( 'name' ),
450
        otherId  = PREFIX + dataName;
451
 
452
    if( 'other' === $( this ).val() ) {
453
      // Insertion du champ "Autre" après les boutons
454
      optionAdd( otherId, $( this ).parent( 'label' ), 'radio', dataName );
455
    } else {
456
      // Suppression du champ autre
457
      optionRemove( otherId );
458
      $( this ).closest( '.radio' ).find( '.other' ).val( 'other' );
459
    }
460
  });
461
 
462
  $( '#charger-form' ).on( 'click', '.list-checkbox .other,.checkbox .other', function () {
463
    var dataName = $( this ).data( 'name' ),
464
        otherId  = PREFIX + dataName,
465
        element = $( this ).data( 'element' );
466
 
467
    if( $( this ).is( ':checked' ) ) {
468
        // Insertion du champ "Autre" après les boutons
469
        optionAdd( otherId, $( this ).parent( 'label' ), element, dataName );
470
      } else {
471
        // Suppression du champ autre
472
        optionRemove( otherId );
473
        $( this ).val( 'other' );
474
      }
475
  });
476
}
477
 
478
function collectOtherOption() {
479
  $( '#charger-form' ).on( 'change', '.collect-other', function () {
480
    var otherIdSuffix = $( this ).data( 'name' ).replace( '[]', '' );
481
    var element = $( this ).data( 'element' );
482
 
483
    if ( '' === $( this ).val() ){
484
      if ( 'select' === element ) {
485
        $( '#' + otherIdSuffix ).find( '.other' ).prop( 'selected', false ).val( 'other' );
486
      } else {
487
        $( '#other-' + otherIdSuffix ).prop( 'checked', false ).val( 'other' );
488
      }
489
      $( 'label.collect-other-' + otherIdSuffix ).remove();
490
      $( this ).remove();
491
    } else {
492
      if ( 'select' === element ) {
493
        $( '#' +  otherIdSuffix ).find( '.other' ).val( $( this ).val() );
494
        $( '#' +  otherIdSuffix ).val( $( this ).val() );
495
        $( '#' +  otherIdSuffix + ' option').not( '.other' ).prop( 'selected', false );
496
        $( '#' +  otherIdSuffix ).find( '.other' ).prop( 'selected', true );
497
      } else {
498
        if ( 'radio' === element ) {
499
          $( 'input[name=' + otherIdSuffix + ']' ).not( '#other-' + otherIdSuffix ).prop( 'checked', false );
500
        }
501
        $( '#other-' + otherIdSuffix ).val( $( this ).val() );
502
        $( '#other-' + otherIdSuffix ).prop( 'checked', true );
503
      }
504
    }
505
  });
506
}
507
 
508
/***************************
509
 *  Lancement des scripts  *
510
 ***************************/
511
const CHEMIN_FICHIERS = $( '#zone-appli' ).data('url-fichiers');
512
 
513
jQuery( document ).ready( function() {
514
  // Modale "aide" du projet
515
  projetHelpModale();
516
  // Affichage input file
517
  inputFile();
518
  // Affichage des List-checkbox
519
  inputListCheckbox();
520
  // Affichage des Range
521
  inputRangeDisplayNumber()
522
  // Modale "aide"
523
  newFieldsHelpModal();
524
  // Ajout/suppression d'un champ texte "Autre"
525
  onOtherOption();
526
  // Récupérer les données entrées dans "Autre"
527
  collectOtherOption();
528
});