"use strict";
try {
const urlKey = window.location.href.includes('ecostageview=true');
if (urlKey) {
var stg_script = document.createElement('script');
stg_script.src = "https://staging.api.ecocart.io/ecocart.js?shop=seekairun.com&shop_name=seekairun.com";
stg_script.async = true;
document.head.append(stg_script);
throw new Error("Stopping Execution!");
}
const ECO_PREVIEW_COOKIE_NAME_BASE = 'eco-preview'
window.getCookie = function (cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
/**
* Renders the toggle box at the bottom left
* @return {void}
*/
const renderToggleBox = () => {
const ecoCartPreviewCookieValue = getCookie(ECO_PREVIEW_COOKIE_NAME_BASE);
// Container
let toggleBox = document.createElement('div');
toggleBox.innerHTML = `
Preview Mode
`;
toggleBox.style = `
position: fixed;
text-align: center;
padding: 1rem;
bottom: 40px;
left: 40px;
height: 140px;
width: 400px;
box-shadow: rgb(0 0 0) 5px 5px 15px -5px;
color: #333333;
background: white;
border-radius: 0.3rem;
`;
// Toggle Button
let toggleBoxButton = document.createElement('button');
toggleBoxButton.innerHTML = ecoCartPreviewCookieValue === 'true' ? 'Disable' : 'Enable';
toggleBoxButton.style = `
background: white;
border: 1px solid #39b54a;
color: #39b54a;
border-radius: 0.3rem;
width: 100%;
padding: .5rem 1rem;
font-size: 1.25rem;
font-weight: 600;
font-family: Montserrat;
transition: all ease-in 0.15s;
`;
toggleBoxButton.onmouseover = function() {
this.style.background = '#39b54a';
this.style.color = 'white';
};
toggleBoxButton.onmouseleave = function() {
this.style.background = 'white';
this.style.color = '#39b54a';
};
toggleBoxButton.onclick = togglePreviewMode(ecoCartPreviewCookieValue);
// Add toggleBoxButton to toggleBox container
toggleBox.appendChild(toggleBoxButton);
// Add toggleBox to document.body
document.body.appendChild(toggleBox);
}
/**
* Toggles the value of the ECO_PREVIEW_COOKIE_NAME_BASE cookie
* and cleans the querystring from the window.location.herf
* @param {string} ecoCartPreviewCookieValue - The value of the preview mode cooikie
* @returns {void}
*/
const togglePreviewMode = (ecoCartPreviewCookieValue) => () => {
setCookieEcoCart(ECO_PREVIEW_COOKIE_NAME_BASE, ecoCartPreviewCookieValue === 'true' ? 'false' : 'true')
// Remove querystring
const [cleanedLocation] = window.location.toString().split(/[?#]/);
window.location.href = cleanedLocation;
}
var preview = true;
var jquery_ecocart = true;
// HTML CONSTANTS
const editor_box_html = `
Editor
`
const info_box_html = `
EcoCart Debugger Active
`
// FILTER CONSTANTS
var filterstrings = ['buy now', 'add to bouqet', 'add to cart', 'add', 'agregar al carrito', 'add to basket', 'add to bag', 'AƱadir al carrito', '^cart', 'pre-order', 'quick add', 'bag'];
var ecocart_debugger;
var ecocart_injection;
class Ecocart {}
class EcoCartMaster {
constructor(debug) {
this.currency_symbols = {
"usd":"$",
"mxn":"$",
"aud":"$",
"cad":"$",
"jpy":"¥",
"eur":"",
"inr":"₹",
"gbp":"£",
"aed":"Dhs.",
"cny":"¥",
"rub":"₽",
}
this.debug = debug;
this.ecocart_product = false;
this.div = false;
this.sidecart = false; // its true all cases except for checkout, cart page
this.iframe = false;
this.ecocartCheckbox = '#ecocart-green-shipping-button';
this.beforeSelector = '.cart-actions a.button.button--primary';
this.sidecart_selector = "a.button.button--primary.previewCartCheckout-checkoutButton";
this.sidecart_placement = "before"
this.subscription = false;
this.subscription_properties = [null];
this.selected_property = null;
this.current_state = false;
this.analytics_script = false;
this.uncheck_iframe = false;
}
async init() {
if (!window.location.href.includes('/cart') && !window.location.href.includes('checkout')) {
this.sidecart = true;
}
if (window.location.href.includes('/checkout')) {
this.getFormData();
}
this.injectCss();
this.design = await this.getDesign();
if(this.design.ab_testing && !this.debug) {
setCookieEcoCart('ab_test_shown', this.design.on);
jQuery.post('/cart/update.js?eco=true', `attributes[ecocart_shown]=${this.design.on}`);
if(!this.design.on) {
return
}
}
this.cart = await this.formatCart();
if(this.cart.item_count == 0 || this.cart.all_digital) {
return;
}
if (this.sidecart) {
this.setBoxState('sidecart_loading', false);
} else {
this.setBoxState('loading', false);
}
if (!this.result) {
this.result = await this.calculate();
}
if (this.result.fee == '3') {
if (this.sidecart) {
this.setBoxState('sidecart_company', false);
} else {
this.setBoxState('company', false);
}
this.generateIframeCompany(false);
return;
}
// variable set up
let re = /##PRICE##/gi;
var cur_symbol = "";
if (this.result.currency_used != undefined && this.result.currency_used != '' && this.result.currency_used.toLowerCase() != undefined) {
cur_symbol = this.currency_symbols[this.result.currency_used.toLowerCase()]
}
var calc_amount = (cur_symbol != "" && cur_symbol != undefined) ? cur_symbol + "" + this.result.calc : this.result.calc + " " + this.result.currency_used;
// if not debug replace the variables
if (!this.debug) {
this.design.shipment = this.design.shipment.replace(re, calc_amount)
if (this.design.sidecart_design && this.sidecart) {
this.design.sidecart_shipment = this.design.sidecart_shipment.replace(re, calc_amount)
}
this.design.estimate_price = this.design.estimate.replace(re, calc_amount)
if (this.design.sidecart_design && this.sidecart) {
this.design.sidecart_estimate_price = this.design.sidecart_estimate.replace(re, calc_amount)
}
} else {
this.design.estimate_price = this.design.estimate
if (this.design.sidecart_design && this.sidecart) {
this.design.sidecart_estimate_price = this.design.sidecart_estimate
}
}
if (this.ecocart_product) {
if (this.sidecart) {
this.setBoxState('sidecart_shipment', false);
} else {
this.setBoxState('shipment', false);
}
this.generateIframe(true);
if (!this.debug) this.listenForAdd();
return;
}
this.variant_id = this.result.variant_id;
if (this.sidecart) {
this.setBoxState('sidecart_estimate_price', false);
} else {
this.setBoxState('estimate_price', false);
}
this.generateIframe(false);
if(!this.debug) {
this.listenForAdd();
}
if(!this.sidecart) {
}
}
storeFormData() {
let form = Object();
var forms_all = document.querySelectorAll('form')
for (var i = 0; i < forms_all.length; ++i) {
var forms = forms_all[i]
Array.from(forms.elements).forEach((input) => {
form[input.name] = input.value
});
}
localStorage.setItem('ecocartForm', JSON.stringify(form));
}
getFormData() {
const excluded_inputs = ['authenticity_token','isConnectedAuth','clientId','merchantId','previous_step','scope','redirectURL','origin_url','apst','step','_method','button']
var retrieved = localStorage.getItem('ecocartForm');
if (retrieved) {
var form = JSON.parse(retrieved);
for (var key of Object.keys(form)) {
try {
if(excluded_inputs.includes(key)) {
continue;
}
var input = "input[name='" + key + "']"
if(key != '') {
var inputs = document.querySelectorAll(input)
inputs.forEach((item, i) => {
item.value = form[key]
});
}
} catch (e) {
console.error('Ecocart Exception', e);
}
}
}
}
async sidecartRun() {
this.setBoxState('loading', false);
this.cart = await this.formatCart();
if (this.cart.item_count == 0 || this.cart.all_digital) {
return;
}
if (!this.result) {
this.result = await this.calculate();
}
if(this.result.fee == '3') {
this.setBoxState('company', false);
this.generateIframeCompany(false);
return;
}
// price variable replacement
let re = /##PRICE##/gi;
var cur_symbol = "";
if (this.result.currency_used != undefined && this.result.currency_used != '' && this.result.currency_used.toLowerCase() != undefined) {
cur_symbol = this.currency_symbols[this.result.currency_used.toLowerCase()]
}
var calc_amount = (cur_symbol != "" && cur_symbol != undefined) ? cur_symbol+""+this.result.calc : this.result.calc+" "+this.result.currency_used;
this.variant_id = this.result.variant_id;
if (this.ecocart_product) {
if (!this.debug) {
this.design.shipment = this.design.shipment.replace(re, calc_amount)
if(this.design.sidecart_design && this.sidecart) {
this.design.sidecart_shipment = this.design.sidecart_shipment.replace(re, calc_amount)
}
this.listenForAdd();
}
this.setBoxState('shipment', false);
this.generateIframe(true);
return;
}
if (!this.debug) {
this.design.estimate_price = this.design.estimate.replace(re, calc_amount)
if (this.design.sidecart_design && this.sidecart) {
this.design.sidecart_estimate_price = this.design.sidecart_estimate.replace(re, calc_amount)
this.design.sidecart_shipment = this.design.sidecart_shipment.replace(re, calc_amount)
}
} else {
this.design.estimate_price = this.design.estimate
if (this.design.sidecart_design && this.sidecart) {
this.design.sidecart_estimate_price = this.design.sidecart_estimate
}
}
this.setBoxState('estimate_price', false);
this.generateIframe(false);
this.listenForAdd();
}
injectCss() {
const addition = this.sidecart ? '&sidecart=true' : ''
let cssUrl = "https://s.ecocartapp.com/ecocart.css?shop_name=seekairun.com" + addition;
let head = document.getElementsByTagName("head")[0];
let link = document.createElement("link");
link.id = 'ecocart-style-id';
link.rel = "stylesheet";
link.type = "text/css";
link.href = cssUrl;
link.media = "all";
head.appendChild(link);
}
async getDesign() {
if(window.sessionStorage && !this.debug) {
var stored_design = window.sessionStorage.getItem('ecocart_design')
if(stored_design != null) {
return JSON.parse(stored_design)
}
}
const ab_testing = getCookie('ab_test_shown')
var url = `https://s.ecocartapp.com/ecocart.json?shop_name=seekairun.com&ab_testing=${ab_testing}`;
if(this.debug) {
url+='&debug=true'
}
let response = await fetch(url, {});
let result = await response.json();
if(window.sessionStorage) {
window.sessionStorage.setItem('ecocart_design', JSON.stringify(result))
}
return result
}
fire_event(name) {
const event = new Event(name);
window.dispatchEvent(event);
}
setBoxState(state, add) {
this.current_state = state;
if(state == 'estimate_price') {
this.fire_event('ec_pricing');
this.current_state = 'estimate';
}
const original_state = state;
if(original_state == 'shipment') {
jQuery.post('/cart/update.js?eco=true', "attributes[ecocart_project_id]="+this.design.project_id);
}
if(original_state == 'company' && "False" == "True") {
jQuery.post('/cart/update.js?eco=true', "attributes[ec_platform]=true");
}
if(this.design.sidecart_design && this.sidecart) {
state = this.design['sidecart_' + state]
} else {
state = this.design[state]
}
if(!this.div) {
this.createDiv()
}
this.div.innerHTML = state
if(original_state == 'estimate_price') {
this.selected_property = this.subscription_properties[this.subscription_properties.length - 1]
}
}
handleSubscriptionChange(e) {
const val = parseInt(e.target.value)
ecocart_injection.selected_property = ecocart_injection.subscription_properties[val]
}
addWidgetOnCheckoutPage() {
/* checks if its checkout page and adds widget to it */
if (window.location.href.includes('checkout')) {
var placementStrings = ['check out', 'checkout', 'input shipping address', 'proceed to checkout', 'go to cart'];
var regex = new RegExp(placementStrings.join( "|" ), "i");
var buttons = jQuery('*').filter(function(){ return (regex.test(jQuery(this).text()) || regex.test(jQuery(this).val())) && (jQuery(this).prop('tagName')=='BUTTON' || jQuery(this).prop('tagName')=='A' || jQuery(this).prop('tagName')=='INPUT');})
let element = buttons[0]
this.div = document.createElement('div');
element.parentNode.parentNode.insertBefore(this.div, element.parentNode);
}
}
createDiv() {
try {
if (this.sidecart) {
this.createSidecart();
} else {
if (this.beforeSelector) {
this.div = document.createElement('div');
let before_element = document.querySelector(this.beforeSelector);
before_element.parentNode.insertBefore(this.div, before_element);
} else if (this.afterSelector) {
this.div = document.createElement('div');
let after_element = document.querySelector(this.afterSelector);
after_element.parentNode.insertBefore(this.div, after_element.nextSibling);
} else if (this.prependSelector) {
this.div = document.createElement('div');
let prepend_element = document.querySelector(this.prependSelector);
prepend_element.prepend(this.div);
} else if (this.appendSelector) {
this.div = document.createElement('div');
let append_element = document.querySelector(this.appendSelector);
append_element.append(this.div);
} else if (this.fixedSelector){
this.div = document.querySelector(this.fixedSelector);
} else {
this.div = document.createElement('div');
}
this.addWidgetOnCheckoutPage(); /* adds widget to checkout page */
}
this.fire_event('ec_show_success')
} catch (e) {
this.div = document.createElement('div');
if(window.location.href.includes('checkout')) {
let before_element = document.querySelector(".step__footer");
before_element.parentNode.insertBefore(this.div, before_element);
} else {
this.fire_event('ec_show_fail')
console.warn('Unable to inject ecocart, the error is below');
}
}
}
createSidecart() {
/* adds widget to sidecart only */
this.div = document.createElement('div');
let element = document.querySelector("a.button.button--primary.previewCartCheckout-checkoutButton");
switch(this.sidecart_placement) {
case 'before':
try {
element.parentNode.insertBefore(this.div, element);
this.fire_event('ec_show_success')
} catch (e) {
this.fire_event('ec_show_fail')
}
break;
case 'after':
try {
element.parentNode.insertBefore(this.div, element.nextSibling);
this.fire_event('ec_show_success')
} catch (e) {
this.fire_event('ec_show_fail')
}
break;
case 'append':
try {
element.prepend(this.div);
this.fire_event('ec_show_success')
} catch (e) {
this.fire_event('ec_show_fail')
}
break;
case 'prepend':
element.append(this.div);
this.fire_event('ec_show_success')
break;
default:
break;
}
}
async calculate() {
/*
step 1: tries to get calculation result from session storage
step 2: if not found in session storage gets from /ecocart POST, updates session storage
*/
if(window.sessionStorage) {
var stored_calculation = window.sessionStorage.getItem('ecocart_calculation')
if(stored_calculation != null) {
const parsed = JSON.parse(stored_calculation)
if(parsed[this.cart.total_variant]) {
return parsed[this.cart.total_variant];
}
}
}
let f = new FormData();
f.append('shop_name', "seekairun.com");
f.append('cart', JSON.stringify(this.cart));
let response = await fetch("https://s.ecocartapp.com/ecocart", {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
body: f
});
let result = await response.json();
if (window.sessionStorage) {
var stored_calculation = window.sessionStorage.getItem('ecocart_calculation')
if(stored_calculation != null) {
const parsed = JSON.parse(stored_calculation)
parsed[this.cart.total_variant] = result
window.sessionStorage.setItem('ecocart_calculation', JSON.stringify(parsed))
} else {
const parsed = {}
parsed[this.cart.total_variant] = result
window.sessionStorage.setItem('ecocart_calculation', JSON.stringify(parsed))
}
}
return result
}
listenForAdd() {
this.checkbox = document.querySelector(this.ecocartCheckbox);
if (this.checkbox) {
this.checkbox.addEventListener('change', () => {
this.addProduct(this.variant_id)
});
}
}
generateIframeCompany(success) {
var currency_iframe = {
"usd":36,
"mxn":36,
"aud":36,
"cad":36,
"jpy":165,
"eur":128,
"gbp":163,
"aed":"Dhs.",
"cny": 165,
"rub":8381,
}
if(this.iframe) {
this.iframe.remove();
}
var num_trees = 0;
var offset = this.result.co2;
var miles = 0;
num_trees = offset/25.2;
if(num_trees < 2) {
num_trees = 2
} else {
num_trees = Math.round(num_trees)
}
miles = 1.104 * offset;
setCookieEcoCart('trees',num_trees,5);
setCookieEcoCart('miles',miles,5);
setCookieEcoCart('offset',offset,5);
setCookieEcoCart('amount',this.result.calc,5);
setCookieEcoCart('ecocart_currency',this.result.currency_used.toLowerCase());
let tree = /##TREES##/gi;
this.div.innerHTML = this.div.innerHTML.replace(tree,num_trees);
var iframe = document.createElement('iframe');
iframe.src = 'https://admin.ecocart.io/tooltip/modal/?offset=' + Math.round(offset) + "&project_id=" + this.design.project_id + "&fee=15&company=See Kai Run" + "&miles=" + Math.round(miles) + "&trees="+ num_trees + "&amount=" + String.fromCharCode(currency_iframe[this.result.currency_used.toLowerCase()]) + this.result.calc + "#openModal";
iframe.id = "ecocart-modal-iframe";
iframe.style.position = "fixed";
iframe.style.top = 0;
iframe.style.left = 0;
iframe.style.height = "100%";
iframe.style.width = "100%";
iframe.style.zIndex = "2147483647";
iframe.style.border = "none";
iframe.style.display = "none";
this.iframe = iframe;
document.body.appendChild(iframe);
}
generateIframe(success) {
var currency_iframe = {
"usd":36,
"mxn":36,
"aud":36,
"cad":36,
"jpy":165,
"eur":128,
"gbp":163,
"aed":"Dhs.",
"cny": 165,
"rub":8381,
}
if(this.iframe) {
this.iframe.remove();
}
if(this.uncheck_iframe) {
this.uncheck_iframe.remove();
}
if(!success) {
var num_trees = 0;
var offset = 0;
var miles = 0;
offset = parseFloat(this.result.variant_title.match(/[\d\.]+/));
if(!offset) {
offset = this.result.co2
}
num_trees = offset/25.2;
if(num_trees < 2) {
num_trees = 2
} else {
num_trees = Math.round(num_trees)
}
miles = 1.104 * offset;
setCookieEcoCart('trees',num_trees,5);
setCookieEcoCart('miles',miles,5);
setCookieEcoCart('offset',offset,5);
setCookieEcoCart('amount',this.result.calc,5);
setCookieEcoCart('ecocart_currency',this.result.currency_used.toLowerCase());
let tree = /##TREES##/gi;
this.div.innerHTML = this.div.innerHTML.replace(tree,num_trees);
var iframe = document.createElement('iframe');
iframe.src = 'https://admin.ecocart.io/tooltip/modal/?offset=' + Math.round(offset) + "&project_id=" + this.design.project_id + "&fee=15&company=See Kai Run" + "&miles=" + Math.round(miles) + "&trees="+ num_trees + "&amount=" + String.fromCharCode(currency_iframe[this.result.currency_used.toLowerCase()]) + this.result.calc + "#openModal";
iframe.id = "ecocart-modal-iframe";
iframe.style.position = "fixed";
iframe.style.top = 0;
iframe.style.left = 0;
iframe.style.height = "100%";
iframe.style.width = "100%";
iframe.style.zIndex = "2147483647";
iframe.style.border = "none";
iframe.style.display = "none";
this.iframe = iframe;
document.body.appendChild(iframe);
} else {
let num_trees = getCookie('trees')
let tree = /##TREES##/gi;
this.div.innerHTML = this.div.innerHTML.replace(tree,num_trees);
var miles = getCookie('miles');
var offset = getCookie('offset');
var iframe = document.createElement('iframe');
iframe.src = 'https://admin.ecocart.io/tooltip/modal/?offset=' + Math.round(offset) + "&project_id=" + this.design.project_id + "&miles=" + Math.round(miles) + "&trees="+ num_trees + "&amount=ordered&fee=15&company=See Kai Run#openModal";
iframe.id = "ecocart-modal-iframe";
iframe.style.position = "fixed";
iframe.style.top = 0;
iframe.style.left = 0;
iframe.style.height = "100%";
iframe.style.width = "100%";
iframe.style.zIndex = "2147483647";
iframe.style.border = "none";
iframe.style.display = "none";
this.iframe = iframe;
document.body.appendChild(iframe);
}
const uncheck_iframe = document.createElement('iframe');
uncheck_iframe.id = "uncheck_modal_ecocart";
const styles = {
position: 'fixed',
top: 0,
left: 0,
height: "100%",
width: "100%",
zIndex: "2147483647",
border: 'none',
display: 'none'
}
Object.entries(styles).forEach(([key, value], i) => {
uncheck_iframe.style[key] = value
});
uncheck_iframe.src = `https://s.ecocartapp.com/uncheck?trees=${getCookie('trees')}&project=${this.design.project_id}`
this.uncheck_iframe = uncheck_iframe
document.body.appendChild(this.uncheck_iframe);
}
}
class EcoCartDebugger {
constructor() {
// this.injector = new EcoCartCalculation(true);
// this.feature_list = [EcoCartBoxEditor]
// this.editor = null;
}
async init() {
const s = document.createElement('script')
s.src = "https://s.ecocartapp.com/debug.js?shop=seekairun.com&shop_name=seekairun.com"
s.async = true;
s.defer = true;
document.head.append(s);
}
}
class EcoCartBoxEditor {
constructor() {
this.event_listener = "click";
this.editable_fields = "";
this.states = ['shipment', 'loading', 'estimate', 'company']
this.element_mapping = {
'#nested-ecocart-container': [
'border',
'padding',
'width',
'margin-top',
'margin-bottom',
'background-color',
'border-radius'
],
'#carbon-header': [
'font-size',
'font-family',
'font-weight',
'color',
'text-align',
'line-height'
],
'#ecocart-green-shipping-button': [
'alias-.ecocart-checker',
'top',
'bottom',
'left',
'right',
'height',
'width',
'border',
'border-radius'
],
'#eco-logo-image': [
'width',
'height',
'margin-top',
'margin-left'
],
'#eco-calc-price': [
'font-size',
'font-family',
'font-weight',
'color',
'text-align',
'line-height'
],
'#powered-ecocart-text': [
'font-size',
'font-family',
'font-weight',
'color',
'text-align',
'line-height'
],
'#eco-globe-image': [
'width',
'height',
'margin-top',
'margin-bottom',
'top',
'bottom',
'left',
'right',
]
}
this.selected_elements = []
}
init() {
this.info_box = document.createElement('div');
this.info_box.innerHTML = editor_box_html;
document.body.appendChild(this.info_box);
jQuery(document).mouseup(function(e)
{
var container = jQuery(".eco-tooltiptext");
// if the target of the click isn't the container nor a descendant of the container
if (!container.is(e.target) && container.has(e.target).length === 0)
{
container.hide();
}
});
for (var element in this.element_mapping) {
var selected_element = document.querySelector(element)
if(selected_element) {
selected_element.contentEditable = "true";
selected_element.addEventListener(this.event_listener, this.processChanges);
selected_element.addEventListener('contextmenu', this.stateSwitcher);
}
}
}
stateSwitcher(event) {
event.preventDefault();
jQuery('.eco-tooltiptext').show()
jQuery('.eco-tooltiptext').css({top: event.clientY, left: event.screenX - 100, position:'absolute'});
jQuery('.eco-tooltiptext').html('');
var tooltip = document.querySelector('.eco-tooltiptext')
ecocart_debugger.editor.states.forEach((item, i) => {
const button = document.createElement('button')
button.value = item;
button.innerHTML = item;
button.id = 'eco-button-switcher'
button.addEventListener('click',function() {
ecocart_debugger.injector.setBoxState(item,false);
for (var element in ecocart_debugger.editor.element_mapping) {
var selected_element = document.querySelector(element)
if(selected_element) {
selected_element.contentEditable = "true";
selected_element.addEventListener(ecocart_debugger.editor.event_listener, ecocart_debugger.editor.processChanges);
selected_element.addEventListener('contextmenu', ecocart_debugger.editor.stateSwitcher);
}
}
})
tooltip.appendChild(button);
});
return false;
}
processChanges(e) {
ecocart_debugger.editor.display_editor(e.target.id, e);
return false;
}
display_editor(element, event) {
let selector = "#" + element;
jQuery('.eco-tooltiptext').show()
jQuery('.eco-tooltiptext').css({top: event.clientY, left: event.screenX - 100, position:'absolute'});
this.populate_editor(selector);
}
populate_editor(s) {
jQuery('.eco-tooltiptext').html('');
var d = ecocart_debugger;
var selector = s;
const attributes = this.element_mapping[selector];
var tooltip = document.querySelector('.eco-tooltiptext')
attributes.forEach((item, i) => {
if(item.includes('alias-')) {
selector = item.replace('alias-','');
} else {
const input = document.createElement('input')
input.placeholder = item;
input.id = "eco-input-format"
input.addEventListener('change',function(e) {
jQuery(selector).css(item,e.target.value)
for (var state in ecocart_debugger.injector.design) {
switchDesign(state, item, e.target.value, selector);
}
})
tooltip.appendChild(input);
}
});
}
}
function switchDesign(state, item, value, selector) {
if(selector != "#nested-ecocart-container") {
var x = jQuery.parseHTML(ecocart_debugger.injector.design[state])
jQuery(x).find(selector).css(item,value)
ecocart_debugger.injector.design[state] = jQuery(x).prop('outerHTML')
} else {
var x = jQuery.parseHTML(ecocart_debugger.injector.design[state])
jQuery(x).css(item,value)
ecocart_debugger.injector.design[state] = jQuery(x).prop('outerHTML')
}
}
function setCookieEcoCart(cname, cvalue, exdays) {
var d = new Date();
const DAY_SCALAR = 24*60*60*1000
d.setTime(d.getTime() + (exdays*DAY_SCALAR));
var expires = `expires=${d.toUTCString()}`;
document.cookie = `${cname}=${cvalue};${expires};path=/`;
}
window.addEventListener('message', message => {
if(message.data == "ECOCART CLOSE IFRAME") {
document.getElementById("ecocart-modal-iframe").style.display = "none";
}
if(message.data == "CHECK ECOCART BOX") {
document.getElementById("ecocart-modal-iframe").style.display = "none";
document.getElementById("ecocart-green-shipping-button").checked = true
document.getElementById("ecocart-green-shipping-button").click();
}
if(message.data == 'CLOSE CHECK') {
document.getElementById('uncheck_modal_ecocart').style.display = "none"
document.getElementById('ecocart-green-shipping-button').checked = true
ecocart_injection.fire_event('uncheck_modal_cancel')
}
if(message.data == 'UNCHECK BOX') {
ecocart_injection.addProduct(ecocart_injection.variant_id, true)
ecocart_injection.fire_event('uncheck_modal_remove')
}
});
window.openEcoCartModal = () => {
document.getElementById("ecocart-modal-iframe").style.display = "block";
}
function addEcoCartListener(e) {
setTimeout(async function() {
if(!window.ecocart_injection) {return;}
ecocart_injection.ecocart_product = false;
if(ecocart_injection.div) {
ecocart_injection.div.remove();
ecocart_injection.div = false;
}
await ecocart_injection.sidecartRun();
},1000 + 1000)
}
function ecocartListeners() {
var regex = new RegExp( filterstrings.join( "|" ), "i");
var buttons = jQuery('*').filter(function(){ return (regex.test(jQuery(this).text()) || regex.test(jQuery(this).val())) && (jQuery(this).prop('tagName')=='BUTTON' || jQuery(this).prop('tagName')=='A' || jQuery(this).prop('tagName')=='INPUT' || jQuery(this).prop('tagName')=='LI');})
for (var i = 0, len = buttons.length; i < len; i++) {
buttons[i].setAttribute('ecl', 'true')
buttons[i].addEventListener("click",addEcoCartListener, false);
}
jQuery('body').on("click mousedown mouseup focus blur keydown change dblclick mouseover mouseout mousewheel keydown keyup keypress textInput touchstart touchcancel resize zoom select change submit reset",async function(e){
var regex = new RegExp( filterstrings.join( "|" ), "i");
var buttons = jQuery("[ecl!='true']")
for (var i = 0, len = buttons.length; i < len; i++) {
if(buttons[i].getAttribute('ecl') != 'true' && (regex.test(jQuery(buttons[i]).text()) || regex.test(jQuery(buttons[i]).val())) && (jQuery(buttons[i]).prop('tagName')=='BUTTON' || jQuery(buttons[i]).prop('tagName')=='A' || jQuery(buttons[i]).prop('tagName')=='INPUT')) {
buttons[i].setAttribute('ecl', 'true')
buttons[i].addEventListener("click", addEcoCartListener, false);
} else {
buttons[i].setAttribute('ecl', 'true')
}
}
})
var extra_selectors = jQuery('li.navUser-item.navUser-item--cart > a.navUser-action')
for (var i = 0, len = extra_selectors.length; i < len; i++) {
extra_selectors[i].setAttribute('ecl', 'true')
extra_selectors[i].addEventListener("click", addEcoCartListener, false);
}
}
class EcoCartCalculation extends EcoCartMaster {
constructor(debug) {
super(debug);
this.product_id = "828"
this.cart_id = null;
}
async formatCart() {
let response = await fetch("/api/storefront/cart");
var cart = await response.json();
cart[0].lineItems.digitalItems.forEach((item) => {
if (Number('828') === item.productId) {
this.ecocart_product = item;
}
});
cart.item_count = cart[0].lineItems.digitalItems.length + cart[0].lineItems.physicalItems.length
return cart;
}
setBoxState(state, add) {
const original_state = state;
state = this.design[state]
if(!this.div) {
this.createDiv()
}
this.div.innerHTML = state
}
createDiv() {
try {
if(this.sidecart) {
this.createSidecart();
} else {
if (this.beforeSelector) {
this.div = document.createElement('div');
let before_element = document.querySelector(this.beforeSelector);
before_element.parentNode.insertBefore(this.div, before_element);
} else if (this.afterSelector) {
this.div = document.createElement('div');
let after_element = document.querySelector(this.afterSelector);
after_element.parentNode.insertBefore(this.div, after_element.nextSibling);
} else if (this.prependSelector) {
this.div = document.createElement('div');
let prepend_element = document.querySelector(this.prependSelector);
prepend_element.prepend(this.div);
} else if (this.appendSelector) {
this.div = document.createElement('div');
let append_element = document.querySelector(this.appendSelector);
append_element.append(this.div);
} else if (this.fixedSelector){
// fixed
this.div = document.querySelector(this.fixedSelector);
} else {
this.div = document.createElement('div');
if(window.location.href.includes("checkout")) {
let selector = '.checkout-steps';
let element = document.querySelector(selector);
element.parentNode.appendChild(this.div, element);
}
else {
var regex = new RegExp( filterstrings.join( "|" ), "i");
var buttons = jQuery('*').filter(function(){ return (regex.test(jQuery(this).text()) || regex.test(jQuery(this).val())) && (jQuery(this).prop('tagName')=='BUTTON' || jQuery(this).prop('tagName')=='A' || jQuery(this).prop('tagName')=='INPUT');})
let element = buttons[buttons.length-1]
element.parentNode.insertBefore(this.div, element);
}
//.cart__policies
}
}
} catch (e) {
console.warn(e)
if(window.location.href.includes("checkout")) {
let selector = '.checkout-steps';
let element = document.querySelector(selector);
element.parentNode.appendChild(this.div, element);
}
}
}
async calculate() {
let f = new FormData();
f.append('shop_name', "seekairun.com");
if (this.latitude && this.longitude) {
f.append('latitude', this.latitude);
f.append('longitude', this.longitude);
}
this.cart_id = this.cart[0].id
f.append('cart', JSON.stringify(this.cart));
let response = await fetch("https://s.ecocartapp.com/ecocart", {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
body: f
});
let result = await response.json();
return result;
}
async addProduct(v_id) {
if (!this.ecocart_product) {
let data = {
line_items:[{ quantity: this.result.quantity, product_id: this.product_id, variant_id: this.variant_id }]
}
try {
var addURL = "/api/storefront/carts/" + this.cart_id + "/items"
let response = await fetch(addURL, {
method: 'POST',
cache: 'no-cache',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
let result = await response.json();
// update ecocart product
this.ecocart_product = result['lineItems']['digitalItems'].find((item) => item.variantId === this.variant_id);
if(this.sidecart) {
this.setBoxState('shipment', false)
this.generateIframe(true);
this.listenForAdd();
} else {
location.reload();
}
} catch (error) {
console.log(error);
}
} else {
this.cart_id = this.cart[0].id
try {
var deleteURL = "/api/storefront/carts/" + this.cart_id + "/items/"+ this.ecocart_product.id
await fetch(deleteURL, {
method: 'DELETE',
cache: 'no-cache',
credentials: 'same-origin',
headers: {'Content-Type': 'application/json'},
});
if(this.sidecart) {
this.ecocart_product = false;
this.sidecartRun();
} else {
location.reload();
}
} catch(error) {
console.log(error);
}
}
}
}
(function (p) {
if(!p) {return;}
if(!window.jQuery) {
jquery_ecocart = false;
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = 'text/javascript';
script.onload = function() {
if(window.location.href.includes('eco_debug=true')) {
ecocart_debugger = new EcoCartDebugger();
ecocart_debugger.init();
} else {
ecocart_injection = new EcoCartCalculation(false);
ecocart_injection.init();
}
ecocartListeners();
};
document.getElementsByTagName('head')[0].appendChild(script);
}
if(jquery_ecocart) {
if(window.location.href.includes('eco_debug=true')) {
ecocart_debugger = new EcoCartDebugger();
ecocart_debugger.init();
} else {
ecocart_injection = new EcoCartCalculation(false);
ecocart_injection.init();
}
}
})(preview);
(function(p) {
if(!p) {return;}
var open = window.XMLHttpRequest.prototype.open,
onReadyStateChange;
function openReplacement(method, url, async, user, password) {
var syncMode = async !== false ? 'async' : 'sync';
if((url.includes('change') || url.includes('update')) && !url.includes('eco=true')) {
setTimeout(async function() {
ecocart_injection.ecocart_product = false;
if(ecocart_injection.div) {
ecocart_injection.div.remove();
ecocart_injection.div = false;
}
await ecocart_injection.sidecartRun();
},1000 + 1000)
}
console.warn(
'Preparing ' +
syncMode +
' HTTP request : ' +
method +
' ' +
url
);
return open.apply(this, arguments);
}
function sendReplacement(data) {
console.warn('Sending HTTP request data : ', data);
if(this.onreadystatechange) {
this._onreadystatechange = this.onreadystatechange;
}
this.onreadystatechange = onReadyStateChangeReplacement;
return send.apply(this, arguments);
}
function onReadyStateChangeReplacement() {
console.warn('HTTP request ready state changed : ' + this.readyState);
if(this._onreadystatechange) {
return this._onreadystatechange.apply(this, arguments);
}
}
window.XMLHttpRequest.prototype.open = openReplacement;
})(preview);
(function(p,j){
if(!p) {return;}
if(!j) {
return
} else {
ecocartListeners();
}
})(preview, jquery_ecocart);
function ecocartReady() {
preview = true;
(function (p) {
if(!p) {return;}
if(!window.jQuery) {
jquery_ecocart = false;
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = 'text/javascript';
script.onload = function() {
if(window.location.href.includes('eco_debug=true')) {
ecocart_debugger = new EcoCartDebugger();
ecocart_debugger.init();
} else {
ecocart_injection = new EcoCartCalculation(false);
ecocart_injection.init();
}
ecocartListeners();
};
document.getElementsByTagName('head')[0].appendChild(script);
}
if(jquery_ecocart) {
if(window.location.href.includes('eco_debug=true')) {
ecocart_debugger = new EcoCartDebugger();
ecocart_debugger.init();
} else {
ecocart_injection = new EcoCartCalculation(false);
ecocart_injection.init();
}
}
})(preview);
(function(p) {
if(!p) {return;}
var open = window.XMLHttpRequest.prototype.open,
onReadyStateChange;
function openReplacement(method, url, async, user, password) {
var syncMode = async !== false ? 'async' : 'sync';
if((url.includes('change') || url.includes('update')) && !url.includes('eco=true')) {
setTimeout(async function() {
ecocart_injection.ecocart_product = false;
if(ecocart_injection.div) {
ecocart_injection.div.remove();
ecocart_injection.div = false;
}
await ecocart_injection.sidecartRun();
},1000 + 1000)
}
console.warn(
'Preparing ' +
syncMode +
' HTTP request : ' +
method +
' ' +
url
);
return open.apply(this, arguments);
}
function sendReplacement(data) {
console.warn('Sending HTTP request data : ', data);
if(this.onreadystatechange) {
this._onreadystatechange = this.onreadystatechange;
}
this.onreadystatechange = onReadyStateChangeReplacement;
return send.apply(this, arguments);
}
function onReadyStateChangeReplacement() {
console.warn('HTTP request ready state changed : ' + this.readyState);
if(this._onreadystatechange) {
return this._onreadystatechange.apply(this, arguments);
}
}
window.XMLHttpRequest.prototype.open = openReplacement;
})(preview);
(function(p,j){
if(!p) {return;}
if(!j) {
return
} else {
ecocartListeners();
}
})(preview, jquery_ecocart);
}
} catch (e) {
console.error('Ecocart Catches', e);
/* logging errors */
try {
const error = e.name;
const info = String(e.stack);
fetch(
`https://ibjlx2qt91.execute-api.us-east-1.amazonaws.com/api/error/fe_v1/ebc9d9a9-e5f4-4390-99f0-35b06bf43ea0/seekairun.com/${error}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: info
}
)
} catch (e) {
console.info('---* Failed Logging *---');
}
}