// Search subjects document.addEventListener('DOMContentLoaded', () => { let orderParams = {}; let searchSubjects = []; const body = document.querySelector('body'); const popup = document.querySelector('.r-popup'); const searchWrap = document.querySelector('.subjects'); const resultWrap = document.querySelector('.subjects__bot'); const resultList = document.querySelector('.subjects__list'); const searchInput = document.querySelector('.subjects__input'); const searchClear = document.querySelector('.subjects__clear'); const searchArrow = document.querySelector('.subjects__arrow'); const mobileTrigger = document.querySelector('.subjects-trigger'); const popupClose = document.querySelector('.subjects__close'); const authButtons = document.querySelectorAll("a[href*='app.studyfy.com']"); const reviewsButton = document.querySelector("[data-button-group='button_internal_page']"); const popularSubjects = `
Popular

Occupational safety and health administration

Nursing

Business and management

English

Psychology

Healthcare

Education

Social work

`; fetch('https://app.studyfy.com/api/directory/external/') .then((response) => { return response.json(); }) .then((json) => { let { subjects } = json; subjects.forEach((subject) => { searchSubjects.push({ name: subject.title, group: subject.subject_group_title, }); }); }) .catch((error) => console.error('Error accessing the API', error)); if (window.innerWidth <= 991) { popup.appendChild(searchWrap); searchInput.placeholder = 'Search'; mobileTrigger.addEventListener('click', function () { searchWrap.style.display = 'block'; popup.style.display = 'flex'; body.classList.add('popup-open'); updateResult(''); notQuizPage && google.accounts.id.cancel(); notQuizPage = false; }); popupClose.addEventListener('click', function () { popup.style.display = 'none'; body.classList.remove('popup-open'); }); } else { document.addEventListener('click', function (event) { if (!event.target.closest('.subjects')) { resultWrap.style.display = 'none'; searchArrow.classList.remove('subjects__arrow--active'); } }); } searchInput.addEventListener('focus', function () { updateResult(''); searchArrow.classList.add('subjects__arrow--active'); }); searchInput.addEventListener('input', function () { let searchText = searchInput.value; updateResult(searchText); if (searchInput.value !== '') { searchClear.classList.add('subjects__clear--active'); } else { searchClear.classList.remove('subjects__clear--active'); } }); searchClear.addEventListener('click', function () { searchInput.value = ''; mobileTrigger.innerText = searchInput.placeholder; searchClear.classList.remove('subjects__clear--active'); searchArrow.classList.add('subjects__arrow--active'); updateResult(''); }); function updateResult(query) { resultWrap.style.display = 'block'; query = query.toLowerCase(); let results = searchSubjects.filter((el) => el.name.toLowerCase().indexOf(query) !== -1); resultList.innerHTML = ''; if (results.length < 1) { resultList.innerHTML = '

Nothing was found

'; return; } let groupedResults = results.reduce((groups, subject) => { const groupName = subject.group; if (!groups[groupName]) { groups[groupName] = []; } groups[groupName].push(subject.name); return groups; }, {}); let sortedGroups = Object.keys(groupedResults).sort(); let resultString = ''; sortedGroups.forEach((group) => { resultString += `
${group}
`; groupedResults[group].sort().forEach((name) => { resultString += `

${name}

`; }); }); if (query === '') { resultList.innerHTML = popularSubjects + resultString; } else { resultList.innerHTML = resultString; } let resultItems = document.querySelectorAll('.subjects__value'); resultItems.forEach((item) => { item.addEventListener('click', function () { searchInput.value = item.innerText; mobileTrigger.innerText = item.innerText; resultList.innerHTML = ''; resultWrap.style.display = 'none'; popup.style.display = 'none'; body.classList.remove('popup-open'); searchClear.classList.add('subjects__clear--active'); orderParams.subject = item.innerText; dataLayer.push({ event: 'landing_page_subject', method: 'drop list', click_text: item.innerText, }); }); }); } async function sendOrder(data) { if (Object.keys(data).length < 1) return false; const orderId = crypto.randomUUID(); const orderData = { front_id: orderId, ...data }; try { const response = await fetch('https://app.studyfy.com/api/order/order-form/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(orderData), }); if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status}: ${errorText}`); } const encodedCookie = encodeURIComponent( JSON.stringify({ context: 'order-form', payload: { front_id: orderId }, }) ); document.cookie = `landing_context=${encodedCookie}; domain=.studyfy.com; path=/;`; return true; } catch (error) { console.error('Error', error.message); return false; } } authButtons.forEach((button) => { button.addEventListener('click', async function (e) { e.preventDefault(); if (button.innerText == 'Log in') { handleAuthPopupClick(0); dataLayer.push({ event: 'click_login_button', button_text: button.innerText, }); } else if (button.innerText == 'Sign up') { handleAuthPopupClick(1); dataLayer.push({ event: 'click_sign_up_button', button_text: button.innerText, }); } else { handleAuthPopupClick(1); dataLayer.push({ event: 'landing_page_click_start_order', button_text: button.innerText, subject: orderParams.subject || 'not selected', }); } body.classList.add('popup-open'); google.accounts.id.cancel(); const success = await sendOrder(orderParams); }); }); reviewsButton.addEventListener('click', function (e) { dataLayer.push({ event: 'landing_page_reviews_block_click', button_text: reviewsButton.innerText, }); }); // Range scroll const rangeScrolls = document.querySelectorAll('[range-scroll]'); const rangeSliders = document.querySelectorAll('[range-input]'); if (rangeScrolls && rangeSliders) { rangeSliders.forEach((range, index) => { rangeSlider(range, rangeScrolls[index], range.getAttribute('range-input')); }); } function rangeSlider(toggle, content, direction = 'horizontal') { const scroll = toggle; const panel = content; const isHorizontal = direction === 'horizontal'; if (isHorizontal) { swipeWithScroll(content); } scroll.oninput = function () { const total = isHorizontal ? panel.scrollWidth - panel.offsetWidth : panel.scrollHeight - panel.offsetHeight; const percentage = total * (this.value / 100); if (isHorizontal) { panel.scrollLeft = percentage; } else { panel.scrollTop = percentage; } }; panel.onscroll = function () { const total = isHorizontal ? panel.scrollWidth - panel.offsetWidth : panel.scrollHeight - panel.offsetHeight; const percentage = isHorizontal ? (panel.scrollLeft / total) * 100 : (panel.scrollTop / total) * 100; scroll.value = percentage; }; } function swipeWithScroll(slider) { let isDown = false; let startX; let scrollLeft; slider.addEventListener('mousedown', (e) => { isDown = true; startX = e.pageX - slider.offsetLeft; scrollLeft = slider.scrollLeft; cancelMomentumTracking(); }); slider.addEventListener('mouseleave', () => { isDown = false; }); slider.addEventListener('mouseup', () => { isDown = false; beginMomentumTracking(); }); slider.addEventListener('mousemove', (e) => { if (!isDown) return; e.preventDefault(); const x = e.pageX - slider.offsetLeft; const walk = (x - startX) * 3; var prevScrollLeft = slider.scrollLeft; slider.scrollLeft = scrollLeft - walk; velX = slider.scrollLeft - prevScrollLeft; }); var velX = 0; var momentumID; slider.addEventListener('wheel', (e) => { cancelMomentumTracking(); }); function beginMomentumTracking() { cancelMomentumTracking(); momentumID = requestAnimationFrame(momentumLoop); } function cancelMomentumTracking() { cancelAnimationFrame(momentumID); } function momentumLoop() { slider.scrollLeft += velX; velX *= 0.95; if (Math.abs(velX) > 0.5) { momentumID = requestAnimationFrame(momentumLoop); } } } // Read more text const text = document.querySelector('.r-intro__span'); const btn = document.querySelector('.r-intro__show'); btn.addEventListener('click', () => { if (text.classList.contains('r-intro__span--active')) { text.classList.remove('r-intro__span--active'); btn.textContent = 'Read more'; } else { text.classList.add('r-intro__span--active'); btn.textContent = 'Read less'; } }); }); // AUTHENTICATION // 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' } ); userMethodRegisterEvent('click_facebook_icon'); }); }); // 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: 'filled_black', size: 'large', width: googleBtnWidth, text: 'continue_with', click_listener: onGoogleClickHandler, }); } 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.studyfy.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.studyfy.com', }), 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: '.studyfy.com', }); setCookie({ name: 'refreshToken', value: data.refresh_token, domain: '.studyfy.com', }); if (data.is_new) { setCookie({ name: 'new_user', value: 'true', domain: '.studyfy.com', }); } fetchUserData().then((userData) => { if (userData.new_user) { userSignUpEvent(userData.id, 'facebook'); } else { userLoginEvent(userData.id, 'facebook'); } if (!userData.allow_unverified_user && userData.state === 'unverified') { showConfirmEmailStep(userData.email); } else { window.location.href = 'https://app.studyfy.com/'; } }); } else { showCodeErrorStep(data.code, 'facebook'); } }) .catch((error) => console.error('Error:', error)); } // get initial user data function fetchUserData() { const accessToken = getCookie('accessToken'); return fetch('https://app.studyfy.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 { window.location.href = `https://app.studyfy.com/`; } } 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); //document.querySelector('.quiz__forgot').textContent = 'Two-factor authentication'; } // Function when api response with confirm email function showConfirmEmailStep(email) { //document.querySelector('.quiz__forgot').textContent = 'Confirm your email'; //document.querySelector('.quiz__confirm').style.display = 'flex'; //document.querySelectorAll('.quiz__prev')[4].style.display = 'none'; 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 === '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); document.querySelector('.auth-form__title').textContent = 'Forgot password'; //document.querySelector('.quiz__forgot').style.display = 'flex'; //document.querySelectorAll('.quiz__prev')[4].style.display = 'none'; }); // 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 = ''; document.querySelector('.auth-form__title').textContent = 'Continue with email'; //document.querySelector('.quiz__forgot').style.display = 'none'; //document.querySelectorAll('.quiz__prev')[4].style.display = 'flex'; }); }); // 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'); }); userMethodRegisterEvent('click_with_email_icon'); }); }); // 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.studyfy.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.studyfy.com', 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: '.studyfy.com', }); setCookie({ name: 'refreshToken', value: data.refresh_token, domain: '.studyfy.com', }); handleApiResponse(data, emailInputWrap, passwordInputWrap, passErrorText, emailErrorText); } else { 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.studyfy.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.studyfy.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: '.studyfy.com', }); setCookie({ name: 'refreshToken', value: data.refresh_token, domain: '.studyfy.com', }); if (!data.allow_unverified_user && data.state === 'unverified') { showConfirmEmailStep(data.email); } else { window.location.href = `https://app.studyfy.com/`; } } }) .catch((error) => console.error('Error:', error)); 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.studyfy.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.studyfy.com', 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) { const userId = getCookie('extra_metadata'); setCookie({ name: 'accessToken', value: data.access_token, domain: '.studyfy.com', }); setCookie({ name: 'refreshToken', value: data.refresh_token, domain: '.studyfy.com', }); localStorage.setItem('currentUser', JSON.stringify(data)); userLoginEvent(userId, 'email'); handleApiResponse(data, emailInputWrap, passwordInputWrap, passErrorText, emailErrorText); } else { 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; handleSignUpSubmission(); } function handleSignUpSubmission() { if (!recaptchaResponse) { return; } 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; const signUpButton = document.getElementById('signUpButton'); toggleLoader(signUpButton, true); let responseData = {}; fetch('https://app.studyfy.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.studyfy.com', is_premium_blog_user: true, }), credentials: 'include', }) .then((response) => response.json()) .then((data) => { responseData = data; if (data.is_sms_otp_allow) { showTwoFactorStep(); loginToken = data.token; toggleLoader(signUpButton, false); return; } if (!data.error_map) { const userId = getCookie('extra_metadata'); setCookie({ name: 'accessToken', value: data.access_token, domain: '.studyfy.com', }); setCookie({ name: 'refreshToken', value: data.refresh_token, domain: '.studyfy.com', }); return fetchUserData().then((userData) => { const combinedData = { ...responseData, ...userData, }; if (combinedData.new_user) { setCookie({ name: 'new_user', value: 'true', domain: '.studyfy.com', }); userSignUpEvent(combinedData.id, 'email'); } else { userLoginEvent(combinedData.id, 'email'); } handleApiResponse( combinedData, emailInputWrap, passwordInputWrap, passErrorText, emailErrorText ); }); } 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, }); } handleApiResponse(data, emailInputWrap, passwordInputWrap, passErrorText, emailErrorText); }) .catch((error) => console.error('Error:', error)) .finally(() => { toggleLoader(signUpButton, false); }); } document.getElementById('signUpButton').addEventListener('click', function (event) { event.preventDefault(); handleSignUpSubmission(); }); 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.studyfy.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); } dataLayer.push({ event: 'auth_modal_open' }); switchTab(tabIndex); toggleIsActive('auth-form', true); } document.getElementById('close-auth-popup').addEventListener('click', () => { toggleIsActive('auth-form', false); document.querySelector('body').classList.remove('popup-open'); const codeStateElement = document.getElementById('code-state'); if (codeStateElement && codeStateElement.classList.contains('is-active')) { toggleIsActive('initial-state', true); toggleIsActive('auth-form-social', true); toggleIsActive('code-state', false); } window.dataLayer.push({ event: 'auth_modal_click_close', click_text: 'Close popup', }); }); // END logic for opening/closing popup // START Returning from confirm email document.getElementById('backToSignup').addEventListener('click', function () { const accessToken = getCookie('accessToken'); toggleIsActive('confirm-state', false); toggleIsActive('initial-state', true); //toggleIsActive('auth-form-social', true); //document.querySelector('.quiz__forgot').textContent = 'Continue with email'; //document.querySelector('.quiz__confirm').style.display = 'none'; //document.querySelectorAll('.quiz__prev')[4].style.display = 'flex'; fetch('https://app.studyfy.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.studyfy.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'); } } function clearCodeInputs() { codeInputs.forEach((input) => { input.value = ''; }); code = ''; twoFactorSubmitBtn.classList.add('not-active'); if (codeInputs.length > 0) { codeInputs[0].focus(); } } 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); const requestBody = { otp: code, token: loginToken, client_id: 'pgnfidgwuKhlfrh4jRuIirRpvteChDGnga9I4hmj', }; fetch('https://app.studyfy.com/api/auth/signin/two-factor/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(requestBody), credentials: 'include', }) .then((response) => response.json()) .then((data) => { if (!data.error_map) { setCookie({ name: 'accessToken', value: data.access_token, domain: '.studyfy.com', }); setCookie({ name: 'refreshToken', value: data.refresh_token, domain: '.studyfy.com', }); window.location.href = `https://app.studyfy.com/`; } else { clearCodeInputs(); handleFormError(codeInputWrap, codeInputError, data.message?.otp?.[0] || ''); toggleIsActive('twoFactorSms', true); } }) .catch((error) => console.error('Error:', error)) .finally(() => { toggleLoader(currentBtn, false); }); }); // Event handler for 'Resend SMS' button click document.getElementById('twoFactorSms').addEventListener('click', function () { fetch('https://app.studyfy.com/api/auth/signin/two-factor/sms/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ token: loginToken, client_id: 'pgnfidgwuKhlfrh4jRuIirRpvteChDGnga9I4hmj', }), credentials: 'include', }) .then((response) => response.json()) .then((data) => { if (!data.error_map) { console.log('SMS resent successfully'); } else { console.error('Error resending SMS:', data.error_map); } }) .catch((error) => console.error('Error:', error)); }); // 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); closeQuiz(); }); //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', }); } function userMethodRegisterEvent(eventName) { const activeTab = document.querySelector('.auth-form__tabs__link.w--current'); const clickText = activeTab ? activeTab.textContent.trim() : ''; window.dataLayer.push({ event: eventName, click_text: clickText, type: 'Auth modal', }); } function onGoogleClickHandler() { userMethodRegisterEvent('click_google_icon'); } document .querySelectorAll('.auth-form__tabs__link.w-tab-link')[1] .addEventListener('click', function () { window.dataLayer.push({ event: 'click_sign_up_tab', click_text: 'Sign up', type: 'Auth modal', }); }); document .querySelectorAll('.auth-form__tabs__link.w-tab-link')[0] .addEventListener('click', function () { window.dataLayer.push({ event: 'click_login_tab', click_text: 'Log in', type: 'Auth modal', }); }); // END analytics