/*megatone*/
var BraindwDomReady = function (callback) {
document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback);
};
var _HASHBNDW = 'megatone_produccion_jk98x';
var _COMPANYEXTBNDW = 'megatonedigital';
var _COMPANY = 'megatone_produccion';
var _URLBNDW = window.location.protocol + '//s.braindw.com';
var _URLBNDWSTATIC = window.location.protocol + '//static-s.braindw.com';
var _URLBNDWAPICONTENT = 'https://s2.braindw.com';
var _LAYOUTBDW = '19ccd66b-b568-43cb-a106-b52f9796f5cd';
var isAttached = (typeof (isAttached) !== 'undefined') ? isAttached : false;
var bdwContents = true;
try{
if (document.location.href.toLowerCase().indexOf("buscar?text=cyber") != -1 ||
document.location.href.toLowerCase().indexOf("buscar?text=ciber") != -1 ||
document.location.href.toLowerCase().indexOf("buscar?text=descuentos") != -1 ||
document.location.href.toLowerCase().indexOf("buscar?text=ofertas") != -1 ||
document.location.href.toLowerCase().indexOf("buscar?text=promociones") != -1 ||
document.location.href.toLowerCase().indexOf("buscar?text=hot sale") != -1 ||
document.location.href.toLowerCase().indexOf("buscar?text=hot%20sale") != -1 ||
document.location.href.toLowerCase().indexOf("buscar?text=black friday") != -1 ||
document.location.href.toLowerCase().indexOf("buscar?text=black%20friday") != -1 ||
document.location.href.toLowerCase().indexOf("buscar?text=monday") != -1) {
window.location = '/busca?fq=H:155';
}
}catch{
}
function BraindwGetFoundWords() {
var e = "",
t = document.body.innerText;
t = t.replace(/(<([^>]+)>)/gi, " ").toLowerCase();
var r = "{wordstofind}".split(",");
for (i = 0; i < r.length; i++) - 1 != t.indexOf(r[i]) && (e += r[i] + ",");
return e
}
function BraindwLoadScript(e, t, r) {
/*
var i = $guadex = function (e) {
i._.push(e)
},
a = BraindwPersistence.GetSucCookie(),
o = i.s = e.createElement(t),
n = e.getElementsByTagName(t)[0];
i.set = function (e) {
i.set._.push(e)
}, i._ = [], i.set._ = [], o.async = !0, o.setAttribute("charset", "utf-8"), o.src = _URLBNDWSTATIC + "/tracking/track?HASH=" + _HASHBNDW + "&branchOffice=" + a + "&wordsfound=" + BraindwGetFoundWords() + "&buyer={CLIENT.BUYER}&name=&lastname=&gender=&country=&state=&city=&email=&u=" + escape(window.location) + "&hs=" + new Date, i.t = +new Date, o.type = "text/javascript", n.parentNode.insertBefore(o, n)
*/
}
//#region Captures
var BraindwCapture = (function () {
let storageEmailKey = 'bdw_email';
function ValidateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
function CookiePush(email) {
if (ValidateEmail(email)) {
var bdwEmailStorage = localStorage.getItem(storageEmailKey);
if (bdwEmailStorage && bdwEmailStorage === email) {
return;
}
try {
fetch(_URLBNDW + '/tracking/SetCookiesNdway?email=' + email + '&company=' + _COMPANY, {
credentials: "include",
mode: 'no-cors',
method: 'POST',
})
.then(function (resp) {
return resp.text();
})
.then(function (data) {
localStorage.setItem(storageEmailKey, email);
BraindwPersistence.PushInfo(email);
return false;
})
.catch(function (ex) {
console.log(ex);
});
} catch (e) { }
}
}
function EmailsSite(btnEmailSelector, textBoxSelector) {
bindEvent(document.querySelector(btnEmailSelector), 'click', function (e) {
var email = document.querySelector(textBoxSelector).value;
if (email == undefined) {
email = "";
if (email == undefined || email == "")
return;
}
CookiePush(email);
});
}
function Category(category) {
localStorage.setItem('bdw_last_category', vtxctx.categoryId);
let _bndwOb2 = document.createElement('script');
_bndwOb2.async = true;
_bndwOb2.src = `${_URLBNDWAPICONTENT}/tracking/capture?HASH=${_HASHBNDW}&iscategory=true&og:categorycode=${category}`;
_bndwOb2.charset = "UTF-8";
document.head.appendChild(_bndwOb2);
}
function Product(productId, isCart) {
fetch('https://' + document.URL.split('/')[2] + '/api/catalog_system/pub/products/search?fq=productId:' + productId + '&sc=' + BraindwPersistence.GetSucCookie())
.then((resp) => resp.json())
.then(function (data) {
if (data.length > 0) {
var tax = 0;
var itemsWithStock = data[0].items.filter(function (item) {
return item.sellers[0].commertialOffer.AvailableQuantity > 0;
});
if (itemsWithStock[0].sellers[0].commertialOffer.Tax > 0) {
tax = itemsWithStock[0].sellers[0].commertialOffer.Tax + 0.01;
}
var price = itemsWithStock[0].sellers[0].commertialOffer.Price + tax;
var oldPrice = itemsWithStock[0].sellers[0].commertialOffer.ListPrice + tax;
var onlinePrice = itemsWithStock[0].sellers[0].commertialOffer.PriceWithoutDiscount + tax;
if (price == oldPrice)
oldPrice = "";
var bdw_arbol_product_clusters = '';
var clusters = data[0].productClusters;
var clusterArray = Object.keys(clusters).map((key) => [key, clusters[key]]);
var clusterId = "";
clusterArray.forEach(function (clusterId) {
bdw_arbol_product_clusters += 'cl_' + clusterId[0] + ",";
});
var urlParameters = "og:title=" + encodeURIComponent(data[0].productName) + "&og:image=" + encodeURIComponent(itemsWithStock[0].images[0].imageUrl) + "&og:url=" + document.URL.replace("#", "") +
"&og:categoriescodes=" + data[0].categoriesIds[0].replace(/\//g, ',') + bdw_arbol_product_clusters + '&og:codeproduct=' + data[0].productId + '&og:brand=' + data[0].brand + '&og:categorycode=' + data[0].categoryId + '&og:price=' +
price + '&og:priceold=' + oldPrice + '&og:og:pricesale=' + onlinePrice + '&iscart=' + isCart;
var _bndwOb2 = document.createElement('script');
_bndwOb2.async = true;
_bndwOb2.src = `${_URLBNDWAPICONTENT}/tracking/capture?HASH=${_HASHBNDW}&${urlParameters}`;
_bndwOb2.charset = "UTF-8";
document.head.appendChild(_bndwOb2);
if (!isCart) {
BraindwPersistence.GetProduct(data);
const urlCategory = location.origin + data[0].categories[0];
BraindwPersistence.PushCategory(urlCategory);
//BraindwGetCrossCustoms(data[0].categoriesIds[0]);
return;
}
}
})
.catch(function (ex) {
console.log(ex);
});
}
function LoggedUser() {
fetch('/api/vtexid/pub/authenticated/user')
.then(r => r.json())
.then(data => {
if (data !== null && data.user) {
CookiePush(data.user);
}
})
.catch();
}
return {
Category,
Product,
EmailsSite,
LoggedUser
}
})();
//#endregion
//#region Oct8ne
var bdwOct8ne = function () {
let valueCartBdw = document.querySelector('.quantity-price .total-selling-price').innerText;
let customerIdBdw = localStorage.getItem('bdw_email');
let licenseBdw = '4FC6AE7AA6D95B78888BC09C966FFAE5';
let referenceBdw = '', localeBdw = '', currencyCodeBdw = '';
var dataBdw = vtexjs.checkout.orderForm;
if (dataBdw != undefined) {
referenceBdw = dataBdw.orderFormId;
localeBdw = dataBdw.clientPreferencesData.locale;
currencyCodeBdw = dataBdw.storePreferencesData.currencyCode;
return `
`;
}
};
//#endregion
//#region Persistencia
var BraindwPersistence = (function () {
let storageEmailKey = 'bdw_email';
function CheckOrder(orderForm) {
const storageOrderKey = 'bdw_itemsOrder';
const oldItems = localStorage.getItem(storageOrderKey);
const newItems = JSON.stringify(orderForm.items);
if (oldItems === null || oldItems === '' || oldItems !== newItems) {
localStorage.setItem(storageOrderKey, newItems);
return true;
}
return false;
}
function ItemsFormatter(data) {
let itemsArray = [];
for (var i = 0; i < data.items.length; i++) {
itemsArray.push({
ProductTitle: data.items[i].name,
ProductCode: data.items[i].productId,
ProductUrlImage: data.items[i].imageUrl,
ProductQuantity: data.items[i].quantity,
ProductQuantityDetails: '',
ProductPrice: (data.items[i].sellingPrice / 100).toString(),
PriceTotal: (data.items[i].sellingPrice / 100) * data.items[i].quantity,
Event: "Load",
ProductSku: data.items[i].id,
idSeller: data.items[i].seller
})
}
return itemsArray;
}
function ProcessOrder(orderForm) {
let e = null;
var items = [];
//var data = vtexjs.checkout.orderForm;
if (orderForm != undefined && CheckOrder(orderForm)) {
items = ItemsFormatter(orderForm);
e = {
CartNumber: '',
BranchOffice: GetSucCookie(),
Items: items
}
}
return e;
}
function CartOpened(orderForm) {
let e = {
sessionDate: GetSessionDate()
};
let a = ProcessOrder(orderForm);
e.cartOpened = a;
if (e.cartOpened !== null) {
SendPersistency(e);
}
}
function GetCartOpened() {
let e = null;
var items = [];
if (typeof vtexjs == "undefined") return e;
var data = vtexjs.checkout.orderForm;
if (data != undefined) {
items = ItemsFormatter(data);
}
e = {
CartNumber: '',
BranchOffice: GetSucCookie(),
Items: items
}
return e;
}
function GetCartClosed() {
var t = document.URL;
if (-1 == t.toLowerCase().indexOf("/checkout/orderconfirmation") && -1 == t.toLowerCase().indexOf("/checkout/orderplaced")) {
return e;
}
let r = t.split("og=")[1],
i = [],
e = {
CartNumber: r,
Items: i
}
if(r != null){
document.querySelector("body").insertAdjacentHTML('beforeend', bdwOct8ne());
}
return e
}
function GetEmail() {
return localStorage.getItem(storageEmailKey) ?? '';
}
function GetCarts() {
if (typeof vtexjs == "undefined") {
let e = {
sessionDate: GetSessionDate()
};
const a = GetCartClosed();
e.cartClosed = a;
SendPersistency(e);
} else {
$(window).on("orderFormUpdated.vtex", function (evt, orderForm) {
console.log('BDW OrderFormUpdated Event');
CartOpened(orderForm);
});
}
}
function GetProduct(data) {
let e = null;
if (data.length > 0) {
var s = {},
t = GetSessionDate();
t && (s.sessionDate = t);
e = {
ProductCode: data[0].productId, //data[0].items[i].itemId,
Title: data[0].items[0].nameComplete,
PriceOnline: data[0].items[0].sellers[0].commertialOffer.PriceWithoutDiscount,
Brand: data[0].brand,
Category: data[0].categories[0].split('/')[data[0].categories[0].split('/').length - 2],
CategoryCode: data[0].categoryId,
UrlImage: data[0].items[0].images[0].imageUrl,
UrlProduct: document.URL,
BranchOffice: GetSucCookie()
};
s.product = e;
SendPersistency(s);
}
}
function GetSucCookie() {
let BraindwCa = decodeURIComponent(document.cookie).split(';');
for (let bnwi = 0; bnwi < BraindwCa.length; bnwi++) {
if (BraindwCa[bnwi].indexOf("VTEXSC") > -1) {
return BraindwCa[bnwi].split('=')[2];
}
}
return '';
}
function GetSessionDate() {
let result = null;
try {
let SalesChannel = GetSucCookie();
result = {
SalesChannel: SalesChannel,
};
} catch (e) {
console.log('GetSessionDate error ', e);
}
return result;
}
function SendPersistency(e, url) {
let n = {
emailguest: GetEmail(),
dataset: encodeURI(JSON.stringify(e)),
page: "",
url: (url) ? url : window.location.href.split("?")[0],
urlb: `${_URLBNDW}/Script/braindw/${_HASHBNDW}?hs=Sat Apr 21 2018 10:00:38 GMT-0300 (Hora estándar de Argentina)`,
BranchOffice: GetSucCookie()
};
fetch('https://p.braindw.com/Api/Data/Capture', {
method: "POST",
body: JSON.stringify(n),
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
.then((resp) => resp.json())
.then(function (data) {
})
.catch(function (ex) {
console.log(ex);
});
}
function PushCategory(urlCategory) {
try {
let e = null;
if (typeof vtxctx !== undefined && vtxctx.categoryId !== "") {
e = {
Title: vtxctx.categoryName,
CategoryCode: vtxctx.categoryId
}
if (e != null) {
var s = {},
t = GetSessionDate();
t && (s.sessionDate = t);
s.category = e
SendPersistency(s, urlCategory);
}
}
} catch (e) { }
}
function PushTermNotFound(term) {
try {
if (term && term !== '') {
let e = {
sessionDate: GetSessionDate()
};
e.search = { searchterm: term };
SendPersistency(e);
}
}
catch (e) { console.log('BDW ' + e); }
}
function PushInfo(emailGuest) {
let e = {
sessionDate: GetSessionDate()
};
let a = GetCartOpened();
a ? e.cartOpened = a : (a = GetCartClosed()) && (e.cartClosed = a);
SendPersistency(e);
}
return {
GetProduct,
GetSucCookie,
PushCategory,
GetCarts,
PushInfo,
PushTermNotFound
}
})();
//#endregion
function BraindwAddHeaderComponent(type, url) {
switch (type) {
case 'css':
let _bndwObjc = document.createElement('link');
_bndwObjc.rel = 'stylesheet';
_bndwObjc.href = url;
_bndwObjc.type = "text/css";
document.head.appendChild(_bndwObjc);
break;
case 'script':
let _bndwObjs = document.createElement('script');
_bndwObjs.async = true;
_bndwObjs.src = url
_bndwObjs.charset = "UTF-8";
document.head.appendChild(_bndwObjs);
break;
default:
console.log(`BDW AddHeaderComponent. Type: ${type} no reconocido`);
break;
}
}
function BraindwGetUrlParam(paramName, usetoLower = true) {
let clusterid = '';
if(paramName === 'map=productClusterIds' && location.href.indexOf('map=productClusterIds') > -1){
let url = location.href.split('?map=productClusterIds')[0];
//clusterid = url.split('.com/')[1];
clusterid = url.split('.digital/')[1];
return clusterid;
}
const url = new URL(usetoLower ? location.href.toLocaleLowerCase() : location.href);
const param = url.searchParams.get(usetoLower ? paramName.toLowerCase() : paramName) ?? '';
return decodeURI(param);
}
function BraindwGetSection() {
if (location.href.toLowerCase().indexOf("cartabandoned=") > -1) {
return 'cartabandoned';
} else if (location.href.indexOf("/buscar?text") > -1) {
return 'busca';
} else if (location.href.includes('fq=H:') || location.href.includes('map=productClusterIds')) {
return 'collection';
} else if (typeof vtxctx === 'undefined') {
if (location.href.includes('/checkout/#/cart')) {
return 'checkout';
}
return '';
} else if (vtxctx.skus === undefined) {
if (vtxctx.searchTerm !== '') {
if (location.href.includes('/buscavazia')) {
return 'searchnoresult';
} else {
return 'search';
}
} else if (vtxctx.categoryId === undefined && vtxctx.departmentyId === undefined) {
return 'home';
} else if (vtxctx.departmentyId === vtxctx.categoryId) {
return 'department';
} else {
return 'category';
}
} else {
return 'product';
}
}
var bdwRankingCategories = (function () {
const localStorageKey = 'bdw_ranking_categories';
function FindCategory(idCategory) {
const s = localStorage.getItem(localStorageKey);
if (s === null || s === '') {
return null;
}
const o = JSON.parse(s)
if (o === null || o.length === 0) {
return null;
}
return o.find(i => i.categoryId === idCategory);
}
function RankingAdd(element) {
let arr = JSON.parse(localStorage.getItem(localStorageKey));
if (arr === null || arr === undefined || arr.length === 0) {
arr = [element];
} else {
arr.push(element);
}
localStorage.setItem(localStorageKey, JSON.stringify(arr));
}
function RankingUpdate(element) {
let arr = JSON.parse(localStorage.getItem(localStorageKey));
arr.splice(arr.findIndex(i => i.categoryId === element.categoryId), 1, element);
localStorage.setItem(localStorageKey, JSON.stringify(arr));
}
function Add(idCategory) {
let obj = FindCategory(idCategory);
if (obj === null || obj === undefined) {
obj = {
categoryId: idCategory,
visits: 1
};
RankingAdd(obj);
} else {
obj.visits++;
RankingUpdate(obj);
}
}
function Get() {
const s = localStorage.getItem(localStorageKey);
console.log(s);
if (s === null || s === '') {
return '';
}
const o = JSON.parse(s)
if (o === null || o.length === 0) {
return '';
}
let arr = o.sort((a, b) => {
return b.visits - a.visits;
}).map(c => c.categoryId);
return arr;
}
return { Add, Get };
})();
function BraindwSetLastNavigated(tipo, data) {
let storageKey = '';
let maxItems = 20;
switch (tipo.toLowerCase()) {
case 'product':
storageKey = 'bdw_last_productIds';
break;
case 'category':
bdwRankingCategories.Add(data.toString());
storageKey = 'bdw_last_categories';
break;
case 'addtocart':
storageKey = 'bdw_last_addToCart';
break;
case 'search':
maxItems = 1;
if (data.indexOf('Buscar...') === -1) {
storageKey = 'bdw_last_searchTerm';
}
break;
default:
break;
}
if (storageKey !== '') {
let stData = data.toString();
var lastItems = localStorage.getItem(storageKey);
var lastItemsList = [];
if (lastItems === null || lastItems === undefined || lastItems === '') {
localStorage.setItem(storageKey, stData);
} else {
lastItemsList = lastItems.split(',', maxItems);
if (lastItemsList[0] !== stData) {
let index = lastItemsList.findIndex(item => item === stData);
if (index !== -1) {
lastItemsList.splice(index, 1);
}
lastItemsList.unshift(stData);
localStorage.setItem(storageKey, lastItemsList.toString());
}
}
}
}
function BraindwInsertDivs(section) {
switch (section) {
case 'checkout':
console.log('BDW - Inserta div de Checkout');
let element = document.querySelector('.cart-template');
if (element !== null) {
element.insertAdjacentHTML('beforeend', '
');
element.insertAdjacentHTML('beforeend', '');
element.insertAdjacentHTML('beforeend', '');
element.insertAdjacentHTML('beforeend', '');
}
break;
default:
break;
}
}
function bindEvent(element, eventName, eventHandler) {
try {
if (element.addEventListener)
element.addEventListener(eventName, eventHandler, false);
else if (element.attachEvent)
element.attachEvent('on' + eventName, eventHandler);
} catch (e) { }
}
function BraindwPushEvent(cat, act, eti) {
try {
dataLayer.push({
event: "ga-braindw",
eventCategory: cat,
eventAction: act,
eventLabel: eti,
});
} catch (err) {
console.log(err);
}
}
function BraindwEvent(component, data) {
try {
let productTitle = component.querySelector('b a').getAttribute('title');
let productId = component.querySelector('div input.buy-button-asynchronous-product-id').value;
let etiqueta = data.GaEventLabel;
etiqueta = etiqueta.replace('{title}', productTitle);
etiqueta = etiqueta.replace('{sku}', productId);
bindEvent(component, 'click', function () {
BraindwPushEvent(data.GaEventCategory, data.GaEventAction, etiqueta);
});
}
catch (error) {
console.log('BraindwEvent Error:' + error);
}
}
async function BraindwCategoryTreeFromProduct(productId) {
let categoryTree = '';
await fetch(`/api/catalog_system/pub/products/search?fq=productId:${productId}&sc=${BraindwPersistence.GetSucCookie()}`)
.then((resp) => resp.json())
.then(function (data) {
if (data.length > 0) {
categoryTree = data[0].categoriesIds[0].split('/').filter(Boolean);
}
})
.catch(function (ex) {
console.log(ex);
});
return categoryTree;
}
async function BraindwCategoryTreeFromCategory(categoryId) {
let _categoryId = categoryId;
let categoryTree = [categoryId];
let findFatherCategory = true;
do {
await fetch(`/api/catalog/pvt/category/${_categoryId}`)
.then((resp) => resp.json())
.then(function (data) {
if (data && data.FatherCategoryId && data.FatherCategoryId !== '') {
categoryTree.unshift(data.FatherCategoryId.toString());
_categoryId = data.FatherCategoryId;
}
else {
findFatherCategory = false
}
})
.catch(function (ex) {
findFatherCategory = false;
console.log(ex);
});
} while (findFatherCategory);
return categoryTree.toString().replaceAll(',', '/');
}
async function BraindwRender() {
let _section = BraindwGetSection();
let _bdwUrlRequestSection = '';
let _email = '';
let _bdwMaxItems = 15;
switch (_section) {
case 'home':
_bdwUrlRequestSection = `home/1/${localStorage.getItem('bdw_last_category') ?? ''}/${localStorage.getItem('bdw_last_productIds') ?? ''}`;
break;
case 'search':
case 'department':
case 'category':
_bdwUrlRequestSection = `category/${vtxctx.categoryId}`;
break;
case 'product':
let _categoryTree = await BraindwCategoryTreeFromProduct(skuJson_0.productId);
let _categoryIntermedia = _categoryTree.length >= 2 ? _categoryTree[_categoryTree.length - 2] : vtxctx.departmentyId;
_bdwUrlRequestSection = `product/${skuJson_0.productId}/${vtxctx.categoryId}/${_categoryIntermedia}/${_categoryTree}`;
break;
case 'checkout':
BraindwInsertDivs(_section);
let idList = [];
let categoryList = [];
await vtexjs.checkout.getOrderForm().done(function (order) {
order.items.forEach(item => {
idList.push(item.id);
categoryList.push(item.productCategoryIds.split('/').filter(Boolean));
});
});
if (idList.length > 0) {
_bdwUrlRequestSection = `checkout/${idList.toString()}/${categoryList.toString()}/${localStorage.getItem('bdw_last_category') ?? ''}/${localStorage.getItem('bdw_last_productIds') ?? ''}`;
}
break;
case 'searchnoresult':
//_bdwUrlRequestSection = `searchnoresult/${BraindwGetUrlParam('ft')}`;
_bdwUrlRequestSection = `searchnoresult/${BraindwGetUrlParam('ft')}/${localStorage.getItem('bdw_last_category') ?? ''}`;
break;
case 'collection':
let cluster = BraindwGetUrlParam('fq', false).replace('H:', '')
_bdwUrlRequestSection = `collection/${cluster !== '' ? cluster : BraindwGetUrlParam('map=productClusterIds', false)}§ionid=BDW-PLP-Carrusel-1`;
break;
default:
break;
}
_email = localStorage.getItem('bdw_email');
if (_bdwUrlRequestSection != '') {
console.log('BDW Get ' + _section);
_bdwUrlRequestSection = `${_URLBNDWAPICONTENT}/tracking/track?HASH=${_HASHBNDW}&branchOffice=1&whitelabel=&wordsfound=&buyer=&name=&lastname=&gender=&country=&state=&city=&email=`+ _email +`&u=` + _bdwUrlRequestSection;
//console.log('BDW Request: ' + _bdwUrlRequestSection);
fetch(_bdwUrlRequestSection, { credentials: 'include' })
.then(res => res.json())
.then(data => {
data.forEach(obj => {
console.log('BDW ' + obj.Section);
if (document.querySelector("#" + obj.Section)) {
let _productQuery = '';
for (let i = 0; i < obj.Products.length && i <= _bdwMaxItems; i++) {
let idProduct = obj.Products[i];
if (idProduct != '' && idProduct != null && idProduct != undefined) {
_productQuery += '&fq=productId:' + idProduct;
}
}
if (_productQuery != '') {
fetch('/buscapagina?PS=' + _bdwMaxItems + '&sl=' + _LAYOUTBDW + '&cc=' + _bdwMaxItems + '&sm=0&PageNumber=1' + _productQuery)
.then(res => res.text())
.then(data => {
console.log('BDW Render ' + _section + ' ' + obj.Section);
$("#" + obj.Section).html('');
let _contentItems = $(data)[1];
if (_contentItems.toString().length > 0) {
//order items
$('li.helperComplement', _contentItems).remove();
let _list = $('li', _contentItems);
$('li', _contentItems).remove();
obj.Products.forEach(productid => {
for (let i = 0; i < _list.length; i++) {
let itemId = $('span div input.buy-button-asynchronous-product-id', _list[i])[0].value;
if (itemId === productid) {
BraindwEvent(_list[i], obj);
$('ul', _contentItems).append(_list[i]);
break;
}
}
});
$("#" + obj.Section).html(_contentItems);
if (obj.Title !== '') {
$("#" + obj.Section).prepend('' + obj.Title + '
');
}
var $showCaseOwl = $("#" + obj.Section + " ul");
if ($showCaseOwl.length) {
$showCaseOwl.find('.helperComplement').remove();
$showCaseOwl.owlCarousel({
items: 5,
nav: true,
autoPlay: true,
stopOnHover: true,
pagination: false,
itemsDesktop: [1199, 5],
itemsDesktopSmall: [980, 4],
itemsTablet: [768, 3],
itemsMobile: [479, 1],
navigation: true,
navigationText: [
'',
'',
],
});
}
try {
removeDecimals();
} catch (e) { }
}
})
.catch(error => { console.log(error) });
}
}
});
})
.catch(error => { console.log(error) });
}
}
//#region Dameros
function BraindwDamero($div, title, items, EventNameGA) {
console.log('BDW Render Damero ' + title);
const isMobile = window.screen.width < 800;
$div.append(`${title}
`);
$div.append('');
const $divList = $('.owl-carousel', $div);
if ($divList.length > 0) {
if (isMobile) {
items = items.slice(0, 8);
}
items.forEach(item => {
let _imageId = item.imageUrl.split('/')[5];
let _imageUrl = item.imageUrl.replace(`/ids/${_imageId}`, `/ids/${_imageId}-250-250`);
$divList.append(``);
});
$('div.cat_img_container', $divList).on('click', function (e) {
const etiqueta = `${$('.product-title', e.currentTarget).first().attr('value')}(${$('.product-sku', e.currentTarget).first().attr('value')})`;
BraindwPushEvent('ga-braindw', EventNameGA, etiqueta);
})
if(isMobile){
$div.append(` 4 ? "display:inline;":"display:none;"} data-damero-id=${$div[0].id}">
Ver más
Ver Menos
+
-
`);
}else{
$div.append(`
Ver más
Ver Menos
+
-
`);
}
if (isMobile) {
$('div.cat_img_container', $div).each(function (index, item) {
if (index >= 4) {
$(item).hide()
}
});
bindEvent($('#' + $div[0].id + ' .damero_button')[0], 'click', function (e) {
if ($('.ver_menos', e.currentTarget).css('display') === "none") {
$('div.cat_img_container', $divList).each(function (i, it) {
$(it).show();
})
$('.damero_button .ver_mas', $div).hide();
$('.damero_button .ver_menos', $div).show();
} else {
$('div.cat_img_container', $div).each(function (index, item) {
if (index >= 4) {
$(item).hide()
}
});
$('.damero_button .ver_mas', $div).show();
$('.damero_button .ver_menos', $div).hide();
}
})
} else {
$divList.owlCarousel({
items: 5,
nav: true,
autoPlay: true,
stopOnHover: true,
pagination: false,
itemsDesktop: [1199, 5],
itemsDesktopSmall: [980, 4],
itemsTablet: [768, 3],
itemsMobile: [479, 1],
navigation: true,
navigationText: [
'',
'',
],
});
}
}
}
function BraindwDameroProductos(idDamero, titleDamero, storageListKey, EventNameGA = '') {
try {
let itemCodes = localStorage.getItem(storageListKey);
let $div = $('#' + idDamero);
let _queryString = ''
let itemCodesArray = [];
if ($div.length > 0) {
$div.empty();
if (itemCodes !== null && itemCodes !== '') {
itemCodesArray = itemCodes.split(',');
itemCodesArray.forEach(item => {
_queryString += '&fq=productId:' + item;
});
}
}
if (_queryString !== '') {
console.log('BDW Damero ' + titleDamero);
_queryString = '/api/catalog_system/pub/products/search?' + _queryString;
fetch(_queryString, { credentials: 'include' })
.then(res => res.json())
.then(data => {
if (data.length > 0) {
let itemsArray = [];
itemCodesArray.forEach(code => {
for (let i = 0; i < data.length; i++) {
if (data[i].productId === code) {
itemsArray.push({
sku: data[i].productId,
link: data[i].link,
imageUrl: data[i].items[0].images[0].imageUrl,
title: data[i].productTitle
});
break;
}
}
});
BraindwDamero($div, titleDamero, itemsArray, EventNameGA);
}
})
.catch(e => {
console.log('BDW api/products error ' + e.message);
});
}
}
catch (e) {
console.log('BDW Error Damero' + titleDamero + ' Error:' + e);
}
}
function BraindwDameroBusqueda(idDamero, titleDamero, storageListKey, EventNameGA = '') {
let maxItems = 15;
try {
let itemCodes = localStorage.getItem(storageListKey);
let $div = $('#' + idDamero);
let _queryString = ''
if ($div.length > 0) {
$div.empty();
if (itemCodes !== null && itemCodes !== '') {
_queryString += 'ft=' + itemCodes.split(',')[0];
}
}
if (_queryString !== '') {
console.log('BDW Damero ' + titleDamero);
_queryString = `https://u.braindw.com/els/${_COMPANYEXTBNDW}?${_queryString}&qt=${maxItems}&refreshmetadata=false`;
fetch(_queryString, { credentials: 'include' })
.then(res => res.json())
.then(data => {
if (data && data.hits && data.hits.hits && data.hits.hits.length > 0) {
const itemsArray = data.hits.hits.map(function (item) {
return {
sku: item._source.sku,
link: item._source.link,
imageUrl: item._source.imageUrl,
title: item._source.title
}
});
BraindwDamero($div, titleDamero, itemsArray, EventNameGA);
}
})
.catch(e => {
console.log('BDW api/serach error ' + e.message);
});
}
}
catch (e) {
console.log('BDW Error Damero' + titleDamero + ' Error:' + e);
}
}
async function BraindwDameroCategorias(idDamero, titleDamero, storageListKey, defaultListArray, EventNameGA = '') {
try {
let codeList = localStorage.getItem(storageListKey);
let $div = $('#' + idDamero);
let _queryString = ''
let codeListArray = [];
let codeDefaultList = defaultListArray;
if ($div.length > 0) {
$div.empty();
console.log('BDW Damero ' + titleDamero);
if (codeList !== null && codeList !== '') {
codeListArray = codeList.split(',');
while (codeListArray.length < 10 && codeDefaultList.length > 0) {
let codeDefault = codeDefaultList.shift().toString();
if (codeListArray.indexOf(codeDefault) === -1) {
codeListArray.push(codeDefault);
}
}
} else {
codeListArray = codeDefaultList;
}
}
let itemsArray = [];
for (let i = 0; i < codeListArray.length; i++) {
//let _categoryTree = await BraindwCategoryTreeFromCategory(codeListArray[i]);
_queryString = `https://u.braindw.com/Vtex/GetSearch?token=&idcategory=${codeListArray[i]}&company=megatonedigital&ext=json&sc=1&whitelabel=&productids=&prioritysku=&idproduct=&limit=1&minprice=&maxprice=&filter_attributes=&order=0&qt=&ft=token&sale=0&minstock=1`;
await fetch(_queryString)
.then(res => res.json())
.then(data => {
if (data.length > 0) {
itemsArray.push({
sku: data[0].Sku,
link: data[0].Link,
imageUrl: data[0].UrlImagen.replace('-350-350', ''),
title: data[0].Descripcion
});
}
})
.catch(e => {
console.log('BDW api/category Category id: ' + codeListArray[i] + ' error ' + e.message);
});
};
if (itemsArray.length > 0) {
BraindwDamero($div, titleDamero, itemsArray, EventNameGA);
}
}
catch (e) {
console.log('BDW Error Damero' + titleDamero + ' Error:' + e);
}
}
//#endregion
//#region desplegable DataLayers
function mapItemsBdwCatalogClick(response) {
var mapItems = [];
let termSearch = localStorage.getItem('bdwTermSearch2');
console.log('datalayercatalogclic');
response.forEach(function (element, index) {
let item = { 'index': index,
'item_id': element.IdArticulo,
'item_name': element.Descripcion,
'coupon': element.Articulo_Oferta != null ? element.Articulo_Oferta : '',
'discount': element.CucardaOferta != null ? element.CucardaOferta : '',
'price':element.Precio,
'currency':'ARG',
'item_list_name':'search_result',
'item_list_id':'search_result',
'affiliation':'Megatone',
'item_brand':element.Marca,
'item_category':element.Categoria,
'item_variant':'',
'quantity':'1'
}
mapItems.push(item);
});
dataLayer.push({'event': 'select_item',
'search_term': termSearch,
'site_search_counter_results': '1',
'search_term_sort': 'default sort',
'search_term_page': '1',
'item_list_name': 'search_result',
'item_list_id': 'search_result',
'items': mapItems}
);
localStorage.setItem('bdwTermSearch2','');
return mapItems;
}
function mapProdBdwCatalog(termSearch, response) {
var mapItems = [];
let countMap = response.total;
console.log('datalayercatalog');
response.hits.forEach(function (element, index) {
let item = { 'index': index,
'item_id': element._source.code,
'item_name': element._source.title,
'coupon': '',
'discount': element._source.discountPrice != null ? element._source.discountPrice : '',
'price':element._source.price,
'currency':'ARG',
'item_list_name':'search_result',
'item_list_id':'search_result',
'affiliation':'Megatone',
'item_brand':element._source.brand,
'item_category':element._source.category,
'item_category2':element._source.category2,
'item_variant':'',
'quantity':'1'
}
mapItems.push(item);
});
dataLayer.push({'event': 'view_search_results',
'search_term': termSearch,
'site_search_counter_results': countMap,
'search_term_sort': 'default sort',
'search_term_page': '',
'item_list_name': 'search_result',
'item_list_id': 'search_result',
'items': mapItems}
);
return mapItems;
}
function mapItemsBdwDesplegable(termSearch, response) {
var mapItems = [];
localStorage.setItem('bdwTermSearch', termSearch);
console.log('datalayerdesplegable');
response.forEach(function (element, index) {
let item = { 'index': index,
'item_id': element.IdArticulo,
'item_name': element.Descripcion,
'coupon': element.Articulo_Oferta != null ? element.Articulo_Oferta : '',
'discount': element.CucardaOferta != null ? element.CucardaOferta : '',
'price':element.Precio,
'currency':'ARG',
'item_list_name':'auto-suggest-dropdown',
'item_list_id':'auto-suggest-dropdown',
'affiliation':'Megatone',
'item_brand':element.Marca,
'item_category':element.Categoria,
'item_variant':'',
'quantity':'1'
}
mapItems.push(item);
});
dataLayer.push({'event': 'view_search_results',
'search_term': termSearch,
'site_search_counter_results': '12',
'search_term_sort': 'default sort',
'search_term_page': '1',
'item_list_name': 'auto-suggest-dropdown',
'item_list_id': 'auto-suggest-dropdown',
'items': mapItems}
);
return mapItems;
}
function mapItemsBdwDesplegableClick(response) {
var mapItems = [];
let termSearch = localStorage.getItem('bdwTermSearch');
console.log('datalayerdesplegable');
response.forEach(function (element, index) {
let item = { 'index': index,
'item_id': element.IdArticulo,
'item_name': element.Descripcion,
'coupon': element.Articulo_Oferta != null ? element.Articulo_Oferta : '',
'discount': element.CucardaOferta != null ? element.CucardaOferta : '',
'price':element.Precio,
'currency':'ARG',
'item_list_name':'auto-suggest-dropdown',
'item_list_id':'auto-suggest-dropdown',
'affiliation':'Megatone',
'item_brand':element.Marca,
'item_category':element.Categoria,
'item_variant':'',
'quantity':'1'
}
mapItems.push(item);
});
dataLayer.push({'event': 'select_item',
'search_term': termSearch,
'site_search_counter_results': '1',
'search_term_sort': 'default sort',
'search_term_page': '1',
'item_list_name': 'auto-suggest-dropdown',
'item_list_id': 'auto-suggest-dropdown',
'items': mapItems}
);
return mapItems;
}
if(window.location.href.includes('bdwsearch=true')){
let bdwSkuClick = skuJson.productId;
bdwUrlRequestSection = `https://u.braindw.com/Vtex/GetProduct?token=&company=megatonedigital&ext=json&sc=1&whitelabel=&idproduct=` + bdwSkuClick;
fetch(bdwUrlRequestSection, { credentials: 'include' })
.then(res => res.json())
.then(data => {
if(data){
mapItemsBdwDesplegableClick(data);
}
})
.catch(error => { console.log(error) });
}
//#endregion
//#region desplegable Buscador
function BraindwBuscador() {
var gotoHref = function (href) {
document.location.href = href;
};
var searchTerm = '';
var mapReturnedItems = function (item) {
let sku = item.items[0].productId;
if(sku != '347336'){
return {
label: (item.thumb != "" ? item.thumb + " " : "") + item.name,
value: item.name,
href: item.href,
criteria: item.criteria
};
}
};
var mapReturnedItemsDesplegable = function (item) {
let productUTM = "?bdwsearch=true";
let sku = item.productId;
if(sku != '347336'){
return {
label: `` + item.Descripcion,
value: item.Descripcion,
href: item.Link + productUTM,
criteria: null
};
}
};
var autoCompleteSourceOriginal = function (request, response) {
$.ajax({
url: "/buscaautocomplete/",
dataType: "json",
data: {
maxRows: 12,
productNameContains: request.term,
suggestionsStack: ''
},
success: function (data) {
if (data) {
console.log('autoCompleteSourceOriginal');
response($.map(data.itemsReturned, mapReturnedItems));
}
}
});
};
var autoCompleteSource = function (request, response) {
$.ajax({
url: `https://u.braindw.com/els/${_COMPANYEXTBNDW}?ft=${request.term}&qt=12&refreshmetadata=true&whitelabel=&branchOffice=1&hash=megatone_produccion_jk98x&`,
dataType: "json",
data: {
//maxRows: 12,
//productNameContains: request.term,
suggestionsStack: suggestionsStack
},
success: function (data) {
if (data) {
console.log('autoCompleteSource');
//response($.map(data.itemsReturned, mapReturnedItems));
response($.map(data, mapReturnedItemsDesplegable));
mapItemsBdwDesplegable(request.term, data);
}
},
error: function(data) {
autoCompleteSourceOriginal(request, response);
}
});
};
if ($.fn.autocomplete) {
$(".fulltext-search-box").autocomplete({
source: autoCompleteSource,
minLength: 3,
delay: 500,
search: function (event, ui) {
searchTerm = event.target.value;
},
select: function (event, ui) {
BraindwSetLastNavigated('Search', searchTerm);
gotoHref(ui.item.href);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
},
focus: function (event, ui) {
suggestionsStack = ui.item.criteria;
}
});
}
}
//#endregion
function braindwGetUrlParameter(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^]*)");
var results = regex.exec(location.search);
return results === null
? ""
: decodeURIComponent(results[1].replace(/\+/g, " "));
}
//#region Carro Abandonado
function BraindwCartAbandoned() {
try {
console.log("cartAbandoned...");
$("#braindw_loader").show();
const skuArray = braindwGetUrlParameter('CartAbandoned').split(',').filter(Boolean);
try{skuArray = skuArray.filter(value => Object.keys(value).length !== 0);}
catch{}
var bdwQueryString = '';
var itemsArray = skuArray.map(item => {
var itemSku = 0;
var sellerId = '';
if (item.indexOf('-') > -1 ) {
itemSku = item.split('-')[0];
sellerId = item.split('-')[1];
return {
id: itemSku,
quantity: 1,
seller: sellerId
}
}else{
bdwQueryString += '&fq=productId:' + item;
return null;
}
}).filter(x => x !== null);
if(bdwQueryString.length>0)
{
bdwQueryString = `/api/catalog_system/pub/products/search?${bdwQueryString}&sc=${BraindwPersistence.GetSucCookie()}`;
fetch(bdwQueryString)
.then(r => r.json())
.then(function (data) {
var bdwOldArray=itemsArray;
if (data.length > 0) {
itemsArray = data.map(item => {
for (var i = 0; i < item.items.length; i++) {
if (item.items[i].sellers[0].commertialOffer.AvailableQuantity > 0) {
return {
id: item.items[i].itemId,
quantity: 1,
seller: item.items[i].sellers[0].sellerId
}
}
}
return {
id: item.items[0].itemId,
quantity: 1,
seller: item.items[0].sellers[0].sellerId
}
});
}
itemsArray = itemsArray.concat(bdwOldArray);
console.log('itemarray',itemsArray);
if (itemsArray.length > 0) {
vtexjs.checkout.getOrderForm().done(function (orderfrom) {
vtexjs.checkout.addToCart(itemsArray, null, 1).done(function (orderfrom) {
setTimeout(function () {
$("#braindw_loader").hide();
window.location.href = location.origin + '/checkout/#/cart';
}, 500);
});
});
}
})
.catch(error => {
$("#braindw_loader").hide();
console.log('BDW CartAbandoned. Error catalog querie' + error);
})
}
else if (itemsArray.length > 0) {
vtexjs.checkout.getOrderForm().done(function (orderfrom) {
vtexjs.checkout.addToCart(itemsArray, null, 1).done(function (orderfrom) {
setTimeout(function () {
$("#braindw_loader").hide();
window.location.href = location.origin + '/checkout/#/cart';
}, 500);
});
});
}
}
catch (e) {
console.log(e);
}
}
//#endregion
//#region Busca
var BraindwBusca = (function () {
let hitsArray = [];
let page = 1;
const itemByPage = 12;
function GetPage() {
return page;
}
function FilterEvent(e) {
const type = e.currentTarget.dataset.type;
const value = e.currentTarget.dataset.value;
let settedFilters = BraindwGetUrlParam('ftAggs', false);
let location = window.location.href.split('&ftAggs')[0];
switch (e.currentTarget.dataset.action) {
case 'add':
settedFilters += `{${type}|${value}}`;
break;
case 'remove':
settedFilters = settedFilters.replace(`{${type}|${value}}`, '');
break;
default:
break;
}
if (settedFilters !== '') {
location += '&ftAggs=' + settedFilters;
}
window.location.href = location;
}
function AddAppliedFilter(type, title, filters) {
const $appliedFilters = $('#bdw-applied-filters');
const filterName = filters.split(`${type}|`)[1].split('}')[0];
const $div = $('', { 'class': `${type} bdw-applied-filters` });
$div.append(`
${title}
`);
$div.append(`
`)
const $li = $('
', {
'class': `${type} bdw-applied-filters item`,
'attr': { 'data-value': `${filterName}`, 'data-type': `${type}`, 'data-action': 'remove' },
'value': `${filterName}`
}).append($('', {}).append($('