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.

" + "
" + "
" + "
" ); } function braindwBuildCart(ids) { var arrayIds = ids.split(","); var configs = []; var headersRequest = new Headers(); if ( localStorage.getItem("drugstore-stock") !== null && localStorage.getItem("drugstore-stock") !== "1" ) { headersRequest.append( "drugstore-stock", localStorage.getItem("drugstore-stock") ); } 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) { for (var i = 0; i <= data.length - 1; i++) { var configProd = window["getProduct"](data[i]); configs.push(configProd); try { if (window["isProductInCart"](configProd.id.toString())) { window["updateProductFromCart"]( configProd.id.toString(), 1, configProd.fractionated ); } else { window["addProductToCart"]( configProd.id.toString(), 1, configProd.fractionated ); window.scrollBy(0, 1); } } catch (e) { console.log(e); } } var iframes = document.querySelectorAll("iframe[id^=Braindw]"); iframes.forEach(function (iframe) { iframe.contentWindow.postMessage( "UpdateItemSlider|" + JSON.stringify(configs) + "|" + actionConfig, "*" ); }); } braindwCloseCart(); }) .catch(function (ex) { console.log(ex); braindwCloseCart(); }); } 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, " ")); } function setWithExpiry(key, value, ttl) { const now = new Date() const item = { value: value, expiry: now.getTime() + ttl, } localStorage.setItem(key, JSON.stringify(item)) } function getWithExpiry(key) { const itemStr = localStorage.getItem(key) // if the item doesn't exist, return null if (!itemStr) { return null } const item = JSON.parse(itemStr) const now = new Date() // compare the expiry time of the item with the current time if (now.getTime() > item.expiry) { // If the item is expired, delete the item from storage // and return null localStorage.removeItem(key) return null } return item.value } // function BraindwLastOrderUser() { console.log(window.dataUser); if (!window.dataUser.hasOwnProperty('authId')) { return; } var urlencoded = new URLSearchParams(); urlencoded.append("grant_type", "client_credentials"); fetch("https://apiprod.farmaciasperuanas.pe/oauth/access-token", { method: 'POST', headers: { "Authorization" : "Basic MW9YQUZPcHo4dkNHbU8yTDdtS0NnWE5BR1JCcEdHMGRIWU1wMmdkUTdOU0ljWUdYOjBjenZTeXhkTGxtQ3NlU0xFVEx2QnpaZE9qNldYQVJYVVNnTnB0Z1JETjQwWTVVNlZBUmNpdGxCcExQQWJ3Q1Q=", "Content-Type" : "application/x-www-form-urlencoded" }, body: urlencoded, redirect: 'follow' }) .then(response => response.json()) .then(function (data) { fetch("https://apiprod.farmaciasperuanas.pe/orders/api/v1/latest-orders", { method: 'POST', headers: { "client_id":"latest-orders", "Authorization": "Bearer " + data["access_token"], "Content-Type":"application/json", "access_token":"xxx" }, body: JSON.stringify({"userId": window.dataUser.authId}), redirect: 'follow' }) .then(response => response.json()) .then(function (result) { var skusOrders = []; result.orders.forEach(function (order) { if (order.shoppingCartStatus !== "CANCELADA") { var skus = order.productList.map(x => { return x.productPack.product.id }); skusOrders.push(skus); } }); if (skusOrders.length > 0) { if (document.querySelectorAll('#braindw-gondola-9 iframe').length === 0){ var _bndwOb2 = document.createElement('script'); _bndwOb2.async = true; _bndwOb2.src = _SURLBNDW + "/tracking/track?HASH=inkafarma_produccion_h5hgp&wordsfound=,&buyer={CLIENT.BUYER}&name=&lastname=&gender=&branchOffice=" +BraindwGetSucCookie()+ "&country=&state=&city=&email=&u=home.braindw.com/lastorders/" + skusOrders.join(',') +"/1"; _bndwOb2.charset = "UTF-8"; document.head.appendChild(_bndwOb2); if(document.URL.indexOf("/carrito") > -1) { var _bndwOb2 = document.createElement('script'); _bndwOb2.async = true; _bndwOb2.src = _SURLBNDW + "/tracking/track?HASH=inkafarma_produccion_h5hgp&wordsfound=,&buyer={CLIENT.BUYER}&name=&lastname=&gender=&branchOffice=" +BraindwGetSucCookie()+ "&country=&state=&city=&email=&u=checkout.braindw.com/lastorders/" + skusOrders.join(',') +"/1"; _bndwOb2.charset = "UTF-8"; document.head.appendChild(_bndwOb2); } } } }) .catch(error => console.log('error', error)); }) .catch(error => console.log('error', error)); } function addEventCaptureDetail(slugList) { var arreglo = Array.from(document.querySelectorAll('a.link')); for (var i = 0; i < arreglo.length; i++) { var elemento = arreglo[i]; elemento.onclick = function() { let urlProduct = this.href; idProduct = urlProduct.split("/")[urlProduct.split("/").length -1]; BraindwCaptureProduct(idProduct, 0, slugList); } } } function addEventCaptureAddToCart2(slugList) { 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')); for (var i = 0; i < arreglo.length; i++) { var elemento = arreglo[i]; elemento.onclick = function() { var _element = this.closest('.card.product'); urlProduct = _element.querySelector('a.link').href; idProduct = urlProduct.split("/")[urlProduct.split("/").length -1]; BraindwCaptureProduct(idProduct, 1, slugList); } } } function getCategoryRootName(){ return location.href.split("/")[location.href.split("/").length -1].split('?')[0]; } function Braindw_getCategory(){ let cp = getCategoryRootName(); fetch('https://5doa19p9r7.execute-api.us-east-1.amazonaws.com/MMPROD/braindw/department-tree?keyword='+ cp ) .then((resp) => resp.json()) .then(function(bdwCatResult){ if(bdwCatResult[0].id > 0 ){ let keyword = decodeURI(location.href.split("/")[location.href.split("/").length -1].split('?')[0]); var categoryId = ''; if (keyword === bdwCatResult[0].keyword) { categoryId = bdwCatResult[0].id; }else{ bdwCatResult[0].categories.forEach(function(item){ if (keyword === item.keyword) { categoryId = item.id; return true; } item.subCategories.forEach(function(subc){ if (keyword === subc.keyword) { categoryId = subc.id; return true; } }); }); } var category = { Title: keyword, CategoryCode: categoryId }; localStorage.setItem('bdw_last_category',categoryId); BraindwCaptureCategory(categoryId); Braindw_PersistencyCategory(category); } }) } var _URLBNDW = ""; var isAttached = typeof isAttached !== "undefined" ? isAttached : false; var productFromCarts = []; var arrayGond = []; var resetTimeEvent = null; BraindwDomReady(function () { try { productFromCarts = JSON.parse(localStorage.getItem("shoppingCartList")); _URLBNDW = window.location.protocol + "//s.braindw.com"; _SURLBNDW = window.location.protocol + "//static-s.braindw.com"; if (!isAttached) { localStorage.setItem("currentPage", location.href); addListener(window, "message", receiveMessage, false); isAttached = true; BdwInterceptorRequest("/cart", "post", function (e) { BdwCloseCartAction(e); if (document.URL.indexOf("/checkout") > -1) { if (document.URL.indexOf("bdwtest")) { console.log("bdw check 222"); //captureEmailCheckout(); } return; } if (productFromCarts.length === 0) { productFromCarts = JSON.parse( localStorage.getItem("shoppingCartList") ); } else { var arr2 = JSON.parse(localStorage.getItem("shoppingCartList")); var difference = []; var differenceUpdate = []; productFromCarts.forEach(function (item) { var c = arr2.find((x) => x.productId == item.productId); if (c === undefined) { difference.push(item.productId); } else { if ( c.quantity !== item.quantity || c.fractionalMode !== item.fractionalMode ) { differenceUpdate.push(item.productId); } } }); if (difference.length > 0) { RemoveItemSlider(difference.join(",")); } if (differenceUpdate.length > 0) { UpdateItemSlider(differenceUpdate.join(","), "update"); } } productFromCarts = JSON.parse(localStorage.getItem("shoppingCartList")); setTimeout(function (event) { var removeElements = document.querySelectorAll( "#deleteProductDesktop button" ); if (removeElements === null) { return; } removeElements.forEach(function (item) { removeAllListeners(item, "click"); item.addEventListener("click", function (ev) { if (ev.currentTarget.closest(".product-mini-cart") === null) { return; } var hrefElement = ev.currentTarget .closest(".product-mini-cart") .querySelector(".link").href; var idRemoveElement = hrefElement.split("/")[ hrefElement.split("/").length - 1 ]; RemoveItemSlider(idRemoveElement); }); }); }, 300); if (document.URL.indexOf("/carrito") > -1) { setTimeout(function (event) { var removeElements = document.querySelectorAll(".empty-cart"); if ( removeElements.length > 0 && document.querySelectorAll("#braindw-cross-custom").length > 0 ) { document.querySelector("#braindw-cross-custom").remove(); } }, 1000); } }); BdwInterceptorRequest("/coverage-locations", "get", function (data) { var drugstoreStock = JSON.parse(data); if (drugstoreStock.hasOwnProperty("favorite")) { localStorage.setItem( "drugstore-stock", drugstoreStock.favorite.drugstoreStockId ); } }); setTimeout(function () { var bdwCartItems = braindwGetUrlParameter("cartAbandoned"); if (bdwCartItems) { braindwLoadingModal(); braindwBuildCart(bdwCartItems); } }, 2500); } if (getWithExpiry('token-request')) { //apagar iframe dejar solo Landings if(window.location.href.indexOf("mundo/") > -1){ //BraindwLoadScript(document, "script", escape(window.location)); } }else{ var myHeaders = new Headers(); myHeaders.append("Authorization", "Basic NDAyMmEycXY4NGM4cm1hNDEzcjM2ODhia3E6Y2hjNzBnNm43bHI1NWRoOWlkcmZtOHA0OGduZWxkMWV1ZmRibTI3aXJpMXNxZHExamsx"); myHeaders.append("Content-Type", "application/x-www-form-urlencoded"); var urlencoded = new URLSearchParams(); urlencoded.append("scope", "third_party_rs/api"); urlencoded.append("grant_type", "client_credentials"); var requestOptions = { method: 'POST', headers: myHeaders, body: urlencoded, redirect: 'follow' }; fetch("https://fpthirdpartytest.auth.us-east-1.amazoncognito.com/oauth2/token", requestOptions) .then(response => response.json()) .then(function(data){ setWithExpiry('token-request',data['access_token'],3600000); }) .catch(error => console.log('error', error)); } Braindw_pushInfo(); getWithExpiry2(); if (window.dataUser && window.dataUser.email && !localStorage.getItem("bdw_email")) { BraindwCookiePush(window.dataUser.email); } //lo que debe hacer cuando compra un producto desde ficha producto /*BraindwAddEvent("button.btn.btn-primary.btn-spacer-large.label-black-1.btn-block", "click", function (e) { var rgxProd = new RegExp('.*?:\/\/(.*)inkafarma.pe\/producto\/(.*)$'); try { if (location.href.match(rgxProd) !== null) { 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) {} });*/ setTimeout(function () { addEventCaptureAddToCart(); }, 2500); setTimeout(function () { //captureEmailCheckout(); }, 3000); setTimeout(function(){ //BraindwLastOrderUser(); }, 2500); var bdwemailPx = braindwGetUrlParameter("bdwemail"); if (bdwemailPx) { BraindwCookiePush(bdwemailPx); } //captures if (document.URL.indexOf('/producto') > -1) { var idProduct = document.location.href.split("/")[document.location.href.split("/").length -1 ].split('?')[0]; BraindwCaptureProduct(idProduct, 0); //skusUltimosVistos(idProduct); } if (document.URL.indexOf('/categoria') > -1) { Braindw_getCategory(); } setTimeout(function(){ if (document.URL.indexOf('/lista') > -1) { var slugList = location.pathname.split('/')[location.pathname.split('/').length -1]; addEventCaptureAddToCart2(slugList); addEventCaptureDetail(slugList); } }, 1000); } catch (e) { console.log("[Braindw] [error]"); } }); if (document.URL.indexOf("bdwtest") > -1) { console.log("search bdw init"); document .querySelector("body") .insertAdjacentHTML( "beforeend", "" ); function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } function openProductBdw(id, slug) { window["openProductDetail"](slug, id); document.querySelector(".bdw__input-search-results-wrapper").remove(); document.querySelector(".bdw-searcher-shadow-overlay").remove(); if (document.querySelectorAll(".searcher-shadow-overlay").length > 0) { document.querySelector(".searcher-shadow-overlay").remove(); } BraindwPushEventIframe("desplegable-buscador", slug, id); return false; } function buildItem(data, text) { var items = ""; var itemsPerView = bdwMobile.any() ? 3 : 4; if (itemsPerView > data["hits"].length) { itemsPerView = data["hits"].length; } for (var i = 0; i < itemsPerView; i++) { var p = data["hits"][i]._source; var slug = p.link.split("/")[p.link.split("/").length - 2]; var reg = new RegExp(text, "gi"); var match = reg.exec(p.title); if (match) { p.title = p.title.replace(match[0], "" + match[0] + ""); } var presentation = p.description; var imgTest = new Image(); imgTest.onerror = function (e) { document .querySelectorAll('img[src="' + e.srcElement.src + '"]') .forEach(function (i) { i.src = "https://inkafarma.pe/assets/images/product/error-image.svg"; }); }; imgTest.src = p.imageUrl; items += '
' + '' + "

" + presentation + "

" + '" + p.title + "" + "
"; } return items; } function buildItemSugeridos(data, text) { var items = ""; var itemsPerViewDesk = bdwMobile.any() ? 3 : 4; if (itemsPerViewDesk > data["hits"].length) { itemsPerViewDesk = data["hits"].length; } data["hits"] = data["hits"].slice(itemsPerViewDesk); var itemsPerView = bdwMobile.any() ? 6 : 7; if (itemsPerView > data["hits"].length) { itemsPerView = data["hits"].length; } for (var i = 0; i < itemsPerView; i++) { var p = data["hits"][i]._source; var slug = p.link.split("/")[p.link.split("/").length - 2]; var reg = new RegExp(text, "gi"); var match = reg.exec(p.title); if (match) { p.title = p.title.replace(match[0], "" + match[0] + ""); } items += '" + '

' + p.title + "

" + "
"; } return items; } var bdwSearchTemplate = function () { return `
%items%

%sugeridos%
`; }; 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(); } }); }