const cookieExists = document.cookie.includes('extra_metadata'); let userSigned = cookieExists ? true : false; function isMobileDevice() { return /Mobi|Android|iPhone|iPad|iPod/i.test(navigator.userAgent); } window.addEventListener('load', function () { const body = document.querySelector('body'); const popup = document.querySelector('.collect'); const closeBtn = document.querySelectorAll('[collect="close"]'); closeBtn.forEach((close) => { close.addEventListener('click', () => { popup.style.display = 'none'; body.classList.remove('popup-open'); if (userSigned) { dataLayer.push({ event: 'blog_welcome_back_popup_click_close' }); } else { dataLayer.push({ event: 'auth_modal_click_close', click_text: "Close popup" }); } }); }); // PDF popup const samples = document.querySelectorAll('.post-sample'); if (samples) { samples.forEach((sample) => { sample.addEventListener('click', (e) => { if (!userSigned) { e.preventDefault(); handleAuthPopupClick1(1); popup.style.display = 'flex'; body.classList.add('popup-open'); sample.querySelector('.post-sample-link.mobile').style.pointerEvents = 'none'; google.accounts.id.cancel(); dataLayer.push({ event: 'auth_modal_open' }); } else { sample.querySelector('.sample-popup').style.display = 'flex'; sample.querySelector('.post-sample-link.mobile').style.pointerEvents = 'auto'; dataLayer.push({ event: 'blog_sample_open', click_text: sample.querySelectorAll('.post-sample-link')[0].textContent }); } }); }); }; // PDF download const sampleBtn = document.querySelectorAll(".banner-sample-link"); if(sampleBtn){ let pdfLink = ''; let pdfTitle = ''; sampleBtn.forEach((item) => { item.addEventListener("click", (e) => { if (!userSigned) { e.preventDefault(); handleAuthPopupClick1(1); popup.style.display = 'flex'; body.classList.add('popup-open'); google.accounts.id.cancel(); dataLayer.push({ event: 'auth_modal_open' }); } else { document.querySelector('.banner-sample').style.display = 'flex'; dataLayer.push({ event: 'blog_plagiarism_banner_open', click_text: item.textContent }); pdfLink = item.getAttribute("data-pdf"); pdfTitle = item.textContent; } }); }); document.getElementById("downloadBtn").addEventListener("click", async function() { try { const response = await fetch(pdfLink, { mode: "cors" }); if (!response.ok) throw new Error("File download error"); const blob = await response.blob(); const link = document.createElement("a"); link.href = URL.createObjectURL(blob); link.download = `${pdfTitle}.pdf`; document.body.appendChild(link); link.click(); document.body.removeChild(link); } catch (error) { window.open(pdfLink, "_blank"); } dataLayer.push({ 'event': 'blog_plagiarism_banner_download' }); }); document.getElementById("orderBtn").addEventListener("click", () => { dataLayer.push({ 'event': 'blog_plagiarism_banner_auth' }); }); } }); function showCollect() { document.querySelector('.collect__start').style.display = 'none'; document.querySelector('.collect__finish').style.display = 'flex'; userSigned = true; dataLayer.push({ event: 'blog_welcome_back_popup_open' }); } // 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 accessTokenApple1; function signInWithApple1() { AppleID.auth .signIn() .then((response) => { accessTokenApple1 = response.authorization.id_token; sendAppleRequest(accessTokenApple1, false); }) .catch((error) => { console.error('Sign in with Apple failed:', error); }); } document.querySelectorAll('[auth="apple"]').forEach((button) => { button.addEventListener('click', function () { signInWithApple1(); dataLayer.push({ event: 'click_apple_icon', click_text: clickText, type: "Auth modal" }); }); }); // 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 accessTokenFb1; // Event handler for 'Login with Facebook' button click document.querySelectorAll('[auth="facebook"]').forEach((button) => { button.addEventListener('click', function () { FB.login( function (response) { if (response.status === 'connected') { accessTokenFb1 = response.authResponse.accessToken; sendFbRequest(false); } else { console.log('User cancelled login or did not fully authorize.'); } }, { scope: 'public_profile,email' } ); dataLayer.push({ event: 'click_facebook_icon', click_text: clickText, type: "Auth modal" }); }); }); // END FB Auth // START Google Auth render buttons let googleBtnWidth1; function renderGoogleButton1(index) { const buttonElement = document.getElementById(`googleBtnRenderb${index}`); const buttonWrap = document.getElementById(`googleBtnWrapb${index}`); googleBtnWidth1 = buttonWrap?.offsetWidth || googleBtnWidth1; google.accounts.id.renderButton(buttonElement, { theme: 'filled_black', size: 'large', width: googleBtnWidth1, text: 'continue_with', }); } let clickText = "Log in"; document.querySelectorAll('.auth-form__tabs__link1.w-tab-link').forEach((tabLink, index) => { tabLink.addEventListener('click', (event) => { const lastChar = event.target.id.slice(-1); renderGoogleButton1(lastChar); clickText = index === 0 ? "Log in" : "Sign up"; dataLayer.push({ event: index === 0 ? "click_login_tab" : "click_sign_up_tab", click_text: clickText, type: "Auth modal" }); }); }); // END Google Auth render buttons let loginToken1 = ''; 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-b', false); toggleIsActive('auth-form-social-b', false); toggleIsActive('confirm-state-b', true); document.getElementById('confirm-email-b').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: accessTokenFb1, activate: activateValue, client_id: 'pgnfidgwuKhlfrh4jRuIirRpvteChDGnga9I4hmj', is_test: false, role: 'customer', site: 'app.essaypro.com', website_source: 'blog_samples', }), credentials: 'include', }) .then((response) => response.json()) .then((data) => { if (data.is_sms_otp_allow) { showTwoFactorStep(); loginToken1 = 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 { showCollect(); } }); } else { showCodeErrorStep(data.code1, '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: 'blog_samples', }), headers: { 'Content-Type': 'application/json', }, credentials: 'include', }) .then((response) => response.json()) .then((data) => { if (data.is_sms_otp_allow) { showTwoFactorStep(); loginToken1 = 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 { showCollect(); } }); } else { showCodeErrorStep(data.code1, '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 switchTab1(tabIndex) { setTimeout(() => { renderGoogleButton1(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(); loginToken1 = data.token; } else if (!data.error_map) { if (!data.allow_unverified_user && data.state === 'unverified') { showConfirmEmailStep(data.email); } else { showCollect(); } } 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-b').style.display = 'block'; setTimeout(() => { document.getElementById('auth-modal-error-b').style.display = 'none'; }, 5000); document.getElementById('auth-modal-error-b').textContent = message; } else { handleFormError(emailInputWrap, emailErrorText, ''); handleFormError(passwordInputWrap, passErrorText, message); } showCodeErrorStep(data.code1, 'email'); } } // Function when api response with two-factor authentication function showTwoFactorStep() { toggleIsActive('initial-state-b', false); toggleIsActive('auth-form-social-b', false); toggleIsActive('code-state-b', true); } // Function when api response with confirm email function showConfirmEmailStep(email) { document.getElementById('confirm-email-b').textContent = email; toggleIsActive('initial-state-b', false); toggleIsActive('auth-form-social-b', false); toggleIsActive('confirm-state-b', true); } // Function when api response with code error function showCodeErrorStep(codeStatus, authType) { if (codeStatus === 'DEACTIVATED_USER_ERROR') { if (authType === 'facebook') { toggleIsActive('reactivate-yes-b', false); toggleIsActive('reactivate-yes-fb-b', true); } else if (authType === 'apple') { toggleIsActive('reactivate-yes', false); toggleIsActive('reactivate-yes-apple-b', true); } toggleIsActive('reactivate-popup-b', true); } else if (codeStatus === 'LOCKED_USER_ERROR') { toggleIsActive('locked-popup-b', 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-b').addEventListener('click', function () { toggleIsActive('initial-state-b', false); toggleIsActive('auth-form-social-b', false); toggleIsActive('forgot-state-b', true); }); // Returning from forgot password document.querySelectorAll('.js-forgot-back').forEach((btn) => { btn.addEventListener('click', function () { toggleIsActive('forgot-state-b', false); toggleIsActive('initial-state-b', true); toggleIsActive('auth-form-social-b', true); toggleIsActive('forgot-success-block-b', false); document.getElementById('email-form-forgot-b').classList.remove('is-hide'); document.querySelector('.js-email-for-reset').textContent = ''; document.getElementById('forgot-email-b').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'); }); dataLayer.push({ event: 'click_with_email_icon', click_text: clickText, type: "Auth modal" }); }); }); // 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-b') .addEventListener('click', () => toggleIsActive('reactivate-popup', false)); // Event handler for 'Contact Help' button click document.getElementById('contact-help-btn-b').addEventListener('click', () => { Intercom('show'); toggleIsActive('locked-popup-b', false); }); // Event handler for 'Reactivate Yes' button click document.getElementById('reactivate-yes-b').addEventListener('click', function () { const email = document.getElementById('signin-email-b').value; const password = document.getElementById('signin-password-b').value; const emailInputWrap = document.getElementById('signin-email-input-wrap-b'); const emailErrorText = document.getElementById('signin-email-input-error-b'); const passwordInputWrap = document.getElementById('signin-pass-input-wrap-b'); const passErrorText = document.getElementById('signin-pass-input-error-b'); 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: 'blog_samples', }), 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-b').addEventListener('click', function () { const accessToken = getCookie('accessToken'); 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', website_source: 'blog_samples', }), credentials: 'include', }) .then((response) => response.json()) .then((data) => { if (data.is_sms_otp_allow) { showTwoFactorStep(); loginToken1 = 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 { showCollect(); } } }) .catch((error) => console.error('Error:', error)); toggleIsActive('reactivate-popup', false); }); // Event handler for 'Reactivate Yes' facebook button click document.getElementById('reactivate-yes-fb-b').addEventListener('click', function () { sendFbRequest(true); toggleIsActive('reactivate-popup', false); }); // Event handler for 'Reactivate Yes' apple button click document.getElementById('reactivate-yes-apple-b').addEventListener('click', function () { sendAppleRequest(accessTokenApple1, true); toggleIsActive('reactivate-popup', false); }); // END reactivate logic // START Login form logic via email function getLoginEmailValidationElements() { return { emailInputWrap: document.getElementById('signin-email-input-wrap-b'), emailErrorText: document.getElementById('signin-email-input-error-b'), email: document.getElementById('signin-email-b').value, }; } function getLoginPasswordValidationElements() { return { passwordInputWrap: document.getElementById('signin-pass-input-wrap-b'), passErrorText: document.getElementById('signin-pass-input-error-b'), password: document.getElementById('signin-password-b').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-b').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: 'blog_samples', }), 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-b').addEventListener('input', validateLoginEmail); document.getElementById('signin-password-b').addEventListener('input', validateLoginPassword); // END Login form logic via email // START Sign Up logic function getSignEmailValidationElements() { return { emailInputWrap: document.getElementById('signup-email-input-wrap-b'), emailErrorText: document.getElementById('signup-email-input-error-b'), email: document.getElementById('signup-email-b').value, }; } function getSignPasswordValidationElements() { return { passwordInputWrap: document.getElementById('signup-pass-input-wrap-b'), passErrorText: document.getElementById('signup-pass-input-error-b'), password: document.getElementById('signup-password-b').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 recaptchaResponse1; function onSubmitSignUp(token) { recaptchaResponse1 = token; document.getElementById('signUpButton-b').click(); } document.getElementById('signUpButton-b').addEventListener('click', function (event) { if (!recaptchaResponse1) { 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: recaptchaResponse1, site: 'app.essaypro.com', website_source: 'blog_samples', }), 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-b').addEventListener('input', validateSignEmail); document.getElementById('signup-password-b').addEventListener('input', validateSignPassword); // END Sign Up logic // START Forgot Password logic function getForgotEmailValidationElements() { return { emailInputWrap: document.getElementById('forgot-email-input-wrap-b'), emailErrorText: document.getElementById('forgot-email-input-error-b'), email: document.getElementById('forgot-email-b').value, }; } function validateForgotEmail() { const { email, emailInputWrap, emailErrorText } = getForgotEmailValidationElements(); validateForm(email, '', emailInputWrap, emailErrorText, null, null); } document.getElementById('forgotButton-b').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-b', true); document.getElementById('email-form-forgot-b').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-b').addEventListener('input', validateForgotEmail); // END Forgot Password logic // START logic for opening popup function handleAuthPopupClick1(tabIndex) { const countryInfo = getCountryInfoByTimezone(Intl.DateTimeFormat().resolvedOptions().timeZone); const allowedCountries = ['GB', 'AU', 'NZ', 'IE']; if (allowedCountries.includes(countryInfo?.country_code)) { document.getElementById('auth-country-b').textContent = countryInfo.name; document.getElementById('auth-country-with-s-b').textContent = `${countryInfo.name}'s`; toggleIsActive('authFormCountry-b', true); } switchTab1(tabIndex); } // END logic for opening popup // START Returning from confirm email document.getElementById('backToSignup-b').addEventListener('click', function () { const accessToken = getCookie('accessToken'); switchTab1(1); toggleIsActive('confirm-state-b', false); toggleIsActive('initial-state-b', true); toggleIsActive('auth-form-social-b', 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-b').addEventListener('click', function () { const confirmEmail = document.getElementById('confirm-email-b').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-b').classList.add('is-hide'); toggleIsActive('authFormConfirmDone-b', true); } }) .catch((error) => console.error('Error:', error)); }); document.getElementById('confirmEmailAgain-b').addEventListener('click', function () { document.getElementById('confirmEmailBtn-b').click(); }); // END re-send link to email // START two-factor authentication const codeInputs1 = document.querySelectorAll('.js-code-input'); const twoFactorSubmitBtn1 = document.getElementById('twoFactorCodeButton-b'); let code1 = ''; function checkInputs() { code1 = Array.from(codeInputs1) .map((input) => input.value) .join(''); if (code1.length === codeInputs1.length) { twoFactorSubmitBtn1.classList.remove('not-active'); document.getElementById('twoFactorCodeButton-b').click(); } else { twoFactorSubmitBtn1.classList.add('not-active'); } } codeInputs1.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 < codeInputs1.length - 1) { codeInputs1[index + 1].focus(); } checkInputs(); }); input.addEventListener('keydown', (e) => { if (e.key === 'Backspace' && index > 0 && input.value === '') { codeInputs1[index - 1].focus(); } }); input.addEventListener('paste', (e) => { e.preventDefault(); const pasteData = e.clipboardData.getData('text'); if (pasteData.length === codeInputs1.length) { codeInputs1.forEach((input, i) => { input.value = pasteData[i] || ''; }); checkInputs(); codeInputs1[codeInputs1.length - 1].focus(); } }); }); document.getElementById('twoFactorCodeButton-b').addEventListener('click', function (event) { const currentBtn = event.currentTarget; const codeInputWrap = document.getElementById('code-input-wrap-b'); const codeInputError = document.getElementById('code-input-error'); if (!code1) { 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: code1, token: loginToken1, 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' }); showCollect(); } 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-b').addEventListener('click', function () { toggleIsActive('authFormCountry-b', false); }); document.getElementById('closeCountryAll-b').addEventListener('click', function () { toggleIsActive('authFormCountry-b', 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', }); } // END analytics