/*File:~/Custom/Content/Widgets/clean.marketing.banner.swiper/Scripts/wd.clean.marketing.banner.swiper.js*/
try{
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Widgets/product.price/Scripts/wd.product.price.js*/
try{!function(a){var o={},r={};a.widget("wd.ProductPrice",a.wd.widget,{_create:function(){var o=this,t=a(o.element),i=t.attr("data-widget-pid"),e=t.data("product-selection"),e=e&&/\/(\d+\.\d+\/)+/g.test(e.PropertyPath)?e.PropertyPath:"",r=browsingContext.Common.Config.Product.SkipCache,c=function(t){t={ID:i,I:[{I:t}]};o._fetchCachedDescription(a.param({R:[t]})).done(function(t){o._updateDescription(t.Prices[0].PriceDescription)})};(r=browsingContext.Page.Product?r:!1)&&browsingContext.Page.Product&&browsingContext.Page.Product.ProductID+""==i+""&&0<browsingContext.Page.Product.SkuID&&c(browsingContext.Page.Product.SkuID),o.subscribe("/wd/product/variation/changed/"+i,function(t,e){var i,n=e.variationContent.sku;null===n||e.variationContent.noPriceChange||(i=(e=o.element.find(".priceContainer")).html(n.priceDescription).text(),e.html(i),r&&c(n.productID))}),o.subscribe("/wd/product/price/change/variationPath/"+i+e,function(t,e){o._fetchCachedDescription({R:[{ID:i,V:e}]}).done(function(t){o._updateDescription(t.Prices[0].PriceDescription)})}),o.subscribe("/wd/product/price/change/description/"+i,function(t,e){e&&o._fetchCachedDescription(e,"POST").done(function(t){o._updateDescription(t.Prices[0].PriceDescription)})}),o.subscribe("/wd/product/variation/optionslist/init/"+i,function(){t.addClass("wd-hide")})},_fetchCachedDescription:function(t,e){var i,n=(e=e?e.toUpperCase():"GET")+"/"+JSON.stringify(t);return o[n]||(r[n]?((i=a.Deferred()).resolve(r[n]),i.promise()):(o[n]=this._fetchDescription(t,e),o[n].done(function(t){r[n]=t}).complete(function(){o[n]=null})))},_fetchDescription:function(t,e){var i;return a.isPlainObject(t)&&(t=JSON.stringify(t)),e&&"GET"!==e?(i=browsingContext.Common.Urls.BaseUrl+"web-api/v1/Shopping/Price/Post",a.ajax({url:i,type:"POST",data:t,headers:{"Content-Type":"application/json"}})):(i=browsingContext.Common.Urls.BaseUrl+"web-api/v1/Shopping/Price/Get",a.ajax({url:i,type:"GET",cache:!0,data:t}))},_updateDescription:function(t){this.element.find(".priceContainer").html(t)}})}(jQuery,(window,document));
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Widgets/clean.product.list.swiper/Scripts/wd.clean.product.list.swiper.js*/
try{
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Widgets/clean.browsing.categorymenu/Scripts/wd.clean.browsing.categorymenu.js*/
try{
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Widgets/error.summary/Scripts/wd.error.summary.js*/
try{$.widget("wd.ErrorSummary",$.wd.widget,{_create:function(){var r,t=this,i=t.getContext();if(window&&window.opener)try{window.opener.$.publish("/Page/Error",i)}catch(e){}window&&null==window.opener&&(t.subscribe("/Page/Error",function(r,e){t.element.html(e.element.html())}),t.subscribe("/Page/Response",function(r,e){if(e&&!e.IsValid){var o,s,a="";for(o in e.Errors){var l=e.Errors[o];if(!l.ErrorGroup||(l.ErrorGroup,null!=l.ErrorGroup)){a=l.ErrorMessage||l.Message||"";break}}""!=a?t.alert('<div class="erros" style="display:none;">Erro(s):</div><ul><li>'+a+"</li></ul>","error",{className:"wd-error-summary-modal"}):(s=$("#ResponseErrorTmpl").html(),s=Mustache.render(s,e),t.element.html(s),"modal"===i().attr("data-mode")?t.alert(s,undefined,{className:"wd-error-summary-modal multi-error-modal"}):$("html, body").animate({scrollTop:0},300))}})),"modal"===i().attr("data-mode")&&(setTimeout(function(){t.publish("/Modal/Error",{error:i(".error-summary-message").text()})},0),r=[],setTimeout(function(){i(".error-summary-message").each(function(){r.push($(this).html())}),r.length&&t.alert('<div class="erros" style="display:none;">Erro(s):</div><ul><li>'+r.join("</li><li>")+"</li></ul>","error",{className:"wd-error-summary-modal"})},0))}});
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Widgets/browsing.modal/Scripts/wd.browsing.modal.js*/
try{!function(p,d,h){var c=p.noop,m='<span class="the-modal-placeholder"></span>';p.widget("wd.BrowsingModal",p.wd.widget,{_create:function(){this.getContext();var t=p("#mainModal"),i=p("#auxiliaryModal");function n(n){var a=n.onOpenFunction||c,l=n.onComplete||c,o=n.customClass||n.className||" ",e=n.modal||t,i=n.onCloseFunction||n.onClosed||c,d=n.width||"auto",s=n.height||"auto",r=n.onCleanup||c;e.modal().open({onOpen:function(e,o){var t,i;e.find(".the-modal .the-modal-container").empty(),e.find(".the-modal").addClass("putted-sizes").css({"max-width":isNaN(d)?d:d+"px","max-height":isNaN(s)?s:s+"px"}),n.hrefAjax=n.hrefAjax||!1,n.returnToOrigin=!1,n.$origin=null,p(".the-modal").addClass("opened"),n.hrefAjax&&n.href!==h?p.ajax({url:n.href,type:"get",success:function(o){e.find(".the-modal .the-modal-container").append(o),p(".the-modal").addClass("populated"),p.publish("browsingModal/centerModal/",{el:e})}}):"string"==typeof n.href?(e.find(".the-modal .the-modal-container").css({overflow:"hidden"}).append('<iframe id="iframe-modal" src="'+n.href+'" />'),p(".the-modal").addClass("populated with-iframe"),null===s&&p.publish("browsingModal/resizeModal/Height",{height:p("#iframe-modal").contents().find("html").height()})):n.html!==h?(e.find(".the-modal .the-modal-container").append(n.html),p(".the-modal").addClass("populated"),p.publish("browsingModal/centerModal/",{el:e})):n.element!==h&&(n.element.length&&"SCRIPT"==n.element[0].tagName?e.find(".the-modal .the-modal-container").html(n.element[0].innerHTML):(n.returnToOrigin=!0,"object"==typeof n.element?(n.element.after(m),n.$origin=n.element,e.find(".the-modal .the-modal-container").append(n.element)):(t=p(n.element),i=e.find(".the-modal .the-modal-container"),(n.$origin=t).after(m),i[0].appendChild(t[0]))),p.publish("browsingModal/centerModal/",{el:e}),p(".the-modal").addClass("populated")),p.publish("browsingModal/opened",{el:e,opt:n}),a(e,o),l(e,o)},onClose:function(o,e,t){n.hasOwnProperty("returnToOrigin")&&n.returnToOrigin&&n.hasOwnProperty("$origin")&&n.$origin&&p(".the-modal-placeholder").replaceWith(n.$origin),i(o,e,t),r(o,e,t),p(".the-modal").removeClass("opened populated with-iframe"),p.publish("browsingModal/closed",{el:o,options:e,close:t})},overlayClass:"themodal-overlay "+o,lockClass:"themodal-lock "+o,closeOnEsc:n.closeOnEsc,closeOnOverlayClick:n.closeOnOverlayClick})}app.tools.modal=function(o){(o=o||{}).width=h,o.height=h,p.publish("browsingModal/openMain/",o)},app.modal=app.tools.modal,app.closeModal=app.tools.closeModal=p.modal().close,p.wd.widget.prototype.modal=app.tools.modal,p.wd.widget.prototype.alert=function(o,e,t){e='<div class="alert '+("alert-"+(e===h?"warning":e))+'"><div class="message">'+o+"</div></div>";"true"==d.browsingModal||1==d.browsingModal?(t.width=h,t.height=h,t.html=e,p.publish("browsingModal/openMain/",t)):this.modal(p.extend({element:e},t))},p.wd.widget.prototype.error=function(o){p.wd.widget.prototype._opendialog(o)},p.wd.widget.prototype.confirm=function(o){p.wd.widget.prototype._opendialog(o)},p.wd.widget.prototype.success=function(o){p.wd.widget.prototype._opendialog(o)},p.wd.widget.prototype.warn=function(o){p.wd.widget.prototype._opendialog(o)},p.wd.widget.prototype.dialog=function(o){p.wd.widget.prototype._opendialog(o)},p.wd.widget.prototype._opendialog=function(o){var t=p(this.options.dialog.html);t.find(".message").html(o.message),p.each(o.buttons||this.options.dialog.buttons,function(){var o=function(){},e=("function"==typeof this.onclick&&(o=this.onclick),p('<button class="'+this["class"]+'">'+this.label+"</button>").click(function(){o(p.modal)}));t.find(".button-wrapper").append(e)}),o.width=h,o.height=h,o.html=t,p.publish("browsingModal/openMain/",o)},p(".the-modal .close").on("click",function(o){return p.modal().close(),!1}),p.subscribe("browsingModal/openDialog/",function(o,e){p.wd.widget.prototype._opendialog(e)}),p.subscribe("browsingModal/openMain/",function(o,e){p.extend(e,{modal:t}),n(e),setTimeout(function(){t.addClass("visible"),p.publish("browsingModal/centerModal/")},50)}),p.subscribe("browsingModal/updateMain/",function(o,e){p("#mainModal").removeAttr("style").parent().addClass(e.customClass),p("#mainModal .the-modal-container").hide().html(e.html).fadeIn()}),p.subscribe("browsingModal/openAux/",function(o,e){p.modal().close(),p.extend(e,{modal:i}),n(e)}),p.subscribe("browsingModal/centerModal/",function(o,e){var t=p(d),i=p(".the-modal"),n=p(".themodal-overlay"),a=i.find(".the-modal-container"),t=t.height(),a=a.outerHeight(),l={};n.removeClass("modal-oversized"),a<t&&"absolute"===i.css("position")?l={"margin-top":a/2*-1}:(l["margin-top"]=0,l.top="",n.addClass("modal-oversized")),i.css(l)}),p.subscribe("browsingModal/resizeModal/Height",function(o,e){e=e.height||0;p(".the-modal").css("max-height",e+"px")}),p.subscribe("browsingModal/resizeModal/resizeWidth",function(o,t){var i=0;p(".the-modal:visible").each(function(o,e){i=p(e).hasClass("with-iframe")?t.width||p("#iframe-modal").contents().find("html").width():t.width||"",p(e).css({"max-width":i+"px"})})}),p.subscribe("browsingModal/updateModal/",function(o,e){e!==h&&p(".the-modal:visible").css(e)}),p.subscribe("browsingModal/closeModal/",function(o,e){return p.modal().close(),!1})}}),p.extend(p.wd.BrowsingModal.prototype.options,{})}(jQuery,window,void document);
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Widgets/clean.google.analytics.v4/Scripts/wd.clean.google.analytics.v4.js*/
try{(function($, window, document, undefined) {
	function getBasketItems() {
		try {
			
			var _items = typeof EasyCheckout === 'undefined' ?  browsingContext.Common.Basket.Items : EasyCheckout.ModelData.Basket.Items
			return _items.map(item => {
				return {
					item_name: item.Name,
					item_id: item.ProductID,
					item_brand: item.BrandName,
					item_category: item.CategoryName,
					price: item.RetailPrice,
					quantity: item.Quantity
				};
			});			 
		} catch (e) {
			console.log(e);
		}
	}

	function _search(nameKey, myArray){
		for (let i=0; i < myArray.length; i++) {
			if (myArray[i].event === nameKey) {
				return i;
			}
		}
	}
	
	function subscribeToEvents() {
			
			/**
			 * add_to_cart
			 */
			$.subscribe('add_to_cart', function(e, {item_id, item_name ,value}) {
				
				try{
					window.dataLayer.push({ 
						event: "add_to_cart",						
						ecommerce: {
							currency: "BRL",
							value,
							items: [{
								item_id,
								item_name,
							}]
						}
					});
				

				}
				catch(e){
					console.error(e);
				}
				
			});
		
			$.subscribe('view_cart', function(e,Basket) {
				console.log(Basket)
				try{
					const items= Basket?.Items.map((item,index)=>{
						return{
							item_name: item.Name,
							item_id:  item.ProductID,
							price: item.RetailPrice,
							quantity: item.Quantity,
							item_brand: item.BrandName,
							index : index+1,
						}
					})
					window.dataLayer.push({
						event: "view_cart",
						ecommerce: {
							currency: 'BRL',
							value: Basket.Total,
							items
							}
					});

				}
				catch(e){
					console.error(e);
				}
				
			});
		
			
			/**
			 * remove_from_cart
			 */
			$.subscribe('checkout/basket/remove/item', function(e, obj) {

					try{
						window.dataLayer.push({ 
							event: "remove_from_cart",
							ecommerce: {
								currency: "BRL",
								value: obj.product.RetailPrice.toFixed(2),
								items: [{
									item_id: obj.product.ProductID.toString(),
									item_name: obj.product.Name
								}]
							}
						});
					}
					catch(e){
						console.error(e);
					}
			});
			
			if (typeof(ko) != 'undefined') {
				/**
				 * purchase
				 */
				ko.postbox.subscribe('checkout/payment/submit',function(args){
					
					if(args && args.hasOwnProperty('Response')){
						
						try{

							const response = args.Response;
							if (response.IsValid) {
								let coupon = '';
								if (EasyCheckout.ModelData.Basket.Coupons.length) {
									coupon = EasyCheckout.ModelData.Basket.Coupons.map(function(c) {
										return c.Code;
									}).join(';');
								}
		
								$.ajax({
									url: browsingContext.Common.Urls.BaseUrl + 'checkout/confirmacao.json',
									dataType: 'json'
								}).done(function(resp) {							
									var discountTotal = 0;
									if (resp.Order.PaymentTaxAmountType == 'Decrease') {
										discountTotal = parseFloat(resp.Order.PaymentTaxAmount) + parseFloat(resp.Order.DiscountAmount);
									} else {
										discountTotal = parseFloat(resp.Order.DiscountAmount);
									}
									window.dataLayer.push({
										event: "purchase",
										ecommerce: {
											transaction_id: response.Custom['PlaceOrder.OrderNumber'],
											value: Number(EasyCheckout.ModelData.Basket.Total.toFixed(2) - (discountTotal || parseFloat(0)).toFixed(2)),
											shipping: EasyCheckout.ModelData.Basket.DeliveryAmount.toFixed(2),
											currency: "BRL",
											coupon,
											items: getBasketItems()
										}
									});
								if(browsingContext.Common.WebSite.WebSiteID==1){
									ScarabQueue.push(['purchase', {
										orderId: response.Custom['PlaceOrder.OrderNumber'],
										items:  browsingContext.Common.Basket.Items.map((item,index) => {
												if(index==0 && EasyCheckout.ModelData.Basket.DeliveryAmount!=0){
													item.RetailPrice += (EasyCheckout.ModelData.Basket.DeliveryAmount/item.Quantity);
												}
												return {
													item: item.SKU,
													price: item.RetailPrice,
													quantity: item.Quantity
												}
											}),
										value:  Number(resp.Order.Total.toFixed(2)),
									}]);
									ScarabQueue.push(['go']);
								}
								});
							}

						}
						catch(e){
							console.error(e);
						}
					}
				});
				/**
				 * add_shipping_info
				 */
				ko.postbox.subscribe('delivery/selected/check', function(e, obj) {
					
					try{

						window.dataLayer.push({ 
							event: "add_shipping_info",
							ecommerce: {
								currency: "BRL",
								value: EasyCheckout.ModelData.Basket.DeliveryAmount.toFixed(2),
								items: getBasketItems()
							}
						});

					}
					catch(e){
						console.error(e);
					}

				});
				
				/**
				 * add_payment_info
				 */
				ko.postbox.subscribe('hashchange/payment', function(hash) {
					
					try{

						var paymentType =  hash[1] == undefined ? "" : hash[1]

						window.dataLayer.push({ 
							event: "add_payment_info",
							ecommerce: {
								currency: "BRL",
								payment_type: paymentType,
								value: EasyCheckout.ModelData.Basket.Total.toFixed(2),
								items: getBasketItems()
							}
						});	

					}
					catch(e){
						console.error(e);
					}
								
				});		
			}
				
			/**
			 * add_to_wishlist
			 */
			var _myTimeout 
			document.addEventListener('click',(e) =>
			{
				
				try{

					if (e.target.offsetParent != null && e.target.offsetParent.id == 'add-wishlist'){
					
						var _result = _search("add_to_wishlist",window.dataLayer)
						var _object = { 
							event: "add_to_wishlist",
							ecommerce: {
								currency: "BRL",
								value:  product.RetailPrice.toFixed(2),
								items: [{
									item_id: product.ProductID.toString(),
									item_name: product.Name,
								}]
							}
						}
	
						if (_result != undefined){
							window.dataLayer[_result] = _object
						}else{
							window.dataLayer.push(_object);
						}					
					}
					
					/*if ((e.target.offsetParent != null && e.target.offsetParent.className.includes('wd-product-line-wishlist') && e.target.closest('.wd-product-line')) != null && e.target.className.includes('js-btn dont-animate added')){
						var _element = e.target.closest('.wd-product-line')					
	
						var _result = _search("add_to_wishlist",window.dataLayer)
						var _object = { 
							event: "add_to_wishlist",
							ecommerce: {
								currency: "BRL",
								value:  _element.getElementsByClassName('sale-price')[0].innerText.replace('R$ ',''),
								items: [{
									item_id: _element.querySelectorAll('[data-pid]')[0].getAttribute('data-pid').toString(),
									item_name: _element.getElementsByClassName('name')[0].innerText,
								}]
							}
						}
	
						if (_result != undefined){
							window.dataLayer[_result] = _object
						}else{
							window.dataLayer.push(_object);
						}	
					}
					*/
	
					if (e.target.offsetParent != null && e.target.offsetParent.className.includes('delivery')){
						setTimeout(function(){
							_add_shipping_info_basket()
						}, 1500);
					}	

				}
				catch(e){
					console.error(e);
				}

			});
			
			/**
			 * add_shipping_info in basket
			 */
			function _add_shipping_info_basket(){

				try{

					
					if (typeof $self !== 'undefined'){
						$self.element.find('.js-delivery-choice input:radio').each(function() {
					
							var val = $('#SelectedDeliveryOptionID').val();
							if (val == $(this).val()) {	
									
								var _result = _search("add_shipping_info",window.dataLayer)
								var _object = { 
									event: "add_shipping_info",
									ecommerce: {
										currency: "BRL",
										value: browsingContext.Common.Basket.SelectedDeliveryOption.Amount.toFixed(2),
										items: getBasketItems()
									}
								}

								if (_result != undefined){
									window.dataLayer[_result] = _object
								}else{
									window.dataLayer.push(_object);
								}			

							}
						});
					}

				}
				catch(e){
					console.error(e);
				}
				
			}
			
			_add_shipping_info_basket();
	}

	function init() {
		subscribeToEvents();
	}

	$(document).ready(init);
}(jQuery, window, document));

}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Widgets/clean.google.tag.manager/Scripts/wd.clean.google.tag.manager.js*/
try{var pageStep;
var GTM = {
	pageView: function () {
		var pageType = (location.hash || '').replace('#', ''),
			pageCategory = '';

		switch (pageType) {
			case 'signin':
				pageCategory = 'signin';
				pageStep = 1;
				break;
			case 'signup':
				pageCategory = 'signup';
				pageStep = 1;
				break;
			case 'delivery':
				pageCategory = 'delivery';
				pageStep = 2;
				break;
			case 'payment':
				pageCategory = 'payment';
				pageStep = 3;
				break;
			case 'confirmation':
				pageCategory = 'confirmation';
				pageStep = 4;
				break;
			default:
				pageCategory = 'signin';
				pageStep = 1;
		}

		if (pageCategory.length) {
			dataLayer.push({
				'pageCategory': pageCategory,
				'visitorType': 'high-value',
				'event': 'checkout',
				'ecommerce': {
					'currencyCode': 'BRL',
					'checkout': {
						'actionField': { 'step': pageStep },
						'products': GTM.getBasketItems()
					}
				}
			});
		}
	},
	getBasketItems: function () {
		var items = [];
		if (browsingContext.Common.Basket.Items.length) {
			$.each(browsingContext.Common.Basket.Items, function (k, i) {
				items.push({
					'id': i.ProductID,
					'sku': i.SKU,
					'name': app.tools.htmlDecode(i.Name),
					'price': i.RetailPrice,
					'category': app.tools.htmlDecode(i.CategoryName),
					'brand': i.BrandName,
					'variant': '',
					'quantity': i.Quantity
				});
			});
		}
		return items;
	},
	getProduct: function () {
		return {
			'id': _dataGTM.id,
			'name': app.tools.htmlDecode(_dataGTM.name),
			'price': _dataGTM.price,
			'category': app.tools.htmlDecode(_dataGTM.category),
			'brand': _dataGTM.brand
		};
	},
	insertScript: function (code) {
		(function (w, d, s, l, i) {
			w[l] = w[l] || [];
			w[l].push({
				'gtm.start': new Date().getTime(),
				event: 'gtm.js'
			});
			var f = d.getElementsByTagName(s)[0]
				, j = d.createElement(s)
				, dl = l != 'dataLayer' ? '&l=' + l : '';
			j.async = true;
			//j.defer = true;
			j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
			f.parentNode.insertBefore(j, f);
		})(window, document, 'script', 'dataLayer', code);
	}
};
; (function ($, window, document, undefined) {
	try {
		var codes = $('.wd-google-tag-manager').data('codes').replace(';', ',').split(',');
		var bodyClass = $('body').attr('class'),
			pageType,
			pageCategory,
			listType;

		// home
		if (!!~bodyClass.indexOf('HomeRoute')) {
			pageCategory = 'home';
			listType = 'Página inicial';
		}

		// produto
		else if (!!~bodyClass.indexOf('context-product')) {
			pageCategory = 'product';
			listType = 'Detalhe do produto';
		}

		// categoria
		else if (!!~bodyClass.indexOf('context-category')) {
			pageCategory = 'category';
			listType = 'Categoria';
		}

		// carrinho
		else if (!!~bodyClass.indexOf('BasketIndexRoute')) {
			pageCategory = 'cart';
			listType = 'Carrinho';
		}

		// checkout
		else if (!!~bodyClass.indexOf('EasyCheckoutStep')) {
			pageCategory = 'checkout';
			listType = 'Checkout';
		}

		dataLayer.push({
			'pageCategory': pageCategory,
			'visitorType': 'high-value',
			'ecommerce': {
				'currencyCode': 'BRL'
			}
		});

		if (pageCategory == "product") {
			dataLayer.push({
				'event': 'productDetail',
				'ecommerce': {
					'detail': {
						'actionField': {
							'list': listType
						},
						'products': [GTM.getProduct()]
					}
				}
			});
		} else if (pageCategory == "cart") {
			var items = GTM.getBasketItems();
			dataLayer.push({
				'event': 'addToCart',
				'ecommerce': {
					'add': {
						'products': items
					}
				}
			});

			$.subscribe('checkout/basket/remove/item', function (e, args) {
				if (!args || !args.product)
					return;

				var product = args.product;

				dataLayer.push({
					'event': 'removeFromCart',
					'ecommerce': {
						'remove': {
							'products': [{
								'id': product.ProductID,
								'name': app.tools.htmlDecode(product.Name),
								'price': product.RetailPrice,
								'category': app.tools.htmlDecode(product.CategoryName),
								'brand': product.BrandName,
								'variant': '',
								'quantity': product.Quantity
							}]
						}
					}
				});
			});

		} else if (pageCategory == "checkout") {
			var basket = EasyCheckout.ModelData.Basket;

			window.onload = function () {
				$(window).on('hashchange', GTM.pageView);
			};

			GTM.pageView();

			if (typeof(ko) != undefined) {
				ko.postbox.subscribe('checkout/setDelivery', function (args) {
					if (args && args.hasOwnProperty('deliveryOption')) {
						dataLayer.push({
							'event': 'checkout',
							'ecommerce': {
								'checkout': {
									'actionField': { 'step': pageStep, 'option': args.deliveryOption.Name },
									'products': GTM.getBasketItems()
								}
							}
						});
					}
				});

				ko.postbox.subscribe('checkout/payment/setType', function (args) {
					if (args && args.hasOwnProperty('paymentMethod')) {
						dataLayer.push({
							'event': 'checkout',
							'ecommerce': {
								'checkout': {
									'actionField': { 'step': pageStep, 'option': args.paymentMethod.Name },
									'products': GTM.getBasketItems()
								}
							}
						});
					}
				});

				ko.postbox.subscribe('checkout/data/update', function (args) {
					if (args && args.hasOwnProperty('Basket')) {
						basket.DeliveryAmount = args.Basket.DeliveryAmount;
						basket.Total = args.Basket.Total;
					}
				});

				ko.postbox.subscribe('checkout/payment/submit', function (args) {
					if (args && args.hasOwnProperty('Response')) {
						var response = args.Response;
						if (response.IsValid) {
							var cupom;
							if (basket.Coupons.length) {
								cupom = basket.Coupons[0].Code;
							}

							$.ajax({
								url: browsingContext.Common.Urls.BaseUrl + 'checkout/confirmacao.json'
							}).done(function (resp) {

								var discountTotal = 0;
								if (resp.Order.PaymentTaxAmountType == 'Decrease') {
									discountTotal = parseFloat(resp.Order.PaymentTaxAmount) + parseFloat(resp.Order.DiscountAmount);
								} else {
									discountTotal = parseFloat(resp.Order.DiscountAmount);
								}

								dataLayer.push({
									'event': 'purchase',
									'ecommerce': {
										'purchase': {
											'actionField': {
												'id': response.Custom['PlaceOrder.OrderNumber'],
												'revenue': (basket.Total || parseFloat(0)).toFixed(2),
												'tax': 0,
												'shipping': (basket.DeliveryAmount || parseFloat(0)).toFixed(2),
												'coupon': cupom,
												'transactionDiscount': (discountTotal || parseFloat(0)).toFixed(2)
											},
											'products': GTM.getBasketItems()
										}
									}
								});

								dataLayer.push({
									'transactionId': response.Custom['PlaceOrder.OrderNumber'],
									'transactionAffiliation': browsingContext.Common.Config.General.Store.Name,
									'transactionTotal': (basket.Total || parseFloat(0)).toFixed(2),
									'transactionTax': 0,
									'transactionShipping': (basket.DeliveryAmount || parseFloat(0)).toFixed(2),
									'transactionProducts': GTM.getBasketItems(),
									'transactionDiscount': (discountTotal || parseFloat(0)).toFixed(2)
								});
							});

						}
					}
				});
			}
		}
	
		if (codes.length) {
			setTimeout(() => {
				var codes = $('.wd-google-tag-manager').data('codes').replace(';', ',').split(',');
				codes.forEach(function (code) {
					GTM.insertScript(code);
				});
			}, 3000);
		}

	} catch (e) {

	}
	
})(jQuery, window, document);

}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
