function gaEcommerceSend(data) {
var subItem = {};
/* if (typeof ga === 'function') {
ga('require', 'ecommerce');
ga('ecommerce:addTransaction', {
id: data.transaction.transId,
affiliation: data.transaction.affiliation,
revenue: data.transaction.revenue,
shipping: data.transaction.shipping,
tax: data.transaction.tax,
currency: data.transaction.currency
});
for (item of data.items) {
subItem = {
id: data.transaction.transId,
name: item.name,
sku: item.sku,
price: item.price,
quantity: item.quantity
};
ga('ecommerce:addItem', subItem);
}
ga('ecommerce:send');
} else */
if (typeof gtag === 'function') {
var items = [];
for (item of data.items) {
items.push({
id: data.transaction.transId,
name: item.name,
sku: item.sku,
price: item.price,
quantity: item.quantity
});
}
if (window.website_settings.conversion_label) {
gtag('event', 'conversion', {
send_to: 'GT/' + window.website_settings.conversion_label
});
}
/** NEW DATA LAYER ***/
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'orderComplete',
orderValue: data.transaction.revenue,
orderId: data.transaction.transId,
orderCurrency: data.transaction.currency
});
/** EOF ***/
gtag('event', 'purchase', {
send_to: window.send_to['GAGT'],
transaction_id: data.transaction.transId,
affiliation: data.transaction.affiliation,
revenue: data.transaction.revenue,
shipping: data.transaction.shipping,
tax: data.transaction.tax,
currency: data.transaction.currency,
items: items
});
}
}
if (window.location.href.indexOf('eshop/checkout') != -1 || $('.simpleCart_grandTotal').length > 0 ) {
window.checkOut = 1;
} else {
window.checkOut = 0;
}
window.states = {};
(function () {
$.fn.serializeObject = function () {
var o = {};
var a = this.find("input,select,textarea").serializeArray();
//console.log(a);
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]]; //detailsFormSubmit
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$.fn.field = function (inputName, value) {
var that = this;
if (typeof inputName !== "string") return false;
var $inputElement = $(this).find("[name='" + inputName + "']").length > 0 ? $(this).find("[name='" + inputName + "']") : $(this).find("#" + inputName);
//console.log([inputName, value, $inputElement,$(this)]);
//console.log([inputName, value,$inputElement.is('input:text') , !$inputElement.val() , !value]);//ads_title
if (typeof value === "undefined" && $inputElement.length >= 1) {
switch ($inputElement.attr("type")) {
case "checkbox":
return $inputElement.is(":checked");
break;
case "radio":
var result;
$inputElement.each(function (i, val) {
if ($(this).is(":checked")) result = $(this).val()
});
return result;
break;
default:
return $inputElement.val();
break;
}
} else {
if ($inputElement.is('select') || $inputElement.is('textarea')) {
if ((inputName == 'model' || inputName == 'manufacturer') && $inputElement.find("option[value='" + value + "']").length === 0) {
var newOption = new Option(value, value, false, false);
$inputElement.append(newOption).trigger('change');
} else if (value > 0 && inputName == 'ads_categories_ads_categories_id' && $inputElement.find("option[value='" + value + "']").length === 0) {
var cat_name = window.currentAdInfo != undefined && window.currentAdInfo.cat_name != undefined ? window.currentAdInfo.cat_name : window.startAdInfo.cat_name;
//console.log(value,cat_name);
var newOption = new Option(cat_name, value, false, false);
$inputElement.append(newOption).trigger('change');
}
$inputElement.val(value).trigger('change');
return $inputElement;
} else if ($inputElement.is('input:text') && !$inputElement.val() && !value) {
return $inputElement;
} else {
switch ($inputElement.attr("type")) {
case "checkbox":
$inputElement.attr({
checked: (parseInt(value) || value == 'show' ? true : false)
});
break;
case "radio":
$inputElement.each(function (i) {
if ($(this).val() == value) $(this).attr({
checked: true
})
});
break;
case undefined:
$(this).append('');
break;
default:
$inputElement.val(value);
break;
}
}
return $inputElement;
}
}
$.fn.fields = function (object) {
if (typeof object === "undefined") {
return this.serializeObject();
} else {
for (filed in object) {
this.field(filed, object[filed]);
}
}
}
$.fn.classes = function (object) {
if (typeof object === "undefined") {
return false;
} else {
for (filed in object) {
this.field(filed, object[filed]);
$(this).find('.' + filed).text(object[filed]);
}
}
}
})();
/************************************************************
Main Scripts
*************************************************************/
! function ($) {
"use strict";
// Global Esc object
window.WEShopping = window.WEShopping || {};
window.WEShopping = {
/**
* Fire all functions
*/
init: function () {
var self = this,
obj;
for (obj in self) {
if (self.hasOwnProperty(obj)) {
var _method = self[obj];
if (_method.init !== undefined) {
_method.init();
}
}
}
},
shooping: {
selector: 'form#mainForm',
init: function () {
var base = this;
//console.log('dddd');
base.initShooping(base);
},
initShooping: function (base) {
//$.get("/eshop/get-buyer-profile-info/", function (res) {
// window.buyerProfile = res;
if (window.checkOut) {
var cartColumns = [{
attr: 'thumb',
label: false,
view: function (item, column) {
return ' ';
}
}, {
attr: "name",
label: "Name",
view: function (item, column) {
//return '
' + item.get('name') + ($.trim(item.get('stock_number')) ? 'Stock# ' + item.get('stock_number') + ' ' : '') + '
';
var html = '' + item.get('name') + ($.trim(item.get('stock_number')) ? ('Stock#' + item.get('stock_number') + ' ') : '');
html += (item.get('is_deposit') == 1 ? (item.get('deposit_type') == 'percentage' ? (' (' + item.get('deposit_rate') + '%) Deposit') : (' ($' + item.get('deposit_rate') + ') Deposit')) : '');
// html += (item.get('is_backorder') == 1 ? 'Temporarily Out of Stock ' : '');
/* if(item.get('is_backorder') == 1 ) {
if(item.get('instock_quantity') > 0) {
html += '
Instock: '+item.get('instock_quantity')+' Items Items out of '+item.get('quantity')+'Backorders: '+item.get('back_orders_quantity')+' Items out of '+item.get('quantity')+' ' ;
} else {
html += 'Temporarily Out of Stock ' ;
}
}*/
html += '';
return html;
}
}, {
attr: "shippable",
view: "itemShippingOption",
label: false,
className: "col-md-6 col-md-offset-6"
}, {
attr: "price",
label: "Price",
view: 'salePrice',
className: "text-center"
},
{
view: "decrement",
label: false,
text: "-",
className: "text-right"
},
/*{
attr: "custom_quantity",
label: "Qty",
className: "text-center item-quantity",
view: "customQuantity",
},*/
{
view: "quantityInput",
attr: "quantity",
label: "Qty",
className: "text-center"
},
{
view: "increment",
label: false,
text: "+",
className: "text-left"
},
{
attr: "backorder_quantity",
label: "Backorder Qty",
className: "col-md-12",
view: "backorderQuantity",
},
{
view: "remove",
text: ' ',
label: false,
className: "text-center"
},
];
} else {
var cartColumns = [{
attr: 'thumb',
label: false,
view: function (item, column) {
return ' ';
}
},
{
attr: "name",
label: "Name",
view: function (item, column) {
//return '' + item.get('name') + ($.trim(item.get('stock_number')) ? 'Stock#' + item.get('stock_number') + ' ' : '') + '
';
var html = '' + item.get('name') + ($.trim(item.get('stock_number')) ? ('Stock#' + item.get('stock_number') + ' ') : '');
html += (item.get('is_deposit') == 1 ? (item.get('deposit_type') == 'percentage' ? (' (' + item.get('deposit_rate') + '%) Deposit') : (' ($' + item.get('deposit_rate') + ') Deposit')) : '');
//html += (item.get('is_backorder') == 1 ? 'Temporarily Out of Stock ' : '');
html += '
';
return html;
}
},
{
attr: "price",
label: "Price",
view: 'salePrice',
className: "text-center"
},
/*{
attr: "total",
label: "SubTotal",
view: 'currency',
className: "text-center"
},*/
{
view: "decrement",
label: false,
text: "-",
className: "text-right"
},
{
view: "quantityInput",
attr: "quantity",
label: "Qty",
className: "text-center"
},
{
view: "increment",
label: false,
text: "+",
className: "text-left"
},
{
attr: "backorder_quantity",
label: "Backorder Qty",
className: "col-md-12",
view: "backorderQuantity",
},
{
view: "remove",
text: ' ',
label: false,
className: "text-center"
},
];
}
if (window.SellableItems == undefined) {
window.SellableItems = {};
}
simpleCart({
cartColumns: cartColumns,
cartStyle: "div",
currency: (window.SellableItems.paymentsCurrency == undefined ? 'CAD' : window.SellableItems.paymentsCurrency),
data: {},
language: "english-us",
excludeFromCheckout: [],
shippingCustom: null,
afterAdd: function (item) {
$('#cartBox').addClass('cart-open');
$('body').addClass('modal-open');
/*Swal.fire({
icon: 'success',
title: '\'' + item.get('name') + '\' Added',
width: 'auto',
showCloseButton: true,
showCancelButton: true,
focusConfirm: false,
confirmButtonText: ' Show Shopping Cart and Checkout',
confirmButtonAriaLabel: 'Show Shopping Cart and Checkout',
cancelButtonText: ' Continue Shopping',
cancelButtonAriaLabel: 'Continue Shopping'
}).then((result) => {
if (result.value) {
//showNormalModal('#cartModal');
$('#cartBox').addClass('cart-open');
//simpleCart.writeCart('.simpleCart_items');
simpleCart.init();
return false;
}
});*/
localStorage.setItem('simpleCart_quantityChange', Math.random());
base.checkItemsAvailability('quantityChange');
//console.log('quantityChange');
},
load: function () {
//alert('load');
//console.log('load');
window.simpleCartLoaded = true;
base.checkItemsAvailability('load');
},
beforeSave: function () {
// base.checkItemsAvailability();
},
beforeAdd: function () {
//simpleCart.load();
},
quantityChange: function () {
base.checkItemsAvailability('quantityChange');
},
afterSave: function () {
if (window.simpleCartLoaded) {
//console.log('afterSave');
localStorage.setItem('simpleCart_quantityChange', Math.random());
}
//alert('load');
// base.checkItemsAvailability();
},
/*update : function () {
console.log('update');
//alert('load');
// base.checkItemsAvailability();
},*/
/*ready: function () {
alert('ready');
base.checkItemsAvailability();
},*/
checkoutSuccess: null,
checkoutFail: null,
beforeCheckout: null,
beforeRemove: null
});
simpleCart.init();
$('body').on('click', '.cart-request-quote', function () {
if (simpleCart.quantity() == 0) {
Swal.fire({
icon: 'error',
title: "Cart is empty!",
showConfirmButton: true
})
return false;
} else {
bootbox.hideAll();
var email = '';
if (simpleCart.getSetting('TargetFullInfo') != undefined) {
email = simpleCart.getSetting('TargetFullInfo').Email;
}
Swal.mixin({
input: 'text',
confirmButtonText: 'Next →',
showCancelButton: true,
progressSteps: ['1', '2']
}).queue([{
input: 'email',
title: 'Enter your Email:',
inputValue: email
},
{
input: 'text',
title: 'Enter your Quote/Request or Question:',
confirmButtonText: 'Submit √',
}
]).then((result) => {
if (result.value) {
var cartHtml = $('.simpleCart_items')[0].outerHTML;
$.post('/eshop/request-quote/', {
quote: result.value,
cartHtml: cartHtml
}, function (res) {
if (res.error == true) {
Swal.fire({
icon: 'error',
title: res.message,
showConfirmButton: true
})
} else {
Swal.fire({
title: 'Request Sent!',
text: 'We usually reply within 24 hours, Thank you.',
confirmButtonText: 'Okay!'
})
}
})
}
})
}
})
$('body').on('click', '.add-to-cart', function () {
var itemId = $(this).data('itemid');
var item = window.SellableItems['items'][itemId];
var quantity = 1;
if ($('.quantityBoxBox').length) {
quantity = $('.quantityBoxBox').val();
}
var cartItem = simpleCart.find(itemId);
if (!Array.isArray(cartItem) && cartItem.get('is_deposit') == 1) {
Swal.fire({
icon: 'error',
title: 'You\'ve reached the maximum units allowed for the purchase of this item.',
showConfirmButton: true
})
return false;
}
if (!Array.isArray(cartItem) && cartItem.get('quantity') >= cartItem.get('max_quantity') && cartItem.get('is_backorder') == 0) {
Swal.fire({
icon: 'error',
title: 'You\'ve reached the maximum units available for the purchase of this item.',
showConfirmButton: true
})
return false;
} else if (!Array.isArray(cartItem) && simpleCart.uniqueQuantity() >= 25) {
Swal.fire({
icon: 'error',
title: 'You\'ve reached the maximum Unique Items Allowed per Order',
showConfirmButton: true
})
return false;
}
if (window.SellableItems.enableBackorders == 1 && item.quantity <= 1) {
///item.quantity = 1;
item.is_backorder = 1;
} else {
item.is_backorder = 0;
}
// console.log(item);
var depositRate = (item.itemDepositRate > 0 ? item.itemDepositRate : window.SellableItems.depositRate);
simpleCart.add({
id: itemId,
name: item.name,
price: item.price,
image: item.image,
url: item.url,
instock: 1,
quantity: quantity,
//shippingFlatRate: window.SellableItems.shippingFlatRate,
shippingTotalRate: window.SellableItems.shippingTotalRate,
tax_rate: 0, //window.SellableItems.taxRate,
taxShipping: window.SellableItems.taxShipping,
shippingQuantityRate: 0,
node_id: window.SellableItems.nid,
node_logo: window.SellableItems.logo,
deposit_rate: depositRate,
is_deposit: 0,
is_backorder: item.is_backorder,
max_quantity: (window.SellableItems.enableBackorders ? 1000 : item.quantity),
item_backorder: (window.SellableItems.enableBackorders ? 1 : 0),
stock_number: item.stock_number,
before_price: item.before_price,
pricing_rules: item.pricing_rules,
enable_free_Pickup: item.enableFreePickup
});
return false;
});
$('body').on('click', '.deposit-to-cart', function () {
var itemId = $(this).data('itemid');
var item = window.SellableItems['items'][itemId];
var cartItem = simpleCart.find(itemId);
if (!Array.isArray(cartItem)) {
Swal.fire({
icon: 'error',
title: 'You\'ve reached the maximum units allowed for the purchase of this item.',
showConfirmButton: true
})
return false;
}
if (window.SellableItems.enableBackorders == 1 && item.quantity <= 1) {
item.is_backorder = 1; //is_backorder
} else {
item.is_backorder = 0;
}
var depositRate = (item.itemDepositRate > 0 ? item.itemDepositRate : window.SellableItems.depositRate);
var depositType = item.itemDepositType;
if (depositRate == 0) {
return false;
}
//console.log([(item.price / depositRate),item.price , depositRate,((item.price * depositRate)/100)]);
simpleCart.add({
id: itemId,
name: item.name,
price: (depositType == 'percentage' ? ((item.price * depositRate) / 100) : depositRate),
image: item.image,
url: item.url,
instock: 1,
quantity: 1,
//shippingFlatRate: window.SellableItems.shippingFlatRate,
shippingTotalRate: window.SellableItems.shippingTotalRate,
tax_rate: 0, //window.SellableItems.taxRate,
taxShipping: window.SellableItems.taxShipping,
shippingQuantityRate: 0,
node_id: window.SellableItems.nid,
node_logo: window.SellableItems.logo,
deposit_rate: depositRate,
deposit_type: depositType,
is_deposit: 1,
is_backorder: item.is_backorder,
max_quantity: item.quantity,
stock_number: item.stock_number,
before_price: (depositType == 'percentage' ? ((item.before_price * depositRate) / 100) : 0),
item_backorder: 0,
pricing_rules: item.pricing_rules,
enable_free_Pickup: item.enableFreePickup
});
return false; //
});
$('body').on('click', '.shopping-cart', function () {
//showNormalModal('#cartModal');
$('#cartBox').addClass('cart-open');
$('body').addClass('modal-open');
//simpleCart.writeCart('.simpleCart_items');
simpleCart.init();
return false;
});
$('body').on('click', '.close-shopping-cart', function () {
$('#cartBox').removeClass('cart-open');
$('body').removeClass('modal-open');
return false;
});
$('body').on('click', '.back-shopping-cart', function () {
$('.cart-content').removeClass('open-login-screen');
return false;
});
$('body').on('click', '.shopping-logout', function () {
$.post('/index/logout', function () {
location.href = "/eshop/";
})
//return false;
});
$('.termsOfService').click(function () {
showIframeModal('/privacy', 'Terms Of Service');
return false;
});
$('#termsCheck').change(function () {
if ($(this).is(":checked")) {
$('#ShoppingRegister').prop('disabled', false);
} else {
$('#ShoppingRegister').prop('disabled', true);
}
});
$('#ShoppingRegister').click(function () {
base.submitRegisterForm(this);
return false;
})
$('#ShoppingSignIn').click(function (e) {
//console.log(e);
base.submitSignInForm(this);
return false;
})
$('#lostPassword').click(function () {
base.handelLostPassword(this);
return false;
})
$('#resetButton').click(function () {
base.resetForm(this);
return false;
});
$('body').on('click', '#saveBuyerProfile,.saveBuyerProfile', function () {
base.saveBuyerProfile(this);
return false;
});
$('body').on('change', '#countryDropDown,.countryDropDown', function () {
var val = $(this).val();
base.stateDropDown(val);
return false;
});
if ($('#completeBuyerProfile').length > 0) {
// base.countryDropDown();
if (window.buyerProfile) {
$('form#completeBuyerProfile').fields(window.buyerProfile);
setTimeout(function () {
$('[name="country_id"]').val(window.buyerProfile.country_id);
$('[name="state_id"]').val(window.buyerProfile.state_id);
}, 1000);
$('form#completeBuyerProfile').find(':input').change(function () {
$('#saveBuyerProfile').prop('disabled', false);
})
}
}
if ($('#buyerProfile').length > 0) {
base.stateDropDown(window.buyerProfile.country_id > 0 ? window.buyerProfile.country_id : 38);
if (window.buyerProfile) {
$('#buyerProfile').classes(window.buyerProfile);
}
}
if (window.init_msg) {
setTimeout(function () {
Swal.fire(window.init_msg);
}, 2000);
}
//})
},
checkItemsAvailability: function (event) {
if (event == 'quantityChange' && window.checkOut == false && 0) {
//simpleCart.init();
return;
} else {
var itemsInfo = simpleCart.getItemsInfo();
// console.log(simpleCart.getSetting('enableBackorders'), itemsInfo);
$.ajax({
type: "POST",
url: "/eshop/check-availability/",
data: {
itemsInfo: itemsInfo,
checkOut: window.checkOut,
fixedShipping:(window.fixedShipping != undefined && Object.entries(window.fixedShipping).length > 0 ? 1:0),
enableBackorders: simpleCart.getSetting('enableBackorders'),
},
dataType: "json",
beforeSend: function () {
if (window.checkOut == true) {
Swal.fire({
title: 'Please Wait...',
allowEscapeKey: false,
allowOutsideClick: false,
timer: 20000,
onOpen: () => {
swal.showLoading();
}
});
}
},
error: function () {
//console.log(res, 'error');
swal.close();
},
success: function (res, textStatus, jqXHR) {
swal.close();
//console.log(res);
if (res.error != undefined && res.error == 1) {
Swal.fire({
icon: 'error',
title: res.message,
});
$('#CartShippingMethod').prop('disabled', true).val(0);
$('a.checkout').addClass('disabled');
} else {
if (res.rates != undefined && res.rates.error != undefined && res.rates.error == 1) {
Swal.fire({
icon: 'error',
title: res.rates.message,
});
res.rates = {};
}
$('#CartShippingMethod').prop('disabled', false);
$('a.checkout').removeClass('disabled');
var updates = simpleCart.updateItems(res);
if (updates.removed.length > 0) {
var message = updates.removed.length == 1 ? "The item: '" + updates.removed[0] + "' is out of stock." : "The items: '" + updates.removed.join('\' \'') + " ' Are out of stock." //updates[0];
Swal.fire({
icon: 'info',
title: 'Some Items are out of stock!',
html: message,
});
} else if (updates.changedToBackorder.length > 0) {
var message = updates.changedToBackorder.length == 1 ? "The item: '" + updates.changedToBackorder[0] + "' is Temporarily out of stock." : "The items: '" + updates.changedToBackorder.join('\' \'') + " ' Are Temporarily out of stock." //updates[0];
Swal.fire({
icon: 'info',
title: 'Some Items are Temporarily out of stock!',
html: message,
});
}
}
}
});
}
},
stateDropDown: function (val, tval) {
var val = val || 0;
if (val == 0) {
// $('#stateDropDown,.stateDropDown').html('');
return;
}
/* newOption = new Option(item, item, false, false);
//console.log(item);
$(elm).append(newOption).trigger('change');*/
// console.log(window.states[val], val, tval);
if (val > 0) {
var tval = tval || 0;
// console.log(window.states[val]);
if (window.states[val] == undefined) {
$.post('/eshop/get-states/', {
stateId: val
}, function (res) {
window.states[val] = res;
var html = '';
html += 'Select a state ';
for (const [key, elm] of Object.entries(res)) {
html += '' + elm.name + ' ';
}
$('#stateDropDown,.stateDropDown').html(html).val(tval);
//console.log( html);
}, 'json');
} else {
var html = '';
html += 'Select a state ';
for (const [key, elm] of Object.entries(window.states[val])) {
html += '' + elm.name + ' ';
}
$('#stateDropDown,.stateDropDown').html(html).val(tval);
}
}
},
countryDropDown: function (val) {
var val = val || 0;
if (val == 0) {
//$('#countryDropDown,.countryDropDown').html('');
return;
}
var html = '';
var newOption;
for (const [key, elm] of Object.entries(window.dealerCountries)) {
html += '' + elm.name + ' ';
}
$('#countryDropDown,.countryDropDown').html(html).val(val).trigger('change');
WEShopping.shooping.stateDropDown(val);
},
handelLostPassword: function (button) {
Swal.fire({
title: 'Enter your login email to reset your password',
input: 'email',
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: true,
confirmButtonText: 'Submit',
showLoaderOnConfirm: true,
preConfirm: function (email) {
console.log(email);
$.post('/eshop/forgot-password', {
email: email
}, function (res) {
Swal.fire({
title: res.message
})
})
},
allowOutsideClick: () => !Swal.isLoading()
})
},
saveBuyerProfile: function (button) {
var $form = $(button).parents('form'); // $('form#completeBuyerProfile');
var errorFound = false;
$.when($form.find(':input').each(function (i, elm) {
var $parent = $(elm).closest('.form-group');
if (this.checkValidity() == false) {
$parent.addClass('has-error');
errorFound = true;
} else {
if ($parent.hasClass('has-error')) {
$parent.removeClass('has-error');
}
}
})).then(function () {
//console.log(errorFound);
if (errorFound) {
return false;
} else {
var data = $form.fields();
data.filesList = window.filesList;
$.post('/eshop/save-buyer-profile', data, function (res) {
//console.log(res);
if (res.error == false) {
if ($(button).data('value') == 'Update') {
Swal.fire({
icon: 'success',
title: 'Saved',
showConfirmButton: false,
timer: 1500,
width: 200
})
} else {
location.href = '/eshop/checkout';
}
} else {
Swal.fire({
icon: 'error',
html: res.message,
showConfirmButton: true
})
}
}, 'json')
return false;
}
})
},
submitSignInForm: function (button) {
var $form = $(button).parents('form');
var errorFound = false;
$.when($form.find(':input').each(function (i, elm) {
var $parent = $(elm).closest('.form-group');
if (this.checkValidity() == false) {
//console.log($parent, $(elm).attr('name'));
$parent.addClass('has-error');
errorFound = true;
} else {
if ($parent.hasClass('has-error')) {
$parent.removeClass('has-error');
}
}
})).then(function () {
if (errorFound) {
return false;
} else {
var data = $form.fields();
data.filesList = window.filesList;
$.post('/eshop/sign-in', data, function (res) {
//console.log(res);
if (res.error == false) {
location.href = '/eshop/checkout';
} else {
Swal.fire({
icon: 'error',
title: res.message,
showConfirmButton: true
})
}
}, 'json')
return false;
}
})
},
submitRegisterForm: function (button) {
var $form = $(button).parents('form');
var errorFound = false;
$.when($form.find(':input').each(function (i, elm) {
var $parent = $(elm).closest('.form-group');
if (this.checkValidity() == false) {
console.log($parent, $(elm).attr('name'));
$parent.addClass('has-error');
errorFound = true;
} else {
if ($parent.hasClass('has-error')) {
$parent.removeClass('has-error');
}
}
if ($(elm).attr('name') == 'password') {
if ($(elm).val() != $form.find('#confirm_password').val()) {
errorFound = true;
$form.find('#confirm_password').closest('.form-group').addClass('has-error');
//$('#confirm_password')[0].setCustomValidity("Passwords Don't Match");
} else {
$form.find('#confirm_password').closest('.form-group').removeClass('has-error');
//$('#confirm_password')[0].setCustomValidity('');
}
}
})).then(function () {
//console.log(errorFound);
if (errorFound) {
return false;
} else {
var data = $form.fields();
data.filesList = window.filesList;
$.post('/eshop/sign-up', data, function (res) {
//console.log(res);
if (res.error == false) {
Swal.fire({
icon: 'success',
title: res.message,
showConfirmButton: true
/*,
width: 200*/
})
} else {
Swal.fire({
icon: 'error',
title: res.message,
showConfirmButton: true
})
}
}, 'json')
return false;
}
})
}
},
stripe: {
init: function () {
var base = this;
base.initStripe(base);
},
initStripe: function (base) {
var handler = StripeCheckout.configure({
key: window.pk_stripe,
token: function (token) {
return base.commitCheckOut(token);
}
});
$('.checkout').on('click', function (e) {
if (simpleCart.quantity() == 0) {
Swal.fire({
icon: 'error',
title: "Cart is empty!",
showConfirmButton: true
})
return false;
} else if (simpleCart.getSetting('isCountrySupported') == 0 && simpleCart.getSetting('shippingServiceName').indexOf('Pickup') == -1) {
Swal.fire({
icon: 'error',
title: "Sorry, We don't ship to your country.",
showConfirmButton: true
})
return false;
} else if ($('.simpleCart_selectShipping').is(":visible") && $.trim($("#CartShippingMethod option:selected").html()).toLowerCase().indexOf('please select') !== -1) {
Swal.fire({
icon: 'error',
title: "Please Specify a Shipping Method!",
showConfirmButton: true
})
return false;
} else if (simpleCart.uniqueQuantity() > 25) {
Swal.fire({
icon: 'error',
title: "Max Number of Unique Items Allowed per Order is 25, \n Selected are: " + simpleCart.uniqueQuantity(),
showConfirmButton: true
})
return false;
}
if ((simpleCart.grandTotalAfterTax() + simpleCart.itemsRulesValue()) == 0 && simpleCart.grandTotal() == 0) {
base.commitCheckOut();
return false;
} else if (simpleCart.getSetting('isLocalPickupPreferred') == 0 && simpleCart.getSetting('shippingServiceName').indexOf('Pickup') != -1) {
Swal.fire({
icon: 'warning',
html: 'Please note your Province is different than the dealer\'s Province, it is recommended to select another shipping method. ',
width: 'auto',
showCloseButton: true,
showCancelButton: true,
focusConfirm: false,
confirmButtonText: ' Select Another shipping method',
confirmButtonAriaLabel: 'Select Another shipping method',
cancelButtonText: ' Continue',
cancelButtonAriaLabel: 'Continue'
}).then((result) => {
if (result.value) {
return false;
} else if (result.dismiss == 'cancel') {
var image = simpleCart.nodeLogo();
//console.log(simpleCart.grandTotal());
handler.open({
name: window.website_settings.website_name,
amount: Math.round((simpleCart.grandTotal() + Number.EPSILON) * 100),
locale: 'auto',
allowRememberMe: true,
description: simpleCart.quantity() + " Items",
currency: simpleCart.currency().code,
email: window.buyerProfile.user_email,
image: image,
//zipCode: true,
billingAddress: simpleCart.isBillingAllowed(),
//allowRememberMe: true//allow_billing_address
});
}
})
} else {
var image = simpleCart.nodeLogo();
//console.log(simpleCart.grandTotal());
handler.open({
name: window.website_settings.website_name,
amount: Math.round((simpleCart.grandTotal() + Number.EPSILON) * 100),
locale: 'auto',
allowRememberMe: true,
description: simpleCart.quantity() + " Items",
currency: simpleCart.currency().code,
email: window.buyerProfile.user_email,
image: image,
//zipCode: true,
billingAddress: simpleCart.isBillingAllowed(),
//allowRememberMe: true
});
}
e.preventDefault();
});
$('body').on('click', '.cartCheckout', function (e) {
if (window.website_settings.isBuyerLoged > 0) {
location.href = '/eshop/checkout';
} else {
$('.cart-content').toggleClass('open-login-screen');
}
});
// Close Checkout on page navigation
$(window).on('popstate', function () {
handler.close();
});
},
commitCheckOut: function (token = {}) {
var TargetFullInfo = simpleCart.getSetting('TargetFullInfo');
var data = {
items: simpleCart.getDataArr(),
currency: simpleCart.currency().code,
quantity: simpleCart.quantity(),
tax: simpleCart.tax(),
taxRate: simpleCart.taxRate().toFixed(),
shipping: simpleCart.shipping(),
cartSettings: simpleCart.getSettings(),
itemsRulesTotal: simpleCart.itemsRulesValue(),
itemsRules: simpleCart.itemsRules(),
grandTotalAfterTax: simpleCart.grandTotalAfterTax(),
TargetFullInfo: TargetFullInfo,
SourceFullInfo: simpleCart.getSetting('SourceFullInfo'),
ShippingAddress: simpleCart.getSetting('ShippingAddress'),
shippingInfo: {
packages: simpleCart.getSetting('Packages'),
//items: simpleCart.getDataShipableArr(),
fromAddress: simpleCart.getSetting('ShippingAddress'),
toAddress: simpleCart.getSetting('TargetFullInfo')
},
creditInfo: {
feedCredit: TargetFullInfo.feedCredit,
appliedCredit: simpleCart.getSetting('appliedCredit')
},
totalBefore: simpleCart.total(),
totalAfter: simpleCart.grandTotal(),
usedCard: token.card
};
if ($('#deliveryInstructions').val().length > 5) {
data.shippingInfo.deliveryInstructions = $('#deliveryInstructions').val();
}
var fd = {
nid: simpleCart.nodeId(),
stripeToken: token.id !== undefined ? token.id : '',
data: data
};
//console.log(fd);
//return;
$.ajax({
type: "POST",
url: "/eshop/charge",
data: fd,
dataType: "json",
beforeSend: function () {
Swal.fire({
title: 'Please Wait...',
allowEscapeKey: false,
allowOutsideClick: false,
timer: 20000,
onOpen: () => {
swal.showLoading();
}
});
},
error: function () {
swal.close();
},
success: function (res, textStatus, jqXHR) {
swal.close();
if (res.error == false) {
if (typeof ga === 'function') {
gaEcommerceSend(res.data);
}
Swal.fire({
icon: 'success',
title: res.message,
showConfirmButton: true
}).then((result) => {
if (window.location.host.indexOf('test.') !== -1) {
return;
} else {
simpleCart.empty();
location.href = '/eshop/account/'
}
})
} else {
Swal.fire({
icon: 'error',
title: res.message,
showConfirmButton: true
});
}
}
});
}
}
}
$(document).ready(function () {
setTimeout(function () {
WEShopping.init();
}, 1000)
});
}(jQuery);