let ajax = null;

let browserLanguage = 'es';

function onLoad() {
	if(sessionStorage['STCMBackEnd:onlyAppZone'] == 0) {
		init.getAddons();
	}
	document.addEventListener('DOMContentLoaded', appStart(), false);

	// Botón para ir a la parte de arriba de la sección
	$('#scrollUp').off().on('click', function() {
		$('.app-content').animate({scrollTop: $('#wrapper').offset().top}, 500);
	});

	// Control para mostrar el botón de desplazamiento vertical
	$('.app-content').scroll(function() {
		let scrollTop = $('.app-content').scrollTop();
		if(scrollTop > 1) {
			$('#scrollUp').fadeIn(400);
			$('.nav-options').addClass('box-shadow-bottom');
		} else {
			$('#scrollUp').fadeOut(300);
			$('.nav-options').removeClass('box-shadow-bottom');
		}
	});
}

function loadHTML(url, id, controller) {
	if(url.indexOf('general/home.html') != -1) {
		removeBack();
	} else {
		addBack();
	}

	$('body').show();
	$.ajax({
		url: url,
		success() {},
		error() {}
	}).done(function(response) {
		$('#' + id).html(response);

		// Refresco de página de manera dinámica
		$('#refresh-section').off().on('click', function(e) {
			e.preventDefault();

			// Ocultar Gestión de comunidad si es necesario
			$('#communityManagement').hide();
			$('#subOptionsContainer').show();
			$('#wrapper').show();
			$('.main').css('height', '100vh');

			$('#commManagLink').data('state', 'off');
			let svgIcon = `
				<svg class="bi bi-chat-left-text ml-1 mb-1" width="16" height="16" fill="currentColor" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
					<path d="M14 1a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H4.414A2 2 0 0 0 3 11.586l-2 2V2a1 1 0 0 1 1-1h12zM2 0a2 2 0 0 0-2 2v12.793a.5.5 0 0 0 .854.353l2.853-2.853A1 1 0 0 1 4.414 12H14a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2z"/>
					<path d="M3 3.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zM3 6a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9A.5.5 0 0 1 3 6zm0 2.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5z"/>
				</svg>
			`;
			$('#commManagLink').html(svgIcon);

			// Recarga
			if(url !== 'inc/gestion_comunidad/gestion_comunidad.html') {
				loadHTML(url, 'wrapper', controller);
			}
		});

		$(window).scrollTop(0);
		controller.setEvents();
		selectOptionMenuByPage();
	});
}

function appStart() {
	//	routerStart();
}

//add loader
function addLoader() {
	//solo se añade si no esta el loader del step by step en survey
	if($('#surveyStepByStepLoader').length == 0) {
		$('body').append('<section id="wrapLoader" class="animated fadeIn loaderspinner"><div id="loader" class="color-loader"></i></section>');
	}
}

//removes loader
function removeLoader() {
	// Efecto de fade in en el loader
	$('body').find('#wrapLoader').addClass('bounceOut');
	setTimeout(function() {
		$('#wrapLoader').remove();
	}, 1000);
}

function removeAllLoaders() {
	$('.loaderspinner').remove();
}

function addBack() {
	// if($('header .go_home').length <= 0) {
		// $('header').prepend('<a href="#!home" class="go_home"><i class="la la-home"></i></a>');
	// }
}

function removeBack() {
	$('header .go_home').remove();
}

$(document).ready(function() {
	let url = window.location.href;

	// Anular los spinners cuando se cambie de página
	window.onhashchange = function() {
		$(".loaderspinner").remove();
	}

	// Entrada directa a chat
	let userAppGet = url.indexOf('?');
	let onlyChatGet = false;
	if(userAppGet != -1) {
		let res = url.substr(userAppGet + 1);
		if(res.length > 0) {
			let resArray = res.split('&');
			let tokenInit = '';

			if(resArray[0].indexOf('jwt=') == 0) {
				onlyChatGet = true;

				tokenInit = resArray[0].replace('jwt=', '');

				// Activar zona de solo app
				sessionStorage['STCMBackEnd:token'] = tokenInit;

				// Validar token GET
				let reqName = 'validateDirectToken';

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

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

				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') {
							let result = resp.result;

							sessionStorage['STCMBackEnd:user'] = '{"email":"' + result.appUserDetails[0].token + '"}';
							sessionStorage.removeItem('STCMBackEnd:config');

							// STCM COMMUNITY MANAGEMENT
							sessionStorage['STCMBackEnd:appUserDetails'] = JSON.stringify(result.appUserDetails[0]);

							// Idioma
							let language = '';
							if(result.lenguage != '') {
								language = result.lenguage.toUpperCase();
							} else {
								language = result.defaultLenguage.toUpperCase();
							}

							// Cambio unicamente para el idioma español
							if(language == 'SPA') {
								language = 'ESP';
							}

							sessionStorage['STCMBackEnd:lenguage'] = language;

							// Zona horaria
							sessionStorage['STCMBackEnd:timeZone'] = result.timezone;

							sessionStorage['STCMBackEnd:onlyAppZone'] = '1';

							// Control de chat directo
							let chat = '';
							if(resArray.length > 1 && resArray[1].indexOf('bid=') == 0) {
								chat = resArray[1].replace('bid=', '');
							}

							// Control de chat directo con contactos
							if(resArray.length > 2 && resArray[2].indexOf('shwc=') == 0) {
								let shwc = resArray[2].replace('shwc=', '');

								if(shwc == '1') {
									sessionStorage['STCMBackEnd:directChatDirWithContacts'] = '1';
								} else {
									sessionStorage['STCMBackEnd:directChatDirWithContacts'] = '0';
								}
							} else {
								sessionStorage['STCMBackEnd:directChatDirWithContacts'] = '0';
							}

							// Mostrar contactos
							// Comprobar si tiene ese contacto o no

							sessionStorage['STCMBackEnd:directChatDir'] = chat;

							window.location.href = 'app.html';
						} else {
							$('#homeScreen').css('display', 'none');
							$('#homeError').css('display', 'block');
						}
					} else {
						$('#homeScreen').css('display', 'none');
						$('#homeError').css('display', 'block');
					}
				});
			}
		}
	}

	// Imagen de error de servicio
	let serviceError = stcm.const.downloads + 'svg_new/panel_login_error_robot.svg';
	$('#homeErrorImgContainer img').attr('src', serviceError);

	if(!url.includes('app.html') && !onlyChatGet) {
		// Valores de plataforma preLogin
		let reqName = 'preLogin';

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

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

		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') {
					// Slogan
					$('#slogan').html(resp.result.slogan);

					// Colores
					document.documentElement.style.setProperty('--maincolor', resp.result.colorPrimario);
					document.documentElement.style.setProperty('--maincolorlighter', getTintedColor(resp.result.colorPrimario, 170));
					document.documentElement.style.setProperty('--maincolorlighter2', getTintedColorDetailed(resp.result.colorPrimario, 7, 46, 44));
					document.documentElement.style.setProperty('--secondcolor', resp.result.colorSecundario);
				}

				// Quitar la pantalla blanca
				$('#homeScreen').css('display', 'none');

				function getTintedColor(color, v) {
					if(color.length > 6) {
						color = color.substring(1,color.length);
					}
					var rgb = parseInt(color, 16);
					var r = Math.abs(((rgb >> 16) & 0xFF) + v);
					if(r > 255) {
						r = r - (r - 255);
					}
					var g = Math.abs(((rgb >> 8) & 0xFF) + v);
					if(g > 255) {
						g = g - (g - 255);
					}
					var b = Math.abs((rgb & 0xFF) + v);
					if(b > 255) {
						b = b - (b - 255);
					}
					r = Number(r < 0 || isNaN(r)) ? 0 : ((r > 255) ? 255 : r).toString(16);
					if(r.length == 1) {
						r = '0' + r;
					}
					g = Number(g < 0 || isNaN(g)) ? 0 : ((g > 255) ? 255 : g).toString(16);
					if(g.length == 1) {
						g = '0' + g;
					}
					b = Number(b < 0 || isNaN(b)) ? 0 : ((b > 255) ? 255 : b).toString(16);
					if(b.length == 1) {
						b = '0' + b;
					}
					return '#' + r + g + b;
				}

				function getTintedColorDetailed(color, red, green, blue) {
					if(color.length > 6) {
						color = color.substring(1, color.length);
					}

					let rgb = parseInt(color, 16);

					let r = Math.abs(((rgb >> 16) & 0xFF) + red);
					if(r > 255) {
						r = r - (r - 255);
					}
					let g = Math.abs(((rgb >> 8) & 0xFF) + green);
					if(g > 255) {
						g = g - (g - 255);
					}
					let b = Math.abs((rgb & 0xFF) + blue);
					if(b > 255) {
						b = b - (b - 255);
					}

					r = Number(r < 0 || isNaN(r)) ? 0 : ((r > 255) ? 255 : r).toString(16);
					if(r.length == 1) {
						r = '0' + r;
					}
					g = Number(g < 0 || isNaN(g)) ? 0 : ((g > 255) ? 255 : g).toString(16);
					if(g.length == 1) {
						g = '0' + g;
					}
					b = Number(b < 0 || isNaN(b)) ? 0 : ((b > 255) ? 255 : b).toString(16);
					if(b.length == 1) {
						b = '0' + b;
					}

					return '#' + r + g + b;
				}
			} else {
				$('#homeScreen').css('display', 'none');
				$('#homeError').css('display', 'block');
			}
		});
	}

	// Idioma del navegador
	let language = navigator.language.split('-')[0];

	if(language == 'en' || language == 'pt') {
		browserLanguage = language;
	}

	// Función para añadir los textos
	initialDictionaryFunction();

	let index = url.indexOf('?');
	if(index != -1) {
		let res = url.substr(index + 1);
		if(res.length > 0) {
			let resArray = res.split('&');

			let tokenInit = '';
			let idiomaInit = '';
			let emailInit = '';
			let size = resArray.length;
			for(let i = 0; i < size; i++) {
				if(resArray[i].indexOf('b=') == 0) {
					tokenInit = resArray[i].replace('b=', '');
				} else if(resArray[i].indexOf('d=') == 0) {
					idiomaInit = resArray[i].replace('d=', '');
				} else if(resArray[i].indexOf('f=') == 0) {
					emailInit = resArray[i].replace('f=', '');
				}
			}

			if(tokenInit !== '' && idiomaInit !== '' && emailInit !== '') {
				getLanguageResetPass(tokenInit, emailInit, idiomaInit);
			}
		}
	}

	$(document).on('click', '.back', function(e) {
		e.preventDefault();
		history.back();
	});
	/* Pablo Munuera 19/04/2023 */
	/* Añadida la función de mostrar contraseña a la pantalla de login */
	$('#btn-pass').mouseup(function() {
		$('#pass').attr('type', 'password');
	});
	$('#btn-pass').mousedown(function() {
		$('#pass').attr('type', 'text');
	});
	/* Pablo Munuera 27/04/2023 */

	if(url.includes('index.html')) {
		/* Añadida la función para cambiar la pantalla al seleccionar "Olvidé mi contraseña" */
		let enlace = document.getElementById("forgotPsw");

		// agregamos un escuchador de eventos
		enlace.addEventListener("click", function() {
			$.alert({
				boxWidth: '65%',
				title: `<h3 style="margin: 0 0 10px;">${initialDictionary.id005[browserLanguage]}</h3>`,
				content: `
					<p>${initialDictionary.id010[browserLanguage]}</p>
					<input id='mailForgot' type='email' placeholder='Example@gmail.com'></input>
				`,
				useBootstrap: false,
				bgOpacity: null,
				theme: 'new-style',
				buttons: {
					cancel: {
						text: initialDictionary.id011[browserLanguage], // Regresar by default
						btnClass: 'new-style-cancel',
						action() {}
					},
					accept: {
						text: initialDictionary.id012[browserLanguage], // Regresar by default
						btnClass: 'new-style-accept login-button',
						action() {
							var mail = $('.jconfirm-box input[type="email"]').val();
							$.alert({
								boxWidth: '65%',
								title: '',
								content: `
									<div class='img-container'>
										<img src='API/Downloads/newPasswordSent.svg'>
									</div>
									<h3 class='confirmedForgot'>${initialDictionary.id013[browserLanguage]} ${mail}</h3>
								`,
								useBootstrap: false,
								bgOpacity: null,
								theme: 'new-style',
								buttons: {
									accept: {
										text: initialDictionary.id014[browserLanguage], // Regresar by default
										btnClass: 'new-style-accept login-button',
									}
								}
							});
						}
					}
				}
			});
		});
	}

	$('#logInApp').submit(function(e) {
		e.preventDefault();

		let email = $('#logInApp #userName').val();
		let password = $('#logInApp input[type="password"]').val();

		if(email == '' && password == '') {
			// Cerrar alert previo si es el caso
			$('article .close').trigger('click');

			let errorTitle = initialDictionary.id008[browserLanguage];
			let errorContent = initialDictionary.id016[browserLanguage];

			pf.utils.showInfoDialog(errorTitle, errorContent, initialDictionary.id015[browserLanguage]);
			return false;
		} else if(email == '' || password == '') {
			// Cerrar alert previo si es el caso
			$('article .close').trigger('click');

			let errorTitle = initialDictionary.id008[browserLanguage];
			let errorContent = initialDictionary.id016[browserLanguage];

			pf.utils.showInfoDialog(errorTitle, errorContent, initialDictionary.id015[browserLanguage]);
			return false;
		}

		reqName = 'authenticate';

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

		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;

					// Comprobación de cambio de contraseña
					if(resp.mustResetPass != undefined) {
						let token = resp.token;

						let lenguageISO = '';
						if(resp.lenguage != '') {
							lenguageISO = resp.lenguage.toUpperCase();
						} else {
							lenguageISO = resp.defaultLenguage.toUpperCase();
						}

						// Cambio unicamente para el idioma español
						if(lenguageISO == 'SPA') {
							lenguageISO = 'ESP';
						}

						// Cargar rsc
						getLanguageResetPass(token, email, lenguageISO);
					} else if(resp.userType == 'Panel') {
						// Anular zona de solo app
						sessionStorage['STCMBackEnd:onlyAppZone'] = '0';

						// Usuario desactivado
						if(resp.enabled != '1') {
							let warningTitle = initialDictionary.id018[browserLanguage];
							let warningContent = initialDictionary.id023[browserLanguage];
							pf.utils.showInfoDialog(warningTitle, warningContent, initialDictionary.id015[browserLanguage]);
							removeLoader();

							return false;
						}

						// Todos los permisos de administrador
						sessionStorage['STCMBackEnd:administrator_permission'] = btoa(JSON.stringify(resp.roleAdminBackend[0]));

						// Usuario de aplicación del administrador
						sessionStorage['STCMBackEnd:adminAppUser'] = resp.appUser;

						// País e Idioma por defecto
						sessionStorage['STCMBackEnd:defaultCountry'] = resp.defaultCountry;
						sessionStorage['STCMBackEnd:defaultLenguage'] = resp.defaultLenguage;

						// Secciones permitidas
						let sectionsHTML = ``;
						sectionsHTML += resp.sectionsHTML;
						sessionStorage['STCMBackEnd:sectionsHTML'] = sectionsHTML;

						let sectionsHTMLMini = ``;
						sectionsHTMLMini += resp.sectionsHTMLMini;
						sessionStorage['STCMBackEnd:sectionsHTMLMini'] = sectionsHTMLMini;

						// Multitenant
						sessionStorage['STCMBackEnd:multiTenant'] = resp.multiTenant;

						// Administrador principal de CPG
						sessionStorage['STCMBackEnd:CPGAdmin'] = resp.mainAdminCPG;

						// Permisos de edición de segmentaciones
						sessionStorage['STCMBackEnd:editSegmentation'] = resp.roleAdminBackend[0].editsegmentations;

						// Permisos de alta de usuario
						sessionStorage['STCMBackEnd:addUsers'] = resp.roleAdminBackend[0].addUsers;

						// Control de versión
						sessionStorage['STCMBackEnd:versionCtrl'] = resp.versionCtrl;
						sessionStorage['STCMBackEnd:versionCtrlCompilacion'] = resp.versionCtrlCompilacion;

						sessionStorage['STCMBackEnd:token'] = resp.token;
						sessionStorage['STCMBackEnd:idTenant'] = resp.roleAdminBackend[0].idTenant;
						sessionStorage['STCMBackEnd:idCPG'] = resp.roleAdminBackend[0].idCPG;
						sessionStorage['STCMBackEnd:user'] = '{"email":"' + email + '"}';

						// Permiso de alta de misiones
						sessionStorage['STCMBackEnd:newMission'] = resp.roleAdminBackend[0].alta_misiones;

						// Permiso de edición de misiones
						sessionStorage['STCMBackEnd:editMission'] = resp.roleAdminBackend[0].edicion_misiones;

						// Permiso de borrado de misiones
						sessionStorage['STCMBackEnd:deleteMission'] = resp.roleAdminBackend[0].borrado_misiones;

						// Trabaja con clientes
						sessionStorage['STCMBackEnd:globalWorkingwithClients'] = resp.globalWorkingwithClients;

						// STCM COMMUNITY MANAGEMENT
						sessionStorage['STCMBackEnd:appUserDetails'] = JSON.stringify(resp.appUserDetails[0]);

						// Idioma
						let language = '';
						if(resp.lenguage != '') {
							language = resp.lenguage.toUpperCase();
						} else {
							language = resp.defaultLenguage.toUpperCase();
						}

						// Cambio únicamente para el idioma español
						if(language == 'SPA') {
							language = 'ESP';
						}

						sessionStorage['STCMBackEnd:lenguage'] = language;

						// Zona horaria
						sessionStorage['STCMBackEnd:timeZone'] = resp.timezone;

						window.location.href = 'app.html';
					} else if(resp.userType == 'App') {
						// Activar zona de solo app
						sessionStorage['STCMBackEnd:token'] = resp.token;
						sessionStorage['STCMBackEnd:user'] = '{"email":"' + email + '"}';
						sessionStorage.removeItem('STCMBackEnd:config');

						// STCM COMMUNITY MANAGEMENT
						sessionStorage['STCMBackEnd:appUserDetails'] = JSON.stringify(resp.appUserDetails[0]);

						// Idioma
						let language = '';
						if(resp.lenguage != '') {
							language = resp.lenguage.toUpperCase();
						} else {
							language = resp.defaultLenguage.toUpperCase();
						}

						// Cambio unicamente para el idioma español
						if(language == 'SPA') {
							language = 'ESP';
						}

						sessionStorage['STCMBackEnd:lenguage'] = language;

						// Zona horaria
						sessionStorage['STCMBackEnd:timeZone'] = resp.timezone;

						sessionStorage['STCMBackEnd:onlyAppZone'] = '1';
						window.location.href = 'app.html';
					} else {
						// Anular zona de solo app
						sessionStorage['STCMBackEnd:onlyAppZone'] = '0';

						// Cerrar alert previo si es el caso
						$('article .close').trigger('click');

						let errorTitle = initialDictionary.id024[browserLanguage];
						let errorContent = initialDictionary.id025[browserLanguage];
						pf.utils.showInfoDialog(errorTitle, errorContent, initialDictionary.id015[browserLanguage]);
					}
				} else {
					// Anular zona de solo app
					sessionStorage['STCMBackEnd:onlyAppZone'] = '0';

					// Cerrar alert previo si es el caso
					$('article .close').trigger('click');

					let errorTitle = initialDictionary.id008[browserLanguage];
					let errorContent = initialDictionary.id026[browserLanguage];
					pf.utils.showInfoDialog(errorTitle, errorContent, initialDictionary.id015[browserLanguage]);
				}
			} else {
				// Cerrar alert previo si es el caso
				$('article .close').trigger('click');

				let errorTitle = initialDictionary.id024[browserLanguage];
				let errorContent = initialDictionary.id025[browserLanguage];;
				pf.utils.showInfoDialog(errorTitle, errorContent, initialDictionary.id015[browserLanguage]);
			}
			removeLoader();
		});
	});

	function getLanguageResetPass(token, email, lenguage) {
		let parameters = {
			token: token,
			lenguage: lenguage,
			system: '1'
		};
		ajaxComunCallWithCallbackOne('getAllRSCByLenguage', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let resp = ajaxReturn.resData.response;
				response = JSON.parse(resp);

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

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

					let diccionario = '{';
					$.each(resp, function(ind, elem,) {
						diccionario += '"RSC' + elem.idRSC + '":"' + elem[lenguage] + '"';

						if(ind != (resp.length - 1)) {
							diccionario += ', ';
						}
					});

					diccionario += '}';
					pf.const.language = JSON.parse(diccionario);

					for(let i = 1; i <= 4000; i++) {
						let rsc = 'RSC' + i;
						if(!pf.const.language[rsc]) {
							pf.const.language[rsc] = rsc;
						}
					}

					let warningTitle = pf.const.language.RSC1616;
					let warningContent = pf.const.language.RSC1623;
					pf.utils.showInfoDialog(warningTitle, warningContent);

					let resetPassword = `
						<form>
							<div class="titleTextPsw">
								<h1 class="titleChange">${pf.const.language.RSC2610}</h1>
								<h2 class="changeText">${pf.const.language.RSC1623}</h2>
							</div>

							<div class="logInInputsPsw">
								<label style="padding-bottom: 26px;">
									<p style="font-size: 14px; font-weight: bold;">${pf.const.language.RSC288}</p>
									<div class="input-wrapper">
										<input id="pass1" type="password" placeholder="${pf.const.language.RSC288}">
										<i id="btn-pass1" class="bi bi-eye c-pointer"></i>
									</div>
								</label>

								<label style="padding-top: 0; padding-bottom: 0;">
									<p style="font-size: 16px; font-weight: bold;">${pf.const.language.RSC2611}</p>
									<div class="input-wrapper">
										<input id="pass2" type="password" placeholder="${pf.const.language.RSC289}">
										<i id="btn-pass2" class="bi bi-eye c-pointer"></i>
									</div>
								</label>
							</div>

							<div class="buttonDivPsw">
								<button id="changePassword" type="submit" class="login-button">${pf.const.language.RSC287}</button>

								<a href="#" class="terms">${pf.const.language.RSC222}</a>
							</div>
						</form>
					`;

					$('#logContainer').html(resetPassword);

					$('#btn-pass1').mouseup(function() {
						$('#pass1').attr('type', 'password');
					});
					$('#btn-pass1').mousedown(function() {
						$('#pass1').attr('type', 'text');
					});

					$('#btn-pass2').mouseup(function() {
						$('#pass2').attr('type', 'password');
					});
					$('#btn-pass2').mousedown(function() {
						$('#pass2').attr('type', 'text');
					});

					$('#changePassword').click(function() {
						changePassword(token, email);
					});
				} else {
					pf.const.language = {};
				}
			}
		}, false);
	}

	function changePassword(token, email) {
		let pass1 = $('#pass1').val().trim();
		let pass2 = $('#pass2').val().trim();

		if(pass1 == pass2 && pass1 != '') {
			let parameters = {
				token: token,
				email: email,
				passwordAPI: pass1
			};
			ajaxComunCallWithCallbackOne('resetPasswordAPIUser', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					$.alert({
						boxWidth: '65%',
						title: '',
						content: `
							<div class='img-container'>
								<img src='API/Downloads/passwordReestored.svg'>
							</div>
							<h3 class='confirmedForgot'>${initialDictionary.id020[browserLanguage]}</h3>
						`,
						useBootstrap: false,
						bgOpacity: null,
						theme: 'new-style',
						buttons: {
							accept: {
								text: initialDictionary.id014[browserLanguage], // Regresar by default
								btnClass: 'new-style-accept login-button',
								action(){
									let url = window.location.href;
									let index = url.indexOf('?');
									let urlSimple = url.substr(0, index);
									window.location.href = urlSimple;
								}
							}
						}
					});
				} else {
					let alertTitle = pf.const.language.RSC287;
					let alertText = pf.const.language.RSC290;
					let alertBtn = initialDictionary.id014[browserLanguage];
					pf.utils.showInfoDialog(alertTitle, alertText, alertBtn);
				}
			});
		} else {
			let alertTitle = pf.const.language.RSC287;
			let alertText = pf.const.language.RSC290;
			let alertBtn = initialDictionary.id014[browserLanguage];
			pf.utils.showInfoDialog(alertTitle, alertText, alertBtn);
		}
	}

	if(/Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) == true) {
		$('html').addClass('mobile');
	}

	$('#wrapper').bind('DOMNodeRemoved', function(e) {
		var elementID = $(e.target).attr('id');
		//removeBack();
	});

	// Esconder menu
	$('#hidden-menu').click(function() {
		if($('.navigation-menu').width() > 60) {
			hideMenu();
		} else {
			showMenu();
		}
	});

	$('#closeNav').on('click', function() {
		$('#hidden-menu').trigger('click');
	});
});

// Diccionario inicial
let initialDictionary = {
	id001: {
		es: 'Bienvenido,',
		en: 'Welcome,',
		pt: 'Bem-vindo,'
	},
	id002: {
		es: 'ingresa tus credenciales para poder acceder',
		en: 'enter your credentials to access',
		pt: 'insira suas credenciais para acessar'
	},
	id003: {
		es: 'Correo electrónico',
		en: 'Email',
		pt: 'Correio eletrônico'
	},
	id004: {
		es: 'Contraseña',
		en: 'Password',
		pt: 'Senha'
	},
	id005: {
		es: 'Olvidé mi contraseña',
		en: 'I forgot my password',
		pt: 'Esqueci minha senha'
	},
	id006: {
		es: 'Acceder',
		en: 'To access',
		pt: 'Acessar'
	},
	id007: {
		es: 'Términos y condiciones',
		en: 'Terms and Conditions',
		pt: 'Termos e Condições'
	},
	id008: {
		es: 'Credenciales incorrectas',
		en: 'Incorrect credentials',
		pt: 'Credenciais incorretas'
	},
	id009: {
		es: 'Las credenciales introducidas no son válidas. Por favor, revise los campos e inténtelo de nuevo.',
		en: 'The credentials entered are not valid. Please check the fields and try again.',
		pt: 'As credenciais inseridas não são válidas. Verifique os campos e tente novamente.'
	},
	id010: {
		es: 'Ingresa tu email, se enviará un correo con un link para cambiar la contraseña',
		en: 'Enter your email, an email will be sent with a link to change the password',
		pt: 'Digite seu e-mail, um e-mail será enviado com um link para alterar a senha'
	},
	id011: {
		es: 'Cancelar',
		en: 'Cancel',
		pt: 'Cancelar'
	},
	id012: {
		es: 'Enviar',
		en: 'Send',
		pt: 'Enviar'
	},
	id013: {
		es: 'Se ha enviado un correo al email',
		en: 'An email has been sent to the email',
		pt: 'Um e-mail foi enviado para o e-mail'
	},
	id014: {
		es: 'Aceptar',
		en: 'Accept',
		pt: 'Aceitar'
	},
	id015: {
		es: 'De acuerdo',
		en: 'Agreed',
		pt: 'De acordo'
	},
	id016: {
		es: 'Complete ambos campos para poder acceder',
		en: 'Complete both fields to gain access',
		pt: 'Preencha os dois campos para obter acesso'
	},
	id017: {
		es: 'Se debe introducir un correo eléctronico válido.',
		en: 'A valid email must be entered.',
		pt: 'Um e-mail válido deve ser inserido.'
	},
	id018: {
		es: 'Usuario desactivado',
		en: 'Deactivated user',
		pt: 'Usuário desativado'
	},
	id019: {
		es: 'Se ha producido un problema',
		en: 'A problem has occurred',
		pt: 'Ocorreu um problema'
	},
	id020: {
		es: 'Contraseña reestablecida con éxito',
		en: 'Password reset successfully',
		pt: 'Senha redefinida com sucesso'
	},
	id021: {
		es: 'Ingresa aquí tu correo electrónico',
		en: 'Enter your email here',
		pt: 'Digite seu email aqui'
	},
	id022: {
		es: 'Ingresa aquí tu contraseña',
		en: 'Enter your password here',
		pt: 'Digite sua senha aqui'
	},
	id023: {
		es: 'Este usuario ha sido dado de baja de la plataforma, contacte con su administrador',
		en: 'This user has been removed from the platform, contact your administrator',
		pt: 'Este usuário foi removido da plataforma, entre em contato com seu administrador'
	},
	id024: {
		es: 'Se ha producido un error',
		en: 'An error has occurred',
		pt: 'Ocorreu um erro'
	},
	id025: {
		es: 'Vuelva a intentarlo en unos minutos o pongase en contacto con su administrador',
		en: 'Please try again in a few minutes or contact your administrator',
		pt: 'Tente novamente em alguns minutos ou entre em contato com seu administrador'
	},
	id026: {
		es: 'Compruebe que las credenciales introducidas son correctas',
		en: 'Check that the credentials entered are correct',
		pt: 'Verifique se as credenciais inseridas estão corretas'
	},
	id027: {
		es: '¡Oh! Parece que algo salió mal',
		en: 'Oh! It seems something went wrong',
		pt: 'Oh! Parece que algo deu errado'
	},
	id028: {
		es: 'Recargue la página o intentelo en unos minutos',
		en: 'Reload the page or try again in a few minutes',
		pt: 'Atualize a página ou tente novamente em alguns minutos'
	}
}

function initialDictionaryFunction() {
	let elements = $('[initDic]');

	elements.each(function() {
		let id = $(this).attr('initDic');
		$(this).text(initialDictionary[id][browserLanguage]);
	});

	let placeHolder = $('[placeholder]');
	placeHolder.each(function() {
		let id = $(this).attr('placeholder');

		if(id.includes('id')) {
			$(this).attr('placeholder', initialDictionary[id][browserLanguage]);
		}
	});
}