function ConsoleLog(logText) { // Check if the URL contains the parameter "debug=true" const urlParams = new URLSearchParams(window.location.search); const debugMode = urlParams.get('debug'); // If debug is set to true, log the text if (debugMode === 'true') { console.log(logText); } } /** * LoadMethods is in the start page head tag, this is just a place to store the code * It sets the initial states and contains code for the getjob button click event. * getJob.addEventListener('click') -> this event has Prompt 1 builtin in * Prompt 1 -> queries LLM with jobTitle and JobDescription and returns Segments in an array and JobDescriptionSummary */ function LoadMethods() { try { // Select the form element and the loader elements const form = document.querySelector('#wf-form-chatgptForm'); const resultWrap = document.querySelector('#statement-component'); const resultLoader = document.querySelector('#statement-loader'); const resultText = document.querySelector('#statement-text'); const getJob = document.querySelector('#btnGetJob'); const getJobNewSearch = document.querySelector('#btnGetJob_NewSearch'); const generateJobDescription = document.querySelector('#openWizard'); const generateJobDescription_NewSearch = document.querySelector('#openWizard-newSearch'); const getJobChat = document.querySelector('#btnGetJobChat'); const getStarted = document.querySelector('#btnGetStarted'); const getStartedBottom = document.querySelector('#get-started-free'); const learnMoreBtn = document.querySelector('#btnLearnMore-1'); const learnMoreBtn_Agency = document.querySelector('#btnLearnMore_Agency'); const checkStatusBtn = document.querySelector('#btnCheckStatus'); const btnCancel = document.querySelector('#btnCancel'); const newSearch = document.querySelector('#NewSearch'); const submitConsent = document.querySelector('#btnSubmitConsent'); var txtJobTitle = document.getElementById('jobTitle'); var jobInput = document.getElementById('jobInput'); var txtJobDescription = document.getElementById('jobDescription'); var btnLogInOut = document.getElementById('btnLogInOut'); var promptLogin = document.getElementById('admin-prompt-login'); //var // agency const getStartedBottom_Agency = document.querySelector('#get-started-free_Agency'); const getStarted_Agency = document.querySelector('#btnGetStarted_Agency'); if(jobInput) { jobInput.addEventListener('click', (event) => { // empty ui var addResponsibilitiesContainter = document.getElementById('add-repsonsibilities-container'); if(addResponsibilitiesContainter) { addResponsibilitiesContainter.innerHTML = ''; } var responsibilitiesContainter = document.getElementById('responsibilities'); var AI_responsibilitiesContainter = document.getElementById('ai-responsibilities'); /*if(responsibilitiesContainter) { responsibilitiesContainter.innerHTML = ''; }*/ if(AI_responsibilitiesContainter) { AI_responsibilitiesContainter.innerHTML = ''; } // clear this of values - decided against that. keep them //selectedResponsibilities = []; // reset to the first step document.querySelectorAll(".wizard-step").forEach(step => { step.style.display = "none"; }); document.querySelector('#step1').style.display = "block"; // trigger modal $('#wizard-modal').css('z-index', '10001').animate({ opacity: 1 }).show(); // set focus to field $('#wizard-modal #jobTitle').focus(); }); $('#wizard-modal .close-btn-w').click(function() { $('#wizard-modal').animate({ opacity: 0 }).hide(); }); $('#n8n-modal .close-btn-w').click(function() { $('#n8n-modal').animate({ opacity: 0 }).hide(); }); } $('#custom-task-modal .close-btn-w').click(function() { $('#custom-task-modal').animate({ opacity: 0 }).hide(); }); var generateCustomBtn = document.getElementById('generate-steps-button'); if(generateCustomBtn) { generateCustomBtn.addEventListener('click', (event) => { // validate var isValid = true; if($('#activity-name').val().length == 0) { $('#validateCustomName').text('Please enter a name for your task (min characters: 5)').show(); isValid = false; } if($('#activity-description').val().length == 0) { $('#validateCustomDescription').text('Please enter a concise description of your task (min characters: 50)').show(); isValid = false; } if($('#output-type').val() == "") { $('#validateCustomOutput').text('Please select a desired output for your custom task').show(); isValid = false; } if(isValid) { var customModal = document.querySelector('#custom-task-modal'); var button = customModal.querySelector("#generate-steps-button"); //document.getElementById("update-listing-button"); var buttonText = customModal.querySelector('#button-text'); //document.getElementById("button-text"); var spinner = customModal.querySelector('#spinner'); //document.getElementById("spinner"); var errorMsg = customModal.querySelector('#custom-activity-error'); // Disable button and show spinner button.disabled = true; spinner.style.display = "inline-block"; errorMsg.style.display = "none"; // submit to server var MYPEAS_payload = {}; MYPEAS_payload["CustomActivityData"] = {}; MYPEAS_payload["ActivityName"] = $('#activity-name').val(); MYPEAS_payload["ActivityDescription"] = $('#activity-description').val(); MYPEAS_payload["DesiredOutput"] = $('#output-type').val(); MYPEAS_payload["promptDescription"] = "CustomActivity"; var memberID = localStorage.getItem("memberID"); if(memberID) { MYPEAS_payload["memberID"] = memberID; } const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // switch to processing UI // Make an API call to API gateway - return will just indicate that it is processing var apiUrl = 'https://lt8psnfy4f.execute-api.eu-west-1.amazonaws.com/Production/MYPEASGPT'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData), }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { // Hide spinner and enable button spinner.style.display = "none"; button.disabled = false; result = JSON.parse(result); ConsoleLog("result (object): ", result); // result (object): {"message":"processing"} ConsoleLog("result (stringified): ", JSON.stringify(result)); // "{\"message\":\"processing\"}" var message = result["message"]; // check the return string // refresh page as it will now be on the profile switch(message) { case "Custom Task Failed": // alert user that it failed errorMsg.style.display = "block"; break; case "Custom Task Created": // perhapes show a message that it completed for 1.5 second then // refresh page /*setTimeout(function() { location.reload(); }, 1500);*/ location.reload(); break; } }).catch(error => { // Hide spinner and enable button spinner.style.display = "none"; button.disabled = false; errorMsg.style.display = "block"; console.error("Error generating custom task", error); }); } }); } // How to use it: if (isTestModeEnabled()) { // Code to execute when testmode is true ConsoleLog('Test mode is active!'); var testOnly = document.getElementById('testOnly'); if(testOnly) { $(testOnly).show(); } // show the profile selecion tools var industryDropdown = document.getElementById('industryDropdown'); var emailDropdown = document.getElementById('emailDropdown'); var jobDropdown = document.getElementById('jobDropdown'); const emailTextField = document.getElementById('email-submit'); if(industryDropdown) { industryDropdown.addEventListener('change', fetchJobDataByDropdown); } if(emailDropdown) { emailDropdown.addEventListener('change', () => { const selectedEmail = emailDropdown.value; emailTextField.value = selectedEmail; password.value = "TestPassword9$"; }); } if(jobDropdown) { jobDropdown.addEventListener('change', fetchJobDataByDropdown); } } // waitlist mode - this only happens when user has got through waitlist // only applies to user home page (not agency or admin) if (!(window.location.href.toLowerCase().includes('/agency') || window.location.href.toLowerCase().includes('/admin'))) { if (isWaitModeEnabled()) { // show // hide $('#btnJoinWaitlist').hide(); $('#join-waitlist-bottom').hide(); $('#waitlist-container').hide(); $('#invite-launcher').hide(); // show $('#btnGetStarted').show().css('display', 'block'); $('#get-started-free').show().css('display', 'block'); $('#Form-container').show(); } else { $('#btnGetStarted').show().css('display', 'none'); $('#get-started-free').show().css('display', 'none'); $('#Form-container').hide(); } } // join waitlist var joinWaitList = document.getElementById('btnJoinWaitlist'); var joinWaitListBottom = document.getElementById('join-waitlist-bottom'); var skipWaitListBottom = document.getElementById('btn-skip-wait-bottom'); var signUpWaitList = document.getElementById('btnSubmitWaitlist'); var inviteLauncher = document.getElementById('invite-launcher'); if(joinWaitList) { // open modal inviteLauncher.addEventListener('click', (event) => { redeemMode("waitlist"); $('#redeem-invitation-modal').animate({ opacity: 1 }).show(); }); // close modal $('#redeem-invitation-modal .close-btn-w').click(function(){ $('#redeem-invitation-modal').animate({ opacity: 0 }).hide(); $('#linkedin-modal').animate({ opacity: 0 }).hide(); unLockScroll(); }); // scroll to sign up form joinWaitList.addEventListener('click', (event) => { $('html, body').animate({ //scrollTop: $('#waitlist-container').offset().top - 50 scrollTop: $('#skipwaitlist-container').offset().top - 50 }, 500); }); joinWaitListBottom.addEventListener('click', (event) => { $('html, body').animate({ //scrollTop: $('#waitlist-container').offset().top - 50 scrollTop: $('#skipwaitlist-container').offset().top - 50 }, 500); }); // sign up form for waitlist signUpWaitList.addEventListener('click', (event) => { var waitingListContainer = document.getElementById('waitlist-container'); var loading_spinner = waitingListContainer.querySelector('#waitlist-loading'); var firstName = document.getElementById('waitlist_txt_FirstName'); var Surname = document.getElementById('waitlist_txt_Surname'); var email = document.getElementById('waitlist_txt_email'); var failed = false; var validationMessages = []; var validateFirstName = waitingListContainer.querySelector('#validateFirstName'); var validateSurname = waitingListContainer.querySelector('#validateSurname'); var validateEmail = waitingListContainer.querySelector('#validateEmail'); var validateConsent = waitingListContainer.querySelector('#validateConsent'); var validateCaptcha = waitingListContainer.querySelector('#validateCaptcha'); var checkboxContactAgreeTerms = waitingListContainer.querySelector('#checkbox_email'); var hiddenCaptchaValue = document.getElementById('hcv').value; var honeypot = document.getElementById('consent_check'); // validate waitlist var MYPEAS_payload = {}; MYPEAS_payload["firstName"] = firstName.value; MYPEAS_payload["Surname"] = Surname.value; MYPEAS_payload["promptDescription"] = "JoinWaitList"; MYPEAS_payload["email"] = email.value; MYPEAS_payload["WaitListData"] = {}; const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // hide all validation messages validateFirstName.style.display = 'none'; validateFirstName.style.color = 'red'; validateSurname.style.display = 'none'; validateSurname.style.color = 'red'; validateEmail.style.display = 'none'; validateEmail.style.color = 'red'; validateConsent.style.display = 'none'; validateConsent.style.color = 'red'; validateCaptcha.style.display = 'none'; validateCaptcha.style.color = 'red'; if(firstName.value.length < 2) { failed = true; validateJobTitle.textContent = "First name is too short"; validateJobTitle.style.display = 'block'; validationMessages.push(validateJobTitle.id); } if(Surname.value.length < 2) { failed = true; validateJobDescription.textContent = "Surname is too short"; validateJobDescription.style.display = 'block'; validationMessages.push(validateJobDescription.id); } if(!isValidEmail(email.value)) { failed = true; validateEmail.textContent = "Please enter a valid email"; validateEmail.style.display = 'block'; validationMessages.push(validateEmail.id); } if(!consentChecked(checkboxContactAgreeTerms)) { failed = true; validateConsent.textContent = "Consent required.‍"; validateConsent.style.display = 'block'; validationMessages.push(validateConsent.id); } // check for solved captcha if(hiddenCaptchaValue == "") { failed = true; validateCaptcha.textContent = "Please confirm you are not a robot!"; validateCaptcha.style.display = 'block'; validationMessages.push(validateCaptcha.id); //document.getElementById('hcv').value } if(!failed) { // hide button $(signUpWaitList).hide(); // show spinner $(loading_spinner).show(); // submit to server // Make an API call to API gateway - return will just indicate that it is processing var apiUrl = 'https://lt8psnfy4f.execute-api.eu-west-1.amazonaws.com/Production/MYPEASGPT'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData), }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("result (object): ", result); // result (object): {"message":"processing"} ConsoleLog("result (stringified): ", JSON.stringify(result)); // "{\"message\":\"processing\"}" var message = result["message"]; // show button $(signUpWaitList).show(); // hide spinner $(loading_spinner).hide(); switch(message) { case "success": // clear the other fields // clear values firstName.value = ""; Surname.value = ""; email.value = ""; OpenModal("Sorted", "We will be in touch soon!", false, false); break; case "failed": /* return { statusCode: 200, body: JSON.stringify({"message": "You have a profile currently processing.", "promptDescription": promptDescription}), }; */ //ShowProcessing("processing"); OpenModal("Please Note", "We encountered a problem. Please try again later.", false, false); break; case "already signed up": /* return { statusCode: 200, body: JSON.stringify({"message": "You have exceeded your free account profile limit", "promptDescription": promptDescription}), }; */ OpenModal("Please Note", "You have already signed up to the waiting list.", false, false); break; } }) .catch(error => { console.error("Error calling RegisterWaitList: ", error); // show button $(signUpWaitList).show(); // hide spinner $(loading_spinner).hide(); }); } if(failed) { // scroll to first error $('html, body').animate({ scrollTop: $('#' + validationMessages[0]).offset().top - 50 }, 500); } }); // skip waitlist skipWaitListBottom.addEventListener('click', (event) => { // scroll to skipwaitlist container $('html, body').animate({ scrollTop: $('#skipwaitlist-container').offset().top - 50 }, 500); }); // submit invitation code redeem var submitInviteCode = document.getElementById('btnSubmitInviteCode'); submitInviteCode.addEventListener('click', (event) => { var redeemInvitationContainer = document.getElementById('redeem-invitation-modal'); var email = redeemInvitationContainer.querySelector('#txtRedeemEmail'); var invitationCode = redeemInvitationContainer.querySelector('#txtInviteCode'); var validateEmail = redeemInvitationContainer.querySelector('#validateRedeemEmail'); var validateInvitationCode = redeemInvitationContainer.querySelector('#validateInviteCode'); // validate fields var failed = false; var validationMessages = []; var MYPEAS_payload = {}; MYPEAS_payload["email"] = email.value; MYPEAS_payload["invitationCode"] = invitationCode.value; MYPEAS_payload["promptDescription"] = "RedeemInvitation"; MYPEAS_payload["redeemInviteData"] = {}; const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // hide all validation messages validateEmail.style.display = 'none'; validateEmail.style.color = 'red'; validateInvitationCode.style.display = 'none'; validateInvitationCode.style.color = 'red'; if(invitationCode.value.length < 8) { failed = true; validateInvitationCode.textContent = "Invitation code is too short"; validateInvitationCode.style.display = 'block'; validationMessages.push(validateInvitationCode.id); } // check the field is visible if(!isValidEmail(email.value) && $('#txtRedeemEmail').is(":visible")) { failed = true; validateEmail.textContent = "Please enter a valid email"; validateEmail.style.display = 'block'; validationMessages.push(validateEmail.id); } // if its linkedin based. dont send to server var sendToServer = true; if(!$('#txtRedeemEmail').is(":visible")) { sendToServer = false; } if(!failed && !sendToServer) { // show loading var loading_spinner = document.getElementById('invitation-code-loading'); $(loading_spinner).show(); // hide button var invitationCodeSubmit = document.getElementById('btnSubmitInviteCode'); $(invitationCodeSubmit).hide(); var enableUX = function(){ // show button $(invitationCodeSubmit).show(); // hide spinner $(loading_spinner).hide(); // clear the other fields email.value = ""; invitationCode.value = ""; // show non wait-list version // store in localstorage localStorage.setItem("waitmode", "unlocked"); showUnlocked(); // hide invitation modal $('#redeem-invitation-modal .close-btn-w').click(); OpenModal("Welcome", "Your personal invitation code has been accepted!", false, false); }; setTimeout(enableUX, 2000); } if(!failed && sendToServer) { // show loading var loading_spinner = document.getElementById('invitation-code-loading'); $(loading_spinner).show(); // hide button var invitationCodeSubmit = document.getElementById('btnSubmitInviteCode'); $(invitationCodeSubmit).hide(); // Make an API call to API gateway - return will just indicate that it is processing var apiUrl = 'https://lt8psnfy4f.execute-api.eu-west-1.amazonaws.com/Production/MYPEASGPT'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData), }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("result (object): ", result); // result (object): {"message":"processing"} ConsoleLog("result (stringified): ", JSON.stringify(result)); // "{\"message\":\"processing\"}" var message = result["message"]; // show button $(invitationCodeSubmit).show(); // hide spinner $(loading_spinner).hide(); switch(message) { case "success": // clear the other fields email.value = ""; invitationCode.value = ""; // show non wait-list version // store in localstorage localStorage.setItem("waitmode", "unlocked"); showUnlocked(); // hide invitation modal $('#redeem-invitation-modal .close-btn-w').click(); OpenModal("Welcome", "Your personal invitation code has been accepted!", false, false); break; case "invalid code": /* return { statusCode: 200, body: JSON.stringify({"message": "You have a profile currently processing.", "promptDescription": promptDescription}), }; */ //ShowProcessing("processing"); OpenModal("Problem", "This invitation code is invalid.", false, false); break; } }) .catch(error => { console.error("Error calling RegisterWaitList: ", error); // show button $(invitationCodeSubmit).show(); // hide spinner $(loading_spinner).hide(); }); } if(failed) { // scroll to first error $('html, body').animate({ scrollTop: $('#' + validationMessages[0]).offset().top - 50 }, 500); } }); } // access code var accessLauncher = document.getElementById('invite-launcher'); var accessauncher = document.getElementById('invite-launcher'); $('#linkedin-modal .close-btn-w').click(function(){ $('#linkedin-modal').animate({ opacity: 0 }).hide(); unLockScroll(); }); $('#invite-launcher-access').click(function(){ // open redeem modal $('#redeem-invitation-modal').animate({ opacity: 100 }).show(); // set to linkedIn mode redeemMode("linkedin"); // close this modal $('#linkedin-modal .close-btn-w').click(); }); if(btnLogInOut) { btnLogInOut.addEventListener('click', (event) => { /*Log in Log in*/ var currentText = $('#btnLogInOut').text(); switch(currentText) { case "Log Out": // trigger logout LogOut(); break; case "Log In": // prompt user to login OpenCloseLoginModal("open"); break; } }); } if(promptLogin) { promptLogin.addEventListener('click', (event) => { // prompt user to login OpenCloseLoginModal("open"); }); } if(form) { // Add a submit event listener to the form form.addEventListener('submit', (event) => { // Prevent the default form submission behavior event.preventDefault(); }); } /* Generate job description with AI */ // button deprecated if(generateJobDescription) { generateJobDescription.addEventListener('click', (event) => { // empty ui var responsibilitiesContainter = document.getElementById('responsibilities'); var AI_responsibilitiesContainter = document.getElementById('ai-responsibilities'); var addResponsibilitiesContainter = document.getElementById('add-repsonsibilities-container'); if(addResponsibilitiesContainter) { addResponsibilitiesContainter.innerHTML = ''; } /*if(responsibilitiesContainter) { responsibilitiesContainter.innerHTML = ''; }*/ if(AI_responsibilitiesContainter) { AI_responsibilitiesContainter.innerHTML = ''; } // clear this of values //selectedResponsibilities = []; $('#wizard-modal').css('z-index', '10001').animate({ opacity: 1 }).show(); }); $('#wizard-modal .close-btn-w').click(function() { $('#wizard-modal').animate({ opacity: 0 }).hide(); }); } if(generateJobDescription_NewSearch) { generateJobDescription_NewSearch.addEventListener('click', (event) => { // empty ui var responsibilitiesContainter = document.getElementById('responsibilities'); var AI_responsibilitiesContainter = document.getElementById('ai-responsibilities'); var addResponsibilitiesContainter = document.getElementById('add-repsonsibilities-container'); if(addResponsibilitiesContainter) { addResponsibilitiesContainter.innerHTML = ''; } if(responsibilitiesContainter) { responsibilitiesContainter.innerHTML = ''; } /*if(AI_responsibilitiesContainter) { AI_responsibilitiesContainter.innerHTML = ''; }*/ // clear this of values selectedResponsibilities = []; $('#wizard-modal').css('z-index', '10001').animate({ opacity: 1 }).show(); }); $('#wizard-modal .close-btn-w').click(function() { $('#wizard-modal').animate({ opacity: 0 }).hide(); }); } /* Click "GENERATE button" */ /* created our own button as the submit kept submitting whatever we tried */ /* prompt completion */ if(getJob) { getJob.addEventListener('click', (event) => { try { /* TO DO */ /* If user clicks prompt again, then store the current job in a hidden field (allow max 5) */ /* Create a function to load stored jobs */ /* Create a function to delete stored jobs */ /* Create membership where user stores data in database */ var isUserLoggedIn = checkLoggedIn(); // Always start new search fresh if(!isUserLoggedIn) { ClearStorage(); } // Prevent the default form submission behavior event.preventDefault(); /* TEST WITH THIS DATA var MYPEAS_payload = JSON.parse(event.body).MYPEAS_payload; var promptDescription = JSON.parse(event.body).MYPEAS_payload.promptDescription; var registered = JSON.parse(event.body).MYPEAS_payload.registered; var memberIDValue = JSON.parse(event.body).MYPEAS_payload.memberID || ""; var emailAddress = JSON.parse(event.body).MYPEAS_payload.email; */ // Get the values of the form fields const JobTitle = document.getElementById('jobTitle').value; const IndustryTitle = $('#wizard_industry').text(); const IndustryId = $('#wizard_industry').val(); const JobDescription = document.getElementById('jobDescription').value; const email = document.getElementById('email-submit').value.toLowerCase(); const password = document.getElementById('password').value; var hiddenCaptchaValue = document.getElementById('hcv').value; var honeypot = document.getElementById('consent_check'); var formContainer = document.getElementById('Form-container'); var consentCheckbox = formContainer.querySelector('#checkbox_email') var MYPEAS_payload = {}; MYPEAS_payload["JobTitle"] = JobTitle; MYPEAS_payload["Industry"] = IndustryTitle; MYPEAS_payload["IndustryId"] = IndustryId; MYPEAS_payload["JobDescription"] = JobDescription; //MYPEAS_payload["promptDescription"] = "Prompt1"; MYPEAS_payload["promptDescription"] = "Signup"; //MYPEAS_payload["promptDescription"] = "promptTest"; MYPEAS_payload["registered"] = "true"; // should always be true now that user provides password at start page MYPEAS_payload["email"] = email; MYPEAS_payload["password"] = password; // Get the client's time zone const clientTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; MYPEAS_payload["timeZone"] = clientTimeZone; const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // validate fields var failed = false; var validationMessages = []; // validation messages /*var validateJobTitle = document.getElementById('validateJobTitle'); var validateJobDescription = document.getElementById('validateJobDescription'); var validateEmail = document.getElementById('validateEmail'); var validatePassword = document.getElementById('validatePassword'); var validateConsent = document.getElementById('validateConsent'); var validateCaptcha = document.getElementById('validateCaptcha');*/ var validateJobTitle = document.querySelector('#Form-container').querySelector('#validateJobTitle'); var validateJobDescription = document.querySelector('#Form-container').querySelector('#validateJobDescription'); var validateEmail = document.querySelector('#Form-container').querySelector('#validateEmail'); var validatePassword = document.querySelector('#Form-container').querySelector('#validatePassword'); var validateConsent = document.querySelector('#Form-container').querySelector('#validateConsent'); var validateCaptcha = document.querySelector('#Form-container').querySelector('#validateCaptcha'); // hide all validation messages validateJobTitle.style.display = 'none'; validateJobTitle.style.color = 'red'; validateJobDescription.style.display = 'none'; validateJobDescription.style.color = 'red'; validateEmail.style.display = 'none'; validateEmail.style.color = 'red'; validatePassword.style.display = 'none'; validatePassword.style.color = 'red'; validateConsent.style.display = 'none'; validateConsent.style.color = 'red'; validateCaptcha.style.display = 'none'; validateCaptcha.style.color = 'red'; if(JobTitle.length < 3) { failed = true; validateJobTitle.textContent = "Job Title is too short"; validateJobTitle.style.display = 'block'; validationMessages.push(validateJobTitle.id); } /* FYI jobData is defined in the webflow main page as a global variable // Store user selections globally let jobData = { title: "", industry: "", responsibilities: [] }; */ if(JobDescription.length < 100 && (JobDescription.trim() !== 'Generated by AI' && jobData)) { failed = true; validateJobDescription.textContent = "Job Description is too short"; validateJobDescription.style.display = 'block'; validationMessages.push(validateJobDescription.id); } if(JobDescription.trim() == 'Generated by AI' && jobData) { var GeneratedJobDescription = generatedJobDescription(jobData); // use jobData to create a jobdescription MYPEAS_payload["JobDescription"] = GeneratedJobDescription; } if(!isValidEmail(email)) { failed = true; validateEmail.textContent = "Please enter a valid email"; validateEmail.style.display = 'block'; validationMessages.push(validateEmail.id); } if(!isValidPassword(password)) { failed = true; validatePassword.textContent = "Minimum length of 8 characters, contains at least one uppercase letter, one lowercase letter, one number, and one special character"; validatePassword.style.display = 'block'; validationMessages.push(validatePassword.id); } if(!consentChecked(consentCheckbox)) { failed = true; validateConsent.textContent = "Consent required.‍"; validateConsent.style.display = 'block'; validationMessages.push(validateConsent.id); } // check for solved captcha /*if(hiddenCaptchaValue == "") { failed = true; validateCaptcha.textContent = "Please confirm you are not a robot!"; validateCaptcha.style.display = 'block'; validationMessages.push(validateCaptcha.id); //document.getElementById('hcv').value }*/ if (honeypot && honeypot.checked) { failed = true; } if(!failed) { // switch to processing UI // hide formcontainer $('#Form-container').hide(); // hide waitlistcontainer $('#waitlist-container').hide(); // hide learn more $('#learn-more-container').hide(); // hide invite launcher $('#invite-launcher').hide(); // show processing containter // add email to processing email field $('#CheckStatusAddress').text(email); $('#processing-container').show(); // hide background video $('.background-video').hide(); $('.background-video-agency').hide(); // hide buttons $('#button-box').hide(); // add email to localstorage localStorage.setItem("email", email); localStorage.setItem("processStatus", "processing/updating"); // trigger timer attempts = 0; startCheckStatusIntervals(); MetaTrackEvent("CompleteRegistration"); ShowProcessing("processing"); // Make an API call to API gateway - return will just indicate that it is processing var apiUrl = 'https://lt8psnfy4f.execute-api.eu-west-1.amazonaws.com/Production/MYPEASGPT'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData), }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("result (object): ", result); // result (object): {"message":"processing"} ConsoleLog("result (stringified): ", JSON.stringify(result)); // "{\"message\":\"processing\"}" var message = result["message"]; // NOTE if logged in you will use this button in a specific circumstance // circumstance: user has cancelled a failed search, has no previous profile and needs to begin a "new search" // check if logged in/and/or no profile // if you have no profile the backend will never say you have exceeded limits switch(message) { case "processing": case "updating": // hide loading and show message to check back // can't do this break; /* Signup */ case "You have a profile currently processing.": /* return { statusCode: 200, body: JSON.stringify({"message": "You have a profile currently processing.", "promptDescription": promptDescription}), }; */ //ShowProcessing("processing"); OpenModal("Please Note", "You have a profile currently processing. Until that is complete you cannot request another on this account.", false, false); break; case "You have exceeded your free account profile limit": /* return { statusCode: 200, body: JSON.stringify({"message": "You have exceeded your free account profile limit", "promptDescription": promptDescription}), }; */ HideProcessing("loggedOut"); RejectHomepageSearch(); OpenModal("Upgrade", "You have exceeded your free account profile limit. Please purchase credit to perform more revisions.", false, true); break; case "You have exceeded your paid account profile limit": /* return { statusCode: 200, body: JSON.stringify({"message": "You have exceeded your paid account profile limit", "promptDescription": promptDescription}), }; */ HideProcessing("loggedOut"); RejectHomepageSearch(); OpenModal("Upgrade", "You have exceeded your paid account profile limit. Please purchase credit to perform more revisions.", false, true); break; // tell user to log in case "Account Exists. Wrong Password Entered": /* return { statusCode: 200, body: JSON.stringify({"message": "Account Exists. Wrong Password Entered", "promptDescription": promptDescription}), }; */ OpenModal("Problem", "Please check your login details", false, false); break; /* Login */ // user is validated case "User Validated": /* return { statusCode: 200, body: JSON.stringify({"message": "User Validated", "promptDescription": promptDescription, "profile": checkUserObj["profile"], "processStatus": checkUserObj["processStatus"]}), }; */ // add useful info to localstorage /* const user = { memberID: items.length > 0 && items[0].hasOwnProperty('memberID') ? items[0].memberID : null, profile: items.length > 0 && items[0].hasOwnProperty('profile') ? items[0].profile : null, processStatus: items.length > 0 && items[0].hasOwnProperty('processStatus') ? items[0].profile : null, registered: items.length > 0 && items[0].hasOwnProperty('registered') ? items[0].registered : null, passwordHash: items.length > 0 && items[0].hasOwnProperty('passwordHash') ? items[0].passwordHash : null, paidAccount: items.length > 0 && items[0].hasOwnProperty('paidAccount') ? items[0].paidAccount : null, revisions: items.length > 0 && items[0].hasOwnProperty('revisions') ? items[0].revisions : 0, mypeasPayload: items.length > 0 && items[0].hasOwnProperty('mypeasPayload') ? items[0].mypeasPayload : null, userExists: items.length > 0, }; */ localStorage.setItem("memberID", checkUserObj["memberID"]); localStorage.setItem("favourites", checkUserObj["favourites"]); localStorage.setItem("auth_token", checkUserObj["auth_token"]); localStorage.setItem("auth_token_date_created", checkUserObj["auth_token_date_created"]); break; // tell user to log in // failed to validate user case "Account Exists. Wrong Password Entered": /* return { statusCode: 200, body: JSON.stringify({"message": "Account Exists. Wrong Password Entered", "promptDescription": promptDescription}), }; */ OpenModal("Problem", "Please check your login details", false, false); break; /* ForgotPassword */ case "Password Changed": /* return { statusCode: 200, body: JSON.stringify({"message": "Password Changed", "promptDescription": promptDescription}), }; */ // update user interface and close loading // clear local storage and cookies localStorage.clear(); // can't delete the cookies, so set their values to expired. so we force UX to require new login // redirect to home page location.href = '/?login=true'; break; /* DeleteAccount */ case "": /* */ break; } }); } if(failed) { // scroll to first error $('html, body').animate({ scrollTop: $('#Form-container #' + validationMessages[0]).offset().top - 50 }, 500); } } catch(errGetJob) { // hide loading and show "something went wrong" message ConsoleLog('error name: ' + errGetJob.name); ConsoleLog('error message: ' + errGetJob.messsage); ConsoleLog('error stacktrace: ' + errGetJob.stack); } }); } if(getStarted) { getStarted.addEventListener('click', (event) => { $('html, body').animate({ //scrollTop: $('#wf-form-chatgptForm').offset().top - 95 scrollTop: $('#Form-container').offset().top - 95 }, 500); }); } if(getStartedBottom) { getStartedBottom.addEventListener('click', (event) => { $('html, body').animate({ //scrollTop: $('#wf-form-chatgptForm').offset().top - 95 scrollTop: $('#Form-container').offset().top - 95 }, 500); }); } if(getStarted_Agency) { getStarted_Agency.addEventListener('click', (event) => { $('html, body').animate({ //scrollTop: $('#wf-form-chatgptForm').offset().top - 95 scrollTop: $('#Form-container').offset().top - 95 }, 500); }); } if(getStartedBottom_Agency) { getStartedBottom_Agency.addEventListener('click', (event) => { $('html, body').animate({ //scrollTop: $('#wf-form-chatgptForm').offset().top - 95 scrollTop: $('#Form-container').offset().top - 95 }, 500); }); } if(learnMoreBtn) { learnMoreBtn.addEventListener('click', (event) => { $('html, body').animate({ scrollTop: $('#learn-more-container').offset().top - 50 }, 500); }); } if(learnMoreBtn_Agency) { //btnPlayVideo //btnLearnMore_Agency learnMoreBtn_Agency.addEventListener('click', (event) => { $('html, body').animate({ scrollTop: $('#learn-more-container').offset().top - 50 }, 500); }); } if(checkStatusBtn) { checkStatusBtn.addEventListener('click', (event) => { CheckStatus(); }); } if(btnCancel) { btnCancel.removeEventListener('click', Cancel); btnCancel.addEventListener('click', Cancel); } /* Click "New Seatch" button */ if(newSearch) { newSearch.addEventListener('click', (event) => { try { FooterView("NewSearch"); } catch(errNewSearch) { ConsoleLog('error name: ' + errNewSearch.name); ConsoleLog('error message: ' + errNewSearch.messsage); ConsoleLog('error stacktrace: ' + errNewSearch.stack); } }); } if(getJobNewSearch) { getJobNewSearch.addEventListener('click', (event) => { try { // Prevent the default form submission behavior event.preventDefault(); // Get the values of the form fields const JobTitle = document.getElementById('jobTitle').value; const JobDescription = document.getElementById('jobDescription').value; var email = localStorage.getItem("email"); var memberID = localStorage.getItem("memberID"); var auth_token = localStorage.getItem("auth_token"); var hiddenCaptchaValue = document.getElementById('hcv').value; var honeypot = document.getElementById('consent_check'); var MYPEAS_payload = {}; MYPEAS_payload["JobTitle"] = JobTitle; MYPEAS_payload["JobDescription"] = JobDescription; //MYPEAS_payload["promptDescription"] = "Prompt1"; MYPEAS_payload["promptDescription"] = "NewSearch"; //MYPEAS_payload["promptDescription"] = "promptTest"; MYPEAS_payload["registered"] = "true"; // should always be true now that user provides password at start page MYPEAS_payload["email"] = email; MYPEAS_payload["memberID"] = memberID; MYPEAS_payload["auth_token"] = auth_token; // Get the client's time zone const clientTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; MYPEAS_payload["timeZone"] = clientTimeZone; const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // validate fields var failed = false; var validationMessages = []; // validation messages var validateJobTitle = document.getElementById('validateJobTitle'); var validateJobDescription = document.getElementById('validateJobDescription'); var validateCaptcha = document.getElementById('validateCaptcha'); // hide all validation messages validateJobTitle.style.display = 'none'; validateJobTitle.style.color = 'red'; validateJobDescription.style.display = 'none'; validateJobDescription.style.color = 'red'; validateCaptcha.style.display = 'none'; validateCaptcha.style.color = 'red'; if(JobTitle.length < 3) { failed = true; validateJobTitle.textContent = "Job Title is too short"; validateJobTitle.style.display = 'block'; validationMessages.push(validateJobTitle.id); } if(JobDescription.length < 100) { failed = true; validateJobDescription.textContent = "Job Description is too short"; validateJobDescription.style.display = 'block'; validationMessages.push(validateJobDescription.id); } // check for solved captcha /*if(hiddenCaptchaValue == "") { failed = true; validateCaptcha.textContent = "Please confirm you are not a robot!"; validateCaptcha.style.display = 'block'; validationMessages.push(validateCaptcha.id); //document.getElementById('hcv').value }*/ if (honeypot && honeypot.checked) { failed = true; } if(!failed) { // switch to processing UI // hide formcontainer $('#Form-container').hide(); // hide waitlistcontainer $('#waitlist-container').hide(); // hide learn more $('#learn-more-container').hide(); // hide invite launcher $('#invite-launcher').hide(); // show processing containter // add email to processing email field $('#CheckStatusAddress').text(email); $('#processing-container').show(); // hide background video $('.background-video').hide(); $('.background-video-agency').hide(); /*$('.hcv-container').show(); $('#hero-holder').show(); $('#background-image-hero').show(); */ // hide buttons $('#button-box').hide(); ShowProcessing("processing"); // trigger timer attempts = 0; startCheckStatusIntervals(); localStorage.setItem("processStatus", "processing/updating"); // Make an API call to API gateway - return will just indicate that it is processing var apiUrl = 'https://lt8psnfy4f.execute-api.eu-west-1.amazonaws.com/Production/MYPEASGPT'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData), }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("result (object): ", result); // result (object): {"message":"processing"} ConsoleLog("result (stringified): ", JSON.stringify(result)); // "{\"message\":\"processing\"}" var message = result["message"]; switch(message) { case "processing": case "updating": // hide loading and show message to check back // can't do this break; /* Signup */ case "You have a profile currently processing.": /* return { statusCode: 200, body: JSON.stringify({"message": "You have a profile currently processing.", "promptDescription": promptDescription}), }; */ OpenModal("Please Note", "You have a profile currently processing. Until that is complete you cannot request another on this account.", false, false); break; case "You have exceeded your free account profile limit": /* return { statusCode: 200, body: JSON.stringify({"message": "You have exceeded your free account profile limit", "promptDescription": promptDescription}), }; */ OpenModal("Please Note", "You have exceeded your free account profile limit. Please purchase credit to perform more revisions.", false, true); break; case "You have exceeded your paid account profile limit": /* return { statusCode: 200, body: JSON.stringify({"message": "You have exceeded your paid account profile limit", "promptDescription": promptDescription}), }; */ OpenModal("Please Note", "You have exceeded your paid account profile limit. Please purchase credit to perform more revisions.", false, true); break; // tell user to log in case "Account Exists. Wrong Password Entered": /* return { statusCode: 200, body: JSON.stringify({"message": "Account Exists. Wrong Password Entered", "promptDescription": promptDescription}), }; */ OpenModal("Please Note", "You have exceeded your paid account profile limit. Please purchase credit to perform more revisions.", false, true); break; /* Login */ // user is validated case "User Validated": /* return { statusCode: 200, body: JSON.stringify({"message": "User Validated", "promptDescription": promptDescription, "profile": checkUserObj["profile"], "processStatus": checkUserObj["processStatus"]}), }; */ // add useful info to localstorage /* const user = { memberID: items.length > 0 && items[0].hasOwnProperty('memberID') ? items[0].memberID : null, profile: items.length > 0 && items[0].hasOwnProperty('profile') ? items[0].profile : null, processStatus: items.length > 0 && items[0].hasOwnProperty('processStatus') ? items[0].profile : null, registered: items.length > 0 && items[0].hasOwnProperty('registered') ? items[0].registered : null, passwordHash: items.length > 0 && items[0].hasOwnProperty('passwordHash') ? items[0].passwordHash : null, paidAccount: items.length > 0 && items[0].hasOwnProperty('paidAccount') ? items[0].paidAccount : null, revisions: items.length > 0 && items[0].hasOwnProperty('revisions') ? items[0].revisions : 0, mypeasPayload: items.length > 0 && items[0].hasOwnProperty('mypeasPayload') ? items[0].mypeasPayload : null, userExists: items.length > 0, }; */ localStorage.setItem("memberID", result["memberID"]); localStorage.setItem("favourites", checkUserObj["favourites"]); localStorage.setItem("auth_token", result["auth_token"]); localStorage.setItem("auth_token_date_created", result["auth_token_date_created"]); break; // tell user to log in // failed to validate user case "Account Exists. Wrong Password Entered": /* return { statusCode: 200, body: JSON.stringify({"message": "Account Exists. Wrong Password Entered", "promptDescription": promptDescription}), }; */ OpenModal("Problem", "Please check your login details", false, true); break; /* ForgotPassword */ case "Password Changed": /* return { statusCode: 200, body: JSON.stringify({"message": "Password Changed", "promptDescription": promptDescription}), }; */ // update user interface and close loading // clear local storage and cookies localStorage.clear(); // can't delete the cookies, so set their values to expired. so we force UX to require new login // redirect to home page location.href = '/?login=true'; break; /* CheckStatus */ case "ProcessStatus returned": /* return { statusCode: 200, body: JSON.stringify({"message": "ProcessStatus returned", "promptDescription": promptDescription, "processStatus": returnProcessStatus}), }; */ // update processing page var processStatus = result["processStatus"]; switch(processStatus) { case "updating": case "processing": // uses the default content $('#UpdateStatusTextH1').text("AI Profile is still " + processStatus); $('#UpdateStatusTextP1').text("Estimated time: 3 minutes"); $('#UpdateStatusTextP2').text("We will email you when it is ready at " + email); $('#CheckStatusAddress').text(email); // show check status button // hide retry button $('#btnCheckStatus').show(); $('#btnRetry').hide(); // hide cancel button $('#btnCancel').hide(); break; case "complete": case "completed": // display message and use try again button $('#UpdateStatusTextH1').text("AI Profile is Ready"); // hide retry and check status buttons $('#btnCheckStatus').hide(); $('#btnRetry').hide(); /* return { statusCode: 200, body: JSON.stringify({"message": "complete", "promptDescription": promptDescription, "processStatus": returnProcessStatus}), }; */ // redirect to profile // load profile in UI - look into making this all work cleanly setTimeout(function() { LoadExistingProfile(result["profile"]); }, 2000); break; case "failed": // show retry button // hide check status button $('#btnCheckStatus').hide(); $('#btnRetry').show(); // use profile that was returned by failed - if present var profileStored = localStorage.getItem("profile"); if(profileStored && profileStored != "") { // also show cancel button if there is a profile to fall back on $('#btnCancel').show(); var btnRetry = document.getElementById("btnRetry"); btnRetry.addEventListener('click', (event) => { try { // send email back to server to do retry // NEXT: where do i get email from var email = localStorage.getItem("email"); // replace with memberID delivered by checkstatus var memberID = localStorage.getItem("memberID"); var auth_token = localStorage.getItem("auth_token"); // make sure it sends to login if these arent present var MYPEAS_payload = {}; MYPEAS_payload["promptDescription"] = "retry"; MYPEAS_payload["memberID"] = memberID; MYPEAS_payload["auth_token"] = auth_token; const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; requestData["RetryObj"] = {}; //requestData["RetryObj"]["email"] = email; requestData["RetryObj"]["memberID"] = memberID; requestData["RetryObj"]["auth_token"] = auth_token; localStorage.setItem("processStatus", "processing/updating"); // set page to show processing or updating UI // uses the default content $('#UpdateStatusTextH1').text("AI Profile is still " + processStatus); $('#UpdateStatusTextP1').text("Estimated time: 3 minutes"); $('#UpdateStatusTextP2').text("We will email you when it is ready at " + email); $('#CheckStatusAddress').text(email); // show check status button // hide retry button $('#btnCheckStatus').show(); $('#btnRetry').hide(); // Make an API call to API gateway - return will just indicate that it is processing var apiUrl = 'https://lt8psnfy4f.execute-api.eu-west-1.amazonaws.com/Production/MYPEASGPT'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData), }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); // we won't wait for this }); } catch(err) { console.error('Error:', err.message); console.error('Stacktrace:', err.stack); } }); var btnCancel = document.getElementById("btnCancel"); btnCancel.removeEventListener('click', Cancel); btnCancel.addEventListener('click', Cancel); } // display message and use try again button $('#UpdateStatusTextH1').text("AI Profile " + processStatus); $('#UpdateStatusTextP1').text("Your profile encountered a problem and did not complete."); $('#UpdateStatusTextP2').text("Would you like to try again?"); $('#CheckStatusAddress').text(""); // update localstorage break; } break; } }); } if(failed) { // scroll to first error $('html, body').animate({ scrollTop: $('#' + validationMessages[0]).offset().top - 50 }, 500); } } catch(errNewSearch) { ConsoleLog('error name: ' + errNewSearch.name); ConsoleLog('error message: ' + errNewSearch.messsage); ConsoleLog('error stacktrace: ' + errNewSearch.stack); } }); } /* close modal buttons */ // close the modal using the close button $('#modal-popup .close-btn-w').click(function(){ $('#modal-popup').animate({ opacity: 0 }).hide(); unLockScroll(); /*$('.modal-popup').each(function() { if ($(this).is(':visible')) { $(this).animate({ opacity: 0 }).hide(); unLockScroll(); } });*/ /* // close the modal using the close button $('.close-btn-w').click(function(){ $('.modal-popup').each(function() { if ($(this).is(':visible')) { $(this).animate({ opacity: 0 }).hide(); unLockScroll(); } }); }); */ }); // close login modal login-modal $('#login-modal .close-btn-w').click(function(){ $('#login-modal').animate({ opacity: 0 }).hide(); unLockScroll(); /*$('.modal-popup').each(function() { if ($(this).is(':visible')) { $(this).animate({ opacity: 0 }).hide(); unLockScroll(); } });*/ }); // close forgotpassword modal forgot-password-modal $('#forgot-password-modal .close-btn-w').click(function(){ $('#forgot-password-modal').animate({ opacity: 0 }).hide(); unLockScroll(); /* open login modal */ // close button - go back to login modal OpenCloseLoginModal("open"); /*$('.modal-popup').each(function() { if ($(this).is(':visible')) { $(this).animate({ opacity: 0 }).hide(); unLockScroll(); } });*/ }); var btnSubmitLogin = document.getElementById("btnSubmitLogin"); if(btnSubmitLogin) { btnSubmitLogin.addEventListener('click', (event) => { event.preventDefault(); var email = document.getElementById("txtLoginEmail").value.toLowerCase(); var password = document.getElementById("txtLoginPassword").value; if (window.location.href.toLowerCase().includes('/agency')) { SubmitLogin_Agency(email, password); } else if(window.location.href.toLowerCase().includes('/admin')) { SubmitLogin_Admin(email, password); } else { SubmitLogin(email, password); } }); } var ForgotPassword = document.getElementById('ForgotPassword'); if(ForgotPassword) { ForgotPassword.addEventListener('click', (event) => { // show forgotpassword event.preventDefault(); // close the modal using the close button OpenCloseLoginModal("close"); // open forgotpassword modal OpenCloseForgotPasswordModal("open"); }); } var btnSubmitForgotPassword = document.getElementById("btnSubmitForgotPassword"); if(btnSubmitForgotPassword) { if (window.location.href.toLowerCase().includes('/agency')) { btnSubmitForgotPassword.addEventListener('click', (event) => { event.preventDefault(); SubmitForgotPassword_Agency(); }); } else { btnSubmitForgotPassword.addEventListener('click', (event) => { event.preventDefault(); SubmitForgotPassword(); }); } } var btnSubmitResetPassword = document.getElementById("btnResetPassword"); if(btnSubmitResetPassword) { btnSubmitResetPassword.addEventListener('click', (event) => { event.preventDefault(); if (window.location.href.toLowerCase().includes('/agency')) { ResetPassword_Agency(); } else { ResetPassword(); } }); } var btnPurchaseCredits = document.getElementById("btnPurchaseCredit"); if(btnPurchaseCredits) { btnPurchaseCredits.addEventListener('click', (event) => { event.preventDefault(); const currentURL = window.location.href; // Get the current URL // agency if (currentURL.includes("/agency")) { ConsoleLog("The page URL contains '/agency'"); // Do something if /agency is found } else { // customer $('#btnBuyNow').click(); } }); } var btnMyAccount = document.getElementById('btnMyAccount'); if (btnMyAccount) { btnMyAccount.addEventListener('click', (event) => { event.preventDefault(); if (window.location.href.toLowerCase().includes('/agency')) { OpenAccountModal_Agency(); } else { OpenAccountModal(); } }); } var btnMyFavourites = document.getElementById("btnFavourites"); if(btnMyFavourites) { btnMyFavourites.addEventListener('click', (event) => { event.preventDefault(); OpenFavourites(); }); } var btnTools = document.getElementById("btnTools"); if(btnTools) { btnTools.addEventListener('click', (event) => { event.preventDefault(); const baseUrl = window.location.origin; // Get the base URL const newPath = "/app-listing/my-tools"; // Path to add const newUrl = `${baseUrl}${newPath}`; // Combine base URL with the path window.location.href = newUrl; // Navigate to the new URL }); } // close category modal $('#category-modal .close-btn-w').click(function(){ CloseCategoryModal(); }); // close lead gen modal $('#lead-modal .close-btn-w').click(function(){ CloseLeadModal(); }); // close app modal $('#app-modal .close-btn-w').click(function(){ CloseAppModal(); }); // close favourites modal $('#favourites-modal .close-btn-w').click(function(){ CloseFavouritesModal(); }); // close my account modal $('#account-modal .close-btn-w').click(function(){ CloseAccountModal(); }); // close delete-account-modal $('#delete-account-modal .close-btn-w').click(function(){ CloseDeleteModal(); }); // close calendar modal $('#calendar-holder-modal .close-btn-w').click(function(){ CloseCalendarModal(); }); // close document outline $('#generate-document-outline-modal .close-btn-w').click(function(){ CloseDocumentOutlineModal(); }); // copy text button on generate document outline $('#generate-document-outline-modal #copy-document-outline').click(function(){ var document_outline_text = document.getElementById('generatedDocumentStore'); copyHiddenFieldValue(document_outline_text.id); //copyTextFromDiv(document_outline_text); }); // close the modal using the close button $('#new-search-holder .close-btn-w').click(function() { $('#new-search-holder').animate({ opacity: 0 }).hide(); }); var btnNewSearchModal_Submit = document.getElementById("btnGetJob-new"); if(btnNewSearchModal_Submit) { btnNewSearchModal_Submit.addEventListener('click', (event) => { try { // Prevent the default form submission behavior event.preventDefault(); // Get the values of the form fields //var holder = document.querySelector('#new-search-holder'); const JobTitle = document.getElementById('jobTitle-new').value; const JobDescription = document.getElementById('jobDescription-new').value; var email = localStorage.getItem("email"); var memberID = localStorage.getItem("memberID"); var auth_token = localStorage.getItem("auth_token"); var hiddenCaptchaValue = document.getElementById('hcv').value; var honeypot = document.getElementById('consent_check_new'); var MYPEAS_payload = {}; MYPEAS_payload["JobTitle"] = JobTitle; MYPEAS_payload["JobDescription"] = JobDescription; //MYPEAS_payload["promptDescription"] = "Prompt1"; MYPEAS_payload["promptDescription"] = "NewSearch"; //MYPEAS_payload["promptDescription"] = "promptTest"; MYPEAS_payload["registered"] = "true"; // should always be true now that user provides password at start page MYPEAS_payload["email"] = email; MYPEAS_payload["memberID"] = memberID; MYPEAS_payload["auth_token"] = auth_token; // Get the client's time zone const clientTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; MYPEAS_payload["timeZone"] = clientTimeZone; const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // validate fields var failed = false; var validationMessages = []; // validation messages var validateJobTitle = document.getElementById('validateJobTitle-new'); var validateJobDescription = document.getElementById('validateJobDescription-new'); var validateCaptcha = document.getElementById('validateCaptcha-new'); // hide all validation messages validateJobTitle.style.display = 'none'; validateJobTitle.style.color = 'red'; validateJobDescription.style.display = 'none'; validateJobDescription.style.color = 'red'; validateCaptcha.style.display = 'none'; validateCaptcha.style.color = 'red'; if(JobTitle.length < 3) { failed = true; validateJobTitle.textContent = "Job Title is too short"; validateJobTitle.style.display = 'block'; validationMessages.push(validateJobTitle.id); } if(JobDescription.length < 100 && (JobDescription.trim() !== 'Generated by AI' && jobData)) { failed = true; validateJobDescription.textContent = "Job Description is too short"; validateJobDescription.style.display = 'block'; validationMessages.push(validateJobDescription.id); } if(JobDescription.trim() == 'Generated by AI' && jobData) { var GeneratedJobDescription = generatedJobDescription(jobData); // use jobData to create a jobdescription MYPEAS_payload["JobDescription"] = GeneratedJobDescription; } // check for solved captcha /*if(hiddenCaptchaValue == "") { failed = true; validateCaptcha.textContent = "Please confirm you are not a robot!"; validateCaptcha.style.display = 'block'; validationMessages.push(validateCaptcha.id); //document.getElementById('hcv').value }*/ if (honeypot && honeypot.checked) { failed = true; } if(!failed) { // switch to processing UI // hide formcontainer //$('#Form-container').hide(); // hide waitlistcontainer $('#waitlist-container').hide(); // hide invite launcher $('#invite-launcher').hide(); // hide learn more $('#learn-more-container').hide(); $('#segments-and-activities').hide(); // show processing containter // add email to processing email field $('#CheckStatusAddress').text(email); $('#processing-container').show(); // hide background video $('.background-video').hide(); $('.background-video-agency').hide(); $('#hero-holder').show(); $('.hcv-container').show(); $('#background-image-hero').show(); // hide buttons $('#button-box').hide(); // close new search modal OpenCloseNewSearchModal("close"); ShowProcessing("processing"); // trigger timer attempts = 0; startCheckStatusIntervals(); localStorage.setItem("processStatus", "processing/updating"); // Make an API call to API gateway - return will just indicate that it is processing var apiUrl = 'https://lt8psnfy4f.execute-api.eu-west-1.amazonaws.com/Production/MYPEASGPT'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData), }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("result (object): ", result); // result (object): {"message":"processing"} ConsoleLog("result (stringified): ", JSON.stringify(result)); // "{\"message\":\"processing\"}" var message = result["message"]; switch(message) { case "processing": case "updating": // hide loading and show message to check back // can't do this break; /* Signup */ case "You have a profile currently processing.": /* return { statusCode: 200, body: JSON.stringify({"message": "You have a profile currently processing.", "promptDescription": promptDescription}), }; */ OpenModal("Please Note", "You have a profile currently processing. Until that is complete you cannot request another on this account.", false, false); break; case "You have exceeded your free account profile limit": /* return { statusCode: 200, body: JSON.stringify({"message": "You have exceeded your free account profile limit", "promptDescription": promptDescription}), }; */ ProcessingRequestShowUX(); OpenModal("Upgrade", "You have exceeded your free account profile limit. Please purchase credit to perform more revisions.", false, true); break; case "You have exceeded your paid account profile limit": /* return { statusCode: 200, body: JSON.stringify({"message": "You have exceeded your paid account profile limit", "promptDescription": promptDescription}), }; */ ProcessingRequestShowUX(); OpenModal("Upgrade", "You have exceeded your paid account profile limit. Please purchase credit to perform more revisions.", false, true); break; // tell user to log in case "Account Exists. Wrong Password Entered": /* return { statusCode: 200, body: JSON.stringify({"message": "Account Exists. Wrong Password Entered", "promptDescription": promptDescription}), }; */ OpenModal("Problem", "Please check your login details", false, false); break; /* Login */ // user is validated case "User Validated": /* return { statusCode: 200, body: JSON.stringify({"message": "User Validated", "promptDescription": promptDescription, "profile": checkUserObj["profile"], "processStatus": checkUserObj["processStatus"]}), }; */ // add useful info to localstorage /* const user = { memberID: items.length > 0 && items[0].hasOwnProperty('memberID') ? items[0].memberID : null, profile: items.length > 0 && items[0].hasOwnProperty('profile') ? items[0].profile : null, processStatus: items.length > 0 && items[0].hasOwnProperty('processStatus') ? items[0].profile : null, registered: items.length > 0 && items[0].hasOwnProperty('registered') ? items[0].registered : null, passwordHash: items.length > 0 && items[0].hasOwnProperty('passwordHash') ? items[0].passwordHash : null, paidAccount: items.length > 0 && items[0].hasOwnProperty('paidAccount') ? items[0].paidAccount : null, revisions: items.length > 0 && items[0].hasOwnProperty('revisions') ? items[0].revisions : 0, mypeasPayload: items.length > 0 && items[0].hasOwnProperty('mypeasPayload') ? items[0].mypeasPayload : null, userExists: items.length > 0, }; */ localStorage.setItem("memberID", result["memberID"]); localStorage.setItem("auth_token", result["auth_token"]); localStorage.setItem("auth_token_date_created", result["auth_token_date_created"]); break; // tell user to log in // failed to validate user case "Account Exists. Wrong Password Entered": /* return { statusCode: 200, body: JSON.stringify({"message": "Account Exists. Wrong Password Entered", "promptDescription": promptDescription}), }; */ OpenModal("Problem", "Please check your login details", false, false); break; /* ForgotPassword */ case "Password Changed": /* return { statusCode: 200, body: JSON.stringify({"message": "Password Changed", "promptDescription": promptDescription}), }; */ // update user interface and close loading // clear local storage and cookies localStorage.clear(); // can't delete the cookies, so set their values to expired. so we force UX to require new login // redirect to home page location.href = '/?login=true'; break; /* CheckStatus */ case "ProcessStatus returned": /* return { statusCode: 200, body: JSON.stringify({"message": "ProcessStatus returned", "promptDescription": promptDescription, "processStatus": returnProcessStatus}), }; */ // update processing page var processStatus = result["processStatus"]; switch(processStatus) { case "updating": case "processing": // uses the default content $('#UpdateStatusTextH1').text("AI Profile is still " + processStatus); $('#UpdateStatusTextP1').text("Estimated time: 3 minutes"); $('#UpdateStatusTextP2').text("We will email you when it is ready at " + email); $('#CheckStatusAddress').text(email); // show check status button // hide retry button $('#btnCheckStatus').show(); $('#btnRetry').hide(); // hide cancel button $('#btnCancel').hide(); break; case "complete": case "completed": // display message and use try again button $('#UpdateStatusTextH1').text("AI Profile is Ready"); // hide retry and check status buttons $('#btnCheckStatus').hide(); $('#btnRetry').hide(); /* return { statusCode: 200, body: JSON.stringify({"message": "complete", "promptDescription": promptDescription, "processStatus": returnProcessStatus}), }; */ // redirect to profile // load profile in UI - look into making this all work cleanly setTimeout(function() { LoadExistingProfile(result["profile"]); }, 2000); break; case "failed": // show retry button // hide check status button $('#btnCheckStatus').hide(); $('#btnRetry').show(); // use profile that was returned by failed - if present var profileStored = localStorage.getItem("profile"); if(profileStored && profileStored != "") { // also show cancel button if there is a profile to fall back on $('#btnCancel').show(); var btnRetry = document.getElementById("btnRetry"); btnRetry.addEventListener('click', (event) => { try { // send email back to server to do retry // NEXT: where do i get email from var email = localStorage.getItem("email"); // replace with memberID delivered by checkstatus var memberID = localStorage.getItem("memberID"); var auth_token = localStorage.getItem("auth_token"); // make sure it sends to login if these arent present var MYPEAS_payload = {}; MYPEAS_payload["promptDescription"] = "retry"; MYPEAS_payload["memberID"] = memberID; MYPEAS_payload["auth_token"] = auth_token; const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; requestData["RetryObj"] = {}; //requestData["RetryObj"]["email"] = email; requestData["RetryObj"]["memberID"] = memberID; requestData["RetryObj"]["auth_token"] = auth_token; localStorage.setItem("processStatus", "processing/updating"); // set page to show processing or updating UI // uses the default content $('#UpdateStatusTextH1').text("AI Profile is still " + processStatus); $('#UpdateStatusTextP1').text("Estimated time: 3 minutes"); $('#UpdateStatusTextP2').text("We will email you when it is ready at " + email); $('#CheckStatusAddress').text(email); // show check status button // hide retry button $('#btnCheckStatus').show(); $('#btnRetry').hide(); // Make an API call to API gateway - return will just indicate that it is processing var apiUrl = 'https://lt8psnfy4f.execute-api.eu-west-1.amazonaws.com/Production/MYPEASGPT'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData), }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); // we won't wait for this }); } catch(err) { console.error('Error:', err.message); console.error('Stacktrace:', err.stack); } }); var btnCancel = document.getElementById("btnCancel"); btnCancel.removeEventListener('click', Cancel); btnCancel.addEventListener('click', Cancel); } // display message and use try again button $('#UpdateStatusTextH1').text("AI Profile " + processStatus); $('#UpdateStatusTextP1').text("Your profile encountered a problem and did not complete."); $('#UpdateStatusTextP2').text("Would you like to try again?"); $('#CheckStatusAddress').text(""); // update localstorage break; } break; } var resultObj = tryParse(result); }); } if(failed) { // scroll to first error $('html, body').animate({ scrollTop: $('#' + validationMessages[0]).offset().top - 50 }, 500); } } catch(errNewSearch) { ConsoleLog('error name: ' + errNewSearch.name); ConsoleLog('error message: ' + errNewSearch.messsage); ConsoleLog('error stacktrace: ' + errNewSearch.stack); } }); } var btnAgencySignup = document.getElementById("btnAgencySignup"); if(btnAgencySignup) { btnAgencySignup.addEventListener('click', (event) => { // Always start new search fresh ClearStorage(); // Prevent the default form submission behavior event.preventDefault(); // Get the values of the form fields const agentFirstName = document.getElementById('agent-first-name').value; const agentSurname = document.getElementById('agent-surname').value; const agentCompanyName = document.getElementById('agent-company-name').value; const agentWorkEmail = document.getElementById('agent-work-email').value; const agentPassword = document.getElementById('agent-password').value; var formContainer = document.getElementById('Form-container'); var agentPhoneCode = formContainer.querySelector('#countryCode').value; var agentPhoneNo = formContainer.querySelector('#telephone').value; var agentLocationCode = formContainer.querySelector('#countrySelect').value; var agentLocationName = $('#Form-container #countrySelect option:selected').text(); var hiddenCaptchaValue = document.getElementById('hcv').value; var MYPEAS_payload = {}; MYPEAS_payload["requestDescription"] = "Signup"; MYPEAS_payload["FirstName"] = agentFirstName; MYPEAS_payload["Surname"] = agentSurname; MYPEAS_payload["CompanyName"] = agentCompanyName; MYPEAS_payload["WorkEmail"] = agentWorkEmail; MYPEAS_payload["email"] = agentWorkEmail; MYPEAS_payload["Password"] = agentPassword; MYPEAS_payload["password"] = agentPassword; // Get the client's time zone const clientTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; MYPEAS_payload["timeZone"] = clientTimeZone; MYPEAS_payload["Location"] = {"locationName": agentLocationName, "locationCode": agentLocationCode}; MYPEAS_payload["TelephoneCode"] = agentPhoneCode; MYPEAS_payload["TelephoneNo"] = agentPhoneNo; const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // Validate fields var failed = false; var validationMessages = []; // Validation messages var validateAgentFirstName = document.getElementById('validateAgentFirstName'); var validateAgentSurname = document.getElementById('validateAgentSurname'); var validateAgentCompanyName = document.getElementById('validateAgentCompanyName'); var validateAgentWorkEmail = document.getElementById('validateAgentWorkEmail'); var validateAgentPassword = document.getElementById('validateAgentPassword'); var validatePhoneCode = document.getElementById('validateAgentTelephoneCode'); var validatePhoneNo = document.getElementById('validateAgentWorkTelephone'); var validateLocation = document.getElementById('validateAgentLocation'); // Hide all validation messages validateAgentFirstName.style.display = 'none'; validateAgentFirstName.style.color = 'red'; validateAgentSurname.style.display = 'none'; validateAgentSurname.style.color = 'red'; validateAgentCompanyName.style.display = 'none'; validateAgentCompanyName.style.color = 'red'; validateAgentWorkEmail.style.display = 'none'; validateAgentWorkEmail.style.color = 'red'; validateAgentPassword.style.display = 'none'; validateAgentPassword.style.color = 'red'; validatePhoneCode.style.display = 'none'; validatePhoneCode.style.color = 'red'; validatePhoneNo.style.display = 'none'; validatePhoneNo.style.color = 'red'; validateLocation.style.display = 'none'; validateLocation.style.color = 'red'; if (agentFirstName.length === 0) { failed = true; validateAgentFirstName.textContent = "First Name is required"; validateAgentFirstName.style.display = 'block'; validationMessages.push(validateAgentFirstName.id); } if (agentSurname.length === 0) { failed = true; validateAgentSurname.textContent = "Surname is required"; validateAgentSurname.style.display = 'block'; validationMessages.push(validateAgentSurname.id); } if (agentCompanyName.length === 0) { failed = true; validateAgentCompanyName.textContent = "Company Name is required"; validateAgentCompanyName.style.display = 'block'; validationMessages.push(validateAgentCompanyName.id); } if (!isValidEmail(agentWorkEmail)) { failed = true; validateAgentWorkEmail.textContent = "Please enter a valid email"; validateAgentWorkEmail.style.display = 'block'; validationMessages.push(validateAgentWorkEmail.id); } if (!isValidPassword(agentPassword)) { failed = true; validateAgentPassword.textContent = "Minimum length of 8 characters, contains at least one uppercase letter, one lowercase letter, one number, and one special character"; validateAgentPassword.style.display = 'block'; validationMessages.push(validateAgentPassword.id); } var nameRegex = /^[A-Za-z\s\-]+$/; // Regex to allow letters, spaces, and hyphens // validate location var locationName = $('#Form-container #countrySelect option:selected').text(); var locationCode = $('#Form-container #countrySelect').val(); if(locationName.trim() == "" || locationCode.trim() == "" ) { failed = true; validateLocation.style.display = 'block'; validationMessages.push(validateLocation.id); } // validate phone // validate country code if (!agentPhoneCode.trim()) { validatePhoneCode.textContent = 'Country Code is required'; validatePhoneCode.style.display = 'block'; failed = true; validationMessages.push(validatePhoneCode.id); } else { validatePhoneCode.style.display = 'none'; } // Validate Telephone if (!agentPhoneCode.trim()) { validatePhoneCode.textContent = 'Country Code is required'; validatePhoneCode.style.display = 'block'; failed = true; validationMessages.push(validatePhoneCode.id); } else { validatePhoneCode.style.display = 'none'; } // Validate Telephone if (!agentPhoneNo.trim()) { validatePhoneNo.textContent = 'Telephone is required.'; validatePhoneNo.style.display = 'block'; failed = true; validationMessages.push(validatePhoneNo.id); } else if (agentPhoneCode.trim() === "+44" && agentPhoneNo.trim().length < 11) { validatePhoneNo.textContent = 'Telephone number must be at least 11 digits for +44 country code.'; validatePhoneNo.style.display = 'block'; failed = true; validationMessages.push(validatePhoneNo.id); } else { validatePhoneNo.style.display = 'none'; } // If validation fails, do something (e.g., prevent form submission, show error messages) if (failed) { ConsoleLog("Validation failed:", validationMessages); // scroll to first error $('html, body').animate({ scrollTop: $('#' + validationMessages[0]).offset().top - 50 }, 500); } if(!failed) { // submit to server $('#main-content').hide(); $('#main-spinner').show(); // show hero image $('.background-video').hide(); $('.background-video-agency').hide(); // hide buttons $('#button-box').hide(); // Make an API call to API gateway - return will just indicate that it is processing var apiUrl = 'https://v2tu3f9o1e.execute-api.eu-west-1.amazonaws.com/AgencyStage/Agency'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData), }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("result (object): ", result); // result (object): {"message":"processing"} ConsoleLog("result (stringified): ", JSON.stringify(result)); // "{\"message\":\"processing\"}" var message = result["message"]; switch(message) { /* Login */ // user is validated case "Account Created": case "User Validated": /* return { statusCode: 200, body: JSON.stringify({"message": "User Validated", "promptDescription": promptDescription, "profile": checkUserObj["profile"], "processStatus": checkUserObj["processStatus"]}), }; */ // add useful info to localstorage /* const user = { memberID: items.length > 0 && items[0].hasOwnProperty('memberID') ? items[0].memberID.S : null, emailAddress: items.length > 0 && items[0].hasOwnProperty('emailAddress') ? items[0].emailAddress.S : null, accountInfo: items.length > 0 && items[0].hasOwnProperty('accountInfo') ? items[0].accountInfo.S : null, auth_token: items.length > 0 && items[0].hasOwnProperty('auth_token') ? items[0].auth_token.S : null, auth_token_date_created: items.length > 0 && items[0].hasOwnProperty('auth_token_date_created') ? items[0].auth_token_date_created.S : null, passwordHash: items.length > 0 && items[0].hasOwnProperty('passwordHash') ? items[0].passwordHash.S : null, passwordSalt: items.length > 0 && items[0].hasOwnProperty('passwordSalt') ? items[0].passwordSalt.S : null, credits: items.length > 0 && items[0].hasOwnProperty('revisions') ? items[0].revisions.S : 0, orderHistory: items.length > 0 && items[0].hasOwnProperty('orderHistory') ? items[0].orderHistory.S : null, userExists: items.length > 0, }; */ /* result (stringified): {"message":"Account Created","memberID":"PwamvyxRR0","auth_token":"9yMgGqNqWA","auth_token_date_created":"2024-07-15T14:46:46.523Z","accountInfo":"{\"requestDescription\":\"Signup\",\"memberID\":\"PwamvyxRR0\",\"FirstName\":\"Ade\",\"Surname\":\"Molajo\",\"CompanyName\":\"Flex Luthor Limited\",\"WorkEmail\":\"ademolajo@gmail.com\",\"Password\":\"Mypeasbola27!\",\"Location\":{\"locationName\":\"United Kingdom\",\"locationCode\":\"GB\"},\"TelephoneCode\":\"+44\",\"TelephoneNo\":\"07738715181\",\"referralCode\":\"PwamvyxRR0\",\"bookingAccountId\":\"98cb9584-dfe2-4b80-95fa-9722bdee8e7c\",\"bookingAccountPw\":\"oJJSHnhN3zuY\",\"bookingLink\":\"https://luthorflex-2.youcanbook.me\",\"ApprovedStatus\":\"processing\"}","orderHistory":"","credits":"0"} */ localStorage.setItem("memberID", result["memberID"]); localStorage.setItem("credits", result["credits"]); localStorage.setItem("accountInfo", result["accountInfo"]); localStorage.setItem("orderHistory", result["orderHistory"]); localStorage.setItem("StripeInvoices", result["StripeInvoices"] || "[]"); localStorage.setItem("auth_token", result["auth_token"]); localStorage.setItem("auth_token_date_created", result["auth_token_date_created"]); localStorage.setItem("agencyMember", true); // HIDE PRELOAD HidePreLoad(); // format UX for Agency dashboard // hide formcontainer $('#Form-container').hide(); // hide waitlistcontainer $('#waitlist-container').hide(); // hide learn more $('#learn-more-container').hide(); // hide invite launcher $('#invite-launcher').hide(); $('#main-content').show(); $('#main-spinner').hide(); // hide background video - show hero image $('.background-video').hide(); $('.background-video-agency').hide(); $('#hero-holder').show(); $('.hcv-container').show(); $('#background-image-hero').show(); // hide buttons $('#button-box').hide(); // change buttons in navbar // show nav buttons ShowNavButtons_Agency(); $(btnLogInOut).text("Log Out"); /// populate dashboard fields // show dashboard fields $('.agency-account-info-holder').show(); // load agency member profile in UI LoadAgencyAccount(result["accountInfo"], result); // hide background video - show hero image $('.background-video').hide(); $('.background-video-agency').hide(); break; // tell user to log in // failed to validate user case "Account Exists. Wrong Password Entered": /* return { statusCode: 200, body: JSON.stringify({"message": "Account Exists. Wrong Password Entered", "promptDescription": promptDescription}), }; */ // HIDE PRELOAD HidePreLoad(); // reset visibility $('#main-content').show(); $('#main-spinner').hide(); // show video $('.background-video').show(); $('.background-video-agency').show(); // show buttons $('#button-box').show(); OpenModal("Problem", "Account Already Exists. Please check your login details", false, true); break; case "Account Creation Failed": /* return { statusCode: 200, body: JSON.stringify({"message": "Account Creation Failed"}), }; */ // HIDE PRELOAD HidePreLoad(); // reset visibility $('#main-content').show(); $('#main-spinner').hide(); // show video $('.background-video').show(); $('.background-video-agency').show(); // show buttons $('#button-box').show(); OpenModal("Problem", "Account Creation Failed, Please Try Again Later", false, true); break; } }); // load agency dashboard // id=agency-account-info-holder } // If validation passes, proceed with form submission or other actions ConsoleLog("Validation passed. Submitting form..."); }); } // add lead gen slider events var slider = document.getElementById('budgetSlider'); var output = document.getElementById('budgetDisplay'); // Update the display value when the slider is moved if(slider) { slider.oninput = function() { output.innerHTML = '£' + parseInt(this.value).toLocaleString('en-GB'); }; // Initial call to start the questionnaire showNext('q1'); } var AddCalendarBtn = document.getElementById("addCalendar"); if(AddCalendarBtn) { AddCalendarBtn.addEventListener('click', (event) => { //var url = 'https://app.youcanbook.me/'; window.open(url, '_blank').focus(); // show loading spinner $('#calendar-spinner').show(); var calendarMessage = ""; // hide message $('#calendar-message').text(calendarMessage).hide(); // check url has 200 status code var calendlyLink = $('#calendly-link').val(); // send to server $('#calendar-message').text(calendarMessage).hide(); // NEXT: where do i get email from var email = localStorage.getItem("email"); // replace with memberID delivered by checkstatus var memberID = localStorage.getItem("memberID"); var auth_token = localStorage.getItem("auth_token"); // make sure it sends to login if these arent present var MYPEAS_payload = {}; MYPEAS_payload["requestDescription"] = "AddCalendarLink"; MYPEAS_payload["memberID"] = memberID; MYPEAS_payload["auth_token"] = auth_token; MYPEAS_payload["bookingLink"] = calendlyLink; MYPEAS_payload["bookingType"] = "Calendly"; const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; requestData["AddCalendarObj"] = {}; requestData["AddCalendarObj"]["memberID"] = memberID; requestData["AddCalendarObj"]["auth_token"] = auth_token; requestData["AddCalendarObj"]["bookingLink"] = calendlyLink; requestData["AddCalendarObj"]["bookingType"] = "Calendly"; // send to server and store // submit to server // Make an API call to API gateway - return will just indicate that it is processing var apiUrl = 'https://v2tu3f9o1e.execute-api.eu-west-1.amazonaws.com/AgencyStage/Agency'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData), }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("result (object): ", result); // result (object): {"message":"processing"} ConsoleLog("result (stringified): ", JSON.stringify(result)); // "{\"message\":\"processing\"}" var message = result["message"]; // hide spinner $('#calendar-spinner').hide(); switch(message) { case "Calendar Added": // set message calendarMessage = "Calendly Link Updated"; $('#calendar-message').text(calendarMessage).show(); var accountInfo = result["accountInfo"]; // set link in localstorage localStorage.setItem("accountInfo", accountInfo); break; case "No Calendar Found": // set message calendarMessage = "Calendly Link Not Valid"; $('#calendar-message').text(calendarMessage).show(); // set link in localstorage break; default: // set message calendarMessage = "Calendly Link Update Failed"; $('#calendar-message').text(calendarMessage).show(); break; } }) .catch(error => { console.error("Error calling AddCalendarLink: ", error); // hide spinner $('#calendar-spinner').hide(); // set message calendarMessage = "Calendly Link Update Failed"; $('#calendar-message').text(calendarMessage).show(); }); }); } // close the agency account modal using the close button $('#agency-account-modal .close-btn-w').click(function() { CloseModal_Agency_Account(); }); var upgradeProBtn = document.getElementById("btnUpgradePro"); var upgradeProPlusBtn = document.getElementById("btnUpgradeProPlus"); var upgradeProButtons = document.querySelectorAll("#btnUpgradePro"); // Get all buttons with the class upgradeProButtons.forEach(button => { button.addEventListener('click', (event) => { event.preventDefault(); const currentURL = window.location.href; // Get the current URL // agency if (currentURL.includes("/agency")) { ConsoleLog("The page URL contains '/agency'"); // Do something if /agency is found } else { // customer //$('#btnBuyNow').click(); // this is for webflow //document.getElementById('btnBuyNow').click(); } }); }); var upgradeProPlusButtons = document.querySelectorAll("#btnUpgradeProPlus"); upgradeProPlusButtons.forEach(button => { button.addEventListener('click', (event) => { // Prevent the default form submission behavior event.preventDefault(); const currentURL = window.location.href; // Get the current URL // agency if (currentURL.includes("/agency")) { ConsoleLog("The page URL contains '/agency'"); // Do something if /agency is found } else { // customer //$('#btnBuyNow').click(); //document.getElementById('btnBuyNow_Plus').click(); } }); }); /* close checkout confirmation */ $('#loading-update-modal .close-btn-w').click(function(){ $('#loading-update-modal').animate({ opacity: 0 }).hide(); unLockScroll(); }); $('#reset-password-modal .close-btn-w').click(function(){ OpenCloseResetPasswordModal("close"); }); /* admin close modal */ $('#approve-modal .close-btn-w').click(function(){ $('#approve-modal').animate({ opacity: 0 }).hide(); unLockScroll(); }); /*$('#launch-invite-moda-access').hide(); $('#already-commented-link').hide();*/ /* $('#launch-invite-moda-access').click(function(){ }); */ $('#already-commented-link').click(function(){ // show access code var accessCode = localStorage.getItem("accessCode"); if(!accessCode) { accessCode = generateRandomString(8); } $('#linkedin-modal #accessCode').val(accessCode); $('#skipwaitlist-container #accessCode').val(accessCode); $('#linkedin-modal #accessCodeHolder').show(); localStorage.setItem("accessCode", accessCode); // hide linkedin button $('#linkedin-modal #goToLinkedinHolder').hide(); // hide 'i have an access code' $('#linkedin-modal #launch-invite-moda-access').hide(); // hide already added $('#linkedin-modal #already-commented-link').hide(); // hide waitlist advice text $('#list-counter-popup').hide(); $('#linkedin-message').hide(); }); /*$('#launch-invite-moda-access').click(function(){ // open // show access code var accessCode = localStorage.getItem("accessCode"); if(!accessCode) { accessCode = generateRandomString(8); } $('#linkedin-modal #accessCode').val(accessCode); $('#skipwaitlist-container #accessCode').val(accessCode); $('#linkedin-modal #accessCodeHolder').show(); localStorage.setItem("accessCode", accessCode); // hide linkedin button $('#linkedin-modal #goToLinkedinHolder').hide(); }); */ $('#info-modal .close-btn-w').click(function(){ CloseInfoModal(); }); // hide HITL modal $('#HITL-modal .close-btn-w').click(function(){ $('#HITL-modal').animate({ opacity: 0 }).hide(); }); $('#assumptions-modal .close-btn-w').click(function(){ $('#assumptions-modal').animate({ opacity: 0 }).hide(); }); $('#n8n-info-modal .close-btn-w').click(function(){ $('#n8n-info-modal').animate({ opacity: 0 }).hide(); }); } catch(err) { ConsoleLog('error name: ' + err.name); ConsoleLog('error message: ' + err.messsage); ConsoleLog('error stacktrace: ' + err.stack); // reset changes // re-enable these fields SearchJobEnable(true); // clear all loading screens LoaderView(false); CancelSimulateGPT(); } } function copyTextFromDiv(divId) { const div = document.getElementById(divId); // Create a temporary textarea to hold the text const tempTextArea = document.createElement('textarea'); tempTextArea.value = div.textContent; document.body.appendChild(tempTextArea); // Select the text and copy tempTextArea.select(); tempTextArea.setSelectionRange(0, 99999); // For large text navigator.clipboard.writeText(tempTextArea.value) .then(() => { alert('Text copied to clipboard!'); }) .catch(err => { console.error('Error copying text: ', err); }); // Clean up document.body.removeChild(tempTextArea); } function lockScroll(){ setTimeout(function () { let scrollPosition = []; let marginB; let marginR; var $html = $('html'); var $body = $('body'); let initWidth = $body.outerWidth(); let initHeight = $body.outerHeight(); scrollPosition = [ self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft, self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop ]; $html.css('overflow', 'hidden'); window.scrollTo(scrollPosition[0], scrollPosition[1]); marginR = $body.outerWidth()-initWidth; marginB = $body.outerHeight()-initHeight; $body.css({'margin-right': marginR,'margin-bottom': marginB}); }, 10); } function unLockScroll(){ setTimeout(function () { let scrollPosition = []; let marginB; let marginR; var $html = $('html'); var $body = $('body'); $html.css('overflow', 'initial'); //window.scrollTo(scrollPosition[0], scrollPosition[1]); $body.css({'margin-right': 0, 'margin-bottom': 0}); }, 10); } function isValidEmail(email) { const regex = /^(([^<>()[\]\\.,;:\s@\"]+)(\.[^<>()[\]\\.,;:\s@\"]+)*)@(([^<>()[\]\\.,;:\s@\"]+)\.)+(([^<>()[\]\\.,;:\s@\"]{1,6})|([^\s]{2,}))$/; return regex.test(email); } function isValidPassword(password) { const hasMinimumLength = password.length >= 8; const hasUpperCaseLetter = /[A-Z]/.test(password); const hasLowerCaseLetter = /[a-z]/.test(password); const hasDigit = /[0-9]/.test(password); const hasSpecialCharacter = /[^a-zA-Z0-9]/.test(password); const isValid = hasMinimumLength && hasUpperCaseLetter && hasLowerCaseLetter && hasDigit && hasSpecialCharacter; return isValid; } function consentChecked(checkbox) { //const checkbox = document.getElementById('checkbox_email'); if (checkbox.checked) { ConsoleLog('The consent checkbox is checked.'); } else { ConsoleLog('The consent checkbox is not checked.'); } return checkbox.checked; } function isEmptyObject(obj) { return Object.keys(obj).length === 0; } function ShowPreLoad() { // hide nav buttons var btnMyAccount = document.getElementById('btnMyAccount'); var btnMyFavourites = document.getElementById("btnFavourites"); var btnLogInOut = document.getElementById("btnLogInOut"); var btnTools = document.getElementById('btnTools'); // Set the display CSS property to none to hide them if (btnMyAccount) btnMyAccount.style.display = 'none'; if (btnMyFavourites) btnMyFavourites.style.display = 'none'; if (btnLogInOut) btnLogInOut.style.display = 'none'; if (btnTools) { btnTools.style.display = 'none'; //btnTools.style.display = 'inline'; // Makes it visible and inline //btnTools.style.maxWidth = '940px'; // Sets the max width to 940px } //hide page content var bgVideo = document.getElementById('background-video'); var mainContent = document.getElementById('main-content'); if (bgVideo) bgVideo.style.display = 'none'; if (mainContent) mainContent.style.display = 'none'; // show spinner var mainSpinner = document.getElementById('main-spinner'); if(mainSpinner) mainSpinner.style.display = 'block'; } function HidePreLoad() { //hide page content var bgVideo = document.getElementById('background-video'); var mainContent = document.getElementById('main-content'); if (bgVideo) bgVideo.style.display = 'block'; if (mainContent) mainContent.style.display = 'block'; // show spinner var mainSpinner = document.getElementById('main-spinner'); if(mainSpinner) mainSpinner.style.display = 'none'; // if agency page give them the buttons back if(window.location.href.toLowerCase().includes('/agency')) { var isUserLoggedIn = checkLoggedIn(); switch(isUserLoggedIn) { case true: var btnMyAccount = document.getElementById('btnMyAccount'); var btnLogInOut = document.getElementById("btnLogInOut"); if(btnMyAccount) btnMyAccount.style.display = 'block'; if(btnLogInOut) btnLogInOut.style.display = 'block'; break; case false: var btnLogInOut = document.getElementById("btnLogInOut"); if(btnLogInOut) btnLogInOut.style.display = 'block'; break; } } } function ShowNavButtons() { var btnMyAccount = document.getElementById('btnMyAccount'); var btnMyFavourites = document.getElementById("btnFavourites"); var btnLogInOut = document.getElementById("btnLogInOut"); var btnTools = document.getElementById('btnTools'); if (btnMyAccount) btnMyAccount.style.display = 'block'; if (btnMyFavourites) btnMyFavourites.style.display = 'block'; if (btnLogInOut) btnLogInOut.style.display = 'block'; if (btnTools) { btnTools.style.display = 'block'; //btnTools.style.display = 'inline'; // Makes it visible and inline //btnTools.style.maxWidth = '940px'; // Sets the max width to 940px } } function ShowNavButtons_Agency() { var btnMyAccount = document.getElementById('btnMyAccount'); var btnLogInOut = document.getElementById("btnLogInOut"); if (btnMyAccount) btnMyAccount.style.display = 'block'; if (btnLogInOut) btnLogInOut.style.display = 'block'; } function HideNavButtons() { var btnMyAccount = document.getElementById('btnMyAccount'); var btnMyFavourites = document.getElementById("btnFavourites"); var btnLogInOut = document.getElementById("btnLogInOut"); var btnAgency = document.getElementById("btnAgency"); var btnTools = document.getElementById("btnTools"); if (btnMyAccount) btnMyAccount.style.display = 'none'; if (btnMyFavourites) btnMyFavourites.style.display = 'none'; if (btnLogInOut) btnLogInOut.style.display = 'none'; if (btnAgency) btnAgency.style.display = 'none'; if (btnTools) btnTools.style.display = 'none'; } function CheckStart() { // check if logged in // localstorage var agencyMember = localStorage.getItem("agencyMember") || null; var adminMember = localStorage.getItem("adminMember") || null; var isUserLoggedIn = checkLoggedIn(); var btnAgency = document.getElementById('btnAgency'); var btnMyAccount = document.getElementById('btnMyAccount'); var btnMyFavourites = document.getElementById("btnFavourites"); var btnLogInOut = document.getElementById("btnLogInOut"); var btnTools = document.getElementById("btnTools"); var btnAgencySignup = document.getElementById("btnAgencySignup"); var containerWaitList = document.getElementById('waitlist-container'); var skipContainer = document.getElementById('skipwaitlist-container'); var bookingPage = isBookingPage(); var adminPage = isAdminPage(); var mainContent = document.getElementById("main-content"); var bookingContent = document.getElementById("Booking-Content"); var backgroundVideo = document.getElementById("background-video"); var linkedinModal = document.getElementById("linkedin-modal"); var codeGeneratorContainer = document.getElementById('admin-account-code-generator'); var sendRecruitAgencyContainer = document.getElementById("admin-account-send-email"); if(bookingPage) { // hide agency and login buttons in nav bar $(btnLogInOut).hide(); $(btnAgency).hide(); // hide main-content $(mainContent).hide(); // hide background video $(backgroundVideo).hide(); // show booking-content $(bookingContent).show(); // hide linkedin-modal $(linkedinModal).hide(); // load calendly embed var embedURL = getParameterByName('calLink'); if (embedURL) { embedURL = addParameterToURL(embedURL, "embed_domain", window.location.host); //embedURL = addParameterToURL(embedURL, "embed_domain", "example.com"); embedURL = addParameterToURL(embedURL, "embed_type", "Inline"); // Ensure the Calendly script is loaded before calling Calendly.initInlineWidget window.addEventListener('load', () => { const container = document.getElementById('Booking-Holder'); Calendly.initInlineWidget({ url: embedURL, parentElement: container, resize: true, prefill: {}, utm: {} }); // hide spinner in 5 seconds if still visible var mainSpinner = document.getElementById('main-spinner'); setTimeout(function(){if(mainSpinner) mainSpinner.style.display = 'none'; console.log('timed out spinner');}, 5000); window.addEventListener("message", function(e) { if (isCalendlyEvent(e)) { const eventName = e.data.event; const eventDetails = e.data.payload; switch (eventName) { case 'calendly.profile_page_viewed': console.log('Profile page viewed'); break; case 'calendly.event_type_viewed': console.log('Event type page viewed'); console.log('cancelled spinner'); // hide the spinner if(mainSpinner) mainSpinner.style.display = 'none'; break; case 'calendly.date_and_time_selected': console.log('Date and time selected'); break; case 'calendly.event_scheduled': console.log('Booking completed:', eventDetails); //alert('Booking confirmed!'); // Display an alert // send to server const requestData = {}; requestData["MYPEAS_payload"] = {}; // identifies the agency requestData["MYPEAS_payload"]["AGENCYCODE"] = GetParam("agencyID"); // identifies the user requestData["MYPEAS_payload"]["MEMBERID"] = GetParam("memberID"); requestData["MYPEAS_payload"]["requestDescription"] = "ConfirmBooking"; // send request to store booking info on server // Make an API call to API gateway var apiUrl = 'https://v2tu3f9o1e.execute-api.eu-west-1.amazonaws.com/AgencyStage/Agency'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData) }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("Send Booking Link return: ",JSON.stringify(result)); var message = result["message"]; switch(message) { case "Agency Found and updated": console.log("booking stored"); // update requests in local storage break; case "Agency Not Found (ConfirmBooking Failed)": console.log("booking NOT stored"); break; } }); break; default: console.log('Unknown Calendly event:', eventName); } } }); }); console.log("set all listeners"); } else { console.error('No "calLink" parameter found in the URL.'); } } if(adminPage) { if(isUserLoggedIn) { $(btnAgency).hide(); $(btnLogInOut).text("Log Out"); var storedMemberID = localStorage.getItem("memberID"); var storedAuthToken = localStorage.getItem("auth_token"); // request profile var MYPEAS_payload = {}; MYPEAS_payload["requestDescription"] = "LoginAdmin"; MYPEAS_payload["registered"] = "true"; // should always be true now that user provides password at start page MYPEAS_payload["memberID"] = storedMemberID; // get from storage MYPEAS_payload["auth_token"] = storedAuthToken; // get from storage const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // send request to checkstatus on website // Make an API call to API gateway var apiUrl = 'https://v2tu3f9o1e.execute-api.eu-west-1.amazonaws.com/AgencyStage/Agency'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData) }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("login status return: ",JSON.stringify(result)); HidePreLoad(); /*return { statusCode: 200, body: JSON.stringify({"message": "Profile Found", "promptDescription": promptDescription, "profile": checkUserObj["profile"], "processStatus": checkUserObj["processStatus"]}), }; */ var processStatus = result["message"]; switch(processStatus) { case "validated": // if completed and not empty - load profile in UI var memberID = result["memberID"]; var authToken = result["auth_token"]; var auth_token_date_created = result["auth_token_date_created"]; var approvalsData = result["approvalData"]; // set memberID localStorage.setItem("memberID", memberID); // set auth_token localStorage.setItem("auth_token", authToken); localStorage.setItem("auth_token_date_created", auth_token_date_created); localStorage.setItem("adminMember", "true"); // show the nav buttons var btnLogInOut = document.getElementById("btnLogInOut"); var btnAgency = document.getElementById("btnAgency"); var containerWaitList = document.getElementById('waitlist-container'); var skipContainer = document.getElementById('skipwaitlist-container'); var promptLogin = document.getElementById('admin-prompt-login'); $(btnLogInOut).show(); $(btnAgency).hide(); $(btnLogInOut).text("Log Out"); $(containerWaitList).hide(); $(skipContainer).hide(); $(codeGeneratorContainer).show(); $(sendRecruitAgencyContainer).show(); // populate the cards // load approvals LoadApprovals(approvalsData); // close modal OpenCloseLoginModal("close"); // hide prompt login $(promptLogin).hide(); removeParam("login"); break; case "rejected": case "notauthenticated": case "failed": // require login // clear local storage and cookies localStorage.clear(); // can't delete the cookies, so set their values to expired. so we force UX to require new login // redirect to home page location.href = '/admin?login=true'; break; } }); } if(!isUserLoggedIn) { HidePreLoad(); $(btnMyAccount).hide(); $(btnMyFavourites).hide(); $(btnTools).hide(); $(btnLogInOut).show(); $(btnAgency).show(); $(btnLogInOut).text("Log In"); } } if(!bookingPage && !adminPage) { // main user website if(!agencyMember && !window.location.href.toLowerCase().includes('/agency')) { if(isUserLoggedIn) { $('#linkedin-modal').hide(); $(btnMyAccount).show(); $(btnMyFavourites).show(); $(btnTools).show(); $(btnLogInOut).show(); $(btnAgency).hide(); $(btnLogInOut).text("Log Out"); $(containerWaitList).hide(); $(skipContainer).hide(); // check if return from product purchase // On page load - check URL const urlParams = new URLSearchParams(window.location.search); const sessionId = urlParams.get('session_id'); // cs_abc123 const isSuccess = urlParams.get('success'); // true if (sessionId && isSuccess === 'true') { // Start polling - check every 2 seconds pollForOrderCompletion(sessionId, 'check-order-status'); } else { var storedProcessStatus = localStorage.getItem("processStatus"); var queryStringContainsProcessing = false; const queryString = window.location.search; const keyValue = 'processStatus=processing'; // Replace with your actual key-value pair var keyValues = ['processStatus=processing', 'processStatus=updating']; for(var x = 0; x < keyValues.length; x++) { if (queryString.includes(keyValues[x])) { queryStringContainsProcessing = true; break; } } // processing/updating/failed if(storedProcessStatus == "processing/updating" || storedProcessStatus == "processing" || storedProcessStatus == "updating" || storedProcessStatus == "failed" || queryStringContainsProcessing) { // THIS SAYS STATUS NOT START CheckStatus(); } // not processing - check server for completed profile - if failed show retry if(!(storedProcessStatus == "processing/updating" || storedProcessStatus == "processing" || storedProcessStatus == "updating" || storedProcessStatus == "failed" || queryStringContainsProcessing)) { var storedMemberID = localStorage.getItem("memberID"); var storedAuthToken = localStorage.getItem("auth_token"); // request profile var MYPEAS_payload = {}; MYPEAS_payload["JobTitle"] = ""; MYPEAS_payload["JobDescription"] = ""; MYPEAS_payload["promptDescription"] = "RequestProfile"; MYPEAS_payload["registered"] = "true"; // should always be true now that user provides password at start page MYPEAS_payload["memberID"] = storedMemberID; // get from storage MYPEAS_payload["auth_token"] = storedAuthToken; // get from storage const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // send request to checkstatus on website // Make an API call to API gateway var apiUrl = 'https://lt8psnfy4f.execute-api.eu-west-1.amazonaws.com/Production/MYPEASGPT'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData) }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("processStatus return: ",JSON.stringify(result)); HidePreLoad(); /*return { statusCode: 200, body: JSON.stringify({"message": "Profile Found", "promptDescription": promptDescription, "profile": checkUserObj["profile"], "processStatus": checkUserObj["processStatus"]}), }; */ var processStatus = result["processStatus"]; switch(processStatus) { case "complete": case "completed": // if completed - load profile in UI var profile = result["profile"]; var favourites = result["favourites"] || JSON.stringify([]); var memberID = result["memberID"]; var authToken = result["auth_token"]; var auth_token_date_created = result["auth_token_date_created"]; var accountInfo = result["accountInfo"] || JSON.stringify({}); var orderHistory = result["orderHistory"] || JSON.stringify([]); var StripeInvoices = result["StripeInvoices"] || JSON.stringify([]); var revisions = result["revisions"] || "0"; var optIn = result["optIn"] !== undefined ? result["optIn"] : true; var paidAccount = result["paidAccount"] !== undefined ? result["paidAccount"] : "false"; if(paidAccount !== undefined) { localStorage.setItem("paidAccount", paidAccount); } else { localStorage.setItem("paidAccount", "false"); } if(optIn !== undefined) { // set optin in localstorage localStorage.setItem("optIn", optIn); } else { localStorage.setItem("optIn", true); } if(accountInfo == "") { accountInfo = JSON.stringify({}); } if(orderHistory == "") { orderHistory = JSON.stringify([]); } HideProcessing("loggedIn"); // set profile in localstorage localStorage.setItem("profile", JSON.stringify(profile)); localStorage.setItem("favourites", favourites); // set memberID localStorage.setItem("memberID", memberID); // set auth_token localStorage.setItem("auth_token", authToken); localStorage.setItem("auth_token_date_created", auth_token_date_created); localStorage.setItem("processStatus", "complete"); localStorage.setItem("accountInfo", accountInfo); localStorage.setItem("orderHistory", orderHistory); localStorage.setItem("StripeInvoices", StripeInvoices); localStorage.setItem("revisions", revisions); // load profile in UI - look into making this all work cleanly LoadExistingProfile(result["profile"]); // close modal OpenCloseLoginModal("close"); // we want to prompt user to complete details if missing from account // check accountInfo - this checks if accountinfo is complete accountInfo = JSON.parse(accountInfo); if(!checkAccountInfo(accountInfo)) { /*OpenAccountModal(); // show red text saying enter missing information $('#modal-message-account').text("** Complete Your Account Information **").show();*/ // create an onboarding modal OpenOnboardModal(); } firstLoad(); break; case "failed": var profile = result["profile"]; var favourites = result["favourites"] || JSON.stringify([]); var memberID = result["memberID"]; var authToken = result["auth_token"]; var auth_token_date_created = result["auth_token_date_created"]; var accountInfo = result["accountInfo"] || JSON.stringify({}); var orderHistory = result["orderHistory"] || JSON.stringify([]); var StripeInvoices = result["StripeInvoices"] || JSON.stringify([]); var revisions = result["revisions"] || "0"; var optIn = result["optIn"] !== undefined ? result["optIn"] : true; var paidAccount = result["paidAccount"] !== undefined ? result["paidAccount"] : "false"; if(paidAccount !== undefined) { localStorage.setItem("paidAccount", paidAccount); } else { localStorage.setItem("paidAccount", "false"); } if(optIn !== undefined) { // set optin in localstorage localStorage.setItem("optIn", optIn); } else { localStorage.setItem("optIn", "true"); } if(accountInfo == "") { accountInfo = JSON.stringify({}); } if(orderHistory == "") { orderHistory = JSON.stringify([]); } HideProcessing("loggedIn"); // set profile in localstorage localStorage.setItem("profile", JSON.stringify(profile)); localStorage.setItem("favourites", favourites); // set memberID localStorage.setItem("memberID", memberID); // set auth_token localStorage.setItem("auth_token", authToken); localStorage.setItem("auth_token_date_created", auth_token_date_created); localStorage.setItem("processStatus", "failed"); localStorage.setItem("accountInfo", accountInfo); localStorage.setItem("orderHistory", orderHistory); localStorage.setItem("StripeInvoices", StripeInvoices); localStorage.setItem("revisions", revisions); // load profile in UI - look into making this all work cleanly if(profile && (profile != "" && profile != "\"\"")) { LoadExistingProfile(result["profile"]); } else { // if there is no profile // need to allow new search NewSearch(); ShowNavButtons(); } // close modal OpenCloseLoginModal("close"); // we want to prompt user to complete details if missing from account // check accountInfo - this checks if accountinfo is complete // add breakpoints and refresh page break; case "processing": case "updating": // if processing ShowProcessing(processStatus); break; case "notauthenticated": // require login // clear local storage and cookies localStorage.clear(); // can't delete the cookies, so set their values to expired. so we force UX to require new login // redirect to home page location.href = '/?login=true'; break; } }); } } } if(!isUserLoggedIn) { HidePreLoad(); $(btnMyAccount).hide(); $(btnMyFavourites).hide(); $(btnTools).hide(); $(btnLogInOut).show(); $(btnAgency).show(); $(btnLogInOut).text("Log In"); // check for query strings // 1. Get the query string from the URL: const queryString = window.location.search; // 2. Create a URLSearchParams object to parse the query string: const urlParams = new URLSearchParams(queryString); var triggerLinkedIn = true; // 3. Iterate through each key-value pair using forEach: urlParams.forEach((value, key) => { switch (key) { case 'processStatus': removeParam(key); ConsoleLog('ProcessStatus:', value); // Perform actions specific to the parameter // redirect to home page location.href = '/?login=true'; triggerLinkedIn = false; break; case 'reset-password': removeParam(key); ConsoleLog('ResetPassword:', value); // Perform actions specific to the parameter OpenCloseResetPasswordModal("open"); triggerLinkedIn = false; break; case 'login': removeParam(key); ConsoleLog('Login:', value); // Perform actions specific to the parameter OpenCloseLoginModal("open"); triggerLinkedIn = false; break; default: ConsoleLog(`Unknown parameter: ${key} with value: ${value}`); } }); if(triggerLinkedIn) { // Update the counter initially calculateWaitlistNumber(); $('#linkedin-modal').animate({ opacity: 100 }).show(); //unLockScroll(); // check for param from linkedin // check for query strings // 1. Get the query string from the URL: const queryString = window.location.search; // 2. Create a URLSearchParams object to parse the query string: const urlParams = new URLSearchParams(queryString); // 3. Iterate through each key-value pair using forEach: urlParams.forEach((value, key) => { switch (key) { case 'access': // show already commented link //$('#already-commented-holder').show(); $('#already-commented-link').show(); break; default: //$('#already-commented-holder').hide(); $('#already-commented-link').hide(); break; } }); // check for 'requestedAccess' var requestedAccessItem = localStorage.getItem("requestedAccess"); if(requestedAccessItem) { // show access code var accessCode = localStorage.getItem("accessCode"); if(!accessCode) { accessCode = generateRandomString(8); } $('#linkedin-modal #accessCode').val(accessCode); $('#skipwaitlist-container #accessCode').val(accessCode); $('#linkedin-modal #accessCodeHolder').show(); localStorage.setItem("accessCode", accessCode); // hide linkedin button $('#linkedin-modal #goToLinkedinHolder').hide(); // hide 'i have an access code' $('#linkedin-modal #launch-invite-moda-access').hide(); // hide already added $('#linkedin-modal #already-commented-link').hide(); // hide waitlist advice text $('#list-counter-popup').hide(); $('#linkedin-message').hide(); } } if (isWaitModeEnabled()) { // this mean no longer in wait mode if true // hide the popup for linkedin // close this modal $('#linkedin-modal .close-btn-w').click(); // hide the skip waitlist container $('#skipwaitlist-container').hide(); // hide skip waitlist button at bottom $('#btn-skip-wait-bottom').hide(); } CancelWaitlist(); } } // agency website if(agencyMember && window.location.href.toLowerCase().includes('/agency')) { // check if return from product purchase // On page load - check URL const urlParams = new URLSearchParams(window.location.search); const sessionId = urlParams.get('session_id'); // cs_abc123 const isSuccess = urlParams.get('success'); // true if (sessionId && isSuccess === 'true') { // Start polling - check every 2 seconds pollForOrderCompletion(sessionId, 'check-agency-order-status'); } else { if(isUserLoggedIn) { $(btnAgency).hide(); $(btnLogInOut).text("Log Out"); var storedMemberID = localStorage.getItem("memberID"); var storedAuthToken = localStorage.getItem("auth_token"); // request profile var MYPEAS_payload = {}; MYPEAS_payload["requestDescription"] = "RequestProfile"; MYPEAS_payload["registered"] = "true"; // should always be true now that user provides password at start page MYPEAS_payload["memberID"] = storedMemberID; // get from storage MYPEAS_payload["auth_token"] = storedAuthToken; // get from storage const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // send request to checkstatus on website // Make an API call to API gateway var apiUrl = 'https://v2tu3f9o1e.execute-api.eu-west-1.amazonaws.com/AgencyStage/Agency'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData) }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("login status return: ",JSON.stringify(result)); HidePreLoad(); /*return { statusCode: 200, body: JSON.stringify({"message": "Profile Found", "promptDescription": promptDescription, "profile": checkUserObj["profile"], "processStatus": checkUserObj["processStatus"]}), }; */ var processStatus = result["message"]; switch(processStatus) { case "Profile Found": case "User Validated": ConsoleLog("2"); // if completed and not empty - load profile in UI var memberID = result["memberID"]; var authToken = result["auth_token"]; var auth_token_date_created = result["auth_token_date_created"]; var accountInfo = result["accountInfo"] || JSON.stringify({}); var orderHistory = result["orderHistory"] || JSON.stringify([]); var bookingHistory = result["bookingHistory"] || JSON.stringify([]); var credits = result["credits"] || "0"; var requests = result["requests"] || JSON.stringify([]); var optIn = result["optIn"] !== undefined ? result["optIn"] : true; var StripeInvoices = result["StripeInvoices"] || JSON.stringify([]); if(optIn !== undefined) { // set optin in localstorage localStorage.setItem("optIn", optIn); } else { localStorage.setItem("optIn", "true"); } if(accountInfo == "") { accountInfo = JSON.stringify({}); } var ApprovedStatus = accountInfo["ApprovedStatus"]; if(orderHistory == "") { orderHistory = JSON.stringify([]); } if(bookingHistory == "") { bookingHistory = JSON.stringify([]); } HideProcessing("loggedIn"); // set memberID localStorage.setItem("memberID", memberID); localStorage.setItem("agencyMember", true); // set auth_token localStorage.setItem("auth_token", authToken); localStorage.setItem("auth_token_date_created", auth_token_date_created); localStorage.setItem("accountInfo", accountInfo); localStorage.setItem("orderHistory", orderHistory); localStorage.setItem("StripeInvoices", StripeInvoices); localStorage.setItem("bookingHistory", bookingHistory); localStorage.setItem("credits", credits); localStorage.setItem("requests", requests); // load agency member profile in UI LoadAgencyAccount(accountInfo, result); // close modal OpenCloseLoginModal("close"); // hide background video - show hero image $('.background-video').hide(); $('.background-video-agency').hide(); break; case "Account Does Not Exist": case "Account Exists. Wrong Password Entered": case "notauthenticated": // require login // clear local storage and cookies localStorage.clear(); // can't delete the cookies, so set their values to expired. so we force UX to require new login // redirect to home page location.href = '/agency?login=true'; break; } }); } if(!isUserLoggedIn) { HidePreLoad(); $(btnAgency).hide(); btnAgencySignup.addEventListener('click', (event) => { // Always start new search fresh ClearStorage(); // Prevent the default form submission behavior event.preventDefault(); // Get the values of the form fields const agentFirstName = document.getElementById('agent-first-name').value; const agentSurname = document.getElementById('agent-surname').value; const agentCompanyName = document.getElementById('agent-company-name').value; const agentWorkEmail = document.getElementById('agent-work-email').value; const agentPassword = document.getElementById('agent-password').value; var formContainer = document.getElementById('Form-container'); var agentPhoneCode = formContainer.querySelector('#countryCode').value; var agentPhoneNo = formContainer.querySelector('#telephone').value; var agentLocationCode = formContainer.querySelector('#countrySelect').value; var agentLocationName = $('#Form-container #countrySelect option:selected').text(); var hiddenCaptchaValue = document.getElementById('hcv').value; var MYPEAS_payload = {}; MYPEAS_payload["requestDescription"] = "Signup"; MYPEAS_payload["FirstName"] = agentFirstName; MYPEAS_payload["Surname"] = agentSurname; MYPEAS_payload["CompanyName"] = agentCompanyName; MYPEAS_payload["WorkEmail"] = agentWorkEmail; MYPEAS_payload["email"] = agentWorkEmail; MYPEAS_payload["Password"] = agentPassword; MYPEAS_payload["password"] = agentPassword; // Get the client's time zone const clientTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; MYPEAS_payload["timeZone"] = clientTimeZone; MYPEAS_payload["Location"] = {"locationName": agentLocationName, "locationCode": agentLocationCode}; MYPEAS_payload["TelephoneCode"] = agentPhoneCode; MYPEAS_payload["TelephoneNo"] = agentPhoneNo; const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // Validate fields var failed = false; var validationMessages = []; // Validation messages var validateAgentFirstName = document.getElementById('validateAgentFirstName'); var validateAgentSurname = document.getElementById('validateAgentSurname'); var validateAgentCompanyName = document.getElementById('validateAgentCompanyName'); var validateAgentWorkEmail = document.getElementById('validateAgentWorkEmail'); var validateAgentPassword = document.getElementById('validateAgentPassword'); var validatePhoneCode = document.getElementById('validateAgentTelephoneCode'); var validatePhoneNo = document.getElementById('validateAgentWorkTelephone'); var validateLocation = document.getElementById('validateAgentLocation'); // Hide all validation messages validateAgentFirstName.style.display = 'none'; validateAgentFirstName.style.color = 'red'; validateAgentSurname.style.display = 'none'; validateAgentSurname.style.color = 'red'; validateAgentCompanyName.style.display = 'none'; validateAgentCompanyName.style.color = 'red'; validateAgentWorkEmail.style.display = 'none'; validateAgentWorkEmail.style.color = 'red'; validateAgentPassword.style.display = 'none'; validateAgentPassword.style.color = 'red'; validatePhoneCode.style.display = 'none'; validatePhoneCode.style.color = 'red'; validatePhoneNo.style.display = 'none'; validatePhoneNo.style.color = 'red'; validateLocation.style.display = 'none'; validateLocation.style.color = 'red'; if (agentFirstName.length === 0) { failed = true; validateAgentFirstName.textContent = "First Name is required"; validateAgentFirstName.style.display = 'block'; validationMessages.push(validateAgentFirstName.id); } if (agentSurname.length === 0) { failed = true; validateAgentSurname.textContent = "Surname is required"; validateAgentSurname.style.display = 'block'; validationMessages.push(validateAgentSurname.id); } if (agentCompanyName.length === 0) { failed = true; validateAgentCompanyName.textContent = "Company Name is required"; validateAgentCompanyName.style.display = 'block'; validationMessages.push(validateAgentCompanyName.id); } if (!isValidEmail(agentWorkEmail)) { failed = true; validateAgentWorkEmail.textContent = "Please enter a valid email"; validateAgentWorkEmail.style.display = 'block'; validationMessages.push(validateAgentWorkEmail.id); } if (!isValidPassword(agentPassword)) { failed = true; validateAgentPassword.textContent = "Minimum length of 8 characters, contains at least one uppercase letter, one lowercase letter, one number, and one special character"; validateAgentPassword.style.display = 'block'; validationMessages.push(validateAgentPassword.id); } var nameRegex = /^[A-Za-z\s\-]+$/; // Regex to allow letters, spaces, and hyphens // validate location var locationName = $('#Form-container #countrySelect option:selected').text(); var locationCode = $('#Form-container #countrySelect').val(); if(locationName.trim() == "" || locationCode.trim() == "" ) { failed = true; validateLocation.style.display = 'block'; validationMessages.push(validateLocation.id); } // validate phone // validate country code if (!agentPhoneCode.trim()) { validatePhoneCode.textContent = 'Country Code is required'; validatePhoneCode.style.display = 'block'; failed = true; validationMessages.push(validatePhoneCode.id); } else { validatePhoneCode.style.display = 'none'; } // Validate Telephone if (!agentPhoneNo.trim()) { validatePhoneNo.textContent = 'Telephone is required.'; validatePhoneNo.style.display = 'block'; failed = true; validationMessages.push(validatePhoneNo.id); } else if (agentPhoneCode.trim() === "+44" && agentPhoneNo.trim().length < 11) { validatePhoneNo.textContent = 'Telephone number must be at least 11 digits for +44 country code.'; validatePhoneNo.style.display = 'block'; failed = true; validationMessages.push(validatePhoneNo.id); } else { validatePhoneNo.style.display = 'none'; } // If validation fails, do something (e.g., prevent form submission, show error messages) if (failed) { ConsoleLog("Validation failed:", validationMessages); // scroll to first error $('html, body').animate({ scrollTop: $('#' + validationMessages[0]).offset().top - 50 }, 500); } if(!failed) { // submit to server $('#main-content').hide(); $('#main-spinner').show(); // show hero image $('.background-video').hide(); $('.background-video-agency').hide(); // hide buttons $('#button-box').hide(); // Make an API call to API gateway - return will just indicate that it is processing var apiUrl = 'https://v2tu3f9o1e.execute-api.eu-west-1.amazonaws.com/AgencyStage/Agency'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData), }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("result (object): ", result); // result (object): {"message":"processing"} ConsoleLog("result (stringified): ", JSON.stringify(result)); // "{\"message\":\"processing\"}" var message = result["message"]; switch(message) { /* Login */ // user is validated case "Account Created": case "User Validated": var optIn = result["optIn"] !== undefined ? result["optIn"] : true; if(optIn !== undefined) { // set optin in localstorage localStorage.setItem("optIn", optIn); } else { localStorage.setItem("optIn", "true"); } /* return { statusCode: 200, body: JSON.stringify({"message": "User Validated", "promptDescription": promptDescription, "profile": checkUserObj["profile"], "processStatus": checkUserObj["processStatus"]}), }; */ // add useful info to localstorage /* const user = { memberID: items.length > 0 && items[0].hasOwnProperty('memberID') ? items[0].memberID.S : null, emailAddress: items.length > 0 && items[0].hasOwnProperty('emailAddress') ? items[0].emailAddress.S : null, accountInfo: items.length > 0 && items[0].hasOwnProperty('accountInfo') ? items[0].accountInfo.S : null, auth_token: items.length > 0 && items[0].hasOwnProperty('auth_token') ? items[0].auth_token.S : null, auth_token_date_created: items.length > 0 && items[0].hasOwnProperty('auth_token_date_created') ? items[0].auth_token_date_created.S : null, passwordHash: items.length > 0 && items[0].hasOwnProperty('passwordHash') ? items[0].passwordHash.S : null, passwordSalt: items.length > 0 && items[0].hasOwnProperty('passwordSalt') ? items[0].passwordSalt.S : null, credits: items.length > 0 && items[0].hasOwnProperty('revisions') ? items[0].revisions.S : 0, orderHistory: items.length > 0 && items[0].hasOwnProperty('orderHistory') ? items[0].orderHistory.S : null, userExists: items.length > 0, }; */ localStorage.setItem("memberID", result["memberID"]); localStorage.setItem("credits", result["credits"]); localStorage.setItem("accountInfo", result["accountInfo"]); localStorage.setItem("orderHistory", result["orderHistory"]); localStorage.setItem("StripeInvoices", result["StripeInvoices"] || "[]"); localStorage.setItem("auth_token", result["auth_token"]); localStorage.setItem("auth_token_date_created", result["auth_token_date_created"]); localStorage.setItem("agencyMember", true); // HIDE PRELOAD HidePreLoad(); // format UX for Agency dashboard // hide formcontainer $('#Form-container').hide(); // hide waitlistcontainer $('#waitlist-container').hide(); // hide learn more $('#learn-more-container').hide(); // hide invite launcher $('#invite-launcher').hide(); $('#main-content').show(); $('#main-spinner').hide(); // hide background video - show hero image $('.background-video').hide(); $('.background-video-agency').hide(); $('#hero-holder').show(); $('.hcv-container').show(); $('#background-image-hero').show(); // hide buttons $('#button-box').hide(); // change buttons in navbar // show nav buttons ShowNavButtons_Agency(); $(btnLogInOut).text("Log Out"); /// populate dashboard fields // show dashboard fields $('.agency-account-info-holder').show(); // load agency member profile in UI LoadAgencyAccount(result["accountInfo"], result); // hide background video - show hero image $('.background-video').hide(); $('.background-video-agency').hide(); break; // tell user to log in // failed to validate user case "Account Exists. Wrong Password Entered": /* return { statusCode: 200, body: JSON.stringify({"message": "Account Exists. Wrong Password Entered", "promptDescription": promptDescription}), }; */ // reset visibility $('#main-content').show(); $('#main-spinner').hide(); // show video $('.background-video').show(); // show buttons $('#button-box').show(); OpenModal("Problem", "Please check your login details", false, true); break; case "Account Creation Failed": /* return { statusCode: 200, body: JSON.stringify({"message": "Account Creation Failed"}), }; */ // reset visibility $('#main-content').show(); $('#main-spinner').hide(); // show video $('.background-video').show(); // show buttons $('#button-box').show(); OpenModal("Problem", "Account Creation Failed, Please Try Again Later", false, true); break; } }); // load agency dashboard // id=agency-account-info-holder } // If validation passes, proceed with form submission or other actions ConsoleLog("Validation passed. Submitting form..."); }); } } } // logged in agency user, arriving on non-agency site gets sent to agency page if(agencyMember && !window.location.href.toLowerCase().includes('/agency') && isUserLoggedIn) { // send to agency page window.location = '/agency'; } // logged in user arriving at agency page gets redirected to main user page if(!agencyMember && window.location.href.toLowerCase().includes('/agency') && isUserLoggedIn) { // send to home page window.location = '/'; } // basically fresh visitor to agency page if(!agencyMember && window.location.href.toLowerCase().includes('/agency') && !isUserLoggedIn) { HidePreLoad(); // show form-container $('#Form-container').show(); $('#get-started-free_Agency').hide(); // check for query strings // 1. Get the query string from the URL: const queryString = window.location.search; // 2. Create a URLSearchParams object to parse the query string: const urlParams = new URLSearchParams(queryString); // 3. Iterate through each key-value pair using forEach: urlParams.forEach((value, key) => { switch (key) { case 'processStatus': removeParam(key); ConsoleLog('ProcessStatus:', value); // Perform actions specific to the parameter // redirect to home page location.href = '/?login=true'; break; case 'reset-password': removeParam(key); ConsoleLog('ResetPassword:', value); // Perform actions specific to the parameter OpenCloseResetPasswordModal("open"); break; case 'login': removeParam(key); ConsoleLog('Login:', value); // Perform actions specific to the parameter OpenCloseLoginModal("open"); break; default: ConsoleLog(`Unknown parameter: ${key} with value: ${value}`); } }); } } } async function pollForOrderCompletion(sessionId, operation) { const memberID = localStorage.getItem("memberID"); const authToken = localStorage.getItem("auth_token"); let attempts = 0; const maxAttempts = 30; // 1 minute total const pollInterval = setInterval(async () => { attempts++; try { // Call your Lambda to check if order was processed const response = await fetch('https://j8glspknjh.execute-api.eu-west-1.amazonaws.com/Production/Checkout', { method: 'POST', body: JSON.stringify({ operation: operation, sessionId: sessionId, // cs_abc123 memberID: memberID, authToken: authToken }) }); const result = await response.json(); if (result.orderProcessed) { // ✅ Webhook completed! Order found in database clearInterval(pollInterval); if(!window.location.href.toLowerCase().includes('/agency')) { // Update localStorage with new account status if (result.paidAccount) localStorage.setItem("paidAccount", result.paidAccount); if (result.revisions) localStorage.setItem("revisions", result.revisions); // Redirect to profile setTimeout(() => { window.location.href = '/'; }, 500); } else { // Redirect to agency profile setTimeout(() => { window.location.href = './'; }, 500); } } else if (attempts >= maxAttempts) { // ❌ Timeout - webhook might have failed clearInterval(pollInterval); OpenModal("Processing", "Your payment was successful. If credits don't appear shortly, please contact support@mypeas.ai", false, false); // Redirect to profile setTimeout(() => { window.location.href = './'; }, 3000); } // If orderProcessed is false, keep polling... } catch (error) { console.error('Polling error:', error); if (attempts >= maxAttempts) { clearInterval(pollInterval); //OpenModal("Error", "Please contact support@mypeas.ai", false, false); OpenModal("Problem", "If credits don't appear shortly, please contact support@mypeas.ai", false, false); // Redirect to profile setTimeout(() => { window.location.href = './'; }, 3000); } } }, 2000); // Poll every 2 seconds } function CancelWaitlist() { // hide $('#btnJoinWaitlist').hide(); $('#join-waitlist-bottom').hide(); $('#waitlist-container').hide(); $('#invite-launcher').hide(); $('#skipwaitlist-container').hide(); $('#get-started-free').hide(); // close this modal $('#linkedin-modal .close-btn-w').click(); // hide skip waitlist button at bottom $('#btn-skip-wait-bottom').hide(); // show $('#btnGetStarted').show().css('display', 'block'); $('#get-started-free').show().css('display', 'block'); $('#Form-container').show(); } function calculateWaitlistNumber() { const currentTime = new Date(); const currentHour = currentTime.getHours(); const listCounter = document.getElementById("list-counter"); var listCounterPopup = document.getElementById("list-counter-popup-span"); let waitlistNumber; // If it's before 6 PM, decrease the number as the day progresses if (currentHour < 18) { // Start at 1200 at 8 AM and decrease down to 800 by 6 PM const startWaitlist = 1200; const endWaitlist = 800; const startHour = 8; const endHour = 18; if (currentHour >= startHour) { // Calculate proportionally how far through the day we are and adjust the waitlist number const progress = (currentHour - startHour) / (endHour - startHour); waitlistNumber = Math.floor(startWaitlist - progress * (startWaitlist - endWaitlist)); } else { waitlistNumber = startWaitlist; // Early in the day, still high waitlist number } } // After 6 PM, increase the waitlist number again else { // Between 6 PM and midnight, the waitlist grows back up to 1200 const startWaitlist = 800; const endWaitlist = 1200; const startHour = 18; const endHour = 24; const progress = (currentHour - startHour) / (endHour - startHour); waitlistNumber = Math.floor(startWaitlist + progress * (endWaitlist - startWaitlist)); } // Update the displayed waitlist number listCounter.textContent = waitlistNumber; listCounterPopup.textContent = waitlistNumber; $('#linkedin-modal').animate({ opacity: 1 }).show(); } /* Booking Page code */ function isBookingPage() { // Get the URL parameters const urlParams = new URLSearchParams(window.location.search); // Check if the required parameters are present const hasBooking = urlParams.has('calLink'); const hasAgencyID = urlParams.has('agencyID'); const hasMemberID = urlParams.has('memberID'); // If all parameters are present, return true, otherwise redirect if (hasBooking && hasAgencyID && hasMemberID) { return true; } else if(hasBooking && !(hasAgencyID && hasMemberID)) { window.location.href = 'https://mypeas.ai'; } else { return false; } } function getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"); var results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); } function addParameterToURL(url, paramName, paramValue) { const urlObject = new URL(url); urlObject.searchParams.set(paramName, paramValue); return urlObject.toString(); } function isCalendlyEvent(e) { console.log('e: ',e); console.log('origin: ',e.origin); console.log('event', e.data.event); console.log('isCalendlyEvent: ',e.origin === "https://calendly.com" && e.data.event && e.data.event.indexOf("calendly.") === 0); return e.origin === "https://calendly.com" && e.data.event && e.data.event.indexOf("calendly.") === 0; } /* END booking page code */ function CheckApp() { // check which page you are on // listing vs my-tools var isListingPage = false; var isMyToolsPage = false; // check url var currentUrl = window.location.href; var urlDirectory = "/app-listing/listing"; if(currentUrl.toLowerCase().includes("/app-listing/listing")) { HideNavButtons(); urlDirectory = "/app-listing/listing"; isListingPage = true; CheckApp_ListingPage(); } if(currentUrl.toLowerCase().includes("/app-listing/my-tools")) { var isUserLoggedIn = checkLoggedIn(); var paramTest = getParameterByName("test", null); var isTest = false; if(paramTest) { isTest = true; } if(isUserLoggedIn || isTest) { urlDirectory = "/app-listing/my-tools"; isMyToolsPage = true; HideNavButtons(); CheckApp_MyToolsPage(); // set tools if present Check_Stored_Tools(); // add invoices createInvoiceTable(); } else { // redirect to home window.location = window.location.origin; } } if(!isListingPage && !isMyToolsPage) { // check for query strings // 1. Get the query string from the URL: const queryString = window.location.search; // 2. Create a URLSearchParams object to parse the query string: const urlParams = new URLSearchParams(queryString); // 3. Check for 'appname' parameter and its value: const appName = urlParams.get('appname'); /*if (!appName || appName.trim() === '') { // Redirect to root if missing or empty value window.location.href = '/'; return; // Prevent further execution if redirected }*/ // 4. Iterate through each key-value pair using forEach: urlParams.forEach((value, key) => { switch (key) { case 'appname': ConsoleLog('appName:', value); var decodedAppName = value ? decodeURIComponent(value) : ""; ConsoleLog('appName (decoded):', decodedAppName); SearchApp("Name", decodedAppName); break; } }); } } // Store a persistent reference to the event handler let handleAddFaqClick = null; function CheckApp_ListingPage() { // check for query params var paramSuccess = getParameterByName("success", null); var paramCancel = getParameterByName("cancel", null); if(paramSuccess) { $('#success-banner').show(); } if(paramCancel) { $('#cancel-banner').show(); } // check local storage var storedListing = localStorage.getItem("createOrUpdateListing"); setData('#submit-new-tool-holder', null); if(storedListing && paramCancel) { // load UI from localstorage /* const payload = { operation: 'createOrUpdateListing', payload: { AppTitle: document.getElementById('app-heading').textContent, AppHeadline: document.getElementById('app-subheading').textContent, AppScreenshot: document.getElementById('app-hero-image').src, AppDescription: document.getElementById('app-description').textContent, AppCategory: appData.task, WebsiteLink: document.getElementById('app-URL').value, FAQs: JSON.stringify(faqs), Paid: false, // Default, can be updated as needed DateOfPayment: DateOfPayment, }, }; */ // create listingObj from localstorage var listingObj = {}; storedListing = JSON.parse(storedListing); // get the payload from the stripe session // get param from the url to request stripe session object // we cant store the data in metadata as the description is longer than the 500 characters listingObj.objectID = storedListing.payload.AppId; listingObj.name = storedListing.payload.AppTitle; listingObj.useCase = storedListing.payload.AppHeadline; listingObj.task = storedListing.payload.AppCategory; // task is category/group listingObj.screenshot = storedListing.payload.AppScreenshot; listingObj.siteUrl = storedListing.payload.WebsiteLink; listingObj.description = storedListing.payload.AppDescription; listingObj.faqs = storedListing.payload.FAQs; /*var appData; appData.name; appData.useCase; appData.task; appData.screenshot; appData.useCase; appData.siteUrl; appData.description;*/ setData("#app-holder", listingObj); } // check for submit type if(paramCancel) { // DETERMINE SUBMIT TYPE: buy listing OR update listing var accountInfo = localStorage.getItem("accountInfo") || null; if(accountInfo) { accountInfo = JSON.parse(accountInfo); // create and populate // get owned tools var tools = accountInfo["tools"] || []; // loop over tools and find appids // Extracting AppId values //const appIds = accountInfo.tools.map(tool => tool.AppId); const appIds = tools.map(tool => tool.AppId); // Output the result console.log(appIds); // compare current appId to the collection of AppId values var appId = ""; if(listingObj) { appId = listingObj.objectID; } // Check if appId exists in appIds if (appIds.includes(appId)) { console.log("Match found for appId:", appId); // Add any actions to execute when there's a match // show update $('#update-listing-holder').show(); $('#make-purchase-holder').hide(); } else { console.log("No match found for appId:", appId); // show purchase $('#make-purchase-holder').show(); $('#update-listing-holder').hide(); } } } // if success - use stored listing to populate UI - server may still be updating databases // NEW* if success just hide those fields and show success banner if(storedListing && paramSuccess) { // change the ui for purchased listing //$('#product-description').hide(); $('#edit-heading').hide(); $('#edit-tagline').hide(); $('#edit-hero-image').hide(); $('#edit-description').hide(); $('#edit-url').hide(); $('#add-faq').hide(); $('#make-purchase-holder').hide(); $('#what-is-mypeas-holder').hide(); $('#welcome-banner').hide(); $('#edit-category').hide(); // make uneditable // appURL.contentEditable = true; var AppDescription = document.getElementById('app-description'); var AppCategory = document.getElementById('app-category'); var AppUrl = document.getElementById('app-URL'); AppDescription.contentEditable = false; AppCategory.contentEditable = false; AppUrl.contentEditable = false; // load UI from localstorage /* const payload = { operation: 'createOrUpdateListing', payload: { AppTitle: document.getElementById('app-heading').textContent, AppHeadline: document.getElementById('app-subheading').textContent, AppScreenshot: document.getElementById('app-hero-image').src, AppDescription: document.getElementById('app-description').textContent, AppCategory: appData.task, WebsiteLink: document.getElementById('app-URL').value, FAQs: JSON.stringify(faqs), Paid: false, // Default, can be updated as needed DateOfPayment: DateOfPayment, }, }; */ // create listingObj from localstorage var listingObj = {}; storedListing = JSON.parse(storedListing); // get the payload from the stripe session // get param from the url to request stripe session object // we cant store the data in metadata as the description is longer than the 500 characters listingObj.objectID = storedListing.payload.AppId; listingObj.name = storedListing.payload.AppTitle; listingObj.useCase = storedListing.payload.AppHeadline; listingObj.task = storedListing.payload.AppCategory; // task is category/group listingObj.screenshot = storedListing.payload.AppScreenshot; listingObj.siteUrl = storedListing.payload.WebsiteLink; listingObj.description = storedListing.payload.AppDescription; listingObj.faqs = storedListing.payload.FAQs; /*var appData; appData.name; appData.useCase; appData.task; appData.screenshot; appData.useCase; appData.siteUrl; appData.description;*/ setData("#app-holder", listingObj); // hide both submit options $('#update-listing-holder').hide(); $('#make-purchase-holder').hide(); } // default to load listing info // all other circumstances use the data from the server if(!(storedListing && paramSuccess) && !(storedListing && paramCancel)) { // set up fields to work if(!paramCancel && !paramSuccess) { // if listing var btnEditHeading = document.getElementById("edit-heading"); var btnEditSubheading = document.getElementById("edit-tagline"); var btnEditImage = document.getElementById("edit-hero-image"); var uploadButton = document.getElementById("upload-button"); var btnEditDescription = document.getElementById("edit-description"); var btnAddFAQ = document.getElementById("add-faq"); var btnEditUrl = document.getElementById("edit-url"); var btnOpenUrl = document.getElementById("visit-website"); var appURL = document.getElementById('app-URL'); var appId = document.getElementById('app-id'); if(appURL) { appURL.addEventListener("focus", () => { appURL.style.border = "2px solid blue"; appURL.style.backgroundColor = "lightblue"; appURL.style.boxShadow = "0px 0px 5px rgba(0, 0, 0, 0.5)"; }); appURL.addEventListener("blur", () => { appURL.style.border = "1px solid lightgray"; appURL.style.backgroundColor = ""; appURL.style.boxShadow = ""; }); appURL.addEventListener("paste", (event) => { event.preventDefault(); // Prevent default paste behavior // Get the plain text from the clipboard const plainText = (event.clipboardData || window.clipboardData).getData('text'); // Insert the plain text at the current caret position const selection = window.getSelection(); if (!selection.rangeCount) return; // Get the current range and replace it with plain text const range = selection.getRangeAt(0); range.deleteContents(); range.insertNode(document.createTextNode(plainText)); }); } btnOpenUrl.addEventListener('click', (event) => { event.preventDefault(); var appLink = appURL.textContent; if(appLink && appLink.trim() !== "") { window.open(appLink, '_blank', 'noopener'); } }); btnEditUrl.addEventListener('click', (event) => { event.preventDefault(); appURL.contentEditable = true; appURL.focus(); }); var appHeading = document.getElementById("app-heading"); appHeading.addEventListener("focus", () => { var placeholder = "Heading"; if(appHeading.textContent.trim() == placeholder) { appHeading.textContent = ""; // Set a minimum width when the content is empty appHeading.style.minWidth = '200px'; // Adjust the value as needed } appHeading.style.border = "2px solid blue"; appHeading.style.backgroundColor = "lightblue"; appHeading.style.boxShadow = "0px 0px 5px rgba(0, 0, 0, 0.5)"; }); appHeading.addEventListener("blur", () => { var placeholder = "Heading"; if(appHeading.textContent.trim() == "") { appHeading.textContent = placeholder; } appHeading.style.border = ""; appHeading.style.backgroundColor = ""; appHeading.style.boxShadow = ""; }); appHeading.addEventListener("paste", (event) => { event.preventDefault(); // Prevent default paste behavior // Get the plain text from the clipboard const plainText = (event.clipboardData || window.clipboardData).getData('text'); // Insert the plain text at the current caret position const selection = window.getSelection(); if (!selection.rangeCount) return; // Get the current range and replace it with plain text const range = selection.getRangeAt(0); range.deleteContents(); range.insertNode(document.createTextNode(plainText)); }); btnEditHeading.addEventListener('click', (event) => { // show forgotpassword event.preventDefault(); /*$('#app-heading-update').show(); $('#app-heading').hide();*/ appHeading.contentEditable = true; appHeading.focus(); }); var appSubheading = document.getElementById("app-subheading"); appSubheading.addEventListener("focus", () => { var placeholder = "App tagline text"; if(appSubheading.textContent.trim() == placeholder) { appSubheading.textContent = ""; // Set a minimum width when the content is empty appSubheading.style.minWidth = '200px'; // Adjust the value as needed } appSubheading.style.border = "2px solid blue"; appSubheading.style.backgroundColor = "lightblue"; appSubheading.style.boxShadow = "0px 0px 5px rgba(0, 0, 0, 0.5)"; }); appSubheading.addEventListener("blur", () => { var placeholder = "App tagline text"; if(appSubheading.textContent.trim() == "") { appSubheading.textContent = placeholder; } appSubheading.style.border = ""; appSubheading.style.backgroundColor = ""; appSubheading.style.boxShadow = ""; }); appSubheading.addEventListener("paste", (event) => { event.preventDefault(); // Prevent default paste behavior // Get the plain text from the clipboard const plainText = (event.clipboardData || window.clipboardData).getData('text'); // Insert the plain text at the current caret position const selection = window.getSelection(); if (!selection.rangeCount) return; // Get the current range and replace it with plain text const range = selection.getRangeAt(0); range.deleteContents(); range.insertNode(document.createTextNode(plainText)); }); btnEditSubheading.addEventListener('click', (event) => { // show forgotpassword event.preventDefault(); /*$('#app-subheading-update').show(); $('#app-subheading').hide(); */ appSubheading.contentEditable = true; appSubheading.focus(); }); btnEditImage.addEventListener('click', (event) => { // show forgotpassword event.preventDefault(); $('#app-hero-image-update').show(); // file picker $('#app-screenshot').show(); // update button $('#upload-button').show(); }); if (uploadButton) { uploadButton.addEventListener('click', async (event) => { event.preventDefault(); const screenshotInput = document.getElementById('app-screenshot'); // File input for new screenshot if (screenshotInput.files.length > 0) { const file = screenshotInput.files[0]; const folderName = 'images'; // Convert file to Base64 using FileReader const fileBuffer = await fileToBase64(file); // Base64-encoded string const payload = { folderName, fileBuffer }; const apiUrl = 'https://9halovn749.execute-api.eu-west-1.amazonaws.com/default/CreateListing'; fetch(apiUrl, { method: 'POST', body: JSON.stringify({ operation: 'generateScreenshotUploadUrl', payload }), }) .then(response => response.json()) // Parse the response as JSON .then(data => { console.log("Upload response received:", data); // Check if the response contains a valid imageUrl if (data && typeof data === 'object' && data.imageUrl && typeof data.imageUrl === 'string' && data.imageUrl.startsWith('https://flexluthor.s3.eu-west-2.amazonaws.com/')) { console.log("Valid image URL detected:", data.imageUrl); // Update the src of the image only if the URL is valid const appHeroImg = document.getElementById('app-hero-image'); if (appHeroImg) { appHeroImg.src = data.imageUrl; } else { console.warn('Element with id "app-hero-image" not found.'); } // Clear the file selection if (screenshotInput) { screenshotInput.value = null; } else { console.warn('Element with id "screenshotInput" not found.'); } } else { console.warn("Response did not contain a valid image URL.", data); } }) .catch(error => { console.error("Upload failed:", error); }); } }); } var appDescription = document.getElementById('app-description'); appDescription.addEventListener("focus", () => { var placeholder = "Description of Your AI solution"; if(appDescription.textContent.trim() == placeholder) { appDescription.textContent = ""; // Set a minimum width when the content is empty appDescription.style.minWidth = '200px'; // Adjust the value as needed } appDescription.style.border = "2px solid blue"; appDescription.style.backgroundColor = "lightblue"; appDescription.style.boxShadow = "0px 0px 5px rgba(0, 0, 0, 0.5)"; appDescription.style.padding = '14px'; appDescription.style.whiteSpace = 'pre-wrap'; appDescription.style.padding = '14px'; appDescription.style.wordWrap = 'break-word'; appDescription.style.overflowWrap = 'break-word'; appDescription.style.maxWidth = '100%'; appDescription.style.overflow = 'hidden'; //appDescription.style.outline = 'none'; /*
Description of Your AI solution
*/ }); appDescription.addEventListener("blur", () => { var placeholder = "Description of Your AI solution"; if(appDescription.textContent.trim() == "") { appDescription.textContent = placeholder; } appDescription.style.whiteSpace = 'pre-wrap'; appDescription.style.padding = '14px'; appDescription.style.border = "1px solid lightgray"; appDescription.style.backgroundColor = ""; appDescription.style.boxShadow = ""; }); appDescription.addEventListener("paste", (event) => { event.preventDefault(); // Prevent default paste behavior // Get the plain text from the clipboard const plainText = (event.clipboardData || window.clipboardData).getData('text'); // Insert the plain text at the current caret position const selection = window.getSelection(); if (!selection.rangeCount) return; // Get the current range and replace it with plain text const range = selection.getRangeAt(0); range.deleteContents(); range.insertNode(document.createTextNode(plainText)); }); btnEditDescription.addEventListener('click', (event) => { // show forgotpassword event.preventDefault(); /*$('#app-description-update').show(); $('#app-description').hide(); var appDescription = document.getElementById("app-description"); const formattedText = appDescription.textContent.replace(/\n/g, "
"); // Replace newlines with
for HTML // Get the textarea element const textarea = document.getElementById('app-description-update'); // Set the textarea's value with the formatted text textarea.value = formattedText; // Create a temporary selection element (optional) const selection = document.createRange(); selection.selectNodeContents(textarea); try { // Attempt to copy the selection (if supported) const successful = document.execCommand('copy'); const msg = successful ? 'Formatted text copied!' : 'Browser may not support copying.'; alert(msg); } catch (err) { console.error('Copying failed:', err); alert('Failed to copy text. Consider manual copy/paste.'); } finally { // Cleanup the temporary selection (if created) selection.detach(); }*/ appDescription.contentEditable = true; appDescription.focus(); }); // add app category var appCategory = document.getElementById('app-category'); appCategory.addEventListener("focus", () => { appCategory.style.border = "2px solid blue"; appCategory.style.backgroundColor = "lightblue"; appCategory.style.boxShadow = "0px 0px 5px rgba(0, 0, 0, 0.5)"; appCategory.style.whiteSpace = 'pre-wrap'; appCategory.style.wordWrap = 'break-word'; appCategory.style.overflowWrap = 'break-word'; appCategory.style.maxWidth = '100%'; appCategory.style.overflow = 'hidden'; appCategory.style.wordBreak = 'break-word'; //appCategory.style.outline = 'none'; }); appCategory.addEventListener("blur", () => { appCategory.style.border = "1px solid lightgray"; appCategory.style.backgroundColor = ""; appCategory.style.boxShadow = ""; }); appCategory.addEventListener("paste", (event) => { event.preventDefault(); // Prevent default paste behavior // Get the plain text from the clipboard const plainText = (event.clipboardData || window.clipboardData).getData('text'); // Insert the plain text at the current caret position const selection = window.getSelection(); if (!selection.rangeCount) return; // Get the current range and replace it with plain text const range = selection.getRangeAt(0); range.deleteContents(); range.insertNode(document.createTextNode(plainText)); }); var btnEditCategory = document.getElementById('edit-category'); btnEditCategory.addEventListener('click', (event) => { event.preventDefault(); appCategory.contentEditable = true; appCategory.focus(); }); const faqList = document.getElementById('faq-list'); // Function to add a new FAQ input pair /*function addFaqEntry(question = '', answer = '') { const faqDiv = document.createElement('div'); faqDiv.style.marginBottom = "10px"; faqDiv.classList.add('faq-entry'); faqDiv.innerHTML = `
`; faqList.appendChild(faqDiv); const removeButton = faqDiv.querySelector('.remove-faq'); removeButton.addEventListener('click', () => { faqDiv.remove(); }); } // Add event listener to the "Add FAQ" button btnAddFAQ.addEventListener('click', () => addFaqEntry());*/ // Function to ensure only one event listener is attached to btnAddFAQ function setupFaqButtonListener() { // If the handler hasn’t been set yet, define it if (!handleAddFaqClick) { handleAddFaqClick = function () { addFaqEntry(); }; } // Remove any existing listener before adding a new one btnAddFAQ.removeEventListener('click', handleAddFaqClick); btnAddFAQ.addEventListener('click', handleAddFaqClick); } // Function to add a new FAQ input pair function addFaqEntry(question = '', answer = '') { const faqDiv = document.createElement('div'); faqDiv.style.marginBottom = "10px"; faqDiv.classList.add('faq-entry'); faqDiv.innerHTML = `
`; faqList.appendChild(faqDiv); const removeButton = faqDiv.querySelector('.remove-faq'); removeButton.addEventListener('click', () => { faqDiv.remove(); }); } // Call this function whenever the event listener needs to be ensured setupFaqButtonListener(); } // check for query strings // 1. Get the query string from the URL: const queryString = window.location.search; // 2. Create a URLSearchParams object to parse the query string: const urlParams = new URLSearchParams(queryString); // 3. Check for 'appname' parameter and its value: const appName = urlParams.get('appname'); /*if (!appName || appName.trim() === '') { // Redirect to root if missing or empty value window.location.href = '/'; return; // Prevent further execution if redirected }*/ // 4. Iterate through each key-value pair using forEach: urlParams.forEach((value, key) => { switch (key) { case 'appname': ConsoleLog('appName:', value); var decodedAppName = value ? decodeURIComponent(value) : ""; ConsoleLog('appName (decoded):', decodedAppName); SearchApp("Name", decodedAppName); break; } }); } } function CheckApp_MyToolsPage() { // check which page you are on // listing vs my-tools var isListingPage = false; var isMyToolsPage = false; // check url var currentUrl = window.location.href; var urlDirectory = "/app-listing/listing"; setData('#submit-new-tool-holder',null); if(currentUrl.toLowerCase().includes("/app-listing/listing")) { urlDirectory = "/app-listing/listing"; isListingPage = true; } if(currentUrl.toLowerCase().includes("/app-listing/my-tools")) { urlDirectory = "/app-listing/my-tools"; isMyToolsPage = true; } // check for query params var paramSuccess = getParameterByName("success", null); var paramCancel = getParameterByName("cancel", null); if(paramSuccess) { $('#success-banner').show(); // just hide those fields // this is default } if(paramCancel) { $('#cancel-banner').show(); } // check local storage var storedListing = localStorage.getItem("createOrUpdateListing"); // if success - use stored listing to populate UI - server may still be updating databases // just hide those fields if(storedListing && paramCancel) { // load UI from localstorage /* const payload = { operation: 'createOrUpdateListing', payload: { AppTitle: document.getElementById('app-heading').textContent, AppHeadline: document.getElementById('app-subheading').textContent, AppScreenshot: document.getElementById('app-hero-image').src, AppDescription: document.getElementById('app-description').textContent, AppCategory: appData.task, WebsiteLink: document.getElementById('app-URL').value, FAQs: JSON.stringify(faqs), Paid: false, // Default, can be updated as needed DateOfPayment: DateOfPayment, }, }; */ // create listingObj from localstorage var listingObj = {}; storedListing = JSON.parse(storedListing); // get the payload from the stripe session // get param from the url to request stripe session object // we cant store the data in metadata as the description is longer than the 500 characters listingObj.objectID = storedListing.payload.AppId; listingObj.name = storedListing.payload.AppTitle; listingObj.useCase = storedListing.payload.AppHeadline; listingObj.task = storedListing.payload.AppCategory; // task is category/group listingObj.screenshot = storedListing.payload.AppScreenshot; listingObj.siteUrl = storedListing.payload.WebsiteLink; listingObj.description = storedListing.payload.AppDescription; listingObj.faqs = storedListing.payload.FAQs; // Example Usage /*const sessionId = 'cs_test_a1s3CompJydFm46qju3jqyKoeIcu3P2nUhNuuzoknQlYFqDbY1jIqQAccb'; // Replace with a valid session ID getSession(sessionId).then(session => { if (session) { console.log('Retrieved session:', session); } else { console.log('Failed to retrieve session.'); } });*/ /*var appData; appData.name; appData.useCase; appData.task; appData.screenshot; appData.useCase; appData.siteUrl; appData.description;*/ setData("#app-holder", listingObj); // show fields document.getElementById('submit-new-tool-holder').style.display = 'block'; } // var StripeInvoices = result["StripeInvoices"] || JSON.stringify([]); //localStorage.setItem("StripeInvoices", result["StripeInvoices"] || "[]"); //localStorage.setItem("StripeInvoices", StripeInvoices); // default is handled in CheckApp if(!paramCancel && !paramSuccess) { // if listing var btnEditHeading = document.getElementById("edit-heading"); var btnEditSubheading = document.getElementById("edit-tagline"); var btnEditImage = document.getElementById("edit-hero-image"); var uploadButton = document.getElementById("upload-button"); var btnEditDescription = document.getElementById("edit-description"); var btnAddFAQ = document.getElementById("add-faq"); var btnEditUrl = document.getElementById("edit-url"); var btnOpenUrl = document.getElementById("visit-website"); var appURL = document.getElementById('app-URL'); var appId = document.getElementById('app-id'); if(appURL) { appURL.addEventListener("focus", () => { appURL.style.border = "2px solid blue"; appURL.style.backgroundColor = "lightblue"; appURL.style.boxShadow = "0px 0px 5px rgba(0, 0, 0, 0.5)"; }); appURL.addEventListener("blur", () => { appURL.style.border = "1px solid lightgray"; appURL.style.backgroundColor = ""; appURL.style.boxShadow = ""; }); appURL.addEventListener("paste", (event) => { event.preventDefault(); // Prevent default paste behavior // Get the plain text from the clipboard const plainText = (event.clipboardData || window.clipboardData).getData('text'); // Insert the plain text at the current caret position const selection = window.getSelection(); if (!selection.rangeCount) return; // Get the current range and replace it with plain text const range = selection.getRangeAt(0); range.deleteContents(); range.insertNode(document.createTextNode(plainText)); }); } btnOpenUrl.addEventListener('click', (event) => { event.preventDefault(); var appLink = appURL.textContent; if(appLink && appLink.trim() !== "") { window.open(appLink, '_blank', 'noopener'); } }); btnEditUrl.addEventListener('click', (event) => { event.preventDefault(); appURL.contentEditable = true; appURL.focus(); }); var appHeading = document.getElementById("app-heading"); appHeading.addEventListener("focus", () => { var placeholder = "Heading"; if(appHeading.textContent.trim() == placeholder) { appHeading.textContent = ""; // Set a minimum width when the content is empty appHeading.style.minWidth = '200px'; // Adjust the value as needed } appHeading.style.border = "2px solid blue"; appHeading.style.backgroundColor = "lightblue"; appHeading.style.boxShadow = "0px 0px 5px rgba(0, 0, 0, 0.5)"; }); appHeading.addEventListener("blur", () => { var placeholder = "Heading"; if(appHeading.textContent.trim() == "") { appHeading.textContent = placeholder; } appHeading.style.border = ""; appHeading.style.backgroundColor = ""; appHeading.style.boxShadow = ""; }); appHeading.addEventListener("paste", (event) => { event.preventDefault(); // Prevent default paste behavior // Get the plain text from the clipboard const plainText = (event.clipboardData || window.clipboardData).getData('text'); // Insert the plain text at the current caret position const selection = window.getSelection(); if (!selection.rangeCount) return; // Get the current range and replace it with plain text const range = selection.getRangeAt(0); range.deleteContents(); range.insertNode(document.createTextNode(plainText)); }); btnEditHeading.addEventListener('click', (event) => { // show forgotpassword event.preventDefault(); /*$('#app-heading-update').show(); $('#app-heading').hide();*/ appHeading.contentEditable = true; appHeading.focus(); }); var appSubheading = document.getElementById("app-subheading"); appSubheading.addEventListener("focus", () => { var placeholder = "App tagline text"; if(appSubheading.textContent.trim() == placeholder) { appSubheading.textContent = ""; // Set a minimum width when the content is empty appSubheading.style.minWidth = '200px'; // Adjust the value as needed } appSubheading.style.border = "2px solid blue"; appSubheading.style.backgroundColor = "lightblue"; appSubheading.style.boxShadow = "0px 0px 5px rgba(0, 0, 0, 0.5)"; }); appSubheading.addEventListener("blur", () => { var placeholder = "App tagline text"; if(appSubheading.textContent.trim() == "") { appSubheading.textContent = placeholder; } appSubheading.style.border = ""; appSubheading.style.backgroundColor = ""; appSubheading.style.boxShadow = ""; }); appSubheading.addEventListener("paste", (event) => { event.preventDefault(); // Prevent default paste behavior // Get the plain text from the clipboard const plainText = (event.clipboardData || window.clipboardData).getData('text'); // Insert the plain text at the current caret position const selection = window.getSelection(); if (!selection.rangeCount) return; // Get the current range and replace it with plain text const range = selection.getRangeAt(0); range.deleteContents(); range.insertNode(document.createTextNode(plainText)); }); btnEditSubheading.addEventListener('click', (event) => { // show forgotpassword event.preventDefault(); /*$('#app-subheading-update').show(); $('#app-subheading').hide(); */ appSubheading.contentEditable = true; appSubheading.focus(); }); btnEditImage.addEventListener('click', (event) => { // show forgotpassword event.preventDefault(); $('#app-hero-image-update').show(); // file picker $('#app-screenshot').show(); // update button $('#upload-button').show(); }); if (uploadButton) { uploadButton.addEventListener('click', async (event) => { event.preventDefault(); const screenshotInput = document.getElementById('app-screenshot'); // File input for new screenshot if (screenshotInput.files.length > 0) { const file = screenshotInput.files[0]; const folderName = 'images'; // Convert file to Base64 using FileReader const fileBuffer = await fileToBase64(file); // Base64-encoded string const payload = { folderName, fileBuffer }; const apiUrl = 'https://9halovn749.execute-api.eu-west-1.amazonaws.com/default/CreateListing'; fetch(apiUrl, { method: 'POST', body: JSON.stringify({ operation: 'generateScreenshotUploadUrl', payload }), }) .then(response => response.json()) // Parse the response as JSON .then(data => { console.log("Upload response received:", data); // Check if the response contains a valid imageUrl if (data && typeof data === 'object' && data.imageUrl && typeof data.imageUrl === 'string' && data.imageUrl.startsWith('https://flexluthor.s3.eu-west-2.amazonaws.com/')) { console.log("Valid image URL detected:", data.imageUrl); // Update the src of the image only if the URL is valid const appHeroImg = document.getElementById('app-hero-image'); if (appHeroImg) { appHeroImg.src = data.imageUrl; } else { console.warn('Element with id "app-hero-image" not found.'); } // Clear the file selection if (screenshotInput) { screenshotInput.value = null; } else { console.warn('Element with id "screenshotInput" not found.'); } } else { console.warn("Response did not contain a valid image URL.", data); } }) .catch(error => { console.error("Upload failed:", error); }); } }); } var appDescription = document.getElementById('app-description'); appDescription.addEventListener("focus", () => { var placeholder = "Description of Your AI solution"; if(appDescription.textContent.trim() == placeholder) { appDescription.textContent = ""; // Set a minimum width when the content is empty appDescription.style.minWidth = '200px'; // Adjust the value as needed } appDescription.style.border = "2px solid blue"; appDescription.style.backgroundColor = "lightblue"; appDescription.style.boxShadow = "0px 0px 5px rgba(0, 0, 0, 0.5)"; appDescription.style.whiteSpace = 'pre-wrap'; appDescription.style.padding = '14px'; appDescription.style.wordWrap = 'break-word'; appDescription.style.overflowWrap = 'break-word'; appDescription.style.maxWidth = '100%'; appDescription.style.overflow = 'hidden'; //appDescription.style.outline = 'none'; }); appDescription.addEventListener("blur", () => { var placeholder = "Description of Your AI solution"; if(appDescription.textContent.trim() == "") { appDescription.textContent = placeholder; } appDescription.style.whiteSpace = 'pre-wrap'; appDescription.style.padding = '14px'; appDescription.style.border = "1px solid lightgray"; appDescription.style.backgroundColor = ""; appDescription.style.boxShadow = ""; }); appDescription.addEventListener("paste", (event) => { event.preventDefault(); // Prevent default paste behavior // Get the plain text from the clipboard const plainText = (event.clipboardData || window.clipboardData).getData('text'); // Insert the plain text at the current caret position const selection = window.getSelection(); if (!selection.rangeCount) return; // Get the current range and replace it with plain text const range = selection.getRangeAt(0); range.deleteContents(); range.insertNode(document.createTextNode(plainText)); }); btnEditDescription.addEventListener('click', (event) => { // show forgotpassword event.preventDefault(); /*$('#app-description-update').show(); $('#app-description').hide(); var appDescription = document.getElementById("app-description"); const formattedText = appDescription.textContent.replace(/\n/g, "
"); // Replace newlines with
for HTML // Get the textarea element const textarea = document.getElementById('app-description-update'); // Set the textarea's value with the formatted text textarea.value = formattedText; // Create a temporary selection element (optional) const selection = document.createRange(); selection.selectNodeContents(textarea); try { // Attempt to copy the selection (if supported) const successful = document.execCommand('copy'); const msg = successful ? 'Formatted text copied!' : 'Browser may not support copying.'; alert(msg); } catch (err) { console.error('Copying failed:', err); alert('Failed to copy text. Consider manual copy/paste.'); } finally { // Cleanup the temporary selection (if created) selection.detach(); }*/ appDescription.contentEditable = true; appDescription.focus(); }); // add app category var appCategory = document.getElementById('app-category'); appCategory.addEventListener("focus", () => { appCategory.style.border = "2px solid blue"; appCategory.style.backgroundColor = "lightblue"; appCategory.style.boxShadow = "0px 0px 5px rgba(0, 0, 0, 0.5)"; appCategory.style.whiteSpace = 'pre-wrap'; appCategory.style.wordWrap = 'break-word'; appCategory.style.overflowWrap = 'break-word'; appCategory.style.maxWidth = '100%'; appCategory.style.overflow = 'hidden'; appCategory.style.wordBreak = 'break-word'; //appCategory.style.outline = 'none'; }); appCategory.addEventListener("blur", () => { appCategory.style.border = "1px solid lightgray"; appCategory.style.backgroundColor = ""; appCategory.style.boxShadow = ""; }); appCategory.addEventListener("paste", (event) => { event.preventDefault(); // Prevent default paste behavior // Get the plain text from the clipboard const plainText = (event.clipboardData || window.clipboardData).getData('text'); // Insert the plain text at the current caret position const selection = window.getSelection(); if (!selection.rangeCount) return; // Get the current range and replace it with plain text const range = selection.getRangeAt(0); range.deleteContents(); range.insertNode(document.createTextNode(plainText)); }); var btnEditCategory = document.getElementById('edit-category'); btnEditCategory.addEventListener('click', (event) => { event.preventDefault(); appCategory.contentEditable = true; appCategory.focus(); }); const faqList = document.getElementById('faq-list'); // Function to add a new FAQ input pair /*function addFaqEntry(question = '', answer = '') { const faqDiv = document.createElement('div'); faqDiv.style.marginBottom = "10px"; faqDiv.classList.add('faq-entry'); faqDiv.innerHTML = `
`; faqList.appendChild(faqDiv); const removeButton = faqDiv.querySelector('.remove-faq'); removeButton.addEventListener('click', () => { faqDiv.remove(); }); } // Add event listener to the "Add FAQ" button btnAddFAQ.addEventListener('click', () => addFaqEntry());*/ // Function to ensure only one event listener is attached to btnAddFAQ function setupFaqButtonListener() { // If the handler hasn’t been set yet, define it if (!handleAddFaqClick) { handleAddFaqClick = function () { addFaqEntry(); }; } // Remove any existing listener before adding a new one btnAddFAQ.removeEventListener('click', handleAddFaqClick); btnAddFAQ.addEventListener('click', handleAddFaqClick); } // Function to add a new FAQ input pair function addFaqEntry(question = '', answer = '') { const faqDiv = document.createElement('div'); faqDiv.style.marginBottom = "10px"; faqDiv.classList.add('faq-entry'); faqDiv.innerHTML = `
`; faqList.appendChild(faqDiv); const removeButton = faqDiv.querySelector('.remove-faq'); removeButton.addEventListener('click', () => { faqDiv.remove(); }); } // Call this function whenever the event listener needs to be ensured setupFaqButtonListener(); } } function Check_Stored_Tools() { // check account for stored tools // populates "my tools" section var accountInfo = JSON.parse(localStorage.getItem("accountInfo")); var mytools = accountInfo["tools"] || []; if(mytools.length > 0) { // show mytools container displayTools(mytools); $('#mytools').show(); } } async function getSession(sessionId) { try { var apiUrl = 'https://j8glspknjh.execute-api.eu-west-1.amazonaws.com/Production/Checkout'; const response = await fetch(apiUrl, { method: 'POST', body: JSON.stringify({ operation: 'get-session', sessionId: sessionId }), }); if (!response.ok) { throw new Error(`Error retrieving session: ${response.statusText}`); } const sessionData = await response.json(); console.log('Session Data:', sessionData); return sessionData; } catch (error) { console.error('Error retrieving session:', error); return null; } } function checkLoggedIn() { var agencyMember = localStorage.getItem("agencyMember") || null; var memberID = localStorage.getItem("memberID") || null; var authToken = localStorage.getItem("auth_token") || null; var authTokenCreated = localStorage.getItem("auth_token_date_created") || null; if(memberID && authToken && authTokenCreated) { if(!isAMonthOld(authTokenCreated)) { return true; } } return false; } function getCurrentDateString() { return new Date().toISOString(); } function isAWeekOld(dateString) { const oneWeek = 7 * 24 * 60 * 60 * 1000; // milliseconds in a week const givenDate = new Date(dateString); const currentDate = new Date(); return (currentDate - givenDate) > oneWeek; } function isAWeekOldUnix(unixTimestamp) { const oneWeekInSeconds = 7 * 24 * 60 * 60; // Seconds in a week const givenDateInSeconds = unixTimestamp; // Assuming input is in seconds const currentDateInSeconds = Math.floor(Date.now() / 1000); // Get current time in seconds return (currentDateInSeconds - givenDateInSeconds) > oneWeekInSeconds; } function isAMonthOld(dateString) { // Get milliseconds in a month (assuming 30 days) const oneMonth = 30 * 24 * 60 * 60 * 1000; // Use similar logic as in isAWeekOld const givenDate = new Date(dateString); const currentDate = new Date(); return (currentDate - givenDate) > oneMonth; } function isMoreThanXHoursOldUnix(unixTimestamp, hours) { const secondsPerHour = 60 * 60; // Calculate seconds in one hour const currentTimestamp = Math.floor(Date.now() / 1000); // Get current Unix timestamp in seconds const timeDifference = currentTimestamp - unixTimestamp; // Get time difference in seconds return timeDifference > hours * secondsPerHour; // Check if it exceeds the threshold } function ShowProcessing(mode) { var email = localStorage.getItem("email"); // switch to processing UI // hide formcontainer $('#Form-container').hide(); // hide waitlistcontainer $('#waitlist-container').hide(); // hide learn more $('#learn-more-container').hide(); // hide invite launcher $('#invite-launcher').hide(); // show processing containter // add email to processing email field $('#CheckStatusAddress').text(email); $('#processing-container').show(); // hide background video $('.background-video').hide(); $('.background-video-agency').hide(); // hide buttons $('#button-box').hide(); // add email to localstorage localStorage.setItem("email", email); localStorage.setItem("processStatus", mode); switch(mode) { case "processing": case "updating": case "processing/updating": // uses the default content $('#UpdateStatusTextH1').text("AI Profile is still " + mode); $('#UpdateStatusTextP1').text("Estimated time: 3 minutes"); $('#UpdateStatusTextP2').text("We will email you when it is ready at " + email); $('#CheckStatusAddress').text(email); // show check status button // hide retry button $('#btnCheckStatus').show(); $('#btnRetry').hide(); // hide cancel button $('#btnCancel').hide(); break; case "failed": // hide check status button $('#btnCheckStatus').hide(); $('#btnRetry').show(); $('#btnCancel').show(); // display message and use try again button $('#UpdateStatusTextH1').text("AI Profile " + mode); $('#UpdateStatusTextP1').text("Your profile encountered a problem and did not complete."); $('#UpdateStatusTextP2').text("Would you like to try again?"); $('#CheckStatusAddress').text(""); // think we need to set the click listener on btnRetry var btnRetry = document.getElementById("btnRetry"); btnRetry.removeEventListener('click', Retry); btnRetry.addEventListener('click', Retry); var btnCancel = document.getElementById("btnCancel"); btnCancel.removeEventListener('click', Cancel); btnCancel.addEventListener('click', Cancel); break; } } function HideProcessing(mode) { switch(mode) { case "loggedOut": break; case "loggedIn": // hide formcontainer $('#Form-container').hide(); // hide waitlistcontainer $('#waitlist-container').hide(); // hide learn more $('#learn-more-container').hide(); // hide invite launcher $('#invite-launcher').hide(); // hide processing containter $('#processing-container').hide(); // hide background video $('.background-video').hide(); $('.background-video-agency').hide(); $('#hero-holder').show(); $('.hcv-container').show(); $('#background-image-hero').show(); // hide buttons $('#button-box').hide(); break; } } function Cancel() { // use profile that was returned by failed - if present var profileStored = localStorage.getItem("profile"); // load original profile if(profileStored && (profileStored != "" && profileStored != "\"\"")) { HideProcessing("loggedIn"); ShowPreLoad(); LoadExistingProfile(profileStored); HidePreLoad(); HideProcessing("loggedIn"); // called again to hide background video (that is shown by hidepreload) ProcessingRequestShowUX(); firstLoad(); // show navbar buttons ShowNavButtons(); // update server to completed var storedMemberID = localStorage.getItem("memberID"); var storedAuthToken = localStorage.getItem("auth_token"); UpdateDBField(storedMemberID, storedAuthToken, "processStatus", "complete") .then(message => { // dont parse as UpdateDBField only returns the message switch(message) { case "FieldUpdate Complete": ConsoleLog("task cancelled"); break; case "FieldUpdate Failed": ConsoleLog("task cancellation failed"); break; } }) .catch(error => console.error("Error calling UpdateDBField: ", error)); /*switch(cancelUpdate) { case "no update message returned": case "no update message returned": break; }*/ // } else { // if there is no profile // need to allow new search NewSearch(); ShowNavButtons(); } } function Retry() { try { // send email back to server to do retry // NEXT: where do i get email from var email = localStorage.getItem("email"); // replace with memberID delivered by checkstatus var memberID = localStorage.getItem("memberID"); var auth_token = localStorage.getItem("auth_token"); // make sure it sends to login if these arent present var MYPEAS_payload = {}; MYPEAS_payload["promptDescription"] = "retry"; MYPEAS_payload["memberID"] = memberID; MYPEAS_payload["auth_token"] = auth_token; const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; requestData["RetryObj"] = {}; //requestData["RetryObj"]["email"] = email; requestData["RetryObj"]["memberID"] = memberID; requestData["RetryObj"]["auth_token"] = auth_token; localStorage.setItem("processStatus", "processing/updating"); var processStatus = "processing/updating"; // set page to show processing or updating UI // uses the default content $('#UpdateStatusTextH1').text("AI Profile is " + processStatus); $('#UpdateStatusTextP1').text("Estimated time: 3 minutes"); $('#UpdateStatusTextP2').text("We will email you when it is ready at " + email); //$('#CheckStatusAddress').text(email); // show check status button // hide retry button $('#btnCheckStatus').show(); $('#btnRetry').hide(); // hide cancel button $('#btnCancel').hide(); // trigger timer attempts = 0; startCheckStatusIntervals(); // Make an API call to API gateway - return will just indicate that it is processing var apiUrl = 'https://lt8psnfy4f.execute-api.eu-west-1.amazonaws.com/Production/MYPEASGPT'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData), }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); // we won't wait for this }); } catch(err) { console.error('Error:', err.message); console.error('Stacktrace:', err.stack); } } function NewSearch() { // show hero image // hide background video $('.background-video').hide(); $('.background-video-agency').hide(); $('#hero-holder').show(); $('.hcv-container').show(); $('#background-image-hero').show(); // hide waitlist container $('#waitlist-container').hide(); // hide invite launcher $('#invite-launcher').hide(); // hide processing containter $('#processing-container').hide(); // hide email and password fields, but pre-fill var email = localStorage.getItem("email"); $('#email-submit').hide(); $('#email-submit').val(email); $('#password').hide(); $('#password').val(''); // hide consent checkbox, but pre-check $('#checkbox-email').hide(); // this is the label that holds it $("#checkbox_email").prop("checked", true); // this makes the underlying checkbox checked // hide buttons $('#button-box').hide(); // generate button event // hide sign up job generate button $('#btnGetJob').hide(); // show new search generate button $('#btnGetJob_NewSearch').show(); $('#Form-container').show(); $('#learn-more-container').hide(); $('#segments-and-activities').hide(); // i think this works as is, but we need to test } //function UpdateDBField(email, password, fieldName, fieldValue) async function UpdateDBField(memberID, authToken, fieldName, fieldValue) { try { // request profile var UpdateValue = {}; //UpdateValue["email"] = email; // get from storage //UpdateValue["password"] = password; // get from storage UpdateValue["memberID"] = memberID; UpdateValue["auth_token"] = authToken; UpdateValue["fieldName"] = fieldName; UpdateValue["fieldValue"] = fieldValue; const requestData = {}; requestData["UpdateValue"] = UpdateValue; // send request to checkstatus on website // Make an API call to API gateway var apiUrl = 'https://lt8psnfy4f.execute-api.eu-west-1.amazonaws.com/Production/MYPEASGPT'; const response = await fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData) }); const result = await response.json(); ConsoleLog("update return: ",JSON.stringify(result)); return result["message"]; } catch (error) { console.error("Error calling UpdateDBField:", error); // You can log the error and return a specific message here (optional) return "Error updating account information"; } } function LogOut() { ConsoleLog('log out called'); // change the login/logout button // clear cookies clearCookies(); // delete all localstorage items localStorage.clear(); // go back to homescreen if (window.location.href.toLowerCase().includes('/agency')) { location.href = "/agency"; } else if(window.location.href.toLowerCase().includes('/admin')) { location.href = "/admin"; } else { location.href = "/"; } } function clearCookies() { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); const equalIndex = cookie.indexOf('='); const name = equalIndex > -1 ? cookie.substr(0, equalIndex) : cookie; document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/'; } } function LogIn() { // trigger login modal OpenCloseLoginModal("open"); // send email and password // on return // set profile in localstorage } function SubmitLogin(email, password) { var failed = false; var validateEmail = document.getElementById('validateLoginEmail'); var validatePassword = document.getElementById('validateLoginPassword'); var validationMessages = []; // hide all validation messages validateEmail.style.display = 'none'; validateEmail.style.color = 'red'; validatePassword.style.display = 'none'; validatePassword.style.color = 'red'; // validate loging fields if(!isValidEmail(email)) { failed = true; validateEmail.textContent = "Please enter a valid email"; validateEmail.style.display = 'block'; validationMessages.push(validateEmail.id); } //if(!isValidPassword(password)) if(!(password.length >= 8)) { failed = true; validatePassword.textContent = "Please enter a valid password"; validatePassword.style.display = 'block'; validationMessages.push(validatePassword.id); } if(!failed) { // clear localstorage localStorage.clear(); // show loading $('#login-modal #login-loading').show(); $('#login-modal #btnSubmitLogin').hide(); // submit to server // request profile var MYPEAS_payload = {}; MYPEAS_payload["JobTitle"] = ""; MYPEAS_payload["JobDescription"] = ""; MYPEAS_payload["promptDescription"] = "Login"; MYPEAS_payload["registered"] = "true"; // should always be true now that user provides password at start page MYPEAS_payload["email"] = email; // get from storage MYPEAS_payload["password"] = password; // get from storage const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // send request to checkstatus on website // Make an API call to API gateway var apiUrl = 'https://lt8psnfy4f.execute-api.eu-west-1.amazonaws.com/Production/MYPEASGPT'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData) }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); // empty storage localStorage.clear(); // hide loading $('#login-modal #login-loading').hide(); $('#login-modal #btnSubmitLogin').show(); ConsoleLog("Login return: ",JSON.stringify(result)); /*return { statusCode: 200, body: JSON.stringify({"message": "Profile Found", "promptDescription": promptDescription, "profile": checkUserObj["profile"], "processStatus": checkUserObj["processStatus"]}), }; */ // successful validation if(result.hasOwnProperty("profile")) { // show the nav buttons var btnMyAccount = document.getElementById('btnMyAccount'); var btnMyFavourites = document.getElementById("btnFavourites"); var btnTools = document.getElementById("btnTools"); var btnLogInOut = document.getElementById("btnLogInOut"); var btnAgency = document.getElementById("btnAgency"); var containerWaitList = document.getElementById('waitlist-container'); var skipContainer = document.getElementById('skipwaitlist-container'); $(btnMyAccount).show(); $(btnMyFavourites).show(); $(btnTools).show(); $(btnLogInOut).show(); $(btnAgency).hide(); $(btnLogInOut).text("Log Out"); $(containerWaitList).hide(); $(skipContainer).hide(); ConsoleLog("1"); // add email to localstorage localStorage.setItem("email", email); // hide linkedin modal var processStatus = result["processStatus"]; switch(processStatus) { case "complete": case "completed": ConsoleLog("2"); // check not empty profile var profile = result.profile; if(profile || (profile !== "" && profile !== "\"\"")) { // hide learn more $('#learn-more-container').hide(); if(profile == "") { HideProcessing("loggedIn"); NewSearch(); ShowNavButtons(); } if(profile != "") { // if completed and not empty - load profile in UI profile = result["profile"]; var favourites = result["favourites"] || JSON.stringify([]); var memberID = result["memberID"]; var authToken = result["auth_token"]; var auth_token_date_created = result["auth_token_date_created"]; var accountInfo = result["accountInfo"] || JSON.stringify({}); var orderHistory = result["orderHistory"] || JSON.stringify([]); var StripeInvoices = result["StripeInvoices"] || JSON.stringify([]); var revisions = result["revisions"] || "0"; var optIn = result["optIn"] !== undefined ? result["optIn"] : true; var paidAccount = result["paidAccount"] !== undefined ? result["paidAccount"] : "false"; if(paidAccount !== undefined) { localStorage.setItem("paidAccount", paidAccount); } else { localStorage.setItem("paidAccount", "false"); } if(optIn !== undefined) { // set optin in localstorage localStorage.setItem("optIn", optIn); } else { localStorage.setItem("optIn", "true"); } if(accountInfo == "") { accountInfo = JSON.stringify({}); } if(orderHistory == "") { orderHistory = JSON.stringify([]); } HideProcessing("loggedIn"); // set profile in localstorage localStorage.setItem("profile", JSON.stringify(profile)); localStorage.setItem("favourites", favourites); // set memberID localStorage.setItem("memberID", memberID); // set auth_token localStorage.setItem("auth_token", authToken); localStorage.setItem("auth_token_date_created", auth_token_date_created); localStorage.setItem("processStatus", "complete"); localStorage.setItem("accountInfo", accountInfo); localStorage.setItem("orderHistory", orderHistory); localStorage.setItem("StripeInvoices", StripeInvoices); localStorage.setItem("revisions", revisions); // load profile in UI - look into making this all work cleanly ConsoleLog("call LoadExistingProfile"); LoadExistingProfile(profile); // close modal OpenCloseLoginModal("close"); // we want to prompt user to complete details if missing from account // check accountInfo - this checks if accountinfo is complete accountInfo = JSON.parse(accountInfo); if(!checkAccountInfo(accountInfo)) { /*OpenAccountModal(); // show red text saying enter missing information $('#modal-message-account').text("** Complete Your Account Information **").show();*/ OpenOnboardModal(); } firstLoad(); } } else { OpenCloseLoginModal("close"); HideProcessing("loggedIn"); NewSearch(); ShowNavButtons(); } break; case "failed": // if failed - show retry // create a function for this //var revertProfile = result["RevertProfile"]; // or revert option if profile is present // if user chooses cancel then we just use the profile returned (the original profile) var profile = result["profile"]; var favourites = result["favourites"] || JSON.stringify([]); var memberID = result["memberID"]; var authToken = result["auth_token"]; var auth_token_date_created = result["auth_token_date_created"]; var accountInfo = result["accountInfo"] || JSON.stringify({}); var orderHistory = result["orderHistory"] || JSON.stringify([]); var StripeInvoices = result["StripeInvoices"] || JSON.stringify([]); var revisions = result["revisions"] || "0"; var optIn = result["optIn"] !== undefined ? result["optIn"] : true; var paidAccount = result["paidAccount"] !== undefined ? result["paidAccount"] : "false"; if(paidAccount !== undefined) { localStorage.setItem("paidAccount", paidAccount); } else { localStorage.setItem("paidAccount", "false"); } if(optIn !== undefined) { // set optin in localstorage localStorage.setItem("optIn", optIn); } else { localStorage.setItem("optIn", "true"); } if(accountInfo == "") { accountInfo = JSON.stringify({}); } if(orderHistory == "") { orderHistory = JSON.stringify([]); } HideProcessing("loggedIn"); // set profile in localstorage localStorage.setItem("profile", JSON.stringify(profile)); localStorage.setItem("favourites", favourites); // set memberID localStorage.setItem("memberID", memberID); // set auth_token localStorage.setItem("auth_token", authToken); localStorage.setItem("auth_token_date_created", auth_token_date_created); localStorage.setItem("processStatus", "failed"); localStorage.setItem("accountInfo", accountInfo); localStorage.setItem("orderHistory", orderHistory); localStorage.setItem("StripeInvoices", StripeInvoices); localStorage.setItem("revisions", revisions); ShowProcessing(processStatus); // close modal OpenCloseLoginModal("close"); // we want to prompt user to complete details if missing from account // check accountInfo - this checks if accountinfo is complete // add breakpoints and refresh page break; case "processing": case "updating": case "processing/updating": var profile = result["profile"]; var favourites = result["favourites"] || JSON.stringify([]); var memberID = result["memberID"]; var authToken = result["auth_token"]; var auth_token_date_created = result["auth_token_date_created"]; var optIn = result["optIn"] !== undefined ? result["optIn"] : true; var paidAccount = result["paidAccount"] !== undefined ? result["paidAccount"] : "false"; if(paidAccount !== undefined) { localStorage.setItem("paidAccount", paidAccount); } else { localStorage.setItem("paidAccount", "false"); } if(optIn !== undefined) { // set optin in localstorage localStorage.setItem("optIn", optIn); } else { localStorage.setItem("optIn", "true"); } localStorage.setItem("profile", JSON.stringify(profile)); localStorage.setItem("favourites", favourites); // set memberID localStorage.setItem("memberID", memberID); // set auth_token localStorage.setItem("auth_token", authToken); localStorage.setItem("auth_token_date_created", auth_token_date_created); localStorage.setItem("processStatus", processStatus); // if processing ShowProcessing(processStatus); // close modal OpenCloseLoginModal("close"); break; } } // validation failed if(!result.hasOwnProperty("profile")) { /*// fail to validate - tell user to login return { statusCode: 200, body: JSON.stringify({"message": "Account Exists. Wrong Password Entered", "promptDescription": promptDescription}), }; }*/ var message = result["message"]; if(message == "Account Exists. Wrong Password Entered") { validationMessages = []; failed = true; validatePassword.textContent = "Wrong Password Entered"; validatePassword.style.display = 'block'; validationMessages.push(validatePassword.id); } if(message == "Account Does Not Exist") { validationMessages = []; failed = true; validateEmail.textContent = "Please check account details"; validateEmail.style.display = 'block'; validationMessages.push(validatePassword.id); } } }); } if(failed) { // scroll to first error $('html, body').animate({ scrollTop: $('#' + validationMessages[0]).offset().top - 50 }, 500); } } function SubmitLogin_Agency(email, password) { var failed = false; var validateEmail = document.getElementById('validateLoginEmail'); var validatePassword = document.getElementById('validateLoginPassword'); var validationMessages = []; // hide all validation messages validateEmail.style.display = 'none'; validateEmail.style.color = 'red'; validatePassword.style.display = 'none'; validatePassword.style.color = 'red'; // validate loging fields if(!isValidEmail(email)) { failed = true; validateEmail.textContent = "Please enter a valid email"; validateEmail.style.display = 'block'; validationMessages.push(validateEmail.id); } //if(!isValidPassword(password)) if(!(password.length >= 8)) { failed = true; validatePassword.textContent = "Please enter a valid password"; validatePassword.style.display = 'block'; validationMessages.push(validatePassword.id); } if(!failed) { // clear localstorage localStorage.clear(); // show loading $('#login-modal #modal-spinner').show(); $('#login-modal #login-loading').show(); $('#login-modal #btnSubmitLogin').hide(); // submit to server // request profile var MYPEAS_payload = {}; MYPEAS_payload["JobTitle"] = ""; MYPEAS_payload["JobDescription"] = ""; MYPEAS_payload["requestDescription"] = "Login"; MYPEAS_payload["registered"] = "true"; // should always be true now that user provides password at start page MYPEAS_payload["email"] = email; // get from storage MYPEAS_payload["password"] = password; // get from storage const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // send request to checkstatus on website // Make an API call to API gateway var apiUrl = 'https://v2tu3f9o1e.execute-api.eu-west-1.amazonaws.com/AgencyStage/Agency'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData) }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); // empty storage localStorage.clear(); // hide loading $('#login-modal #modal-spinner').hide(); $('#login-modal #login-loading').hide(); $('#login-modal #btnSubmitLogin').show(); ConsoleLog("Login return: ",JSON.stringify(result)); /*return { statusCode: 200, body: JSON.stringify({"message": "Profile Found", "promptDescription": promptDescription, "profile": checkUserObj["profile"], "processStatus": checkUserObj["processStatus"]}), }; */ // successful validation if(result.hasOwnProperty("memberID")) { // show the nav buttons var btnMyAccount = document.getElementById('btnMyAccount'); var btnLogInOut = document.getElementById("btnLogInOut"); var btnAgency = document.getElementById("btnAgency"); $(btnMyAccount).show(); $(btnLogInOut).show(); $(btnAgency).hide(); $(btnLogInOut).text("Log Out"); ConsoleLog("1"); // add email to localstorage localStorage.setItem("email", email); var message = result["message"]; switch(message) { case "Profile Found": case "User Validated": ConsoleLog("2"); // if completed and not empty - load profile in UI var memberID = result["memberID"]; var authToken = result["auth_token"]; var auth_token_date_created = result["auth_token_date_created"]; var accountInfo = result["accountInfo"] || JSON.stringify({}); var orderHistory = result["orderHistory"] || JSON.stringify([]); var StripeInvoices = result["StripeInvoices"] || JSON.stringify([]); var bookingHistory = result["bookingHistory"] || JSON.stringify([]); var credits = result["credits"] || "0"; // this is the request sent to users for a booking to be made var requests = result["requests"]; var optIn = result["optIn"] !== undefined ? result["optIn"] : true; if(optIn !== undefined) { // set optin in localstorage localStorage.setItem("optIn", optIn); } else { localStorage.setItem("optIn", "true"); } if(accountInfo == "") { accountInfo = JSON.stringify({}); } var ApprovedStatus = accountInfo["ApprovedStatus"]; if(orderHistory == "") { orderHistory = JSON.stringify([]); } if(bookingHistory == "") { bookingHistory = JSON.stringify([]); } HideProcessing("loggedIn"); // set memberID localStorage.setItem("memberID", memberID); localStorage.setItem("agencyMember", true); // set auth_token localStorage.setItem("auth_token", authToken); localStorage.setItem("auth_token_date_created", auth_token_date_created); localStorage.setItem("accountInfo", accountInfo); localStorage.setItem("orderHistory", orderHistory); localStorage.setItem("StripeInvoices", StripeInvoices); localStorage.setItem("bookingHistory", bookingHistory); localStorage.setItem("credits", credits); localStorage.setItem("requests", requests); // load agency member profile in UI LoadAgencyAccount(accountInfo, result); // close modal OpenCloseLoginModal("close"); // hide background video - show hero image $('.background-video').hide(); $('.background-video-agency').hide(); // check for calendly link if (typeof accountInfo === 'string') { try { accountInfo = JSON.parse(accountInfo); } catch (error) { console.error("Error parsing JSON property:", error); } } var calendarLink = accountInfo["bookingLink"]; var calendarPresent = false; if(calendarLink && calendarLink != "") { calendarPresent = true; } if(!calendarPresent) { // prompt user to add calendar and open modal OpenCalendarModal(); } break; case "Account Exists. Wrong Password Entered": validationMessages = []; failed = true; validatePassword.textContent = "Wrong Password Entered"; validatePassword.style.display = 'block'; validationMessages.push(validatePassword.id); break; case "Account Does Not Exist": failed = true; validateEmail.textContent = "Please check account details"; validateEmail.style.display = 'block'; validationMessages.push(validatePassword.id); localStorage.clear(); break; } } // validation failed if(!result.hasOwnProperty("memberID")) { /*// fail to validate - tell user to login return { statusCode: 200, body: JSON.stringify({"message": "Account Exists. Wrong Password Entered", "promptDescription": promptDescription}), }; }*/ var message = result["message"]; if(message == "Account Exists. Wrong Password Entered") { validationMessages = []; failed = true; validatePassword.textContent = "Wrong Password Entered"; validatePassword.style.display = 'block'; validationMessages.push(validatePassword.id); } } }); } if(failed) { // scroll to first error $('html, body').animate({ scrollTop: $('#' + validationMessages[0]).offset().top - 50 }, 500); } } function SubmitLogin_Admin(email, password) { var failed = false; var validateEmail = document.getElementById('validateLoginEmail'); var validatePassword = document.getElementById('validateLoginPassword'); var validationMessages = []; // hide all validation messages validateEmail.style.display = 'none'; validateEmail.style.color = 'red'; validatePassword.style.display = 'none'; validatePassword.style.color = 'red'; // validate loging fields if(!isValidEmail(email)) { failed = true; validateEmail.textContent = "Please enter a valid email"; validateEmail.style.display = 'block'; validationMessages.push(validateEmail.id); } //if(!isValidPassword(password)) if(!(password.length >= 8)) { failed = true; validatePassword.textContent = "Please enter a valid password"; validatePassword.style.display = 'block'; validationMessages.push(validatePassword.id); } if(!failed) { // clear localstorage localStorage.clear(); // show loading $('#login-modal #login-loading').show(); $('#login-modal #btnSubmitLogin').hide(); // submit to server // request profile var MYPEAS_payload = {}; MYPEAS_payload["requestDescription"] = "LoginAdmin"; MYPEAS_payload["email"] = email; // get from storage MYPEAS_payload["password"] = password; // get from storage const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // send request to checkstatus on website // Make an API call to API gateway var apiUrl = 'https://v2tu3f9o1e.execute-api.eu-west-1.amazonaws.com/AgencyStage/Agency'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData) }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); // empty storage localStorage.clear(); ConsoleLog("LoginAdmin return: ",JSON.stringify(result)); // hide loading $('#login-modal #login-loading').hide(); $('#login-modal #btnSubmitLogin').show(); ConsoleLog("1"); // add email to localstorage localStorage.setItem("email", email); var processStatus = result["message"]; switch(processStatus) { case "validated": // if validated it returns the agency info for approvals var memberID = result["memberID"]; var authToken = result["auth_token"]; var auth_token_date_created = result["auth_token_date_created"]; var approvalsData = result["approvalData"]; // set memberID localStorage.setItem("memberID", memberID); // set auth_token localStorage.setItem("auth_token", authToken); localStorage.setItem("auth_token_date_created", auth_token_date_created); localStorage.setItem("adminMember", "true"); // show the nav buttons var btnLogInOut = document.getElementById("btnLogInOut"); var btnAgency = document.getElementById("btnAgency"); var containerWaitList = document.getElementById('waitlist-container'); var skipContainer = document.getElementById('skipwaitlist-container'); var promptLogin = document.getElementById('admin-prompt-login'); var codeGeneratorContainer = document.getElementById('admin-account-code-generator'); var sendRecruitAgencyContainer = document.getElementById("admin-account-send-email"); $(btnLogInOut).show(); $(btnAgency).hide(); $(btnLogInOut).text("Log Out"); $(containerWaitList).hide(); $(skipContainer).hide(); $(codeGeneratorContainer).show(); $(sendRecruitAgencyContainer).show(); // populate the cards // load approvals LoadApprovals(approvalsData); // close modal OpenCloseLoginModal("close"); // hide prompt login $(promptLogin).hide(); removeParam("login"); break; case "rejected": case "notauthenticated": case "failed": // require login // clear local storage and cookies localStorage.clear(); // can't delete the cookies, so set their values to expired. so we force UX to require new login // redirect to home page location.href = '/admin?login=true'; break; } }); } if(failed) { // scroll to first error $('html, body').animate({ scrollTop: $('#' + validationMessages[0]).offset().top - 50 }, 500); } } function checkAccountInfo(accountInfo) { var accountComplete = true; if(!accountInfo.hasOwnProperty("firstname") || (accountInfo.hasOwnProperty("firstname") && accountInfo["firstname"] == "")) { accountComplete = false; } if(!accountInfo.hasOwnProperty("surname") || (accountInfo.hasOwnProperty("surname") && accountInfo["surname"] == "")) { accountComplete = false; } if(!accountInfo.hasOwnProperty("location") || (accountInfo.hasOwnProperty("location") && !accountInfo["location"].hasOwnProperty("locationName"))) { accountComplete = false; } // add an extra so that old users can see the new onboarding experience if(!accountInfo.hasOwnProperty("onboard")) { accountComplete = false; } return accountComplete; } /* Admin page js */ function RequestAdmin() { var storedMemberID = localStorage.getItem("memberID"); var storedAuthToken = localStorage.getItem("auth_token"); var btnLogInOut = document.getElementById("btnLogInOut"); var btnAgency = document.getElementById("btnAgency"); var containerWaitList = document.getElementById('waitlist-container'); var skipContainer = document.getElementById('skipwaitlist-container'); var promptLogin = document.getElementById('admin-prompt-login'); var codeGeneratorContainer = document.getElementById('admin-account-code-generator'); var sendRecruitAgencyContainer = document.getElementById("admin-account-send-email"); // request profile var MYPEAS_payload = {}; MYPEAS_payload["requestDescription"] = "RequestAdmin"; MYPEAS_payload["memberID"] = storedMemberID; // get from storage MYPEAS_payload["auth_token"] = storedAuthToken; // get from storage MYPEAS_payload["ApprovalsFlag"] = {}; const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // send request to checkstatus on website // Make an API call to API gateway var apiUrl = 'https://v2tu3f9o1e.execute-api.eu-west-1.amazonaws.com/AgencyStage/Agency'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData) }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("processStatus return: ",JSON.stringify(result)); var processStatus = result["message"]; switch(processStatus) { case "validated": // if validated it returns the agency info for approvals var memberID = result["memberID"]; var authToken = result["auth_token"]; var auth_token_date_created = result["auth_token_date_created"]; var approvalsData = result["approvalData"]; // set memberID localStorage.setItem("memberID", memberID); // set auth_token localStorage.setItem("auth_token", authToken); localStorage.setItem("auth_token_date_created", auth_token_date_created); localStorage.setItem("adminMember", "true"); $(btnLogInOut).show(); $(btnAgency).hide(); $(btnLogInOut).text("Log Out"); $(containerWaitList).hide(); $(skipContainer).hide(); $(codeGeneratorContainer).show(); $(sendRecruitAgencyContainer).show(); // populate the cards // load approvals LoadApprovals(approvalsData); // close modal OpenCloseLoginModal("close"); // hide prompt login $(promptLogin).hide(); break; case "rejected": case "notauthenticated": case "failed": // require login // clear local storage and cookies localStorage.clear(); // can't delete the cookies, so set their values to expired. so we force UX to require new login // redirect to home page location.href = '/admin?login=true'; break; } }); } function LoadApprovals(approvalData) { const container = document.getElementById('dashboard-info-container'); container.innerHTML = ''; // Clear the container before appending new data if (approvalData.length === 0) { const noApprovalsMessage = document.createElement('div'); noApprovalsMessage.className = 'no-approvals-message'; noApprovalsMessage.innerText = 'No approvals at this time'; container.appendChild(noApprovalsMessage); } approvalData.forEach(approval => { approval = JSON.parse(approval["accountInfo"]["S"]); const card = document.createElement('div'); card.className = 'approval-card'; const companyName = approval.CompanyName; const websiteUrl = `https://${approval.WorkEmail.split('@')[1]}`; const contactNo = `${approval.TelephoneCode}${approval.TelephoneNo}`; const workEmail = approval.WorkEmail; card.innerHTML = `

${companyName}

${websiteUrl} Contact No: ${contactNo} Email: ${workEmail}

Approval Status: ${approval.ApprovedStatus}

`; switch(approval.ApprovedStatus) { case "Approved": case "approved": case "AwaitingApproval": case "rejected": card.innerHTML = card.innerHTML + `

`; break; case "InviteSent": `

`; break; case "processing": card.innerHTML = card.innerHTML + /*`*/ `

`; break; } container.appendChild(card); }); $('.admin-account-info-holder').show(); } function copyToClipboard(text) { navigator.clipboard.writeText(text).then(() => { alert('Copied to clipboard'); }).catch(err => { console.error('Could not copy text: ', err); }); } function confirmInvite(memberID, email, button) { // Also add flag to agency account var MYPEAS_payload = {}; MYPEAS_payload["requestDescription"] = "InviteSent"; MYPEAS_payload["InviteFlag"] = {}; // add agency data MYPEAS_payload["agencyMemberID"] = memberID; // get from storage MYPEAS_payload["agencyEmail"] = email; // get from storage MYPEAS_payload["ApprovedStatus"] = "InviteSent"; const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // send request to checkstatus on website // Make an API call to API gateway var apiUrl = 'https://v2tu3f9o1e.execute-api.eu-west-1.amazonaws.com/AgencyStage/Agency'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData) }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("message return: ",JSON.stringify(result)); var message = result["message"]; switch(message) { case "Completed": OpenModal("Success", "Invite Confirmed: Agency account updated", false); button.nextSibling.nextSibling.disabled = false; // Enable the "Approve" button break; case "failed": OpenModal("Failed", "Not Confirmed: Agency account NOT updated", false); break; } }); } var ClickListener; function LoadApprovalModal(callingElement, memberID, approvedStatus) { // uncheck the validation boxes var approvalModal = document.querySelector("#approve-modal"); const checkboxes = approvalModal.querySelectorAll('input[type="checkbox"]'); checkboxes.forEach(checkbox => { checkbox.checked = false; }); // set the clickevent on the approvebtn const ApproveBtn = document.querySelector('#ApproveBtn'); if(ClickListener) { ApproveBtn.removeEventListener('click', ClickListener); } ClickListener = () => { ApproveAgency(callingElement, memberID, approvedStatus)}; ApproveBtn.addEventListener('click', ClickListener); // open modal OpenApprovalModal(); } function OpenApprovalModal() { $('#approve-modal').animate({ opacity: 1 }).show(); } function CloseApprovalModal() { $('#approve-modal').animate({ opacity: 0 }).hide(); unLockScroll(); } function areAllCheckboxesChecked() { const calendarCheck = document.getElementById("calendarCheck").checked; const removeCalendarCheck = document.getElementById("removeCalendarCheck").checked; const zoomCheck = document.getElementById("zoomCheck").checked; const bookingPageCheck = document.getElementById("bookingPageCheck").checked; return calendarCheck && removeCalendarCheck && zoomCheck && bookingPageCheck; } function ApproveAgency(callingElement, memberID, approvedStatus) { // validate checkboxes before send /*if (areAllCheckboxesChecked()) {*/ ConsoleLog("All checkboxes are checked!"); // disable element until call back from server callingElement.prop('disabled', true); // change updating message callingElement.parent().find('#UpdatingStatus').text("Updating Status on server"); var storedMemberID = localStorage.getItem("memberID"); var storedAuthToken = localStorage.getItem("auth_token"); // request profile var MYPEAS_payload = {}; MYPEAS_payload["requestDescription"] = "ApproveAccount"; MYPEAS_payload["memberID"] = storedMemberID; // get from storage MYPEAS_payload["auth_token"] = storedAuthToken; // get from storage MYPEAS_payload["ApprovalsFlag"] = {}; // add agency data MYPEAS_payload["agencyMemberID"] = memberID; // get from storage MYPEAS_payload["ApprovedStatus"] = approvedStatus; const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // send request to checkstatus on website // Make an API call to API gateway var apiUrl = 'https://v2tu3f9o1e.execute-api.eu-west-1.amazonaws.com/AgencyStage/Agency'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData) }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("message return: ",JSON.stringify(result)); var processStatus = result["message"]; switch(processStatus) { case "Completed": // if validated it returns the agency info for approvals // change updating message callingElement.parent().find('#UpdatingStatus').text("Completed"); break; case "failed": // change updating message callingElement.parent().find('#UpdatingStatus').text("Fadiled Status update"); break; } }); // Your logic to approve the agency ConsoleLog(`Agency with memberID ${memberID} approved`); /* } else { ConsoleLog("Not all checkboxes are checked."); window.alert("Not all checkboxes are checked."); // ... your code to handle the unchecked state (e.g., display an error message) }*/ } // Example approval data for testing /* const approvalData = [ { CompanyName: "Example Corp", WorkEmail: "contact@example.com", TelephoneCode: "+1", TelephoneNo: "1234567890", bookingLink: "https://example.com/booking", memberID: "12345" }, // Add more data objects as needed ]; LoadApprovals(approvalData);*/ /* END Admin page */ function BuyPaidCredits() { } // add to order confirmation page // use fetch to update the server function OpenModal_OrderConfirmation(Title, Message, isLoading) { switch(isLoading) { case true: // hide close button $('#loading-update-modal .close-btn-w').hide(); $('#loading-update-modal #modal-spinner').show(); break; case false: $('#loading-update-modal .close-btn-w').show(); $('#loading-update-modal #modal-spinner').hide(); break; } // set title text $('#loading-update-modal #modal-title').text(Title); // set message text $('#loading-update-modal #modal-message').text(Message); // animate and show $('#loading-update-modal ').animate({ opacity: 1 }).show(); } function CloseModal_OrderConfirmation() { // close the modal using the close button $('#loading-update-modal .close-btn-w').click(function(){ /*$('.modal-popup').each(function() { if ($(this).is(':visible')) { $(this).animate({ opacity: 0 }).hide(); unLockScroll(); } });*/ $('#loading-update-modal').animate({ opacity: 0 }).hide(); unLockScroll(); }); // add it first, then call it $('#loading-update-modal .close-btn-w').click(); } function OpenNewSearchDialog() { //$('#new-search-holder').animate({ opacity: 1 }).show(); var newSearchHolder = document.querySelector('#new-search-holder'); // empty ui var addResponsibilitiesContainter = newSearchHolder.querySelector('#add-repsonsibilities-container'); if(addResponsibilitiesContainter) { addResponsibilitiesContainter.innerHTML = ''; } var responsibilitiesContainter = newSearchHolder.querySelector('#responsibilities'); var AI_responsibilitiesContainter = newSearchHolder.querySelector('#ai-responsibilities'); /*if(responsibilitiesContainter) { responsibilitiesContainter.innerHTML = ''; }*/ if(AI_responsibilitiesContainter) { AI_responsibilitiesContainter.innerHTML = ''; } // clear this of values - decided against that. keep them //selectedResponsibilities = []; // reset to the first step newSearchHolder.querySelectorAll(".wizard-step").forEach(step => { step.style.display = "none"; }); newSearchHolder.querySelector('#step1').style.display = "block"; // trigger modal $('#new-search-holder').css('z-index', '10001').animate({ opacity: 1 }).show(); // set focus to field $('#new-search-holder #jobTitle').focus(); } function CloseModal_New_Search() { $('#new-search-holder').animate({ opacity: 0 }).hide(); unLockScroll(); } function CloseModal_Agency_Account() { $('#agency-account-modal').animate({ opacity: 0 }).hide(); unLockScroll(); } function findCountryTaxes() { let result = { full: "", message: "", currencySymbol: "", currencyAbbreviation: "", amount: "" }; var countryTaxesContainer = [...document.querySelectorAll('.w-commerce-commercecheckoutordersummaryextraitemslistitem div')] .find(element => element.textContent.toLowerCase().includes("country taxes".toLowerCase()))?.parentElement; if (countryTaxesContainer) { var taxAmountElement = countryTaxesContainer.querySelector('div[data-wf-bindings*="CommercePrice"]'); if (taxAmountElement) { var taxAmountText = taxAmountElement.textContent.trim(); result.full = taxAmountText; result.message = "Tax present"; // Attempt to extract the numeric part as a string let numericPattern = /[\d.,]+/; let matches = taxAmountText.match(numericPattern); if (matches) { result.amount = matches[0]; // Extract non-numeric parts as potential currency symbols or abbreviations let nonNumericParts = taxAmountText.replace(numericPattern, '').trim(); // Heuristic to guess symbol and abbreviation let symbolMatch = nonNumericParts.match(/[\D]/); if (symbolMatch) { result.currencySymbol = symbolMatch[0]; } let abbreviationMatch = nonNumericParts.match(/[A-Za-z]{3}/); if (abbreviationMatch) { result.currencyAbbreviation = abbreviationMatch[0]; } } } else { result.message = "Tax amount element not found within the country taxes container."; } } else { result.message = "Country Taxes container not found."; } return result; } // Example usage: /*var taxDetails = findCountryTaxes(); ConsoleLog(taxDetails);*/ // Initialize an array to hold parts of the address var addressParts = []; function StoreInvoiceObject() { var invoiceObj = {}; invoiceObj["invoice-client-name"] = $('#invoice-client-name').text() || ""; invoiceObj["invoice-order-number"] = GetParam("orderId") || ""; invoiceObj["OrderID"] = GetParam("orderId") || ""; invoiceObj["invoice-order-date"] = getCurrentDateString(); invoiceObj["invoice-purchase-subtotal"] = $('#invoice-purchase-subtotal').text() || ""; invoiceObj["invoice-purchase-countrytaxes"] = findCountryTaxes() || ""; invoiceObj["invoice-purchase-total"] = $('#invoice-purchase-total').text() || ""; // Add each address part to the array if present addToAddress('#invoice-address-1'); addToAddress('#invoice-address-2'); addToAddress('#invoice-address-city'); addToAddress('#invoice-address-state'); addToAddress('#invoice-address-postcode'); addToAddress('#invoice-address-country'); // Join the parts with a comma to create a comma-separated string var addressString = addressParts.join(', '); invoiceObj["invoice-address"] = addressString; ConsoleLog(addressString); // Log the address string to the console or use as needed // itemised billing // create an array of items in the order, titles, quantities, prices return invoiceObj; } // Function to add text of an element to the addressParts array if it's not empty function addToAddress(selector) { var text = $(selector).text().trim(); if (text) { addressParts.push(text); } } function analyseOrder() { var orderObj = {}; var totalCredits = 0; var totalOrderType = ""; var itemsArray = []; $('[id=order-item-holder]').each(function() { try { // Extract order information with null/undefined checks var orderTitle = $(this).find('[id=order-title]').text().trim(); if (orderTitle === "") { orderTitle = "Unknown Title"; } var quantityElement = $(this).find('[id=order-quantity]'); var quantity = 0; if (quantityElement.length > 0) { quantity = parseInt(quantityElement.text().trim(), 10); if (isNaN(quantity)) { quantity = 0; } } // Find order price with null/undefined checks and fallback var orderPriceText = $(this).closest('.w-commerce-commercecheckoutorderitem').find('.order-price').text().trim(); var orderPriceMatch = orderPriceText.match(/([£$€¥])\s*([\d.,]+)\s*([A-Z]{3})/i); var orderPriceCurrency = "Unknown"; var orderPriceValue = 0; var orderPriceCurrencyCode = "Unknown"; if (orderPriceMatch) { orderPriceCurrency = orderPriceMatch[1]; orderPriceValue = parseFloat(orderPriceMatch[2].replace(/[^\d.]/g, '')); orderPriceCurrencyCode = orderPriceMatch[3].toUpperCase(); } // Calculate credits with default for unknown order types var orderType = "unknown"; var credits = 0; switch (orderTitle) { case "AI profile + 2 revisions": orderType = "employee_profile"; credits = 3; break; case "AI profile + 8 revisions": orderType = "employee_profile"; credits = 9; break; case "AI Meeting Accelerator (3 meetings)": orderType = "agency_meeting_credit"; credits = 3; break; case "AI Meeting Accelerator (10 meetings)": orderType = "agency_meeting_credit"; credits = 10; break; default: console.warn("Unknown order type: " + orderTitle); } var orderCredits = quantity * credits; totalCredits += orderCredits; // Create item object var item = { orderType: orderType, credits: orderCredits, orderTitle: orderTitle, quantity: quantity, orderPrice: { currency: orderPriceCurrency, currencyCode: orderPriceCurrencyCode, value: orderPriceValue }, totalPrice: quantity * orderPriceValue }; itemsArray.push(item); totalOrderType = orderType; // Output ConsoleLog("Order Type:", orderType); ConsoleLog("Order Credits:", orderCredits); } catch (error) { console.error("Error processing order (unexpected):", error); } }); ConsoleLog("Total Credits:", totalCredits); ConsoleLog("Items Array:", itemsArray); ConsoleLog("Credit Type:", totalOrderType); orderObj["totalCredits"] = totalCredits; orderObj["itemsArray"] = itemsArray; orderObj["creditType"] = totalOrderType; return orderObj; } function PaidAccountUpdate() { // take the orderid, store in user account so cant duplicate purchase var orderId = GetParam("orderId"); // use a modal to block the interface until complete OpenModal_OrderConfirmation("Confirming Purchase", "Thanks for your purchase. We are adding paid credits to your account.", true); var PaidUpdateData = {}; // change this. get memberID from localstorage. set this PaidUpdateData["memberID"] = localStorage.getItem("memberID"); PaidUpdateData["authToken"] = localStorage.getItem("auth_token"); PaidUpdateData["orderID"] = GetParam("orderId"); // NEXT // write a loop to check through all $('[id=order-title]') // discern between consumer buying profile credits and agent buying meeting credits // create a total number of credits for AI Meeting Accelerator based on Quantity in each type // AI Meeting Accelerator fuels your sales team with qualified AI/automation leads and pre-booked consultations. Target motivated businesses ready to invest in your solutions. Schedule a demo today! var orderObj = analyseOrder(); /*PaidUpdateData["creditType"] = orderObj["creditType"]; PaidUpdateData["totalCredits"] = orderObj["totalCredits"];*/ // NEXT - add invoice item information from itemsArray PaidUpdateData["invoiceData"] = StoreInvoiceObject(); // add itemsArray PaidUpdateData["invoiceData"]["itemsArray"] = orderObj["itemsArray"]; PaidUpdateData["invoiceData"]["creditType"] = orderObj["creditType"]; PaidUpdateData["invoiceData"]["totalCredits"] = orderObj["totalCredits"]; // https://mypeas.ai/?reset-password=yes&OTC=${OTC}&memberID=${memberIDValue} // url depends on client type // Make an API call to API gateway creditType = orderObj["creditType"]; switch(creditType) { case "employee_profile": PaidUpdateData["promptDescription"] = "PaidUpdate"; var requestData = {}; requestData["PaidUpdateData"] = PaidUpdateData; var apiUrl = 'https://lt8psnfy4f.execute-api.eu-west-1.amazonaws.com/Production/MYPEASGPT'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData) }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("PaidUpdate return: ",JSON.stringify(result)); // create a paid flag, so the profile returned is different if paid // store the orderId on server to prevent duplicates /* return { statusCode: 200, body: JSON.stringify({"message": "Upgraded to Paid", "promptDescription": promptDescription}), //, "profile": checkUserObj["profile"] }; */ switch(result.message) { /* UpgradeAccount */ case "Upgraded to Paid": /* return { statusCode: 200, body: JSON.stringify({"message": "Upgraded to Paid", "promptDescription": promptDescription, "profile": checkUserObj["profile"], "paidAccount": checkUserObj["paidAccount"], "revisions": checkUserObj["revisions"]}), //, "profile": checkUserObj["profile"] }; */ CloseModal_OrderConfirmation(); // update storage localStorage.setItem("paidAccount", result["paidAccount"]); ConsoleLog("paid account updated: " + result["paidAccount"]); // click back to profile var btnBackToProfile = document.getElementById('btnBackToProfile'); if(btnBackToProfile) { btnBackToProfile.click(); } break; /* UpgradeAccount */ case "PaidUpdate Failed": /* return { statusCode: 200, body: JSON.stringify({"message": "PaidUpdate Failed"}) }; */ ConsoleLog("paid account update failed"); function updateRetriesUrl(maxRetries = 5) { // Get the current URL const url = new URL(window.location.href); // Get the current value of the "retries" parameter, or initialize it to 0 let retries = parseInt(url.searchParams.get("retries")) || 0; // Check if the maximum retries have been reached if (retries >= maxRetries) { // Maximum retries reached, handle the error or display a message // ... (e.g., alert("Maximum retries exceeded. Please try again later.")) return url.toString(); // Return the current URL without further updates } // Increment the retry count retries++; // Update the "retries" parameter in the URL url.searchParams.set("retries", retries); // Return the updated URL return url.toString(); } // Example usage: const updatedUrl = updateRetriesUrl(); // Redirect the browser to the updated URL only if retries are still allowed if (updatedUrl !== window.location.href) { // Check for changes before redirection window.location.href = updatedUrl; } else { // alert user that failed and to contact us to activate your credit CloseModal_OrderConfirmation(); OpenModal("Problem", "Please contact us at support@mypeas.ai to activate your credit", false, false); } // Additional notes: /* This code uses the `URL` object to parse and manipulate the URL components. * The `parseInt` function is used to convert the retrieved "retries" value from a string to an integer. * The `maxRetries` parameter allows you to specify the maximum allowed retry count. * You can call this function multiple times to increment the retry count further. */ break; /* UpgradeAccount */ case "Already activated credit": /* return { statusCode: 200, body: JSON.stringify({"message": "Already activated credit", "promptDescription": promptDescription, "profile": checkUserObj["profile"], "paidAccount": checkUserObj["paidAccount"], "revisions": checkUserObj["revisions"]}), //, "profile": checkUserObj["profile"] }; */ CloseModal_OrderConfirmation(); // give message that this order was already activated OpenModal("Message", "You have already activated this purchase", false, false); break; } }); break; case "agency_meeting_credit": var requestData = {}; PaidUpdateData["promptDescription"] = "AddCredits"; requestData["PaidCreditsData"] = PaidUpdateData; requestData["MYPEAS_payload"] = {}; requestData["MYPEAS_payload"]["requestDescription"] = "AddCredits"; var apiUrl = 'https://v2tu3f9o1e.execute-api.eu-west-1.amazonaws.com/AgencyStage/Agency'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData) }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); ConsoleLog("AddCredits return: ",JSON.stringify(result)); // create a paid flag, so the profile returned is different if paid // store the orderId on server to prevent duplicates /* return { statusCode: 200, body: JSON.stringify({"message": "Added Credits", "credits": checkUserObj["credits"], "orderHistory": checkUserObj["orderHistory"]}), //, "profile": checkUserObj["profile"] }; */ switch(result.message) { /* UpgradeAccount */ case "Added Credits": /* return { statusCode: 200, body: JSON.stringify({"message": "Upgraded to Paid", "promptDescription": promptDescription, "profile": checkUserObj["profile"], "paidAccount": checkUserObj["paidAccount"], "revisions": checkUserObj["revisions"]}), //, "profile": checkUserObj["profile"] }; */ CloseModal_OrderConfirmation(); // update storage localStorage.setItem("credits", result["credits"]); localStorage.setItem("orderHistory", result["orderHistory"]); localStorage.setItem("StripeInvoices", result["StripeInvoices"]); localStorage.setItem("accountInfo", result["accountInfo"]); ConsoleLog("credits balance updated: " + result["credits"]); break; /* UpgradeAccount */ case "AddCredits Failed": /* return { statusCode: 200, body: JSON.stringify({"message": "AddCredits Failed"}) }; */ ConsoleLog("add credits failed"); function updateRetriesUrl(maxRetries = 5) { // Get the current URL const url = new URL(window.location.href); // Get the current value of the "retries" parameter, or initialize it to 0 let retries = parseInt(url.searchParams.get("retries")) || 0; // Check if the maximum retries have been reached if (retries >= maxRetries) { // Maximum retries reached, handle the error or display a message // ... (e.g., alert("Maximum retries exceeded. Please try again later.")) return url.toString(); // Return the current URL without further updates } // Increment the retry count retries++; // Update the "retries" parameter in the URL url.searchParams.set("retries", retries); // Return the updated URL return url.toString(); } // Example usage: const updatedUrl = updateRetriesUrl(); // Redirect the browser to the updated URL only if retries are still allowed if (updatedUrl !== window.location.href) { // Check for changes before redirection window.location.href = updatedUrl; } else { // alert user that failed and to contact us to activate your credit CloseModal_OrderConfirmation(); OpenModal("Problem", "Please contact us at support@mypeas.ai to activate your credit", false, false); } // Additional notes: /* This code uses the `URL` object to parse and manipulate the URL components. * The `parseInt` function is used to convert the retrieved "retries" value from a string to an integer. * The `maxRetries` parameter allows you to specify the maximum allowed retry count. * You can call this function multiple times to increment the retry count further. */ break; /* UpgradeAccount */ case "Already activated credit": /* return { statusCode: 200, body: JSON.stringify({"message": "Already activated credit", "promptDescription": promptDescription, "profile": checkUserObj["profile"], "paidAccount": checkUserObj["paidAccount"], "revisions": checkUserObj["revisions"]}), //, "profile": checkUserObj["profile"] }; */ CloseModal_OrderConfirmation(); // give message that this order was already activated OpenModal("Message", "You have already activated this purchase", false, false); break; } }); break; } } /* New stripe integration for main site checkout */ async function initiateCheckout(productType) { try { // Show loading state showLoadingState(); // Get user info from localStorage const userInfo = { memberID: localStorage.getItem("memberID"), authToken: localStorage.getItem("auth_token") }; // Validate user is logged in if (!userInfo.memberID || !userInfo.authToken) { alert("Please log in before purchasing"); hideLoadingState(); return; } var currentOrigin = window.location.origin; var successUrl = `${currentOrigin}?&success=true`; var cancelUrl = `${currentOrigin}?&cancel=true`; // Call your Lambda to create Stripe checkout session const response = await fetch('https://j8glspknjh.execute-api.eu-west-1.amazonaws.com/Production/Checkout', { method: 'POST', body: JSON.stringify({ operation: 'create-main-site-checkout-session', productType: productType, successUrl: successUrl, cancelUrl: cancelUrl, userInfo: userInfo }) }); const result = await response.json(); if (result.url) { // Redirect to Stripe checkout window.location.href = result.url; } else { throw new Error('Failed to create checkout session'); } } catch (error) { console.error('Checkout failed:', error); hideLoadingState(); alert('Checkout failed. Please try again.'); } } function showLoadingState() { document.querySelectorAll('.upgrade-button').forEach(btn => { btn.disabled = true; btn.textContent = 'Loading...'; }); } function hideLoadingState() { document.querySelectorAll('.upgrade-button').forEach((btn, index) => { btn.disabled = false; btn.textContent = 'Upgrade'; }); } function OpenDeleteAccount() { // hide loading spinner $('#spinner-holder-flex-delete-account').hide(); // show submit button $('#btnDeleteAccountSubmit').show(); // clear fields var deletePassword = document.getElementById('txtDeleteAccountPassword'); var deleteText = document.getElementById('txtDeleteAccountWord'); deletePassword.value = ""; deleteText.value = ""; // validation fields var validateDeletePassword = document.getElementById('validateDeletePassword'); validateDeletePassword.style.display = 'none'; validateDeletePassword.style.color = 'red'; var validateDeleteText = document.getElementById('validateDeleteWord'); validateDeleteText.style.display = 'none'; validateDeleteText.style.color = 'red'; // animate and show $('#delete-account-modal').animate({ opacity: 1 }).show(); // z axis bringModalToFront('delete-account-modal'); } function ValidateDeleteAccount() { var email = localStorage.getItem("email"); var failed = false; var password = $('#txtDeleteAccountPassword').val(); var typedWord = $('#txtDeleteAccountWord').val(); // validation fields var validateDeletePassword = document.getElementById('validateDeletePassword'); validateDeletePassword.style.display = 'none'; validateDeletePassword.style.color = 'red'; var validateDeleteText = document.getElementById('validateDeleteWord'); validateDeleteText.style.display = 'none'; validateDeleteText.style.color = 'red'; // validate password format if(!isValidPassword(password)) { failed = true; validateDeletePassword.textContent = "Please enter your password"; validateDeletePassword.style.display = 'block'; } // validate typed word if(typedWord.toLowerCase() != "DELETE".toLowerCase()) { failed = true; } if(!failed) { // show spinner $('#spinner-holder-flex-delete-account').show(); // hide submit button $('#btnDeleteAccountSubmit').hide(); var MYPEAS_payload = {}; MYPEAS_payload["JobTitle"] = ""; MYPEAS_payload["JobDescription"] = ""; MYPEAS_payload["promptDescription"] = "DeleteAccount"; MYPEAS_payload["registered"] = "true"; // should always be true now that user provides password at start page MYPEAS_payload["email"] = email; MYPEAS_payload["password"] = ""; const requestData = {}; requestData["MYPEAS_payload"] = MYPEAS_payload; // send request to checkstatus on website // Make an API call to API gateway var apiUrl = 'https://lt8psnfy4f.execute-api.eu-west-1.amazonaws.com/Production/MYPEASGPT'; fetch(apiUrl, { method: 'POST', body: JSON.stringify(requestData) }) // Then get the API response object, convert it to text and display it .then(response => response.text()) .then(result => { result = JSON.parse(result); // hide spinner again $('#spinner-holder-flex-delete-account').hide(); // show submit button $('#btnDeleteAccountSubmit').show(); switch(result.message) { case "Account Deleted": localStorage.clear(); // redirect to home page location.href = '/?login=true'; break; case "Internal Server Error": case "Failed Account Deleted": // close modal $('#delete-account-modal').animate({ opacity: 0 }).hide(); // open modal and show failed account delete OpenModal("Problem", "There was a problem deleting your account. Please try again or contact us for assistance.", false, false); break; default: break; } ConsoleLog("processStatus return: ",JSON.stringify(result)); }); } } function OpenModal(Title, Message, isLoading, requestCredit) { // set title text $('#modal-popup #modal-title').text(Title).show(); // set message text $('#modal-popup #modal-message').text(Message).show(); switch(isLoading) { case true: $('#modal-popup .close-btn-w').hide(); $('#modal-popup #modal-spinner').show(); break; case false: $('#modal-popup .close-btn-w').show(); $('#modal-popup #modal-spinner').hide(); break; } switch(requestCredit) { case true: // cancel timer if running stopCheckStatusIntervals(); // not using it anymore $('#modal-popup #btnPurchaseCredit').hide(); $('#modal-popup #pricing-table').show(); $('#modal-popup .close-btn-w').show(); $('#modal-popup #modal-spinner').hide(); $('#modal-popup #btnPurchaseCredit').text("PURCHASE CREDITS"); if(Title == "Maximize Your AI Potential") { $('#modal-popup #upgrade-message').show(); $('#modal-popup #modal-message').hide(); $('#modal-popup #btnPurchaseCredit').text("UPGRADE NOW"); } break; case false: $('#modal-popup #upgrade-message').hide(); $('#modal-popup #pricing-table').hide(); $('#modal-popup #btnPurchaseCredit').hide(); break; } // animate and show $('#modal-popup ').animate({ opacity: 1 }).show(); } function CloseModal() { // close the modal using the close button $('#modal-popup .close-btn-w').click(function(){ /*$('.modal-popup').each(function() { if ($(this).is(':visible')) { $(this).animate({ opacity: 0 }).hide(); unLockScroll(); } });*/ $('#modal-popup').animate({ opacity: 0 }).hide(); unLockScroll(); }); $('#modal-popup').animate({ opacity: 0 }).hide(); unLockScroll(); } function OpenCloseLoginModal(mode) { switch(mode) { case "open": // hide loading if present $('#login-modal .close-btn-w').show(); $('#login-modal #modal-spinner').hide(); // animate and show $('#login-modal ').animate({ opacity: 1 }).show(); break; case "close": // close the modal using the close button $('#login-modal').animate({ opacity: 0 }).hide(); unLockScroll(); break; } } function OpenCloseNewSearchModal(mode) { switch(mode) { case "open": // clear field values const JobTitle = document.getElementById('jobTitle-new'); const JobDescription = document.getElementById('jobDescription-new'); if(JobTitle){ JobTitle.value = "";} if(JobDescription){ JobDescription.value = "";} // hide loading if present $('#new-search-holder .close-btn-w').show(); $('#new-search-holder #modal-spinner').hide(); // animate and show $('#new-search-holder ').animate({ opacity: 1 }).show(); break; case "close": // close the modal using the close button $('#new-search-holder').animate({ opacity: 0 }).hide(); unLockScroll(); break; } } function ForgotPassword() { // set onlick - in loadmethods var ForgotPassword = document.getElementById('ForgotPassword'); ForgotPassword.addEventListener('click', (event) => { // show forgotpassword event.preventDefault(); // close the modal using the close button OpenCloseLoginModal("close"); // open forgotpassword modal OpenCloseForgotPasswordModal("open"); }); // validate email in btnSubmitForgotPassword } function OpenCloseForgotPasswordModal(mode) { switch(mode) { case "open": // hide login modal OpenCloseLoginModal("close"); // hide loading if present $('#forgot-password-modal .close-btn-w').show(); $('#forgot-password-modal #modal-spinner').hide(); // hide success message $('#forgot-password-message').hide(); // show main form $('#ForgotPasswordFormBlock').show(); // animate and show $('#forgot-password-modal').animate({ opacity: 1 }).show(); break; case "close": // close the modal using the close button $('#forgot-password-modal').animate({ opacity: 0 }).hide(); unLockScroll(); OpenCloseLoginModal("open"); break; } } function OpenCloseResetPasswordModal(mode) { switch(mode) { case "open": // hide all modals $('.close-btn-w').each(function() { if ($(this).is(':visible')) { $(this).click(); } }); // hide loading if present $('#reset-password-modal .close-btn-w').show(); $('#reset-password-modal #modal-spinner').hide(); // hide success message $('#reset-confirm-message').hide(); // show main form $('#reset-form').show(); // animate and show $('#reset-password-modal').animate({ opacity: 1 }).show(); break; case "close": // close the modal using the close button $('#reset-password-modal').animate({ opacity: 0 }).hide(); unLockScroll(); //OpenCloseLoginModal("open"); break; } } /* category modal */ function OpenCategoryModal(isLoading, Title, Message) { // clear any results $('#category-modal #category-content-holder').empty(); // always show loading initially //$('#category-modal .close-btn-w').hide(); $('#category-modal #modal-spinner').show(); // hide it when results found or not found /*switch(isLoading) { case true: $('#category-modal .close-btn-w').hide(); $('#category-modal #modal-spinner').show(); break; case false: $('#category-modal .close-btn-w').show(); $('#category-modal #modal-spinner').hide(); break; }*/ // set title text $('#category-modal #category-title').text(Title); // set message text $('#category-modal #category-subheading').text("More " + Title + " related AI applications"); // animate and show $('#category-modal ').animate({ opacity: 1 }).show(); } /* favourites modal */ function OpenFavourtiesModal(isLoading, Title, Message) { // clear any results $('#favourites-modal #favourites-content-holder').empty(); // always show loading initially $('#favourites-modal #modal-spinner').show(); // hide it when results found or not found // set title text $('#favourites-modal #favourites-title').text(Title); // set message text $('#favourites-modal #favourites-subheading').text("A collection of apps you have saved"); // animate and show $('#favourites-modal ').animate({ opacity: 1 }).show(); } /* lead modal */ function OpenLeadModal(isLoading, Title, Message) { // reset fields - do this at end // set title text $('#lead-modal #modal-title').text(Title); // set message text $('#lead-modal #modal-message').text(Message); // animate and show $('#lead-modal').animate({ opacity: 1 }).show(); // append countries to select addCountrySelect(document.getElementById('countrySelect_holder')); // append country codes addCountryCode(document.getElementById('countryCode_holder')); // reset form to q1 showNext('q1'); } function addCountrySelect(container) { var selectHTML = ``; /*if($('#countrySelect').length == 0) { container.append(selectHTML); }*/ //var countrySelect = document.getElementById('countrySelect'); var countrySelect = container.querySelector('#countrySelect'); if (countrySelect === null) { // Equivalent to jQuery's length check container.innerHTML = ""; container.innerHTML += selectHTML; // Assuming selectHTML is a string containing your HTML } // check for agency const currentUrl = window.location.href; const regex = /\/agency/; // Regular expression to match '/agency' countrySelect = container.querySelector('#countrySelect'); if (currentUrl.match(regex)) { // URL contains '/agency' ConsoleLog("The URL contains '/agency'"); // Add the classes to the existing classList countrySelect.classList.add('w-input', 'text-field'); } } function addCountryCode(container) { var countryCode = ``; /*if($('#countryCode').length == 0) { container.append(countryCode); }*/ var countryCodeElement = container.querySelector('#countryCode'); if (countryCodeElement === null) { container.innerHTML = ""; container.innerHTML += countryCode; // Assuming countryCode is a string of HTML } // check for agency const currentUrl = window.location.href; const regex = /\/agency/; // Regular expression to match '/agency' countryCodeElement = container.querySelector('#countryCode'); if (currentUrl.match(regex)) { // URL contains '/agency' ConsoleLog("The URL contains '/agency'"); // Add the classes to the existing classList countryCodeElement.classList.add('w-input', 'text-field'); } } function CreateMyAccount() { var myaccount = `

Name
Enter a valid first name
Enter a valid surname
Location
Select a location country
Email
Enter a valid email address
Credit Balance
Purchase History

Notifications
Delete Account
Logout
`; $('#accountInfoContainer').append(myaccount); // set event listener var buyCreditBtn = document.getElementById('myAccountBuyBtn'); if(buyCreditBtn) { buyCreditBtn.addEventListener('click', (event) => { CloseAccountModal(); OpenModal("Maximize Your AI Potential", "Need more help with your AI Strategy? Unlock it with a paid account", false, true); }); } } function CreateOnboardUI() { /* add confetti https://www.npmjs.com/package/js-confetti https://codepen.io/ieatwebsites/pen/KKBvywP */ var myaccount = `