Subversion Repositories eFlore/Applications.cel

Rev

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

Rev Author Line No. Line
2688 mathias 1
/**
2
 * Constructeur WidgetSaisie par défaut
3
 */
4
function WidgetSaisie() {
5
	this.obsNbre = 0;
6
	this.nbObsEnCours = 1;
7
	this.totalObsATransmettre = 0;
8
	this.nbObsTransmises = 0;
9
	this.map = null;
10
	this.marker = null;
2736 mathias 11
	this.latLng = null; // position en cours
2688 mathias 12
	this.geocoder = null;
2700 mathias 13
	this.debug = null;
14
	this.html5 = null;
15
	this.tagProjet = null;
16
	this.tagImg = null;
17
	this.tagObs = null;
18
	this.separationTagImg = null;
19
	this.separationTagObs = null;
20
	this.obsId = null;
21
	this.serviceSaisieUrl = null;
22
	this.serviceObsUrl = null;
23
	this.nomSciReferentiel = null;
2707 mathias 24
	this.especeImposee = false;
2700 mathias 25
	this.infosEspeceImposee = null;
26
	this.autocompletionElementsNbre = null;
27
	this.referentielImpose = null;
28
	this.serviceAutocompletionNomSciUrl = null;
29
	this.serviceAutocompletionNomSciUrlTpl = null;
30
	this.obsMaxNbre = null;
31
	this.dureeMessage = null;
32
	this.serviceAnnuaireIdUrl = null;
33
	this.serviceNomCommuneUrl = null;
34
	this.serviceNomCommuneUrlAlt = null;
35
	this.googleMapMarqueurUrl = null;
36
	this.chargementIconeUrl = null;
37
	this.chargementImageIconeUrl = null;
38
	this.calendrierIconeUrl = null;
39
	this.pasDePhotoIconeUrl = null;
2688 mathias 40
}
41
 
42
/**
43
 * Initialisation du widget
44
 */
45
WidgetSaisie.prototype.init = function() {
46
	this.initCarto();
47
	this.initForm();
48
	this.initEvts();
2707 mathias 49
	this.requeterIdentite();
2688 mathias 50
};
51
 
52
/**
53
 * Initialise la cartographie
54
 */
55
WidgetSaisie.prototype.initCarto = function() {
56
	this.initialiserGoogleMap();
57
	this.initialiserAutocompleteCommune();
58
}
59
 
60
/**
61
 * Initialise le formulaire, les validateurs, les listes de complétion...
62
 */
63
WidgetSaisie.prototype.initForm = function() {
2700 mathias 64
	if (this.obsId != '') {
2697 mathias 65
		this.chargerInfoObs();
2688 mathias 66
	}
67
 
2707 mathias 68
	this.configurerDatePicker('#date');
2688 mathias 69
	this.ajouterAutocompletionNoms();
70
	this.configurerFormValidator();
71
	this.definirReglesFormValidator();
72
 
2700 mathias 73
	if(this.especeImposee) {
2688 mathias 74
		$("#taxon").attr("disabled", "disabled");
75
		$("#taxon-input-groupe").attr("title","");
2839 mathias 76
		// Bricolage cracra pour avoir le nom retenu avec auteur (nom_retenu.libelle ne le mentionne pas)
77
		var nomRetenuComplet = this.infosEspeceImposee["nom_retenu_complet"],
78
			debutAnneRefBiblio = nomRetenuComplet.indexOf(" [");
79
		if (debutAnneRefBiblio != -1) {
80
			nomRetenuComplet = nomRetenuComplet.substr(0, debutAnneRefBiblio);
81
		}
82
		// fin bricolage cracra
2688 mathias 83
		var infosAssociee = {
2700 mathias 84
			label : this.infosEspeceImposee.nom_sci_complet,
85
			value : this.infosEspeceImposee.nom_sci_complet,
86
			nt : this.infosEspeceImposee.num_taxonomique,
87
			nomSel : this.infosEspeceImposee.nom_sci,
88
			nomSelComplet : this.infosEspeceImposee.nom_sci_complet,
89
			numNomSel : this.infosEspeceImposee.id,
2839 mathias 90
			nomRet : nomRetenuComplet,
2700 mathias 91
			numNomRet : this.infosEspeceImposee["nom_retenu.id"],
92
			famille : this.infosEspeceImposee.famille,
93
			retenu : (this.infosEspeceImposee.retenu == 'false') ? false : true
2688 mathias 94
		};
95
		$("#taxon").data(infosAssociee);
96
	}
97
}
98
 
99
/**
100
 * Initialise les écouteurs d'événements
101
 */
102
WidgetSaisie.prototype.initEvts = function() {
103
	var lthis = this;
104
	$('body').on('click', '.effacer-miniature', function() {
105
		$(this).parent().remove();
1210 jpm 106
	});
1524 aurelien 107
	$("#fichier").bind('change', function (e) {
108
		arreter(e);
2328 jpm 109
		var options = {
2688 mathias 110
			success: lthis.afficherMiniature.bind(lthis), // post-submit callback
2328 jpm 111
			dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
112
			resetForm: true // reset the form after successful submit
1524 aurelien 113
		};
2700 mathias 114
		$("#miniature").append('<img id="miniature-chargement" class="miniature" alt="chargement" src="'+this.chargementImageIconeUrl+'"/>');
1524 aurelien 115
		$("#ajouter-obs").attr('disabled', 'disabled');
2688 mathias 116
		if(lthis.verifierFormat($("#fichier").val())) {
1524 aurelien 117
			$("#form-upload").ajaxSubmit(options);
118
		} else {
2005 aurelien 119
			$('#form-upload')[0].reset();
1524 aurelien 120
			window.alert("Le format de fichier n'est pas supporté, les formats acceptés sont "+	$("#fichier").attr("accept"));
1210 jpm 121
		}
1524 aurelien 122
		return false;
123
	});
2697 mathias 124
	// identité
2688 mathias 125
	$("#courriel").on('blur', this.requeterIdentite.bind(this));
126
	$("#courriel").on('keypress', this.testerLancementRequeteIdentite.bind(this));
127
	$(".alert .close").on('click', this.fermerPanneauAlert);
2707 mathias 128
	$(".has-tooltip").tooltip('enable');
2688 mathias 129
	$("#btn-aide").on('click', this.basculerAffichageAide);
130
	$("#prenom").on("change", this.formaterPrenom.bind(this));
131
	$("#nom").on("change", this.formaterNom.bind(this));
2328 jpm 132
 
2688 mathias 133
	$("#courriel_confirmation").on('paste', this.bloquerCopierCollerCourriel.bind(this));
2711 mathias 134
	$(".afficher-coord").on('click', this.basculerAffichageCoord.bind(this));
2688 mathias 135
	$("#ajouter-obs").on('click', this.ajouterObs.bind(this));
136
	$(".obs-nbre").on('changement', this.surChangementNbreObs.bind(this));
137
	$("body").on('click', ".supprimer-obs", function() {
138
		var that = this,
139
			suppObs = lthis.supprimerObs.bind(lthis);
140
		// bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
141
		suppObs(that);
142
	});
143
	$("#transmettre-obs").on('click', this.transmettreObs.bind(this));
144
	$("#referentiel").on('change', this.surChangementReferentiel.bind(this));
2328 jpm 145
 
2688 mathias 146
	$("body").on('click', ".defilement-miniatures-gauche", function(event) {
147
		event.preventDefault();
148
		lthis.defilerMiniatures($(this));
1524 aurelien 149
	});
2688 mathias 150
	$("body").on('click', ".defilement-miniatures-droite", function(event) {
151
		event.preventDefault();
152
		lthis.defilerMiniatures($(this));
153
	});
2700 mathias 154
 
155
	// fermeture fenêtre
156
	if (this.debug == false) {
157
		$(window).on('beforeunload', function(event) {
158
			return 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.';
159
		});
160
	}
2707 mathias 161
 
162
	// Autocompletion du champ adresse
163
	$("#carte-recherche").on('focus', function() {
164
		$(this).select();
165
	});
166
	$("#carte-recherche").on('mouseup', function(event) {// Pour Safari...
167
		event.preventDefault();
168
	});
169
	$("#carte-recherche").keypress(function(e) {
170
		if (e.which == 13) {
171
			e.preventDefault();
172
		}
173
	});
2688 mathias 174
}
1249 jpm 175
 
2688 mathias 176
/**
177
 * Retourne true si l'extension de l'image "nom" est .jpg ou .jpeg
178
 */
179
WidgetSaisie.prototype.verifierFormat = function(nom) {
1524 aurelien 180
	var parts = nom.split('.');
181
	extension = parts[parts.length - 1];
182
	return (extension.toLowerCase() == 'jpeg' || extension.toLowerCase() == 'jpg');
2688 mathias 183
};
1210 jpm 184
 
2688 mathias 185
/**
186
 * Affiche la miniature d'une image temporaire (formulaire) qu'on a ajoutée à l'obs
187
 */
188
WidgetSaisie.prototype.afficherMiniature = function(reponse) {
2700 mathias 189
	if (this.debug) {
1210 jpm 190
		var debogage = $("debogage", reponse).text();
1822 aurelien 191
		//console.log("Débogage upload : "+debogage);
1210 jpm 192
	}
193
	var message = $("message", reponse).text();
194
	if (message != '') {
195
		$("#miniature-msg").append(message);
196
	} else {
2688 mathias 197
		$("#miniatures").append(this.creerWidgetMiniature(reponse));
1210 jpm 198
	}
2328 jpm 199
	$('#ajouter-obs').removeAttr('disabled');
2688 mathias 200
};
1210 jpm 201
 
2688 mathias 202
/**
203
 * Crée la miniature d'une image temporaire (formulaire), avec le bouton pour l'effacer
204
 */
205
WidgetSaisie.prototype.creerWidgetMiniature = function(reponse) {
1524 aurelien 206
	var miniatureUrl = $("miniature-url", reponse).text();
207
	var imgNom = $("image-nom", reponse).text();
2328 jpm 208
	var html =
1524 aurelien 209
		'<div class="miniature">'+
210
			'<img class="miniature-img" class="miniature" alt="'+imgNom+'" src="'+miniatureUrl+'"/>'+
211
			'<button class="effacer-miniature" type="button">Effacer</button>'+
212
		'</div>'
213
	return html;
2688 mathias 214
};
1524 aurelien 215
 
2688 mathias 216
/**
2707 mathias 217
 * Efface une miniature (formulaire)
218
 */
219
WidgetSaisie.prototype.supprimerMiniature = function(miniature) {
220
	miniature.parents('.miniature').remove();
221
}
222
 
223
/**
2688 mathias 224
 * Efface toutes les miniatures (formulaire)
225
 */
226
WidgetSaisie.prototype.supprimerMiniatures = function() {
1524 aurelien 227
	$("#miniatures").empty();
1210 jpm 228
	$("#miniature-msg").empty();
2688 mathias 229
};
1210 jpm 230
 
2688 mathias 231
/**
232
 * Initialise l'autocomplétion de la commune, en fonction du référentiel
233
 */
234
WidgetSaisie.prototype.initialiserAutocompleteCommune = function() {
2136 mathias 235
	var geocoderOptions = {
2688 mathias 236
	},
237
	addressSuffix = '',
238
	lthis = this;
1210 jpm 239
 
2700 mathias 240
	switch(this.nomSciReferentiel) {
2125 mathias 241
		case 'isfan':
2136 mathias 242
			// Si des résultats se trouvent dans ce rectangle, ils apparaîtront en premier.
243
			// Ça marche moyen...
244
			geocoderOptions.bounds = new google.maps.LatLngBounds(
245
				new google.maps.LatLng(20.756114, -22.023927),
246
				new google.maps.LatLng(38.065392, 33.78662)
247
			);
248
			break;
2155 mathias 249
		case 'apd':
2136 mathias 250
			geocoderOptions.bounds = new google.maps.LatLngBounds(
251
					new google.maps.LatLng(-6.708254, -26.154786),
252
					new google.maps.LatLng(27.488781, 30.490722)
253
				);
254
			break;
255
		case 'bdtfx':
256
		case 'bdtxa':
257
			geocoderOptions.region = 'fr';
258
			addressSuffix = ', France';
2125 mathias 259
	}
2709 mathias 260
 
261
	$("#carte-recherche").autocomplete({
262
		//Cette partie utilise geocoder pour extraire des valeurs d'adresse
263
		source: function(request, response) {
264
			geocoderOptions.address = request.term + addressSuffix;
265
			lthis.geocoder.geocode( geocoderOptions, function(results, status) {
266
				if (status == google.maps.GeocoderStatus.OK) {
267
					response($.map(results, function(item) {
268
						var retour = {
269
							label: item.formatted_address,
270
							value: item.formatted_address,
271
							latitude: item.geometry.location.lat(),
272
							longitude: item.geometry.location.lng()
273
						};
274
						return retour;
275
					}));
276
				} else {
277
					lthis.afficherErreurGoogleMap(status);
278
				}
279
			});
280
		},
281
		// Cette partie est executee a la selection d'une adresse
282
		select: function(event, ui) {
2736 mathias 283
			lthis.latLng = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
284
			lthis.deplacerMarker(lthis.latLng);
2709 mathias 285
		}
286
	});
2127 mathias 287
};
2125 mathias 288
 
2688 mathias 289
WidgetSaisie.prototype.afficherErreurGoogleMap = function(status) {
2700 mathias 290
	if (this.debug) {
1576 jpm 291
		$('#dialogue-google-map .contenu').empty().append(
292
			'<pre class="msg-erreur">'+
293
			"Le service de Géocodage de Google Map a échoué à cause de l'erreur : "+status+
294
			'</pre>');
2700 mathias 295
		this.afficherPanneau('#dialogue-google-map');
1576 jpm 296
	}
2688 mathias 297
};
1576 jpm 298
 
2688 mathias 299
WidgetSaisie.prototype.surDeplacementMarker = function() {
2736 mathias 300
	this.latLng = this.marker.getPosition();
301
	this.trouverCommune(this.latLng);
2688 mathias 302
	this.mettreAJourMarkerPosition(this.marker.getPosition());
303
};
1249 jpm 304
 
2688 mathias 305
WidgetSaisie.prototype.surClickDansCarte = function(event) {
2736 mathias 306
	this.latLng = event.latLng;
307
	this.deplacerMarker(this.latLng);
2688 mathias 308
};
1249 jpm 309
 
2688 mathias 310
/**
311
 * Place le marqueur aux coordonnées indiquées dans les champs "latitude" et "longitude"
312
 */
313
WidgetSaisie.prototype.geolocaliser = function() {
1249 jpm 314
	var latitude = $('#latitude').val();
315
	var longitude = $('#longitude').val();
2688 mathias 316
	this.latLng = new google.maps.LatLng(latitude, longitude);
317
	this.deplacerMarker(this.latLng);
318
};
1249 jpm 319
 
2715 mathias 320
WidgetSaisie.prototype.initialiserGoogleMap = function(localisationNavigateur) {
321
	// par défaut on tente de localiser le navigateur (avec son sextant)
322
	if (localisationNavigateur === undefined) {
323
		localisationNavigateur = true;
324
	}
325
 
2713 mathias 326
	var lthis = this;
2688 mathias 327
	var latLng,
328
		zoomDefaut;
2553 mathias 329
	// Carte @TODO mettre ça dans la config
2700 mathias 330
	if(this.nomSciReferentiel == 'bdtre') {
2688 mathias 331
		latLng = new google.maps.LatLng(-21.10, 55.30);// Réunion
332
		zoomDefaut = 7;
2700 mathias 333
	} else if(this.nomSciReferentiel == 'lbf') {
2688 mathias 334
		latLng = new google.maps.LatLng(33.72211, 35.8603);// Liban
335
		zoomDefaut = 7;
2700 mathias 336
	} else if(this.nomSciReferentiel == 'bdtxa') {
2688 mathias 337
		latLng = new google.maps.LatLng(14.6, -61.08334);// Fort-De-France
338
		zoomDefaut = 8;
2700 mathias 339
	} else if(this.nomSciReferentiel == 'isfan') {
2688 mathias 340
		latLng = new google.maps.LatLng(29.28358, 10.21884);// Afrique du Nord
341
		zoomDefaut = 4;
2700 mathias 342
	} else if(this.nomSciReferentiel == 'apd') {
2688 mathias 343
		latLng = new google.maps.LatLng(8.75624, 1.80176);// Afrique de l'Ouest et du Centre
344
		zoomDefaut = 4;
2988 mathias 345
	} else if(this.nomSciReferentiel == 'florical') {
346
		latLng = new google.maps.LatLng(-21.40722, 165.4541);// Nouvelle-Calédonie
347
		zoomDefaut = 7;
348
	} else if(this.nomSciReferentiel == 'aublet') {
349
		latLng = new google.maps.LatLng(3.80287, -53.09692);// Guyane
350
		zoomDefaut = 7;
1476 aurelien 351
	} else {
2736 mathias 352
		latLng = new google.maps.LatLng(46.30871, 2.54395);// Centre de la France - @WARNING Prémilhat !! :)
2688 mathias 353
		zoomDefaut = 5;
1476 aurelien 354
	}
2328 jpm 355
 
1210 jpm 356
	var options = {
1476 aurelien 357
		zoom: zoomDefaut,
1210 jpm 358
		center: latLng,
359
		mapTypeId: google.maps.MapTypeId.HYBRID,
360
		mapTypeControlOptions: {
361
			mapTypeIds: ['OSM', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]}
362
	};
363
 
364
	// Ajout de la couche OSM à la carte
365
	osmMapType = new google.maps.ImageMapType({
366
		getTileUrl: function(coord, zoom) {
367
			return "http://tile.openstreetmap.org/" +
368
			zoom + "/" + coord.x + "/" + coord.y + ".png";
369
		},
370
		tileSize: new google.maps.Size(256, 256),
371
		isPng: true,
372
		alt: 'OpenStreetMap',
373
		name: 'OSM',
374
		maxZoom: 19
375
	});
2328 jpm 376
 
1210 jpm 377
	// Création de la carte Google
2688 mathias 378
	this.map = new google.maps.Map(document.getElementById('map-canvas'), options); //affiche la google map dans la div map_canvas
379
	this.map.mapTypes.set('OSM', osmMapType);
2328 jpm 380
 
1216 jpm 381
	// Création du Geocoder
2688 mathias 382
	this.geocoder = new google.maps.Geocoder();
2328 jpm 383
 
1210 jpm 384
	// Marqueur google draggable
2688 mathias 385
	this.marker = new google.maps.Marker({
386
		map: this.map,
1210 jpm 387
		draggable: true,
388
		title: 'Ma station',
2700 mathias 389
		icon: this.googleMapMarqueurUrl,
1210 jpm 390
		position: latLng
391
	});
2328 jpm 392
 
2688 mathias 393
	this.initialiserMarker(latLng);
2328 jpm 394
 
2715 mathias 395
	// Tentative de geocalisation depuis le navigateur
396
	if (localisationNavigateur && navigator.geolocation) {
1210 jpm 397
		navigator.geolocation.getCurrentPosition(function(position) {
398
			var latitude = position.coords.latitude;
399
			var longitude = position.coords.longitude;
2713 mathias 400
			lthis.latLng = new google.maps.LatLng(latitude, longitude);
2714 mathias 401
			lthis.deplacerMarker(lthis.latLng);
1210 jpm 402
		});
403
	}
2127 mathias 404
 
405
	// intéraction carte
2688 mathias 406
	$("#geolocaliser").on('click', this.geolocaliser.bind(this));
407
	google.maps.event.addListener(this.marker, 'dragend', this.surDeplacementMarker.bind(this));
408
	google.maps.event.addListener(this.map, 'click', this.surClickDansCarte.bind(this));
409
};
1210 jpm 410
 
2688 mathias 411
WidgetSaisie.prototype.initialiserMarker = function(latLng) {
412
	if (this.marker != undefined) {
413
		this.marker.setPosition(latLng);
414
		this.map.setCenter(latLng);
2859 mathias 415
		// au chargement de la carte, la position est nulle
416
		this.viderMarkerPosition();
1485 aurelien 417
	}
2688 mathias 418
};
1485 aurelien 419
 
2688 mathias 420
WidgetSaisie.prototype.deplacerMarker = function(latLng) {
421
	if (this.marker != undefined) {
422
		this.marker.setPosition(latLng);
423
		this.map.setCenter(latLng);
424
		this.mettreAJourMarkerPosition(latLng);
425
		this.trouverCommune(latLng);
1210 jpm 426
	}
2688 mathias 427
};
1210 jpm 428
 
2859 mathias 429
WidgetSaisie.prototype.viderMarkerPosition = function() {
430
	this.remplirChampLatitude(null);
431
	this.remplirChampLongitude(null);
432
};
433
 
2688 mathias 434
WidgetSaisie.prototype.mettreAJourMarkerPosition = function(latLng) {
1210 jpm 435
	var lat = latLng.lat().toFixed(5);
2328 jpm 436
	var lng = latLng.lng().toFixed(5);
2688 mathias 437
	this.remplirChampLatitude(lat);
438
	this.remplirChampLongitude(lng);
439
};
1210 jpm 440
 
2859 mathias 441
/**
442
 * Définit la valeur de latitude, à travers la "value" du champ "#latitude";
443
 * pour définir une valeur vraiment vide (et non 0), passer null en argument
444
 */
2688 mathias 445
WidgetSaisie.prototype.remplirChampLatitude = function(latDecimale) {
2859 mathias 446
	var lat = '';
447
	if (latDecimale !== null) {
448
		lat = Math.round(latDecimale * 100000) / 100000;
449
	}
1210 jpm 450
	$('#latitude').val(lat);
2688 mathias 451
};
1210 jpm 452
 
2859 mathias 453
/**
454
 * Définit la valeur de longitude, à travers la "value" du champ "#longitude";
455
 * pour définir une valeur vraiment vide (et non 0), passer null en argument
456
 */
2688 mathias 457
WidgetSaisie.prototype.remplirChampLongitude = function(lngDecimale) {
2859 mathias 458
	var lng = '';
459
	if (lngDecimale !== null) {
460
		lng = Math.round(lngDecimale * 100000) / 100000;
461
	}
1210 jpm 462
	$('#longitude').val(lng);
2688 mathias 463
};
1210 jpm 464
 
2688 mathias 465
WidgetSaisie.prototype.trouverCommune = function(pos) {
2736 mathias 466
	if (this.latLng == null) { // tentative de protection contre le démon de Prémilhat
467
		return;
468
	}
2700 mathias 469
	var lthis = this;
1210 jpm 470
	$(function() {
2328 jpm 471
 
2700 mathias 472
		var url_service = lthis.serviceNomCommuneUrl;
2328 jpm 473
 
1476 aurelien 474
		var urlNomCommuneFormatee = url_service.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
1210 jpm 475
		$.ajax({
476
			url : urlNomCommuneFormatee,
477
			type : "GET",
478
			dataType : "jsonp",
479
			beforeSend : function() {
2328 jpm 480
				$(".commune-info").empty();
1220 jpm 481
				$("#dialogue-erreur .alert-txt").empty();
1210 jpm 482
			},
483
			success : function(data, textStatus, jqXHR) {
484
				$(".commune-info").empty();
485
				$("#commune-nom").append(data.nom);
486
				$("#commune-code-insee").append(data.codeINSEE);
487
				$("#marqueur-commune").data('commune', {'nom' : data.nom, 'codeInsee' : data.codeINSEE});
488
			},
489
			statusCode : {
490
			    500 : function(jqXHR, textStatus, errorThrown) {
2700 mathias 491
					if (this.debug) {
1220 jpm 492
						$("#dialogue-erreur .alert-txt").append('<p id="msg">Un problème est survenu lors de l\'appel au service fournissante le nom des communes.</p>');
1210 jpm 493
						reponse = jQuery.parseJSON(jqXHR.responseText);
494
						var erreurMsg = "";
495
						if (reponse != null) {
496
							$.each(reponse, function (cle, valeur) {
497
								erreurMsg += valeur + "<br />";
498
							});
499
						}
2328 jpm 500
 
1220 jpm 501
						$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
1210 jpm 502
					}
503
			    }
504
			},
505
			error : function(jqXHR, textStatus, errorThrown) {
2700 mathias 506
				if (this.debug) {
2707 mathias 507
					$("#dialogue-erreur .alert-txt").append('<p class="msg">Une erreur Ajax est survenue lors de la recherche de la commune.</p>');
1210 jpm 508
					reponse = jQuery.parseJSON(jqXHR.responseText);
509
					var erreurMsg = "";
510
					if (reponse != null) {
511
						$.each(reponse, function (cle, valeur) {
512
							erreurMsg += valeur + "<br />";
513
						});
514
					}
2328 jpm 515
 
1220 jpm 516
					$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
1210 jpm 517
				}
518
			},
519
			complete : function(jqXHR, textStatus) {
1249 jpm 520
				var debugMsg = extraireEnteteDebug(jqXHR);
521
				if (debugMsg != '') {
2700 mathias 522
					if (this.debug) {
1220 jpm 523
						$("#dialogue-erreur .alert-txt").append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
1210 jpm 524
					}
525
				}
526
				if ($("#dialogue-erreur .msg").length > 0) {
1220 jpm 527
					$("#dialogue-erreur").show();
1210 jpm 528
				}
529
			}
530
		});
531
	});
2688 mathias 532
};
1249 jpm 533
 
2688 mathias 534
WidgetSaisie.prototype.testerLancementRequeteIdentite = function(event) {
1249 jpm 535
	if (event.which == 13) {
2688 mathias 536
		this.requeterIdentite();
537
		this.event.preventDefault();
538
		this.event.stopPropagation();
1249 jpm 539
	}
2688 mathias 540
};
1249 jpm 541
 
2688 mathias 542
WidgetSaisie.prototype.requeterIdentite = function() {
543
	var lthis = this;
1249 jpm 544
	var courriel = $("#courriel").val();
2701 mathias 545
	var urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;
2709 mathias 546
	if (courriel != '') {
547
		$.ajax({
548
			url : urlAnnuaire,
549
			type : "GET",
550
			success : function(data, textStatus, jqXHR) {
2710 mathias 551
				if (lthis.debug) {
552
					console.log('SUCCESS: '+textStatus);
553
				}
2709 mathias 554
				if (data != undefined && data[courriel] != undefined) {
555
					var infos = data[courriel];
2710 mathias 556
					lthis.surSuccesCompletionCourriel(infos, courriel);
2709 mathias 557
				} else {
558
					lthis.surErreurCompletionCourriel();
559
				}
560
			},
561
			error : function(jqXHR, textStatus, errorThrown) {
2710 mathias 562
				if (lthis.debug) {
563
					console.log('ERREUR: '+textStatus);
564
				}
2688 mathias 565
				lthis.surErreurCompletionCourriel();
2709 mathias 566
			},
567
			complete : function(jqXHR, textStatus) {
2710 mathias 568
				if (lthis.debug) {
569
					console.log('COMPLETE: '+textStatus);
570
				}
2709 mathias 571
				// @TODO harmoniser class="hidden" VS style="display:none;"
572
				$("#zone-prenom-nom").removeClass("hidden").show();
573
				$("#zone-courriel-confirmation").removeClass("hidden").show();
1241 jpm 574
			}
2709 mathias 575
		});
576
	}
2688 mathias 577
};
1210 jpm 578
 
2710 mathias 579
WidgetSaisie.prototype.surSuccesCompletionCourriel = function(infos, courriel) {
580
	$("#id_utilisateur").val(infos.id);
581
	$("#prenom").val(infos.prenom);
582
	$("#nom").val(infos.nom);
583
	$("#courriel_confirmation").val(courriel);
584
	$("#prenom, #nom, #courriel_confirmation").attr('disabled', 'disabled');
585
	this.focusChampFormulaire();
586
	this.masquerPanneau("#dialogue-courriel-introuvable");
587
};
2707 mathias 588
 
2688 mathias 589
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
1249 jpm 590
	$("#prenom, #nom, #courriel_confirmation").val('');
591
	$("#prenom, #nom, #courriel_confirmation").removeAttr('disabled');
2700 mathias 592
	this.afficherPanneau("#dialogue-courriel-introuvable");
2688 mathias 593
};
2256 aurelien 594
 
2710 mathias 595
WidgetSaisie.prototype.focusChampFormulaire = function() {
596
	$("#date").focus();
597
};
598
 
2688 mathias 599
WidgetSaisie.prototype.chargerInfoObs = function() {
2700 mathias 600
	var urlObs = this.serviceObsUrl + '/' + this.obsId;
2707 mathias 601
	var lthis = this;
2256 aurelien 602
	$.ajax({
603
		url: urlObs,
604
		type: 'GET',
605
		success: function(data, textStatus, jqXHR) {
606
			if (data != undefined && data != "") {
2758 aurelien 607
				lthis.prechargerForm(data);
2707 mathias 608
			} else {
609
				lthis.surErreurChargementInfosObs();
2328 jpm 610
			}
2256 aurelien 611
		},
612
		error: function(jqXHR, textStatus, errorThrown) {
2707 mathias 613
			lthis.surErreurChargementInfosObs();
2256 aurelien 614
		}
615
	});
2688 mathias 616
};
2256 aurelien 617
 
2707 mathias 618
// @TODO faire mieux que ça !
619
WidgetSaisie.prototype.surErreurChargementInfosObs = function() {
620
	alert("Erreur lors du chargement de l'observation");
621
}
622
 
2688 mathias 623
WidgetSaisie.prototype.prechargerForm = function(data) {
2328 jpm 624
 
2256 aurelien 625
	$("#milieu").val(data.milieu);
2328 jpm 626
 
2256 aurelien 627
	$("#carte-recherche").val(data.zoneGeo);
628
	$("#commune-nom").text(data.zoneGeo);
2328 jpm 629
 
2257 aurelien 630
	if(data.hasOwnProperty("codeZoneGeo")) {
631
		// TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
632
		$("#commune-code-insee").text(data.codeZoneGeo.replace('INSEE-C:', ''));
633
	}
2328 jpm 634
 
2256 aurelien 635
	if(data.hasOwnProperty("latitude") && data.hasOwnProperty("longitude")) {
636
		var latLng = new google.maps.LatLng(data.latitude, data.longitude);
2688 mathias 637
		this.mettreAJourMarkerPosition(latLng);
638
		this.marker.setPosition(latLng);
639
		this.map.setCenter(latLng);
640
		this.map.setZoom(16);
2256 aurelien 641
	}
2688 mathias 642
};
2256 aurelien 643
 
2688 mathias 644
WidgetSaisie.prototype.configurerFormValidator = function() {
1210 jpm 645
	$.validator.addMethod(
2328 jpm 646
		"dateCel",
647
		function (value, element) {
648
			return value == "" || (/^[0-9]{2}[-\/][0-9]{2}[-\/][0-9]{4}$/.test(value));
649
		},
1213 jpm 650
		"Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.");
1210 jpm 651
	$.extend($.validator.defaults, {
652
		errorClass: "control-group error",
653
		validClass: "control-group success",
654
		errorElement: "span",
1213 jpm 655
		highlight: function(element, errorClass, validClass) {
1210 jpm 656
			if (element.type === 'radio') {
657
				this.findByName(element.name).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
2328 jpm 658
			} else {
1210 jpm 659
				$(element).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
660
			}
661
		},
1213 jpm 662
		unhighlight: function(element, errorClass, validClass) {
1210 jpm 663
			if (element.type === 'radio') {
664
				this.findByName(element.name).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
665
			} else {
1213 jpm 666
				if ($(element).attr('id') == 'taxon') {
1493 aurelien 667
					if ($("#taxon").val() != '') {
668
						// Si le taxon n'est pas lié au référentiel, on vide le data associé
2688 mathias 669
						if ($("#taxon").data("value") != $("#taxon").val()) {
1493 aurelien 670
							$("#taxon").data("numNomSel","");
671
							$("#taxon").data("nomRet","");
672
							$("#taxon").data("numNomRet","");
673
							$("#taxon").data("nt","");
674
							$("#taxon").data("famille","");
1213 jpm 675
						}
1493 aurelien 676
						$("#taxon-input-groupe").removeClass(errorClass).addClass(validClass);
677
						$(element).next(" span.help-inline").remove();
1213 jpm 678
					}
679
				} else {
680
					$(element).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
681
					$(element).next(" span.help-inline").remove();
682
				}
1210 jpm 683
			}
684
		}
685
	});
2688 mathias 686
};
1249 jpm 687
 
2688 mathias 688
WidgetSaisie.prototype.definirReglesFormValidator = function() {
1210 jpm 689
	$("#form-observateur").validate({
690
		rules: {
691
			courriel : {
692
				required : true,
693
				email : true},
694
			courriel_confirmation : {
695
				required : true,
696
				equalTo: "#courriel"}
697
		}
698
	});
699
	$("#form-station").validate({
700
		rules: {
701
			latitude : {
702
				range: [-90, 90]},
703
			longitude : {
704
				range: [-180, 180]}
705
		}
706
	});
707
	$("#form-obs").validate({
708
		rules: {
2892 aurel 709
			date : "date",
1210 jpm 710
			taxon : "required"
711
		}
712
	});
2688 mathias 713
};
1249 jpm 714
 
2707 mathias 715
WidgetSaisie.prototype.configurerDatePicker = function(selector) {
1249 jpm 716
	$.datepicker.setDefaults($.datepicker.regional["fr"]);
2707 mathias 717
	$(selector).datepicker({
1990 jpm 718
		dateFormat: "dd/mm/yy",
719
		maxDate: new Date,
1249 jpm 720
		showOn: "button",
1990 jpm 721
		buttonImageOnly: true,
2700 mathias 722
		buttonImage: this.calendrierIconeUrl,
1249 jpm 723
		buttonText: "Afficher le calendrier pour saisir la date.",
2707 mathias 724
		showButtonPanel: true,
725
		onSelect: function(date) {
726
			$(this).valid();
727
		}
1210 jpm 728
	});
2707 mathias 729
	$(selector + ' + img.ui-datepicker-trigger').appendTo(selector + '-icone.add-on');
2688 mathias 730
};
1249 jpm 731
 
2688 mathias 732
WidgetSaisie.prototype.fermerPanneauAlert = function() {
1249 jpm 733
	$(this).parentsUntil(".zone-alerte", ".alert").hide();
2688 mathias 734
};
1249 jpm 735
 
2688 mathias 736
WidgetSaisie.prototype.formaterNom = function() {
1249 jpm 737
	$(this).val($(this).val().toUpperCase());
2688 mathias 738
};
1249 jpm 739
 
2688 mathias 740
WidgetSaisie.prototype.formaterPrenom = function() {
1249 jpm 741
	var prenom = new Array();
742
	var mots = $(this).val().split(' ');
743
	for (var i = 0; i < mots.length; i++) {
744
		var mot = mots[i];
745
		if (mot.indexOf('-') >= 0) {
746
			var prenomCompose = new Array();
747
			var motsComposes = mot.split('-');
748
		    for (var j = 0; j < motsComposes.length; j++) {
749
		    	var motSimple = motsComposes[j];
750
		    	var motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
751
		    	prenomCompose.push(motMajuscule);
752
		    }
753
		    prenom.push(prenomCompose.join('-'));
754
		} else {
755
			var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
756
			prenom.push(motMajuscule);
757
		}
758
	}
759
	$(this).val(prenom.join(' '));
2688 mathias 760
};
1249 jpm 761
 
2688 mathias 762
WidgetSaisie.prototype.basculerAffichageAide = function()  {
1249 jpm 763
	if ($(this).hasClass('btn-warning')) {
2707 mathias 764
		$(".has-tooltip").tooltip('enable');
1249 jpm 765
		$(this).removeClass('btn-warning').addClass('btn-success');
766
		$('#btn-aide-txt', this).text("Désactiver l'aide");
767
	} else {
2707 mathias 768
		$(".has-tooltip").tooltip('disable');
1249 jpm 769
		$(this).removeClass('btn-success').addClass('btn-warning');
770
		$('#btn-aide-txt', this).text("Activer l'aide");
771
	}
2688 mathias 772
};
1249 jpm 773
 
2688 mathias 774
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
2700 mathias 775
	this.afficherPanneau("#dialogue-bloquer-copier-coller");
1249 jpm 776
	return false;
2688 mathias 777
};
1249 jpm 778
 
2688 mathias 779
WidgetSaisie.prototype.basculerAffichageCoord = function() {
1249 jpm 780
	$("a.afficher-coord").toggle();
781
	$("#coordonnees-geo").toggle('slow');
782
	//valeur false pour que le lien ne soit pas suivi
783
	return false;
2688 mathias 784
};
1249 jpm 785
 
2688 mathias 786
/**
787
 * Ajoute une observation saisie dans le formulaire à la liste des observations à transmettre
788
 */
789
WidgetSaisie.prototype.ajouterObs = function() {
2710 mathias 790
	// Fermeture automatique des dialogue de transmission de données
791
	// @WARNING TEST
792
	$('#dialogue-obs-transaction-ko').hide();
793
	$('#dialogue-obs-transaction-ok').hide();
794
 
2688 mathias 795
	if (this.validerFormulaire() == true) {
2854 mathias 796
		this.masquerPanneau('#dialogue-form-invalide');
2688 mathias 797
		this.obsNbre = this.obsNbre + 1;
798
		$(".obs-nbre").text(this.obsNbre);
1249 jpm 799
		$(".obs-nbre").triggerHandler('changement');
2688 mathias 800
		this.afficherObs();
801
		this.stockerObsData();
802
		this.supprimerMiniatures();
2700 mathias 803
		if(! this.especeImposee) {
1856 aurelien 804
			$("#taxon").val("");
805
			$("#taxon").data("numNomSel",undefined);
806
		}
2688 mathias 807
		$('#barre-progression-upload').attr('aria-valuemax', this.obsNbre);
808
		$('#barre-progression-upload .sr-only').text('0/'+this.obsNbre+" observations transmises");
1249 jpm 809
	} else {
2700 mathias 810
		this.afficherPanneau('#dialogue-form-invalide');
1249 jpm 811
	}
2688 mathias 812
};
1249 jpm 813
 
2688 mathias 814
/**
815
 * Affiche une observation dans la liste des observations à transmettre
816
 */
817
WidgetSaisie.prototype.afficherObs = function() {
2746 aurelien 818
 
819
	var commune = $("#commune-nom").text();
820
	commune = commune.trim() != "" ? commune : $("#carte-recherche").val();
821
 
822
	var code_insee = $('#commune-code-insee').text();
823
	code_insee = code_insee.trim() != "" ? "("+code_insee+")" : "";
2854 mathias 824
 
825
	if (this.debug) {
826
		console.log(commune+'  -  '+code_insee);
827
	}
2746 aurelien 828
 
1249 jpm 829
	$("#liste-obs").prepend(
2688 mathias 830
		'<div id="obs'+this.obsNbre+'" class="row-fluid obs obs'+this.obsNbre+'">'+
1249 jpm 831
			'<div class="span12">'+
1253 jpm 832
				'<div class="well">'+
2707 mathias 833
					'<div class="obs-action pull-right has-tooltip" data-placement="bottom" '+
1253 jpm 834
						'title="Supprimer cette observation de la liste à transmettre">'+
2688 mathias 835
						'<button class="btn btn-danger supprimer-obs" value="'+this.obsNbre+'" title="'+this.obsNbre+'">'+
1249 jpm 836
							'<i class="icon-trash icon-white"></i>'+
837
						'</button>'+
2328 jpm 838
					'</div> '+
839
					'<div class="row-fluid">'+
1249 jpm 840
						'<div class="thumbnail span2">'+
2688 mathias 841
						this.ajouterImgMiniatureAuTransfert()+
1240 jpm 842
						'</div>'+
1249 jpm 843
						'<div class="span9">'+
844
							'<ul class="unstyled">'+
845
								'<li>'+
846
									'<span class="nom-sci">'+$("#taxon").val()+'</span> '+
2688 mathias 847
									this.ajouterNumNomSel()+'<span class="referentiel-obs">'+
2700 mathias 848
									($("#taxon").data("numNomSel") == undefined ? '' : '['+ this.nomSciReferentiel +']')+'</span>'+
1249 jpm 849
									' observé à '+
2746 aurelien 850
									'<span class="commune">'+commune+'</span> '+
851
									code_insee+' ['+$("#latitude").val()+' / '+$("#longitude").val()+']'+
1249 jpm 852
									' le '+
853
									'<span class="date">'+$("#date").val()+'</span>'+
854
								'</li>'+
855
								'<li>'+
856
									'<span>Lieu-dit :</span> '+$('#lieudit').val()+' '+
857
									'<span>Station :</span> '+$('#station').val()+' '+
858
									'<span>Milieu :</span> '+$('#milieu').val()+' '+
859
								'</li>'+
860
								'<li>'+
861
									'Commentaires : <span class="discretion">'+$("#notes").val()+'</span>'+
862
								'</li>'+
863
							'</ul>'+
864
						'</div>'+
1237 jpm 865
					'</div>'+
1249 jpm 866
				'</div>'+
867
			'</div>'+
868
		'</div>');
2707 mathias 869
	$('#zone-liste-obs').removeClass("hidden").show();
2688 mathias 870
};
1249 jpm 871
 
2688 mathias 872
WidgetSaisie.prototype.stockerObsData = function() {
873
	var lthis = this;
2746 aurelien 874
 
875
	var commune = $("#commune-nom").text();
876
	commune = commune.trim() == "" ? commune : $("#carte-recherche").val();
877
 
2688 mathias 878
	$("#liste-obs").data('obsId'+this.obsNbre, {
2328 jpm 879
		'date' : $("#date").val(),
2710 mathias 880
		'notes' : $("#notes").val().trim(),
2328 jpm 881
 
1249 jpm 882
		'nom_sel' : $("#taxon").val(),
883
		'num_nom_sel' : $("#taxon").data("numNomSel"),
884
		'nom_ret' : $("#taxon").data("nomRet"),
885
		'num_nom_ret' : $("#taxon").data("numNomRet"),
886
		'num_taxon' : $("#taxon").data("nt"),
887
		'famille' : $("#taxon").data("famille"),
2700 mathias 888
		'referentiel' : ($("#taxon").data("numNomSel") == undefined ? '' : lthis.nomSciReferentiel),
2328 jpm 889
 
1249 jpm 890
		'latitude' : $("#latitude").val(),
891
		'longitude' : $("#longitude").val(),
2746 aurelien 892
		'commune_nom' : commune,
1249 jpm 893
		'commune_code_insee' : $("#commune-code-insee").text(),
1251 jpm 894
		'lieudit' : $("#lieudit").val(),
1249 jpm 895
		'station' : $("#station").val(),
896
		'milieu' : $("#milieu").val(),
2328 jpm 897
 
1249 jpm 898
		//Ajout des champs images
2688 mathias 899
		'image_nom' : lthis.getNomsImgsOriginales(),
2709 mathias 900
		'image_b64' : lthis.getB64ImgsOriginales(),
901
 
902
		// Ajout des champs étendus de l'obs
903
		'obs_etendue': lthis.getObsChpEtendus()
1210 jpm 904
	});
2688 mathias 905
};
1249 jpm 906
 
2709 mathias 907
/**
908
 * Retourne un Array contenant les valeurs des champs étendus
909
 */
910
WidgetSaisie.prototype.getObsChpEtendus = function() {
911
	var champs = [];
912
 
913
	$('.obs-chp-etendu').each(function() {
914
		var valeur = $(this).val(),
915
			cle = $(this).attr('name'),
916
			label = $(this).data('label');
917
		if (valeur != '') {
918
			var chpEtendu = {cle: cle, label: label, valeur: valeur};
919
			champs.push(chpEtendu);
920
		}
921
	});
922
	return champs;
923
}
924
 
2688 mathias 925
WidgetSaisie.prototype.surChangementReferentiel = function() {
2700 mathias 926
	this.nomSciReferentiel = $('#referentiel').val();
1476 aurelien 927
	$('#taxon').val('');
2688 mathias 928
	this.initialiserAutocompleteCommune();
2715 mathias 929
	this.initialiserGoogleMap(false);
2688 mathias 930
};
1476 aurelien 931
 
2688 mathias 932
WidgetSaisie.prototype.surChangementNbreObs = function() {
933
	if (this.obsNbre == 0) {
1249 jpm 934
		$("#transmettre-obs").attr('disabled', 'disabled');
935
		$("#ajouter-obs").removeAttr('disabled');
2700 mathias 936
	} else if (this.obsNbre > 0 && this.obsNbre < this.obsMaxNbre) {
1249 jpm 937
		$("#transmettre-obs").removeAttr('disabled');
938
		$("#ajouter-obs").removeAttr('disabled');
2700 mathias 939
	} else if (this.obsNbre >= this.obsMaxNbre) {
1249 jpm 940
		$("#ajouter-obs").attr('disabled', 'disabled');
2700 mathias 941
		this.afficherPanneau("#dialogue-bloquer-creer-obs");
1249 jpm 942
	}
2688 mathias 943
};
1249 jpm 944
 
2688 mathias 945
WidgetSaisie.prototype.transmettreObs = function() {
1249 jpm 946
	var observations = $("#liste-obs").data();
2710 mathias 947
	if (this.debug) {
948
		console.log(observations);
949
	}
1249 jpm 950
	if (observations == undefined || jQuery.isEmptyObject(observations)) {
2700 mathias 951
		this.afficherPanneau("#dialogue-zero-obs");
1249 jpm 952
	} else {
2688 mathias 953
		this.nbObsEnCours = 1;
954
		this.nbObsTransmises = 0;
955
		this.totalObsATransmettre = $.map(observations, function(n, i) { return i; }).length;
956
		this.depilerObsPourEnvoi();
2110 aurelien 957
	}
958
	return false;
2688 mathias 959
};
2110 aurelien 960
 
2688 mathias 961
WidgetSaisie.prototype.depilerObsPourEnvoi = function() {
2110 aurelien 962
	var observations = $("#liste-obs").data();
963
	// la boucle est factice car on utilise un tableau
964
	// dont on a besoin de n'extraire que le premier élément
965
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
966
	// TODO: utiliser var.keys quand ça sera plus répandu
967
	// ou bien utiliser un vrai tableau et pas un objet
2328 jpm 968
	for (var obsNum in observations) {
2697 mathias 969
		var obsATransmettre = {
2700 mathias 970
			'projet' : this.tagProjet,
971
			'tag-obs' : this.tagObs,
972
			'tag-img' : this.tagImg
2688 mathias 973
		};
2697 mathias 974
		var utilisateur = {
975
			id_utilisateur : $("#id_utilisateur").val(),
976
			prenom : $("#prenom").val(),
977
			nom : $("#nom").val(),
978
			courriel : $("#courriel").val()
979
		};
2110 aurelien 980
		obsATransmettre['utilisateur'] = utilisateur;
981
		obsATransmettre[obsNum] = observations[obsNum];
982
		var idObsNumerique = obsNum.replace('obsId', '');
983
		if(idObsNumerique != "") {
2688 mathias 984
			this.envoyerObsAuCel(idObsNumerique, obsATransmettre);
2110 aurelien 985
		}
2328 jpm 986
 
2110 aurelien 987
		break;
1249 jpm 988
	}
2688 mathias 989
};
1249 jpm 990
 
2688 mathias 991
WidgetSaisie.prototype.mettreAJourProgression = function() {
992
	this.nbObsTransmises++;
993
	var pct = (this.nbObsTransmises/this.totalObsATransmettre)*100;
994
	$('#barre-progression-upload').attr('aria-valuenow', this.nbObsTransmises);
2110 aurelien 995
	$('#barre-progression-upload').attr('style', "width: "+pct+"%");
2688 mathias 996
	$('#barre-progression-upload .sr-only').text(this.nbObsTransmises+"/"+this.totalObsATransmettre+" observations transmises");
2110 aurelien 997
 
2688 mathias 998
	if(this.obsNbre == 0) {
2110 aurelien 999
		$('.progress').removeClass('active');
1000
		$('.progress').removeClass('progress-striped');
1001
	}
2688 mathias 1002
};
2110 aurelien 1003
 
2688 mathias 1004
WidgetSaisie.prototype.envoyerObsAuCel = function(idObs, observation) {
1005
	var lthis = this;
1249 jpm 1006
	var erreurMsg = "";
1007
	$.ajax({
2700 mathias 1008
		url : lthis.serviceSaisieUrl,
1249 jpm 1009
		type : "POST",
2110 aurelien 1010
		data : observation,
1249 jpm 1011
		dataType : "json",
1012
		beforeSend : function() {
1251 jpm 1013
			$("#dialogue-obs-transaction-ko").hide();
1014
			$("#dialogue-obs-transaction-ok").hide();
2697 mathias 1015
			$('.alert-txt').empty();
2709 mathias 1016
			$(".alert-txt .msg-erreur").remove();
1017
			$(".alert-txt .msg-debug").remove();
1249 jpm 1018
			$("#chargement").show();
1019
		},
1020
		success : function(data, textStatus, jqXHR) {
2110 aurelien 1021
			// mise à jour du nombre d'obs à transmettre
1022
			// et suppression de l'obs
2688 mathias 1023
			lthis.supprimerObsParId(idObs);
2700 mathias 1024
			lthis.nbObsEnCours++;
2110 aurelien 1025
			// mise à jour du statut
2688 mathias 1026
			lthis.mettreAJourProgression();
2700 mathias 1027
			if(lthis.obsNbre > 0) {
2110 aurelien 1028
				// dépilement de la suivante
2688 mathias 1029
				lthis.depilerObsPourEnvoi();
2110 aurelien 1030
			}
1249 jpm 1031
		},
1032
		statusCode : {
1033
			500 : function(jqXHR, textStatus, errorThrown) {
1034
				erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
1035
		    }
1036
		},
1037
		error : function(jqXHR, textStatus, errorThrown) {
1038
			erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
1039
			try {
1040
				reponse = jQuery.parseJSON(jqXHR.responseText);
1041
				if (reponse != null) {
1042
					$.each(reponse, function (cle, valeur) {
1043
						erreurMsg += valeur + "\n";
1044
					});
1045
				}
1046
			} catch(e) {
2700 mathias 1047
				erreurMsg += "Erreur inconnue: " + jqXHR.responseText;
1249 jpm 1048
			}
1049
		},
1050
		complete : function(jqXHR, textStatus) {
1051
			var debugMsg = extraireEnteteDebug(jqXHR);
2328 jpm 1052
 
1249 jpm 1053
			if (erreurMsg != '') {
2700 mathias 1054
				if (this.debug) {
1249 jpm 1055
					$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
1056
					$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
1210 jpm 1057
				}
1901 mathias 1058
				var hrefCourriel = "mailto:cel_remarques@tela-botanica.org?"+
2700 mathias 1059
					"subject=Dysfonctionnement du widget de saisie "+ this.tagProjet +
1902 mathias 1060
					"&body="+erreurMsg+"%0D%0ADébogage :%0D%0A"+debugMsg;
2328 jpm 1061
 
2110 aurelien 1062
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
1063
				$('#obs'+idObs+' div div').addClass('obs-erreur');
1064
				window.location.hash = "obs"+idObs;
2328 jpm 1065
 
1249 jpm 1066
				$('#dialogue-obs-transaction-ko .alert-txt').append($("#tpl-transmission-ko").clone()
1067
					.find('.courriel-erreur')
1068
					.attr('href', hrefCourriel)
1069
					.end()
1070
					.html());
1071
				$("#dialogue-obs-transaction-ko").show();
2110 aurelien 1072
				$("#chargement").hide();
2688 mathias 1073
				lthis.initialiserBarreProgression();
1249 jpm 1074
			} else {
2700 mathias 1075
				if (lthis.debug) {
1249 jpm 1076
					$("#dialogue-obs-transaction-ok .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
1077
				}
2700 mathias 1078
				if(lthis.obsNbre == 0) {
2110 aurelien 1079
					setTimeout(function() {
1080
						$("#chargement").hide();
1081
						$('#dialogue-obs-transaction-ok .alert-txt').append($('#tpl-transmission-ok').clone().html());
1082
						$("#dialogue-obs-transaction-ok").show();
2117 aurelien 1083
						window.location.hash = "dialogue-obs-transaction-ok";
2688 mathias 1084
						lthis.initialiserObs();
2110 aurelien 1085
					}, 1500);
2328 jpm 1086
 
1087
				}
1251 jpm 1088
			}
1210 jpm 1089
		}
1090
	});
2688 mathias 1091
};
1210 jpm 1092
 
2688 mathias 1093
WidgetSaisie.prototype.validerFormulaire = function() {
1210 jpm 1094
	$observateur = $("#form-observateur").valid();
1095
	$station = $("#form-station").valid();
1096
	$obs = $("#form-obs").valid();
1097
	return ($observateur == true && $station == true && $obs == true) ? true : false;
2688 mathias 1098
};
1210 jpm 1099
 
2688 mathias 1100
WidgetSaisie.prototype.getNomsImgsOriginales = function() {
1524 aurelien 1101
	var noms = new Array();
1102
	$(".miniature-img").each(function() {
1103
		noms.push($(this).attr('alt'));
1104
	});
1105
	return noms;
2688 mathias 1106
};
1524 aurelien 1107
 
2688 mathias 1108
WidgetSaisie.prototype.getB64ImgsOriginales = function() {
1524 aurelien 1109
	var b64 = new Array();
1110
	$(".miniature-img").each(function() {
1111
		if ($(this).hasClass('b64')) {
1112
			b64.push($(this).attr('src'));
1113
		} else if ($(this).hasClass('b64-canvas')) {
1114
			b64.push($(this).data('b64'));
1115
		}
1116
	});
1117
 
1210 jpm 1118
	return b64;
2688 mathias 1119
};
1210 jpm 1120
 
2688 mathias 1121
WidgetSaisie.prototype.supprimerObs = function(selector) {
1122
	var obsId = $(selector).val();
1210 jpm 1123
	// Problème avec IE 6 et 7
1124
	if (obsId == "Supprimer") {
2688 mathias 1125
		obsId = $(selector).attr("title");
1210 jpm 1126
	}
2688 mathias 1127
	this.supprimerObsParId(obsId);
1128
};
2110 aurelien 1129
 
2688 mathias 1130
WidgetSaisie.prototype.supprimerObsParId = function(obsId) {
1131
	this.obsNbre = this.obsNbre - 1;
1132
	$(".obs-nbre").text(this.obsNbre);
1237 jpm 1133
	$(".obs-nbre").triggerHandler('changement');
1215 jpm 1134
	$('.obs'+obsId).remove();
1210 jpm 1135
	$("#liste-obs").removeData('obsId'+obsId);
2688 mathias 1136
};
1210 jpm 1137
 
2688 mathias 1138
WidgetSaisie.prototype.initialiserBarreProgression = function() {
2110 aurelien 1139
	$('#barre-progression-upload').attr('aria-valuenow', 0);
1140
	$('#barre-progression-upload').attr('style', "width: 0%");
1141
	$('#barre-progression-upload .sr-only').text("0/0 observations transmises");
1142
	$('.progress').addClass('active');
1143
	$('.progress').addClass('progress-striped');
2688 mathias 1144
};
2110 aurelien 1145
 
2688 mathias 1146
WidgetSaisie.prototype.initialiserObs = function() {
1147
	this.obsNbre = 0;
1148
	this.nbObsTransmises = 0;
1149
	this.nbObsEnCours = 0;
1150
	this.totalObsATransmettre = 0;
1151
	this.initialiserBarreProgression();
1152
	$(".obs-nbre").text(this.obsNbre);
1249 jpm 1153
	$(".obs-nbre").triggerHandler('changement');
1154
	$("#liste-obs").removeData();
1155
	$('.obs').remove();
1156
	$("#dialogue-bloquer-creer-obs").hide();
2688 mathias 1157
};
1231 jpm 1158
 
2688 mathias 1159
/**
1160
 * Ajoute une boîte de miniatures avec défilement des images,
1161
 * pour une obs de la liste des obs à transmettre
1162
 */
1163
WidgetSaisie.prototype.ajouterImgMiniatureAuTransfert = function() {
1164
	var html = '',
1165
		miniatures = '',
1166
		premiere = true;
1524 aurelien 1167
	if ($("#miniatures img").length >= 1) {
1168
		$("#miniatures img").each(function() {
1169
			var visible = premiere ? 'miniature-selectionnee' : 'miniature-cachee';
1170
			premiere = false;
2688 mathias 1171
			var css = $(this).hasClass('b64') ? 'miniature b64' : 'miniature',
1172
				src = $(this).attr("src"),
1173
				alt = $(this).attr("alt"),
1174
				//miniature = '<img class="'+css+' '+visible+'"  alt="'+alt+'"src="'+src+'" />';
1175
				miniature = '<div class="'+css+' '+visible+'"  alt="'+alt+'" style="background-image: url('+src+')" ></div>';
1524 aurelien 1176
			miniatures += miniature;
1177
		});
1178
		visible = ($("#miniatures img").length > 1) ? '' : 'defilement-miniatures-cache';
2328 jpm 1179
		var html =
1524 aurelien 1180
			'<div class="defilement-miniatures">'+
1181
				'<a href="#" class="defilement-miniatures-gauche '+visible+'">&#60;</a>'+
1182
				miniatures+
1183
				'<a href="#" class="defilement-miniatures-droite '+visible+'">&#62;</a>'+
1184
			'</div>';
1237 jpm 1185
	} else {
2700 mathias 1186
		html = '<img class="miniature" alt="Aucune photo"src="'+ this.pasDePhotoIconeUrl +'" />';
1210 jpm 1187
	}
1524 aurelien 1188
	return html;
2688 mathias 1189
};
1210 jpm 1190
 
2688 mathias 1191
WidgetSaisie.prototype.defilerMiniatures = function(element) {
2328 jpm 1192
 
2688 mathias 1193
	var miniatureSelectionne = element.siblings("div.miniature-selectionnee");
1524 aurelien 1194
	miniatureSelectionne.removeClass('miniature-selectionnee');
1195
	miniatureSelectionne.addClass('miniature-cachee');
1196
	var miniatureAffichee = miniatureSelectionne;
2328 jpm 1197
 
1524 aurelien 1198
	if(element.hasClass('defilement-miniatures-gauche')) {
1199
		if(miniatureSelectionne.prev('.miniature').length != 0) {
1200
			miniatureAffichee = miniatureSelectionne.prev('.miniature');
1201
		} else {
1202
			miniatureAffichee = miniatureSelectionne.siblings(".miniature").last();
1203
		}
1204
	} else {
1205
		if(miniatureSelectionne.next('.miniature').length != 0) {
1206
			miniatureAffichee = miniatureSelectionne.next('.miniature');
1207
		} else {
1208
			miniatureAffichee = miniatureSelectionne.siblings(".miniature").first();
1209
		}
1210
	}
1822 aurelien 1211
	//console.log(miniatureAffichee);
1524 aurelien 1212
	miniatureAffichee.addClass('miniature-selectionnee');
1213
	miniatureAffichee.removeClass('miniature-cachee');
2688 mathias 1214
};
1524 aurelien 1215
 
2688 mathias 1216
WidgetSaisie.prototype.ajouterNumNomSel = function() {
1240 jpm 1217
	var nn = '';
1218
	if ($("#taxon").data("numNomSel") == undefined) {
1219
		nn = '<span class="alert-error">[non lié au référentiel]</span>';
1220
	} else {
1221
		nn = '<span class="nn">[nn'+$("#taxon").data("numNomSel")+']</span>';
1222
	}
1223
	return nn;
2688 mathias 1224
};
1240 jpm 1225
 
2688 mathias 1226
WidgetSaisie.prototype.ajouterAutocompletionNoms = function() {
1227
	var lthis = this;
1210 jpm 1228
	$('#taxon').autocomplete({
2328 jpm 1229
		source: function(requete, add){
1210 jpm 1230
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
1231
			requete = "";
2343 aurelien 1232
			if($("#referentiel").val() != "autre") {
2688 mathias 1233
				var url = lthis.getUrlAutocompletionNomsSci();
2343 aurelien 1234
				$.getJSON(url, requete, function(data) {
2688 mathias 1235
					var suggestions = lthis.traiterRetourNomsSci(data);
2343 aurelien 1236
					add(suggestions);
1237
	            });
1238
			}
1210 jpm 1239
        },
1240
        html: true
1241
	});
2328 jpm 1242
 
2863 mathias 1243
	$("#taxon").bind("autocompleteselect", this.surAutocompletionTaxon);
2688 mathias 1244
};
1210 jpm 1245
 
2863 mathias 1246
WidgetSaisie.prototype.surAutocompletionTaxon = function(event, ui) {
1247
	$("#taxon").data(ui.item);
1248
	if (ui.item.retenu == true) {
1249
		$("#taxon").addClass('ns-retenu');
1250
	} else {
1251
		$("#taxon").removeClass('ns-retenu');
1252
	}
1253
};
1254
 
2688 mathias 1255
WidgetSaisie.prototype.getUrlAutocompletionNomsSci = function() {
1215 jpm 1256
	var mots = $('#taxon').val();
2700 mathias 1257
	var url = this.serviceAutocompletionNomSciUrlTpl.replace('{referentiel}', this.nomSciReferentiel);
1476 aurelien 1258
	url = url.replace('{masque}', mots);
1210 jpm 1259
	return url;
2688 mathias 1260
};
1210 jpm 1261
 
2688 mathias 1262
WidgetSaisie.prototype.traiterRetourNomsSci = function(data) {
2328 jpm 1263
	var suggestions = [];
1210 jpm 1264
	if (data.resultat != undefined) {
1265
		$.each(data.resultat, function(i, val) {
1266
			val.nn = i;
2328 jpm 1267
			var nom = {label : '', value : '', nt : '', nomSel : '', nomSelComplet : '', numNomSel : '',
1215 jpm 1268
				nomRet : '', numNomRet : '', famille : '', retenu : false
1269
			};
2700 mathias 1270
			if (suggestions.length >= this.autocompletionElementsNbre) {
1213 jpm 1271
				nom.label = "...";
1272
				nom.value = $('#taxon').val();
1273
				suggestions.push(nom);
1274
				return false;
1275
			} else {
1231 jpm 1276
				nom.label = val.nom_sci_complet;
1277
				nom.value = val.nom_sci_complet;
1215 jpm 1278
				nom.nt = val.num_taxonomique;
1279
				nom.nomSel = val.nom_sci;
1280
				nom.nomSelComplet = val.nom_sci_complet;
1281
				nom.numNomSel = val.nn;
1237 jpm 1282
				nom.nomRet = val.nom_retenu_complet;
1220 jpm 1283
				nom.numNomRet = val["nom_retenu.id"];
1231 jpm 1284
				nom.famille = val.famille;
2243 mathias 1285
				// Tester dans ce sens, permet de considérer "absent" comme "false" => est-ce opportun ?
1286
				// en tout cas c'est harmonisé avec le CeL
1287
				nom.retenu = (val.retenu == 'true') ? true : false;
2328 jpm 1288
 
1213 jpm 1289
				suggestions.push(nom);
2328 jpm 1290
			}
1210 jpm 1291
		});
1292
	}
2328 jpm 1293
 
1210 jpm 1294
	return suggestions;
2688 mathias 1295
};
1210 jpm 1296
 
2700 mathias 1297
WidgetSaisie.prototype.afficherPanneau = function(selecteur) {
1298
	$(selecteur).fadeIn("slow").delay(this.dureeMessage).fadeOut("slow");
2701 mathias 1299
};
2700 mathias 1300
 
2701 mathias 1301
WidgetSaisie.prototype.masquerPanneau = function(selecteur) {
1302
	$(selecteur).hide();
1303
};
1304
 
2697 mathias 1305
// lib hors objet --
1306
 
1307
/**
1308
* Stope l'évènement courant quand on clique sur un lien.
1309
* Utile pour Chrome, Safari...
1310
*/
1311
function arreter(evenement) {
1312
	if (evenement.stopPropagation) {
1313
		evenement.stopPropagation();
1314
	}
1315
	if (evenement.preventDefault) {
1316
		evenement.preventDefault();
1317
	}
1318
	return false;
1319
}
1320
 
1321
/**
1322
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1323
 * @param jqXHR
1324
 * @returns {String}
1325
 */
1326
function extraireEnteteDebug(jqXHR) {
1327
	var msgDebug = '';
1328
	if (jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
1329
		var debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
1330
		if (debugInfos != null) {
1331
			$.each(debugInfos, function (cle, valeur) {
1332
				msgDebug += valeur + "\n";
1333
			});
1334
		}
1335
	}
1336
	return msgDebug;
1337
}
1338
 
1210 jpm 1339
/*
1340
 * jQuery UI Autocomplete HTML Extension
1341
 *
1342
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1343
 * Dual licensed under the MIT or GPL Version 2 licenses.
1344
 *
1345
 * http://github.com/scottgonzalez/jquery-ui-extensions
2328 jpm 1346
 *
1210 jpm 1347
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1348
 */
1349
(function( $ ) {
1215 jpm 1350
	var proto = $.ui.autocomplete.prototype,
1351
		initSource = proto._initSource;
2328 jpm 1352
 
2688 mathias 1353
	WidgetSaisie.prototype.filter = function( array, term ) {
1215 jpm 1354
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1355
		return $.grep( array, function(value) {
1356
			return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1357
		});
1358
	}
2328 jpm 1359
 
1215 jpm 1360
	$.extend( proto, {
1361
		_initSource: function() {
1362
			if ( this.options.html && $.isArray(this.options.source) ) {
1363
				this.source = function( request, response ) {
1364
					response( filter( this.options.source, request.term ) );
1365
				};
1366
			} else {
1367
				initSource.call( this );
1368
			}
1369
		},
1370
		_renderItem: function( ul, item) {
1371
			if (item.retenu == true) {
1372
				item.label = "<strong>"+item.label+"</strong>";
1373
			}
2328 jpm 1374
 
1215 jpm 1375
			return $( "<li></li>" )
1376
				.data( "item.autocomplete", item )
1377
				.append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1378
				.appendTo( ul );
1379
		}
1210 jpm 1380
	});
2849 aurel 1381
})( jQuery );