let PopUpsController = {
	rscDataAll: {},
	defaultImage: '',
	dataAddons: null,
	addOnsElement: null,
	inputToFill: '',
	deletePopUps: [],
	idForUsersAssignment: null,

	reset() {
		let self = this;

		self.rscDataAll = {};
		self.defaultImage = '';
		self.dataAddons = null;
		self.addOnsElement = null;
		self.inputToFill = '';
		self.deletePopUps = [];
		self.idForUsersAssignment = null;
	},

	setEvents() {
		let self = this;
		self.reset();

		// Reducción de Header
		headerSectionHeight(0);

		// Añadir título
		$('#page-title').text(pf.const.language.RSC2234);

		// Opciones de header
		let jsonsubopt = {
			save: 'save',
			preview: 'preview',
			screen: 'screen'
		};

		let nav = `
			<div class="row mx-0">
				${createSubOptionPreview(jsonsubopt.preview)}
				${createSubOptionAddScreen(jsonsubopt.screen)}
				${createSubOptionSave(jsonsubopt.save)}
			</div>
		`;

		// Acciones de página (flex-row-reverse)s
		$('#page-actions').html(nav);

		// Botón principal
		$('#save').addClass('main-button');

		// Botones secundarios
		$('#preview').addClass('secondary-button');
		$('#addImage').addClass('secondary-button');

		// Imagen por defecto
		self.defaultImage = stcm.const.downloads + 'pop_ups/pop_ups.png';

		self.loadLanguage();
		self.applyEvents();

		// Iniciar spinner
		addLoader();

		self.getAllRSC();

		// Collapse
		addEventArrowTableHeader();
	},

	loadLanguage() {
		pf.rsc.translateByTag('text');
	},

	applyEvents() {
		let self = this;

		$('#sortableImages').sortable();
		$('#sortableImages').disableSelection();

		$('#addImage').click(function() {
			let count = $('#sortableImages li').length;

			$('#sortableImages').append(`
				<li class="ui-state-default list-group-item liImage d-flex row align-items-center pb-0" role="button" data-id="">
					<div class="col-1">
						${stcmbackend.svg.arrowDownUpWithoutColor}
						<span class="text-primary orderPopUps"></span>
					</div>

					<div class="d-flex col-2 justify-content-center pl-4">
						<img src="${self.defaultImage}" class="targetImage border wel-tour-img">
						<!-- Editar -->
						<button type="button" class="btn btn-nav btn-image">
							${stcmbackend.svg.pencil}
						</button>
						<input type="file" class="inputImage mt-2 d-none" accept="image/*">
						<span class="place-self-center text-center">
							<!-- Download -->
							<button type="button" class="btn btn-nav btn-image-download" value="${self.defaultImage}">
								${stcmbackend.svg.download}
							</button>
						</span>
					</div>

					<div class="d-flex flex-column col-7 pl-1">
						<div>
							<!-- Nombre -->
							<div class="form-group row">
								<div class="col-3">
									<label for="name_${count}" class="col-form-label col-form-label-sm">${pf.const.language.RSC123}</label>
								</div>

								<div class="col row ma-ri-14">
									<div class="col">
										<input id="name_${count}" type="text" class="form-control popUpName">
									</div>

									<!-- Activa -->
									<div class=" col-3 form-group text-right mb-0">
										<label for="enabled_${count}" class="mr-1 col-form-label col-form-label-sm">${pf.const.language.RSC114}</label>
										<div class="custom-control custom-switch d-inline-block">
											<input id="enabled_${count}" type="checkbox" class="custom-control-input enabledSwitch">
											<label for="enabled_${count}" class="custom-control-label c-pointer"></label>
										</div>
									</div>
								</div>
							</div>
						</div>

						<!-- Descripción -->
						<div class="form-group row">
							<div class="col-3">
								<label for="description_${count}" class="col-form-label col-form-label-sm">${pf.const.language.RSC178}</label>
							</div>

							<div class="col ma-ri-34">
								<input id="description_${count}" type="text" class="form-control popUpDesc">
							</div>
						</div>

						<!-- Título -->
						<div class="form-group row mb-2 pr-3">
							<div class="col-3 col-form-label col-form-label-sm mr-1">
								<label>${pf.const.language.RSC112}</label>
							</div>

							<div class="input-group new-input-style col ml-3">
								<input type="text" class="form-control titleInput" rsc="" disabled>
								<div class="input-group-append">
									<button type="button" class="btn btn-outline-secondary searchRSC he-32" data-toggle="modal" data-target="#modalContainer">
										${stcmbackend.svg.threeDotsWithoutMargin}
									</button>
								</div>
							</div>

							<span class="d-flex justify-content-center c-pointer deleteInput mt-1 pt-2 pl-2 he-32">
								${stcmbackend.svg.bigTrash}
							</span>
						</div>

						<!-- Texto -->
						<div class="form-group row mb-2 pr-3">
							<div class="col-3 col-form-label col-form-label-sm mr-1">
								<label>${pf.const.language.RSC1210}</label>
							</div>

							<div class="input-group new-input-style col ml-3">
								<input type="text" class="form-control descriptionInput" rsc="" disabled>
								<div class="input-group-append">
									<button type="button" class="btn btn-outline-secondary searchRSC he-32" data-toggle="modal" data-target="#modalContainer">
										${stcmbackend.svg.threeDotsWithoutMargin}
									</button>
								</div>
							</div>

							<span class="d-flex justify-content-center c-pointer deleteInput mt-1 pt-2 pl-2 he-32">
								${stcmbackend.svg.bigTrash}
							</span>
						</div>

						<!-- Texto de botón -->
						<div class="form-group row mb-2 pr-3">
							<div class="col-3 col-form-label col-form-label-sm mr-1">
								<label>${pf.const.language.RSC2235}</label>
							</div>

							<div class="input-group new-input-style col ml-3">
								<input type="text" class="form-control buttonTextInput" rsc="" disabled>
								<div class="input-group-append">
									<button type="button" class="btn btn-outline-secondary searchRSC he-32" data-toggle="modal" data-target="#modalContainer">
										${stcmbackend.svg.threeDotsWithoutMargin}
									</button>
								</div>
							</div>

							<span class="d-flex justify-content-center c-pointer deleteInput mt-1 pt-2 pl-2 he-32">
								${stcmbackend.svg.bigTrash}
							</span>
						</div>

						<!-- AddOn -->
						<div class="form-group row mb-2 pr-3">
							<div class="col-3 col-form-label col-form-label-sm mr-1">
								<label>AddOn</label>
							</div>

							<div class="input-group new-input-style col ml-3 ma-ri-34">
								<input type="text" class="form-control idaddon" data-idaddon="" disabled>
								<div class="input-group-append">
									<button type="button" class="btn btn-outline-secondary btnAddons he-32" data-toggle="modal" data-target="#modalAddons">
										${stcmbackend.svg.threeDotsWithoutMargin}
									</button>
								</div>
							</div>
						</div>

						<!-- deeplink -->
						<div class="form-group row mb-2">
							<div class="col-3 col-form-label col-form-label-sm">
								<label for="deeplinkPopUp">Deep Link</label>
							</div>

							<div class="col ma-ri-34">
								<select id="deeplinkPopUp" class="form-control deeplink" disabled></select>
							</div>
						</div>
					</div>

					<div class="col-2 text-center">
						<button type="button" class="btn btn-outline-secondary deleteImage" data-id="">${pf.const.language.RSC2162}</button>
						<button type="button" class="btn btn-outline-secondary userAssignment mt-2" data-id="" disabled>${pf.const.language.RSC2239}</button>
					</div>
				</li>
			`);

			self.sortableItemsEvents();
		});

		// Se actualizan los valores del índice (actualizar los valores de índice con los eventos de sortable.js da algunos errores)
		setInterval(function() {
			let i = 1;
			$('#sortableImages li').each(function() {
				$(this).find('.orderPopUps').text(i);
				i++;
			});
		}, 1000);

		$('#save').click(function() {
			let objInfo = {
				accept: {
					text: pf.const.language.RSC78
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC78;
			let alertText = pf.const.language.RSC105;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.processData('save');
			}, function() {});
		});

		$('#preview').click(function() {
			self.processData('preview');
		});
	},

	getAllRSC() {
		let self = this;

		ajaxComunCallWithCallback('getAllRSC', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let rscData = ajaxReturn.result;

				// Dicionario completo
				let language = sessionStorage['STCMBackEnd:lenguage'];
				self.rscDataAll = {};
				let size = rscData.length;
				for(let i = 0; i < size; i++) {
					self.rscDataAll[rscData[i].idRSC] = rscData[i][language];
				}

				self.getAllAddOns();
			}
		}, false);
	},

	getAllAddOns() {
		let self = this;

		ajaxComunCallWithCallback('getAllAddOns', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.dataAddons = ajaxReturn.response;

				let table = `
					<table id="tableAddons" class="table table-hover tRegs tv-80">
						<thead>
							<tr>
								<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
								<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
							</tr>
						</thead>

						<thead class="filtersAddons">
							<tr>
								<td>nombre</td>
								<td>descripcion</td>
							</tr>
						</thead>

						<tbody>
				`;

				let size = self.dataAddons.length;
				for(let i = 0; i < size; i++) {
					table += `
						<tr data-index="${i}" class="c-pointer">
							<td class="text-truncate" title="${self.dataAddons[i].addon_name}">${self.dataAddons[i].addon_name}</td>
							<td class="text-truncate" title="${self.dataAddons[i].addon_description}">${self.dataAddons[i].addon_description}</td>
						</tr>
					`;
				}

				table += `
						</tbody>
					</table>
				`;

				$('#ContainerAddons').html(table);

				// Setup - add a text input to each footer cell
				$('#tableAddons .filtersAddons td').each(function() {
					value = `<input type="text" class="form-control">`;

					$(this).html(value);
				});

				let tableAddons = $('#tableAddons').DataTable({
					language: self.language,
					scrollY: 300,
					scroller: false,
					paging: true,
					pageLength: 25,
					autoWidth: false,
					aaSorting: []
				});

				// Ocultar botones de tabla
				hideTableButtons('tableAddons');

				// Apply the search
				applyTheSearch(tableAddons, 'filtersAddons');

				$('#tableAddons tbody').off().on('click', 'tr', function() {
					let index = $(this).data('index');
					self.addOnsElement.find('input').val(self.dataAddons[index].addon_name);
					self.addOnsElement.find('input').data('idaddon', self.dataAddons[index].id);
					let selectDeepLink = self.addOnsElement.parent().parent().find('.deeplink');
					selectDeepLink.html('');

					let deeplinks = self.dataAddons[index].deeplinks;

					let size = deeplinks.length;
					if(size == 0) {
						selectDeepLink.prop('disabled', true);
					} else {
						let options = '';
						for(let i = 0; i < size; i++) {
							options += `<option value="${deeplinks[i].id}">${deeplinks[i].id}</option>`;
						}

						selectDeepLink.html(options);
						selectDeepLink.prop('disabled', false);
					}

					$('#closeAddons').trigger('click');
				});

				self.getAllPopups();
			}
		}, false);
	},

	getAllPopups() {
		let self = this;

		ajaxComunCallWithCallback('getAllPopups', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let data = ajaxReturn.result;

				$('#sortableImages').html('');

				let size = data.length;
				for(let i = 0; i < size; i++) {
					let image = data[i].imagen;
					let checked = data[i].enabled == 1 ? 'checked' : '';
					let nameAddOn = '';
					let options = '';
					let selectDisabled = '';
					let popup_sistema = data[i].sistema;

					for(let j = 0; j < self.dataAddons.length; j++) {
						if(data[i].idAddon == self.dataAddons[j].id) {
							nameAddOn = self.dataAddons[j].addon_name;

							let deeplinks = self.dataAddons[j].deeplinks;

							let size = deeplinks.length;
							if(size == 0) {
								selectDisabled = 'disabled';
							} else {
								selectDisabled = '';
								for(let n = 0; n < size; n++) {
									let selected = data[i].deeplink == deeplinks[n].id ? 'selected' : '';

									options += `<option value="${deeplinks[n].id}" ${selected}>${deeplinks[n].id}</option>`;
								}
							}
						}
					}

					let disabledPopUpSistema = '';
					let hiddenPopUpSistema = '';
					let checkedSistema = '';
					let showEach = ' dis-none';

					if(popup_sistema == '1') {
						disabledPopUpSistema = 'disabled';
						hiddenPopUpSistema = ' dis-none';
						checkedSistema = 'checked';
						if(data[i].deeplink == 'MissionCenter') {
							options = `<option value="${data[i].deeplink}"selected>${data[i].deeplink}</option>`;
						}
						showEach = '';
					}

					$('#sortableImages').append(`
						<li class="ui-state-default list-group-item liImage d-flex row align-items-center pb-0" role="button" data-id="${data[i].id}">
							<div class="col-1">
								${stcmbackend.svg.arrowDownUpWithoutColor}
								<span class="text-primary orderPopUps"></span>
							</div>

							<div class="d-flex col-2 justify-content-center pl-4">
								<img src="${(image + '?stamp=' + new Date().getTime() + '') || self.defaultImage}" class="targetImage border wel-tour-img">
								<!-- Editar -->
								<button type="button" class="btn btn-nav btn-image">
									${stcmbackend.svg.pencil}
								</button>
								<input type="file" class="inputImage mt-2 d-none" accept="image/*" loadedImage="true">
								<span class="place-self-center text-center">
									<!-- Download -->
									<button type="button" class="btn btn-nav btn-image-download" value="${(image) || self.defaultImage}">
										${stcmbackend.svg.download}
									</button>
								</span>
							</div>

							<div class="d-flex flex-column col-7 pl-1">
								<div>
									<!-- Nombre -->
									<div class="form-group row">
										<div class="col-3">
											<label for="name_${i}" class="col-form-label col-form-label-sm">${pf.const.language.RSC123}</label>
										</div>

										<div class="col row ma-ri-14">
											<div class="col">
												<input id="name_${i}" type="text" class="form-control popUpName" ${disabledPopUpSistema} value="${data[i].nombre}">
											</div>

											<!-- Sistema -->
											<div class="col-3 form-group text-right mb-0">
												<label class="mr-1 col-form-label col-form-label-sm">${pf.const.language.RSC408}</label>
												<div class="custom-control custom-switch d-inline-block">
													<input id="enabled_sistema_${i}" type="checkbox" class="custom-control-input enabledSystemSwitch" ${checkedSistema}>
													<label class="custom-control-label"></label>
												</div>
											</div>

											<!-- Activa -->
											<div class="col-3 form-group text-right mb-0">
												<label for="enabled_${i}" class="mr-1 col-form-label col-form-label-sm">${pf.const.language.RSC114}</label>
												<div class="custom-control custom-switch d-inline-block">
													<input id="enabled_${i}" type="checkbox" class="custom-control-input enabledSwitch" ${checked}>
													<label for="enabled_${i}" class="custom-control-label c-pointer"></label>
												</div>
											</div>
										</div>
									</div>
								</div>

								<!-- Descripción -->
								<div class="form-group row">
									<div class="col-3">
										<label for="description_${i}" class="col-form-label col-form-label-sm">${pf.const.language.RSC178}</label>
									</div>

									<div class="col ma-ri-34">
										<input id="description_${i}" type="text" class="form-control popUpDesc" ${disabledPopUpSistema} value="${data[i].descripcion}">
									</div>
								</div>

								<!-- Título -->
								<div class="form-group row mb-2 pr-3">
									<div class="col-3 col-form-label col-form-label-sm mr-1">
										<label>${pf.const.language.RSC112}</label>
									</div>

									<div class="input-group new-input-style col ml-3">
										<input type="text" class="form-control titleInput" rsc="${data[i].titulo}" value="${self.rscDataAll[data[i].titulo] || ''}" disabled>
										<div class="input-group-append">
											<button type="button" class="btn btn-outline-secondary searchRSC he-32" data-toggle="modal" data-target="#modalContainer">
												${stcmbackend.svg.threeDotsWithoutMargin}
											</button>
										</div>
									</div>

									<span class="d-flex justify-content-center c-pointer deleteInput mt-1 pt-2 pl-2 he-32">
										${stcmbackend.svg.bigTrash}
									</span>
								</div>

								<!-- Texto -->
								<div class="form-group row mb-2 pr-3">
									<div class="col-3 col-form-label col-form-label-sm mr-1">
										<label>${pf.const.language.RSC1210}</label>
									</div>

									<div class="input-group new-input-style col ml-3">
										<input type="text" class="form-control descriptionInput" rsc="${data[i].texto}" value="${self.rscDataAll[data[i].texto] || ''}" disabled>
										<div class="input-group-append">
											<button type="button" class="btn btn-outline-secondary searchRSC he-32" data-toggle="modal" data-target="#modalContainer">
												${stcmbackend.svg.threeDotsWithoutMargin}
											</button>
										</div>
									</div>

									<span class="d-flex justify-content-center c-pointer deleteInput mt-1 pt-2 pl-2 he-32">
										${stcmbackend.svg.bigTrash}
									</span>
								</div>

								<!-- Texto de botón -->
								<div class="form-group row mb-2 pr-3">
									<div class="col-3 col-form-label col-form-label-sm mr-1">
										<label>${pf.const.language.RSC2235}</label>
									</div>

									<div class="input-group new-input-style col ml-3">
										<input type="text" class="form-control buttonTextInput" rsc="${data[i].texto_boton}" value="${self.rscDataAll[data[i].texto_boton] || ''}" disabled>
										<div class="input-group-append">
											<button type="button" class="btn btn-outline-secondary searchRSC he-32" data-toggle="modal" data-target="#modalContainer">
												${stcmbackend.svg.threeDotsWithoutMargin}
											</button>
										</div>
									</div>

									<span class="d-flex justify-content-center c-pointer deleteInput mt-1 pt-2 pl-2 he-32">
										${stcmbackend.svg.bigTrash}
									</span>
								</div>

								<!-- Mostrar cada: -->
								<div class="form-group row mb-2${showEach}">
									<div class="col-3 col-form-label col-form-label-sm">
										<label for="showEach_${i}">${pf.const.language.RSC2432} (${pf.const.language.RSC427})</label>
									</div>

									<div class="col ma-ri-34">
										<input id="showEach_${i}" type="number" class="form-control showEach" value="${data[i].timeshow}">
									</div>
								</div>

								<!-- AddOn -->
								<div class="form-group row pr-3 mb-2${hiddenPopUpSistema}">
									<div class="col-3 col-form-label col-form-label-sm mr-1">
										<label>AddOn</label>
									</div>

									<div class="input-group new-input-style col ml-3 ma-ri-34">
										<input type="text" class="form-control idaddon" data-idaddon="${data[i].idAddon}" value="${nameAddOn}" disabled>
										<div class="input-group-append">
											<button id="f2AddOnsPopUpSection" class="btn btn-outline-secondary btnAddons he-32" ${disabledPopUpSistema} type="button" data-toggle="modal" data-target="#modalAddons">
												${stcmbackend.svg.threeDotsWithoutMargin}
											</button>
										</div>
									</div>
								</div>

								<!-- deeplink -->
								<div class="form-group row mb-2${hiddenPopUpSistema}">
									<div class="col-3 col-form-label col-form-label-sm">
										<label for="deeplinkPopUp">Deep Link</label>
									</div>

									<div class="col ma-ri-34">
										<select id="deeplinkPopUp" class="form-control deeplink" ${selectDisabled}>
											${options}
										</select>
									</div>
								</div>
							</div>

							<div class="col-2 text-center">
								<button type="button" class="btn btn-outline-secondary deleteImage${hiddenPopUpSistema}" data-id="${data[i].id}">${pf.const.language.RSC2162}</button>
								<button type="button" class="btn btn-outline-secondary userAssignment mt-2${hiddenPopUpSistema}" data-id="${data[i].id}">${pf.const.language.RSC2239}</button>
							</div>
						</li>
					`);
				}

				self.sortableItemsEvents();

				// Finalizar spinner
				removeLoader();
			}
		}, false);
	},

	processData(target) {
		let self = this;

		let sectionsArray = [];
		let imageArray = [];
		let emptyImages = false;
		let nImages = 0;

		addLoader();

		$('.liImage').each(function(index) {
			nImages++;
			let inputImage = $(this).find('.inputImage');
			let img = '';
			let type = '';
			let preloadedImage = false;
			if(inputImage[0].files.length != 0) {
				img = inputImage[0].files[0].name;
				type = inputImage[0].files[0].type;
				imageArray.push([inputImage[0].files[0], index]);
				inputImage.prev().prev().removeClass('border-danger');

				let id = $(this).data('id');
				let nombre = $(this).find('.popUpName').val();
				let descripcion = $(this).find('.popUpDesc').val();
				let inputTitle = $(this).find('.titleInput');
				let inputDescription = $(this).find('.descriptionInput');
				let texto_boton = $(this).find('.buttonTextInput');
				let idAddon = $(this).find('.idaddon').data('idaddon');
				let deeplink = $(this).find('.deeplink').val();
				let enabled = $(this).find('.enabledSwitch').prop('checked') == true ? '1' : '0';
				let showEach = $(this).find('.showEach').val();
				let section = {
					id: id,
					prioridad: index + 1,
					nombre: nombre,
					descripcion: descripcion,
					imageName: img,
					title: inputTitle.attr('rsc') || '',
					description: inputDescription.attr('rsc') || '',
					texto_boton: texto_boton.attr('rsc') || '',
					type: type,
					preloadedImage: preloadedImage,
					idAddon: idAddon,
					deeplink: deeplink,
					enabled: enabled,
					timeshow: showEach
				}

				//sectionsArray.push(section);
				sectionsArray[index] = section;
			} else if(inputImage.attr('loadedImage') == 'true') {
				preloadedImage = true;
				// Creación del file para las imágenes precargadas		
				setTimeout(() => {
					fetch(inputImage.prev().prev().attr('src'))
					.then(res => res.blob())
					.then(blob => {
						const file = new File([blob], 'preloadedimage.png', blob);
						imageArray.push([file, index]);

						let id = $(this).data('id');
						let nombre = $(this).find('.popUpName').val();
						let descripcion = $(this).find('.popUpDesc').val();
						let inputTitle = $(this).find('.titleInput');
						let inputDescription = $(this).find('.descriptionInput');
						let texto_boton = $(this).find('.buttonTextInput');
						let idAddon = $(this).find('.idaddon').data('idaddon');
						let deeplink = $(this).find('.deeplink').val();
						let enabled = $(this).find('.enabledSwitch').prop('checked') == true ? '1' : '0';
						let showEach = $(this).find('.showEach').val();
						img = file.name;
						type = file.type;
						let section = {
							id: id,
							prioridad: index + 1,
							nombre: nombre,
							descripcion: descripcion,
							imageName: img,
							title: inputTitle.attr('rsc') || '',
							description: inputDescription.attr('rsc') || '',
							texto_boton: texto_boton.attr('rsc') || '',
							type: type,
							preloadedImage: preloadedImage,
							idAddon: idAddon,
							deeplink: deeplink,
							enabled: enabled,
							timeshow: showEach
						}

						//sectionsArray.push(section);
						sectionsArray[index] = section;
					});
				}, 100);
			} else {
				inputImage.prev().prev().addClass('border-danger');
				emptyImages = true;
			}
		});

		// Comprobar que haya una imágen como mínimo para guardar/previsualizar
		if(nImages == 0) {
			let successTitle = pf.const.language.RSC61;
			let successContent = target === 'save' ? pf.const.language.RSC2137 : pf.const.language.RSC2151;

			pf.utils.showInfoDialog(successTitle, successContent);
			removeLoader();
			return false;
		}

		if(emptyImages) {
			let objInfo = {
				accept: {
					text: pf.const.language.RSC141
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};
			let alertTitle = pf.const.language.RSC85;
			if(target == 'save') {
				alertTitle = pf.const.language.RSC78;
			}
			let alertText = pf.const.language.RSC793;
			removeLoader();
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				//
			});
		} else {
			setTimeout(() => {
				// Verificación validez de los formatos de las imágenes
				let invalidImageFormat = false;

				sectionsArray.map(obj => {
					let format = obj.type.split('/')[1];
					if(format != 'png' && format != 'jpg' && format != 'jpeg' && format != 'bmp' && format != 'webp') {
						invalidImageFormat = true;
					}
				});
				if(invalidImageFormat) {
					let objInfo = {
						accept: {
							text: pf.const.language.RSC141
						},
						cancel: {
							text: pf.const.language.RSC57
						}
					};
					let alertTitle = pf.const.language.RSC654;
					let alertText = pf.const.language.RSC2136;
					removeLoader();
					pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
						//
					});
				} else {
					let orderedArray = [];
					for(let i = 0; i < imageArray.length; i++) {
						for(let j = 0; j < imageArray.length; j++) {
							if(imageArray[j][1] == i) {
								orderedArray.push(imageArray[j]);
							}
						}
					}

					removeLoader();
					if(target === 'save') {
						self.saveImages(sectionsArray, orderedArray);
					}
					if(target === 'preview') {
						self.previewImages(sectionsArray, orderedArray);
					}
				}
			}, 1000);
		}
	},

	clickEventsRSC(data, dType = null) {
		let self = this;

		// Limpiar el texto de la etiquetas html para ver su tamaño real
		let cleanText = data.descripcion.replaceAll('&lt;', '<').replaceAll('&gt;', '>');
		let textWithTags = cleanText;
		cleanText = cleanText.replace(/<[^>]*>?/g, '');

		if(($(self.inputToFill).hasClass('titleInput') && cleanText.length > 40) || ($(self.inputToFill).hasClass('descriptionInput') && cleanText.length > 180)) {
			let objInfo = {
				accept: {
					text: pf.const.language.RSC141
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC1616;
			let alertText = $(self.inputToFill).hasClass('titleInput') ? pf.const.language.RSC2155 : pf.const.language.RSC2156;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				$(self.inputToFill).val(textWithTags);
				$(self.inputToFill).attr('rsc', data.id);
			}, function() {});
		} else {
			$(self.inputToFill).val(textWithTags);
			$(self.inputToFill).attr('rsc', data.id);
		}
	},

	saveImages(sectionsArray, imageArray) {
		let self = this;

		let parameters = {
			sectionsArray: JSON.stringify(sectionsArray),
			path: stcm.const.downloads + 'pop_ups/',
			deletePopUps: JSON.stringify(self.deletePopUps),
			idcpg: getidCPG()
		}

		// Otras imágenes
		let imgSize = imageArray.length;
		for(let i = 0; i < imgSize; i++) {
			if(imageArray[i] == '0') {
				continue;
			}
			parameters['img' + i] = imageArray[i][0];
		}

		ajaxComunCallWithCallback('setPopups', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC78;
				let successContent = pf.const.language.RSC948;
				pf.utils.showInfoDialog(successTitle, successContent);
				self.getAllRSC();
			}
		}, true);
	},

	sortableItemsEvents() {
		let self = this;

		// Pintar texto de label
		changeLabelsColor();

		let i = 1;
		$('#sortableImages li').each(function() {
			$(this).find('.orderPopUps').text(i);
			i++;
		});

		$('.inputImage').change(function() {
			self.loadImage(this);
		});

		// Cambiar imagen
		$('.btn-image').off().on('click', function() {
			$(this).next().trigger('click');
		});

		// Download imagen
		$('.btn-image-download').off().on('click', function() {
			self.downloadImage(this);
		});

		// Eliminar PopUp
		$('.deleteImage').off().on('click', function() {
			let id = $(this).data('id');
			if(id !== '') {
				self.deletePopUps.push(id);
			}

			$(this).parent().parent().remove();
			let i = 1;
			$('#sortableImages li').each(function() {
				$(this).find('.orderPopUps').text(i);
				i++;
			});
		});

		// No System RSC - Modal
		let rscModal = new TableNoSystemRSC(0, 'PopUpsController');
		$('.searchRSC').off().on('click', function() {
			self.inputToFill = $(this).parent().parent().children()[0];
			rscModal.setEvents();
		});

		// Borrar input de RSC
		$('.deleteInput').off().on('click', function() {
			let input = $(this).parent().find('input');
			input.val('');
		});

		// Selección de AddOn
		$('.btnAddons').off().on('click', function() {
			self.addOnsElement = $(this).parent().parent();
		});

		// Asignar usuarios
		$('.userAssignment').off().on('click', function() {
			self.idForUsersAssignment = $(this).data('id');

			let parameters = {
				idPopUp: self.idForUsersAssignment
			};
			ajaxComunCallWithCallback('getAllPopupsUserAssignment', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					// Lista de usuarios para añadir a PopUps
					let userAssignment = new TableUsers(1, 'popUps', '', 1, 1, 1);
					userAssignment.data = null;
					userAssignment.members = ajaxReturn.result;
					userAssignment.surname = false;
					$('#modalContainer').modal('show');
					userAssignment.setEvents();
				}
			}, false);
		});
	},

	downloadImage(source) {
		const fileName = source.value.split('/').pop();
		var el = document.createElement('a');
		el.setAttribute('href', source.value);
		el.setAttribute('download', fileName);
		document.body.appendChild(el);
	 	el.click();
		el.remove();
	},

	loadImage(input) {
		if(input.files && input.files[0]) {
			let src = URL.createObjectURL(input.files[0]);
			$(input).prev().prev().attr('src', src);
		} else {
			$(input).prev().prev().attr('src', self.defaultImage);
		}
	},

	previewImages(sectionsArray, imageArray) {
		let self = this;

		let previewData = [];

		$('.liImage').each(function(index) {
			let obj = {
				img: $(this).find('.targetImage').attr('src'),
				title: $(this).find('.titleInput').val(),
				description: $(this).find('.descriptionInput').val()
			}
			previewData.push(obj);
		});

		self.previewFormat(previewData);
	},

	previewFormat(previewData) {
		let popUps = {
			userViewPopUps() {
				return jsxc.storage.getItem('popUps');
			},

			isShowingPopUps() {
				return $('.stcm_popUps').length > 0;
			},

			showPopUps(previewData) {
				let self = this;

				$('#previewImages').html('');

				$('<div class="stcm_popUps"><span class="finishWT"></span>').appendTo('#previewImages');

				var template = self.renderTemplatePopUps(previewData);

				$('.stcm_popUps').append(template);
				$('.stcm_popUps').append(template.template);
				$('.stcm_popUps').append(template.templateicons);

				$('.slider').slick({
					arrows: false,
					dots: true,
					infinite: false,
					speed: 0,
					focusOnSelect: false,
					customPaging(slider, i) {
						return '<a><svg width="100%" height="100%" viewBox="0 0 16 16"><circle cx="8" cy="8" r="6.215"></circle></svg><span></span></a>';
					},
				}).on('beforeChange', function(event, slick, currentSlide, nextSlide) {
					self.slideAction(currentSlide, nextSlide);
				}).on('afterChange', function(event, slick, currentSlide) {
					$('.item').eq(currentSlide).addClass('ready');
				});

				var elem = $('<div class="stcm_nav_slick">').append($('.slick-dots'));

				//append next button
				var btnPrev = `
					<button type="button" class="slick-prev slick-arrow slick-disabled dis-none" data-role="none" aria-label="Previous" role="button" aria-disabled="true">
						<span>${pf.const.language.RSC653}</span>
					</button>
				`;
				var btnNext = `
					<button type="button" class="slick-next slick-arrow pageChangeButton d-block" data-role="none" aria-label="Next" role="button" aria-disabled="false">
						<span>${pf.const.language.RSC663}</span>
					</button>
				`;

				elem.prepend(btnPrev);
				elem.append(btnNext);

				$('.stcm_popUps .onboard .slider').append(elem);

				self.setEventBtnsSlides();
				// Al cerrar PopUps, poner el style de la barra normal segun estemos en login o dentro
			},

			slideAction(currentSlide, nextSlide) {
				$('.item').removeClass('from-right from-left ready');
				var c = (currentSlide < nextSlide) ? 'from-right' : 'from-left';
				$('.item').eq(nextSlide).addClass(c);
				$('#icon-' + nextSlide).removeClass('d-none');
				$('#icon-' + currentSlide).addClass('d-none');
			},

			setEventBtnsSlides() {
				$('.slick-prev').off('click').click(function() {
					var prevElem = $('li.slick-active').prev();
					var prevId = prevElem.attr('id');

					if(prevId == 'slick-slide00') $('.slick-prev').hide();
					else $('.slick-prev').show();

					var idPrev = $(prevElem).attr('id');
					$('li#' + idPrev).click();
				});

				$('.slick-next').off('click').click(function() {
					var nextElem = $('li.slick-active').next();

					if(nextElem.length > 0) {
						$('.slick-prev').show();
						var idNext = $(nextElem).attr('id');
						$('li#' + idNext).click();
					}
				});
			},

			renderElemPopUps(object, i) {
				return `
					<div class="item" data-item="${i}">
						<div>
							<div class="tit">
								${object.title}
							</div>

							<div class="text">
								${object.description}
							</div>
						</div>
					</div>
				`;
			},

			renderTemplatePopUps(data) {
				let self = this;

				var template = `
					<div class="onboard">
						<div class="slider">
				`;

				var templateIcons = '';
				var strClass = '';
				for(var i = 0; i < data.length; ++i) {
					template += self.renderElemPopUps(data[i], i);
					if(i > 0) {
						strClass = 'd-none';
					}
					templateIcons += `<span id="icon-${i}" class="stcm_popUpsBgImage ${strClass}" style="background-image: url('${data[i].img}')"></span>`;
				};

				template += `
						</div>
					</div>
				`;

				return {'template': template, 'templateicons': templateIcons};
			}
		}

		// Primero tiene que cargar el html del modal para que los elementos de la librería 'slick' se inserten de manera correcta
		$('#modalPreview').on('shown.bs.modal', function() {
			popUps.showPopUps(previewData);

			if($(window).height() <= 800) {
				$('.tit').css({'font-size': '1rem'});
				$('.text').css({'font-size': '0.8rem'});
			}
			window.addEventListener('resize', function(event) {
				if($(window).height() <= 800) {
					$('.tit').css({'font-size': '1rem'});
					$('.text').css({'font-size': '0.8rem'});
				} else {
					$('.tit').css({'font-size': '1.8rem'});
					$('.text').css({'font-size': '1.3rem'});
				};

			}, true);
		});

		$('#modalPreview').modal('toggle');
	},

	clickEvents(data) {
		let self = this;

		// Asignar usuarios a PopUp
		let usersMail = '';
		let size = data.length;
		for(let i = 0; i < size; i++) {
			usersMail += data[i].email + ';';
		}
		usersMail = usersMail.slice(0, -1);

		let parameters = {
			idPopUp: self.idForUsersAssignment,
			idUser: usersMail
		};
		ajaxComunCallWithCallback('setPopupsUserAssignment', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = (pf.const.language.RSC2234);
				let successContent = (pf.const.language.RSC2240);
				pf.utils.showInfoDialog(successTitle, successContent);
			}
		});
	}
};