/*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.join/Scripts/wd.product.join.js*/
try{!function(n,i,o){n.widget("wd.ProductJoin",n.wd.widget,{_create:function(){var e;this.getContext()("select").on("change",function(){n(this).val()&&(o.location.href=n(this).val())}),n(".wd-product-line .wd-product-join.hover").length&&n(o).on("hover",".wd-product-line",function(o){var t=n(this);return"mouseenter"==o.type?(e=i.setTimeout(function(){t.find(".wd-product-join.hover").show()},250),!1):"mouseleave"==o.type?(i.clearTimeout(e),t.find(".wd-product-join.hover").hide(),!1):void 0})}}),n.extend(n.wd.ProductJoin.prototype.options,{})}(jQuery,window,document);
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Widgets/clean.product.associations/Scripts/wd.clean.product.associations.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/product.reviews/Scripts/wd.product.reviews.js*/
try{function clearReviewFields(e){try{var t=getWidgetId();e?resetCaptchaField():($("textarea#review-reviewbody-"+t).val(""),$("input#review-title-"+t).val(""),resetCaptchaField(t))}catch(a){console.error("Erro ao limpar campos do review:",a)}}function reloadCaptcha(){var e=$(".wd-product-reviews .captcha-box"),t=e.find("img"),a=t.width(),i=t.height(),r=t.attr("id"),o=(t.attr("data-src")||t.attr("src")).split("?")[0]+"?_="+Math.floor(1e6*Math.random()),r=$("<img>").attr({id:r,width:a,height:i,src:o,"data-src":o});t.remove(),e.append(r),resetCaptchaField(null)}function resetCaptchaField(e){try{$("input#review-catptchatext-"+(e||getWidgetId())).val("")}catch(t){console.error("Erro ao resetar campo do captcha:",t)}}function getWidgetId(){var e=$("[name='Title']").attr("id").split("-");return e[e.length-1]}$.widget("wd.ProductReviews",$.wd.widget,{_create:function(){var r=this,o=this.getContext(),e=$(".wd-list-reviews-itens").length?$.parseJSON($(".wd-list-reviews-itens").attr("data-options")):{},t=e.isList,i=browsingContext.Common;window.ReviewCount=e.ReviewCount||0,window.PageSize=e.PageSize||3,window.PageIndex=e.PageIndex||0,window.data_paginate=e.data_paginate,window.TextPagination=e.TextPagination,window.productId=e.productId||browsingContext.Page.Product.ProductID,window.showMail=e.showMail||!1,r.element.find(".review-create").click(function(e){e.preventDefault();e=i.Config.Platform.Product;e.EnableReviewOnlyForBuyers||e.EnableUniqueReview?r._checkReviewPermission():r.publish("/product/review/create",{widget:r.element})}),$.subscribe("productReview/reloadCaptcha",function(){var e=$(".wd-product-reviews .reload-captcha").parents(".captcha"),t=e.find('img[id^="review-catptchaimg-"]'),a=t.attr("data-src"),i=~a.indexOf("?")?a.slice(0,a.indexOf("?")):a,r=new Date,i=i+"?_="+Math.floor(Math.random()*r.getTime()),r=t.clone();r.attr("src",i+2),r.attr("data-src",a),r.on("load",function(){e.removeClass("loading")}),e.addClass("loading"),t.after(r).remove()}),$(".reload-captcha",r.element).off("click").on("click",function(){reloadCaptcha(),console.log("Reloading captcha...")}),$(r.element).delegate(".btn-thumbs-up","click",function(e){var t,a;i.Shopper.IsAuthenticated?(t=$(this).data("review-id"),a=$('.btn-thumbs-down[data-review-id="'+t+'"]'),r._saveProductReview(this,a,t,1)):r._showModalForUnauthenticatedUser()}),$(r.element).delegate(".btn-thumbs-down","click",function(e){var t,a;browsingContext.Common.Shopper.IsAuthenticated?(t=$(this).data("review-id"),a=$('.btn-thumbs-up[data-review-id="'+t+'"]'),r._saveProductReview(this,a,t,2)):r._showModalForUnauthenticatedUser()}),1==t&&(r.paginate(r),r.element.on("click",".wd-review-paginate a",function(){r.changePage(this,r)})),r.subscribe("/product/review/info",function(e,t){e.preventDefault();e=$(".wd-product-reviews-info");e.find(".product-reviews-info-content").html(t.message),r.modal({element:$(e.get(0)).find("div.wd-widget"),"class":"modal-wd-product-info",className:"modal-wd-product-info",width:"auto",height:"auto"})}),r.subscribe("/product/review/create",function(e,t){e.preventDefault();var e=$(".wd-product-reviews-create",r.element),a=e.attr("style"),i=(e.css({position:"absolute",visibility:"hidden",display:"block"}),e.height());e.attr("style",a||""),e.length&&((a=$('img[id^="review-catptchaimg-"]',r.element)).attr("src",a.attr("data-src")),r.modal({element:e,"class":"modal-wd-product-reviews",className:"modal-wd-product-reviews",width:o(".modalWidth").val(),height:i||"auto",onComplete:function(e){var t=e.find("form"),a=(r.validate(t,{errorPlacement:$.wd.ProductReviews.prototype.options.validate.errorFlyout,submitHandler:function(e){return $(e).find("button:submit").attr("disabled",!0),r._submit(e),!1}}),window.sessionStorage&&"true"===sessionStorage.getItem("reviewSubmitted")&&(reloadCaptcha(),sessionStorage.setItem("reviewSubmitted","false")),getWidgetId());$.ajax({type:"POST",url:"Login/GetDataUser/",data:"","async":!1,success:function(e){e.logged&&($("input#review-name-"+a).val(e.nameUser),$("input#review-email-"+a).val(e.emailUser))}}),$(".rating label",e).hover(r.overRating,r.outRating).click(r.setRating),$(".button-wrapper",r.element).click(function(e){e.preventDefault(),t=r.element.find("form"),r._submit(t)}),$(".slider").find(".range-value").val(0).css("left","0%"),$(".slider").each(function(e,t){t=$(t).data("steps");$(".slider").slider({value:0,min:0,max:100,step:t,slide:function(e,t){$(e.target).attr("data-range",t.value),$(e.target).closest(".sliderWrapper").find(".range-value").val(t.value).css("left",t.value+"%")}})})}}))}),1<=window.location.search.indexOf("openAvailabilityModal")&&$(".review-create").first().click()},_checkReviewPermission:function(){var e,t,a=this;function i(e){e&&e.IsValid?a.publish("/product/review/create",{widget:a.element}):(e=e.Errors&&e.Errors.length?e.Errors[0].ErrorMessage:"Você precisa comprar este produto para comentar",a.publish("/product/review/info",{widget:a.element,message:e}))}browsingContext.Common.Shopper.IsAuthenticated?browsingContext.Custom.wdReviews&&browsingContext.Custom.wdReviews.ValidateCustomerReviewPermit?i(browsingContext.Custom.wdReviews.ValidateCustomerReviewPermit):(t=browsingContext.Page.Product.ProductID,e=browsingContext.Common.Customer.CustomerID,t=browsingContext.Common.Urls.BaseUrl+"shopping/review/ValidateCustomerReviewPermit/"+t,$.ajax({type:"POST",url:t,data:{customerID:e},success:function(e){browsingContext.Custom.wdReviews={ValidateCustomerReviewPermit:e},i(browsingContext.Custom.wdReviews.ValidateCustomerReviewPermit)}})):a.publish("/product/review/info",{widget:a.element,message:"Você precisa fazer o login continuar."})},changePage:function(e,t){var a=t.getContext(),t=e?$(e):null,i=a(".load");data_paginate=t?$(e).attr("data-paginate"):0,a(" .wd-review-paginate .page-selected").removeClass("page-selected"),t&&t.addClass("page-selected"),i.show(),$.ajax({type:"POST",url:browsingContext.Common.Urls.BaseUrl+"widget/product_reviews?ProductID="+productId+"&PageIndex="+data_paginate+"&PageSize="+PageSize+"&Template=wd.product.reviews.paginate.template",success:function(e){i.hide(),a(".wd-list-reviews-itens").html(e)}})},paginate:function(e){var t=Math.ceil(ReviewCount/PageSize),a="",i="";if(1<=(t=Math.round(t))){for(var i="<span>"+TextPagination+"</span><ul>",r=1;r<=t;r++)a="",i+="<li><a "+(a=data_paginate==r-1?'class="page-selected dont-animate"':a)+' href="javascript:void(0)" class="dont-animate" data-paginate="'+(r-1)+'">'+r+"</a></li>";i+="</ul>"}e.element.find(".wd-review-paginate").append(i)},setRating:function(){$(this).siblings().find(":checked").removeAttr("checked"),$("input[type=radio]",this).attr("checked","checked"),$(this).parent().attr("class","rating").addClass("selected-"+$(this).attr("class"))},overRating:function(){$(this).parent().addClass($(this).attr("class"))},outRating:function(){$(this).parent().removeClass($(this).attr("class"))},_showModalForUnauthenticatedUser:function(){var e=browsingContext.Common.Urls.BaseUrl;app.modal({html:'<div><p>Você precisa estar autenticado</p><div class="button-wrapper"><a class="btn btn-wide" href="'+e+"Login/?Url="+window.location.href+'">Clique aqui para ser redirecionado.</a></div></div>',width:"auto",height:210,className:"open-modal-review"})},_saveProductReview:function(t,a,i,e){var r=this,o=(r._toggleLoadingFeedback(i),browsingContext.Common.Urls.BaseUrl+"shopping/review/AddProductReviewReaction");$.ajax({type:"POST",url:o,data:{reviewID:i,productID:browsingContext.Page.Product.ProductID,reaction:e},success:function(e){e.IsValid&&(r._showSuccessMessageReview(i),r._disableButton(t),r._disableButton(a),r._addVotedClass(t),r._incrementButtonVotes(t),null!=(e=$('.wd-review-thumb-signal[data-review-id="1"]')).data("customer-vote")&&r._decrementButtonVotes(a),e.data("customer-vote",3)),r._toggleLoadingFeedback(i)},error:function(e){r._toggleLoadingFeedback(i),r._hideSuccessMessageReview(i)}})},_toggleLoadingFeedback:function(e){var t=$('.loading-review[data-review-id="'+e+'"]');t.is(":visible")?t.hide(0):t.show(0),$('.btn-thumbs-up[data-review-id="'+e+'"],.btn-thumbs-down[data-review-id="'+e+'"]').each(function(){$(this).is(":visible")?$(this).hide(0):$(this).show(0)})},_showSuccessMessageReview:function(e){$('.success-message-review[data-review-id="'+e+'"]').show(0)},_hideSuccessMessageReview:function(e){$('.success-message-review[data-review-id="'+e+'"]').hide(0)},_enableButton:function(e){$(e).prop("disabled",!1)},_disableButton:function(e){$(e).prop("disabled",!0)},_addVotedClass:function(e){$(e).addClass("voted")},_incrementButtonVotes:function(e){var t=$(e).data("votes"),a=t+1;$(e).data("votes",a),$(e).html($(e).html().replace(t,a))},_decrementButtonVotes:function(e){var t=$(e).data("votes"),a=0==t?0:t-1;$(e).data("votes",a),$(e).html($(e).html().replace(t,a))},_submit:function(e){var t=this,a=$(e);t.ajax({type:"POST",dataType:"json",url:a.attr("action"),data:a.serialize(),success:function(e){e.IsValid?(clearReviewFields(!1),t._handleSuccess(e)):(clearReviewFields(!0),t._handleError(e)),window.sessionStorage&&sessionStorage.setItem("reviewSubmitted","true")},error:function(e){},complete:function(){$(e).find("button:submit").attr("disabled",!1)}})},_handleSuccess:function(e){this.alert(this.options.messages.success,"success",{"class":"wd-product-reviews-create-response",className:"wd-product-reviews-create-response-modal"})},_handleError:function(e){var t=this,a=!1,i=t.options.messages.error;e.Errors.length&&("CaptchaText"==(e=e.Errors)[0].Key&&(a=!0),i=e[0].ErrorMessage),t.alert(i,"error",{"class":"wd-product-reviews-create-response",className:"wd-product-reviews-create-response-modal",onClose:function(){a&&$('input[name="CaptchaText"]').addClass("error"),t.publish("/product/review/create",{widget:t.element})}})},_lazyReload:function(){var t=$(window),a=this,i=this.getContext();t.bind("scroll.ProductReview",_.throttle(function(){var e=t.scrollTop()+t.height()+100;i().offset().top<e&&(t.unbind("scroll.ProductReview"),a.changePage(null,a))},280)).trigger("scroll")}}),$.extend($.wd.ProductReviews.prototype.options,{messages:{success:"Seu review foi enviado com sucesso!",error:"Ocorreram erros no envio de seu review!"}}),$.extend($.wd.ProductReviews.prototype.options.validate,{rules:{Name:{required:!0},Email:{required:!0,email:!0},Title:{required:!0},ReviewBody:{required:!0}}});
}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/Scripts/wd.clean.google.analytics.js*/
try{// https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce
(function(i, s, o, g, r, a, m) {
	if (s.getElementById('ez-ga') || window.ga) {
		return false;
	}
	i['GoogleAnalyticsObject'] = r;
	i[r] = i[r] || function() {
			(i[r].q = i[r].q || []).push(arguments);
		},
		i[r].l = 1 * new Date();
	a = s.createElement(o),
	m = s.getElementsByTagName(o)[0];
	a.async = 1;
	a.src = g;
	a.id = 'ez-ga';
	m.parentNode.insertBefore(a, m);
	i['GaAddedProductsImpression'] = [];
	i['GaTrackers'] = [];
	i['GaTrackerCount'] = 0;

	// debugger;
	a.onerror = function() {
		a.src = '';
		a.src = g;
		a.onerror = function() {};
	};

	i['GaTryInit'] = function() {};
	a.onload = function() {
		// debugger;
		i['EzGaCfg'] = i['EzGaCfg'] || {};
		i['EzGaCfg']['ready'] = true;

		GaTryInit((window.EzGaCfg) || false);
	};

})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ezga');

$(function() {
	var ezGaTracking = null;
	/* valida execução */
	if (window['EzGaReady'] && window['EzGaReady'] === true) {
		return false;
	}

	window['EzGaReady'] = true;

	var $body = $('body'),
		bodyClass = $body.attr('class'),
		EZ_UA_CODE = 'UA-2269208-2',
		retryInitCount = 0;

	/* hack old browsers */
	if (!Object.keys) {
		Object.keys = function(obj) {
			var keys = [],
				k;
			if (typeof obj === 'object') {
				for (k in obj) {
					if (Object.prototype.hasOwnProperty.call(obj, k)) {
						keys.push(k);
					}
				}
			}
			return keys;
		};
	}

	var tryInit = function(AnalyticsConfiguration) {
		if(/(googlebot|google\.com|google\-site\-verification|google\-xrawler|feedfetcher\-google|adsbot\-google|apis\-google|mediapartners\-google|yahoo|bingpreview|bingbot|msnbot|facebook|whatsapp|twitter|pinterest|altavista|alta\-vista|ezbot|nagios|pingdom|woobot|uptimerobot|pagarme|pagosonline|chaordic|intelipost|outlook|performa\.ai)/gi.test(navigator.userAgent)){
			return;
		}

		if (typeof AnalyticsConfiguration != 'object') {
			retryInitCount++;
			if (retryInitCount < 4) {
				setTimeout(tryInit, 600);
			} else {
				return false;
			}
		}

		//console.log('AnalyticsConfiguration', AnalyticsConfiguration);

		var GaCode = AnalyticsConfiguration.UAS || '';
		var GaType = AnalyticsConfiguration.IntegrationType || 1;
		var GaDebug = AnalyticsConfiguration.Debugging || !1;
		var GaEZCode = EZ_UA_CODE; // EZ Analytics

		if (GaCode == '') {
			GaCode = GaEZCode;
		} else {
			GaCode = GaCode + ',' + GaEZCode;
		}

		window['GaDebug'] = GaDebug;

		window.onpageready(function(){
			//GaJsTracker(GaCode);
			AnalyticsJsTracker(GaCode);
		});

	};

	if(browsingContext
		&& browsingContext.Common
		&& browsingContext.Common.ready
		&& browsingContext.Common.WebSite.Type === 'Mobile'
		&& browsingContext.Common.Config.General.Store.LoadAsyncAssets
		&& !window.EzGaCfg.ready)
	{
		// debugger;
		window.GaTryInit = tryInit;
		// mata a execução para garantir que ocorra apenas uma vez
		return;
	}

	tryInit((window.EzGaCfg) || false);

	function AnalyticsJsTracker(GaCodes) {

		var _GaCodes = GaCodes.replace(' ', '').split(',');
		var Codes = [];
		var registeredCodes = [];

		try {
			// debugger;
			if (window.ga && window.ga.getAll) {
				_.each(window.ga.getAll(), function(ua) {
					var _ua = ua.get('trackingId');
					if(_ua) {
						registeredCodes.push(_ua);
					}
				});
			}

			if (window.ezga && window.ezga.getAll) {
				_.each(window.ezga.getAll(), function(ua) {
					var _ua = ua.get('trackingId');
					if(_ua) {
						registeredCodes.push(_ua);
					}
				});
			}
		} catch(er) {
			// console.error(er);
		}

		for (var i = 0; i < _GaCodes.length; i++) {
			if ((_GaCodes[i] || '').substr(0, 2).toUpperCase() === 'UA'
				&& $.inArray(_GaCodes[i], Codes) === -1
				&& $.inArray(_GaCodes[i], registeredCodes) === -1
			) {
				Codes.push(_GaCodes[i]);
			}
		}

		if (!Codes.length) {
			tryInit(window.EzGaCfg);
			return false;
		}

		var isEzUA = function (trackerName) {
			if (!ezga.hasOwnProperty('getByName')) {
				return ezGaTracking === trackerName;
			}

			var tracker = ezga.getByName(trackerName.replace('.',''));
			if(tracker){
				return ( tracker.get('trackingId') == EZ_UA_CODE );
			}

			return false;
		};

		var bodyId = (document.body && document.body.id || '').replace('page-', '');
		//var referer				= ($('[name="http-referer"]').val() || '').replace(cfg.Url, '');
		var referer = '';
		var productsListPages = ['default', 'produtos-secoes', 'produtos-pesquisa', 'produtos', 'carrinho'];

		//console.log('antes dos trackers - Codes', Codes);

		for (var i = 0; i < Codes.length; i++) {
			Async(function(){

				window['GaTrackerCount'] = window['GaTrackerCount'] + 1;
				var trackerName = 'tracker' + window['GaTrackerCount'] + '.';
				var GaCode = Codes[i];

				//console.log('GaCode', GaCode);
				
				if(typeof GaTrackers !== 'undefined') {
					GaTrackers.push(trackerName);
				}

				// cria rastreamento
				var objCreate = {
					'siteSpeedSampleRate':50,
					'allowLinker': true,
					'name': trackerName.substr(0, trackerName.length - 1)
				};
				//if(GaCode == EZ_UA_CODE){
				//	objCreate.sampleRate = 50;
				//}
				if (EzGaCfg.Shopper.IsAuthenticated) {
					// deve ser string conforme documentação : https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#user
					objCreate.userId = browsingContext.Common.Customer.CustomerID + '';
				}

				ezga('create', GaCode, 'auto', objCreate);
				if (GaCode == EZ_UA_CODE) {
					ezGaTracking = trackerName;
					ezga(trackerName + 'set', 'allowAdFeatures', false);
					ezga(trackerName + 'set', 'dimension1', EzGaCfg.Config.Store.Name);
					ezga(trackerName + 'set', 'dimension2', browsingContext.Common.Basket.BasketID + "");
					ezga(trackerName + 'set', 'page', 		(location.host || location.hostname ).substring(location.hostname.indexOf('.')+1));
					ezga(trackerName + 'set', 'title', 		(findPageType() || location.pathname || '') );
				}
				EzLog('Tracker ' + (trackerName.length ? trackerName : 'default') + ' criado com código ' + GaCode, trackerName);

				// tracker multiples domains.
				ezga(trackerName + 'require', 'linker');
				//ezga(trackerName + 'linker:autoLink', [cfg.DomainName, 'ssl.'+cfg.DomainName, 'ezcommerce.com.br', 'ssl.ezcommerce.com.br'], false, true);

				// carrega ec.js
				ezga(trackerName + 'require', 'ec');

				// Recursos Gráficos
				ezga(trackerName + 'require', 'displayfeatures');

				// força SSL e envio por beacon
				ezga(trackerName + 'set', 'transport', 'beacon');
				ezga(trackerName + 'set', 'forceSSL', true);

				// define a moeda para BRL
				ezga(trackerName + 'set', '&cu', 'BRL');

				// envia pageview e evento para monitoramento realtime
				ezga(trackerName + 'send', 'pageview');
				EzLog('Pageview enviado!', trackerName);

				///////////////// DETALHE DO PRODUTO
				if (!!~bodyClass.indexOf('context-product') && EzGaCfg.hasOwnProperty('ProductDetail')) {

					if(!isEzUA(trackerName) && GaCode!=EZ_UA_CODE){ // nao trackear visualizacao de produtos para DCG

						var product = EzGaCfg.ProductDetail;

						var objProduct = {
							'id': product.id,
							'name': app.tools.htmlDecode(product.name),
							'category': app.tools.htmlDecode(product.category),
							'brand': app.tools.htmlDecode(product.brand),
							'price': parseFloat(product.price).toFixed(2),
							'list': 'Detalhe do produto ' + app.tools.htmlDecode(product.name)
						};

						ezga(trackerName + 'ec:addProduct', objProduct);
						ezga(trackerName + 'ec:setAction', 'detail');
						ezga(trackerName + 'send', 'event', 'Produto', 'Produto visualizado', 'Detalhes do produto visualizado');

						EzLog('Detalhes do produto ' + product.id + ' enviado.\n  ' + JSON.stringify(objProduct), trackerName);

					}
				}

				///////////////// CARRINHO
				if (!!~bodyClass.indexOf('BasketIndexRoute') && EzGaCfg.hasOwnProperty('Basket')) {
					window.GatrackCart = function(trackerName) {

						if (!$('.wd-checkout-basket').length) {
							return;
						}

						var basketItens = EzGaCfg.Basket;

						if (basketItens.length == 0) {
							setTimeout('window.GatrackCart("' + trackerName + '")', 100);
							return;
						}

						var i = 0,
							strProducts = '';

						for (var c in basketItens) {
							//var cartItem;
							//eval('cartItem = cart.itens.'+item);
							var item = basketItens[c];

							var id = item.id || '',
								name = item.name || '',
								price = item.price || '',
								category = item.category || '',
								brand = item.brand || '',
								quantity = item.quantity || 1;
							var objProduct = {
								'id': id,
								'name': app.tools.htmlDecode(name),
								'category': app.tools.htmlDecode(category),
								'brand': app.tools.htmlDecode(brand),
								'price': price,
								'quantity': quantity,
								'list': 'Carrinho de compras'
							};
							strProducts += JSON.stringify(objProduct) + '\n  ';
							ezga(trackerName + 'ec:addProduct', objProduct);
							i++;

						}

						if (i > 0) {

							EzLog('Carrinho enviado com ' + i + ' produtos.\n  ' + strProducts, trackerName);

							ezga(trackerName + 'ec:setAction', 'add');
							ezga(trackerName + 'send', 'event', 'Carrinho', 'Carrinho visualizado', 'Produtos adicionados e visualizados no carrinho');

						}

					};
					if(!isEzUA(trackerName) && GaCode!=EZ_UA_CODE) {
						window.GatrackCart(trackerName);
					}
				}

			})(); // auto execute async funcion

		} //// fim each Codes(UA's')

		////////////////// CORE CUSTOM

		var $productLine = $('.wd-product-line');
		if ($productLine.length) {
			//console.log('$productLine', $productLine);

			function runProcess() {
				$productLine = $('.wd-product-line');
				addProductsPageImpression();
			}

			if ($('.wd-browsing-grid-list.wd-live-scroll')) {
				$body.on('onLiveScrollComplete', function() {
					runProcess();
				});

			}
			$body.on('onBuildFacetingComplete', function() {
				runProcess();
			});

			var screen_bottom = $(window).scrollTop() + $(window).height() + 40;

			var addProductsPageImpression = function() {

				screen_bottom = $(window).scrollTop() + $(window).height() + 40;

				window.clearTimeout(window.gaImpressionProducts);
				window.gaImpressionProducts = window.setTimeout(function() {

					var addProductImpression = function(li, trackerName) {
						var id = li.data('product-id') || '',
							name = (li.data('name') || ''),
							category = (li.data('category') || ''),
							//brand		= (li.data('brand') || ''),
							position = ($productLine.index(li) + 1);

						var list = findPageType();
						if (id) {
							id = parseInt(id);
						}

						var objImpression = {
							'id': id,
							'name': app.tools.htmlDecode(name),
							'category': app.tools.htmlDecode(category),
							//'brand': app.tools.htmlDecode(brand),
							'list': app.tools.htmlDecode(list),
							'position': position
						};
						// se não tiver pelo menos o id ou name não envia
						if (id || name) {
							ezga(trackerName + 'ec:addImpression', objImpression);
							EzLog(trackerName + 'ec:addImpression', objImpression);
						}

					};
					
					if (typeof GaTrackers !== 'undefined') {
						for (var i = 0; i < GaTrackers.length; i++) {
							var trackerName = GaTrackers[i];

							if(isEzUA(trackerName)) { continue; } // não trackear visualizacao de produtos para UA da DCG

							var trackedProductsCount = 0;
							var className = 'ga-viewed-' + (i + 1);

							$productLine.not('.' + className).each(function() {
								var $el = $(this);

								if ( $el.offset().top < screen_bottom ) {
									// aqui o produto já apareceu
									//console.log(' na view port!', $el);
									$el.addClass(className);
									addProductImpression($el, trackerName);
									trackedProductsCount++;
								}
							});

							if (trackedProductsCount > 0) {
								EzLog('Lista de produtos', 'Produtos visualizados', trackedProductsCount + ' produtos foram visualizados');
								ezga(trackerName + 'send', 'event', 'Lista de produtos', 'Produtos visualizados', trackedProductsCount + ' produtos foram visualizados',{'nonInteraction':!0});
							}
						}
					}

				}, 500);
			};

			$(window).bind('load resize scroll', addProductsPageImpression);

		};

		var $basket = $('.wd-checkout-basket');
		if ($basket.length && EzGaCfg.hasOwnProperty('Basket')) {
			function updateBasketGa() {

				var setProductGa = function(trackerName, product) {
						ezga(trackerName + 'ec:addProduct', {
							'id': product.id,
							'name': app.tools.htmlDecode(product.name),
							'category': app.tools.htmlDecode(product.category),
							'brand': app.tools.htmlDecode(product.brand),
							'price': parseFloat(product.price).toFixed(2),
							'quantity': product.quantity,
							'list': 'Carrinho de compras'
						});
					},
					updateItemQuantityGa = function($item, item) {
						var qty = $item.find('.quantity .js-qty').val();
						if (qty) {
							item.quantity = parseInt(qty);
							
							if (typeof GaTrackers !== 'undefined') {
								for (var i = 0; i < GaTrackers.length; i++) {
									var trackerName = GaTrackers[i];
									if(isEzUA(trackerName)) { continue; }

									setProductGa(trackerName, item);

									ezga(trackerName + 'ec:setAction', 'add');
									ezga(trackerName + 'send', 'event', 'Carrinho', 'Alteração de quantidade', 'Quantidade do produto alterada');

									EzLog('Quantidade do produto alterada', trackerName + 'send Alteração de quantidade');
								}
							}
						}
					},
					removeItemGa = function(item) {
						if (typeof GaTrackers !== 'undefined') {
							for (var i = 0; i < GaTrackers.length; i++) {
								var trackerName = GaTrackers[i];
								if(isEzUA(trackerName)) { continue; }

								var index = _.indexOf(EzGaCfg.Basket, item);
								EzGaCfg.Basket[index] = undefined;

								setProductGa(trackerName, item);
								ezga(trackerName + 'ec:setAction', 'remove');
								ezga(trackerName + 'send', 'event', 'Carrinho', 'Exclusão de produtos', 'Produto removido do carrinho');

								EzLog('Produto removido do carrinho', trackerName + 'send Exclusão de produtos');
							}
						}
					},
					clearProductsCart = function(e) {
						if (typeof GaTrackers !== 'undefined') {
							for (var i = 0; i < GaTrackers.length; i++) {
								var trackerName = GaTrackers[i];
								if(isEzUA(trackerName)) { continue; }

								_.each(EzGaCfg.Basket, function(item, propertyName) {
									if (item)
										setProductGa(trackerName, item);
								});
								ezga(trackerName + 'ec:setAction', 'remove');
								ezga(trackerName + 'send', 'event', 'Carrinho', 'Exclusão de produtos', 'Todos os produtos foram removidos do carrinho');

								EzLog('Todos os produtos foram removidos do carrinho', trackerName + 'send Exclusão de produtos');
							}
						}
					};

				if (!$('tbody tr.item', $basket).length) {
					clearProductsCart();
					return;
				}
				_.each(EzGaCfg.Basket, function(item, idx) {
					if (item) {
						var $item = $('#basket-item-' + item.basketItemId, $basket);
						if ($item.length) {
							updateItemQuantityGa($item, item);
						} else {
							removeItemGa(item);
						}
					}
				});
			};
			EzGaCfg.Basket.Shipping = {
				locked: false,
				id: null
			};
			//setShippingOptionGa();
			$.subscribe(EzGaCfg.Urls.ParentBaseUrl + 'checkout/basket/changed', function() {
				//console.log('subscribe basket change!!!');
				$basket = $('.wd-checkout-basket');
				updateBasketGa();
				//setShippingOptionGa();
			});
		}

		var $checkout;
		if (EzGaCfg.hasOwnProperty('Checkout') || !!~bodyClass.indexOf('OnePageCheckoutStep') || !!~bodyClass.indexOf('EasyCheckoutStep')) {
			if (!EzGaCfg.hasOwnProperty('Checkout')) {
				EzGaCfg.Checkout = {
					Items: browsingContext.Common.Basket.Items,
					BasketID: browsingContext.Common.Basket.BasketID
				};
			};
			var checkoutHelper = {
				step: {
					set: function(val) {
						return $.cookie('GaCheckoutStep-' + EzGaCfg.Checkout.BasketID, val);
					},
					get: function() {
						return $.cookie('GaCheckoutStep-' + EzGaCfg.Checkout.BasketID);
					}
				},
				addProductsGa: function(trackerName, isEasy) {
					var x = 0;
					for (var i in EzGaCfg.Checkout.Items) {
						var item = EzGaCfg.Checkout.Items[i];
						ezga(trackerName + 'ec:addProduct', {
							'id': item.code,
							'name': app.tools.htmlDecode(item.name),
							'category': app.tools.htmlDecode(item.category),
							'brand': app.tools.htmlDecode(item.brand),
							'price': item.price,
							'quantity': item.quantity,
							'list': 'Checkout'
						});
						x++;
					}
					EzLog(x + ' produtos enviados.', trackerName);
				}
			};

			var easyGaProcess = function() {
				/*
					STEP
					----
					1 - Identificação
					2 - Seta meio de entrega
					3 - Seta meio de pagamento

				*/

				var step = 0,
					hash = handleHash(window.location.hash),
					basket = {
						DeliveryAmount: 0,
						Total: 0
					};
				EzGaCfg.Checkout.SelectedPaymentMethod = {
					ID: null,
					Name: null
				};

				var sendWaitingIdentification = function() {
					if (typeof GaTrackers !== 'undefined') {
						for (var i = 0; i < GaTrackers.length; i++) {
							var trackerName = GaTrackers[i];
							if(isEzUA(trackerName)) { continue; }
							ezga(trackerName + 'send', 'event', 'Checkout', '[easy] Aguardando identificação');
							EzLog('[easy] Aguardando identificação', trackerName);
						}
					}
				};

				var sendLogin = function() {
					if (typeof GaTrackers !== 'undefined') {
						for (var i = 0; i < GaTrackers.length; i++) {
							var trackerName = GaTrackers[i];
							if(isEzUA(trackerName)) { continue; }
							ezga(trackerName + 'send', 'event', 'Checkout', '[easy] Login realizado');
							EzLog('[easy] Login realizado', trackerName);
						}
					}
				};

				var sendRegister = function() {
					if (typeof GaTrackers !== 'undefined') {
						for (var i = 0; i < GaTrackers.length; i++) {
							var trackerName = GaTrackers[i];
							if(isEzUA(trackerName)) { continue; }
							ezga(trackerName + 'send', 'event', 'Checkout', '[easy] Cadastro realizado');
							EzLog('[easy] Cadastro realizado', trackerName);
						}
					}
				};

				var sendShippingOptionGa = function(sendStep) {
					sendStep = sendStep || 2;
					var shippingOption = '';

					if (EzGaCfg.Checkout.SelectedDeliveryOption && EzGaCfg.Checkout.SelectedDeliveryOption.hasOwnProperty('Name')) {
						shippingOption = app.tools.htmlDecode(EzGaCfg.Checkout.SelectedDeliveryOption.Name);
						var SecondStepDetails = {
							'step': sendStep,
							'option': shippingOption
						};

						if (typeof GaTrackers !== 'undefined') {
							for (var i = 0; i < GaTrackers.length; i++) {
								var trackerName = GaTrackers[i];
								ezga(trackerName + 'ec:setAction', 'checkout_option', SecondStepDetails);
								ezga(trackerName + 'send', 'event', 'Checkout', '[easy] Frete', 'Frete selecionado');
								EzLog('Etapa ' + sendStep + ' do checkout atualizada. Frete selecionado \n' + JSON.stringify(SecondStepDetails), trackerName);
							}
						}
					}
				};

				var sendPaymentOptionGa = function(sendStep) {
					sendStep = sendStep || 3;
					var paymentGroupSelected = '';

					if (EzGaCfg.Checkout.SelectedPaymentMethod.Name) {
						paymentGroupSelected = app.tools.htmlDecode(EzGaCfg.Checkout.SelectedPaymentMethod.Name);
						var details = {
							'step': sendStep,
							'option': paymentGroupSelected
						};

						for (var i = 0; i < GaTrackers.length; i++) {
							var trackerName = GaTrackers[i];
							ezga(trackerName + 'ec:setAction', 'checkout_option', details);
							ezga(trackerName + 'send', 'event', 'Checkout', '[easy] Pagamento', 'Pagamento selecionado');
							EzLog('Etapa ' + sendStep + ' do checkout atualizada. Pagamento selecionado \n' + JSON.stringify(details), trackerName);
						}
					}
				};

				var sendAction = function(sendStep) {
					sendStep = sendStep || step;
					for (var i = 0; i < GaTrackers.length; i++) {
						var trackerName = GaTrackers[i];

						checkoutHelper.addProductsGa(trackerName);

						ezga(trackerName + 'ec:setAction', 'checkout', {
							'step': sendStep
						});
						ezga(trackerName + 'send', 'event', 'Checkout', '[easy] Step '+sendStep+' definida' );
						EzLog('Etapa ' + sendStep + ' do checkout definida.', trackerName);
					}
				};

				function handleHash(hash) {
					if (hash)
						hash = hash.replace('#', '');
					return hash;
				};

				function checkPaymentStep() {
					if (hash === 'payment') {
						//garante o envio dos steps anteriores
						sendAction(1);
						sendAction(2);

						// seta step 3
						step = 3
						sendAction(step);
						sendPaymentOptionGa(step);
						return true;
					}
					return false;
				};

				function checkSelectedDeliveryOption(sendStep) {
					if (EzGaCfg.Checkout.SelectedDeliveryOption) {
						// seta opção de delivery selecionada
						sendShippingOptionGa(sendStep);
					}
				};


				function setUserID() {
					var userID = EasyCheckout.ModelData.Customer.CustomerID + '';
					ezga('set', 'userId', userID);
				};

				$(window).on('hashchange', function() {
					//console.log('hashchange');
					hash = handleHash(window.location.hash);
					checkPaymentStep();
					for(var i = 0; i < GaTrackers.length; i++){
						var trackerName = GaTrackers[i];
						ezga(trackerName + 'set', 'title', ('page-easycheckout-' + hash ) );
						ezga(trackerName + 'send', 'pageview', '/checkout/easy/'+hash);
					}
				});

				/////////////////////////////////////////  Ações iniciais
				if ( EzGaCfg.Shopper.IsAuthenticated ) {

					// garante o envio do step 1
					sendAction(1);

					// seta step 2 (entrega), pois já está identificado
					step = 2;
					sendAction(step);

					checkSelectedDeliveryOption(step);
					// verifica se pulou por ultimo passo
					checkPaymentStep();

				} else {

					sendWaitingIdentification();

					// nao esta autenticado, aguardando identificacao
					step = 1
					sendAction(step);

					ko.postbox.subscribe('checkout/IsAuthenticated', function() {
						//console.log('subscribe checkout/IsAuthenticated');
						EzGaCfg.Shopper.IsAuthenticated = true;

						// seta step 2, pois já identificou e esta na entrega
						step = 2;
						sendAction(step);
						//checkSelectedDeliveryOption(step);
						// verifica se pulou por ultimo passo
						checkPaymentStep();
						setUserID();
					});

					ko.postbox.subscribe('checkout/signin/done', function() {
						sendLogin();
						setUserID();
					});

					ko.postbox.subscribe('checkout/signup/done', function() {
						sendRegister();
						setUserID();
					});

				}
				/////////////////////////////////////// FIM Ações iniciais

				ko.postbox.subscribe('checkout/setDelivery', function(args) {
					//console.log('args',args);
					var deliveryOptionName = '';
					if (args && args.hasOwnProperty('deliveryOption')) {
						EzGaCfg.Checkout.SelectedDeliveryOption = EzGaCfg.Checkout.SelectedDeliveryOption || {};

						EzGaCfg.Checkout.SelectedDeliveryOption.Name = args.deliveryOption.Name;
						EzGaCfg.Checkout.SelectedDeliveryOption.DeliveryOptionID = args.deliveryOption.ID;
						// atualiza step 2 com o valor do delivery
						if (step > 1)
							checkSelectedDeliveryOption();
					}

				});

				ko.postbox.subscribe('checkout/payment/setType', function(args) {
					//console.log('subscribe checkout/payment/setType args',args);
					if (args && args.hasOwnProperty('paymentMethod')) {
						EzGaCfg.Checkout.SelectedPaymentMethod = {
							ID: args.paymentMethod.ID,
							Name: args.paymentMethod.Name
						};
						if (step == 3) {
							sendPaymentOptionGa();
						}
					}
				});

				ko.postbox.subscribe('checkout/data/update', function(data) {
					//console.log('subscribe checkout/data/update', data);
					if (data.hasOwnProperty('Basket')) {
						basket.DeliveryAmount = data.Basket.DeliveryAmount;
						basket.Total = data.Basket.Total;
					}
				});

				ko.postbox.subscribe('checkout/payment/submit', function(response) {
					//console.log('subscribe checkout/payment/submit response', response);
					if (response.hasOwnProperty('Response')) {
						var res = response;
						response = response.Response;
						if (response.IsValid) {
							var orderNumber = (response.Custom['PlaceOrder.OrderNumber'] !== undefined) ? response.Custom['PlaceOrder.OrderNumber'] : response.Custom['EmptyPlaceOrder.OrderNumber'];
							// monta objeto
							var order = {
								Total: (res.Order.Total || basket.Total || parseFloat(0)).toFixed(2),
								DeliveryAmount: (basket.DeliveryAmount || parseFloat(0)).toFixed(2),
								Items: EzGaCfg.Checkout.Items,
								OrderNumber: orderNumber,
								PaymentMethods: [{
									Title: EzGaCfg.Checkout.SelectedPaymentMethod.Name
								}]
							};
							sendPurchaseGa(order);
						}
					}
				});
			};

			var onepageGaProcess = function() {
				/*
					STEP
					----
					1 - Identificação
					2 - Seta meio de entrega
					3 - Seta meio de pagamento

				*/
				var currentStep = checkoutHelper.step.get();
				//console.log('currentStep',currentStep);

				var sendPrevSteps = function() {
					if (!currentStep)
						return false;
					var count = currentStep;
					//console.log('sendPrevs currentStep',currentStep);
					while (--count) {
						sendAction(count, true);
					};
				};

				var findCurrentStep = function() {
					var stepNumber = 1;
					$('.step', $checkout).each(function(i, $step) {

						if ($($step).hasClass('step-complete')) {
							stepNumber++;
						}
					});

					return stepNumber;
				};

				var subscribeEvents = function() {
					// Escuta evento de selecionar meio de entrega
					$.subscribe('/wd/checkout/deliveryservices/selected', function() {
						//console.log('escutou evento de selecionar deliveryservice!!! currentStep-',currentStep);
						sendShippingOptionGa(currentStep);
					});

					$body.on('change', '.wd-checkout-paymentgroup .payment-method-id', function() {
						//console.log('chenge no .payment-method-id - currentStep-',currentStep);
						sendPaymentOptionGa(currentStep);
					});
				};

				var sendShippingOptionGa = function(step) {
					step = step || 2;
					var shippingOption = '';
					var $deliveryService = $('.wd-checkout-deliveryservices', $checkout),
						$deliveryServiceSelected = $deliveryService.find('.js-delivery-choice input:checked');
					if ($deliveryServiceSelected.length) {
						shippingOption = $deliveryServiceSelected.closest('li').find('.item-name').text();
						EzGaCfg.Checkout.SelectedDeliveryOption = EzGaCfg.Checkout.SelectedDeliveryOption || {};
						EzGaCfg.Checkout.SelectedDeliveryOption.Name = shippingOption;
						var SecondStepDetails = {
							'step': step,
							'option': shippingOption
						};

						for (var i = 0; i < GaTrackers.length; i++) {
							var trackerName = GaTrackers[i];
							ezga(trackerName + 'ec:setAction', 'checkout_option', SecondStepDetails);
							ezga(trackerName + 'send', 'event', 'Checkout', 'Frete', 'Frete selecionado');
							EzLog('Etapa ' + step + ' do checkout atualizada. Frete selecionado \n' + JSON.stringify(SecondStepDetails), trackerName);
						}
					}
				};

				var sendPaymentOptionGa = function(step) {
					step = step || 3;
					var paymentGroupSelected = '';
					var $paymentGroup = $('.wd-checkout-paymentgroup', $checkout),
						$paymentGroupSelected = $paymentGroup.find('input.payment-method-id:checked');
					if ($paymentGroupSelected.length) {
						paymentGroupSelected = $paymentGroupSelected.closest('label').find('img').attr('alt');
						var details = {
							'step': step,
							'option': paymentGroupSelected
						};

						for (var i = 0; i < GaTrackers.length; i++) {
							var trackerName = GaTrackers[i];
							ezga(trackerName + 'ec:setAction', 'checkout_option', details);
							ezga(trackerName + 'send', 'event', 'Checkout', 'Pagamento', 'Pagamento selecionado');
							EzLog('Etapa ' + step + ' do checkout atualizada. Pagamento selecionado \n' + JSON.stringify(details), trackerName);
						}
					}
				};

				var sendAction = function(step, isPrevStep) {

					step = step || currentStep;
					for (var i = 0; i < GaTrackers.length; i++) {
						var trackerName = GaTrackers[i];

						checkoutHelper.addProductsGa(trackerName);

						ezga(trackerName + 'ec:setAction', 'checkout', {
							'step': step
						});
						ezga(trackerName + 'send', 'event', 'Checkout', 'Login', {
							useBeacon: true
						});
						EzLog('Etapa ' + step + ' do checkout definida.', trackerName);

					}

					if (EzGaCfg.Shopper.IsAuthenticated) {
						if (!EzGaCfg.Checkout.SelectedDeliveryOption)
							sendShippingOptionGa(step);

						sendPaymentOptionGa(step);
					}

				};

				var checkStepState = function() {
					if (currentStep < 3) {
						var $nextStep = $('.step.step-' + (currentStep + 1), $checkout);
						//console.log('$nextStep', $nextStep);
						if ($nextStep.length && !$nextStep.hasClass('step-disabled')) {
							//console.log('entrou increment checkStepState');
							currentStep++;
							// recursivo
							checkStepState();
						}

					}
				};

				if (currentStep) {
					var oldStep = currentStep = parseInt(currentStep);
					if (!EzGaCfg.Shopper.IsAuthenticated)
						currentStep = 1;
					// verifica se mudou a step ou o cliente somente atualizou a página
					checkStepState();
					//console.log('pós checkStepState oldStep=',oldStep,' currentStep=',currentStep, ' diferença=',(currentStep - oldStep));
					// se a diferença entre a entre a etapa atual e a etapa anterior for maior que 1, envia ações anteriores
					if ((currentStep - oldStep) > 1)
						sendPrevSteps();
				} else {
					// se currentStep for nulo

					// procura currentStep
					currentStep = findCurrentStep();
					// se currentStep for maior que 1
					if (currentStep > 1) {
						// envia ação de etapas anteriores não setadas
						sendPrevSteps();
					}
				}

				// se o elemento de classe 'step-'+currentStep +1 existir lança evento
				var $currentStep = $('.step.step-' + currentStep);
				if ($currentStep.length) {
					sendAction();
					if (currentStep <= 3) {
						//console.log('setou cookie currentStep!!!!!', currentStep);
						checkoutHelper.step.set(currentStep);
					}
				}

				// escuta eventos de setar frete e setar meio de pagamento
				subscribeEvents();
			};
			/*
			TIPOS DE CHECKOUT - WIDGETS
			-------------------------
			Checkout normal =
			Checkout One Page = wd-checkout-onepage
			EasyCheckout = wd-easy-checkout

			*/
			var retryCheckoutProcessCount = 0;
			var tryRunProcess = function() {
				var $onePage = $('.wd-checkout-onepage'),
					$easy = $('.wd-easy-checkout');
				if (!!~bodyClass.indexOf('OnePageCheckoutStep')) {
					$checkout = $('.wd-checkout-onepage');
					onepageGaProcess();
				} else if (!!~bodyClass.indexOf('EasyCheckoutStep')) {
					$checkout = $('.wd-easy-checkout');
					easyGaProcess();
				} else {
					retryCheckoutProcessCount++;
					if (retryCheckoutProcessCount < 6) {
						setTimeout(tryRunProcess, 550);
					}
				}
			};

			tryRunProcess();

		};

		var sendPurchaseGa = function(order, isEasy) {
			function addProductsGa(trackerName) {
				var x = 0;
				for (var i in order.Items) {
					var item = order.Items[i];
					ezga(trackerName + 'ec:addProduct', {
						'id': item.code,
						'name': app.tools.htmlDecode(item.name),
						'category': app.tools.htmlDecode(item.category),
						'brand': app.tools.htmlDecode(item.brand),
						'price': item.price,
						'quantity': item.quantity
					});
					x++;
				}
				EzLog(x + ' produtos enviados.', trackerName);
			}

			// envia a transação na finalização da compra
			var orderAffiliate = (EzGaCfg.Config.Store.Name || ''),
				orderTotal = (order.Total || parseFloat(0).toFixed(2)),
				shippingAmount = (order.DeliveryAmount || parseFloat(0).toFixed(2)),
				orderId = order.OrderNumber || '';

			var purchase = {
				affiliation: orderAffiliate,
				id: orderId,
				revenue: orderTotal,
				shipping: shippingAmount
			};

			if (order.PaymentMethods.length) {
				purchase.option = order.PaymentMethods[0].Title;
			}

			for (var i = 0; i < GaTrackers.length; i++) {
				var trackerName = GaTrackers[i];

				addProductsGa(trackerName);

				ezga(trackerName + 'ec:setAction', 'purchase', purchase);
				var easyPrefix = isEasy ? '[easy] ' : '';
				ezga(trackerName + 'send', 'event', 'Checkout', easyPrefix + 'Pedido', 'Pedido realizado com sucesso');

				//console.log('Order', order);
				EzLog('Dados do pedido ' + orderId + ' enviados.', trackerName);
			}

		};

		// confirmação de compra checkout onePage
		if (EzGaCfg.hasOwnProperty('Order') && (bodyClass.indexOf('EasyCheckoutReceiptStep') != -1 || bodyClass.indexOf('OneStepCheckoutReceiptStep') != -1 || bodyClass.indexOf('DefaultCheckoutReceiptStep ') != -1)) {
			if (EzGaCfg.Order.OrderNumber)
				sendPurchaseGa(EzGaCfg.Order);
		}

		window['ga'] = ezga;

		////////////////// FIM CORE CUSTOM

	};

	function findPageType() {
		var pageType = 'Outros';

		if (!!~bodyClass.indexOf('HomeRoute')) {
			pageType = "Home";
		}
		if (!!~bodyClass.indexOf('context-search')) {
			pageType = "Página de Pesquisa";
		}
		if (!!~bodyClass.indexOf('context-product')) {
			pageType = "Detalhe de produto";
		}
		if (!!~bodyClass.indexOf('BasketIndexRoute')) {
			pageType = "Carrinho de compras";
		}
		if (!!~bodyClass.indexOf('OneStepCheckoutReceiptStep')) {
			pageType = "Página de Confirmação de Compra";
		}
		return pageType;
	};

	function EzLog() { return;
		if (window['GaDebug'] && console) {
			console.log('\n%cEZ Commerce%c - %cG%co%co%cg%cl%ce%c Analytics %c[Debug]\n\n',
				'color:#060;font-weight:bold;font-size:13px', // EZ Commerce
				'color:#060;font-weight:bold;font-size:13px', // -
				'color:#0266C8;font-weight:bold;font-size:13px', // G
				'color:#F90101;font-weight:bold;font-size:13px', // o
				'color:#F2B50F;font-weight:bold;font-size:13px', // o
				'color:#0266C8;font-weight:bold;font-size:13px', // g
				'color:#00933B;font-weight:bold;font-size:13px', // l
				'color:#F90101;font-weight:bold;font-size:13px', // e
				'color:#000;font-weight:bold;font-size:13px', // Analytics
				'color:#AAA;font-weight:bold;font-size:13px', // [Debug]
				(arguments[0] || '') + '\n' +
				'  Tracker ' + (arguments[1] ? arguments[1] : 'default') + '\n\n'
			);
		}
	};

});

}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; };
