Subversion Repositories eFlore/Applications.cel

Rev

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

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