(function (ns) { ns.Gtm = function (options) { this.construct.apply(this, arguments); }; ns.Gtm.prototype.construct = function (options) { this.namespace = 'gtm'; this.options = $.extend({ cartItems: {}, products: {}, actionField: {} }, options); this.initProductClicks(); this.initRemovingFromCart(); }; ns.Gtm.prototype.initProductClicks = function () { for (var productId in this.options.products) { $('[data-product-id=' + productId + ']').bind( 'click.' + this.namespace, _.bind(this.onProductClick, this, productId) ); } }; ns.Gtm.prototype.onProductClick = function (productId, ev) { ev.preventDefault(); var data = { 'event': 'productClick', 'ecommerce': { 'click': { 'actionField': this.options.actionField, 'products': [this.options.products[productId]] } }, 'eventCallback': function() { document.location = $('[data-product-id=' + productId + ']').prop('href'); } }; dataLayer.push(data); ns.Gtm._debug(data); }; ns.Gtm.prototype.initRemovingFromCart = function () { for (var itemId in this.options.cartItems) { $('[data-cartitem-id=' + itemId + ']').bind( 'click.' + this.namespace, _.bind(this.onRemoveFromCart, this, itemId) ); } }; ns.Gtm.prototype.onRemoveFromCart = function (itemId, ev) { var defaultPrevented; if (-1 != navigator.userAgent.indexOf('MSIE 8')) { defaultPrevented = ('1' == $('[data-cartitem-id=' + itemId + ']').data('default-prevented')); } else { defaultPrevented = ev.isDefaultPrevented(); } if (false == defaultPrevented) { ev.preventDefault(); var product = this.options.cartItems[itemId]; var quantity = '' + $('[data-cartitem-id=' + itemId + ']').closest('div').find('input[name^=quantity]').val(); if (!isNaN(parseInt(quantity))) { product.quantity = quantity; } var data = { 'event': 'removeFromCart', 'ecommerce': { 'remove': { 'products': [product] } }, 'eventCallback': function() { document.location = $('[data-cartitem-id=' + itemId + ']').prop('href'); } }; dataLayer.push(data); ns.Gtm._debug(data); } }; ns.Gtm.onAddToCart = function (product) { var data = { 'event': 'addToCart', 'ecommerce': { 'add': { 'products': [product] } } }; dataLayer.push(data); ns.Gtm._debug(data); }; ns.Gtm.onCheckout = function (step, products, callback) { var data = { 'event': 'checkout', 'ecommerce': { 'checkout': { 'actionField': {'step': step}, 'products': products } } }; if (undefined != callback) { data['eventCallback'] = callback; } dataLayer.push(data); ns.Gtm._debug(data); }; ns.Gtm.onCheckoutOption = function (step, checkoutOption) { var data = { 'event': 'checkoutOption', 'ecommerce': { 'checkout_option': { 'actionField': {'step': step, 'option': checkoutOption} } } }; dataLayer.push(data); ns.Gtm._debug(data); }; ns.Gtm._debug = function (data) { if (false == qs.constant('SITE_LIVE')) { if (true == qs.constant('DEBUG')) { alert(JSON.stringify(data, undefined, 4)); } if (undefined != data.eventCallback) { data.eventCallback(); } } }; })(qs.defineNS('lib'));