Subversion Repositories eFlore/Applications.cel

Rev

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

Rev Author Line No. Line
2943 delphine 1
// Héritage
2
WidgetSaisieArbresRemarquables = function() {
3
	this.serviceAltitudeUrl = null;
4
	this.taxons = {};
5
}
6
WidgetSaisieArbresRemarquables.prototype = new WidgetSaisie();
7
 
8
WidgetSaisieArbresRemarquables.prototype.initEvts = function() {
9
	// super()
10
	WidgetSaisie.prototype.initEvts.call(this);
11
 
12
	var lthis = this;
13
	$('body').on('click', '.fermer', function(event) {
14
			event.preventDefault();
15
			lthis.basculerOuvertureFermetureCadre($(this).find('.icone'));
16
	});
17
 
2944 mathias 18
	// multi cases à cocher dans un menu déroulant : clic confortable !
19
	$('.btn-group.dropdown ul li input[type="checkbox"], .btn-group.dropdown ul li label').on('click', function(event) {
20
		$(this).valid();
21
		event.stopPropagation();
22
	});
23
 
2943 delphine 24
	this.surChangementTaxonListe();// Vérif lors du chargement de la page
25
	$('#taxon-liste').on('change', this.surChangementTaxonListe.bind(this));
26
	this.surChangementSituation();// Vérif lors du chargement de la page
2944 mathias 27
	$('#situation-autre').on('change', this.surChangementSituation.bind(this));
2943 delphine 28
	this.surChangementEsthetique();// Vérif lors du chargement de la page
2944 mathias 29
	$('#esthetique-autre').on('change', this.surChangementEsthetique.bind(this));
30
	this.surChangementRemarquable();// Vérif lors du chargement de la page
31
	$('.cb-remarquable').on('change', this.surChangementRemarquable.bind(this));
2943 delphine 32
 
33
	// Gestion des obs
34
	this.surChangementNbreObs();
35
};
36
 
37
WidgetSaisieArbresRemarquables.prototype.focusChampFormulaire = function() {
38
	$("#carte-recherche").focus();
39
};
40
 
41
WidgetSaisieArbresRemarquables.prototype.mettreAJourMarkerPosition = function(latLng) {
42
	this.trouverCommune(latLng);
43
	this.trouverAltitude(latLng);
44
 
45
	var lat = latLng.lat().toFixed(5),
46
		lng = latLng.lng().toFixed(5);
47
	this.remplirChampLatitude(lat);
48
	this.remplirChampLongitude(lng);
49
	this.remplirChampsLambert93(lat, lng);
50
};
51
 
52
proj4.defs([
53
	['EPSG:4326', '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'],
54
	['EPSG:2154', '+title=RGF93 / Lambert-93 +proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs']
55
]);
56
WidgetSaisieArbresRemarquables.prototype.remplirChampsLambert93 = function(lat, lng) {
57
	// Prendre en compte l'initialisation des projections
58
	var coordinate = {x: lng,y: lat};
59
	proj4(proj4.defs('EPSG:4326'), proj4.defs('EPSG:2154')).forward(coordinate);
60
	$('#l93-x').val(coordinate.x.toFixed(0));
61
	$('#l93-y').val(coordinate.y.toFixed(0));
62
};
63
 
64
WidgetSaisieArbresRemarquables.prototype.trouverAltitude = function(pos) {
65
	var url_service = this.serviceAltitudeUrl,
66
		urlAltFormatee = url_service.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
67
	var lthis = this;
68
	$.ajax({
69
		url: urlAltFormatee,
70
		type: 'GET',
71
		dataType: 'jsonp',
72
		beforeSend : function() {
73
			$('#altitude').empty();
74
			$('#dialogue-erreur .alert-txt').empty();
75
		},
76
		success : function(data, textStatus, jqXHR) {
77
			$('#altitude').empty().append(data.altitude);
78
			$('#marqueur-altitude').data('altitude', data.altitude);
79
		},
80
		statusCode : {
81
		    500 : function(jqXHR, textStatus, errorThrown) {
82
				if (lthis.debug) {
83
					$('#dialogue-erreur .alert-txt').append('<p id="msg">Un problème est survenu lors de l\'appel au service fournissant l\'altitude.</p>');
84
					reponse = jQuery.parseJSON(jqXHR.responseText);
85
					var erreurMsg = '';
86
					if (reponse != null) {
87
						$.each(reponse, function (cle, valeur) {
88
							erreurMsg += valeur + '<br />';
89
						});
90
					}
91
 
92
					$('#dialogue-erreur .alert-txt').append('<p class="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
93
				}
94
		    }
95
		},
96
		error : function(jqXHR, textStatus, errorThrown) {
97
			if (lthis.debug) {
98
				$("#dialogue-erreur .alert-txt").append('<p class="msg">Une erreur Ajax est survenue lors de l\'appel au service fournissant l\'altitude.</p>');
99
				reponse = jQuery.parseJSON(jqXHR.responseText);
100
				var erreurMsg = '';
101
				if (reponse != null) {
102
					$.each(reponse, function (cle, valeur) {
103
						erreurMsg += valeur + '<br />';
104
					});
105
				}
106
 
107
				$('#dialogue-erreur .alert-txt').append('<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
108
			}
109
		},
110
		complete : function(jqXHR, textStatus) {
111
			var debugMsg = extraireEnteteDebug(jqXHR);
112
			if (debugMsg != '') {
113
				if (lthis.debug) {
114
					$('#dialogue-erreur .alert-txt').append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
115
				}
116
			}
117
			if ($('#dialogue-erreur .msg').length > 0) {
118
				$('#dialogue-erreur').show();
119
			}
120
		}
121
	});
122
};
123
 
124
WidgetSaisieArbresRemarquables.prototype.surChangementTaxonListe = function() {
125
	if ($('#taxon-liste').val() === '?') {
126
		$('#taxon-input-groupe').removeClass('hidden');
127
		$('#taxon').valid();
128
	} else {
129
		$('#taxon-input-groupe').addClass('hidden');
130
	}
131
};
132
 
133
WidgetSaisieArbresRemarquables.prototype.surChangementEsthetique = function() {
2944 mathias 134
	var cochee = $('#esthetique-autre').prop("checked");
135
	if (cochee) {
136
		$('#autre-esthetique-id').removeClass('hidden');
2943 delphine 137
	} else {
2944 mathias 138
		$('#autre-esthetique-id').addClass('hidden');
2943 delphine 139
	}
140
};
141
 
142
WidgetSaisieArbresRemarquables.prototype.surChangementSituation = function() {
2944 mathias 143
	var cochee = $('#situation-autre').prop("checked");
144
	if (cochee) {
2943 delphine 145
		$('#autre-situation-id').removeClass('hidden');
146
	} else {
147
		$('#autre-situation-id').addClass('hidden');
148
	}
149
};
150
 
2944 mathias 151
// Activation de la saisie si on clique sur un type de champ
152
WidgetSaisieArbresRemarquables.prototype.surChangementRemarquable = function() {
153
	$('.cb-remarquable').each(function() {
154
		var id = $(this).prop('id'),
155
			cochee = $(this).prop("checked"),
156
			idCommentaire = id + '-commentaire',
157
			champCommentaire = $('#' + idCommentaire);
158
		if (cochee) {
159
			champCommentaire.removeClass('hidden');
160
		} else {
161
			champCommentaire.addClass('hidden');
162
		}
163
	});
164
};
165
 
2943 delphine 166
WidgetSaisieArbresRemarquables.prototype.configurerFormValidator = function() {
167
	$.validator.addMethod(
168
		'dateCel',
169
		function (value, element) {
170
			return value == '' || (/^[0-9]{2}[-\/][0-9]{2}[-\/][0-9]{4}$/.test(value));
171
		},
172
		'Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.');
173
 
174
	$.validator.addMethod(
175
		'aligneNbre',
176
		function (value, element) {
177
			var ok = true;
178
			if ($('#formation').val() === 'alignement') {
179
				ok = (value != '' && /^[0-9]+$/.test(value) && value > 1);
180
			}
181
			return ok;
182
		},
183
		"Veuillez indiquer le nombre d'arbres d'alignement.");
184
 
185
	$.validator.addMethod(
186
		'autreSp',
187
		function (value, element) {
188
			var taxonListe = $('#taxon-liste').val();
189
			return taxonListe !== '?' || (taxonListe === '?' && value != '');
190
		},
191
		"Veuillez sélectionner une espèce ou une indication sur la plante.");
192
 
193
	// Modification des méthodes par défaut de Jquery Validation pour Boostrap 3
194
	$.validator.setDefaults({
195
		ignore: [],// Forcer Jquery Validate à examiner les éléments en "display:none;"
196
		highlight: function(element) {
197
			$(element).closest('.form-group').addClass('has-error');
198
		},
199
		unhighlight: function(element) {
200
			$(element).closest('.form-group').removeClass('has-error');
201
		},
202
		success: function(element) {
203
			$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
204
 
205
			if ($(element).attr('id') == 'taxon' && $('#taxon').val() != '') {
206
				// Si le taxon n'est pas lié au référentiel, on vide le data associé
207
				if ($('#taxon').data('value') != $('#taxon').val()) {
208
					$('#taxon').data('numNomSel', '');
209
					$('#taxon').data('nomRet', '');
210
					$('#taxon').data('numNomRet', '');
211
					$('#taxon').data('nt', '');
212
					$('#taxon').data('famille', '');
213
				}
214
			}
215
		},
216
		errorElement: 'span',
217
		errorClass: 'help-block',
218
		errorPlacement: function(error, element) {
219
			//console.log(element.attr('name') +'-'+ element.parent('.input-group').length);
220
			if (element.parent('.input-group').length) {
221
				error.insertAfter(element.parent());
222
			} else {
223
				error.insertAfter(element);
224
			}
225
		}
226
	});
227
};
228
 
229
WidgetSaisieArbresRemarquables.prototype.definirReglesFormValidator = function() {
230
	$('#form-observateur').validate({
231
		rules: {
232
			courriel : {
233
				required : true,
234
				email : true},
235
			courriel_confirmation : {
236
				required : true,
237
				equalTo: '#courriel'}
238
		}
239
	});
240
	$('#form-station').validate({
241
		rules: {
242
			latitude : {
243
				range: [-90, 90],
244
				required: true},
245
			longitude : {
246
				range: [-180, 180],
247
				required: true},
248
			'l93-x': 'required',
249
			'l93-y': 'required'
250
		}
251
	});
252
	$('#form-obs').validate({
253
		rules: {
254
			date: {
255
				required: true,
256
				'dateCel' : true},
257
			'taxon-liste': {required: true},
258
			taxon: {autreSp: true},
259
			certitude: 'required',
260
			arbreTetardFormation: 'required',
261
			arbreTetardAligneNbre: {aligneNbre: true}
262
		}
263
	});
264
};
265
 
266
 
267
 
268
WidgetSaisieArbresRemarquables.prototype.basculerOuvertureFermetureCadre = function(element) {
269
	if (element.hasClass('glyphicon-plus-sign')) {
270
		element.removeClass('glyphicon-plus-sign').addClass('glyphicon-minus-sign');
271
	} else {
272
		element.removeClass('glyphicon-minus-sign').addClass('glyphicon-plus-sign');
273
	}
274
};
275
 
276
WidgetSaisieArbresRemarquables.prototype.basculerAffichageCoord = function() {
277
	var textActuel = $(this).text(),
278
			textARemplacer = $(this).data('toggle-text');
279
	$(this).text(textARemplacer).data('toggle-text', textActuel);
280
 
281
	if ($(this).hasClass('cacher-coord')) {
282
		$(this).removeClass('cacher-coord').addClass('afficher-coord');
283
		$('#coordonnees-geo').addClass('hidden');
284
	} else {
285
		$(this).removeClass('afficher-coord').addClass('cacher-coord');
286
		$('#coordonnees-geo').removeClass('hidden');
287
	}
288
 
289
	return false;
290
};
291
 
292
WidgetSaisieArbresRemarquables.prototype.afficherObs = function() {
293
	var numNomSel = ($('#taxon-liste').val() == '?') ? $('#taxon').data('numNomSel') : $('#taxon-liste').val(),
294
		nomSpecial = $('#taxon-liste option:selected').hasClass('nom-special'),
295
		taxon = ($('#taxon-liste').val() == '?') ? $('#taxon').val() : $('#taxon-liste option:selected').data('nom-a-sauver'),
296
		referentiel = (numNomSel == undefined) ? '' : '['+ this.nomSciReferentiel +']',
297
		commune = $('#commune-nom').text(),
298
		codeInsee = $('#commune-code-insee').text(),
299
		lat = $('input[name="latitude"]').val(),
300
		lng = $('input[name="longitude"]').val(),
301
		date = $('#date').val(),
302
		formation = this.getTextOptionSelectionne('formation'),
303
		nbreAligne = ($('#aligne-nbre').val() != undefined ? ' (' + $('#aligne-nbre').val() + ')' : ''),
304
		cavites = this.getTextOptionSelectionne('cavites'),
305
		circonference = this.getTextOptionSelectionne('circonference'),
306
		hauteurTete = this.getTextOptionSelectionne('hauteur-tete'),
307
		presenceSp = $('#presence-sp').val(),
308
		taille = this.getTextOptionSelectionne('taille-type'),
309
		entretien = this.getTextOptionSelectionne('entretien'),
310
		etatSanitaire = this.getTextOptionSelectionne('etat-sanitaire'),
311
		milieux = this.getMilieux(),
312
		notes = (nomSpecial ? this.taxons[numNomSel]['nom_fr'] + ".<br />" : '') + $('#notes').val();
313
 
314
	var culture = ($('input[name=type-culture]').is(':checked') ? $('input[name=type-culture]:checked').data('titre') : "?");
315
	var cultureDetails = ($('input[name=type-culture]').is(':checked') ? $('input[name=type-culture]:checked').parent().find('input[type=text]').val() : '?');
316
 
317
 
318
	$('#liste-obs').prepend(
319
		'<div id="obs'+this.obsNbre+'" class="obs obs'+this.obsNbre+'">'+
320
				'<div class="well">'+
321
					'<div class="obs-action pull-right has-tooltip" data-placement="bottom" '+
322
						'title="Supprimer cette observation de la liste à transmettre">'+
323
						'<button class="btn btn-danger supprimer-obs" value="'+this.obsNbre+'" title="'+this.obsNbre+'">'+
324
							'<span class="glyphicon glyphicon-trash icon-white"></i>'+
325
						'</button>'+
326
					'</div> '+
327
					'<div class="row">'+
328
						'<div class="col-md-2 obs-miniatures">'+
329
							this.ajouterImgMiniatureAuTransfert()+
330
						'</div>'+
331
						'<div class="col-md-8">'+
332
							'<ul class="list-unstyled obs-entete">'+
333
								'<li>'+
334
									'<span class="nom-sci">' + taxon + '</span> ' +
335
									this.formaterNumNomSel(numNomSel)+
336
									'<span class="referentiel-obs">' + referentiel + '</span>' +
337
									' observé à ' +
338
									'<span class="commune">' + commune + '</span> ' +
339
									'(' + codeInsee + ') [' + lat +' / ' + lng + ']' +
340
									' le ' +
341
									'<span class="date">' + date + '</span>' +
342
								'</li>' +
343
							'</ul>'+
344
							'<ul class="list-unstyled obs-details">'+
345
								'<li>' +
346
									'<span>Situation(s) :</span> ' + milieux + ' ; ' +
347
									'<span>Formation :</span> ' + formation + nbreAligne + ' ; ' +
348
									'<span>Cavités :</span> ' + cavites + ' ; ' +
349
									'<span>Circonférence :</span> ' + circonference + ' ; ' +
350
									'<span>Hauteur de la tête :</span> ' + hauteurTete + ' ; ' +
351
								'</li>' +
352
								'<li>' +
353
									'<span>Présences sur l\'arbre :</span> ' + presenceSp + ' ' +
354
								'</li>' +
355
								'<li>' +
356
									'<span>Type taille :</span> ' + taille + ' ; ' +
357
									'<span>Entretien :</span> ' + entretien + ' ; ' +
358
									'<span class="span4">Culture de <span class="gras">'+cultureDetails+'</span> de type <span class="gras">'+culture+'</span></span>'+
359
									'<span>État sanitaire :</span> ' + etatSanitaire + ' ; ' +
360
								'</li>' +
361
								'<li>' +
362
									'<span>Commentaires :</span> ' + notes +
363
								'</li>'+
364
							'</ul>'+
365
						'</div>'+
366
					'</div>'+
367
				'</div>'+
368
		'</div>');
369
};
370
 
371
WidgetSaisieArbresRemarquables.prototype.formaterNumNomSel = function(numNomSel) {
372
	var nn = '';
373
	if (numNomSel == undefined) {
374
		nn = '<span class="alert-error">[non lié au référentiel]</span>';
375
	} else {
376
		nn = '<span class="nn">[nn'+numNomSel+']</span>';
377
	}
378
	return nn;
379
};
380
 
381
WidgetSaisieArbresRemarquables.prototype.getMilieux = function() {
382
	var milieuxStr = '',
383
		milieux = [];
384
	$('.cb-milieux:checked').each(function() {
385
		milieux.push($(this).val());
386
	});
387
 
388
	milieuxStr = Array.prototype.slice.call(milieux).join(', ');
389
	return milieuxStr;
390
};
391
 
392
WidgetSaisieArbresRemarquables.prototype.getTextOptionSelectionne = function(id) {
393
	return ($('#' + id).val() != undefined ? $('#' + id + ' option:selected').text()  : '');
394
};
395
 
396
// @TODO harmoniser (altitude)
397
WidgetSaisieArbresRemarquables.prototype.stockerObsData = function() {
398
	var nomHorsListe = $('#taxon-liste').val() == '?' ? true : false;
399
		nomSpecial = $('#taxon-liste option:selected').hasClass('nom-special'),
400
		numNomSel = nomHorsListe ? $('#taxon').data('numNomSel') : $('#taxon-liste').val(),
401
		nomSel = nomHorsListe ? $('#taxon').val() : $('#taxon-liste option:selected').data('nom-a-sauver'),
402
		nomRet = nomHorsListe ? $('#taxon').data('nomRet') : this.taxons[numNomSel]['nom_ret'],
403
		numNomRet = nomHorsListe ? $('#taxon').data('numNomRet') : this.taxons[numNomSel]['num_nom_ret'],
404
		numTaxon = nomHorsListe ? $('#taxon').data('nt') : this.taxons[numNomSel]['num_taxon'],
405
		famille = nomHorsListe ? $('#taxon').data('famille') : this.taxons[numNomSel]['famille'],
406
		referentiel = (numNomSel == undefined) ? '' : this.nomSciReferentiel;
407
 
408
	$('#liste-obs').data('obsId'+this.obsNbre, {
409
		'date' : $('#date').val(),
410
		'notes' : $('#notes').val(),
411
 
412
		'nom_sel': nomSel,
413
		'num_nom_sel': numNomSel,
414
		'nom_ret': nomRet,
415
		'num_nom_ret': numNomRet,
416
		'num_taxon': numTaxon,
417
		'famille': famille,
418
		'referentiel': referentiel,
419
 
420
		'latitude' : $('#latitude').val(),
421
		'longitude' : $('#longitude').val(),
422
		'commune_nom' : $('#commune-nom').text(),
423
		'commune_code_insee' : $('#commune-code-insee').text(),
424
		'altitude': $('#altitude').text(),
425
		'lieudit': $('#lieudit').val(),
426
		'milieu': this.getMilieux(),
427
		'certitude': $('#certitude').val(),
428
 
429
		//Ajout des champs images
430
		'image_nom' :this. getNomsImgsOriginales(),
431
 
432
		// Ajout des champs étendus de l'obs
433
		'obs_etendue': this.getObsChpEtendus()
434
	});
435
};
436
 
2944 mathias 437
/**
438
 * Redéfinition pour les champs complexes
439
 */
440
WidgetSaisieArbresRemarquables.prototype.getObsChpEtendus = function() {
441
	var champs = [];
2943 delphine 442
 
2944 mathias 443
	$('.obs-chp-etendu').each(function() {
444
		var valeur = $(this).val(),
445
			cle = $(this).attr('name'),
446
			label = $(this).data('label');
447
		if (valeur != '') {
448
			var chpEtendu = {cle: cle, label: label, valeur: valeur};
449
			champs.push(chpEtendu);
450
		}
451
	});
452
	return champs;
453
};