Subversion Repositories eFlore/Applications.cel

Rev

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

Rev Author Line No. Line
1824 jpm 1
//+----------------------------------------------------------------------------------------------------------+
2
// Initialisation de Jquery mobile
3
$(document).on('mobileinit', function() {
4
	$.mobile.defaultPageTransition = 'fade';
5
});
6
$(document).on('online', function(event) {
7
	console.log('online');
8
	miseAJourObs();
9
});
10
 
11
function changerPage(id, event) {
12
	$.mobile.changePage(id);
13
	event.stopPropagation();
14
	event.preventDefault();
15
}
16
//+----------------------------------------------------------------------------------------------------------+
17
// Gestion des paramètres URL
18
var modal_recherche = false;
19
$.urlParam = function(name){
20
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
21
	return decodeURIComponent(results[1]) || 0;
22
}
23
function recupererParametresUrl() {
24
	$('#referentiel').val($.urlParam('ref'));
25
	$('#nom').html($.urlParam('nom_sci'));
26
	$('#nom-sci-select').val($.urlParam('nom_sci'));
27
	$('#num-nom-select').val($.urlParam('num_nom'));
28
}
29
$(document).ready(function() {
30
	$('#geolocaliser').on('vclick', obtenirPosition);
31
 
32
	$('body').on('pagebeforeshow', '#infos', obtenirDate);
33
	$('body').on('pageshow', '#saisie', function(event) {
34
		if (!modal_recherche) {
35
			obtenirPosition(event);
36
			recupererParametresUrl();
37
		} else {
38
			modal_recherche = false;
39
		}
40
	});
41
	$('body').on('pagehide', '#saisie-popup', function() {
42
		modal_recherche = true;
43
	});
44
});
45
 
46
//+----------------------------------------------------------------------------------------------------------+
47
// Géolocalisation et date du jour
48
var gps = navigator.geolocation;
49
 
50
function obtenirPosition(event) {
51
	event.stopImmediatePropagation();
52
	event.stopPropagation();
53
	event.preventDefault();
54
 
55
	obtenirDate();
56
	geolocaliser();
57
}
58
function geolocaliser() {
59
	if (gps) {
60
	    navigator.geolocation.getCurrentPosition(surSuccesGeoloc, surErreurGeoloc);
61
	} else {
62
	    var erreur = {code:'0', message: 'Géolocalisation non supportée par le navigateur'};
63
	    surErreurGeoloc(erreur);
64
	}
65
}
66
function surSuccesGeoloc(position){
67
	if (position) {
68
		var lat = position.coords.latitude;
69
		var lng = position.coords.longitude;
70
		$('#lat').html(lat);
71
		$('#lng').html(lng);
72
 
73
		console.log('Geolocation SUCCESS');
74
		var url_service = SERVICE_NOM_COMMUNE_URL;
75
		var urlNomCommuneFormatee = url_service.replace('{lat}', lat).replace('{lon}', lng);
76
		$.ajax({
77
			url : urlNomCommuneFormatee,
78
			type : 'GET',
79
			dataType : 'jsonp',
80
			success : function(data) {
81
				console.log('NOM_COMMUNE found.');
82
				$('#location').html(data['nom']);
83
				$('#code-insee').val(data['codeINSEE']);
84
			},
85
			complete : function() {
86
				var texte = ($('#location').html() == '') ? TEXTE_HORS_LIGNE : $('#location').html();
87
				$('#location').html(texte);
88
			}
89
		});
90
	}
91
}
92
function surErreurGeoloc(error){
93
	alert('Echec de la géolocalisation, code: ' + error.code + ' message: '+ error.message);
94
}
95
 
96
function obtenirDate() {
97
	var d = new Date();
98
	var jour = d.getDate();
99
	var mois = d.getMonth()+1;
100
	var annee = d.getFullYear();
101
	var aujourdhui =
102
		( (''+jour).length < 2 ? '0' : '') + jour + '/' +
103
		( (''+mois).length < 2 ? '0' : '') + mois + '/' +
104
		annee;
105
	$('#date').html(aujourdhui);
106
	$('#annee').html(annee);
107
}
108
//+----------------------------------------------------------------------------------------------------------+
109
// Local Storage
110
$(document).ready(function() {
111
	$('#sauver-obs').on('click', ajouterObs);
112
	$('#valider-photos').on('click', ajoutPhoto);
113
	$('body').on('pageshow', '#liste', chargerListeObs);
114
	$('body').on('pageshow', '#transmission', miseAJourObs);
115
});
116
 
117
var bdd = window.localStorage,
118
	index_obs = (bdd.getItem('index_obs') == null) ? 1 : bdd.getItem('index_obs'),
119
	index_photos = (bdd.getItem('index_photos') == null) ? 1 : bdd.getItem('index_photos');
120
//bdd.clear();
121
 
122
console.log(bdd);
123
function ajouterObs(event) {
124
	if ($('#nom').html() != '') {
125
		var obs = {
126
			num:TEXTE_OBS,
127
			maj:0,
128
			date:'',
129
			referentiel:'',
130
			lat:'', lng:'',
131
			commune:'', code_insee: 0,
132
			nom:'',
133
			nom_sci_select:'',
134
			nn_select:'',
135
			nom_sci_retenu:'',
136
			nn_retenu:'',
137
			num_taxon:'',
138
			famille:''
139
		};
140
 
141
		obs.num += index_obs++;
142
		obs.date = $('#date').html();
143
		obs.referentiel = $('#referentiel').val();
144
		obs.lat = $('#lat').html();
145
		obs.lng = $('#lng').html();
146
		obs.commune = $('#location').html();
147
		obs.code_insee = $('#code-insee').val();
148
		obs.nom = $('#nom').html();
149
		obs.referentiel = $('#referentiel').val();
150
		obs.nom_sci_select = $('#nom-sci-select').val();
151
		obs.nn_select = $('#num-nom-select').val();
152
 
153
		var cle = obs.num;
154
		sauvegarderObs(cle, obs);
155
		bdd.setItem('index_obs', index_obs);
156
		effacerFormulaire();
157
		changerPage('#liste', event);
158
	} else {
159
		changerPage('#saisie', event);
160
	}
161
}
162
 
163
function sauvegarderObs(cle, obs) {
164
	var val = JSON.stringify(obs),
165
		poids = JSON.stringify(bdd).length + val.length;
166
	if (poids > 2621940) {
167
		$('#cache-plein').popup('open');
168
	}
169
	bdd.setItem(cle, val);
170
}
171
 
172
function effacerFormulaire() {
173
    $('#lat').html('');
174
    $('#lng').html('');
175
    $('#location').html('');
176
}
177
 
178
function chargerListeObs() {
179
	console.log('space used: '+JSON.stringify(bdd).length);
180
	$('#liste-obs').empty();
181
 
182
	var nbre = bdd.length;
183
	for (var i = 0; i < nbre; i++) {
184
		var cle = bdd.key(i);
185
		if (cle.indexOf(TEXTE_OBS) !== -1) {
186
			var obs = JSON.parse(bdd.getItem(cle));
187
			console.log(obs);
188
			$('#liste-obs').prepend(
189
				'<li>'+
190
					'<a href="#" onclick="detailsObs(this);" data-split-icon="next" data-split-theme="a" title="Voir la fiche" data-obs-num="' + obs.num + '">' +
191
						'<strong>' + obs.nom + '</strong> <br />' + obs.date +
192
						((obs.commune == TEXTE_HORS_LIGNE ||  obs.commune == '') ? '' :  (' à ' + obs.commune)) +
193
						'<br />(Nbre photos : ' + compterPhotos(obs.num) + ')<br />' +
194
					'</a>'+
195
					'<a href="#" onclick="supprimerObs(this);" title="Supprimer l\'observation" ' +
196
						'data-obs-num="' + obs.num + '">' +
197
						'Supprimer'+
198
					'</a>'+
199
				'</li>'
200
			);
201
		}
202
		$('#liste-obs').listview('refresh');
203
	}
204
}
205
 
206
function compterPhotos(num_obs) {
207
	var compteur = 0;
208
	if (num_obs != '') {
209
		var nbre = bdd.length;
210
		for (var i = 0; i < nbre; i++) {
211
			var cle = bdd.key(i);
212
			if (cle.indexOf(TEXTE_PHOTO) !== -1) {
213
				var photo = JSON.parse(bdd.getItem(cle));
214
				if (photo.parent == num_obs) {
215
					compteur++;
216
				}
217
			}
218
		}
219
	}
220
	return compteur;
221
}
222
 
223
function supprimerObs(data) {
224
	var cle_obs = data.getAttribute('data-obs-num'),
225
		obs = JSON.parse(bdd.getItem(cle_obs)),
226
		nbre = bdd.length,
227
		a_supprimer = new Array();
228
	for (var i = 0; i < nbre; i++) {
229
		var cle = bdd.key(i);
230
		if (cle.indexOf(TEXTE_PHOTO) !== -1) {
231
			var photo = JSON.parse(bdd.getItem(cle));
232
			if (photo.parent == obs.num) {
233
				a_supprimer.push(photo.num);
234
			}
235
		}
236
	}
237
	for (var c = 0; c < a_supprimer.length; c++) {
238
		bdd.removeItem(a_supprimer[c]);
239
	}
240
	bdd.removeItem(cle_obs);
241
 
242
	var txt = obs.num + ' supprimée.';
243
	$('#obs-suppression-infos').html('<p class="reponse ui-btn-inner ui-btn-corner-all">'+txt+'</p>')
244
		.fadeIn(0)
245
		.delay(1600)
246
		.fadeOut('slow');
247
 
248
	chargerListeObs();
249
}
250
 
251
function detailsObs(data) {
252
	var num_obs = data.getAttribute('data-obs-num');
253
	var obs = JSON.parse(bdd.getItem(num_obs));
254
	$('#id-obs').html(obs.num);
255
 
256
	var texte = '<strong>' + obs.nom + '</strong> vue le ' + obs.date;
257
	texte += (obs.commune == TEXTE_HORS_LIGNE ||  obs.commune == '') ? '' :  ' à ' + obs.commune;
258
	$('#details-obs').html(texte);
259
	$.mobile.changePage('#observation');
260
	afficherPhotos(obs.num);
261
}
262
 
263
function ajoutPhoto() {
264
	var id_obs = $('#id-obs').html();
265
	if (id_obs != '') {
266
		$.each($('#pic').get(0).files, function(index, valeur) {
267
			var reader = new FileReader();
268
            reader.addEventListener('loadend', function () {
269
				var photo_nom = valeur.name,
270
					arr_nom = photo_nom.split("."),
271
					dernier = arr_nom.length - 1;
272
				if (arr_nom[dernier].toUpperCase() != "JPG" && arr_nom[dernier].toUpperCase() != "JPEG") {
273
					$('#pic').val('');
274
					var txt = 'Seuls les fichiers .JPG ou .JPEG sont acceptés.';
275
					$('#photo-suppression-infos').html('<p class="reponse ui-btn-inner ui-btn-corner-all">' + txt + '</p>')
276
						.fadeIn(0)
277
						.delay(1600)
278
						.fadeOut('slow');
279
				} else {
280
					var photo = {
281
						num: TEXTE_PHOTO,
282
						nom: '',
283
						parent: '',
284
						base64: 0
285
					};
286
					photo.num += index_photos++;
287
					photo.nom = photo_nom;
288
					photo.parent = id_obs;
289
					photo.base64 = reader.result;
290
 
291
					var cle = photo.num;
292
					sauvegarderObs(cle, photo);
293
					bdd.setItem('index_photos', index_photos);
294
					afficherPhotos(id_obs);
295
				}
296
			}, false);
297
			reader.readAsDataURL(valeur);
298
		});
299
	}
300
}
301
 
302
function afficherPhotos(num_obs) {
303
	$('#pic').val('');
304
	$('#photos-obs').empty();
305
	if (num_obs != '') {
306
		var nbre = bdd.length;
307
		for (var i = 0; i < nbre; i++) {
308
			var cle = bdd.key(i);
309
			if (cle.indexOf(TEXTE_PHOTO) !== -1) {
310
				var photo = JSON.parse(bdd.getItem(cle));
311
				if (photo.parent == num_obs) {
312
					$('#photos-obs').prepend(
313
						'<li>'+
314
							'<a href="#" onclick="afficherVue(this);" data-ajax="false" data-role="button" data-inline="true" data-photo-num="' + photo.num + '">' +
315
								'<img src="' + photo.base64 + '" />' +
316
								photo.nom +
317
							'</a>' +
318
							'<a href="#" onclick="supprimerPhoto(this);" title="Supprimer la photo" ' +
319
								'data-icon="delete" data-photo-num="' + photo.num + '" data-photo-parent="' + num_obs + '"' +
320
								'data-theme="c">' +
321
								'Supprimer cette photo' +
322
							'</a>' +
323
						'</li>'
324
					);
325
				}
326
			}
327
			$('#photos-obs').listview('refresh');
328
		}
329
	}
330
}
331
 
332
function afficherVue(data) {
333
	var cle_photo = data.getAttribute('data-photo-num'),
334
		photo = JSON.parse(bdd.getItem(cle_photo));
335
	$('#photo-zoom-infos').html('<img class="photo-popup" width="80%" src="' + photo.base64 + '" />');
336
	$('#photo-zoom')
337
		.popup('open')
338
		.on('popupafterclose', function(event) {
339
			event.stopImmediatePropagation();
340
			event.stopPropagation();
341
			event.preventDefault();
342
		});
343
}
344
 
345
function supprimerPhoto(data) {
346
	var cle_photo = data.getAttribute('data-photo-num'),
347
		parent = data.getAttribute('data-photo-parent'),
348
		photo = JSON.parse(bdd.getItem(cle_photo));
349
	bdd.removeItem(cle_photo);
350
 
351
	afficherPhotos(parent);
352
}
353
 
354
function miseAJourObs() {
355
	console.log('majObs');
356
	var nbre = bdd.length;
357
	for (var i = 0; i < nbre; i++) {
358
		var cle = bdd.key(i);
359
		if (cle.indexOf(TEXTE_OBS) !== -1) {
360
			var obs = JSON.parse(bdd.getItem(cle));
361
 
362
			if (obs.maj == 0) {
363
				var maj = 1;
364
 
365
				if (obs.commune == TEXTE_HORS_LIGNE ||  obs.commune == '') {
366
					var url_service = SERVICE_NOM_COMMUNE_URL;
367
					var urlNomCommuneFormatee = url_service.replace('{lat}', lat).replace('{lon}', lng);
368
					jQuery.ajax({
369
						url: urlNomCommuneFormatee,
370
						type : 'GET',
371
						dataType : 'jsonp',
372
						success: function(data) {
373
							obs.commune = data['nom'];
374
							obs.code_insee = data['codeINSEE'];
375
						 },
376
						 error: function() {
377
							 maj = 0;
378
						 },
379
						async: false
380
				   });
381
				}
382
 
383
				if (obs.nom_sci_retenu == '') {
384
					jQuery.ajax({
385
						url:	'/service:eflore:0.1/' + obs.referentiel + '/noms?'
386
								 + 'masque.nn=' + obs.nn_select
387
								 + '&retour.champs=num_taxonomique',
388
						success: function(data) {
389
							var cle = '',
390
								compteur = 0;
391
							for (name in data['resultat']) {
392
								if (compteur == 0) {
393
									cle = name;
394
								}
395
								compteur++;
396
							}
397
							obs.num_taxon = data['resultat'][cle]['num_taxonomique'];
398
							jQuery.ajax({
399
								url: 	'/service:eflore:0.1/' + obs.referentiel + '/noms?'
400
										 + 'masque.nt=' + obs.num_taxon
401
										 + '&retour.champs=famille'
402
										 + '&retour.tri=retenu',
403
								type : 'GET',
404
								dataType : 'jsonp',
405
								success: function(data) {
406
									var cle = '';
407
									for (name in data['resultat']) {
408
										if (data['resultat'][name]['retenu'] == 'true') {
409
											cle = name;
410
											break;
411
										}
412
									}
413
									obs.famille = data['resultat'][cle]['famille'];
414
									obs.nom_sci_retenu = data['resultat'][cle]['nom_sci'];
415
									obs.nn_retenu = cle;
416
								 },
417
								 error: function() {
418
									 maj = 0;
419
								 },
420
								async:   false
421
							});
422
						 },
423
						async:   false
424
					});
425
				}
426
 
427
				obs.maj = maj;
428
			}
429
 
430
			sauvegarderObs(obs.num, obs);
431
		}
432
	}
433
}
434
 
435
//+----------------------------------------------------------------------------------------------------------+
436
// Autocomplétion des noms latins
437
var recherche = '';
438
$(document).on('pageinit', '#saisie', function() {
439
    $('#liste-noms-latins').on('listviewbeforefilter', function(e, data) {
440
        var $input = $(data.input);
441
        recherche = $input.val();
442
 
443
		$input.keyup(function() {
444
			clearTimeout($.data(this, 'timer'));
445
			var wait = setTimeout(lancerRecherche, DELAI_RECHERCHE);
446
			$(this).data('timer', wait);
447
		});
448
    });
449
});
450
 
451
function lancerRecherche() {
452
	var $ul = $('#liste-noms-latins'),
453
		html = '';
454
    $ul.html('');
455
 
456
	if (recherche && recherche.length > 2) {
457
		afficherChargement();
458
		$ul.html('<li><div class="ui-loader"><span class="ui-icon ui-icon-loading"></span></div></li>');
459
		$ul.listview('refresh');
460
		$.ajax({ })
461
		.then(function() {
462
			for (index in BDTFX) {
463
				var espece = BDTFX[index],
464
					nom_sci = espece['nom_sci'],
465
					num_nom = espece['num_nom'],
466
					auteur = espece['auteur'],
467
					annee = espece['annee'],
468
					nom_sci_complet = nom_sci + ((auteur == '' || auteur == null) ? '' : (' ' + auteur)) + ((annee == '' || annee == null) ? '' : (' (' + annee + ')'));
469
 
470
				if (nom_sci !== '') {
471
					var arr_nom_sci = nom_sci.split(' '),
472
						arr_recherche = recherche.split(' ');
473
 
474
					if (arr_nom_sci[1] !== undefined) {
475
						nom_sci_recherche = arr_nom_sci[1];
476
 
477
						if (arr_nom_sci[1].toLowerCase() == 'x') {
478
							nom_sci_recherche = arr_nom_sci[2];
479
						}
480
					} else {
481
						nom_sci_recherche = arr_nom_sci[0];
482
					}
483
 
484
					if ((arr_nom_sci[0].toLowerCase().substring(0, arr_recherche[0].length)) == arr_recherche[0].toLowerCase()) {
485
						var flag = true;
486
						if (arr_recherche[1] !== undefined) {
487
							flag = ( (nom_sci_recherche.toLowerCase().substring(0, arr_recherche[1].length)) == arr_recherche[1].toLowerCase() );
488
						}
489
 
490
						if (flag) {
491
							html += '<li>'
492
									+ '<a href="#" data-nom-sci="' + nom_sci + '" data-num-nom="' + num_nom + '" '
493
										+ ' data-auteur="' + auteur + '" data-nom-sci-complet="' + nom_sci_complet
494
										+ '" class="noms-latins" >'
495
									+ nom_sci_complet
496
									+ '</a>'
497
								+ '</li>';
498
						}
499
					}
500
				}
501
			}
502
			$.mobile.loading('hide');
503
			$ul.html(html);
504
			$ul.listview('refresh');
505
			$ul.trigger('updatelayout');
506
			$('.noms-latins').on('click', choisirEspece);
507
		});
508
	}
509
}
510
 
511
function afficherChargement() {
512
	var $this = $('#recherche-chargement'),
513
		theme = $this.jqmData("theme") || $.mobile.loader.prototype.options.theme,
514
		msgText = $this.jqmData("msgtext") || $.mobile.loader.prototype.options.text,
515
		textVisible = $this.jqmData("textvisible") || $.mobile.loader.prototype.options.textVisible,
516
		textonly = !!$this.jqmData("textonly");
517
		html = $this.jqmData("html") || "";
518
	$.mobile.loading( 'show', {
519
			text: msgText,
520
			textVisible: textVisible,
521
			theme: theme,
522
			textonly: textonly,
523
			html: html
524
	});
525
 }
526
 
527
function choisirEspece(event) {
528
	var espece = event.currentTarget,
529
		auteur = espece.getAttribute('data-auteur'),
530
		nom_sci = espece.getAttribute('data-nom-sci'),
531
		nom_sci_complet = espece.getAttribute('data-nom-sci-complet')
532
		num_nom = espece.getAttribute('data-num-nom');
533
 
534
	$('#nom').html(nom_sci_complet);
535
	$('#nom-sci-select').val(nom_sci);
536
	$('#num-nom-select').val(num_nom);
537
	$('#liste-noms-latins').html('');
538
	$('#saisie-popup').dialog('close');
539
}
540
 
541
//+----------------------------------------------------------------------------------------------------------+
542
// Manifest Cache
543
var appCache = window.applicationCache;
544
console.log(appCache);
545
appCache.addEventListener('updateready', function() {
546
	if (appCache.status === appCache.UPDATEREADY) {
547
		surMiseAJourCache();
548
	}
549
});
550
 
551
function surMiseAJourCache() {
552
	appCache.swapCache();
553
	if (confirm('Une nouvelle version de ce site est disponible. Mettre à jour ?')) {
554
	  window.location.reload();
555
	}
556
}
557
 
558
//+----------------------------------------------------------------------------------------------------------+
559
//Transmission données
560
$(document).ready(function() {
561
	$('#transmettre-obs').on('click', transmettreObs);
562
});
563
 
564
function transmettreObs() {
565
	var msg = '',
566
		courriel = ($('#courriel').val() == '') ? bdd.getItem('utilisateur.courriel') : $('#courriel').val();
567
	if (recupererStatutIdentite() == 'true' && validerCourriel(courriel)) {
568
		if (verifierConnexion()) {
569
			var nbre = bdd.length;
570
			for (var i = 0; i < nbre; i++) {
571
				var cle = bdd.key(i);
572
				if (cle.indexOf('obs') !== -1) {
573
					var obs = JSON.parse(bdd.getItem(cle));
574
					stockerObsData(obs);
575
				}
576
			}
577
 
578
			var observations = $('#details-obs').data();
579
			if (observations == undefined || jQuery.isEmptyObject(observations)) {
580
				msg = 'Aucune observation à transmettre.';
581
			} else {
582
				msg = 'Transmission en cours...';
583
				observations['projet'] = TAG_PROJET;
584
				observations['tag-obs'] = '';
585
				observations['tag-img'] = '';
586
 
587
				var utilisateur = new Object();
588
				utilisateur.id_utilisateur = ($('#id-utilisateur').val() == '') ? bdd.getItem('utilisateur.id') : $('#id-utilisateur').val();
589
				utilisateur.prenom = ($('#prenom-utilisateur').val() == '') ? bdd.getItem('utilisateur.prenom') : $('#prenom-utilisateur').val();
590
				utilisateur.nom = ($('#nom-utilisateur').val() == '') ? bdd.getItem('utilisateur.nom') : $('#nom-utilisateur').val();
591
				utilisateur.courriel = courriel;
592
				observations['utilisateur'] = utilisateur;
593
				envoyerObsAuCel(observations);
594
			}
595
		} else {
596
			msg = 'Aucune connexion disponible. Merci de réessayer ultérieurement.';
597
		}
598
	} else {
599
		msg = 'Merci de vérifier et de confirmer votre adresse e-mail avant de transmettre vos observations.';
600
	}
601
 
602
	if (msg != '') {
603
		$('#identification-infos').html('<p class="reponse">' + msg + '</p>')
604
			.fadeIn(0)
605
			.delay(2000)
606
			.fadeOut('slow');
607
	}
608
}
609
 
610
function verifierConnexion() {
611
	return ( ('onLine' in navigator) && (navigator.onLine));
612
}
613
 
614
function stockerObsData(obs) {
615
	var nbre = bdd.length,
616
		img_noms = new Array(),
617
		img_codes = new Array();
618
	for (var i = 0; i < nbre; i++) {
619
		var cle = bdd.key(i);
620
		if (cle.indexOf(TEXTE_PHOTO) !== -1) {
621
			var photo = JSON.parse(bdd.getItem(cle));
622
			if (photo.parent == obs.num) {
623
				img_noms.push(photo.nom);
624
				img_codes.push(photo.base64);
625
			}
626
		}
627
	}
628
 
629
	$('#details-obs').data(obs.num, {
630
		'date' : obs.date,
631
		'notes' : '',
632
 
633
		'nom_sel' : obs.nom,
634
		'num_nom_sel' : obs.nn_select,
635
		'nom_ret' : obs.nom_sci_retenu,
636
		'num_nom_ret' : obs.nn_retenu,
637
		'num_taxon' : obs.num_taxon,
638
		'famille' : obs.famille,
639
		'referentiel' : obs.referentiel,
640
 
641
		'latitude' : obs.lat,
642
		'longitude' : obs.lng,
643
		'commune_nom' : obs.commune,
644
		'commune_code_insee' : obs.code_insee,
645
		'lieudit' : '',
646
		'station' : '',
647
		'milieu' : '',
648
 
649
		//Ajout des champs images
650
		'image_nom' : img_noms,
651
		'image_b64' : img_codes
652
	});
653
}
654
 
655
 
656
function envoyerObsAuCel(observations) {
657
	console.log(observations);
658
	var msg = '';
659
	var erreurMsg = '';
660
	$.ajax({
661
		url : SERVICE_SAISIE_URL,
662
		type : 'POST',
663
		data : observations,
664
		dataType : 'json',
665
		success : function(data, textStatus, jqXHR) {
666
			console.log('Transmission SUCCESS.');
667
			msg = 'Transmission réussie ! Vos observations sont désormais disponibles sur votre carnet en ligne et ont été supprimées sur cette application.';
668
			$('#identification-infos').html('<p class="reponse">' + msg + '</p>')
669
				.fadeIn(0)
670
				.delay(2000)
671
				.fadeOut('slow');
672
		},
673
		statusCode : {
674
			500 : function(jqXHR, textStatus, errorThrown) {
675
				erreurMsg += 'Erreur 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
676
				msg = 'Erreur 500. Merci de contacter le responsable.';
677
		    }
678
		},
679
		error : function(jqXHR, textStatus, errorThrown) {
680
			erreurMsg += 'Erreur Ajax :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
681
				msg = 'Erreur indéterminée. Merci de contacter le responsable.';
682
			try {
683
				reponse = jQuery.parseJSON(jqXHR.responseText);
684
				if (reponse != null) {
685
					$.each(reponse, function (cle, valeur) {
686
						erreurMsg += valeur + '\n';
687
					});
688
				}
689
			} catch(e) {
690
				erreurMsg += 'L\'erreur n\'était pas en JSON.';
691
			}
692
		},
693
		complete : function(jqXHR, textStatus) {
694
			console.log('complete');
695
			console.log(jqXHR);
696
		}
697
	});
698
}
699
 
700
//+---------------------------------------------------------------------------------------------------------+
701
//IDENTITÉ
702
$(document).ready(function() {
703
	$('#courriel').on('blur', requeterIdentite);
704
	$('#courriel').on('keypress', function(event) {
705
		if (event.which == 13) {
706
			requeterIdentite();
707
		}
708
	});
709
 
710
	$('body').on('pagebeforeshow', '#transmission', completerCompte);
711
	$('body').on('pagebeforeshow', '#identification-popup', testerLancementRequeteIdentite);
712
 
713
	$('#valider-courriel').on('vmousedown', requeterIdentite);
714
	$('#valider-identification').on('vmousedown', confirmerIdentification);
715
});
716
 
717
function completerCompte() {
718
	if (bdd.getItem('utilisateur.courriel') != null) {
719
		var courriel = bdd.getItem('utilisateur.courriel');
720
		$('#identification-texte').html(TEXTE_OUI_COMPTE);
721
		$('#utilisateur-compte').html(courriel);
722
		$('#identification-btn * .ui-btn-text').html('Modifier le compte');
723
	} else {
724
		$('#identification-texte').html(TEXTE_NON_COMPTE);
725
		$('#identification-btn * .ui-btn-text').html('Ajouter un compte');
726
	}
727
}
728
 
729
function testerLancementRequeteIdentite(event) {
730
	if (bdd.getItem('utilisateur.courriel') != null) {
731
		var courriel = bdd.getItem('utilisateur.courriel');
732
		$('#courriel').val(courriel);
733
 
734
		if (recupererStatutIdentite() == 'true') {
735
			$('#courriel-confirmation').val(courriel);
736
		}
737
	}
738
	if (bdd.getItem('utilisateur.nom') != null) {
739
		$('#nom-utilisateur').val(bdd.getItem('utilisateur.nom'));
740
	}
741
	if (bdd.getItem('utilisateur.prenom') != null) {
742
		$('#prenom-utilisateur').val(bdd.getItem('utilisateur.prenom'));
743
	}
744
	if (bdd.getItem('utilisateur.id') != null) {
745
		$('#id-utilisateur').val(bdd.getItem('utilisateur.id'));
746
	}
747
 
748
	event.preventDefault();
749
	event.stopPropagation();
750
}
751
 
752
function recupererStatutIdentite() {
753
	return bdd.getItem('utilisateur.identite');
754
}
755
 
756
function confirmerIdentification(event) {
757
	confirmerCourriel();
758
	changerPage('#transmission', event);
759
}
760
 
761
function confirmerCourriel() {
762
	if (validerCourriel($('#courriel').val())) {
763
		if ($('#courriel').val() == $('#courriel-confirmation').val()) {
764
			bdd.setItem('utilisateur.identite', true);
765
		} else {
766
			bdd.setItem('utilisateur.identite', false);
767
		}
768
	} else  {
769
		$('#identification-infos').html('<p class="reponse">Adresse e-mail invalide.</p>')
770
			.fadeIn(0)
771
			.delay(2000)
772
			.fadeOut('slow');
773
	}
774
}
775
 
776
function requeterIdentite(event) {
777
	var courriel = $('#courriel').val();
778
	if (validerCourriel(courriel)) {
779
		miseAJourCourriel();
780
		var urlAnnuaire = SERVICE_ANNUAIRE + courriel;
781
		$.ajax({
782
			url : urlAnnuaire,
783
			type : 'GET',
784
			success : function(data, textStatus, jqXHR) {
785
				console.log('Annuaire SUCCESS : ' + textStatus);
786
				if (data != undefined && data[courriel] != undefined) {
787
					var infos = data[courriel];
788
					$('#id-utilisateur').val(infos.id);
789
					$('#prenom-utilisateur').val(infos.prenom);
790
					$('#nom-utilisateur').val(infos.nom);
791
					$('#courriel-confirmation').val(courriel);
792
					$('#prenom-utilisateur, #nom-utilisateur, #courriel-confirmation').attr('disabled', 'disabled');
793
 
794
					if ($('#courriel-memoire').is(':checked')) {
795
						bdd.setItem('utilisateur.prenom',  $("#prenom-utilisateur").val());
796
						bdd.setItem('utilisateur.nom',  $("#nom-utilisateur").val());
797
						bdd.setItem('utilisateur.id',  $("#id-utilisateur").val());
798
					}
799
				} else {
800
					surErreurCompletionCourriel();
801
				}
802
			},
803
			error : function(jqXHR, textStatus, errorThrown) {
804
				console.log('Annuaire ERREUR : ' + textStatus);
805
				surErreurCompletionCourriel();
806
			},
807
			complete : function(jqXHR, textStatus) {
808
				console.log('Annuaire COMPLETE : ' + textStatus);
809
				$('#zone-prenom-nom').removeClass('hidden');
810
				$('#zone-courriel-confirmation').removeClass('hidden');
811
			}
812
		});
813
	}
814
 
815
	event.preventDefault();
816
	event.stopPropagation();
817
}
818
 
819
function validerCourriel(email) {
820
    var regex = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i),
821
		flag = regex.test(email);
822
 
823
    console.log('Valid email ? (', email, ') : ', flag);
824
    return flag;
825
}
826
 
827
function miseAJourCourriel() {
828
	if ($('#courriel-memoire').is(':checked')) {
829
		bdd.setItem('utilisateur.courriel',  $("#courriel").val());
830
	}
831
}
832
 
833
function surErreurCompletionCourriel() {
834
	$('#id-utilisateur').val('');
835
	$('#prenom-utilisateur, #nom-utilisateur, #courriel-confirmation').removeAttr('disabled');
836
}