if(window.auth={remexAuth:null,env:document.querySelector('meta[name="app-env"]').content,analyticSent:{},defaultProfilePicture:"https://remesita.s3.amazonaws.com/cdn/blank-profile-picture.jpg",inizialized:!1,uiRendererd:!1,usingFirebase:"undefined"!=typeof firebase,authMethod:null,fingerprint:null,authFormCssSelector:"#remex-auth-container",locale:(window.currentLocale??navigator.language??navigator.userLanguage).split("-")[0].toLowerCase(),translate:{es:{"Double safety factor verification failed.":"La verificación de doble factor de seguridad ha fallado.","A double safety factor verification is required.":"Se requiere una verificación de doble factor de seguridad."},en:{"Código de verificación":"Verification Code","Verificación de seguridad con código TOTP":"Verificación de seguridad con código TOTP", "Por tu seguridad, es necesario que hagamos una verificación. Por favor usa un código temporal generado en tu aplicación de autenticación.":"For your security, it is necessary that we do a verification. Please use a temporary code generated in your authentication application.","¿Deseas configurarlo ahora?":"Would you like to configure it now?","Tu sesión de usuario se a cambiado, debes recargar la página":"Your user session has been changed, you must reload the page","¿Te gustaría marcar este navegador como un dispositivo de confianza?":"Would you like to mark this browser as a trusted device?","Digita tu celular":"Type your cell phone","Tu sesión de usuario se ha desconectado":"Your user session has been disconnected","Tu sesión de usuario se ha desconectado porque hemos actualizado la plataforma y necesitas recargar la página":"Your user session has been disconnected because we have updated the platform and you need to reload the page","Nueva actualización!":"New update!", "Hemos actualizado la plataforma y necesitas recargar la página":"We have updated the platform and you need to reload the page","Tu cuenta se encuentra suspendida de forma indefinida":"Your account is suspended indefinitely","Tu cuenta se encuentra deshabilitada":"Your account is disabled","Tu cuenta se encuentra cerrada de forma definitiva":"Your account is closed permanently","ENVIAR CÓDIGO":"SEND CODE","Digita el código recibido":"Type the received code","Prefiero recibir el código via Telegram":"I prefer to receive the code via Telegram","Prefiero recibir el código via Whatsapp":"I prefer to receive the code via Whatsapp",VERIFICAR:"VERIFY",SIGUIENTE:"NEXT","Revisa tu bandeja de entrada o spam":"Check your inbox or spam","Iniciar sesión con el celular":"Log in with your mobile",ESPERE:"WAITING","Debe escribir un celular válido":"You must write a valid cell phone",REENVIAR:"RESEND", "Te enviaremos un código de seguridad para verificar tu identidad":"We will send you a security code to verify your identity","El código es incorrecto o ha caducado":"The code is incorrect or expired","Lo sentimos, has superado el máximo de intentos":"Sorry, you have exceeded the maximum attempts","Espere 30 min para volverlo a intentar":"Wait 30 min to try again","Completa tu registro de usuario":"Complete your user registration","Nombre y Apellidos":"Name and surname","Tal como aparece en tu documento de identidad":"As it appears on your identity document","Correo electrónico":"Email","También te enviaremos un código para verificar tu correo":"We will also send you a code to verify your email","Este correo electrónico ya esta en uso":"This email already in use","Lo sentimos, ha ocurrido un error inesperado":"Sorry, an unexpected error has occurred","Lo sentimos!":"Sorry!","Inténtalo luego":"try again later", "Podrás reenviar el código en __DURATION__":"You will be able to resend the code in __DURATION__","Reenviar código":"Resend code","Teléfono celular":"Celular number","Identifícate con tu teléfono celular":"Sign in with your cell phone",CANCELAR:"CANCEL",DESCONECTAR:"LOGOUT","Email not found in our system":"Email not found in our system","Phone not found in our system":"Phone not found in our system","Sorry we have a problem, please reload web page, and try again":"Sorry we have a problem, please reload web page, and try again",Desconectando:"Disconnecting","Estás conectado como":"You are logged in as","Revisa y completa tu información":"Review and complete your information","Usuario desconocido":"Unknown user","Estas usando tu cuenta de Google":"You are using your Google account","Estas usando tu cuenta de Facebook":"You are using your Facebook account","Tu cuenta se encuentra suspendida de forma indefinida":"Your account is suspended indefinitely", "Tu cuenta se encuentra deshabilitada":"Your account is disabled","Tu cuenta se encuentra cerrada de forma definitiva":"Your account is closed permanently"}},towfactorCount:0,verifyIntent:0,i18n:e=>window.auth.translate[window.auth.locale][e]??e,init:async()=>{const e=async()=>{window.auth.remexAuth=new window.RemexAuthComponentClass({i18n:{es:{"User was disabled":"Cuenta de usuario deshabilitado","Your user account has been closed":"Tu cuenta de usuario ha sido cerrada","Reset Now":"Reiniciar Ahora","If you have accidentally uninstalled the authenticator app that generates the TOTP codes or you have lost your phone, you can disable the TOTP second-factor layer of security by resetting a new password.":"Si has desinstalado accidentalmente la aplicación de autenticación que genera los códigos TOTP o has perdido tu teléfono, puedes desactivar la capa de seguridad de doble factor TOTP restableciendo una nueva contraseña.", "What can I do if I have lost my TOTP?":"¿Qué puedo hacer si he perdido mi TOTP?","Invalid code":"Código inválido",Accept:"Aceptar",Deny:"Denegar","Disable TOTP layer.":"Desactivar seguridad de doble factor TOTP.","Customer ID":"ID de Cliente","This device is trusted":"Este dispositivo es confiable","This is not a reliable device?":"¿Este no es un dispositivo confiable?","Device is not trust, session disconnected by security":"Dispositivo no confiable, sesión desconectada por seguridad","Invalid Signature, session disconnected by security":"Firma inválida, sesión desconectada por seguridad","Now you can log back in with your new password.":"Ahora puedes iniciar sesión con tu nueva contraseña.","Password set successfully":"Contraseña establecida con éxito","User is not enabled or closed":"Usuario no habilitado o cuenta cerrada","Token was created from another device. Session disconnected by security":"El Token fue creado desde otro dispositivo. Sesión desconectada por seguridad", "Application updated, force reload required":"Aplicación actualizada, se requiere recarga forzada","Enter Password":"Introduce tu Contraseña",Authentication:"Autentícate","Password secirity _VALUE_ %":"Seguridad de la contraseña _VALUE_ %","Use minnimum 8 characters, uppercase, lowercase, numbers and special characters":"Usa mínimo 8 caracteres, mayúsculas, minúsculas, números y caracteres especiales",Cancel:"Cancelar","Invalid verification code. Please try again.":"Código de verificación inválido. Por favor inténtalo de nuevo.","Verify Your Email":"Verifica tu Correo Electrónico","Please enter the 6-digit code sent to your email.":"Por favor introduce el código de 6 dígitos enviado a tu correo electrónico.","Please login to your account.":"Por favor inicie sesión en su cuenta.",Email:"Correo Electrónico",Password:"Contraseña","Remember Me":"Recuérdame", "We will send you a verification code to your email and after validating that it is yours we will let you change the password.":"Te enviaremos un código de verificación a tu correo electrónico y después de validar que es tuyo te dejaremos estbalecer una nueva contraseña.",Login:"Iniciar Sesión","Sign in with Google":"Iniciar sesión con Google","Don't have an account yet?":"¿Aún no tienes una cuenta?","Sign Up":"Regístrate","You are logged in as":"Has iniciado sesión como",Register:"Crear una cuenta","Already have an account?":"¿Ya tienes una cuenta?","Forgot Password":"Crear nueva Contraseña","Back to Login":"Volver a Iniciar Sesión","Verify TOTP":"Verificar TOTP","Verify by TOTP code":"Verificar por medio de código TOTP","For security reasons, two-factor OTP verification is required with a code generated in your authenticator app.":"Por razones de seguridad, se requiere la verificación OTP de dos factores con un código generado en su aplicación de autenticación.", "Generate a temporary code from your authentication application to secure access to your account.":"Genera un código temporal desde tu aplicación de autenticación para asegurar el acceso a tu cuenta.","Enter TOTP Code":"Introduce el código TOTP","Update Profile":"Actualizar Perfil","Profile data":"Datos de Perfil",Fullname:"Nombre Completo",Update:"Actualizar",Male:"Masculino",Continue:"Continuar",Female:"Femenino",Gender:"Género","Select Country":"Seleccionar País",Country:"País de Residencia","Recovery Password":"Crear nueva Contraseña",Connecting:"Conectando","Your access password":"Tu contraseña de acceso","Are you new here?":"¿Eres nuevo por aquí?","Frequent Countries":"Paises más frecuentes","All Countries":"Todos los paises","Verify Your Email before set new passowrd":"Verifica tu correo electrónico antes de establecer una nueva contraseña","Complete your registration":"Completa tu registro", "Invalid credentials. Please try again.":"Credenciales inválidas. Por favor inténtalo de nuevo.","There is no user in our system with this email":"No hay usuario en nuestro sistema con este correo","New Password":"Nueva Contraseña","User is disconnected":"Usuario desconectado","Your new access password":"Tu nueva contraseña de acceso","Set password":"Establecer contraseña","Repeat password":"Repetir contraseña",Verify:"Verificar","Phone number":"Número de celular","Comeback to Login":"Volver al Inicio","Verify Your Celular before login":"Verifica tu celular antes de iniciar sesión","Please enter the 6-digit code sent to your phone.":"Por favor introduce el código de 6 dígitos enviado a tu celular.","Verify Your Celular before set new passowrd":"Verifica tu celular antes de establecer una nueva contraseña","Please enter the 6-digit code sent to your phone.":"Por favor introduce el código de 6 dígitos enviado a tu celular.",Logout:"Cerrar Sesión", "In a few steps you will be registered.":"En pocos pasos te habrás dado de alta.","User not found with this phone":"Usuario no encontrado con este número de celular","User not found with this email":"Usuario no encontrado con este correo","User registration successful":"Registro de usuario exitoso","Password must contain at least one uppercase letter.":"La contraseña debe contener al menos una letra mayúscula.","Password must be at least _minLength_ characters long.":"La contraseña debe tener al menos _minLength_ caracteres.","Password must not contain more than two consecutive identical numbers.":"La contraseña no debe contener más de dos números seguidos.","Congratulations _NAME_!, you are now a registered user and you can access safely with your email and password.":"Felicidades _NAME_!, ya eres un usuario registrado y puedes acceder de forma segura con tu correo y contraseña.", "Phone already registered or in use bad account wsa desactivated":"Teléfono ya registrado o en uso mala cuenta fue desactivada","This is not a trusted device, your session will be disconnected in 30 minutes":"Este no es un dispositivo confiable, tu sesión se desconectará en 30 minutos"}},providers:{email:!0,sms:!1},popularCountries:["cu","us","mx","ec"],endpoint:`https://${"dev"==window.auth.env?"dev.":""}remesita.com`,defaultLanguage:window.auth.locale}),window.auth.remexAuth.addEventListener("RemexAuthLogout",(e=>{$("#remex-auth-container").removeClass("pt-5"),$("#user-explain-loading").remove(),window.dispatchEvent(new CustomEvent("sessionDestroyed",{bubbles:!0})),$("#login-explain").show(),$("body").removeClass("logged")})),window.auth.remexAuth.addEventListener("RemexAuthRendered",(e=>{$("body").removeClass("logged"),window.dispatchEvent(new CustomEvent("afterAuthFormRender",{}))})),window.auth.remexAuth.addEventListener("RemexAuthReConnected",(e=>{ window.auth.user&&window.auth.user.email==e.detail.email&&($("body").addClass("logged"),$("#login-explain").hide(),window.dispatchEvent(new CustomEvent("sessionRefreshed",{bubbles:!0,detail:window.auth.user})))})),window.auth.remexAuth.addEventListener("RemexAuthConnected",(async e=>{$("#form-loading").remove(),$("#remex-auth-container").addClass("pt-5"),$("body").addClass("logged"),window.auth.user=e.detail,window.dispatchEvent(new CustomEvent("sessionCreating",{bubbles:!0,detail:window.auth.user})),$("#login-explain").hide(),$("#user-explain-loading").remove(), $("#rightinfo").append('
\n
\n
\n
\n
\n
\n
');const t=await window.auth.remexAuth.getUserData(),o={token:$("script[lockuptoken]").attr("lockuptoken"),phone:t.phone,email:t.email,autoAuth:!0,fingerprint:window.auth.remexAuth.fingerprint,dim:$(window).width()+"x"+$(window).height()};JSON.stringify(o),$.ajax({type:"POST",url:window.location.origin+"/customer/discovery", dataType:"json",data:o,success:e=>{if(e.locked||e.disabled||e.closed){const t=window.auth.i18n(e.locked?window.auth.i18n("Tu cuenta se encuentra suspendida de forma indefinida"):e.disabled?window.auth.i18n("Tu cuenta se encuentra deshabilitada"):window.auth.i18n("Tu cuenta se encuentra cerrada de forma definitiva"));return window.dispatchEvent(new CustomEvent("sessionError",{bubbles:!0,detail:t})),window.auth.user=null,reject(t),window.auth.logout().then((()=>window.alertModal(window.auth.i18n("Lo sentimos!"),t,void 0,"lock","OK")??void 0)),!1}{const t=e;window.auth.user=t,window.localStorage.setItem("rmses",btoa(JSON.stringify(window.auth.user))),window.dispatchEvent(new CustomEvent("sessionCreated",{bubbles:!0,detail:window.auth.user})),window.auth.renderSessionInfo(),window.dispatchEvent(new CustomEvent("sessionRefreshed",{bubbles:!0,detail:window.auth.user}))}}})})),window.auth.remexAuth.addEventListener("RemexAuthFingerprint",(async e=>{window.auth.env, window.auth.fingerprint=e.detail.id,window.auth.deviceLabel=e.detail.label})),window.auth.remexAuth.addEventListener("RemexAuthInitialized",(async e=>{window.auth.env,window.auth.inizialized=!0,$(`${window.auth.authFormCssSelector}`).length&&await window.auth.renderAuthForm(),window.auth.env}))};if(!window.RemexAuthComponentLoading)if(customElements.get("remex-auth"))await e();else{window.RemexAuthComponentLoading=!0;let o=document.querySelector('meta[name="x-cpl"]')?.getAttribute("content")||"1.0.0";var t=document.createElement("script");t.src=`/cdn/${o}/microfronts/authenticator/index.min.js`,t.async=!0,t.onload=async()=>{window.dispatchEvent(new CustomEvent("RemexAuthComponentLoaded",{})),window.RemexAuthComponentLoading=!1,await e()},document.head.appendChild(t)}},renderAuthForm:async e=>{if(!$(window.auth.authFormCssSelector).length||window.auth.uiRendererd)return;const t=setInterval((()=>{ !window.auth.inizialized||window.auth.remexAuth.rendered||window.auth.uiRendererd||(clearInterval(t),$(window.auth.authSessionInfoCssSelector).hide(),$(window.auth.authFormCssSelector).fadeIn(),window.dispatchEvent(new CustomEvent("beforeAuthFormRender",{})),window.auth.uiRenderer=!0,document.querySelector(window.auth.authFormCssSelector).appendChild(window.auth.remexAuth),e&&window.auth.remexAuth.addEventListener("RemexAuthLogged",(()=>{e()})))}),100)},windowIsFocused:!0,isConnected:()=>(window.auth.sowToken(),window.auth.remexAuth&&window.auth.remexAuth.isConnected()),checkUserIsLogged:async()=>{let e=!1;if(null!=window.localStorage.getItem("rmses"))try{const t=JSON.parse(atob(window.localStorage.getItem("rmses")));null!=t&&(await window.auth.setUserInSession(t),e=!0)}catch(e){}window.auth.user?await window.auth.setUserInSession(window.auth.user):await window.auth.renderAuthForm()},user:null,setUserInSession:async e=>{if(window.auth.user={id:e?.id??null, fullName:e?.fullName??e?.displayName??e?.name??"",photoURL:e?.photoURL??window.auth.defaultProfilePicture,email:e?.email??(e?.providerData?e?.providerData.email??e?.providerData[0].email??null:null),phone:e?.phone??e?.phoneNumber??null,firebaseId:e?.firebaseId??e?.uid??null,facebookId:e?.facebookId??(!e?.providerData||"facebook.com"!=e?.providerData.providerId&&"facebook.com"!=e?.providerData[0].providerId?null:e?.providerData.uid||e?.providerData[0].uid),authMethod:window.authMethod??(e?.providerData?e?.providerData.providerId??e?.providerData[0].providerId??"email":"email").replace(".com",""),commissions:e?.commissions??null,balance:e?.balance??null,dateOfBirth:e?.dateOfBirth??null,identificationNumber:e?.identificationNumber??null,address:e?.address??null,countReferralsN1:e?.countReferralsN1??"?",countReferralsN2:e?.countReferralsN2??"?",countReferralsN3:e?.countReferralsN3??"?",countRecipients:e?.countRecipients??null,countOrders:e?.countOrders??null, countCompletedOrders:e?.countCompletedOrders??null,verificationStatus:e?.verificationStatus??null,referCode:e?.referCode??null,token:e?.token??!1,level:e?.level??null,sex:e?.sex??null,risk:e?.risk??null,walletEnabled:e?.walletEnabled??!1,wasReferred:e?.wasReferred??!1,fingerprint:null,totp:e?.totp??window.auth?.user?.totp??!1},window.authMethod=window.auth.user.authMethod,(window.auth.user?.token??"").length&&window.localStorage.setItem("rmses",btoa(JSON.stringify(window.auth.user))),null!=window.localStorage.getItem("rmses"))try{const e=JSON.parse(atob(window.localStorage.getItem("rmses")));null!=e&&(window.auth.user=e)}catch(e){}/:0$/.test(window.auth?.user?.token)&&window.auth.sowToken()},sowToken:()=>{const e=Date.now();e-(window.lastSessionCreatedEventTime??0)<1e4||window.auth?.user?.token&&!localStorage.getItem("RemexAuthToken")&&(localStorage.setItem("RemexAuthToken",`${window.auth.user.token}:${btoa(JSON.stringify({id:window.auth.user.id,name:window.auth.user.fullName, picture:window.auth.user.photoURL,email:window.auth.user.email,phone:window.auth.user.phone}))}`),window.dispatchEvent(new CustomEvent("sessionCreated",{bubbles:!0,detail:window.auth.user})),window.lastSessionCreatedEventTime=e)},showTOTPForceDialog:e=>{window.confirmModal(`
${e}
${window.auth.i18n("¿Deseas configurarlo ahora?")}`,(()=>{$("#secutiryModal").length?$("#secutiryModal").modal("show"):window.location.href="/customer/profile"}),(()=>0),"+"+moment.now())},_lockupPromises:{},renderSessionInfo:()=>{const e=window.auth.user?.photoURL||window.auth.user?.pictireUrl||window.auth.defaultProfilePicture;if(window.auth.defaultProfilePicture!=e){const t=new Image;t.onload=()=>$("#session-picture").attr("src",e),t.src=e}$(".auth-form-logged .customer-picture").css({"border-radius":"50%","margin-top":"-60px",width:"80px",height:"80px"}), $(".auth-form-logged").height($("body").hasClass("device-mobile")?"auto":$("#customer-data-items").height()-40),$(`${window.auth.authSessionInfoCssSelector}`).show(),window.auth.loadTransactionalReputation(),window.dispatchEvent(new CustomEvent("sessionInfoRendered",{bubbles:!0,detail:window.auth.user}))},_transactionalReputationHtml:null,loadTransactionalReputation:()=>!1,logout:()=>new Promise((async(e,t)=>{await window.auth.remexAuth.handleLogout(),window.auth.user=null,window.fspt=!1,window.localStorage.removeItem("rmses"),window.logouting||(window.logouting=!0,window.fspt=!1,window.dispatchEvent(new CustomEvent("sessionDestroyed",{bubbles:!0})),$("#user-explain-loading").remove(),e())})),refreshing:!1,clearCacheAndReload:()=>{setTimeout((()=>window.location.reload(!0)),1e3),navigator.serviceWorker.getRegistrations().then((function(e){for(let t of e)t.unregister()})),caches.keys().then((function(e){for(let t of e)caches.delete(t)}))}, showTOTPModal:async()=>(bringToFront=(e,t="*")=>{if(!(e instanceof HTMLElement))return;let o=0;document.querySelectorAll(t).forEach((e=>{if(e.classList.contains("alwaysOnTop"))return;const t=window.getComputedStyle(e);if("static"!==t.position){const e=parseInt(t.zIndex);!isNaN(e)&&e>o&&(o=e)}})),e.style.zIndex=o+1},new Promise(((e,t)=>{const o=$(".modal:visible");$(o).modal("toggle");const a="totp"+Math.random().toString(36).substr(2,9);$("#totpOverlay").remove(), $("body").append(`
\n
\n
\n
${window.auth.i18n("Verificación de seguridad con código TOTP")}
\n

${window.auth.i18n("Por tu seguridad, es necesario que hagamos una verificación. Por favor usa un código temporal generado en tu aplicación de autenticación.")}

\n
\n ${Array.from({length:6 }).map(((e,t)=>`
`)).join("")}\n
\n \n \n \n
\n
`),bringToFront(document.querySelector("#totpOverlay")),$("body").css("overflow","hidden");const n=document.querySelector("#totp-container form");setTimeout((()=>n.querySelector(`#${a}midleWareTotpcode0`).focus()),250), n.querySelector('button[type="button"]').addEventListener("click",(e=>{e.preventDefault(),$("#totpOverlay").fadeOut((()=>$("#totpOverlay").remove())),$("body").css("overflow","auto"),$(o).modal("toggle"),t()})),n.querySelectorAll('input[type="number"]').forEach(((e,t)=>{e.addEventListener("focus",(e=>{e.target.setAttribute("type","number")})),e.addEventListener("blur",(e=>{e.target.setAttribute("type","password")})),e.addEventListener("keyup",(e=>{const t=e.key.toLowerCase();if("backspace"==t||"delete"==t){e.target.value="";const t=parseInt(e.target.getAttribute("data-index")),o=n.querySelector(`#${a}midleWareTotpcode${t-1}`);o&&o.focus()}})),e.addEventListener("input",(e=>{if(n.querySelector(".auth-error-message").innerHTML="",n.querySelector('button[type="submit"]').setAttribute("disabled",!0),e.target.value.toString().length>1&&(e.target.value=e.target.value.toString().slice(e.target.value.toString().length-1,e.target.value.toString().length)),e.target.value.toString().length>0){ const e=n.querySelector(`#${a}midleWareTotpcode${t+1}`);e?(e.focus(),i()&&n.querySelector('button[type="submit"]').removeAttribute("disabled")):i()&&(n.querySelector('button[type="submit"]').removeAttribute("disabled"),n.querySelector('button[type="submit"]').focus())}else t>0&&n.querySelector(`#${a}midleWareTotpcode${t-1}`).focus()}))})),n.querySelector(".totpcode").addEventListener("paste",(e=>{const t=e.clipboardData.getData("text");6===t.length&&/^\d{6}$/.test(t)&&(e.preventDefault(),t.split("").forEach(((e,t)=>{const o=n.querySelector(`#${a}midleWareTotpcode${t}`);o&&(o.value=e,setTimeout((()=>o.setAttribute("type","password")),250))})),i()&&n.querySelector("button").removeAttribute("disabled"))}));const i=()=>6===Array.from({length:6}).map(((e,t)=>n.querySelector(`#${a}midleWareTotpcode${t}`).value)).join("").length;n.addEventListener("submit",(async t=>{t.preventDefault(),n.querySelector(".auth-error-message").innerHTML="";const i=n.querySelector('button[type="submit"]') ;i.setAttribute("disabled",!0),n.querySelector('button[type="button"]').setAttribute("disabled",!0),i.cacheHTML=i.innerHTML,i.innerHTML='';const r=Array.from({length:6}).map(((e,t)=>n.querySelector(`#${a}midleWareTotpcode${t}`).value)).join("");n.querySelectorAll('input[inputmode="numeric"]').forEach((e=>e.setAttribute("disabled",!0)));const s=await window.auth.remexAuth.handleTOTPVerification(window.auth.user.email,r);s.success?($("#totpOverlay").fadeOut((()=>$("#totpOverlay").remove())),$("body").css("overflow","auto"),localStorage.removeItem("x-force-totp"),$(o).modal("toggle"),e(s.seed)):(i.removeAttribute("disabled"),n.querySelector('button[type="button"]').removeAttribute("disabled"),n.querySelectorAll('input[inputmode="numeric"]').forEach((e=>e.removeAttribute("disabled"))),n.querySelector(".auth-error-message").innerHTML=` ${window.auth.i18n(s.message??"Invalid code")}`,i.innerHTML=i.cacheHTML)}))})))}, window.waitDefinition=e=>new Promise((t=>{const o=setInterval((()=>{void 0!==window[e]&&(clearInterval(o),t())}),250)})),window._networkSpeed=0,window.waitDefinition("jQuery").then((()=>{$(document).ready((()=>{setTimeout((()=>window.auth.init()),1e3)}))})),window.setNetworkPropertieToBody=()=>{},"connection"in navigator&&(window.setNetworkPropertieToBody=()=>{$("body").addClass(`network-${navigator.connection.effectiveType}`).data("net_type",navigator.connection.effectiveType).data("net_max_mbps",navigator.connection.downlink).data("net_rtt",navigator.connection.rtt).data("net_speed",window._networkSpeed)},window.setNetworkPropertieToBody(),navigator.connection.addEventListener("change",window.setNetworkPropertieToBody)),"undefined"==typeof moment){var script=document.createElement("script");script.src="/assets/moment/moment-with-locales.min.js",script.async=!0,document.head.appendChild(script)}!function(){ const e=XMLHttpRequest.prototype.open,t=XMLHttpRequest.prototype.send,o=XMLHttpRequest.prototype.setRequestHeader;let a=!1,n=new Map;const i=(e,t)=>{n.forEach((({xhr:o,body:a,originalHandlers:n,method:i,url:r})=>{if(e){let e=a,s="application/json";if("string"==typeof a)try{e=JSON.parse(a),s="application/json"}catch(e){s="application/x-www-form-urlencoded"}else a instanceof FormData&&(s="multipart/form-data",e=Object.fromEntries(a.entries()));const d={...o._headers,"x-totp-seed":t,"Content-Type":s,Accept:"application/json"},u=(e,t=403,a="Network Error")=>{Object.defineProperties(o,{response:{value:e},responseText:{value:"string"==typeof e?e:JSON.stringify(e)},status:{value:t},statusText:{value:a},readyState:{value:4}}),n.onreadystatechange&&n.onreadystatechange.call(o),n.onload&&n.onload.call(o)};fetch(r,{method:i,headers:d,body:"application/json"===s?JSON.stringify(e):a,credentials:"include"}).then((async e=>{if(e.ok)try{const t=await e.json();u(t,e.status,e.status)}catch(e){ u(null,500,"JSON Parse Error",{error:"Failed to parse response",details:e.message})}else try{const t=await e.json().catch((()=>({})));u(t,e.status,e.statusText)}catch(t){u({error:"Request failed"},e.status,e.statusText)}})).catch((e=>{"TypeError"===e.name&&e.message.includes("Failed to fetch")?u(0,"Network Request Failed"):"AbortError"===e.name?u(0,"Request Aborted"):u(505,e.message||"Network Error")}))}else Object.defineProperties(o,{status:{value:403,writable:!0},statusText:{value:"Forbidden",writable:!0},responseText:{value:JSON.stringify({success:!1,error:"TOTP Verification is Required"}),writable:!0},readyState:{value:4,writable:!0}}),"function"==typeof n.onreadystatechange&&n.onreadystatechange.call(o),"function"==typeof n.onload&&n.onload.call(o)})),n.clear(),a=!1};XMLHttpRequest.prototype.open=function(t,o){this._method=t,this._url=o,this._headers={},e.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(e,t){this._headers&&(this._headers[e]=t), o.apply(this,arguments)},XMLHttpRequest.prototype.send=function(e){if(window.auth&&window.auth.user&&window.auth.user.token&&("dev"==window.auth.env?this.setRequestHeader("Token",`${window.auth.user.token}:${document.querySelector('meta[name="x-sv"]')?.getAttribute("content")}`):this.setRequestHeader("Authorization",`Bearer ${window.auth.user.token}`),this.setRequestHeader("rmatk",`remesit-unit-time:${Date.now()}:${window.auth.user?.token}:${Date.now()}`),"y"==localStorage.getItem("x-force-totp")&&this.setRequestHeader("x-force-totp",1),window.auth?.remexAuth?.inizialized&&this.setRequestHeader("x-cpl",document.querySelector('meta[name="x-cpl"]')?.getAttribute("content")??window.auth.remexAuth.cookies.fetch("x-cpl")??"1.0.0"),window.auth&&window.auth.fingerprint&&(window.fspt=window.auth.fingerprint,this.setRequestHeader("x-rm-fingerprint",window.auth.fingerprint),this.setRequestHeader("x-device",window.auth.deviceLabel??""))),!(e=>{if(!e.startsWith("http"))return!0;try{ return new URL(e).origin===window.location.origin}catch(e){return!1}})(this._url))return void t.call(this,e);const o=this,r={onreadystatechange:o.onreadystatechange?o.onreadystatechange.bind(o):null,onload:o.onload?o.onload.bind(o):null,onerror:o.onerror?o.onerror.bind(o):null};o.onreadystatechange=null,o.onload=null,o.onerror=null,o.addEventListener("load",(function(){if(401===o.status)return window.auth.logout().then((()=>{setTimeout((()=>{$("body").createFlashMessage({type:"fail",message:"La sesión ha sido desconectada por seguridad. Inicia sesión nuevamente!",closeable:!0,permanent:!1,position:"fixed",location:"bottom-left",duration:5e3})}),250)})),!1;if(511===o.status){const t=((e,t,o)=>{const a=o?"string"==typeof o?o:JSON.stringify(o):"";return`${e.toUpperCase()}:${t}:${a}`})(o._method,o._url,e);return n.has(t)||n.set(t,{xhr:o,body:e,originalHandlers:r,method:o._method,url:o._url}),void(a||(a=!0,window.auth.showTOTPModal().then((e=>i(!0,e))).catch((()=>i(!1)))))} "function"==typeof r.onreadystatechange&&r.onreadystatechange.call(o),"function"==typeof r.onload&&r.onload.call(o)})),o.addEventListener("error",(function(){"function"==typeof r.onerror&&r.onerror.apply(o,arguments)})),t.call(o,e)}}();