let PaisesEditController = {
	language: '',
	countryIso: '',
	country: '',
	rscData: '',
	paymentFields: '',
	rscDataAll: {},
	tableRSCFlag: false,
	identificationArray: [],
	accountArray: [],
	banksArray: [],
	chatsArray: [],
	userOrder: '',
	maxSize: 0,
	surveyIndex: '',
	chatsNew: false,
	chatsChange: false,
	chatsAttached: false,
	attachmentsArray: [],
	loaders: {},
	weightings: null,
	location: '',
	profilingAlgorithms: [],

	reset() {
		let self = this;

		self.language = pf.const.language_table;
		self.countryIso = '';
		self.country = '';
		self.rscData = '';
		self.paymentFields = '';
		self.rscDataAll = {};
		self.tableRSCFlag = false;
		self.identificationArray = [];
		self.accountArray = [];
		self.banksArray = [];
		self.chatsArray = [];
		self.userOrder = '';
		self.maxSize = 0;
		self.surveyIndex = '';
		self.chatsNew = false;
		self.chatsChange = false;
		self.chatsAttached = false;
		self.attachmentsArray = [];
		self.loaders = {
			getAllRSC: false,
			getPaisByID: false,
			getTemplatePagosByCountry: false,
			getPaisesTipoCuentas: false,
			getPaisesTipoIdentificacion: false,
			getPaisesBancos: false,
			getWelcomeChatsById: false,
			getPonderacionesByCountry: false,
			getSPSchemaCorporate: false
		};
		self.weightings = null;
		self.location = '';
		self.profilingAlgorithms= [];
	},

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

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

		// Añadir titulo
		$('#page-title').text(pf.const.language.RSC549 + ' - ' + pf.const.language.RSC225);

		$('.currencyPoints').hide();

		// Opciones de header
		let jsonsubopt = {
			back: 'backCountries',
			save: 'saveCountry'
		};

		let nav = `
			${createSubOptionSave(jsonsubopt.save)}
			${createSubOptionBack(jsonsubopt.back)}
		`;

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

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

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

		self.countryIso = atob(sessionStorage.getItem('editCountryIso'));

		self.loadLang();
		self.applyEvents();

		addLoader();
		self.getAllRSC();
		self.getTemplatePagosByCountry();
		self.getPaisesBancos();
		self.getPonderacionesByCountry();
		self.getAlgoritmosPerfilacionData();

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
		self.maxSize = config.upload_max_filesize_bytes;

		// Control de uso de CPG
		if(sessionStorage['STCMBackEnd:idCPG'] != '0') {
			$('.disableByCPG').prop('disabled', true);
			$('.hideByCPG').hide();
		}

		// Collapse
		addEventArrowTableHeader();

		// Pintar texto de label
		changeLabelsColor();
	},

	loadLang() {
		pf.rsc.translateByTag('text');

		// TITLES
		$('.exportTitle').attr('title', pf.const.language.RSC47);
	},

	applyEvents() {
		let self = this;

		// Volver a Listas de países
		$('#backCountries').on('click', function() {
			window.location.href = '#!paises';
		});

		// Añadir texto de identificación
		$('#newIdentification').off().on('click', function() {
			let obj = {
				rsc: '',
				code: ''
			};
			self.identificationArray.push(obj);
			self.identificationTable();
		});

		// Añadir texto de cuenta
		$('#newAccount').off().on('click', function() {
			let obj = {
				rsc: '',
				code: ''
			};
			self.accountArray.push(obj);
			self.accountTable();
		});

		// Añadir banco
		$('#newBank').off().on('click', function() {
			let obj = {
				code: '',
				description: ''
			};
			self.banksArray.push(obj);
			self.banksTable();
		});

		// Añadir chat de bienvenida
		$('#newChat').off().on('click', function() {
			let obj = {
				user: '',
				type: '0',
				message: '',
				typeAttached: 'Imagen',
				attachedPath: '',
				attached: '',
				survey: '',
				mission: '',
				textoiniciomision: ''
			};
			self.chatsArray.push(obj);
			self.chatsTable();
		});

		//Input activo/predefinido
		$('#countryDefault').off().on('click', ()=>{
			if($('#countryDefault').prop('checked')) {
				$('#countryEnable').prop('checked', true);
			}
		});

		$('#countryEnable').off().on('click', ()=>{
			if(!$('#countryEnable').prop('checked')) {
				$('#countryDefault').prop('checked', false);
			}
		});

		// Rellenar input de moneda
		$('#countryCurrency').on('blur', function() {
			let cValue = $('#countryCurrency').val();
			$('#currencySpan').text(cValue);
			if(cValue !== '') {
				$('.currencyPoints').show();
			} else {
				$('.currencyPoints').hide();
				$('#currencyPointsInput').val('');
			}
		});

		// Editar información de país
		$('#saveCountry').off().on('click', function() {
			// General
			self.country.currency = $('#countryCurrency').val();
			self.country.currency_symbol = $('#countrySymbol').val();
			self.country.zone = $('#zone').val();
			self.country.enabled = $('#countryEnable').prop('checked') == true ? 1 : 0;
			self.country.default = $('#countryDefault').prop('checked') == true ? 1 : 0;
			self.country.sp_perfilacion = $('#inputProfilingAlgorithm').val();

			// Campos de pagos
			self.paymentFields.banco = $('#banco').prop('checked') == true ? 1 : 0;
			self.paymentFields.ciudad = $('#ciudad').prop('checked') == true ? 1 : 0;
			self.paymentFields.direccion = $('#direccion').prop('checked') == true ? 1 : 0;
			self.paymentFields.identificacion = $('#identificacion').prop('checked') == true ? 1 : 0;
			self.paymentFields.telefono = $('#telefono').prop('checked') == true ? 1 : 0;
			self.paymentFields.tipoCuenta = $('#tipoCuenta').prop('checked') == true ? 1 : 0;
			self.paymentFields.tipoIdentificacion = $('#tipoIdentificacion').prop('checked') == true ? 1 : 0;

			// Tipos de identificación
			let checkID = true;
			$('.valueInputID').removeClass('is-invalid');
			let sizeID = self.identificationArray.length;
			for(let i = 0; i < sizeID; i++) {
				if(self.identificationArray[i].rsc != '' && self.identificationArray[i].code == '') {
					$('#valueInputID' + i).addClass('is-invalid');
					checkID = false;
				}
			}

			// Tipos de cuenta
			let checkAC = true;
			$('.valueInputAC').removeClass('is-invalid');
			let sizeAC = self.accountArray.length;
			for(let i = 0; i < sizeAC; i++) {
				if(self.accountArray[i].rsc != '' && self.accountArray[i].code == '') {
					$('#valueInputAC' + i).addClass('is-invalid');
					checkAC = false;
				}
			}

			// Bancos
			let checkBanks = true;
			$('.bankCodeInput').removeClass('is-invalid');
			let sizeBanks = self.banksArray.length;
			for(let i = 0; i < sizeBanks; i++) {
				if(self.banksArray[i].description != '' && self.banksArray[i].code == '') {
					$('#bankCodeInput' + i).addClass('is-invalid');
					checkBanks = false;
				}
			}

			if(checkID && checkAC && checkBanks) {
				self.updateCountries();
			} else {
				pf.utils.alerts.showCompleteAllFields();
			}
		});

		// Descargar ponderacions en excel
		$('#exportWeightings').off().on('click', function() {
			self.exportExcel();
		});
	},

	getAllRSC() {
		let self = this;

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

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

				self.getCountries();
				self.getPaisesTipoCuentas();
				self.getPaisesTipoIdentificacion();
				self.getWelcomeChatsById();

				// Control de spinner
				self.loaders.getAllRSC = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	getCountries() {
		let self = this;

		let parameters = {
			isocode: self.countryIso
		};
		ajaxComunCallWithCallback('getPaisByID', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.country = ajaxReturn.result[0];
				self.location = self.country.locations;

				self.renderCountry();
				self.renderLocation();
				self.renderTextsByCountry();

				// Control de spinner
				self.loaders.getPaisByID = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	renderCountry() {
		let self = this;

		$('#countryIso').val(self.country.isocode);
		$('#countryName').val(self.country.descripcion);
		if(self.country.enabled == '1') {
			$('#countryEnable').prop('checked', true);
		}
		$('#zone').val(self.country.zone);
		$('#countryCurrency').val(self.country.currency);
		$('#currencySpan').text(self.country.currency);
		if(self.country.currency !== '') {
			$('.currencyPoints').show();
			$('#currencyPointsInput').val(self.country.equivalencePoints);
		}
		$('#countrySymbol').val(self.country.currency_symbol);
		if(self.country.default == '1') {
			$('#countryDefault').prop('checked', true);
		}
		$('#inputProfilingAlgorithm').val(self.country.sp_perfilacion);

		if(self.country.formatoFecha == 'DDMMAAAA') {
			$('#ddmmaaaa').prop('checked', true);
		} else if(self.country.formatoFecha == 'AAAAMMDD') {
			$('#aaaammdd').prop('checked', true);
		}

		$('#population').val(self.country.poblacion);
	},

	renderLocation() {
		let self = this;

		let table = `
			<table class="table table-hover tr-pointer tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1799}">${pf.const.language.RSC1799}</th>
						<th scope="col" title="${pf.const.language.RSC1800}">${pf.const.language.RSC1800}</th>
					</tr>
				</thead>

				<thead class="filtersLocations">
					<tr>
						<td>lenguaje</td>
						<td>localizacion</td>
					</tr>
				</thead>

				<tbody>
		`;

		let enabled = '';
		let locationCode = '';
		let size = self.location.length;
		for(let i = 0; i < size; i++) {
			if(self.location[i].default == '1') {
				enabled = self.location[i].lenguage;
				locationCode = self.location[i].location;
			}

			table += `
				<tr class="c-pointer">
					<td class="location_tr" title="${self.location[i].lenguage}">${self.location[i].lenguage}</td>
					<td class="location_tr_code" title="${self.location[i].location}">${self.location[i].location}</td>
				</tr>
			`;
		}

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

		$('#tableLocation').html(table);
		$('#location').val(enabled);
		$('#location').attr('title', enabled);

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

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

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

		// Como se genera al cargar la página y el modal está oculto, se utiliza el botón de mostrarlo con un intervalo para la animación de la aparición del modal para ajustar las columnas de la tabla
		$('#searchLocation').on('click', function() {
			setTimeout(function() {
				tableLocation.columns.adjust();
			}, 200);
		});

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

		// Apply the search
		applyTheSearch(tableLocation, 'filtersLocations');

		// Detectar click
		$('#tableLocation tbody').off().on('click', 'tr', function() {
			let location = $(this).find('.location_tr').text();
			let locationCode = $(this).find('.location_tr_code').text();
			$('#location').val(location);
			$('#location').attr('title', location);
			$('#locationCode').text(locationCode);
			$('#closeLocation').trigger('click');
		});
	},

	renderTextsByCountry() {
		let self = this;

		let excelTitle = pf.const.language.RSC1209;

		let table = `
			<table id="tableCountryTexts" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1210}">${pf.const.language.RSC1210}</th>
						<th scope="col" title="RSC">RSC</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
					</tr>
				</thead>

				<tbody>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1211}">
							${pf.const.language.RSC1211}
						</td>
						<td class="text-truncate p-1">
							<span class="d-none">${(self.country.rscRegisterNoLicenses == 0 ? '' : self.country.rscRegisterNoLicenses)}</span>
							<div class="form-group mb-0">
								<div class="input-group new-input-style">
									<input id="rscRegisterNoLicenses" type="text" class="form-control" value="${(self.country.rscRegisterNoLicenses == 0 ? '' : self.country.rscRegisterNoLicenses)}" title="${(self.country.rscRegisterNoLicenses == 0 ? '' : self.country.rscRegisterNoLicenses)}" disabled>
									<div class="input-group-append">
										<button id="btn_rscRegisterNoLicenses" type="button" class="btn btn-outline-secondary btn-table" data-toggle="modal" data-target="#modalRSCTable" data-input="rscRegisterNoLicenses" data-cell="rscRegisterNoLicensesCell">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
							</div>
						</td>
						<td id="rscRegisterNoLicensesCell" class="text-truncate" title="${(self.rscDataAll[self.country.rscRegisterNoLicenses] == undefined ? '' : self.rscDataAll[self.country.rscRegisterNoLicenses])}">
							${(self.rscDataAll[self.country.rscRegisterNoLicenses] == undefined ? '' : self.rscDataAll[self.country.rscRegisterNoLicenses])}
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1212}">
							${pf.const.language.RSC1212}
						</td>
						<td class="text-truncate p-1">
							<span class="d-none">${(self.country.rscWelcomePage == 0 ? '' : self.country.rscWelcomePage)}</span>
							<div class="form-group mb-0">
								<div class="input-group new-input-style">
									<input id="rscWelcomePage" type="text" class="form-control" value="${(self.country.rscWelcomePage == 0 ? '' : self.country.rscWelcomePage)}" title="${(self.country.rscWelcomePage == 0 ? '' : self.country.rscWelcomePage)}" disabled>
									<div class="input-group-append">
										<button id="btn_rscWelcomePage" type="button" class="btn btn-outline-secondary btn-table" data-toggle="modal" data-target="#modalRSCTable" data-input="rscWelcomePage" data-cell="rscWelcomePageCell">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
							</div>
						</td>
						<td id="rscWelcomePageCell" class="text-truncate" title="${(self.rscDataAll[self.country.rscWelcomePage] == undefined ? '' : self.rscDataAll[self.country.rscWelcomePage])}">
							${(self.rscDataAll[self.country.rscWelcomePage] == undefined ? '' : self.rscDataAll[self.country.rscWelcomePage])}
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1213}">
							${pf.const.language.RSC1213}
						</td>
						<td class="text-truncate p-1">
							<span class="d-none">${(self.country.rscCongratsMessage == 0 ? '' : self.country.rscCongratsMessage)}</span>
							<div class="form-group mb-0">
								<div class="input-group new-input-style">
									<input id="rscCongratsMessage" type="text" class="form-control" value="${(self.country.rscCongratsMessage == 0 ? '' : self.country.rscCongratsMessage)}" title="${(self.country.rscCongratsMessage == 0 ? '' : self.country.rscCongratsMessage)}" disabled>
									<div class="input-group-append">
										<button id="btn_rscCongratsMessage" type="button" class="btn btn-outline-secondary btn-table" data-toggle="modal" data-target="#modalRSCTable" data-input="rscCongratsMessage" data-cell="rscCongratsMessageCell">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
							</div>
						</td>
						<td id="rscCongratsMessageCell" class="text-truncate" title="${(self.rscDataAll[self.country.rscCongratsMessage] == undefined ? '' : self.rscDataAll[self.country.rscCongratsMessage])}">
							${(self.rscDataAll[self.country.rscCongratsMessage] == undefined ? '' : self.rscDataAll[self.country.rscCongratsMessage])}
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1214}">
							${pf.const.language.RSC1214}
						</td>
						<td class="text-truncate p-1">
							<span class="d-none">${(self.country.rscFailMessage == 0 ? '' : self.country.rscFailMessage)}</span>
							<div class="form-group mb-0">
								<div class="input-group new-input-style">
									<input id="rscFailMessage" type="text" class="form-control" value="${(self.country.rscFailMessage == 0 ? '' : self.country.rscFailMessage)}" title="${(self.country.rscFailMessage == 0 ? '' : self.country.rscFailMessage)}" disabled>
									<div class="input-group-append">
										<button id="btn_rscFailMessage" type="button" class="btn btn-outline-secondary btn-table" data-toggle="modal" data-target="#modalRSCTable" data-input="rscFailMessage" data-cell="rscFailMessageCell">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
							</div>
						</td>
						<td id="rscFailMessageCell" class="text-truncate" title="${(self.rscDataAll[self.country.rscFailMessage] == undefined ? '' : self.rscDataAll[self.country.rscFailMessage])}">
							${(self.rscDataAll[self.country.rscFailMessage] == undefined ? '' : self.rscDataAll[self.country.rscFailMessage])}
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1215}">
							${pf.const.language.RSC1215}
						</td>
						<td class="text-truncate p-1">
							<span class="d-none">${(self.country.rscMyReferralsPage == 0 ? '' : self.country.rscMyReferralsPage)}</span>
							<div class="form-group mb-0">
								<div class="input-group new-input-style">
									<input id="rscMyReferralsPage" type="text" class="form-control" value="${(self.country.rscMyReferralsPage == 0 ? '' : self.country.rscMyReferralsPage)}" title="${(self.country.rscMyReferralsPage == 0 ? '' : self.country.rscMyReferralsPage)}" disabled>
									<div class="input-group-append">
										<button id="btn_rscMyReferralsPage" type="button" class="btn btn-outline-secondary btn-table" data-toggle="modal" data-target="#modalRSCTable" data-input="rscMyReferralsPage" data-cell="rscMyReferralsPageCell">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
							</div>
						</td>
						<td id="rscMyReferralsPageCell" class="text-truncate" title="${(self.rscDataAll[self.country.rscMyReferralsPage] == undefined ? '' : self.rscDataAll[self.country.rscMyReferralsPage])}">
							${(self.rscDataAll[self.country.rscMyReferralsPage] == undefined ? '' : self.rscDataAll[self.country.rscMyReferralsPage])}
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1216}">
							${pf.const.language.RSC1216}
						</td>
						<td class="text-truncate p-1">
							<span class="d-none">${(self.country.rscClabeText == 0 ? '' : self.country.rscClabeText)}</span>
							<div class="form-group mb-0">
								<div class="input-group new-input-style">
									<input id="rscClabeText" type="text" class="form-control" value="${(self.country.rscClabeText == 0 ? '' : self.country.rscClabeText)}" title="${(self.country.rscClabeText == 0 ? '' : self.country.rscClabeText)}" disabled>
									<div class="input-group-append">
										<button id="btn_rscClabeText" type="button" class="btn btn-outline-secondary btn-table" data-toggle="modal" data-target="#modalRSCTable" data-input="rscClabeText" data-cell="rscClabeTextCell">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
							</div>
						</td>
						<td id="rscClabeTextCell" class="text-truncate" title="${(self.rscDataAll[self.country.rscClabeText] == undefined ? '' : self.rscDataAll[self.country.rscClabeText])}">
							${(self.rscDataAll[self.country.rscClabeText] == undefined ? '' : self.rscDataAll[self.country.rscClabeText])}
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1217}">
							${pf.const.language.RSC1217}
						</td>
						<td class="text-truncate p-1">
							<span class="d-none">${(self.country.rscClabeLabel == 0 ? '' : self.country.rscClabeLabel)}</span>
							<div class="form-group mb-0">
								<div class="input-group new-input-style">
									<input id="rscClabeLabel" type="text" class="form-control" value="${(self.country.rscClabeLabel == 0 ? '' : self.country.rscClabeLabel)}" title="${(self.country.rscClabeLabel == 0 ? '' : self.country.rscClabeLabel)}" disabled>
									<div class="input-group-append">
										<button id="btn_rscClabeLabel" type="button" class="btn btn-outline-secondary btn-table" data-toggle="modal" data-target="#modalRSCTable" data-input="rscClabeLabel" data-cell="rscClabeLabelCell">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
							</div>
						</td>
						<td id="rscClabeLabelCell" class="text-truncate" title="${(self.rscDataAll[self.country.rscClabeLabel] == undefined ? '' : self.rscDataAll[self.country.rscClabeLabel])}">
							${(self.rscDataAll[self.country.rscClabeLabel] == undefined ? '' : self.rscDataAll[self.country.rscClabeLabel])}
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1218}">
							${pf.const.language.RSC1218}
						</td>
						<td class="text-truncate p-1">
							<span class="d-none">${(self.country.rscClabePlaceholder == 0 ? '' : self.country.rscClabePlaceholder)}</span>
							<div class="form-group mb-0">
								<div class="input-group new-input-style">
									<input id="rscClabePlaceholder" type="text" class="form-control" value="${(self.country.rscClabePlaceholder == 0 ? '' : self.country.rscClabePlaceholder)}" title="${(self.country.rscClabePlaceholder == 0 ? '' : self.country.rscClabePlaceholder)}" disabled>
									<div class="input-group-append">
										<button id="btn_rscClabePlaceholder" type="button" class="btn btn-outline-secondary btn-table" data-toggle="modal" data-target="#modalRSCTable" data-input="rscClabePlaceholder" data-cell="rscClabePlaceholderCell">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
							</div>
						</td>
						<td id="rscClabePlaceholderCell" class="text-truncate" title="${(self.rscDataAll[self.country.rscClabePlaceholder] == undefined ? '' : self.rscDataAll[self.country.rscClabePlaceholder])}">
							${(self.rscDataAll[self.country.rscClabePlaceholder] == undefined ? '' : self.rscDataAll[self.country.rscClabePlaceholder])}
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1219}">
							${pf.const.language.RSC1219}
						</td>
						<td class="text-truncate p-1">
							<span class="d-none">${(self.country.rscClabeInvalid == 0 ? '' : self.country.rscClabeInvalid)}</span>
							<div class="form-group mb-0">
								<div class="input-group new-input-style">
									<input id="rscClabeInvalid" type="text" class="form-control" value="${(self.country.rscClabeInvalid == 0 ? '' : self.country.rscClabeInvalid)}" title="${(self.country.rscClabeInvalid == 0 ? '' : self.country.rscClabeInvalid)}" disabled>
									<div class="input-group-append">
										<button id="btn_rscClabeInvalid" type="button" class="btn btn-outline-secondary btn-table" data-toggle="modal" data-target="#modalRSCTable" data-input="rscClabeInvalid" data-cell="rscClabeInvalidCell">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
							</div>
						</td>
						<td id="rscClabeInvalidCell" class="text-truncate" title="${(self.rscDataAll[self.country.rscClabeInvalid] == undefined ? '' : self.rscDataAll[self.country.rscClabeInvalid])}">
							${(self.rscDataAll[self.country.rscClabeInvalid] == undefined ? '' : self.rscDataAll[self.country.rscClabeInvalid])}
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1220}">
							${pf.const.language.RSC1220}
						</td>
						<td class="text-truncate p-1">
							<span class="d-none">${(self.country.rscClabeExists == 0 ? '' : self.country.rscClabeExists)}</span>
							<div class="form-group mb-0">
								<div class="input-group new-input-style">
									<input id="rscClabeExists" type="text" class="form-control" value="${(self.country.rscClabeExists == 0 ? '' : self.country.rscClabeExists)}" title="${(self.country.rscClabeExists == 0 ? '' : self.country.rscClabeExists)}" disabled>
									<div class="input-group-append">
										<button id="btn_rscClabeExists" type="button" class="btn btn-outline-secondary btn-table" data-toggle="modal" data-target="#modalRSCTable" data-input="rscClabeExists" data-cell="rscClabeExistsCell">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
							</div>
						</td>
						<td id="rscClabeExistsCell" class="text-truncate" title="${(self.rscDataAll[self.country.rscClabeExists] == undefined ? '' : self.rscDataAll[self.country.rscClabeExists])}">
							${(self.rscDataAll[self.country.rscClabeExists] == undefined ? '' : self.rscDataAll[self.country.rscClabeExists])}
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1221}">
							${pf.const.language.RSC1221}
						</td>
						<td class="text-truncate p-1">
							<span class="d-none">${(self.country.rscClabeAdded == 0 ? '' : self.country.rscClabeAdded)}</span>
							<div class="form-group mb-0">
								<div class="input-group new-input-style">
									<input id="rscClabeAdded" type="text" class="form-control" value="${(self.country.rscClabeAdded == 0 ? '' : self.country.rscClabeAdded)}" title="${(self.country.rscClabeAdded == 0 ? '' : self.country.rscClabeAdded)}" disabled>
									<div class="input-group-append">
										<button id="btn_rscClabeAdded" type="button" class="btn btn-outline-secondary btn-table" data-toggle="modal" data-target="#modalRSCTable" data-input="rscClabeAdded" data-cell="rscClabeAddedCell">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
							</div>
						</td>
						<td id="rscClabeAddedCell" class="text-truncate" title="${(self.rscDataAll[self.country.rscClabeAdded] == undefined ? '' : self.rscDataAll[self.country.rscClabeAdded])}">
							${(self.rscDataAll[self.country.rscClabeAdded] == undefined ? '' : self.rscDataAll[self.country.rscClabeAdded])}
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1222}">
							${pf.const.language.RSC1222}
						</td>
						<td class="text-truncate p-1">
							<span class="d-none">${(self.country.rscClabeSecure == 0 ? '' : self.country.rscClabeSecure)}</span>
							<div class="form-group mb-0">
								<div class="input-group new-input-style">
									<input id="rscClabeSecure" type="text" class="form-control" value="${(self.country.rscClabeSecure == 0 ? '' : self.country.rscClabeSecure)}" title="${(self.country.rscClabeSecure == 0 ? '' : self.country.rscClabeSecure)}" disabled>
									<div class="input-group-append">
										<button id="btn_rscClabeSecure" type="button" class="btn btn-outline-secondary btn-table" data-toggle="modal" data-target="#modalRSCTable" data-input="rscClabeSecure" data-cell="rscClabeSecureCell">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
							</div>
						</td>
						<td id="rscClabeSecureCell" class="text-truncate" title="${(self.rscDataAll[self.country.rscClabeSecure] == undefined ? '' : self.rscDataAll[self.country.rscClabeSecure])}">
							${(self.rscDataAll[self.country.rscClabeSecure] == undefined ? '' : self.rscDataAll[self.country.rscClabeSecure])}
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1223}">
							${pf.const.language.RSC1223}
						</td>
						<td class="text-truncate p-1">
							<span class="d-none">${(self.country.rscClabeEdit == 0 ? '' : self.country.rscClabeEdit)}</span>
							<div class="form-group mb-0">
								<div class="input-group new-input-style">
									<input id="rscClabeEdit" type="text" class="form-control" value="${(self.country.rscClabeEdit == 0 ? '' : self.country.rscClabeEdit)}" title="${(self.country.rscClabeEdit == 0 ? '' : self.country.rscClabeEdit)}" disabled>
									<div class="input-group-append">
										<button id="btn_rscClabeEdit" type="button" class="btn btn-outline-secondary btn-table" data-toggle="modal" data-target="#modalRSCTable" data-input="rscClabeEdit" data-cell="rscClabeEditCell">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
							</div>
						</td>
						<td id="rscClabeEditCell" class="text-truncate" title="${(self.rscDataAll[self.country.rscClabeEdit] == undefined ? '' : self.rscDataAll[self.country.rscClabeEdit])}">
							${(self.rscDataAll[self.country.rscClabeEdit] == undefined ? '' : self.rscDataAll[self.country.rscClabeEdit])}
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1224}">
							${pf.const.language.RSC1224}
						</td>
						<td class="text-truncate p-1">
							<span class="d-none">${(self.country.rscWelcomeMsg == 0 ? '' : self.country.rscWelcomeMsg)}</span>
							<div class="form-group mb-0">
								<div class="input-group new-input-style">
									<input id="rscWelcomeMsg" type="text" class="form-control" value="${(self.country.rscWelcomeMsg == 0 ? '' : self.country.rscWelcomeMsg)}" title="${(self.country.rscWelcomeMsg == 0 ? '' : self.country.rscWelcomeMsg)}" disabled>
									<div class="input-group-append">
										<button id="btn_rscWelcomeMsg" type="button" class="btn btn-outline-secondary btn-table" data-toggle="modal" data-target="#modalRSCTable" data-input="rscWelcomeMsg" data-cell="rscWelcomeMsgCell">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
							</div>
						</td>
						<td id="rscWelcomeMsgCell" class="text-truncate" title="${(self.rscDataAll[self.country.rscWelcomeMsg] == undefined ? '' : self.rscDataAll[self.country.rscWelcomeMsg])}">
							${(self.rscDataAll[self.country.rscWelcomeMsg] == undefined ? '' : self.rscDataAll[self.country.rscWelcomeMsg])}
						</td>
					</tr>
				</tbody>
			</table>
		`;

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

		let tableTexts = $('#tableCountryTexts').DataTable({
			retrieve: true,
			language: self.language,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{width: '90px', targets: 1}
			],
			ordering: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1067 + '_' + pf.const.language.RSC965,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Exportar tabla
		$('#exportTextTables').off().on('click', function() {
			$('#textsTables .buttons-excel').trigger('click');
		});

		self.textsByCountryEvents();
	},

	textsByCountryEvents() {
		let self = this;

		// Modal de RSC
		$('.btn-table').off().on('click', function() {
			let position = $(this).data('input');
			let inputId = $(this).data('input');
			let cellId = $(this).data('cell');
			self.renderRscData(inputId, cellId, position);
		});
	},

	getTemplatePagosByCountry() {
		let self = this;

		let parameters = {
			pais: self.countryIso
		};
		ajaxComunCallWithCallback('getTemplatePagosByCountry', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.paymentFields = ajaxReturn.result[0];
					
				if(self.paymentFields == undefined) {
					self.paymentFields = {
						banco: '',
						ciudad: '',
						direccion: '',
						identificacion: '',
						pais: self.countryIso,
						telefono: '',
						tipoCuenta: '',
						tipoIdentificacion: ''
					};
				}
				self.paymentFieldsTable();

				// Control de spinner
				self.loaders.getTemplatePagosByCountry = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	paymentFieldsTable() {
		let self = this;

		let table = `
			<table id="tablePaymentFields" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1225}">
							${pf.const.language.RSC1225}
							<span class="float-right">${pf.const.language.RSC278}:</span>
						</th>
						<th scope="col" class="pl-0">
							<div class="custom-control custom-switch">
								<input id="allSwitchs" type="checkbox" class="custom-control-input">
								<label for="allSwitchs" class="custom-control-label c-pointer"></label>
							</div>
						</th>
					</tr>
				</thead>

				<tbody>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC610}">${pf.const.language.RSC610}</td>
						<td class="pl-0">
							<span class="d-none">${(self.paymentFields.identificacion == 1 ? '1' : '0')}</span>
							<div class="custom-control custom-switch">
								<input id="identificacion" type="checkbox" class="custom-control-input uSwitch" ${(self.paymentFields.identificacion == 1 ? 'checked' : '')}>
								<label for="identificacion" class="custom-control-label c-pointer"></label>
							</div>
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC609}">${pf.const.language.RSC609}</td>
						<td class="pl-0">
							<span class="d-none">${(self.paymentFields.tipoIdentificacion == 1 ? '1' : '0')}</span>
							<div class="custom-control custom-switch">
								<input id="tipoIdentificacion" type="checkbox" class="custom-control-input uSwitch" ${(self.paymentFields.tipoIdentificacion == 1 ? 'checked' : '')}>
								<label for="tipoIdentificacion" class="custom-control-label c-pointer"></label>
							</div>
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1226}">${pf.const.language.RSC1226}</td>
						<td class="pl-0">
							<span class="d-none">${(self.paymentFields.banco == 1 ? '1' : '0')}</span>
							<div class="custom-control custom-switch">
								<input id="banco" type="checkbox" class="custom-control-input uSwitch" ${(self.paymentFields.banco == 1 ? 'checked' : '')}>
								<label for="banco" class="custom-control-label c-pointer"></label>
							</div>
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1227}">${pf.const.language.RSC1227}</td>
						<td class="pl-0">
							<span class="d-none">${(self.paymentFields.tipoCuenta == 1 ? '1' : '0')}</span>
							<div class="custom-control custom-switch">
								<input id="tipoCuenta" type="checkbox" class="custom-control-input uSwitch" ${(self.paymentFields.tipoCuenta == 1 ? 'checked' : '')}>
								<label for="tipoCuenta" class="custom-control-label c-pointer"></label>
							</div>
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC607}">${pf.const.language.RSC607}</td>
						<td class="pl-0">
							<span class="d-none">${(self.paymentFields.ciudad == 1 ? '1' : '0')}</span>
							<div class="custom-control custom-switch">
								<input id="ciudad" type="checkbox" class="custom-control-input uSwitch" ${(self.paymentFields.ciudad == 1 ? 'checked' : '')}>
								<label for="ciudad" class="custom-control-label c-pointer"></label>
							</div>
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1229}">${pf.const.language.RSC1229}</td>
						<td class="pl-0">
							<span class="d-none">${(self.paymentFields.direccion == 1 ? '1' : '0')}</span>
							<div class="custom-control custom-switch">
								<input id="direccion" type="checkbox" class="custom-control-input uSwitch" ${(self.paymentFields.direccion == 1 ? 'checked' : '')}>
								<label for="direccion" class="custom-control-label c-pointer"></label>
							</div>
						</td>
					</tr>
					<tr>
						<td class="text-truncate" title="${pf.const.language.RSC1228}">${pf.const.language.RSC1228}</td>
						<td class="pl-0">
							<span class="d-none">${(self.paymentFields.telefono == 1 ? '1' : '0')}</span>
							<div class="custom-control custom-switch">
								<input id="telefono" type="checkbox" class="custom-control-input uSwitch" ${(self.paymentFields.telefono == 1 ? 'checked' : '')}>
								<label for="telefono" class="custom-control-label c-pointer"></label>
							</div>
						</td>
					</tr>
				</tbody>
			</table>
		`;

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

		let tablePaymentFields = $('#tablePaymentFields').DataTable({
			retrieve: true,
			language: self.language,
			paging: false,
			searching: false,
			ordering: false,
			autoWidth: false,
			columnDefs: [
				{width: '30px', targets: 1}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1225,
				className: 'd-none',
				title: pf.const.language.RSC1225,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

		// Si todos los checkbox están seleccionados, se selecciona el checkbox principal, y viceversa
		// Comprobación inicial
		if($('.uSwitch').length == $('.uSwitch:checked').length) {
			$('#allSwitchs').prop('checked', true);
		} else {
			$('#allSwitchs').prop('checked', false);
		} 

		// La id del elemento principal modifica los elementos secundarios a través de su clase
		$('#allSwitchs').on('click', function() {
			$('.uSwitch').prop('checked', this.checked);
		});

		// Si todos los checkbox están seleccionados, se selecciona el checkbox principal, y viceversa
		$('.uSwitch').on('click', function() {
			if($('.uSwitch').length == $('.uSwitch:checked').length) {
				$('#allSwitchs').prop('checked', true);
			} else {
				$('#allSwitchs').prop('checked', false);
			}
		});

		// Exportar tabla
		$('#exportPaymentFieldsTables').off().on('click', function() {
			$('#paymentFields .buttons-excel').trigger('click');
		});
	},

	renderRscData(inputId, cellId, position, eArray) {
		let self = this;

		let language = sessionStorage['STCMBackEnd:lenguage'];

		if(self.tableRSCFlag) {
			$('#tableRSC').dataTable().fnDestroy();
		} else {
			self.tableRSCFlag = true;
		}

		// Comprobación de array
		if(!Array.isArray(self.rscData)) {
			self.rscData = [];
		}

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
					<th scope="col" title="${language}">${language}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>id</td>
					<td>language</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.rscData.length;
		for(let i = 0; i < size; i++) {
			let languageRSC = self.rscData[i][language];

			// Solo RSC que no son de system
			if(self.rscData[i].system == 1) {
				continue;
			}

			table += `
				<tr id="id-${self.rscData[i].idRSC}" class="c-pointer rscElement" data-id="${self.rscData[i].idRSC}" data-text="${languageRSC}">
					<td title="${self.rscData[i].idRSC}">${self.rscData[i].idRSC}</td>
					<td title="${languageRSC}">${languageRSC}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

		let tableRSC = $('#tableRSC').DataTable({
			retrieve: true,
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			aaSorting: [],
			columnDefs: [
				{width: '60px', targets: 0}
			]
		});

		setTimeout(function() {
			tableRSC.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(tableRSC, 'filtersResult');

		self.rscDataEvents(inputId, cellId, position, eArray);

		$('#tableRSC').on('draw.dt', function() {
			self.rscDataEvents(inputId, cellId, position, eArray);
		});
	},

	rscDataEvents(inputId = null, cellId = null, position, eArray = null) {
		let self = this;

		// Seleccionar RSC
		$('.rscElement').off().on('click', function() {
			let rscId = $(this).data('id');
			let rscText = $(this).data('text');

			if(inputId == null && cellId == null) {
				self.chatsArray[position].message = rscId;
				$('#chatMessage' + position).val(rscText);
				$('#chatMessage' + position).prop('title', rscText);
			} else {
				$('#' + inputId).val(rscId);
				$('#' + inputId).attr('title', rscId);
				$('#' + cellId).html(rscText);
				$('#' + cellId).attr('title', rscText);

				if(eArray === 'identification') {
					self.identificationArray[position].rsc = rscId;
					self.identificationArray[position].description = rscText;
				} else if(eArray === 'account') {
					self.accountArray[position].rsc = rscId;
					self.accountArray[position].description = rscText;
				} else {
					self.country[position] = rscId;
				}
			}

			$('#closeRSC').trigger('click');
		});
	},

	getPaisesTipoIdentificacion() {
		let self = this;

		let parameters = {
			pais: self.countryIso
		};
		ajaxComunCallWithCallback('getPaisesTipoIdentificacion', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					let obj = {
						rsc: ajaxReturn.result[i].descripcion,
						code: ajaxReturn.result[i].code
					};
					self.identificationArray.push(obj);
				}

				self.identificationTable();

				// Control de spinner
				self.loaders.getPaisesTipoIdentificacion = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	identificationTable() {
		let self = this;

		let excelTitle = pf.const.language.RSC609;

		let table = `
			<table id="tableIdentification" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="RSC">RSC</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC437}">${pf.const.language.RSC437}</th>
						<th scope="col" title=""></th>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.identificationArray.length;
		if(size < 1) {
			let obj = {
				rsc: '',
				code: ''
			};
			self.identificationArray.push(obj);
			size = 1;
		}

		for(let i = 0; i < size; i++) {
			let cellValue = self.identificationArray[i].rsc == '' ? '' : self.rscDataAll[self.identificationArray[i].rsc];

			table += `
				<tr data-id="id${i}">
					<td class="text-truncate p-1">
						<span class="d-none">${self.identificationArray[i].rsc}</span>
						<div class="form-group mb-0">
							<div class="input-group new-input-style">
								<input id="identification_${i}" type="text" class="form-control" value="${self.identificationArray[i].rsc}" title="${self.identificationArray[i].rsc}" disabled>
								<div class="input-group-append">
									<button id="btn_identification_${i}" type="button" class="btn btn-outline-secondary btn-table-id" data-toggle="modal" data-target="#modalRSCTable" data-input="identification_${i}" data-cell="cell_id_${i}">
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
					<td id="cell_id_${i}" class="text-truncate" title="${cellValue}">
						${cellValue}
					</td>
					<td class="text-truncate p-1">
						<span id="valueID${i}" class="d-none">${self.identificationArray[i].code}</span>
						<input id="valueInputID${i}" type="text" class="form-control valueInputID" value="${self.identificationArray[i].code}" title="${self.identificationArray[i].code}">
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteIdentification">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

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

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

		let tableIdentification = $('#tableIdentification').DataTable({
			retrieve: true,
			language: self.language,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{width: '90px', targets: 0},
				{width: '30px', targets: 3}
			],
			ordering: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: excelTitle,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Exportar tabla
		$('#exportIdentificationTables').off().on('click', function() {
			self.identificationTable();
			$('#identificationTable .buttons-excel').trigger('click');
		});

		self.identificationTableEvents();
	},

	identificationTableEvents() {
		let self = this;

		// Modal de RSC
		$('.btn-table-id').off().on('click', function() {
			let position = $(this).attr('id').replace('btn_identification_', '');
			let inputId = $(this).data('input');
			let cellId = $(this).data('cell');
			self.renderRscData(inputId, cellId, position, 'identification');
		});

		// Input de código
		$('.valueInputID').off().on('blur', function() {
			let index = $(this).attr('id').replace('valueInputID', '');
			let value = $(this).val();
			self.identificationArray[index].code = value;
		});

		// Eliminar registro
		$('.deleteIdentification').off().on('click', function() {
			let index = $(this).parent().parent().attr('data-id').replace('id', '');
			self.identificationArray.splice(index, 1);
			self.identificationTable();
		});
	},

	getPaisesTipoCuentas() {
		let self = this;

		let parameters = {
			pais: self.countryIso
		};
		ajaxComunCallWithCallback('getPaisesTipoCuentas', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					let obj = {
						rsc: ajaxReturn.result[i].descripcion,
						code: ajaxReturn.result[i].code
					};
					self.accountArray.push(obj);
				}

				self.accountTable();

				// Control de spinner
				self.loaders.getPaisesTipoCuentas = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	accountTable() {
		let self = this;

		let excelTitle = pf.const.language.RSC1111;

		let table = `
			<table id="tableAccount" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="RSC">RSC</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC437}">${pf.const.language.RSC437}</th>
						<th scope="col" title=""></th>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.accountArray.length;
		if(size < 1) {
			let obj = {
				rsc: '',
				code: ''
			};
			self.accountArray.push(obj);
			size = 1;
		}

		for(let i = 0; i < size; i++) {
			let cellValue = self.accountArray[i].rsc === '' ? '' : self.rscDataAll[self.accountArray[i].rsc];

			table += `
				<tr data-id="id${i}">
					<td class="text-truncate p-1">
						<span class="d-none">${self.accountArray[i].rsc}</span>
						<div class="form-group mb-0">
							<div class="input-group new-input-style">
								<input id="account_${i}" type="text" class="form-control" value="${self.accountArray[i].rsc}" title="${self.accountArray[i].rsc}" disabled>
								<div class="input-group-append">
									<button id="btn_account_${i}" type="button" class="btn btn-outline-secondary btn-table-account" data-toggle="modal" data-target="#modalRSCTable" data-input="account_${i}" data-cell="cell_account_${i}">
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
					<td id="cell_account_${i}" class="text-truncate" title="${cellValue}">
						${cellValue}
					</td>
					<td class="text-truncate p-1">
						<span id="valueAC${i}" class="d-none">${self.accountArray[i].code}</span>
						<input id="valueInputAC${i}" type="text" class="form-control valueInputAC" value="${self.accountArray[i].code}" title="${self.accountArray[i].code}">
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteAccount">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

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

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

		let tableAccount = $('#tableAccount').DataTable({
			retrieve: true,
			language: self.language,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{width: '90px', targets: 0},
				{width: '30px', targets: 3}
			],
			ordering: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: excelTitle,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Exportar tabla
		$('#exportAccountTables').off().on('click', function() {
			self.accountTable();
			$('#accountTable .buttons-excel').trigger('click');
		});

		self.accountTableEvents();
	},

	accountTableEvents() {
		let self = this;

		// Modal de RSC
		$('.btn-table-account').off().on('click', function() {
			let position = $(this).attr('id').replace('btn_account_', '');
			let inputId = $(this).data('input');
			let cellId = $(this).data('cell');
			self.renderRscData(inputId, cellId, position, 'account');
		});

		// Input de código
		$('.valueInputAC').off().on('blur', function() {
			let index = $(this).attr('id').replace('valueInputAC', '');
			let value = $(this).val();
			self.accountArray[index].code = value;
		});

		// Eliminar registro
		$('.deleteAccount').off().on('click', function() {
			let index = $(this).parent().parent().attr('data-id').replace('id', '');
			self.accountArray.splice(index, 1);
			self.accountTable();
		});
	},

	getPaisesBancos() {
		let self = this;

		let parameters = {
			pais: self.countryIso
		};
		ajaxComunCallWithCallback('getPaisesBancos', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					let obj = {
						code: ajaxReturn.result[i].code,
						description: ajaxReturn.result[i].descripcion
					};
					self.banksArray.push(obj);
				}

				self.banksTable();

				// Control de spinner
				self.loaders.getPaisesBancos = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	banksTable() {
		let self = this;

		let excelTitle = pf.const.language.RSC1230;

		let table = `
			<table id="tableBanks" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1226}">${pf.const.language.RSC1226}</th>
						<th scope="col" title="${pf.const.language.RSC437}">${pf.const.language.RSC437}</th>
						<th scope="col" title=""></th>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.banksArray.length;
		if(size < 1) {
			let obj = {
				code: '',
				description: ''
			};
			self.banksArray.push(obj);
			size = 1;
		}

		for(let i = 0; i < size; i++) {
			table += `
				<tr data-id="id${i}">
					<td class="text-truncate p-1">
						<span id="bank${i}" class="d-none">${self.banksArray[i].description}</span>
						<input id="bankInput${i}" type="text" class="form-control bankInput" value="${self.banksArray[i].description}" title="${self.banksArray[i].description}">
					</td>
					<td class="text-truncate p-1">
						<span id="bankCode${i}" class="d-none">${self.banksArray[i].code}</span>
						<input id="bankCodeInput${i}" type="text" class="form-control bankCodeInput" value="${self.banksArray[i].code}" title="${self.banksArray[i].code}">
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteBank">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

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

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

		let tableBanks = $('#tableBanks').DataTable({
			retrieve: true,
			language: self.language,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{width: '90px', targets: 1},
				{width: '30px', targets: 2}
			],
			ordering: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: excelTitle,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Exportar tabla
		$('#exportBankTable').off().on('click', function() {
			self.banksTable();
			$('#banks .buttons-excel').trigger('click');
		});

		self.banksTableEvents();
	},

	banksTableEvents() {
		let self = this;

		// Input de descripción de banco
		$('.bankInput').off().on('blur', function() {
			let index = $(this).attr('id').replace('bankInput', '');
			let value = $(this).val();
			self.banksArray[index].description = value;
		});

		// Input de código
		$('.bankCodeInput').off().on('blur', function() {
			let index = $(this).attr('id').replace('bankCodeInput', '');
			let value = $(this).val();
			self.banksArray[index].code = value;
		});

		// Eliminar registro
		$('.deleteBank').off().on('click', function() {
			let index = $(this).parent().parent().attr('data-id').replace('id', '');
			self.banksArray.splice(index, 1);
			self.banksTable();
		});
	},

	getWelcomeChatsById() {
		let self = this;

		let parameters = {
			pais: self.countryIso
		};
		ajaxComunCallWithCallback('getWelcomeChatsById', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(ajaxReturn.result !== 'No welcome message for country.') {
					let size = ajaxReturn.result.length;
					for(let i = 0; i < size; i++) {
						let obj = {
							user: ajaxReturn.result[i].jid,
							type: ajaxReturn.result[i].MotivoNotificacion,
							message: ajaxReturn.result[i].RSCANotficar,
							typeAttached: ajaxReturn.result[i].TipoArchivoANotificar,
							attached: ajaxReturn.result[i].ArchivoANotificar,
							attachedPath: ajaxReturn.result[i].PathArchivoANotificar,
							survey: ajaxReturn.result[i].EncuestaANotificar,
							mission: ajaxReturn.result[i].MisionANotificar,
							missionName: ajaxReturn.result[i].idmision,
							textoiniciomision: ajaxReturn.result[i].textoiniciomision
						};
						self.chatsArray.push(obj);
					}
				} else {
					self.chatsNew = true;
				}

				self.chatsTable();

				// Control de spinner
				self.loaders.getWelcomeChatsById = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	chatsTable() {
		let self = this;

		let table = `
			<table id="tableChats" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC68}">${pf.const.language.RSC68}</th>
						<th scope="col" title="${pf.const.language.RSC367}">${pf.const.language.RSC367}</th>
						<th scope="col" title="${pf.const.language.RSC164}">${pf.const.language.RSC164}</th>
						<th scope="col" title="${pf.const.language.RSC1519}">${pf.const.language.RSC1519}</th>
						<th scope="col" title=""></th>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.chatsArray.length;
		if(size < 1) {
			let obj = {
				user: '',
				type: '0',
				message: '',
				typeAttached: 'Imagen',
				attached: '',
				attachedPath: '',
				survey: '',
				mission: '',
				missionName: '',
				textoiniciomision: ''
			};
			self.chatsArray.push(obj);
			size = 1;
		}

		for(let i = 0; i < size; i++) {
			table += `
				<tr data-id="id${i}">
					<td class="text-truncate p-1">
						<div class="input-group new-input-style mb-0">
							<input id="userChat${i}" type="text" class="form-control" aria-describedby="btn-user${i}" placeholder="${pf.const.language.RSC434}" value="${self.chatsArray[i].user}" title="${self.chatsArray[i].user}" disabled>
							<div class="input-group-append">
								<button id="btn-user${i}" type="button" class="btn btn-outline-secondary btn-user" data-toggle="modal" data-target="#modalContainer" data-index="${i}">
									${stcmbackend.svg.threeDots}
								</button>
							</div>
						</div>
					</td>

					<td class="text-truncate text-center p-1" title="${pf.const.language.RSC226}">
						<div class="form-group mb-0">
							<select id="chatType${i}" class="form-control chatType" name="chatType${i}" data-index="${i}">
								<option value="0" ${(self.chatsArray[i].type == 0 ? 'selected' : '')}>${pf.const.language.RSC164}</option>
								<option value="1" ${(self.chatsArray[i].type == 1 ? 'selected' : '')}>${pf.const.language.RSC415}</option>
								<option value="2" ${(self.chatsArray[i].type == 2 ? 'selected' : '')}>${pf.const.language.RSC416}</option>
								<option value="3" ${(self.chatsArray[i].type == 3 ? 'selected' : '')}>${pf.const.language.RSC2322}</option>
							</select>
						</div>
					</td>

					<td class="text-truncate p-1">
						<div id="chatMessageContainer${i}" class="form-group mb-0 ${(self.chatsArray[i].type == 3 ? 'd-none' : '')}">
							<div class="input-group new-input-style">
								<input id="chatMessage${i}" type="text" class="form-control" value="${(self.rscDataAll[self.chatsArray[i].message] == undefined ? '' : self.rscDataAll[self.chatsArray[i].message])}" title="${(self.rscDataAll[self.chatsArray[i].message] == undefined ? '' : self.rscDataAll[self.chatsArray[i].message])}" disabled>
								<div class="input-group-append">
									<button id="btn_chatMessage${i}" type="button" class="btn btn-outline-secondary chatMessage" data-toggle="modal" data-target="#modalRSCTable" data-index="${i}">
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>

						<span id="startText${i}" class="fs-1_2em ${(self.chatsArray[i].type == 3 ? '' : 'd-none')}" title="${self.chatsArray[i].textoiniciomision}">${self.chatsArray[i].textoiniciomision}</span>
					</td>

					<td class="text-truncate p-1">
						<div id="chatAttachment${i}" class="form-row ${(self.chatsArray[i].type == 1 ? '' : 'd-none')}">
							<div class="col-4">
								<div class="form-group m-0">
									<select id="tipoArchivoANotificar${i}" class="form-control tipoArchivoANotificar" data-index="${i}">
										<!-- Imagen -->
										<option value="Imagen" ${(self.chatsArray[i].typeAttached == 'Imagen' ? 'selected' : '')}>${pf.const.language.RSC419}</option>
										<!-- PDF -->
										<option value="PDF" ${(self.chatsArray[i].typeAttached == 'PDF' ? 'selected' : '')}>${pf.const.language.RSC418}</option>
										<!-- Video -->
										<option value="Video" ${(self.chatsArray[i].typeAttached == 'Video' ? 'selected' : '')}>${pf.const.language.RSC420}</option>
									</select>
								</div>
							</div>
							<div class="col-8">
								<div class="input-group new-input-style">
									<input id="archivoANotificar${i}" type="text" class="form-control" name="archivoANotificar${i}" value="${self.chatsArray[i].attached}" disabled>
									<div class="input-group-append">
										<button type="button" class="btn btn-outline-secondary archivoANotificar" data-index="${i}">
											${stcmbackend.svg.threeDots}
										</button>
									</div>
								</div>
								<div class="custom-file d-none">
									<input id="archivoANotificarHidden${i}" type="file" class="custom-file-input" accept="image/*" placeholder="" aria-describedby="archivoANotificarHidden">
									<label for="archivoANotificarHidden${i}" class="custom-file-label" data-browse="..."></label>
								</div>
							</div>
						</div>

						<div id="chatSurvey${i}" class="input-group new-input-style ${(self.chatsArray[i].type == 2 ? '' : 'd-none')}">
							<!-- Selecciona encuesta -->
							<input id="descEncuestaANotificar${i}" type="text" class="form-control" name="descEncuestaANotificar${i}" placeholder="${pf.const.language.RSC423}" value="${self.chatsArray[i].survey}" disabled>
							<div class="input-group-append">
								<button id="btn-survey${i}" type="button" class="btn btn-outline-secondary btn-survey" data-toggle="modal" data-target="#modalContainer" data-index="${i}">
									${stcmbackend.svg.threeDots}
								</button>
							</div>
						</div>

						<div id="chatMission${i}" class="input-group new-input-style ${(self.chatsArray[i].type == 3 ? '' : 'd-none')}">
							<!-- Selecciona mision -->
							<input id="descMisionANotificar${i}" type="text" class="form-control" name="descMisionANotificar${i}" placeholder="${pf.const.language.RSC2323}" value="${self.chatsArray[i].missionName}" title="${self.chatsArray[i].missionName}" disabled>
							<div class="input-group-append">
								<button id="btn-mission${i}" type="button" class="btn btn-outline-secondary btn-mission" data-toggle="modal" data-target="#modalContainer" data-index="${i}">
									${stcmbackend.svg.threeDots}
								</button>
							</div>
						</div>
					</td>

					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteChat" data-index="${i}">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

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

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

		let tableChats = $('#tableChats').DataTable({
			retrieve: true,
			language: self.language,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{width: '190px', targets: 1},
				{width: '30px', targets: 4}
			],
			ordering: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1515,
				className: 'd-none',
				title: pf.const.language.RSC1515,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Exportar tabla
		$('#exportChat').off().on('click', function() {
			$('#chats .buttons-excel').trigger('click');
		});

		self.chatsTableEvents();
	},

	chatsTableEvents() {
		let self = this;

		// Input de usuario de chat
		let users = new TableUsers(0, 'editCountry');

		users.enabled = '1';
		users.staff = '1';
		$('.btn-user').click(function() {
			self.userOrder = $(this).data('index');
			users.surname = false;
			users.setEvents('tableModal');
			self.chatsChange = true;
		});

		// Tipo de notificación
		$('.chatType').change(function() {
			let value = $(this).val();
			let index = $(this).data('index');
			self.chatsArray[index].type = value;
			if(value == '0') {
				$('#btn_chatMessage' + index).attr('disabled', false);
				$('#chatAttachment' + index).addClass('d-none');
				$('#chatSurvey' + index).addClass('d-none');
				$('#chatMission' + index).addClass('d-none');
				$('#chatMessageContainer' + index).removeClass('d-none');
				$('#startText' + index).addClass('d-none');
			} else if(value == '1') {
				$('#btn_chatMessage' + index).attr('disabled', false);
				$('#chatAttachment' + index).removeClass('d-none');
				$('#chatSurvey' + index).addClass('d-none');
				$('#chatMission' + index).addClass('d-none');
				$('#chatMessageContainer' + index).removeClass('d-none');
				$('#startText' + index).addClass('d-none');
			} else if(value == '2') {
				$('#btn_chatMessage' + index).attr('disabled', false);
				$('#chatAttachment' + index).addClass('d-none');
				$('#chatSurvey' + index).removeClass('d-none');
				$('#chatMission' + index).addClass('d-none');
				$('#chatMessageContainer' + index).removeClass('d-none');
				$('#startText' + index).addClass('d-none');
			} else if(value == '3') {
				$('#btn_chatMessage' + index).attr('disabled', false);
				$('#chatAttachment' + index).addClass('d-none');
				$('#chatSurvey' + index).addClass('d-none');
				$('#chatMission' + index).removeClass('d-none');
				$('#chatMessageContainer' + index).addClass('d-none');
				$('#startText' + index).removeClass('d-none');
			}
			self.chatsChange = true;
		});

		// RSC de mensaje
		$('.chatMessage').click(function() {
			let position = $(this).data('index');
			let inputId = null;
			let cellId = null;
			self.renderRscData(inputId, cellId, position);
			self.chatsChange = true;
		});

		// Tipo de archivo
		$('.tipoArchivoANotificar').on('change', function() {
			let type = $(this).val();
			let index = $(this).data('index');
			self.chatsArray[index].typeAttached = type;

			$('#archivoANotificar' + index).val('');
			self.chatsArray[index].attached = null;
			switch(type) {
				case 'PDF':
					$('#archivoANotificarHidden' + index).attr('accept', 'application/pdf')
					break;
				case 'Imagen':
					$('#archivoANotificarHidden' + index).attr('accept', 'image/*')
					break;
				case 'Video':
					$('#archivoANotificarHidden' + index).attr('accept', 'video/*')
					break;
				default:
					break;
			}
		});

		// Adjunto a notificar
		$('.archivoANotificar').click(function() {
			let index = $(this).data('index');

			$('#archivoANotificarHidden' + index).off().on('change', function(evt) {
				let inputFile = evt.target;
				let typeSelect = $('#tipoArchivoANotificar' + index).val();
				self.chatsArray[index].typeAttached = typeSelect;
				let type = inputFile.files[0].type;
				let correctSyze = false;
				if(typeSelect == 'Imagen') {
					let ext = type.split('/');
					if(ext[1] == 'png' || ext[1] == 'gif' || ext[1] == 'bmp' || ext[1] == 'jpg' || ext[1] == 'jpeg') {
						correctSyze = true;
					}
				} else if(typeSelect == 'Video') {
					let ext = type.split('/');
					if(ext[1] == 'mp4' || ext[1] == 'mov' || ext[1] == 'avi') {
						correctSyze = true;
					}
				} else if(typeSelect == 'PDF') {
					let ext = type.split('/');
					if(ext[1] == 'pdf') {
						correctSyze = true;
					}
				}

				if(!correctSyze) {
					// Archivo a notificar
					let errorTitle = pf.const.language.RSC417;
					// Tipo de archivo no permitido 
					let errorContent = pf.const.language.RSC507;
					pf.utils.showInfoDialog(errorTitle, errorContent);
					self.chatsArray[index].attached = '';
					$('#archivoANotificar' + index).val('');
				} else if(inputFile.files[0].size > self.maxSize) {
					// Archivo a notificar
					let errorTitle = pf.const.language.RSC417;
					// EL tamaño del archivo supera el maáximo permitido 
					let errorContent = pf.const.language.RSC439;
					pf.utils.showInfoDialog(errorTitle, errorContent);
					self.chatsArray[index].attached = '';
					$('#archivoANotificar' + index).val('');
				} else {
					self.chatsAttached = true;
					self.chatsArray[index].attached = inputFile.files[0].name;
					self.attachmentsArray.push(inputFile.files[0]);
					$('#archivoANotificar' + index).val(inputFile.files[0].name);
				}
			});

			self.chatsChange = true;
			$('#archivoANotificarHidden' + index).trigger('click');
		});

		// Seleccionar encuesta
		let surveys = new TableSurveys(0, 'editCountries');
		$('.btn-survey').click(function() {
			self.surveyIndex = $(this).data('index');

			surveys.setEvents('tableModal');
			self.chatsChange = true;
		});

		// Seleccionar mision
		let mission = new TableStartMissions('editCountries');
		$('.btn-mission').click(function() {
			self.surveyIndex = $(this).data('index');

			mission.setEvents('tableModal');
			self.chatsChange = true;
		});

		// Eliminar registro
		$('.deleteChat').off().on('click', function() {
			let index = $(this).data('index');
			self.chatsArray.splice(index, 1);
			self.chatsTable();
			self.chatsChange = true;
		});
	},

	clickUser(user) {
		let self = this;

		self.chatsArray[self.userOrder].user = user.id;
		$('#userChat' + self.userOrder).val(user.id);
		$('#userChat' + self.userOrder).attr('title', user.id);
	},

	clickSurvey(survey) {
		let self = this;

		self.chatsArray[self.surveyIndex].survey = survey.sid;
		$('#descEncuestaANotificar' + self.surveyIndex).val(survey.sid);
		$('#descEncuestaANotificar' + self.surveyIndex).attr('title', survey.surveyls_title);
	},

	clickMission(mission) {
		let self = this;

		self.chatsArray[self.surveyIndex].mission = mission.stampMision;
		self.chatsArray[self.surveyIndex].missionName = mission.idmision;
		$('#descMisionANotificar' + self.surveyIndex).val(mission.idmision);
		$('#descMisionANotificar' + self.surveyIndex).attr('title', mission.idmision);
		$('#startText' + self.surveyIndex).text(mission.textoiniciomision);
		$('#startText' + self.surveyIndex).attr('title', mission.textoiniciomision);
	},

	getPonderacionesByCountry() {
		let self = this;

		let parameters = {
			country: self.countryIso
		};
		ajaxComunCallWithCallback('getPonderacionesByCountry', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(!Array.isArray(ajaxReturn.result)) {
					$('#weightingsContainer').show();
					self.weightings = ajaxReturn.result;

					for(data in self.weightings) {
						self.renderWeightings(data, self.weightings[data]);
					}

					$('.inputWeightings').off().on('blur', function() {
						let value = $(this).val();
						let element = $(this).data('element');
						let row = $(this).data('row');

						if(parseInt(value) < 0) {
							value = 0;
						} else if(parseInt(value) > 100) {
							value = 100;
						}

						self.weightings[element][row] = value;
						$(this).val(value);
						$(this).parent().parent().find('.textValue').text(value);
					});
				} else {
					$('#weightingsContainer').hide();
				}

				// Control de spinner
				self.loaders.getPonderacionesByCountry = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	renderWeightings(element, data) {
		let self = this;

		let excelTitle = '';

		switch(element) {
			case 'sec':
				excelTitle = pf.const.language.RSC598;
				break;
			case 'edad':
				excelTitle = pf.const.language.RSC565;
				break;
			case 'region':
				excelTitle = pf.const.language.RSC597;
				break;
			case 'genero':
				excelTitle = pf.const.language.RSC151;
				break;
		}

		let table = `
			<table id="table_${element}" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${excelTitle}">${excelTitle}</th>
						<th scope="col" title="${pf.const.language.RSC1777}">${pf.const.language.RSC1777}</th>
					</tr>
				</thead>

				<tbody>
		`;

		for(row in data) {
			table += `
				<tr>
					<td class="text-truncate" title="${row}">
						${row}
					</td>
					<td class="text-truncate p-1">
						<span class="d-none textValue">${data[row]}</span>
						<div class="input-group input-group-sm">
							<input type="number" class="form-control inputWeightings d-inline-block" data-element="${element}" data-row="${row}" value="${data[row]}" title="${data[row]}" placeholder="" aria-label="" aria-describedby="basic-addon" min="0" max="100">
							<div class="input-group-append">
								<span id="basic-addon" class="input-group-text">%</span>
							</div>
						</div>
					</td>
				</tr>
			`;
		}

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

		switch(element) {
			case 'sec':
				$('#weightingsNSE').html(table);
				let table_nse = $('#table_' + element).DataTable({
					retrieve: true,
					language: self.language,
					paging: false,
					autoWidth: false,
					ordering: false,
					aaSorting: []
				});

				break;
			case 'edad':
				$('#weightingsAge').html(table);
				let table_age = $('#table_' + element).DataTable({
					retrieve: true,
					language: self.language,
					paging: false,
					autoWidth: false,
					ordering: false,
					aaSorting: []
				});

				break;
			case 'region':
				$('#weightingsRegion').html(table);
				let table_region = $('#table_' + element).DataTable({
					retrieve: true,
					language: self.language,
					paging: false,
					autoWidth: false,
					ordering: false,
					aaSorting: []
				});

				break;
			case 'genero':
				$('#weightingsGender').html(table);
				let table_gendr = $('#table_' + element).DataTable({
					retrieve: true,
					language: self.language,
					paging: false,
					autoWidth: false,
					ordering: false,
					aaSorting: []
				});

				break;
		}

		// Ocultar botones de tabla
		hideTableButtons('table_' + element);
	},

	updateCountries() {
		let self = this;

		// Comprobación de repeticiones en chats de bienvenida
		let chatsUserArray = [];
		let chatsUserCheck = false;
		for(let i = 0; i < self.chatsArray.length; i++) {
			if(chatsUserArray.indexOf(self.chatsArray[i].user) != -1) {
				chatsUserCheck = true;
			} else {
				chatsUserArray.push(self.chatsArray[i].user);
			}
		}

		if(chatsUserCheck) {
			let alertTitle = pf.const.language.RSC1515;
			let alertText = pf.const.language.RSC1558;
			pf.utils.showInfoDialog(alertTitle, alertText);
			return;
		}

		if(self.weightings) {
			let aHundredPercent = true;
			let totalCount = 0;
			for(element in self.weightings) {
				let count = 0;
				for(data in self.weightings[element]) {
					count += parseInt(self.weightings[element][data]);
				}

				totalCount += count;

				if(count !== 100) {
					aHundredPercent = false;
				}
			}

			if(!aHundredPercent && totalCount !== 0) {
				let warningTitle = pf.const.language.RSC549 + ' - ' + pf.const.language.RSC1776;
				let warningContent = pf.const.language.RSC1778;
				pf.utils.showInfoDialog(warningTitle, warningContent);
				return false;
			} else {
				self.weightings = JSON.stringify(self.weightings);
			}
		}

		let equivalencePoints = self.country.equivalencePoints;
		if($('#currencyPointsInput').val() !== '') {
			equivalencePoints = $('#currencyPointsInput').val();
		}

		let formatoFecha = '';
		if($('#ddmmaaaa').prop('checked')) {
			formatoFecha = 'DDMMAAAA';
		} else if($('#aaaammdd').prop('checked')) {
			formatoFecha = 'AAAAMMDD';
		}

		let parameters = {
			country: JSON.stringify(self.country),
			paymentFields: JSON.stringify(self.paymentFields),
			identificationArray: JSON.stringify(self.identificationArray),
			accountArray: JSON.stringify(self.accountArray),
			banksArray: JSON.stringify(self.banksArray),
			chatsNew: self.chatsNew,
			chatsChange: self.chatsChange,
			chatsAttached: self.chatsAttached,
			weightings: self.weightings,
			location: $('#locationCode').text(),
			equivalencePoints: equivalencePoints,
			sp_perfilacion: self.country.sp_perfilacion,
			chatsArray: JSON.stringify(self.chatsArray),
			formatoFecha: formatoFecha,
			poblacion: $('#population').val()
		};

		let size = self.attachmentsArray.length;
		for(let i = 0; i < size; i++) {
			parameters['element' + i] = self.attachmentsArray[i];
		}

		ajaxComunCallWithCallback('updatePaises', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let errorTitle = pf.const.language.RSC78;
				let errorContent = pf.const.language.RSC106;
				pf.utils.showInfoDialog(errorTitle, errorContent);
				window.location.href = '#!paises';
			}
		});
	},

	modalAlgoritmosPerfilacion() {
		let self = this;

		let table = `
			<table id="tableAlgoritmoPerfilacion" class="table table-hover tr-pointer tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1925}">${pf.const.language.RSC1925}</th>
					</tr>
				</thead>

				<thead class="filtersPA">
					<tr>
						<td>profilingAlgorithm</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.profilingAlgorithms.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr id="${i}" class="user_selected edit-group" data-id="${i}">
					<td class="text-truncate" title="${self.profilingAlgorithms[i].ROUTINE_NAME}">${(self.profilingAlgorithms[i].ROUTINE_NAME != '' ? self.profilingAlgorithms[i].ROUTINE_NAME : '-')}</td>
				</tr>
			`;
		}

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

		$('#modalProfilingAlgorithm-body').html(table);

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

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

		let dataTable = $('#tableAlgoritmoPerfilacion').DataTable({
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			aaSorting: []
		});

		// Como se genera al cargar la página y el modal está oculto, se utiliza el botón de mostrarlo con un intervalo para la animación de la aparición del modal para ajustar las columnas de la tabla
		let element = document.getElementById('modalProfilingAlgorithm');
		const observer = new MutationObserver(function(mutations) {
			mutations.forEach(function(mutation) {
				if(mutation.target.className.includes('show')) {
						setTimeout(function() {
							dataTable.columns.adjust();
						}, 200);
				}
			});
		});
		observer.observe(element, {attributes: true});

		// Apply the search
		applyTheSearch(dataTable, 'filtersPA');

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

		// Detectar click
		$('#modalProfilingAlgorithm-body tbody').off().on('click', 'tr', function() {
			let profAlgortihm = $(this).find('.text-truncate').text();
			$('#inputProfilingAlgorithm').val(profAlgortihm);
			$('#inputProfilingAlgorithm').attr('title', profAlgortihm);
			$('#closeProfilingAlgorithm').trigger('click');
		});
	},

	getAlgoritmosPerfilacionData() {
		let self = this;

		ajaxComunCallWithCallback('getSPSchemaCorporate', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.profilingAlgorithms = ajaxReturn.result;
				self.modalAlgoritmosPerfilacion();

				// Control de spinner
				self.loaders.getSPSchemaCorporate = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	exportExcel() {
		let self = this;

		let rsc = {
			nse: {
				title: [pf.const.language.RSC598],
				headers: [pf.const.language.RSC598, pf.const.language.RSC1777]
			},
			age: {
				title: [pf.const.language.RSC565],
				headers: [pf.const.language.RSC565, pf.const.language.RSC1777]
			},
			region: {
				title: [pf.const.language.RSC597],
				headers: [pf.const.language.RSC597, pf.const.language.RSC1777]
			},
			gender: {
				title: [pf.const.language.RSC151],
				headers: [pf.const.language.RSC151, pf.const.language.RSC1777]
			}
		}

		let data = {
			nse: [],
			age: [],
			region: [],
			gender: []
		};

		// NSE
		for(let nse in self.weightings.sec) {
			data.nse.push([nse, self.weightings.sec[nse]]);
		}

		// Age
		for(let age in self.weightings.edad) {
			data.age.push([age, self.weightings.edad[age]]);
		}

		// Region
		for(let region in self.weightings.region) {
			data.region.push([region, self.weightings.region[region]]);
		}

		// Gender
		for(let gender in self.weightings.genero) {
			data.gender.push([gender, self.weightings.genero[gender]]);
		}

		let parameters = {
			data: JSON.stringify(data),
			rsc: JSON.stringify(rsc)
		};
		ajaxComunCallWithCallback('exportPonderacionesByCountry', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				window.location = stcm.const.downloads + '/' + ajaxReturn.response;
				setTimeout(function() {
					self.deleteFiles(ajaxReturn.response);
				}, 1000 * 20);
			}
		});
	},

	deleteFiles(filename) {
		let parameters = {
			filename: filename
		};
		ajaxComunCallWithCallbackVoid('deleteFileExcel', parameters);
	}
};