document.addEventListener('DOMContentLoaded', function () { // console.log('DOM is ready'); getThePlanCodes(); detectPageTypeAndDoThings(); mixpanel.init('f2ea11789cac8461684c61814bf2ea5a', { debug: false, track_pageview: false, persistence: 'localStorage' }); mixpanel.track('Magnifi Premium: Loaded a Page'); }); function setEmailCookie(email) { // Base64 encode the email const encodedEmail = btoa(email); // Create or update the cookies // First clear any existing cookies document.cookie = "ac=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; document.cookie = "upgraded=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; // Set new cookies - expires in 30 days const d = new Date(); d.setTime(d.getTime() + (30*24*60*60*1000)); document.cookie = `ac=${encodedEmail}; expires=${d.toUTCString()}; path=/;`; document.cookie = `upgraded=0; expires=${d.toUTCString()}; path=/;`; } function getEmailCookie() { const name = "ac="; const decodedCookie = decodeURIComponent(document.cookie); const ca = decodedCookie.split(';'); for(let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { // Base64 decode the email return atob(c.substring(name.length, c.length)); } } return ""; } function isRecurlyLoaded() { // console.log('Recurly.js is loaded'); return typeof recurly !== 'undefined'; } function isOrderFormPage() { // console.log('Checking if this is an order form page'); return document.getElementById('plan_code') !== null; } function isLeadGenPage() { return document.querySelector('.lp-pom-form') !== null; } function detectPageTypeAndDoThings() { // console.log('Detecting page type...'); if (isRecurlyLoaded() && isOrderFormPage()) { // console.log('This is an order form page with Recurly.js'); let publicKey; let division; const domain = window.location.hostname; // Capture just the hostname const path = window.location.pathname; // Capture the path switch (domain) { case 'offers.investorsalley.com': publicKey = 'ewr1-Q66Uuy0ZbVftIw1Az8iaV4';; division = 'IA'; break; case 'offers.stocknews.com': if (path === '/powr30-under10/') { publicKey = 'ewr1-Q66Uuy0ZbVftIw1Az8iaV4';; } else { publicKey = 'ewr1-F3kTLusxIPH1Q8iv5eNhQS'; } division = 'SN'; break; case 'offer.ino.com': publicKey = 'ewr1-wlfazXYxWlwvAClZJRysb1'; division = 'INO'; break; default: publicKey = 'ewr1-Q66Uuy0ZbVftIw1Az8iaV4'; division = 'SN'; // Or any default division value if needed break; } console.log('Configured Recurly.js with publicKey:', publicKey); recurly.configure({ publicKey: publicKey, currency: 'USD', fields: { all: { style: { padding: '0.25rem', fontSize: '1rem', fontWeight: '400', lineHeight: '1.5', color: '#212529', }, }, number: { selector: '#recurly-card-number', style: { placeholder: { content: 'Credit Card Number', }, }, }, month: { selector: '#recurly-card-month', style: { placeholder: { content: "Month", }, }, }, year: { selector: '#recurly-card-year', style: { placeholder: { content: "Year", }, }, }, cvv: { selector: '#recurly-card-cvv', style: { placeholder: { content: "CVV", }, }, }, }, }); if (document.getElementById('upgrade-plan')) { // console.log('Upgrade plan checkbox exists'); document.getElementById('upgrade-plan').addEventListener('change', updatePlanCost); } // add EF fields const _ef_transaction_id_value = getParameterByName('_ef_transaction_id'); const offer_id_value = getParameterByName('offer_id'); const affid_value = getParameterByName('affid'); const _ef_transaction_id = document.createElement('input'); _ef_transaction_id.type = 'hidden'; _ef_transaction_id.name = '_ef_transaction_id'; _ef_transaction_id.id = '_ef_transaction_id'; _ef_transaction_id.value = _ef_transaction_id_value || ''; const offer_id = document.createElement('input'); offer_id.type = 'hidden'; offer_id.name = 'offer_id'; offer_id.id = 'offer_id'; offer_id.value = offer_id_value || ''; const affid = document.createElement('input'); affid.type = 'hidden'; affid.name = 'affid'; affid.id = 'affid'; affid.value = affid_value || ''; const form = document.getElementById('recurly-form'); form.appendChild(_ef_transaction_id); form.appendChild(offer_id); form.appendChild(affid); // end EF fields } else if (isLeadGenPage()) { // console.log('This is a lead gen page with Unbounce native form'); var userEmail; function getUserEmail(form) { var emailInput = form.querySelector('input[type="email"]'); return emailInput ? emailInput.value : ''; } window.ub.hooks.afterFormSubmit.push(function (args) { userEmail = getUserEmail(args.formElement); mixpanel.identify(userEmail); mixpanel.track("Magnifi Premium: Leadgen Form Submission", { 'Email': userEmail, 'Division': 'IA' }); }); } else { console.log('Unable to determine the page type'); } } function tokenizeAndSubmit() { // Validate the form validate( [ 'first_name', 'last_name', 'email', 'address1', 'city', 'state', 'postal_code', 'country', 'phone', ], 'email', 'terms-of-service', 'postal_code', 'phone' ); // Tokenize the credit card information recurly.token({ first_name: document.querySelector('[data-recurly=first_name]').value, last_name: document.querySelector('[data-recurly=last_name]').value, // Recurly's Card Element will handle the card details address1: document.querySelector('[data-recurly=address1]').value, city: document.querySelector('[data-recurly=city]').value, state: document.querySelector('[data-recurly=state]').value, country: document.querySelector('[data-recurly=country]').value, postal_code: document.querySelector('[data-recurly=postal_code]').value, email: document.querySelector('[data-recurly=email]').value, plan_code: document.querySelector('[data-recurly=plan_code]').value, }, function (err, token) { if (err) { console.error(err); } else { // Log the token to the console for testing, remove when live //console.log('Recurly Token:', token.id); // Set the Recurly token in the hidden input document.querySelector('[name=recurly-token]').value = token.id; const email = document.getElementById('email').value; const planCode = document.getElementById('plan_code').value; const first_name = document.getElementById('first_name').value; const last_name = document.getElementById('last_name').value; const address1 = document.getElementById('address1').value; const address2 = document.getElementById('address2').value; const phone = document.getElementById('phone').value; const city = document.getElementById('city').value; const state = document.getElementById('state').value; const country = document.getElementById('country').value; const postal_code = document.getElementById('postal_code').value; const ref_url = document.getElementById('referrerUrl').value = window.location.href; const unbounceVariant = ub.page.variantId; const unbouncePageName = ub.page.name; const planCode2 = document.getElementById('plan_code2').value; const upgradePlanCheckbox = document.getElementById('upgrade-plan'); const cioElement = document.getElementById('cio'); const cioValue = cioElement !== null ? cioElement.value : 'false'; const _ef_transaction_id = document.getElementById('_ef_transaction_id').value; const offer_id = document.getElementById('offer_id').value; const affid = document.getElementById('affid').value; const eventId = typeof event_id !== 'undefined' ? event_id : null; let isUpgrade = false; if (upgradePlanCheckbox !== null && upgradePlanCheckbox.checked) { isUpgrade = true; } else { isUpgrade = false; } // Submit the form with the token submitOrder(token.id, email, planCode, first_name, last_name, address1, address2, phone, city, state, country, postal_code, ref_url, unbounceVariant, unbouncePageName, planCode2, isUpgrade, cioValue, _ef_transaction_id, offer_id, affid, eventId); } }); } function disableFormBtn() { document.getElementById('send').disabled = true; document.getElementById('send').innerText = 'Sending…'; } function reenableFormBtn() { document.getElementById('send').disabled = false; document.getElementById('send').innerText = 'Complete Purchase'; } function submitOrder(recurlyToken, email, planCode, first_name, last_name, address1, address2, phone, city, state, country, postal_code, ref_url, unbounceVariant, unbouncePageName, planCode2, isUpgrade, cioValue, _ef_transaction_id, offer_id, affid, eventId) { // indicate form submission disableFormBtn(); const endpoint = 'https://charge.investorsalley.com/orderProcess/'; const data = { recurlyToken: recurlyToken, email: email, plan_code: planCode, first_name: first_name, last_name: last_name, address1: address1, address2: address2, phone: phone, city: city, state: state, country: country, postal_code: postal_code, ref_url: ref_url, unbounceVariant: unbounceVariant, unbouncePageName: unbouncePageName, plan_code2: planCode2, isUpgrade: isUpgrade, cio: cioValue, _ef_transaction_id: _ef_transaction_id, offer_id: offer_id, affid: affid, eventId: eventId }; //console.log('Request Payload:', JSON.stringify(data)); fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }) .then(response => response.json()) .then(responseData => { //console.log('Response Data:', responseData); // Check if the status is success and if thank_you_url exists if (responseData.status === 'success' && responseData.thank_you_url) { // Mixpanel Event mixpanel.track("Magnifi Premium: Subscription Purchased", { 'Email': email, 'Division': 'IA' }); const currentCookie = getEmailCookie(); if (email) { // Assuming 'email' variable exists in scope setEmailCookie(email); } // Redirect the user to the thank_you_url window.location.href = responseData.thank_you_url; } if (responseData.status === 'error') { // Display the response on the page document.getElementById('response-container').innerText = JSON.stringify(responseData.message); document.getElementById('response-container').classList.remove('visually-hidden'); reenableFormBtn(); } if (responseData.status === 'three_d_secure_action_required' && responseData.url) { // Redirect the user to the 3d secure authentication page } }) .catch(error => { console.error('Error:', error); // Handle errors as needed reenableFormBtn(); }); } function validate(fields, emailId, tosId, zipId, phoneId) { // fields is an array of form IDs to check for missing values // others are specific form field IDs with additional validation requirements let err = false; let mssg = 'Please correct the following information:\n'; function checkMissing() { let missing = ''; for (fieldIndex in fields) { if (document.getElementById(fields[fieldIndex]).value === '') { err = true; missing += 'Missing '; missing += document.getElementById(fields[fieldIndex]).getAttribute('title'); missing += '\n'; document.getElementById(fields[fieldIndex]).classList.add('is-invalid'); } else { document.getElementById(fields[fieldIndex]).classList.remove('is-invalid'); } } mssg += missing; } function checkEmail() { const em = document.getElementById(emailId).value; if ( // check for minimum length (em.length >= 7) && // check for an @ sign (em.indexOf('@') !== -1) && // check for a domain name of at least 2 characters ((em.indexOf('@') + 2) < em.lastIndexOf('.')) && // check for a domain extension of at least 2 characters (em.lastIndexOf('.') < (em.length - 2)) ) { // email passes minimum validation document.getElementById(emailId).classList.remove('is-invalid'); } else { err = true; mssg += 'The email address is an invalid format.\n'; document.getElementById(emailId).classList.add('is-invalid'); } } function checkMinLength(field, ln) { const em = document.getElementById(field).value; const fieldTitle = document.getElementById(field).getAttribute('title'); if (em.length < ln) { err = true; mssg += 'The ' + fieldTitle + ' is an invalid format.\n'; document.getElementById(field).classList.add('is-invalid'); } else { document.getElementById(field).classList.remove('is-invalid'); } } function checkTerms() { if (!document.getElementById(tosId).checked) { err = true; mssg += 'You must agree to the terms of service.\n'; document.getElementById(tosId).classList.add('is-invalid'); } else { document.getElementById(tosId).classList.remove('is-invalid'); } } function doValidate() { checkMissing(); checkEmail(); checkTerms(); checkMinLength(zipId, 5); checkMinLength(phoneId, 10); } doValidate(); return !err; } // set plan cost on the client-side and update UI let standardPlanCost = 0; let upgradedPlanCost = 0; let totalCost = 0; let priceCheckUrl = 'https://charge.investorsalley.com/orderProcess/priceCheck/'; function fetchPlanCost(planCode) { let referer = window.location.origin + window.location.pathname; console.log('Fetching plan information...', planCode); console.log('Referer URL:', referer); return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest(); let params = 'plan_code=' + encodeURIComponent(planCode) + '&referer=' + encodeURIComponent(referer); console.log('Sending params:', params); // Log params to ensure correct format xhr.open('POST', priceCheckUrl, true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.onerror = function() { console.error('Request error:', xhr.statusText); }; xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { let planVar = parseFloat(xhr.responseText); resolve(planVar); } else { reject('Error fetching plan information.'); } } }; // Log the final request URL //console.log('Request URL:', priceCheckUrl); xhr.send(params); }); } function updatePlanCost() { // console.log('Updating plan cost...'); // upgrade plan cost if (document.getElementById('upgrade-cost')) { totalCost = upgradedPlanCost + standardPlanCost; document.getElementById('upgrade-cost').innerHTML = '$' + upgradedPlanCost; if (document.getElementById('upgrade-plan').checked) { document.getElementById('total-cost').innerHTML = '$' + totalCost.toFixed(2); } else { document.getElementById('total-cost').innerHTML = '$' + standardPlanCost.toFixed(2); } } // update the renewal cost if (document.getElementById('bump_renew')) { // console.log('bump renew'); let stdRenewTxt = 'in 12 months'; let bumpRenewTxt = 'after this promotional period'; function calcRenewPrice(renewField, className) { let renewPrice = parseInt(renewField.value); let renewElements = document.getElementsByClassName(className); for (let i = 0; i < renewElements.length; i++) { renewElements[i].innerHTML = '$' + renewPrice; } // console.log('Renewal Price:', renewPrice); } function setRenewalText(renewalText, className) { if (document.getElementsByClassName(className).length > 0) { let renewTextElements = document.getElementsByClassName(className); for (let i = 0; i < renewTextElements.length; i++) { renewTextElements[i].innerHTML = renewalText; } } } // bump renew if (document.getElementById('upgrade-plan').checked) { calcRenewPrice(document.getElementById('bump_renew'), 'renewal-cost'); setRenewalText(bumpRenewTxt, 'renewal-text'); // reg renew } else { calcRenewPrice(document.getElementById('reg_renew'), 'renewal-cost'); setRenewalText(stdRenewTxt, 'renewal-text'); } // set bump renewal in bump offer text if (document.getElementsByClassName('bump-renewal-cost').length > 0) { calcRenewPrice(document.getElementById('bump_renew'), 'bump-renewal-cost'); } } } function getThePlanCodes() { if (isRecurlyLoaded() && isOrderFormPage()) { // console.log('This is an order form page with Recurly.js'); const planCode = document.getElementById('plan_code').value; const planCode2Element = document.getElementById('plan_code2'); let planCode2 = null; let fetchPromise2 = Promise.resolve(0); if (planCode2Element && planCode2Element.value !== '') { planCode2 = planCode2Element.value; fetchPromise2 = fetchPlanCost(planCode2); } else { document.querySelector('.upgrade-offer').classList.add('visually-hidden'); } fetchPlanCost(planCode) .then(cost => { standardPlanCost = cost; // console.log('Standard Plan Cost:', standardPlanCost); return fetchPromise2; }) .then(cost => { upgradedPlanCost = cost; // console.log('Upgraded Plan Cost:', upgradedPlanCost); updatePlanCost(); }) .catch((err) => { console.error(err); }); } } // end UI updates function getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[[\]]/g, '\\$&'); var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, ' ')); }