var _URLBNDW2 = "https://s2.braindw.com"; var BraindwDomReady = function (callback) { document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback); }; function BraindwLoadScript(e, t, r) { var drugstore = ""; if ( localStorage.getItem("drugstore-stock") !== null && localStorage.getItem("drugstore-stock") !== undefined ) { drugstore = localStorage.getItem("drugstore-stock"); } var i = ($guadex = function (e) { i._.push(e); }), a = drugstore, 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 = _SURLBNDW + "/tracking/track?HASH=inkafarma_produccion_h5hgp&branchOffice=" + a + "&wordsfound=" + BraindwGetFoundWords() + "&buyer={CLIENT.BUYER}&name=&lastname=&gender=&country=&state=&city=&email&minify=1&u=" + escape(window.location) + "&hs=" + new Date()), (i.t = +new Date()), (o.type = "text/javascript"), n.parentNode.insertBefore(o, n); } function bdwRemoveCurrentStorage() { if (localStorage.getItem("currentPage")) { localStorage.removeItem("currentPage"); } } window.onbeforeunload = bdwRemoveCurrentStorage(); 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; } var bdwMobile = { Android: function () { return navigator.userAgent.match(/Android/i); }, BlackBerry: function () { return navigator.userAgent.match(/BlackBerry/i); }, iOS: function () { return navigator.userAgent.match(/iPhone|iPad|iPod/i); }, Opera: function () { return navigator.userAgent.match(/Opera Mini/i); }, Windows: function () { return navigator.userAgent.match(/IEMobile/i); }, any: function () { return ( bdwMobile.Android() || bdwMobile.BlackBerry() || bdwMobile.iOS() || bdwMobile.Opera() || bdwMobile.Windows() ); }, }; 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 BraindwPushEventIframe(cat, eti, sku) { try { if (sku != "") eti = eti + "[" + sku + "]"; dataLayer.push({ event: "ga-braindw", eventCategory: "ga-braindw", eventAction: cat, eventLabel: eti, }); } catch (err) { console.log(err); } } function BdwInterceptorRequest(url, method, callback) { var __XHROpenFn = window.XMLHttpRequest.prototype.open; window.XMLHttpRequest.prototype.open = function ( method, url, async, user, password ) { var event = new CustomEvent("request.open", { detail: { xhr: this, request: this, method: method, url: url, async: async, }, }); window.dispatchEvent(event); return __XHROpenFn.apply(this, arguments); }; window.addEventListener("request.open", handleXHR); function handleXHR(ev) { if ( ev.detail.method.toLowerCase() == method && ev.detail.url.indexOf(url) > -1 ) { ev.detail.xhr.onload = function () { if (ev.detail.xhr.readyState === 4 && ev.detail.xhr.status === 200) { callback(ev.detail.xhr.responseText); } else { console.error(xhr.statusText); } }; } } } function RemoveItemSlider(ids) { var arrayIds = ids.split(","); var iframes = document.querySelectorAll("iframe[id^=Braindw]"); iframes.forEach(function (iframe) { iframe.contentWindow.postMessage( "RemoveItemSlider|" + JSON.stringify(arrayIds), "*" ); }); setTimeout(function () { addEventCaptureAddToCart(); }, 2500); Braindw_pushInfo(); } function UpdateItemSlider(ids, actionConfig) { var configs = []; var headersRequest = new Headers(); headersRequest.append("Content-Type", "application/json"); headersRequest.append("Authorization", getWithExpiry('token-request')); fetch( "https://5doa19p9r7.execute-api.us-east-1.amazonaws.com/MMPROD/braindw/products/"+ids, /*{ method: "GET", headers: headersRequest, redirect: "follow", }*/ ) .then((resp) => resp.json()) .then(function (data) { if (data.length > 0) { for (var i = 0; i <= data.length - 1; i++) { var configProd = window["getProduct"](data[i]); configs.push(configProd); } var iframes = document.querySelectorAll("iframe[id^=Braindw]"); iframes.forEach(function (iframe) { iframe.contentWindow.postMessage( "UpdateItemSlider|" + JSON.stringify(configs) + "|" + actionConfig, "*" ); }); } }) .catch(function (ex) { console.log(ex); }); Braindw_pushInfo(); } //Extension Datalayer inkafarma o enance ecomm function BraindwPushEventClickIframe( productId, cat, eti, vitrina, sku, brand, price, slug, position ) { try { var priceFormat = price; dataLayer.push({ event: "clickBraindw", ecommerce: { click: { actionField: { list: cat, }, products: [{ name: eti, id: sku, price: priceFormat, brand: brand, variant: undefined, position: position, slug: slug, vitrina:vitrina, productId:productId, "dimensionBraindw": "Braindw", }, ], }, }, }); } catch (err) { console.log(err); } } function BraindwPushEventBuyIframe( productId, cat, eti, vitrina, sku, brand, price, slug, position, quantity ) { try { var priceFormat = price; dataLayer.push({ event: "addToCartBraindw", ecommerce: { currencyCode: "PE", add: { actionField: { list: cat, }, products: [{ name: eti, id: sku, price: priceFormat, brand: brand, variant: undefined, position: position, slug: slug, vitrina:vitrina, productId:productId, quantity:quantity, "dimensionBraindw": "Braindw", }, ], }, }, }); } catch (err) { console.log(err); } } //Formato del objeto con un tiempo de vida function FormatWithTTL(productId, shelf, description, shelfname, sku, brand, price,slug,position, ttl) { const now = new Date(); var item = { product: { productId: productId, description: description, brand: brand, price: price, sku: sku, slug: slug, position: position }, shelf: shelf, shelfname: shelfname, dateCreated: now, expiry: now.getTime() + ttl, } return item; } //Chequea que no exista objeto repetido y si existe los elimina para pushear el visto por ultima vez function AlreadyExists(Items, i) { var filtered = Items.filter(function (item) { return item.product.productId !== i.product.productId; }); return filtered; } //funcion Onclick function BdwDataLayer(key, productId, shelf, description, shelfname, sku, brand, price,slug,position) { if (productId === null || shelf === null || key === null) return 0; const ttl = 3600000; //Equivale a un tiempo de vida de 1 horas. var item = FormatWithTTL(productId, shelf, description, shelfname,sku, brand, price,slug,position, ttl); var Items = JSON.parse(localStorage.getItem(key)) || []; Items = AlreadyExists(Items, item); Items.push(item); localStorage.setItem(key, JSON.stringify(Items)); } //chequea si un producto esta en el localstorage function inLocalStorage(productId) { var key = "bdw-clicked-products"; var Items = JSON.parse(localStorage.getItem(key)); if (!Items) { return null; } var i = Items.length; while (i--) { if (Items[i].product.productId === productId.toString()) { return Items[i]; } } return null; } //elimina si se se paso el tiempo de vida function getWithExpiry2() { const now = new Date(); var key = "bdw-clicked-products"; var Items = localStorage.getItem(key); if (!Items) { return null; } Items = JSON.parse(Items); for (var i = 0; i < Items.length; ++i) { if (now.getTime() > Items[i].expiry) { Items.shift(); } else { break; } } Items = JSON.stringify(Items); localStorage.setItem(key, Items); } function receiveMessage(event) { try { if (!event.origin.includes("braindw")) return; if (event.data.includes("InitBraind")) { var elementId = event.data.split("|")[2]; var idsForQuery = event.data.split("|")[1]; var arrayIds = idsForQuery.split(","); var minStock = isNaN(parseInt(event.data.split("|")[3])) ? 0 : parseInt(event.data.split("|")[3]); var configs = []; var headersRequest = new Headers(); headersRequest.append("Content-Type", "application/json"); headersRequest.append("Authorization", getWithExpiry('token-request')); fetch( "https://5doa19p9r7.execute-api.us-east-1.amazonaws.com/MMPROD/braindw/products/"+idsForQuery, /*{ method: "GET", headers: headersRequest, redirect: "follow", }*/ ) .then((resp) => resp.json()) .then(function (data) { if (data.length > 0) { for (var i = 0; i <= data.length - 1; i++) { var configProd = window["getProduct"](data[i]); if (configProd.quantityLimit > minStock) { configs.push(configProd); } } document .querySelectorAll(elementId + " iframe")[0] .contentWindow.postMessage( "GetBraindwRender;" + JSON.stringify(configs), "*" ); } }) .catch(function (ex) { console.log(ex); }); } if (event.data.includes("BraindwAddCartEvent")) { var dataToSend = event.data.split("|")[1].split(","); if (dataToSend.length > 1) { AddToMiniCartBraindGond(dataToSend[0], dataToSend[1], dataToSend[2],dataToSend[3],dataToSend[4]); } return; } if (event.data.includes("BraindwClickRedirectParent")) { var urlReceived = event.data.split("|")[1]; window.location.href = urlReceived; return; } if (event.data.includes("BraindwClickRedirect")) { var dataToSend = event.data.split("|")[1].split("_"); BdwDataLayer( dataToSend[1],//key que necesito para guardar en local dataToSend[2],//iddeproducto dataToSend[3],//shelf la gondola dataToSend[4],//descripcion dataToSend[5],//shelfname o titulo de gondola dataToSend[6],//sku? dataToSend[7],//sellername dataToSend[8],//precio dataToSend[9],//slug dataToSend[10]);//posicion BraindwPushEventClickIframe( dataToSend[2], dataToSend[3], dataToSend[4], dataToSend[5], dataToSend[6], dataToSend[7], dataToSend[8], dataToSend[9], dataToSend[10] ); window["openProductDetail"](dataToSend[9], dataToSend[2]); return; } if (event.data.includes("BraindwEventAnalyticsBuy")) { var dataToSend = event.data.split("|")[1].split("_"); if (dataToSend[3] && dataToSend[4] && dataToSend[6]) { BraindwPushEventBuyIframe( dataToSend[2],//iddeproducto dataToSend[3],//shelf la gondola dataToSend[4],//descripcion dataToSend[5],//shelfname o titulo de gondola dataToSend[6],//sku? dataToSend[7],//sellername dataToSend[8],//precio dataToSend[9],//slug dataToSend[10],//position dataToSend[11]//quantity ); } } if (event.data.includes("AddCartCaptureEvent")) { var dataToSend = event.data.split("|")[1].split(","); BraindwCaptureProduct(dataToSend[0], 1, "", dataToSend[1], dataToSend[2]); return; } if ( event.data.includes("FullLoadedCarouselWithConfig") || event.data.includes("FullLoadedCarousel") ) { var dataReceived = event.data.split("|")[1]; if (event.data === "FullLoadedCarouselWithConfig") { dataReceived = parseInt(dataReceived) + 50; } var elementReceived = document.querySelector(event.data.split("|")[2]); elementReceived.style.overflow = "hidden"; elementReceived.style.position = "relative"; elementReceived.style.width = "100%"; if (elementReceived.querySelectorAll("iframe").length >= 0) { elementReceived.style.height = dataReceived + "px"; elementReceived.style.display = "block"; elementReceived.style.visibility = "visible"; clearTimeout(resetTimeEvent); resetTimeEvent = setTimeout(function(){ try { for (let i = 0; i < arrayGond.length; i++) { let gondola = arrayGond[i]; let impressions = []; window[gondola + "_DATA_EVENT"].forEach(function (item) { item.list = gondola; item.dimensionBraindw = "Braindw"; impressions.push(item); }); //console.log("impressions" + impressions); dataLayer.push({ event: "viewBraindw", ecommerce: { currencyCode: "PE", impressions: impressions, }, }); } } catch (err) { console.log(err); } }, 4000) } return; } if (event.data === "BraindwRemoveElements") { var sufixReceived = event.data.split("|")[1]; var bdwRemoveClasses = sufixReceived.includes("TEMPLATE_REMOVECLASS") ? "" : sufixReceived; if (bdwRemoveClasses.length > 0) { var elementsRemoves = document.querySelectorAll(bdwRemoveClasses); elementsRemoves.forEach(function (item) { item.parentNode.removeChild(item); }); } return; } if (event.data.includes("PushEventCarousel")) { var dataToSend = event.data.split("|")[1].split("_"); arrayGond.push(dataToSend[0]); arrayGond = Array.from(new Set(arrayGond)); window[dataToSend[0] + "_DATA_EVENT"] = JSON.parse(dataToSend[2]); } if (event.data.includes("BraindwEventAnalytics")) { var dataToSend = event.data.split("|")[1].split(","); if (dataToSend.length > 2) BraindwPushEventIframe(dataToSend[0], dataToSend[1], dataToSend[2]); } } catch (e) { console.log(e); } } function BraindwAddEvent(e, ev, callback) { var elements = document.querySelectorAll(e); for (var i = 0; i < elements.length; i++) { elements[i].addEventListener(ev, callback); } } function BdwGetConfigProduct(product) { var p = productFromCarts.find((x) => x.id === product.id); return { id: product.id, name: product.name, favorite: product.favorite, slug: product.slug, limitOfferTime: product.limitOfferTime, fractionated: false, image: product.imageList[1], quantityLimit: product.maxUnitSale, presentation: product.presentation, description: product.noFractionatedText, price: product.price, isProductInCart: window["isProductInCart"](product.id), quantity: p !== undefined ? p.quantity : 1, statusId: product.productStatusId, }; } var _eventHandlers = {}; function addListener(node, event, handler, capture) { if (!(node in _eventHandlers)) { _eventHandlers[node] = {}; } if (!(event in _eventHandlers[node])) { _eventHandlers[node][event] = []; } _eventHandlers[node][event].push([handler, capture]); node.addEventListener(event, handler, capture); } function removeAllListeners(node, event) { if (node in _eventHandlers) { var handlers = _eventHandlers[node]; if (event in handlers) { var eventHandlers = handlers[event]; for (var i = eventHandlers.length; i--; ) { var handler = eventHandlers[i]; if (handler[0] === receiveMessage) { node.removeEventListener(event, handler[0], handler[1]); } } } } } function AddToMiniCartBraindGond(IdCode, quantity, fractionalMode, sellerName, sellerId) { try { if (window["isProductInCart"](IdCode.toString())) { window["updateProductFromCart"]( IdCode.toString(), parseInt(quantity), fractionalMode === "true", sellerId ? sellerId : sellerName, sellerName ); } else { window["addProductToCart"]( IdCode.toString(), parseInt(quantity), fractionalMode === "true", sellerId, sellerName ); window.scrollBy(0, 1); } if (document.URL.indexOf("/carrito") > -1) { setTimeout(function () { window.scrollBy(0, 1); }, 3000); } if (window["isProductInCart"](IdCode.toString())) { UpdateItemSlider(IdCode, "update"); }else{ RemoveItemSlider(IdCode); } } catch (e) { console.log(e); } } function formatstringBnw(s) { var r = s.toLowerCase(); r = r.replace(new RegExp(/\s/g), ""); r = r.replace(new RegExp(/[àáâãäå]/g), "a"); r = r.replace(new RegExp(/[èéêë]/g), "e"); r = r.replace(new RegExp(/[ìíîï]/g), "i"); r = r.replace(new RegExp(/ñ/g), "n"); r = r.replace(new RegExp(/[òóôõö]/g), "o"); r = r.replace(new RegExp(/[ùúûü]/g), "u"); return r; } function BraindwCaptureCategory(category) { var _bndwOb2 = document.createElement("script"); _bndwOb2.async = true; _bndwOb2.src = _URLBNDW2 + "/tracking/capture?HASH=inkafarma_produccion_h5hgp&iscategory=true&og:categorycode=" + category; _bndwOb2.charset = "UTF-8"; document.head.appendChild(_bndwOb2); } var bdwLastProductCodeProcess = ''; function BraindwCaptureProduct(idProduct, isCart, slugList, section, title) { var headersRequest = new Headers(); /* try { if (section && title) { dataLayer.push({ event: "ga-braindw", eventCategory: "ga-braindw-addtocart", eventAction: section, eventLabel: title, }); } } catch (error) { console.log(error); }*/ headersRequest.append("Content-Type", "application/json"); headersRequest.append("Authorization", getWithExpiry('token-request')); fetch( "https://5doa19p9r7.execute-api.us-east-1.amazonaws.com/MMPROD/braindw/products/"+idProduct, /*{ method: "GET", headers: headersRequest, redirect: "follow", }*/ ) .then((resp) => resp.json()) .then(function (data) { if (data.length > 0) { var item = data[0]; var categoriesList = ""; item.categoryList.forEach((element) => { categoriesList += BdwCategoryTreeRecursion(element, ""); }); if (slugList) { categoriesList = slugList; } var urlParameters = "og:title=" + item.name + "&og:image=" + encodeURIComponent(item.imageList[2].url) + "&og:url=" + encodeURIComponent( "https://inkafarma.pe/producto/" + item.slug + "/" + item.id ) + "&og:categoriescodes=" + categoriesList + item.brand.toLowerCase().replace(',','') + "&og:codeproduct=" + item.id + "&og:brand=" + item.brand + "&og:categorycode=" + categoriesList + "&og:price=" + item.price + "&og:priceold=&iscart=" + isCart; var _bndwOb2 = document.createElement("script"); _bndwOb2.async = true; _bndwOb2.src = _URLBNDW2 + "/tracking/capture?HASH=inkafarma_produccion_h5hgp&" + urlParameters; _bndwOb2.charset = "UTF-8"; document.head.appendChild(_bndwOb2); if(isCart==0 && bdwLastProductCodeProcess!=item.id) { bdwLastProductCodeProcess = item.id; var bdwCatFirst = ''; if(categoriesList.indexOf(',')!=-1)bdwCatFirst=categoriesList.split(',')[0]; Braindw_getProduct(item,bdwCatFirst); } console.log('bdw push cp product'); } }) .catch(function (ex) { console.log(ex); }); } function BraindwvalidateEmail(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 BraindwCookiePush(email) { if (BraindwvalidateEmail(email)) { var bdwEmailStorage = localStorage.getItem("bdw_email"); if (bdwEmailStorage && bdwEmailStorage === email) { return; } try { fetch( _URLBNDW + "/tracking/SetCookiesNdway?email=" + email + "&company=inkafarma_produccion", { credentials: "include", mode: "no-cors", method: "POST", } ) .then(function (resp) { return resp.text(); }) .then(function (data) { localStorage.setItem("bdw_email", email); Braindw_pushInfo(email); return false; }) .catch(function (ex) { console.log(ex); }); } catch (e) {} } } function searchTree(element, matchingTitle) { if (element.title == matchingTitle) { return element; } else if (element.children != null) { var i; var result = null; for (i = 0; result == null && i < element.children.length; i++) { result = searchTree(element.children[i], matchingTitle); } return result; } return null; } function BdwCategoryTreeRecursion(category, listCategoriesString) { var newStringAppend = listCategoriesString.includes(category.id) ? listCategoriesString : listCategoriesString + category.id + ","; if (category.categories.length > 0) { category.categories.forEach(function (item) { newStringAppend += item.id + ","; newStringAppend = BdwCategoryTreeRecursion(item, newStringAppend); // Llamada recursiva para cada subcategoría }); } return newStringAppend; } function pushEventEECAddCart(){ //lo que debe hacer cuando compra un producto desde ficha producto console.log('pushEventEECAddCart....') try { var id = ""; var quantity = 1; var id=document.location.href.split("/")[5] if (id !== "" && id !== null) { var item = inLocalStorage(id); if (item !== null) { BraindwPushEventBuyIframe( item.product.productId, item.shelf, item.product.description, item.shelfname, item.product.sku, item.product.brand, item.product.price, item.product.slug, item.product.position, quantity ); } } } catch (e) {} } function addEventCaptureAddToCart() { var arreglo = Array.from( document.querySelectorAll( "button.btn.btn-primary.btn-spacer-regular.label-black.btn-block, button.btn.btn-primary.btn-spacer-large.label-black-1.btn-block" ) ); if (document.URL.indexOf("/carrito") > -1) { return; } for (var i = 0; i < arreglo.length; i++) { var elemento = arreglo[i]; elemento.onclick = function () { let urlProduct = location.href; if (urlProduct.indexOf("producto") > -1) { idProduct = urlProduct .split("/") [urlProduct.split("/").length - 1].split("?")[0]; BraindwCaptureProduct(idProduct, 1); pushEventEECAddCart(); } else { var _element = this.closest(".card"); if (_element && _element.querySelectorAll("a").length > 0) { urlProduct = _element.querySelector("a").href; idProduct = urlProduct.split("/")[urlProduct.split("/").length - 1]; BraindwCaptureProduct(idProduct, 1); UpdateItemSlider(idProduct, "update"); setTimeout(function () { var bdwinputs = _element.querySelectorAll( "#btn-plus-quantity button,#btn-minus-quantity button" ); bdwinputs.forEach(function (e) { e.onclick = function () { UpdateItemSlider(idProduct, "update"); }; }); }, 500); } } }; } } function BraindwGetSucCookie() { if ( localStorage.getItem("drugstore-stock") !== null && localStorage.getItem("drugstore-stock") !== "1" ) { return localStorage.getItem("drugstore-stock"); } return ""; } function braindw_getSessionDate() { let result = null; try { let SalesChannel = BraindwGetSucCookie(); result = { SalesChannel: SalesChannel, }; } catch (e) { console.log("braindw_getSessionDate error ", e); } return result; } function Braindw_PersistencyCategory(e) { try { if (e != null) { var s = {}, t = braindw_getSessionDate(); t && (s.sessionDate = t); s.category = e; braindw_sendPersistency(s); } } catch (e) {} } function Braindw_getProduct(data, cat) { let e = null; if (data !== null) { var s = {}, t = braindw_getSessionDate(); t && (s.sessionDate = t); e = { ProductCode: data.id, Title: data.name, PriceOnline: data.price, Brand: data.brand, Category: cat, CategoryCode: cat, UrlImage: data.imageList[0].url, UrlProduct: document.URL, BranchOffice: BraindwGetSucCookie(), }; s.product = e; braindw_sendPersistency(s); } } function Braindw_getCatOpened() { let e = null; var items = []; var data = JSON.parse(localStorage.getItem("shoppingCartList")); for (var i = 0; i < data.length; i++) { items.push({ ProductTitle: "", ProductCode: data[i].productId, ProductUrlImage: "", ProductQuantity: data[i].quantity, ProductQuantityDetails: "", ProductPrice: "", PriceTotal: "", Event: "Load", }); } e = { CartNumber: "", BranchOffice: BraindwGetSucCookie(), Items: items, }; return e; } function Braindw_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, }; return e; } function braindw_getSearch() { let e = null; try { if (-1 === document.URL.toLowerCase().indexOf("/buscador")) return e; e = { searchterm: braindwGetUrlParameter("keyword") } } catch (e) { console.log(e) } return e } function Braindw_pushInfo(emailGuest) { setTimeout(function (h) { if (emailGuest === undefined) { emailGuest = localStorage.getItem("bdw_email"); } let e = { sessionDate: braindw_getSessionDate(), }; let a = Braindw_getCatOpened(); e.search = braindw_getSearch(); a ? (e.cartOpened = a) : (a = Braindw_getCartClosed()) && (e.cartClosed = a); braindw_sendPersistency(e, emailGuest); }, 1000); } function braindw_sendPersistency(e, emailGuest) { let n = { emailguest: emailGuest != undefined ? emailGuest : "", dataset: encodeURI(JSON.stringify(e)), page: "", url: window.location.href.split("?")[0], urlb: _URLBNDW + "/Script/braindw/inkafarma_produccion_h5hgp?hs=Sat Apr 21 2018 10:00:38 GMT-0300 (Hora estándar de Argentina)", BranchOffice: BraindwGetSucCookie(), }; 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 BdwCloseCartAction(e) { var bdwCheckValue = false; var bdwCheckValue2 = false; var bdwEmailGuest = ""; var bdwchecks = document.querySelectorAll(".terms-row input[type=checkbox]"); if (bdwchecks.length > 0) { bdwCheckValue = bdwchecks[0].checked; bdwCheckValue2 = bdwchecks[1].checked; bdwEmailGuest = document.querySelectorAll("#emailAnonymous").length > 0 ? document.querySelector("#emailAnonymous").value : ""; } if (e) { var cartConfirmation = JSON.parse(e); if ( cartConfirmation.hasOwnProperty("orderInfo") ) { var bdwcart = { CartNumber: cartConfirmation.orderInfo.shoppingCartId, BranchOffice: BraindwGetSucCookie(), Items: null, }; let ce = { sessionDate: braindw_getSessionDate(), cartClosed: bdwcart, }; braindw_sendPersistency(ce, bdwEmailGuest); } } } function captureEmailCheckout() { var bdwEmailGuest = ""; var bdwchecks = document.querySelectorAll("fp-checkbox-control"); if (bdwchecks.length > 0 && bdwchecks[0].classList.value.indexOf('ng-valid') > -1 && bdwchecks[1].classList.value.indexOf('ng-valid') > -1) { document.querySelector( ".btn.btn-primary.btn-spacer-regular.label-black.btn-block" ).onclick = function () { if (bdwchecks[0].classList.value.indexOf('ng-valid') > -1 && bdwchecks[1].classList.value.indexOf('ng-valid') > -1) { bdwEmailGuest = document.querySelector("#ctrl--email").value; if (document.URL.indexOf("bdwtest")) { console.log("bdw check1"); } BraindwCookiePush(bdwEmailGuest); } }; } bdwchecks.forEach(function (item) { item.onclick = function (e) { if (bdwchecks[0].classList.value.indexOf('ng-valid') > -1 && bdwchecks[1].classList.value.indexOf('ng-valid') > -1) { var bdwbuttons = document.querySelectorAll( ".btn.btn-primary.btn-spacer-regular.label-black.btn-block" ); if (bdwbuttons.length > 0) { document.querySelector( ".btn.btn-primary.btn-spacer-regular.label-black.btn-block" ).onclick = function () { if (bdwchecks[0].classList.value.indexOf('ng-valid') > -1 && bdwchecks[1].classList.value.indexOf('ng-valid') > -1) { if (document.URL.indexOf("bdwtest")) { console.log("bdw check2"); } bdwEmailGuest = document.querySelector("#ctrl--email").value; BraindwCookiePush(bdwEmailGuest); } }; } } }; }); } function braindwCloseCart() { document.querySelector("#braindw_loader").remove(); } function braindwLoadingModal() { document .querySelector("body") .insertAdjacentHTML( "afterend", " " + '
Espera un momento, tu carrito se está cargando.
" + "' + p.title + "
" + ""; } return items; } var bdwSearchTemplate = function () { return ` `; }; var controller = new AbortController(); document .querySelector("#main-header-search-input") .addEventListener("input", function (e) { controller.abort(); controller = new AbortController(); var signal = controller.signal; var bdwQuery = document.querySelector("#main-header-search-input").value; if (bdwQuery !== "" && bdwQuery.length >= 3) { fetch( "https://u.braindw.com/els/inkafarma?ft=" + bdwQuery + "&qt=24&sc=" + BraindwGetSucCookie() + "&refreshmetadata=false&disablecategoryexclusion=true&apisearch=true", { method: "get", signal: signal, } ) .then(function (resp) { return resp.json(); }) .then(function (data) { if ( document.querySelectorAll(".bdw__input-search-results-wrapper") .length > 0 ) { document .querySelector(".bdw__input-search-results-wrapper") .remove(); document.querySelector(".bdw-searcher-shadow-overlay").remove(); } if (data.hits.total === 0) { var searchContent = document.querySelectorAll( "fp-searcher-header > .products-filtered-container" ); if (searchContent.length > 0) { searchContent[0].style.display = "block"; } return; } var searchHtml = bdwSearchTemplate(); searchHtml = searchHtml.replace(/%bdwQuery%/g, bdwQuery); var prodsStock = []; data.hits.hits.forEach(function (item) { var prod = window["getProduct"]( JSON.parse(item._source.extensionData[0].value) ); if (prod.quantityLimit > 0) { prodsStock.push(item); } }); data.hits.hits = prodsStock; searchHtml = searchHtml.replace( /%items%/g, buildItem(data.hits, bdwQuery) ); searchHtml = searchHtml.replace( /%sugeridos%/g, buildItemSugeridos(data.hits, bdwQuery) ); var searchContent = document.querySelectorAll( "fp-searcher-header > .products-filtered-container" ); if (searchContent.length > 0) { searchContent[0].style.display = "none"; } document .querySelector("fp-searcher-header") .insertAdjacentHTML("beforeend", searchHtml); document .querySelector(".bdw-searcher-shadow-overlay") .addEventListener("click", function (e) { if ( document.querySelectorAll( ".bdw__input-search-results-wrapper" ).length > 0 ) { document.querySelector( ".bdw__input-search-results-wrapper" ).style.display = "none"; document.querySelector( ".bdw-searcher-shadow-overlay" ).style.display = "none"; } }); }) .catch(function (ex) { console.log(ex); }); } else { if ( document.querySelectorAll(".bdw__input-search-results-wrapper") .length > 0 ) { document.querySelector(".bdw__input-search-results-wrapper").remove(); document.querySelector(".bdw-searcher-shadow-overlay").remove(); } } }); document .querySelector("#main-header-search-input") .addEventListener("focusin", function (e) { var bdwQuery = document.querySelector("#main-header-search-input").value; if (bdwQuery !== "" && bdwQuery.length >= 3) { if ( document.querySelectorAll(".bdw__input-search-results-wrapper") .length > 0 ) { document.querySelector( ".bdw__input-search-results-wrapper" ).style.display = "block"; document.querySelector(".bdw-searcher-shadow-overlay").style.display = "block"; } } else { if ( document.querySelectorAll(".bdw__input-search-results-wrapper") .length > 0 ) { document.querySelector(".bdw__input-search-results-wrapper").remove(); document.querySelector(".bdw-searcher-shadow-overlay").remove(); } } }); document .querySelector("#main-header-search-input") .addEventListener("keyup", function (e) { if ( event.code === "Enter" && document.querySelectorAll(".bdw__input-search-results-wrapper").length > 0 ) { document.querySelector(".bdw__input-search-results-wrapper").remove(); document.querySelector(".bdw-searcher-shadow-overlay").remove(); } }); }