Subversion Repositories eFlore/Applications.cel

Rev

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