// Pasar colores de RGB a Hexadecimal
function rgb2hex(colorval) {
	let parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

	delete (parts[0]);

	for(let i = 1; i <= 3; ++i) {
		parts[i] = parseInt(parts[i]).toString(16);

		if(parts[i].length == 1) {
			parts[i] = '0' + parts[i];
		}
	}

	return '#' + parts.join('');
}

// Pasar colores de Hexadecimal a RGB
function hex2rgb(hex) {
	if(hex.charAt(0) === '#') {
		hex = hex.substr(1);
	}

	if((hex.length < 2) || (hex.length > 6)) {
		return false;
	}

	let values = hex.split(''),
		r,
		g,
		b;

	if(hex.length === 2) {
		r = parseInt(values[0].toString() + values[1].toString(), 16);
		g = r;
		b = r;
	} else if(hex.length === 3) {
		r = parseInt(values[0].toString() + values[0].toString(), 16);
		g = parseInt(values[1].toString() + values[1].toString(), 16);
		b = parseInt(values[2].toString() + values[2].toString(), 16);
	} else if(hex.length === 6) {
		r = parseInt(values[0].toString() + values[1].toString(), 16);
		g = parseInt(values[2].toString() + values[3].toString(), 16);
		b = parseInt(values[4].toString() + values[5].toString(), 16);
	} else {
		return false;
	}

	return r + ', ' + g + ', ' + b;
}

// Generar rango de colores
function generateColors(colorStart, colorEnd, colorCount) {
	function hex(c) {
		let s = '0123456789abcdef';
		let i = parseInt(c);

		if(i == 0 || isNaN(c)) {
			return '00';
		}

		i = Math.round(Math.min(Math.max(0, i), 255));

		return s.charAt((i - i % 16) / 16) + s.charAt(i % 16);
	}

	/* Convert an RGB triplet to a hex string */
	function convertToHex(rgb) {
		return '#' + hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
	}

	/* Remove '#' in color hex string */
	function trim(s) {
		return (s.charAt(0) == '#') ? s.substring(1, 7) : s;
	}

	/* Convert a hex string to an RGB triplet */
	function convertToRGB(hex) {
		let color = [];

		color[0] = parseInt((trim(hex)).substring(0, 2), 16);
		color[1] = parseInt((trim(hex)).substring(2, 4), 16);
		color[2] = parseInt((trim(hex)).substring(4, 6), 16);

		return color;
	}

	function generateColor(colorStart, colorEnd, colorCount) {
		// The beginning of your gradient
		let start = convertToRGB(colorStart);

		// The end of your gradient
		let end = convertToRGB(colorEnd);

		// The number of colors to compute
		let len = colorCount;

		//Alpha blending amount
		let alpha = 0.0;

		let arrayColors = [];

		for(let i = 0; i < len; i++) {
			let c = [];
			alpha += (1.0 / len);

			c[0] = start[0] * alpha + (1 - alpha) * end[0];
			c[1] = start[1] * alpha + (1 - alpha) * end[1];
			c[2] = start[2] * alpha + (1 - alpha) * end[2];

			arrayColors.push(convertToHex(c));
		}

		return arrayColors;
	}

	let array = generateColor(colorStart, colorEnd, colorCount);

	return array;
}

// Array de colores de plataforma con respecto a cantidad de elementos
function arrayColors(colorsHex, totalColors) {
	let colors = [];
	let arraylColors = colors.length;

	while(arraylColors < totalColors) {
		for(let i = 0; i < colorsHex.length; i++) {
			colors.push(colorsHex[i]);
			arraylColors = colors.length;

			if(arraylColors == totalColors) {
				break;
			}
		}
	}

	return colors;
}

// Función para hacer saltos de lineas en los textos del eje X
function formatLabel(str, maxwidth) {
	let sections = [];

	if(typeof str === 'undefined' || str === null) {
		return sections;
	}

	let words = str.toString().split(' ');
	let temp = '';

	words.forEach(function(item, index) {
		if(temp.length > 0) {
			let concat = temp + ' ' + item;

			if(concat.length > maxwidth) {
				sections.push(temp);
				temp = '';
			} else {
				if(index == (words.length-1)) {
					sections.push(concat);
					return;
				} else {
					temp = concat;
					return;
				}
			}
		}

		if(index == (words.length-1)) {
			sections.push(item);
			return;
		}

		if(item.length < maxwidth) {
			temp = item;
		} else {
			sections.push(item);
		}
	});

	return sections;
}

const getidCPG = () => {
	const JSONuser = sessionStorage['STCMBackEnd:user'];
	const userAdmin = JSON.parse(JSONuser);

	return userAdmin.idCPG;
}

let menuCommunity = ['usuarios', 'usuarios/nuevo', 'usuarios/editar', 'usuarios_importar', 'roles', 'roles_new', 'roles_edit', 'editsegmentations', 'segmentaciones_new', 'segmentaciones_edit', 'segmentaciones_automatizadas', 'segmentaciones_automatizadas_new', 'segmentaciones_automatizadas_edit', 'grupos', 'grupos/nuevo', 'grupos/editar', 'difusion', 'difusion_new', 'difusion_edit'];
let menuNotifications = ['notificaciones', 'notificaciones/nueva', 'notificaciones/editar', 'notificaciones/consejeros', 'notificaciones_consejeros_telf', 'notificaciones_pre_consejeros', 'notificaciones_cola', 'pop_ups'];
let menuOperar = ['productos', 'proyectos', 'proyectos_new', 'proyectos_edit', 'proyectos_objectives', 'proyectos_validar', 'proyectos_videocall', 'expulsion', 'misiones', 'misiones_new', 'misiones_edit', 'misiones_type', 'misiones_type_new', 'misiones_type_edit', 'cumplimiento', 'misiones_cola', 'misiones_urls','generador_encuestas', 'rotaciones', 'rotaciones/nuevo', 'rotaciones/editar', 'templates'];
let menuAnalytics = ['asesores', 'word_cloud', 'conversaciones', 'catalogacion', 'licencias', 'perfilacionsinfinalizar', 'stores', 'muestreo', 'muestreo_dinamico', 'muestreodetallado', 'muestreodetallado_maz', 'muestreodetallado_maz_tabla', 'muestreodetallado_maz_seg', 'muestreodetallado_maz_seg_tabla', 'muestreocomparativo', 'cumplimientos', 'inversion', 'kpi_surveys', 'tiempo_respuesta','cdp', 'cubos', 'cubos_new', 'cubos_edit', 'cubos_execute', 'passiveTracking', 'muestreodetalladocomparativo', 'diferenciassignificativas', 'plantillas_reportes', 'plantillas_reportes_new', 'plantillas_reportes_edit'];
let menuMerchandising = ['pagos', 'pagos_archivo', 'pagos_detalle', 'pagos_automatizados', 'pagos_automatizados_new', 'pagos_automatizados_edit', 'articulos_catalogo', 'articulos_catalogo_new', 'articulos_catalogo_edit', 'catalogos', 'catalogos_new', 'catalogos_edit'];
let menuConsumo = ['show_all_items', 'items_new', 'items_edit', 'show_all_stores', 'stores_new', 'stores_edit', 'show_stores_type', 'stores_type_new', 'stores_type_edit'];
let menuExtension = ['html', 'html/nuevo', 'html/editar', 'addons', 'addons_new', 'addons_edit', 'voiceAssistant', 'voiceAssistant_new', 'voiceAssistant_edit', 'sinonimos', 'hashtag', 'hashtags_new', 'hashtags_edit'];
let menuMultitenant = ['tenant', 'tenant_new', 'tenant_edit', 'tenant_licenses'];
let menuCPG = ['cpg', 'cpg_new', 'cpg_edit', 'cpg_licenses'];
let menuCustomers = ['show_all_clients', 'customers_new', 'customers_edit'];
let menuAdminsBackend = ['administradores_backend', 'administradores_backend/nuevo', 'administradores_backend/editar', 'roles_backend', 'roles_backend_new', 'roles_backend_edit'];
let menuAjustes = ['welcometour', 'dominios_embebidos', 'dominios_embebidos_new', 'dominios_embebidos_edit', 'bots', 'bots_new', 'bots_edit', 'definicion_catalogacion_asesores', 'perfilacion', 'perfilacion_new', 'perfilacion_edit', 'formulario_registro', 'paises', 'paises_edit', 'idiomas', 'perfiles', 'perfiles_new', 'perfiles_edit', 'exclusiones_wordcloud', 'exclusiones_wordcloud_new', 'exclusiones_wordcloud_edit'];
let menuConfig = ['configuracion', 'funcionalidades_app', 'logs', 'rsc', 'rsc_new', 'rsc_edit', 'table_information'];
let menuClientsManagement = ['clientes'];

let navigationMenuArray = {
	backendshowcommunity: menuCommunity,
	backendshownotificaciones: menuNotifications,
	backendshowoperations: menuOperar,
	backendshowanalytics: menuAnalytics,
	backendshowrewards: menuMerchandising,
	backendshowConsumo: menuConsumo,
	backendshowintegraciones: menuExtension,
	backendshowtenants: menuMultitenant,
	backendshowcpg: menuCPG,
	backendshowclients: menuCustomers,
	backendshowadminsbackend: menuAdminsBackend,
	backendshowajustes: menuAjustes,
	backendshowconfiguracion: menuConfig,
	backendshowgestionclientes: menuClientsManagement
}

function selectOptionMenuByPage() {
	let pageActive = window.location.href.split('!')[1];
	let resultElem = '';

	Object.keys(navigationMenuArray).forEach(element => {
		navigationMenuArray[element].forEach(object => {
			if(object == pageActive) {
				resultElem = element;
				return;
			}
		});
	});

	$('.selectMenuElemSelected').removeClass('selectMenuElemSelected');
	$('.selectMenuElemSingleSelected').removeClass('selectMenuElemSingleSelected');

	if(resultElem != '') {
		$('#menuSectionsMini #' + resultElem + 'Mini .selectMenuElem, #menuSections #' + resultElem + ' .selectMenuElem').addClass('selectMenuElemSelected');

		let idParent = $('a[href="#!' + pageActive + '"]').closest('div').attr('id');
		let idParentSpan = $('a[href="#!' + pageActive + '"]').closest('span').attr('id');

		if(!$('a[href="#!' + pageActive + '"]').closest('div').hasClass('show')) {
			$('[href="#' + idParent + '"]').click();
		}

		if(!$('a[href="#!' + pageActive + '"]').closest('span').hasClass('show')) {
			$('[data-target="#' + idParentSpan + '"]').click();
		}

		let menuHeight = $('a[href="#!' + pageActive + '"]').height();

		if(menuHeight > 40) {
			menuHeight = $('a[href="#!' + pageActive + '"]').height();
		} else {
			menuHeight = 40;
		}

		$('a[href="#!' + pageActive + '"] > div').addClass('selectMenuElemSingleSelected');
		$('.selectMenuElemSingleSelected').height(menuHeight);
	}
}

function addEventArrowTableHeader() {
	// Para abarcar todo el título
	$('.section-title').parent().parent().off().on('click', function() {
		$(this).find('.arrow').trigger('click');
	});

	$('.arrow').off().on('click', function(event) {
		// Evitar la propagación
		event.stopPropagation();

		let arrow = $(this).data('arrow');
		let direction = '';

		if(arrow == 'left') {
			direction = stcmbackend.svg.chevronDown;
			$(this).data('arrow', 'down');
		} else {
			direction = stcmbackend.svg.chevronRight;
			$(this).data('arrow', 'left');
		}

		$(this).html(direction);

		if($(this).data('sub') == '1') {
			$(this).parent().next().collapse('toggle');
		} else if($(this).data('sub') == '2') {
			$(this).parent().parent().find('.collapse').collapse('toggle');
		} else {
			$(this).parent().parent().parent().find('.collapse').collapse('toggle');
		}
	});
}

// AJAX COMÚN CON CALLBACK
function ajaxComunCallWithCallback(serviceName, parameters, callback, loader = true) {
	let reqName = serviceName;
	let token = sessionStorage['STCMBackEnd:token'];
	let ajaxReturn = null;

	let form = new FormData();
	form.append('action', reqName);
	form.append('token', token);

	// Parámetros
	for(let key in parameters) {
		form.append(key, parameters[key]);
	}

	let reqData = {
		url: stcm.const.serverAPI,
		method: 'POST',
		timeout: stcm.const.AJAX_TIMEOUT,
		processData: false,
		mimeType: 'application/x-www-form-urlencoded',
		contentType: false,
		data: form
	};

	if(loader) {
		addLoader();
	}

	pf.ajax.request(reqName, reqData);
	$(document).off(reqName);
	$(document).on(reqName, function(event, response) {
		if(response.status === 'OK') {
			let resp = JSON.parse(response.resData.response);

			if(resp.status === 'OK') {
				ajaxReturn = resp;
			} else {
				if(resp.result == '##change##') {
					if(!init.refreshTime) {
						init.refreshTime = true;

						refreshTokenModal();
					}
				} else if(resp.result == 'Not authorized') {
					pf.ajax.setWindowLocationIndex();
				} else {
					let errorTitle = pf.const.language.RSC61;
					let errorContent = resp.result;
					pf.utils.showInfoDialog(errorTitle, errorContent);
				}

				removeLoader();
			}
		} else {
			if(response.result == 'Not authorized') {
				pf.ajax.setWindowLocationIndex();
			} else {
				let errorTitle = pf.const.language.RSC61;
				let errorContent = response.result;
				pf.utils.showInfoDialog(errorTitle, errorContent);
			}

			removeLoader();
		}

		if(loader) {
			removeLoader();
		}

		// Devolución de resultado
		callback(ajaxReturn);
	});
}

// AJAX COMÚN CON CALLBACK Y UNA SOLA COMPROBACIÓN
function ajaxComunCallWithCallbackOne(serviceName, parameters, callback, loader = true) {
	let reqName = serviceName;
	let token = sessionStorage['STCMBackEnd:token'];

	if(typeof(parameters['token']) !== 'undefined') {
		token = parameters['token'];
	}

	let ajaxReturn = null;

	let form = new FormData();
	form.append('action', reqName);
	form.append('token', token);

	// Parámetros
	for(let key in parameters) {
		if(key != 'token') {
			form.append(key, parameters[key]);
		}
	}

	let reqData = {
		url: stcm.const.serverAPI,
		method: 'POST',
		timeout: stcm.const.AJAX_TIMEOUT,
		processData: false,
		mimeType: 'application/x-www-form-urlencoded',
		contentType: false,
		data: form
	};

	if(loader) {
		addLoader();
	}

	pf.ajax.request(reqName, reqData);
	$(document).off(reqName);
	$(document).on(reqName, function(event, response) {
		if(response.status === 'OK') {
			ajaxReturn = response;
		} else {
			if(resp.result == '##change##') {
				if(!init.refreshTime) {
					init.refreshTime = true;

					refreshTokenModal();
				}
			} else if(response.result == 'Not authorized') {
				pf.ajax.setWindowLocationIndex();
			} else {
				let errorTitle = pf.const.language.RSC61;
				let errorContent = response.result;
				pf.utils.showInfoDialog(errorTitle, errorContent);
			}

			removeLoader();
		}

		if(loader) {
			removeLoader();
		}

		// Devolución de resultado
		callback(ajaxReturn);
	});
}

// CON CALLBACK SIMPLE
function ajaxComunCallWithCallbackVoid(serviceName, parameters, loader = true) {
	let reqName = serviceName;
	let token = sessionStorage['STCMBackEnd:token'];

	let form = new FormData();
	form.append('action', reqName);
	form.append('token', token);

	// Parámetros
	for(let key in parameters) {
		form.append(key, parameters[key]);
	}

	let reqData = {
		url: stcm.const.serverAPI,
		method: 'POST',
		timeout: stcm.const.AJAX_TIMEOUT,
		processData: false,
		mimeType: 'application/x-www-form-urlencoded',
		contentType: false,
		data: form
	};

	if(loader) {
		addLoader();
	}

	pf.ajax.request(reqName, reqData);
	$(document).off(reqName);
	$(document).on(reqName, function(event, response) {
		if(loader) {
			removeLoader();
		}
	});
}

// Control de spinner
function spinnerControl(loaders) {
	let allLoaders = false;

	for(let loader in loaders) {
		if(loaders[loader]) {
			allLoaders = true;
		} else {
			allLoaders = false;
			break;
		}
	}

	if(allLoaders) {
		removeLoader();
	}
}

// select 'Todos', 'Si', 'No'
function optionsSelectAllYesNo() {
	let options = `
		<select class="form-control form-control-sm">
			<option value="">${pf.const.language.RSC119}</option>
			<option value="${pf.const.language.RSC121}">${pf.const.language.RSC121}</option>
			<option value="${pf.const.language.RSC120}">${pf.const.language.RSC120}</option>
		</select>
	`;

	return options;
}

// DataTables excel customize, primera línea en negrita, alterno fondo gris
function dataTablesExcelCustomize(xlsx) {
	let sheet = xlsx.xl.worksheets['sheet1.xml'];

	$('row:first c', sheet).attr('s', '7');
	$('row:even c', sheet).attr('s', '5');
}

// Función para los filtros de las tablas
function applyTheSearch(dataTable, filter) {
	if (dataTable.columns().count() === 0) return false;
	dataTable.columns().eq(0).each(function(colIdx) {
		$('input', $('.' + filter + ' td')[colIdx]).on('keyup change', function() {
			dataTable
				.column(colIdx)
				.search(this.value)
				.draw();
			$(this).blur().focus();
		});
		$('select', $('.' + filter + ' td')[colIdx]).on('change', function() {
			dataTable
				.column(colIdx)
				.search(this.value)
				.draw();
			$(this).blur().focus();
		});
	});
}

// Restricciones de carácteres por tecla para input
function characterRestrictionsPerKey(value, warningTitle, warningContent, pattern = null) {
	//Tecla de retroceso para borrar, siempre la permite
	if(value == 8) {
		return true;
	}

	if(pattern === null) {
		pattern = stcm.const.overrideSpecialCharactersText;
	}

	let valueControl = String.fromCharCode(value);
	let valueFinal = pattern.test(valueControl);

	// Aviso
	if(valueFinal === false) {
		pf.utils.showInfoDialog(warningTitle, warningContent);
	}

	return valueFinal;
}

// Restricciones de carácteres por pegado para input
function characterRestrictionsPerPaste(element, warningTitle, warningContent, pattern = null) {
	if(pattern === null) {
		pattern = stcm.const.overrideSpecialCharacters;
	}

	setTimeout(function() {
		let value = element.val();
		let valueFinal = value.replace(pattern, '').trim();

		// Aviso
		if(value !== valueFinal) {
			pf.utils.showInfoDialog(warningTitle, warningContent);
		}

		element.val(valueFinal);
	}, 200);
}

// Modificar formato de fecha, cambia de DD/MM/AAAA a AAAA/MM/DD y viceversa
function modifyDateFormat(date) {
	let dateArray = date.split('/');
	let formattedDate = dateArray[2] + '/' + dateArray[1] + '/' + dateArray[0];

	return formattedDate;
}

// Pintar texto de label focus/blur
function changeLabelsColor() {
	$('.form-control').on('focus', function() {
		let id = $(this).attr('id');

		$('[for="' + id + '"]').css('color', '#0066ff');

		if($('#' + id).parent().hasClass('new-input-pass-style') || $('#' + id).parent().hasClass('new-input-others-style')) {
			if($('#' + id).parent().hasClass('group-invalid')) {
				$('#' + id).parent().addClass('parent-focus-invalid');
			} else {
				$('#' + id).parent().addClass('parent-focus');
			}
		}
	});
	$('.form-control').on('blur', function() {
		let id = $(this).attr('id');

		$('[for="' + id + '"]').css('color', '#212529');

		if($('#' + id).parent().hasClass('new-input-pass-style') || $('#' + id).parent().hasClass('new-input-others-style')) {
			$('#' + id).parent().removeClass('parent-focus');
			$('#' + id).parent().removeClass('parent-focus-invalid');
		}
	});
}

// Eventos del input global de selección para eliminar
function globalSelectionInputActions(idTable = '') {
	// Estado del input global con respecto a los inputs en página
	if($(idTable + '.deleteSelection').length == $(idTable + '.deleteSelection:checked').length && $(idTable + '.deleteSelection').length > 0) {
		$(idTable + '.globalSelection').prop('checked', true);
	} else {
		$(idTable + '.globalSelection').prop('checked', false);
	}

	// Evento del input global
	$(idTable + '.globalSelection').off().on('click', function() {
		if(this.checked) {
			$(idTable + '.deleteSelection').each(function() {
				if(!$(this).prop('checked')) {
					$(this).prop('checked', true);
					$(this).trigger('change');
				}
			});
		} else {
			$(idTable + '.deleteSelection').each(function() {
				if($(this).prop('checked')) {
					$(this).prop('checked', false);
					$(this).trigger('change');
				}
			});
		}
	});
}

// Eventos de los inputs individuales de selección para eliminar con respecto al input global y el botón de eliminar
function deleteSelectionInputActions(arrayDelMult) {
	if(arrayDelMult.length > 0) {
		$('#multSelecDelete').removeClass('d-none');
	} else {
		$('#multSelecDelete').addClass('d-none');
	}

	// Estado del input global con respecto a los inputs en página
	if($('.deleteSelection').length == $('.deleteSelection:checked').length && $('.deleteSelection').length > 0) {
		$('.globalSelection').prop('checked', true);
	} else {
		$('.globalSelection').prop('checked', false);
	}
}

// Eventos de dropdown de página
function dropDownPageEvents() {
	// Evitar que se cierre el menu de dropdown al hacer las selecciones de checks
	$('#profileContainerPage.dropdown-menu').on('click', function(e) {
		e.stopPropagation();
	});

	// Cambio de ángulo con el dropdown de filtro
	let profileContainerPage = document.getElementById('profileContainerPage');
	const observerPage = new MutationObserver(function(mutations) {
		mutations.forEach(function(mutation) {
			let angle = `
				<svg class="bi bi-chevron-down" width="12" height="12" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
					<path fill-rule="evenodd" d="M1.646 4.646a.5.5 0 01.708 0L8 10.293l5.646-5.647a.5.5 0 01.708.708l-6 6a.5.5 0 01-.708 0l-6-6a.5.5 0 010-.708z" clip-rule="evenodd"/>
				</svg>
			`;
			if(mutation.target.className.includes('show')) {
				angle = `
					<svg class="bi bi-chevron-up" width="12" height="12" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
						<path fill-rule="evenodd" d="M7.646 4.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1-.708.708L8 5.707l-5.646 5.647a.5.5 0 0 1-.708-.708l6-6z"/>
					</svg>
				`;
			}

			$('#svgContainerPage').html(angle);
		});
	});
	observerPage.observe(profileContainerPage, {attributes: true});
}

// Ocultar botones de tabla
function hideTableButtons(idTabla) {
	$('.dt-buttons').hide();
	$('.dataTables_filter').hide();
	$('#' + idTabla + '_length').hide();
}

// Limpiar modal general
function clearGeneralModal() {
	$('#headerModalTitle').text('');
	$('#divTableModal').html('');
	$('#divModalFooter').html('');
}

// Apariencia y comportamiento de los inputs tipo 'color'
function inputTypeColorEvents() {
	document.querySelectorAll(".colorSelectDiv").forEach(e=>e.addEventListener("focus", Focus));
	function Focus(event){
		$(this).css('height', '32px');
		$(this).parent().addClass('colorSelectDivContainerFocus');
		$(this).parent().parent().find('label').css('color', '#0066FF');
	}

	document.querySelectorAll(".colorSelectDiv").forEach(e=>e.addEventListener("blur", Blur));
	function Blur(event){
		$(this).css('height', '38px');
		$(this).parent().removeClass('colorSelectDivContainerFocus');
		$(this).parent().parent().find('label').css('color', '#383838');
	}

	// Cambios de color
	$('.colorSelectDiv').on('click', function() {
		let id = $(this).data('id');
		$('#' + id).trigger('click');
	});
	$('.colorSelectInput').on('change', function() {
		let color = $(this).val();
		let divId = $(this).attr('id') + 'Div';
		$('#' + divId).css('background-color', color);
	});
}

// Refrescar token
function refreshTokenModal() {
	let content = `
		<div class="form-group">
			<label for="userRefresh" class="fw-500">${pf.const.language.RSC806}</label>
			<input id="userRefresh" type="text" class="form-control" name="email">
		</div>

		<div class="form-group">
			<label for="passwordRefresh" class="fw-500">${pf.const.language.RSC71}</label>
			<input id="passwordRefresh" type="password" class="form-control" name="email">
		</div>

		<script>
			// Pintar texto de label
			changeLabelsColor();

			$('.jconfirm-open').on('keyup', function(e) {
				let code = (e.keyCode ? e.keyCode : e.which);
				if(code == 13) { //Enter keycode
					$('.new-style-accept').trigger('click');
				}
			});
		</script>
	`;

	let objInfo = {
		accept: {
			text: pf.const.language.RSC2635
		},
		cancel: {
			text: pf.const.language.RSC1854
		}
	};

	let alertTitle = pf.const.language.RSC2635;
	pf.utils.showInfoDialogCustomWidthAcceptCancelNewStyle(alertTitle, content, objInfo, '500px', function() {
		// Refrescar token
		let user = $('#userRefresh').val().trim();
		let password = $('#passwordRefresh').val().trim();

		if(user != '' && password != '') {
			let reqName = 'refreshToken';
			let form = new FormData();
			form.append('action', reqName);
			form.append('email', user);
			form.append('password', password);

			let reqData = {
				url: stcm.const.serverAPI,
				method: 'POST',
				timeout: stcm.const.AJAX_TIMEOUT,
				processData: false,
				mimeType: 'multipart/form-data',
				contentType: false,
				data: form
			};

			addLoader();
			pf.ajax.request(reqName, reqData);
			$(document).off(reqName);
			$(document).on(reqName, function(event, response) {
				if(response.status == 'OK') {
					let resp = response.resData.response;
					response = JSON.parse(resp);

					if(response.status == 'OK') {
						let resp = response.result;

						sessionStorage['STCMBackEnd:token'] = resp.token;
						init.refreshTime = false;
						window.location.reload();
					} else {
						let errorTitle = pf.const.language.RSC61;
						let errorContent = resp.result;
						pf.utils.showInfoDialog(errorTitle, errorContent);
					}
				} else {
					let errorTitle = pf.const.language.RSC61;
					let errorContent = resp.result;
					pf.utils.showInfoDialog(errorTitle, errorContent);
				}
			});
		} else {
			let alertTitle = pf.const.language.RSC2635;
			let alertText = pf.const.language.RSC101;
			pf.utils.showInfoDialog(alertTitle, alertText);
		}
	}, function() {
		// Salir
		pf.ajax.setWindowLocationIndex();
	});
}

// Mensaje de Notificaciones no activadas
function notifNotActi() {
	let textTitle = pf.const.language.RSC224;
	let textContent = pf.const.language.RSC2625;
	pf.utils.showInfoDialog(textTitle, textContent, pf.const.language.RSC141);
}