const block = document.querySelector("#post-nav-anchor"); const links = block.querySelectorAll("a"); let originalLinks = []; function saveAndReplaceLinks() { links.forEach((link) => { originalLinks.push(link.getAttribute("href")); const newUrl = "#premium"; link.setAttribute("href", newUrl); }); } function restoreOriginalLinks() { if (originalLinks.length === 0) { return; } links.forEach((link, index) => { link.setAttribute("href", originalLinks[index]); }); } function isMobileDevice() { return /Mobi|Android|iPhone|iPad|iPod/i.test(navigator.userAgent); } checkUrlForPremium(); // Function to show premium content function showPremium() { toggleIsActive("auth-form", false); document.querySelector(".premium").style.display = "none"; document.querySelector(".post__content--mod").classList.remove("is-hide"); document.getElementById("signup").style.display = "none"; document.getElementById("login").style.display = "block"; restoreOriginalLinks(); userSigned = true; } document .querySelector(".js-log-in-popup") .addEventListener("click", function (event) { event.preventDefault(); handleAuthPopupClick(0); }); document .querySelector(".js-sign-in-popup") .addEventListener("click", function (event) { event.preventDefault(); handleAuthPopupClick(1); }); window.addEventListener("load", function () { const cookieExists = document.cookie.includes("extra_metadata"); if (cookieExists) { showPremium(); } if (!cookieExists && !isMobileDevice()) { google.accounts.id.prompt(); } }); // START Apple ID Auth AppleID.auth.init({ clientId: "com.epro.web", scope: "name email", redirectURI: "https://essaypro.com/apple-callback", state: "init", nonce: "9b1deb4d-3b7d-4bad-9baw-2b0d7b3dcb6d", usePopup: true, }); let accessTokenApple; function signInWithApple() { AppleID.auth .signIn() .then((response) => { accessTokenApple = response.authorization.id_token; sendAppleRequest(accessTokenApple, false); }) .catch((error) => { console.error("Sign in with Apple failed:", error); }); } document.querySelectorAll(".js-apple-login-btn").forEach((button) => { button.addEventListener("click", signInWithApple); }); // END Apple ID // START FB Auth window.fbAsyncInit = function () { FB.init({ appId: "1377613392528854", cookie: true, xfbml: true, version: "v14.0", }); FB.AppEvents.logPageView(); }; (function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); })(document, "script", "facebook-jssdk"); let accessTokenFb; // Event handler for 'Login with Facebook' button click document.querySelectorAll(".js-fb-login-btn").forEach((button) => { button.addEventListener("click", function () { FB.login( function (response) { if (response.status === "connected") { accessTokenFb = response.authResponse.accessToken; sendFbRequest(false); } else { console.log("User cancelled login or did not fully authorize."); } }, { scope: "public_profile,email" } ); }); }); // END FB Auth // START Google Auth render buttons let googleBtnWidth; function renderGoogleButton(index) { const buttonElement = document.getElementById(`googleBtnRender${index}`); const buttonWrap = document.getElementById(`googleBtnWrap${index}`); googleBtnWidth = buttonWrap?.offsetWidth || googleBtnWidth; google.accounts.id.renderButton(buttonElement, { theme: "outline", size: "large", width: googleBtnWidth, }); } document .querySelectorAll(".auth-form__tabs__link.w-tab-link") .forEach((tabLink) => { tabLink.addEventListener("click", (event) => { const lastChar = event.target.id.slice(-1); renderGoogleButton(lastChar); }); }); // END Google Auth render buttons let loginToken = ""; if (getCookie("accessToken")) { fetchUserData().then(() => { const storedData = localStorage.getItem("currentUser"); if (storedData) { const user = JSON.parse(storedData); if (user.state === "unverified") { toggleIsActive("auth-form", true); toggleIsActive("initial-state", false); toggleIsActive("auth-form-social", false); toggleIsActive("confirm-state", true); document.getElementById("confirm-email").textContent = user.email; } } }); } // START GENERAL FUNCTIONS // facebook api request function sendFbRequest(activateValue) { fetch("https://app.essaypro.com/api/social/auth/signin/facebook/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ access_token: accessTokenFb, activate: activateValue, client_id: "pgnfidgwuKhlfrh4jRuIirRpvteChDGnga9I4hmj", is_test: false, role: "customer", site: "app.essaypro.com", website_source: "is_premium_blog_user", }), credentials: "include", }) .then((response) => response.json()) .then((data) => { if (data.is_sms_otp_allow) { showTwoFactorStep(); loginToken = data.token; } else if (!data.error_map) { setCookie({ name: "accessToken", value: data.access_token, domain: ".essaypro.com", }); setCookie({ name: "refreshToken", value: data.refresh_token, domain: ".essaypro.com", }); fetchUserData().then((userData) => { if (userData.new_user) { setCookie({ name: "new_user", value: "true", domain: ".essaypro.com", }); userSignUpEvent(userData.id, "facebook"); } else { userLoginEvent(userData.id, "facebook"); } if ( !userData.allow_unverified_user && userData.state === "unverified" ) { showConfirmEmailStep(userData.email); } else { showPremium(); } }); } else { showCodeErrorStep(data.code, "facebook"); } }) .catch((error) => console.error("Error:", error)); } // apple api request function sendAppleRequest(token, activateValue) { fetch("https://app.essaypro.com/api/social/auth/signin/apple-id/", { method: "POST", body: JSON.stringify({ access_token: token, client_id: "pgnfidgwuKhlfrh4jRuIirRpvteChDGnga9I4hmj", role: "customer", activate: activateValue, website_source: "is_premium_blog_user", }), headers: { "Content-Type": "application/json", }, credentials: "include", }) .then((response) => response.json()) .then((data) => { if (data.is_sms_otp_allow) { showTwoFactorStep(); loginToken = data.token; } else if (!data.error_map) { setCookie({ name: "accessToken", value: data.access_token, domain: ".essaypro.com", }); setCookie({ name: "refreshToken", value: data.refresh_token, domain: ".essaypro.com", }); fetchUserData().then((userData) => { if (userData.new_user) { setCookie({ name: "new_user", value: "true", domain: ".essaypro.com", }); userSignUpEvent(userData.id, "apple-id"); } else { userLoginEvent(userData.id, "apple-id"); } if ( !userData.allow_unverified_user && userData.state === "unverified" ) { showConfirmEmailStep(userData.email); } else { showPremium(); } }); } else { showCodeErrorStep(data.code, "apple"); } }) .catch((error) => { console.error("Error during login", error); }); } // get initial user data function fetchUserData() { const accessToken = getCookie("accessToken"); return fetch("https://app.essaypro.com/api/auth/user/", { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Bearer ${accessToken}`, }, credentials: "include", }) .then((response) => response.json()) .then((data) => { if (data.error_map) { localStorage.removeItem("currentUser"); } else { localStorage.setItem("currentUser", JSON.stringify(data)); } return data; }) .catch((error) => { console.error("Error:", error); }); } // get Cookie function function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(";").shift(); } // set Cookie function function setCookie({ name, value, domain }) { document.cookie = name + "=" + encodeURIComponent(value) + "; domain=" + domain + "; path=/"; } // Function to toggle 'is-active' class function toggleIsActive(id, add = true) { const element = document.getElementById(id); if (add) { element.classList.add("is-active"); } else { element.classList.remove("is-active"); } } // Function to switch tabs function switchTab(tabIndex) { document .querySelectorAll(".auth-form__tabs__link.w-tab-link") [tabIndex].click(); setTimeout(() => { renderGoogleButton(tabIndex); }, 100); } // Function to validate email function isValidEmail(email) { const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailPattern.test(email); } // Function to handle form errors function handleFormError(inputWrap, errorText, message) { inputWrap.classList.add("is-error"); if (message === "Incorrect credentials") { errorText.textContent = "Invalid email address or password. Try again"; } else { errorText.textContent = message; } } // Function to clear form errors function clearFormError(inputWrap, errorText) { inputWrap.classList.remove("is-error"); errorText.textContent = ""; } // Universal function to handle API response function handleApiResponse( data, emailInputWrap, passwordInputWrap, passErrorText, emailErrorText ) { if (data.is_sms_otp_allow) { showTwoFactorStep(); loginToken = data.token; } else if (!data.error_map) { if (!data.allow_unverified_user && data.state === "unverified") { showConfirmEmailStep(data.email); } else { showPremium(); } } else { let message = ""; if (typeof data.message === "object" && data.message !== null) { message = data.message.email || ""; } else { message = data.message; } if (message[0].includes("Email")) { handleFormError(emailInputWrap, emailErrorText, message); handleFormError(passwordInputWrap, passErrorText, ""); } else if (message.includes("WriterPro")) { document.getElementById("auth-modal-error").style.display = "block"; setTimeout(() => { document.getElementById("auth-modal-error").style.display = "none"; }, 5000); document.getElementById("auth-modal-error").textContent = message; } else { handleFormError(emailInputWrap, emailErrorText, ""); handleFormError(passwordInputWrap, passErrorText, message); } showCodeErrorStep(data.code, "email"); } } // Function when api response with two-factor authentication function showTwoFactorStep() { toggleIsActive("initial-state", false); toggleIsActive("auth-form-social", false); toggleIsActive("code-state", true); } // Function when api response with confirm email function showConfirmEmailStep(email) { document.getElementById("confirm-email").textContent = email; toggleIsActive("initial-state", false); toggleIsActive("auth-form-social", false); toggleIsActive("confirm-state", true); } // Function when api response with code error function showCodeErrorStep(codeStatus, authType) { if (codeStatus === "DEACTIVATED_USER_ERROR") { if (authType === "facebook") { toggleIsActive("reactivate-yes", false); toggleIsActive("reactivate-yes-fb", true); } else if (authType === "apple") { toggleIsActive("reactivate-yes", false); toggleIsActive("reactivate-yes-apple", true); } toggleIsActive("reactivate-popup", true); } else if (codeStatus === "LOCKED_USER_ERROR") { toggleIsActive("locked-popup", true); } } // Function to validate form input function validateForm( email, password, emailInputWrap, emailErrorText, passwordInputWrap, passErrorText ) { let isValid = true; if (emailInputWrap && emailErrorText) { clearFormError(emailInputWrap, emailErrorText); if (!email) { handleFormError(emailInputWrap, emailErrorText, "Email is required"); isValid = false; } else if (!isValidEmail(email)) { handleFormError(emailInputWrap, emailErrorText, "Invalid email address"); isValid = false; } } if (passwordInputWrap && passErrorText) { clearFormError(passwordInputWrap, passErrorText); if (!password) { handleFormError(passwordInputWrap, passErrorText, "Password is required"); isValid = false; } else if (password.length < 6) { handleFormError( passwordInputWrap, passErrorText, "Password must be at least 6 characters long" ); isValid = false; } } return isValid; } // Toggle password visibility document.querySelectorAll(".js-toggle-password").forEach((icon) => { icon.addEventListener("click", function () { const parent = this.closest(".auth-form__input-wrap-upd"); const passwordInput = parent.querySelector("input"); const passwordHideIcon = parent.querySelector( ".auth-form__input-hide-pass" ); const passwordShowIcon = parent.querySelector( ".auth-form__input-show-pass" ); const isPassword = passwordInput.type === "password"; passwordInput.type = isPassword ? "text" : "password"; passwordHideIcon.classList.toggle("hide", !isPassword); passwordShowIcon.classList.toggle("hide", isPassword); }); }); // Event handler for switching to forgot password document .getElementById("forgot-password-btn") .addEventListener("click", function () { toggleIsActive("initial-state", false); toggleIsActive("auth-form-social", false); toggleIsActive("forgot-state", true); }); // Returning from forgot password document.querySelectorAll(".js-forgot-back").forEach((btn) => { btn.addEventListener("click", function () { toggleIsActive("forgot-state", false); toggleIsActive("initial-state", true); toggleIsActive("auth-form-social", true); toggleIsActive("forgot-success-block", false); document.getElementById("email-form-forgot").classList.remove("is-hide"); document.querySelector(".js-email-for-reset").textContent = ""; document.getElementById("forgot-email").value = ""; }); }); // show email auth state document.querySelectorAll(".js-start-email-btn").forEach((button) => { button.addEventListener("click", () => { document.querySelectorAll(".js-auth-email-step").forEach((step) => { step.classList.remove("is-hide"); }); document.querySelectorAll(".js-google-icon").forEach((btn) => { btn.classList.remove("is-hide"); }); document.querySelectorAll(".js-auth-start-state").forEach((state) => { state.classList.add("is-hide"); }); }); }); // show/hide loader on btn function toggleLoader(button, isLoading) { if (isLoading) { button.classList.add("is-loading"); } else { button.classList.remove("is-loading"); } } // END GENERAL FUNCTIONS // START reactivate logic // Event handler for 'Reactivate No' button click document .getElementById("reactivate-no") .addEventListener("click", () => toggleIsActive("reactivate-popup", false)); // Event handler for 'Contact Help' button click document.getElementById("contact-help-btn").addEventListener("click", () => { Intercom("show"); toggleIsActive("locked-popup", false); }); // Event handler for 'Reactivate Yes' button click document .getElementById("reactivate-yes") .addEventListener("click", function () { const email = document.getElementById("signin-email").value; const password = document.getElementById("signin-password").value; const emailInputWrap = document.getElementById("signin-email-input-wrap"); const emailErrorText = document.getElementById("signin-email-input-error"); const passwordInputWrap = document.getElementById("signin-pass-input-wrap"); const passErrorText = document.getElementById("signin-pass-input-error"); fetch("https://app.essaypro.com/api/auth/signin/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ activate: true, remember_me: true, email: email, password: password, client_id: "pgnfidgwuKhlfrh4jRuIirRpvteChDGnga9I4hmj", site: "app.essaypro.com", website_source: "is_premium_blog_user", }), credentials: "include", }) .then((response) => response.json()) .then((data) => { setCookie({ name: "accessToken", value: data.access_token, domain: ".essaypro.com", }); setCookie({ name: "refreshToken", value: data.refresh_token, domain: ".essaypro.com", }); handleApiResponse( data, emailInputWrap, passwordInputWrap, passErrorText, emailErrorText ); }) .catch((error) => console.error("Error:", error)); toggleIsActive("reactivate-popup", false); }); // Event handler for 'Reactivate Yes' google button click document .getElementById("reactivate-yes-google") .addEventListener("click", function () { const accessToken = getCookie("accessToken"); const authForm = document.getElementById("auth-form"); const isPremiumUser = authForm && authForm.classList.contains("is-active"); fetch("https://app.essaypro.com/api/social/auth/signin/google-oauth2/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ activate: true, access_token: accessToken, client_id: "pgnfidgwuKhlfrh4jRuIirRpvteChDGnga9I4hmj", is_test: false, role: "customer", site: "app.essaypro.com", ...(isPremiumUser && { is_premium_blog_user: true }), }), credentials: "include", }) .then((response) => response.json()) .then((data) => { if (data.is_sms_otp_allow) { showTwoFactorStep(); loginToken = data.token; } else if (!data.error_map) { setCookie({ name: "accessToken", value: data.access_token, domain: ".essaypro.com", }); setCookie({ name: "refreshToken", value: data.refresh_token, domain: ".essaypro.com", }); if (!data.allow_unverified_user && data.state === "unverified") { showConfirmEmailStep(data.email); } else { showPremium(); } } }) .catch((error) => console.error("Error:", error)); toggleIsActive("reactivate-popup", false); }); // Event handler for 'Reactivate Yes' facebook button click document .getElementById("reactivate-yes-fb") .addEventListener("click", function () { sendFbRequest(true); toggleIsActive("reactivate-popup", false); }); // Event handler for 'Reactivate Yes' apple button click document .getElementById("reactivate-yes-apple") .addEventListener("click", function () { sendAppleRequest(accessTokenApple, true); toggleIsActive("reactivate-popup", false); }); // END reactivate logic // START Login form logic via email function getLoginEmailValidationElements() { return { emailInputWrap: document.getElementById("signin-email-input-wrap"), emailErrorText: document.getElementById("signin-email-input-error"), email: document.getElementById("signin-email").value, }; } function getLoginPasswordValidationElements() { return { passwordInputWrap: document.getElementById("signin-pass-input-wrap"), passErrorText: document.getElementById("signin-pass-input-error"), password: document.getElementById("signin-password").value, }; } function validateLoginEmail() { const { email, emailInputWrap, emailErrorText } = getLoginEmailValidationElements(); validateForm(email, "", emailInputWrap, emailErrorText, null, null); } function validateLoginPassword() { const { password, passwordInputWrap, passErrorText } = getLoginPasswordValidationElements(); validateForm("", password, null, null, passwordInputWrap, passErrorText); } document .getElementById("loginButton") .addEventListener("click", function (event) { const currentBtn = event.currentTarget; const { email, emailInputWrap, emailErrorText } = getLoginEmailValidationElements(); const { password, passwordInputWrap, passErrorText } = getLoginPasswordValidationElements(); const isEmailValid = validateForm( email, "", emailInputWrap, emailErrorText, null, null ); const isPasswordValid = validateForm( "", password, null, null, passwordInputWrap, passErrorText ); if (!isEmailValid || !isPasswordValid) return; toggleLoader(currentBtn, true); fetch("https://app.essaypro.com/api/auth/signin/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ activate: null, remember_me: true, email: email, password: password, client_id: "pgnfidgwuKhlfrh4jRuIirRpvteChDGnga9I4hmj", site: "app.essaypro.com", website_source: "is_premium_blog_user", }), credentials: "include", }) .then((response) => response.json()) .then((data) => { const userId = getCookie("extra_metadata"); setCookie({ name: "accessToken", value: data.access_token, domain: ".essaypro.com", }); setCookie({ name: "refreshToken", value: data.refresh_token, domain: ".essaypro.com", }); localStorage.setItem("currentUser", JSON.stringify(data)); if (!data.error_map) { userLoginEvent(userId, "email"); } handleApiResponse( data, emailInputWrap, passwordInputWrap, passErrorText, emailErrorText ); }) .catch((error) => console.error("Error:", error)) .finally(() => { toggleLoader(currentBtn, false); }); }); document .getElementById("signin-email") .addEventListener("input", validateLoginEmail); document .getElementById("signin-password") .addEventListener("input", validateLoginPassword); // END Login form logic via email // START Sign Up logic function getSignEmailValidationElements() { return { emailInputWrap: document.getElementById("signup-email-input-wrap"), emailErrorText: document.getElementById("signup-email-input-error"), email: document.getElementById("signup-email").value, }; } function getSignPasswordValidationElements() { return { passwordInputWrap: document.getElementById("signup-pass-input-wrap"), passErrorText: document.getElementById("signup-pass-input-error"), password: document.getElementById("signup-password").value, }; } function validateSignEmail() { const { email, emailInputWrap, emailErrorText } = getSignEmailValidationElements(); validateForm(email, "", emailInputWrap, emailErrorText, null, null); } function validateSignPassword() { const { password, passwordInputWrap, passErrorText } = getSignPasswordValidationElements(); validateForm("", password, null, null, passwordInputWrap, passErrorText); } let recaptchaResponse; function onSubmitSignUp(token) { recaptchaResponse = token; document.getElementById("signUpButton").click(); } document .getElementById("signUpButton") .addEventListener("click", function (event) { if (!recaptchaResponse) { return; } const currentBtn = event.currentTarget; let responseData = {}; const { email, emailInputWrap, emailErrorText } = getSignEmailValidationElements(); const { password, passwordInputWrap, passErrorText } = getSignPasswordValidationElements(); const isEmailValid = validateForm( email, "", emailInputWrap, emailErrorText, null, null ); const isPasswordValid = validateForm( "", password, null, null, passwordInputWrap, passErrorText ); if (!isEmailValid) { window.dataLayer.push({ event: "auth_error_email", order_error_type: emailErrorText.innerText, }); } if (!isPasswordValid) { window.dataLayer.push({ event: "auth_error_password", order_error_type: passErrorText.innerText, }); } if (!isEmailValid || !isPasswordValid) return; toggleLoader(currentBtn, true); fetch("https://app.essaypro.com/api/auth/signup/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ email, password, role: "customer", client_id: "pgnfidgwuKhlfrh4jRuIirRpvteChDGnga9I4hmj", g_recaptcha_response: recaptchaResponse, site: "app.essaypro.com", website_source: "is_premium_blog_user", }), credentials: "include", }) .then((response) => response.json()) .then((data) => { responseData = data; const userId = getCookie("extra_metadata"); setCookie({ name: "accessToken", value: data.access_token, domain: ".essaypro.com", }); setCookie({ name: "refreshToken", value: data.refresh_token, domain: ".essaypro.com", }); if (!data.error_map) { return fetchUserData(); } if (typeof data.message === "object" && data.message !== null) { window.dataLayer.push({ event: "auth_error_email", order_error_type: data.message.email[0] || "", }); } else { window.dataLayer.push({ event: "auth_error_password", order_error_type: data.message, }); } }) .then((userData) => { const combinedData = { ...responseData, ...userData, }; if (combinedData.new_user) { setCookie({ name: "new_user", value: "true", domain: ".essaypro.com", }); userSignUpEvent(combinedData.id, "email"); } else { userLoginEvent(combinedData.id, "email"); } handleApiResponse( combinedData, emailInputWrap, passwordInputWrap, passErrorText, emailErrorText ); }) .catch((error) => console.error("Error:", error)) .finally(() => { toggleLoader(currentBtn, false); }); }); document .getElementById("signup-email") .addEventListener("input", validateSignEmail); document .getElementById("signup-password") .addEventListener("input", validateSignPassword); // END Sign Up logic // START Forgot Password logic function getForgotEmailValidationElements() { return { emailInputWrap: document.getElementById("forgot-email-input-wrap"), emailErrorText: document.getElementById("forgot-email-input-error"), email: document.getElementById("forgot-email").value, }; } function validateForgotEmail() { const { email, emailInputWrap, emailErrorText } = getForgotEmailValidationElements(); validateForm(email, "", emailInputWrap, emailErrorText, null, null); } document.getElementById("forgotButton").addEventListener("click", function () { const { email, emailInputWrap, emailErrorText } = getForgotEmailValidationElements(); const isEmailValid = validateForm( email, "", emailInputWrap, emailErrorText, null, null ); if (!isEmailValid) return; fetch( `https://app.essaypro.com/api/auth/forgot-password?email=${encodeURIComponent( email )}`, { method: "GET", } ) .then((response) => response) .then((data) => { if (data.status === 200) { toggleIsActive("forgot-success-block", true); document.getElementById("email-form-forgot").classList.add("is-hide"); document.querySelector(".js-email-for-reset").textContent = email; } else { handleFormError(emailInputWrap, emailErrorText, "Email not registered"); } }) .catch((error) => console.error("Error:", error)); }); document .getElementById("forgot-email") .addEventListener("input", validateForgotEmail); // END Forgot Password logic // START logic for opening/closing popup function handleAuthPopupClick(tabIndex) { const countryInfo = getCountryInfoByTimezone( Intl.DateTimeFormat().resolvedOptions().timeZone ); const allowedCountries = ["GB", "AU", "NZ", "IE"]; if (allowedCountries.includes(countryInfo?.country_code)) { document.getElementById("auth-country").textContent = countryInfo.name; document.getElementById( "auth-country-with-s" ).textContent = `${countryInfo.name}'s`; toggleIsActive("authFormCountry", true); } switchTab(tabIndex); toggleIsActive("auth-form", true); } document.getElementById("close-auth-popup").addEventListener("click", () => { toggleIsActive("auth-form", false); }); // END logic for opening/closing popup // START Returning from confirm email document.getElementById("backToSignup").addEventListener("click", function () { const accessToken = getCookie("accessToken"); switchTab(1); toggleIsActive("confirm-state", false); toggleIsActive("initial-state", true); toggleIsActive("auth-form-social", true); fetch("https://app.essaypro.com/api/auth/signout/", { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Bearer ${accessToken}`, }, credentials: "include", }) .then((response) => response.json()) .then((data) => { if (data.status) { localStorage.removeItem("currentUser"); } }) .catch((error) => { console.error("Error:", error); }); }); // END Returning from confirm email // START re-send link to email document .getElementById("confirmEmailBtn") .addEventListener("click", function () { const confirmEmail = document.getElementById("confirm-email").textContent; const accessToken = getCookie("accessToken"); fetch("https://app.essaypro.com/api/auth/verify-email/resend/", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${accessToken}`, }, body: JSON.stringify({ email: confirmEmail, }), credentials: "include", }) .then((response) => response) .then((data) => { if (data.ok) { document .getElementById("authFormConfirmBtn") .classList.add("is-hide"); toggleIsActive("authFormConfirmDone", true); } }) .catch((error) => console.error("Error:", error)); }); document .getElementById("confirmEmailAgain") .addEventListener("click", function () { document.getElementById("confirmEmailBtn").click(); }); // END re-send link to email // START two-factor authentication const codeInputs = document.querySelectorAll(".js-code-input"); const twoFactorSubmitBtn = document.getElementById("twoFactorCodeButton"); let code = ""; function checkInputs() { code = Array.from(codeInputs) .map((input) => input.value) .join(""); if (code.length === codeInputs.length) { twoFactorSubmitBtn.classList.remove("not-active"); document.getElementById("twoFactorCodeButton").click(); } else { twoFactorSubmitBtn.classList.add("not-active"); } } codeInputs.forEach((input, index) => { input.addEventListener("input", (e) => { let { value } = e.target; if (value.length > 1) { value = value.charAt(0); e.target.value = value; } if (value.length === 1 && index < codeInputs.length - 1) { codeInputs[index + 1].focus(); } checkInputs(); }); input.addEventListener("keydown", (e) => { if (e.key === "Backspace" && index > 0 && input.value === "") { codeInputs[index - 1].focus(); } }); input.addEventListener("paste", (e) => { e.preventDefault(); const pasteData = e.clipboardData.getData("text"); if (pasteData.length === codeInputs.length) { codeInputs.forEach((input, i) => { input.value = pasteData[i] || ""; }); checkInputs(); codeInputs[codeInputs.length - 1].focus(); } }); }); document .getElementById("twoFactorCodeButton") .addEventListener("click", function (event) { const currentBtn = event.currentTarget; const codeInputWrap = document.getElementById("code-input-wrap"); const codeInputError = document.getElementById("code-input-error"); if (!code) { handleFormError( codeInputWrap, codeInputError, "Verification code is required" ); return; } toggleLoader(currentBtn, true); fetch("https://app.essaypro.com/api/auth/signin/two-factor/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ otp: code, token: loginToken, client_id: "pgnfidgwuKhlfrh4jRuIirRpvteChDGnga9I4hmj", }), credentials: "include", }) .then((response) => response.json()) .then((data) => { if (!data.error_map) { setCookie({ name: "accessToken", value: data.access_token, domain: ".essaypro.com", }); setCookie({ name: "refreshToken", value: data.refresh_token, domain: ".essaypro.com", }); showPremium(); } else { handleFormError(codeInputWrap, codeInputError, ""); } }) .catch((error) => console.error("Error:", error)) .finally(() => { toggleLoader(currentBtn, false); }); }); // END two-factor authentication // START Country logic // Get country params function getCountryInfoByTimezone(timezone) { for (const country of countries) { if (country.timezones.includes(timezone)) { return { country_code: country.country_code, name: country.name, }; } } return null; } // Listeners for country popup buttons document .getElementById("closeCountryPopup") .addEventListener("click", function () { toggleIsActive("authFormCountry", false); }); document .getElementById("closeCountryAll") .addEventListener("click", function () { toggleIsActive("authFormCountry", false); toggleIsActive("auth-form", false); }); //END Country logic // START analytics window.dataLayer = window.dataLayer || []; function userLoginEvent(userId, method) { window.dataLayer.push({ user_id: userId, method: method, color_theme: "system", event: "user_login", }); } function userSignUpEvent(userId, method) { const currentDate = new Date(); const formattedDate = currentDate.getDate() + "." + (currentDate.getMonth() + 1) + "." + currentDate.getFullYear(); window.dataLayer.push({ userId: userId, eventCategory: "SignUp", eventAction: "Completed", registration_date: formattedDate, method: method, color_theme: "system", event: "CompleteRegistration", }); } document .querySelectorAll(".auth-form__tabs__link.w-tab-link")[1] .addEventListener("click", function () { window.dataLayer.push({ event: "auth_page_visit", }); }); // END analytics