Subversion Repositories eFlore/Applications.cel

Rev

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

Rev Author Line No. Line
3631 idir 1
function WidgetPhotoPopup( proprietes ) {
2
	if( this.valOk( proprietes ) ) {
3823 idir 3
		this.urlWidget                    = proprietes.urlWidget;
4
		this.urls                         = proprietes.urls;
3837 idir 5
		this.infosImages                  = proprietes.infosImages;
6
		this.urlImage                     = proprietes.urlImage;
7
		this.indexPremiereImage           = proprietes.indexPremiereImage;
3833 idir 8
		this.indexImage                   = this.indexPremiereImage;
3823 idir 9
		this.tailleMax                    = proprietes.tailleMax;
10
		this.popupUrl                     = proprietes.popupUrl;
11
		this.urlBaseTelechargement        = proprietes.urlBaseTelechargement;
12
		this.urlServiceRegenererMiniature = proprietes.urlServiceRegenererMiniature;
3958 julien 13
		this.userId       				  = proprietes.userId;
14
		this.token						  = proprietes.token;
15
		this.protocoles					  = proprietes.protocoles;
3983 julien 16
		this.urlServiceDel				  = proprietes.urlServiceDel;
3631 idir 17
	}
3958 julien 18
	this.protocole = null;
19
	this.voteId = null;
20
	this.votes = null;
3823 idir 21
	this.mettreAJourInfosImage();
3631 idir 22
}
23
 
3825 idir 24
WidgetPhotoPopup.prototype = new WidgetPhotoCommun();
3631 idir 25
 
26
WidgetPhotoPopup.prototype.initTpl = function() {
27
	this.redimensionnerGalerie();
3837 idir 28
	$( '#info-img-galerie' ).find( '.active' ).removeClass( 'active' );
29
	$( '#img-cadre-' + this.indexImage + ',#indicateur-img-' + this.indexImage ).addClass( 'active' );
3823 idir 30
 
3837 idir 31
	this.mettreAJourPopup();
3823 idir 32
 
3631 idir 33
	this.redimentionnerModaleCarousel();
34
};
35
 
36
WidgetPhotoPopup.prototype.initEvts = function() {
37
	const lthis = this;
38
 
39
	this.initEvtsDefilerImage();
3980 julien 40
	// this.initEvtsContact();
3631 idir 41
	$( window ).on( 'resize', lthis.redimentionnerModaleCarousel.bind( lthis ) );
3823 idir 42
	this.initEvtsFonctionsPhoto();
3631 idir 43
	this.initEvtsRetourGalerieResponsive();
44
};
45
 
3823 idir 46
WidgetPhotoPopup.prototype.mettreAJourPopup = function() {
47
	this.mettreAJourInfosImage();
48
	this.afficherTitreImage();
49
	this.traiterMetas();
50
	this.regenererMiniature();
51
	this.fournirLienIdentiplante();
3948 julien 52
	this.pivoterImage();
3958 julien 53
	this.initEvtsProtocole();
3983 julien 54
	this.initEvtsTagsPF();
55
	this.initEvtsTagsCel();
3823 idir 56
};
57
 
58
WidgetPhotoPopup.prototype.mettreAJourInfosImage = function() {
3837 idir 59
	this.item          = this.infosImages[this.urls[this.indexImage]];
3826 idir 60
	this.titreImage    = this.item['titre'];
3825 idir 61
	this.urlLienEflore = this.item['lien'];
3826 idir 62
	this.idImage       = this.item['id_photo'];
3946 julien 63
 
64
	// If last caract of the url is a ',' we remove it
65
	const lastCaractUrlImage = this.item['url_photo'].slice(-1);
66
	if (lastCaractUrlImage === ','){
67
		this.item['url_photo'] = this.item['url_photo'].replace(/.$/,'');
68
	}
69
 
3826 idir 70
	this.urlThisImage  = this.item['url_photo']+'.jpg';
71
	this.obs           = this.item['obs'];
72
	this.nn            = '[nn' + this.obs['nom_sel_nn']+']';
73
	this.urlIP         = this.obs['url_ip'];
74
	this.tagsImage     = this.tagsToArray( this.item['tags_photo'] );
75
	this.tagsObs       = this.tagsToArray( this.obs['tags_obs'] );
3958 julien 76
	let auteurMail = this.item['utilisateur']['mail_utilisateur'].split("@")[0];
77
	this.auteur        = this.item["utilisateur"]["nom_utilisateur"] ? this.item["utilisateur"]["nom_utilisateur"] : auteurMail;
3826 idir 78
	this.date          = this.item['date'];
3823 idir 79
};
80
 
3825 idir 81
WidgetPhotoPopup.prototype.tagsToArray = function( tags ) {
3832 idir 82
	if(!this.valOk(tags)) {
83
		return [];
84
	}
3825 idir 85
	tags = tags.replace( new RegExp('\\.'), '' ).split( ',' );
86
 
87
	let cleanTags       = [],
88
		nbTags          = tags.length,
89
		tag             = '',
90
		tagsSansEspaces = '',
91
		cleanTagIndex   = 0;
92
 
93
	for(let i = 0; i < nbTags; i++) {
94
		tag = tags[i];
95
		tagsSansEspaces = tag.replace( ' ', '');
96
		if( '' !== tagsSansEspaces ) {
97
			cleanTags.push( tag.trim() );
98
		}
99
	}
100
 
101
	return cleanTags;
102
};
103
 
3631 idir 104
WidgetPhotoPopup.prototype.initEvtsDefilerImage = function() {
105
	const lthis = this;
106
 
3983 julien 107
	$( '#precedent, #suivant' ).off('click');
108
 
3631 idir 109
	$( '#precedent, #suivant' ).on( 'click', function() {
110
		lthis.defilerImage( this.id );
3983 julien 111
		lthis.initEvtsTagsPF();
3631 idir 112
	});
3823 idir 113
 
3631 idir 114
	$( '#print_content:not(saisir-tag)' ).on( 'keydown', function( event ) {
115
 
3823 idir 116
		const determinerSens = function( enventKey, left, right ) {
117
			switch ( enventKey ) {
118
				case left:
119
					return 'suivant';
120
				case right:
3825 idir 121
					return 'precedent';
3823 idir 122
				default:
123
					break;
3631 idir 124
			}
3823 idir 125
 
126
			return;
3631 idir 127
		}
3823 idir 128
 
129
		event = (event || window.event);
130
		// event.keyCode déprécié, on tente d'abord event.key
131
		let sens = ( 'key' in event ) ? determinerSens( event.key, 'ArrowLeft', 'ArrowRight' ) : determinerSens( event.keyCode, 37, 39 );;
132
 
3631 idir 133
		if ( lthis.valOk( sens ) ) {
134
			lthis.defilerImage( sens );
135
		}
136
	});
137
};
138
 
3980 julien 139
// WidgetPhotoPopup.prototype.initEvtsContact = function() {
140
// 	const lthis = this;
141
//
142
// 	$( '#bloc-infos-img' ).on( 'click', '.lien_contact', function( event ) {
143
// 		event.preventDefault();
144
// 		lthis.chargerContenuModale( this.href );
145
// 	});
146
// };
3631 idir 147
 
3823 idir 148
WidgetPhotoPopup.prototype.initEvtsFonctionsPhoto = function() {
3631 idir 149
	const lthis = this;
150
 
151
	$( '#boutons-footer #bloc-fct a, #retour-metas' ).on( 'click', function( event ){
152
		event.preventDefault();
153
		var voletAOuvrir = $( this ).data( 'volet' ),
154
			voletAFermer = $( '.bloc-volet:not(.hidden)' ).data( 'volet' );
155
 
156
		lthis.ouvrirVoletFct( voletAOuvrir, voletAFermer );
157
		if ( window.matchMedia( '(max-width: 991px)' ).matches ) {
158
			$( '#info-img-galerie' ).addClass( 'hidden' );
159
			$( '#volet, #retour-galerie' ).removeClass( 'hidden' );
160
		}
161
	});
162
};
163
 
164
WidgetPhotoPopup.prototype.initEvtsRetourGalerieResponsive = function() {
165
	$( '#retour-galerie' ).on( 'click', function( event ) {
166
		event.preventDefault();
167
		$( '#info-img-galerie' ).removeClass( 'hidden' );
168
		$( this ).addClass( 'hidden' );
169
		if ( window.matchMedia( '(max-width: 991px)' ).matches ) {
170
			$( '#volet' ).addClass( 'hidden' );
171
			$( '.bouton-fct.actif' ).removeClass( 'actif' );
172
		}
173
	});
174
};
175
 
3983 julien 176
WidgetPhotoPopup.prototype.initEvtsTagsCel = function(){
177
	const lthis = this;
178
	$( '#tags-cel' ).html('');
179
 
180
	$( '#tags-cel' ).append(
181
		"<p>"+ lthis.item['tags_photo']+"</p>"
182
	)
183
}
184
 
3631 idir 185
WidgetPhotoPopup.prototype.initEvtsTagsPF = function() {
3983 julien 186
	const tagsPfDiv = $('#tags-pf');
187
	tagsPfDiv.html('');
188
	tagsPfDiv.append('<a id="port" class="btn tag">Port</a>' +
189
		'<a id="fleur" class="btn tag">Fleur</a>' +
190
		'<a id="fruit" class="btn tag">Fruit</a>' +
191
		'<a id="feuille" class="btn tag">Feuille</a>' +
192
		'<a id="ecorce" class="btn tag">Ecorce</a>' +
193
		'<a id="rameau" class="btn tag">Rameau</a>' +
194
		'<a id="planche" class="btn tag">Planche</a>' +
195
		'<a id="rosette" class="btn tag">Rosette</a>' +
196
		'<a id="pousse" class="btn tag">Pousse</a>');
197
 
198
	this.tagsPf();
3631 idir 199
	this.tagsPfCustom();
3983 julien 200
 
201
	$( '#bloc-tags' ).off('click');
202
 
3631 idir 203
	$( '#bloc-tags' ).on( 'click', '.tag', function( event ) {
204
		event.preventDefault();
205
		$( this ).toggleClass( 'actif' );
3983 julien 206
 
207
		var motCleClique = '';
208
		motCleClique = $(this).attr('id');
209
 
210
		// Utiliser la méthode findIndex pour obtenir l'index de l'élément dans le tableau
211
		var indexElementTrouve = lthis.item['tags_pf'].findIndex(function (tag) {
212
			return tag['mot_cle'] === motCleClique;
213
		});
214
 
215
		// Vérifier si l'élément a été trouvé
216
		if (indexElementTrouve !== -1) {
217
			//supprimer tag dans DEL
218
			if (lthis.item['tags_pf'][indexElementTrouve].hasOwnProperty('id_mot_cle') && lthis.item['tags_pf'][indexElementTrouve]['id_mot_cle'] != ''){
219
				let url = lthis.urlServiceDel + 'mots-cles/' + lthis.item['tags_pf'][indexElementTrouve]['id_mot_cle']
220
 
221
				lthis.envoyerVersService('DELETE', url)
222
			}
223
 
224
			// Supprimer l'élément de this.item['tags_pf'] à l'index trouvé
225
			lthis.item['tags_pf'].splice(indexElementTrouve, 1);
226
		} else {
227
			//Ajout tag dans le DEL
228
			let url = lthis.urlServiceDel + 'mots-cles';
229
			let donnees = {
230
				"image" : lthis.idImage,
231
				"mot_cle" : motCleClique,
232
				"auteur.id" : lthis.item["utilisateur"]["id_utilisateur"]
233
			}
234
 
235
			lthis.envoyerVersService('PUT', url, JSON.stringify(donnees), function (erreur, tagId) {
236
				if (erreur) {
237
					console.error("Erreur lors de la requête :", erreur);
238
				} else {
239
					console.log('tag : ' + motCleClique + ' ajouté');
240
					lthis.item['tags_pf'].push({'id_mot_cle' : tagId['id'][0], 'mot_cle' : motCleClique})
241
				}
242
			});
243
		}
244
		//TODO post vers le del
3631 idir 245
	});
3983 julien 246
	/* //@TODO est-ce qu'on garde cette croix?
3631 idir 247
	$( '#bloc-tags' ).on( 'click', '.custom-tag.actif .fermer', function( event ) {
248
		event.preventDefault();
249
		//			Supprimer un custom-tag
250
		//	_OPTIONS
251
		// https://api-test.tela-botanica.org/service:del:0.1/mots-cles/38368
252
		// 	_paramètres
253
		// L'id du tag à la fin de l'url
254
		//	_DELETE
255
		// https://api-test.tela-botanica.org/service:del:0.1/mots-cles/38368
256
		// 	_réponse:
257
		// ""
258
		// 			Mettre à jour les mots cles
259
		//	_OPTIONS
260
		// https://api-test.tela-botanica.org/service:del:0.1/mots-cles?image=197938
261
		//	_GET
262
		// https://api-test.tela-botanica.org/service:del:0.1/mots-cles?image=197938
263
		$( this ).parent( '.custom-tag' ).remove();
264
	});
3983 julien 265
	*/
266
/*
3631 idir 267
	$( '#bloc-tags' ).on( 'keyup', '.custom-tag.actif', function( event ) {
3823 idir 268
		let supprimerTag = false;
3631 idir 269
 
3823 idir 270
		event = ( event || window.event );
3631 idir 271
		// event.keyCode déprécié, on tente d'abord event.key
272
		if ( 'key' in event ) {
273
			supprimerTag = ( 'Delete' === event.key || 'Backspace' === event.key );
274
		} else {
275
			supprimerTag = ( 46 === event.keyCode || 8 === event.keyCode );
276
		}
277
		if ( supprimerTag ) {
3823 idir 278
			//			Supprimer un custom-tag
279
			//	_OPTIONS
280
			// https://api-test.tela-botanica.org/service:del:0.1/mots-cles/38368
281
			// 	_paramètres
282
			// L'id du tag à la fin de l'url
283
			//	_DELETE
284
			// https://api-test.tela-botanica.org/service:del:0.1/mots-cles/38368
285
			// 	_réponse:
286
			// ""
287
			// 			Mettre à jour les mots cles
288
			//	_OPTIONS
289
			// https://api-test.tela-botanica.org/service:del:0.1/mots-cles?image=197938
290
			//	_GET
291
			// https://api-test.tela-botanica.org/service:del:0.1/mots-cles?image=197938
3631 idir 292
			$( this ).parent( '.custom-tag' ).remove();
293
		}
294
	});
3983 julien 295
 */
3631 idir 296
};
297
 
298
WidgetPhotoPopup.prototype.defilerImage = function( sens ) {
3823 idir 299
	if ( 'suivant' === sens ) {
3631 idir 300
		this.indexImage++ ;
3837 idir 301
		if( this.indexImage >= this.urls.length ) {
3631 idir 302
			this.indexImage = 0;
303
		}
3823 idir 304
	} else if ( 'precedent' === sens ) {
3631 idir 305
		this.indexImage--;
306
		if( this.indexImage <= 0 ) {
3837 idir 307
			this.indexImage = this.urls.length -1;
3631 idir 308
		}
309
	}
3823 idir 310
	// @TODO: Modifier l'attr content de 'meta[property=og:image]' et y mettre l'url de l'image
311
	this.mettreAJourPopup();
3631 idir 312
};
313
 
314
WidgetPhotoPopup.prototype.afficherTitreImage = function() {
3823 idir 315
	let lienContact  =
316
			this.urlWidget +'?mode=contact&nn=' + this.nn +
317
			'&nom_sci=' + this.obs['nom_sel'] +
318
			'&date=' + this.date +
319
			'&localisation=' + this.obs['localisation'] +
320
			'&id_image=' + this.idImage +
321
			'&auteur=' + this.auteur;
3631 idir 322
 
3823 idir 323
	if ( this.valOk( this.popupUrl ) ) {
324
		if (! this.popupUrl.match( new RegExp( 'img:' + this.idImage ) ) ) {
325
			this.popupUrl = this.actualiserPopupUrl( this.popupUrl, this.urlThisImage );
3631 idir 326
		}
3823 idir 327
		lienContact += '&popup_url=' + encodeURIComponent( this.popupUrl );
3631 idir 328
	}
329
 
3823 idir 330
	$( '#bloc-infos-img' ).html(
3825 idir 331
		this.afficherLien( this.urlLienEflore, this.obs['nom_sel'] )+
3823 idir 332
		' par '+
3979 julien 333
		'<a class="lien_contact" href="' + this.item['urlProfil'] + '" target="_blank" title="Afficher le profil">' + this.auteur + '</a> '+
3823 idir 334
		' le ' + this.date + ' - ' + this.obs['localisation']
335
	);
3631 idir 336
};
337
 
338
WidgetPhotoPopup.prototype.actualiserPopupUrl = function( queryString, remplacement ) {
3823 idir 339
	let queryStringParsee = queryString.substring(1).split('&');
3631 idir 340
 
341
	$.each( queryStringParsee,  function( i, param ) {
342
		if( /url_image/.test( param ) ) {
343
			queryString = queryString.replace( param, 'url_image=' + remplacement );
344
			return false;
345
		}
346
	});
347
	return queryString;
348
};
349
 
350
WidgetPhotoPopup.prototype.redimentionnerModaleCarousel = function() {
351
	this.redimensionnerGalerie();
352
	if ( window.matchMedia( '(max-width: 991px)' ).matches ) {
353
		$( '#volet, #retour-galerie' ).addClass( 'hidden' );
354
		$( '#info-img-galerie' ).removeClass( 'hidden' );
355
		$( '.bouton-fct.actif' ).removeClass( 'actif' );
356
		$( '.nettoyage-volet.haut' ).text( $( '#bloc-infos-img' ).text() );
357
		$( '#boutons-footer, #info-img-galerie' ).removeClass( 'col-lg-8' );
358
		$( '#bloc-infos-img, #volet' ).removeClass( 'col-lg-4' );
359
	} else {
360
		$( '#volet, #info-img-galerie' ).removeClass( 'hidden' );
361
		if ( this.valOk( $( '.bloc-volet:not(.hidden)' ) ) ) {
362
			$( '.bouton-fct.' + $( '.bloc-volet:not(.hidden)' ).data( 'volet' ) ).addClass( 'actif' );
363
		}
364
		$( '.nettoyage-volet.bas' ).text( $( '#bloc-infos-img' ).text() );
365
		$( '#boutons-footer, #info-img-galerie' ).addClass( 'col-lg-8' );
366
		$( '#bloc-infos-img, #volet' ).addClass( 'col-lg-4' );
367
		$( '#retour-galerie' ).addClass( 'hidden' );
368
	}
369
};
370
 
371
WidgetPhotoPopup.prototype.redimensionnerGalerie = function() {
372
	var maxSize = ( $( window ).width() / $( window ).height() ) < 1 ? $( window ).width() : $( window ).height();
373
 
374
	maxSize -= 30;
375
	$( '.carousel-item img' ).each( function( index, image ) {
376
		var proportion  = image.dataset.width / image.dataset.height,
377
			cssResize   = {};
378
 
379
		if ( proportion >= 1 ) {
380
			cssResize['width'] = maxSize;
381
		}
382
		if ( proportion <= 1) {
383
			cssResize['height'] = maxSize;
384
		}
385
		$( image ).css( cssResize );
386
	});
387
};
388
 
389
WidgetPhotoPopup.prototype.ouvrirVoletFct = function( voletAOuvrir, voletAFermer ) {
390
	if( voletAOuvrir !== voletAFermer ) {
391
		$( '#boutons-footer  .' + voletAFermer ).removeClass( 'actif' );
392
		$( '#boutons-footer  .' + voletAOuvrir ).addClass( 'actif' );
393
		$( '#bloc-' + voletAFermer ).addClass( 'hidden' );
394
		$( '#bloc-' + voletAOuvrir ).removeClass( 'hidden' );
395
		$( '#volet' ).scrollTop(0);
3823 idir 396
		$( '#retour-metas' ).removeClass( 'hidden', 'meta' === voletAOuvrir );
3631 idir 397
	}
398
};
399
 
3983 julien 400
WidgetPhotoPopup.prototype.tagsPf = function () {
401
	const lthis = this;
402
	$('#tags-pf-supp').html('');
403
 
404
	lthis.item['tags_pf'].forEach(tag => {
405
		const tagElement = document.getElementById(tag['mot_cle']);
406
 
407
		// Vérifier si l'élément existe
408
		if (tagElement) {
409
			// Ajouter la classe 'active' à l'élément <a>
410
			tagElement.classList.add('actif');
411
		} else {
412
			$('#tags-pf-supp').append('<a id="'+tag['mot_cle']+'" class="btn tag custom-tag actif">' + tag['mot_cle'] + '&nbsp;' +
413
				// '<i class="fas fa-times-circle fermer"></i>' +
414
				'</a>')
415
		}
416
	});
417
}
418
 
3631 idir 419
WidgetPhotoPopup.prototype.tagsPfCustom = function() {
420
	const lthis = this;
421
 
422
	$( '#saisir-tag' ).on( 'blur keyup', function( event ) {
3823 idir 423
		event = ( event || window.event );
3631 idir 424
 
425
		var ajouterTag = ( 'blur' === event.type );
426
 
427
		// event.keyCode déprécié, on tente d'abord event.key
428
		if ( 'key' in event  ) {
429
			if ( 'Enter' === event.key ) {
430
				ajouterTag = true;
431
			}
432
		} else if ( 13 === event.keyCode ) {
433
			ajouterTag = true;
434
		}
435
		if	( ajouterTag ) {
436
			var nouveauTag     = $( this ).val(),
437
				nouveauTagAttr = lthis.chaineValableAttributsHtml( nouveauTag.toLowerCase() );
438
 
439
			if( lthis.valOk( nouveauTagAttr ) && !lthis.valOk( $( '#' + nouveauTagAttr + '.tag' ) ) ) {
440
				$( '#tags-pf-supp' ).append(
3823 idir 441
					'<a id="' + nouveauTagAttr + '" class="btn tag custom-tag actif">' +
3983 julien 442
						nouveauTag + '&nbsp;' +
443
					// '<i class="fas fa-times-circle fermer"></i>' +
3631 idir 444
					'</a>'
445
				);
3983 julien 446
 
447
				let url = lthis.urlServiceDel + 'mots-cles';
448
				let donnees = {
449
					"image" : lthis.idImage,
450
					"mot_cle" : nouveauTagAttr,
451
					"auteur.id" : lthis.item["utilisateur"]["id_utilisateur"]
452
				}
453
 
454
				// Envoie du nouveau tag dans le DEL
455
				lthis.envoyerVersService('PUT', url, JSON.stringify(donnees), function (erreur, tagId) {
456
					if (erreur) {
457
						console.error("Erreur lors de la requête :", erreur);
458
					} else {
459
						console.log('tag : ' + nouveauTagAttr + ' ajouté');
460
						lthis.item['tags_pf'].push({'id_mot_cle' : tagId['id'][0], 'mot_cle' : nouveauTagAttr})
461
					}
462
				});
463
 
464
				// $( '#form-tags-auteur' )[0].reset();
3631 idir 465
				$( this ).val( '' );
466
			}
467
		}
468
	});
469
};
3823 idir 470
 
471
WidgetPhotoPopup.prototype.traiterMetas = function() {
472
	this.afficherMetas();
473
	this.afficherPopupLocalisation();
474
	this.afficherMetasPlus();
475
	this.fournirLienTelechargement();
476
};
477
 
478
WidgetPhotoPopup.prototype.afficherMetas = function() {
479
	const lthis         = this;
480
	const META_CONTENUS = {
3825 idir 481
		'nom' : this.afficherLien( this.urlLienEflore, this.obs['nom_sel'] ),
3823 idir 482
		'localisation' : this.obs['localisation'],
483
		'auteur' : this.auteur,
484
		'date-obs' : this.date,
485
		'commentaire' : this.obs['commentaire'],
486
		'certitude' : this.obs['certitude'],
487
		'fiabilite' : this.obs['fiabilite'],
488
		'num-photo' : this.idImage,
489
		'titre-original' : this.item['nom_original'],
490
		'date-photo' : this.formaterDate( this.item['date_photo'] ),
491
		'attribution-copy' : this.item['attribution'],
492
		'url-copy' : this.urlThisImage
493
	};
494
 
495
	$.each( META_CONTENUS, function( attrId, contenu ) {
496
		let $metaContainer = $( '#bloc-meta #'+attrId );
497
 
498
		if ( lthis.valOk( contenu ) ) {
499
			switch( attrId ) {
500
				case 'attribution-copy' :
501
				case 'url-copy' :
502
					$metaContainer.val( contenu );
503
					lthis.copieAutoChamp( $metaContainer );
504
					break;
505
				case 'nom' :
506
					$( '.contenu', $metaContainer ).html( contenu );
3825 idir 507
					$( '.bouton', $metaContainer ).attr( 'href', lthis.urlLienEflore );
3823 idir 508
					break;
509
				case 'auteur' :
3827 idir 510
					$( '.bouton', $metaContainer ).attr( 'href', lthis.item['urlProfil'] );
3823 idir 511
				default:
512
					$( '.contenu', $metaContainer ).text( contenu );
513
					break;
514
			}
515
		}
516
	});
517
};
518
 
3824 idir 519
WidgetPhotoPopup.prototype.copieAutoChamp = function( $champACopier ) {
3838 idir 520
	$champACopier.off( 'click' ).on( 'click', function() {
521
		$( '#attribution-copy, #url-copy' ).removeClass( 'hidden' )
522
			.find( '.copy-message' ).remove();
3823 idir 523
 
524
		$( this ).select();
525
		document.execCommand( 'copy' );
526
 
527
		$( this ).after(
528
			'<p class="copy-message alert-success" style="width: 100%; height:' + $( this ).outerHeight() + 'px; margin: 0; display:flex;">'+
529
				'<span style="margin:auto; font-size:1rem;">Copié dans le presse papier</span>'+
530
			'</p>'
531
		).addClass( 'hidden' );
532
 
533
		setTimeout( function() {
534
			$( '.copy-message' ).remove();
535
			$champACopier.removeClass( 'hidden' );
536
		}, 1000 );
537
	});
538
};
539
 
540
WidgetPhotoPopup.prototype.afficherMetasPlus = function() {
541
	const lthis         = this;
542
	const META_LABELS  = {
543
		'id_obs' : 'observation n°',
544
		'projet' : 'projet',
3825 idir 545
		'nom_referentiel' : 'réferentiel',
3823 idir 546
		'date_obs' : 'date d´observation',
547
		'nom_sel': 'nom scientifique',
548
		'nom_sel_nn' : 'nom scientifique n°',
549
		'nom_ret' : 'nom retenu',
550
		'nom_ret_nn' : 'nom retenu n°',
551
		'famille' : 'famille',
552
		'tags_obs' : 'tags de l´observation',
553
		'lieudit' : 'lieu dit',
554
		'station' : 'station',
555
		'milieu' : 'milieu',
556
		'latitude' : 'latitude',
557
		'longitude' : 'longitude',
558
		'altitude' : 'altitude',
559
		'localisation_precision': 'précision de la localisation',
560
		'code_insee' : 'code insee de la commune',
561
		'dept' : 'département',
562
		'pays' : 'pays',
563
		'est_ip_valide' : 'validée sur identiplante',
564
		'score_ip' : 'score identiplante',
565
		'url_ip' : 'url identiplante',
566
		'abondance' : 'abondance',
567
		'phenologie' : 'phénologie',
568
		'spontaneite' : 'spontaneite',
569
		'type_donnees' : 'type de donnees',
570
		'biblio' : 'bibliographie',
571
		'source' : 'source',
572
		'herbier' : 'herbier',
573
		'observateur' : 'observateur',
574
		'observateur_structure' : 'structure'
575
	};
3825 idir 576
 
3823 idir 577
	const $contenuPlusMeta  = $( '#contenu-meta-plus' );
3825 idir 578
	let degres = $contenuPlusMeta.is( ':visible' ) ? '180' : '0';
3823 idir 579
 
580
	this.rotationFleche( degres );
3825 idir 581
	$contenuPlusMeta.empty();
3823 idir 582
 
583
	$.each( META_LABELS, function( cle, label ) {
584
		let idAttr = cle.replace( '_', '-' ),
585
			contenu = lthis.obs[cle];
586
 
3825 idir 587
		switch( cle ) {
588
			case 'nom_sel':
589
				contenu = lthis.afficherLien( lthis.urlLienEflore, contenu );
590
				break;
591
 
592
			case 'nom_ret':
593
				let urlEfloreNomRetenu = lthis.urlLienEflore.replace( lthis.obs['nom_sel_nn'], lthis.obs['nom_ret_nn'] );
594
 
595
				contenu = lthis.afficherLien( urlEfloreNomRetenu, contenu );
596
				break;
597
 
598
			case 'url_ip':
599
				contenu = lthis.afficherLien( contenu, contenu );
600
				break;
601
 
602
			case 'est_ip_valide':
603
			case 'herbier':
604
				if( '0' === contenu ) {
605
					contenu = 'non';
606
				}
607
				break;
608
 
609
			case 'date_obs':
610
				contenu = lthis.formaterDate( contenu );
611
				break;
612
 
613
			case 'tags_obs':
614
				let tagsObsLength = lthis.tagsObs.length;
615
				contenu = lthis.tagsObs.join( '<br>' );
616
				break;
617
 
618
			default:
619
				break;
3823 idir 620
		}
621
 
622
		if ( lthis.valOk( contenu ) ) {
623
			$contenuPlusMeta.append(
624
				'<li id="' + idAttr + '-meta-plus" class="row">'+
625
					'<div class="col-5 label">' + label.charAt( 0 ).toUpperCase() + label.slice( 1 ) + '</div>'+
3829 idir 626
					'<div class="col-7 contenu">' + contenu + '</div>'+
3823 idir 627
				'</li>'
628
			);
629
		}
630
	});
631
 
3825 idir 632
	if( !$contenuPlusMeta.hasClass( 'actif' ) ) {
633
		$contenuPlusMeta.hide();
634
	}
635
 
636
	let estVisible = false;
637
 
3823 idir 638
	$( '#plus-meta' ).off( 'click' ).on( 'click', function( event ) {
639
		event.preventDefault();
640
		$contenuPlusMeta.toggle( 200, function() {
3825 idir 641
			estVisible = $contenuPlusMeta.is( ':visible' );
642
			degres     = estVisible ? '180' : '0';
643
			$( this ).toggleClass( 'actif', estVisible );
3823 idir 644
			lthis.rotationFleche( degres );
645
		});
646
	});
647
};
648
 
649
WidgetPhotoPopup.prototype.rotationFleche = function( degres ) {
650
	$( '#plus-meta i' ).css({
651
		'-webkit-transform' : 'rotate('+ degres +'deg)',
652
		'-moz-transform' : 'rotate('+ degres +'deg)',
653
		'-ms-transform' : 'rotate('+ degres +'deg)',
654
		'transform' : 'rotate('+ degres +'deg)'
655
	});
656
};
657
 
658
WidgetPhotoPopup.prototype.fournirLienTelechargement = function() {
659
	const lthis = this;
660
 
661
	$( '#formats' ).on( 'change', function() {
662
		let format             = ( $( this ).val() || 'O' ),
663
			lienTelechargement = lthis.urlBaseTelechargement + lthis.idImage + '?methode=telecharger&format=' + format;
664
 
665
		$( '#telecharger' ).attr( 'href', lienTelechargement );
666
	});
667
 
668
	$( '#formats' ).trigger( 'change' );
669
};
670
 
671
 
672
WidgetPhotoPopup.prototype.afficherPopupLocalisation = function() {
673
	const lthis = this;
674
 
675
	$( '#localisation a.bouton' ).on( 'click', function( event ){
676
		event.preventDefault();
677
 
678
		$( this ).after(
679
			'<div id="localisation-map-container">'+
680
				'<button id="map-close" type="button" class="bouton btn btn-sm btn-outline-secondary" aria-label="Close">'+
681
					'<span aria-hidden="true">×</span>'+
682
				'</button>'+
683
				'<div id="localisation-map"></div>'+
684
			'</div>'
685
		);
686
 
687
		let lat = lthis.obs['latitude'],
688
			lng = lthis.obs['longitude'],
689
			map = L.map( 'localisation-map', {
690
				zoomControl: true,
691
				dragging: false,
692
				scrollWheelZoom: 'center'
693
			} ).setView( [lat, lng], 12 );
694
 
695
		map.markers = [];
696
 
697
		L.tileLayer(
3971 julien 698
			// 'https://osm.tela-botanica.org/tuiles/osmfr/{z}/{x}/{y}.png',
699
			'https://a.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png',
3823 idir 700
			{
701
				attribution: 'Data © <a href="http://osm.org/copyright">OpenStreetMap</a>',
702
				maxZoom: 18
703
			}
704
		).addTo( map );
705
 
706
		map.addLayer( new L.FeatureGroup() );
707
 
708
		let marker = new L.Marker(
709
			{
710
				'lat': lat,
711
				'lng': lng
712
			},
713
			{
714
				draggable: false,
715
			}
716
		);
717
 
718
 
719
		map.addLayer( marker );
720
		map.markers.push( marker );
721
 
722
		$( '#map-close' ).on( 'click', function( event ){
723
			$( '#localisation-map-container' ).remove();
724
		});
725
	});
726
 
727
	$( '#fenetre-modal' ).on( 'click', function( event ) {
728
		if(
729
			!$( event.target ).closest( '#localisation-map-container' ).length
730
			&& !$( event.target ).closest( '#obs-localisation' ).length
731
		) {
732
			$( '#localisation-map-container' ).remove();
733
		}
734
	});
735
};
736
 
737
 
738
WidgetPhotoPopup.prototype.regenererMiniature = function() {
739
	const lthis = this;
740
	$( '#regenerer-miniature' ).off( 'click' ).on( 'click', function( event ) {
741
		event.preventDefault();
742
 
743
		let url = lthis.urlServiceRegenererMiniature + lthis.idImage;
3829 idir 744
		$.get( url, function( data ) {
745
				console.log( data );
746
			}
747
		).fail( function() {
3948 julien 748
			console.log( 'La régénération d´image ne s´est pas faite' );
3823 idir 749
		});
750
	});
751
};
752
 
753
WidgetPhotoPopup.prototype.formaterDate = function( sqlDate ) {
754
	dateFormatee = sqlDate
755
		.substring( 0, 10 )
756
		.split( '-' )
757
		.reverse()
758
		.join('/');
759
 
760
	return dateFormatee;
761
};
762
 
3825 idir 763
WidgetPhotoPopup.prototype.afficherLien = function( url, nom ) {
764
	if( !/https?:\/\//.test( url ) ) {
765
		url = 'https://' + url;
766
	}
767
	return '<a href="' + url + '" target="_blank">' + nom + '</a> ';
768
};
769
 
3823 idir 770
WidgetPhotoPopup.prototype.fournirLienIdentiplante = function() {
771
	const lthis = this;
772
	$( '.signaler-erreur-obs' ).each( function() {
3950 julien 773
		$( this ).attr( 'href', 'https://' + lthis.urlIP );
3823 idir 774
	});
775
};
776
 
3948 julien 777
WidgetPhotoPopup.prototype.initEvtsProtocole = function() {
778
	const lthis = this;
3958 julien 779
	$('#bloc-notes-protocole').addClass('hidden');
780
	lthis.votes = null
781
	//On transforme la promesse en array
782
	const PROTOCOLES_ARRAY = Object.values(lthis.protocoles);
3948 julien 783
 
3958 julien 784
	const $select = $('#protocole');
785
	$select.empty(); // Clear existing options
786
 
787
	// Add the default hidden option
788
	$select.append('<option value="" selected hidden>Choix du protocole</option>');
789
 
790
	PROTOCOLES_ARRAY.forEach(protocoleData => {
791
		$select.append(`<option id="protocole_${protocoleData['protocole.id']}" value="protocole_${protocoleData['protocole.id']}">${protocoleData['protocole.intitule']}</option>`);
792
	})
793
 
3948 julien 794
	$( '#protocole').on( 'change', function( event ){
795
		event.preventDefault();
3958 julien 796
		lthis.votes = null
797
 
3948 julien 798
		var id = $(this).children(":selected").attr("id");
3958 julien 799
		var protocole = id.split("_")[1];
3948 julien 800
 
801
		$('#bloc-notes-protocole').removeClass('hidden');
802
 
3958 julien 803
		// Find the object corresponding to the selected id (protocole.id)
804
		var selectedProtocoleData = PROTOCOLES_ARRAY.find(protocoleData => protocoleData['protocole.id'] === protocole);
805
 
806
		lthis.protocole = selectedProtocoleData['protocole.id'];
807
		const message = selectedProtocoleData['protocole.descriptif'];
808
 
809
		$('#message-protocole').html('<p>' + message + '</p>');
810
 
811
		// On envoie le protocole sélectionné à la partie "vote"
812
		// On récupère tous les votes de l'image depuis pictoflora
813
		lthis.votes = lthis.getVotes(lthis.protocole)
814
 
815
		// Si l'utilisateur est connect, on vérifie s'il a déjà voté pour cette image et on affiche les étoiles
816
		// correspondantes
817
		if(lthis.userId){
818
			lthis.checkUserVote(lthis.userId, lthis.protocole, lthis.votes);
819
		} else {
820
			lthis.voteId = null;
821
			lthis.removeVoteStars()
3948 julien 822
		}
3958 julien 823
 
824
		// Remove any previous click event listeners on rating stars
825
		for (let i=1; i<=5; i++){
826
			$("#rating-star-"+i).off("click");
827
		}
828
 
829
		// Si l'utilisateur vote, on affiche les étoiles correspondantes et on l'envoie vers pictoflora
830
		lthis.traiterVote();
3948 julien 831
	});
3958 julien 832
}
3948 julien 833
 
834
WidgetPhotoPopup.prototype.traiterVote = function () {
3958 julien 835
	const lthis = this;
836
	let starSelected = 0
837
	let mode = '';
3948 julien 838
 
839
	$("#note").attr("value", -1);
840
 
3958 julien 841
	// Traitement du bouton suppression du vote
3948 julien 842
	$("#note-remove").click(function (){
3958 julien 843
		lthis.removeVoteStars();
844
		mode = 'DELETE';
845
		// On n'envoie le vote que si l'utilisateur est connecté
846
		if (lthis.userId) {
847
			lthis.sendVote(lthis.userId, lthis.protocole, starSelected, mode, lthis.voteId);
848
		}
3948 julien 849
	})
850
 
3958 julien 851
	// Si l'utilisateur a déjà voté pour cette image on affiche son vote et on passe en mode modification
852
	let userAVoter = lthis.checkUserVote(lthis.userId, lthis.protocole, lthis.votes);
853
	userAVoter ? mode = 'POST' : mode = 'PUT';
3948 julien 854
 
3958 julien 855
	// Affichage du nombre d'étoiles sélectionnées et envoi du vote
856
	for (let i=1; i<=5; i++){
857
		$("#rating-star-"+i).click(function () {
858
			starSelected = i
859
			lthis.displayVote(starSelected);
860
			$("#note").attr("value", starSelected);
861
			// On n'envoie le vote que si l'utilisateur est connecté
862
			if (lthis.userId){
863
				lthis.sendVote(lthis.userId, lthis.protocole, starSelected, mode);
864
			}
865
		});
866
	}
867
};
3948 julien 868
 
3958 julien 869
// Envoi du vote vers la fonction sendVote() du fichier php
870
WidgetPhotoPopup.prototype.sendVote = function (userId, protocole, note, mode, voteId){
871
	const lthis = this;
3948 julien 872
 
3958 julien 873
	var xhttp = new XMLHttpRequest();
874
	xhttp.onreadystatechange = function() {
875
		if (this.readyState == 4 && this.status == 200) {
3971 julien 876
 
3979 julien 877
			console.log('vote envoyé')
3958 julien 878
		}
879
	};
3948 julien 880
 
3958 julien 881
	var url = "../widget:cel:photo/";
3948 julien 882
 
3958 julien 883
	// Convertir les données en une chaîne JSON pour les envoyer dans le corps de la requête
884
	var data = {
885
		idImage: this.idImage,
886
		mode: mode,
887
		user: userId,
888
		protocole: protocole,
889
		vote: note,
890
		voteId: voteId
891
	}
892
	var jsonData = JSON.stringify(data);
3948 julien 893
 
3958 julien 894
	xhttp.open("POST", url+"?action=send_pf_vote", true);
895
	xhttp.setRequestHeader("Content-Type", "application/json");
896
	xhttp.send(jsonData);
897
}
3948 julien 898
 
3958 julien 899
WidgetPhotoPopup.prototype.getVotes = function (protocoleId){
900
	let votes = Object.values(this.item["votes"]);
901
	let noteMoyenne = 0;
902
	let nombreVotes= 0;
903
	let noteTotal = 0;
904
	let itemVotes = [];
3948 julien 905
 
3958 julien 906
	votes.forEach(vote => {
907
		if (vote["protocole.id"] == protocoleId){
908
			nombreVotes++
909
			noteTotal += parseInt(vote["vote"]);
910
			noteMoyenne = (noteTotal / nombreVotes).toFixed(1)
911
			itemVotes.push(vote);
912
		}
913
	})
3948 julien 914
 
3958 julien 915
	let elementNoteMoyenne = $("#note-moyenne .contenu");
916
	elementNoteMoyenne.text(noteMoyenne);
3948 julien 917
 
3958 julien 918
	let elementNoteCount = $("#note-count .contenu");
919
	elementNoteCount.text(nombreVotes);
3948 julien 920
 
3958 julien 921
	return itemVotes;
922
}
3948 julien 923
 
3958 julien 924
WidgetPhotoPopup.prototype.displayVote = function (note){
925
	lthis.removeVoteStars();
3948 julien 926
 
3958 julien 927
	for (let i=1; i<=5; i++){
928
		for (let j=1; j<=note; j++){
929
			$("#rating-star-"+j).removeClass('far').addClass('fa').css("color", "#c3d45d");
930
		}
931
	}
932
}
3948 julien 933
 
3958 julien 934
WidgetPhotoPopup.prototype.removeVoteStars = function (){
935
	$(".notation-star").removeClass('fa').addClass('far').css("color", "grey");
936
	$("#note").attr("value", -1);
937
}
3948 julien 938
 
3958 julien 939
WidgetPhotoPopup.prototype.checkUserVote = function (userId, protocoleId, votes){
940
	let userVote = null;
3948 julien 941
 
3958 julien 942
	votes.forEach(vote => {
943
		if (vote["protocole.id"] == protocoleId && vote["auteur.id"] == userId){
944
			userVote = vote;
945
		}
946
	})
947
 
948
	if (userVote){
949
		this.displayVote(userVote['vote']);
950
		// this.traiterVote()
951
		this.voteId = userVote['vote.id'];
952
 
953
		return true
954
	} else {
955
		this.voteId = null;
956
		this.removeVoteStars()
957
	}
958
}
959
 
3948 julien 960
WidgetPhotoPopup.prototype.pivoterImage = function() {
3949 julien 961
	lthis = this;
962
	$( '#pivoter-droite' ).off( 'click' ).on( 'click', function( event ) {
3948 julien 963
		event.preventDefault();
964
 
3949 julien 965
		lthis.pivoter('droite');
3948 julien 966
	});
967
 
3949 julien 968
	$( '#pivoter-gauche' ).off( 'click' ).on( 'click', function( event ) {
3948 julien 969
		event.preventDefault();
970
 
3949 julien 971
		lthis.pivoter('gauche');
3948 julien 972
	});
973
};
974
 
3949 julien 975
WidgetPhotoPopup.prototype.pivoter = function(direction) {
976
	let imageSelected = $('img[src="' + lthis.urlThisImage + '"]').attr('id');
977
	let angle = $('#' + imageSelected).data('angle');
978
 
979
	if (angle == 360 || angle == (-360) || angle == undefined){
980
		angle = 0
981
	}
982
	if (direction == 'droite'){
983
		angle += 90;
984
	} else {
985
		angle -= 90;
986
	}
3950 julien 987
 
3949 julien 988
	$('#' + imageSelected).css("transform", "rotate(" + angle + "deg) ");
989
	$('#' + imageSelected).data('angle', angle);
990
}
991
 
3823 idir 992
// WidgetPhotoPopup.prototype.afficherTags = function() {
993
// 	const lthis = this;
994
// 	const TAGS_BASE = [
995
// 		'port',
996
// 		'fleur',
997
// 		'fruit',
998
// 		'feuille',
999
// 		'ecorce',
1000
// 		'rameau',
1001
// 		'planche',
1002
// 		'insecte'
1003
// 	];
1004
 
1005
 
1006
// };