/* Minification failed. Returning unminified contents.
(482,34): run-time error JS1004: Expected ';'
(482,44-45): run-time error JS1010: Expected identifier: (
 */
if (window.innDataLayer == undefined) {
    window.innDataLayer = [];
}
;
var googleTagManager = (function () {

    var analyticsListNames = {
        'supplierdetail': 'Supplier Detail',
        'stay': 'Stay Detail',
        'activities': 'Activity'
    };

    // ----- Impressions -----
    var getProductCategoryName = function(viewName, categoryId) {
        var categoryName;
        switch (viewName) {
            case 'Activity':
                categoryName = $('#pCategory_' +categoryId + ' span').text();
                break;
            case 'Merchandise':
                categoryName = $('#productCategoryFilters input[value=' +categoryId + ']+span').text();
                break;
            default:
                    // on Lodging & Car views, this is also the category Name
                categoryName = viewName;
        }

        return categoryName;
    }

    var getLodgingImpressionsInfo = function(viewName, lodgingMapper) {
        var gtmSupplierList = [];
        var domSupplierList = $('#supplierList li:visible');
        for(var i = 0; i < domSupplierList.length; i++) {
            var supplier = $(domSupplierList[i]);
            var gtmSupplier = lodgingMapper(viewName, supplier, i);
            gtmSupplierList.push(gtmSupplier);
        }

        return gtmSupplierList;
    }

    var getCalendarImpressionsInfo = function (viewName, lodgingMapper) {
        var gtmProductList =[];
        var domOptionList = $('#optionsList tr:visible');
        for (var i = 0; i < domOptionList.length; i++) {
            var product = $(domOptionList[i]);
            var gtmProduct = lodgingMapper(viewName, product, i);
            gtmProductList.push(gtmProduct);
        }

        return gtmProductList;
    }

    function defaultLodgingMapper(viewName, supplier, index) {
        var product = supplier.find('tr:first');
        return {
            id: supplier.data('supplier-id') + '-' + product.data('product-id'),
            price: product.data('price'),
            position: index + 1,
            name: product.data('product-name'),
            list: viewName,
            category: getProductCategoryName(viewName, product.data('category')),
            brand: supplier.data('name')
        };
    }

    function defaultProductMapper(viewName, product, index) {
        return {
            id: product.data('supplier-id') + '-' + product.data('product-id'),
            price: product.data('price'),
            position: index + 1,
            name: product.data('name'),
            list: viewName,
            category: product.data('category-name') || getProductCategoryName(viewName, product.data('category')),
            brand: product.data('supplier-name')
        };
    }
    
    var getImpressionsInfo = function (viewName, productMapper, lodgingMapper) {
        if (!productMapper) {
            productMapper = defaultProductMapper;
        }
        if (!lodgingMapper) {
            lodgingMapper = defaultLodgingMapper;
        }      

        var gtmProductList = [];
        var domProductList = $('#productList li:visible');

        for (var i = 0; i < domProductList.length; i++) {
            var product = $(domProductList[i]);
            var gtmProduct = productMapper(viewName, product, i);
            gtmProductList.push(gtmProduct);
        }

        if (!gtmProductList.length) {
            gtmProductList = getLodgingImpressionsInfo(viewName, lodgingMapper);
        }

        if (!gtmProductList.length) {
            gtmProductList = getCalendarImpressionsInfo(viewName, productMapper);
        }

        return gtmProductList;
    }
    
    var pushImpressions = function(viewName, productMapper, lodgingMapper) {
        var gtmProductList = getImpressionsInfo(viewName, productMapper, lodgingMapper);

        var gtmInfo = {
            event: 'gtm4inntopia.pushImpressions',
            ecommerce: {
                impressions: gtmProductList
            }
        };

        innDataLayer.push(gtmInfo);
    }

    // ----- Cart Events: Add/Remove -----
    var addToCartEvents = {
        add: 'add',
        remove: 'remove'
    }

    var getInsuranceInfo = function(insuranceObj) {
        var gtmInsurance = {
            name: insuranceObj.ProductName,
            id: insuranceObj.SupplierId + '-' + insuranceObj.ProductId,
            price: insuranceObj.Price,
            brand: insuranceObj.SupplierName,
            category: 'Insurance',
            list: 'Review',
            position: 1 // no other position on insurance
        }
        return gtmInsurance;
    }

    var pushCartEvent = function (cartEvent, itineraryId, products, list) {
        var cartGtmEventName = cartEvent === 'add' ? 'gtm4inntopia.addToCart' : 'gtm4inntopia.removeFromCart';

        if (!list) {
            list = defaultListName();
        }

        var gtmInfo = {
            event: cartGtmEventName,
            ecommerce: {
                currencyCode: currencyCode
            }
        };
        gtmInfo.ecommerce[cartEvent] = {
            actionField: {
                id: itineraryId,
                list: list
            },
            products: products
        }

        innDataLayer.push(gtmInfo);
    }

    function defaultListName() {
        var location = window.location.toString();
        var list = location.match('((?:.+?/){4})([a-zA-Z]*)'); // find the fourth piece in slashes of the URL
        if ($.isArray(list) && list.length > 2) {
            list = list[2]; // select the match we are interested in

            var analyticsListKey = list.toLowerCase();
            if (analyticsListNames.hasOwnProperty(analyticsListKey)) {
                return analyticsListNames[analyticsListKey];
            }

            list = list.charAt(0).toUpperCase() + list.slice(1).toLowerCase();
            return list;
        }
        else {
            return null;
        }
    }

    var pushAddToCart = function (itineraryId, products, list) {
        pushCartEvent(addToCartEvents.add, itineraryId, products, list);
    }

    var pushAddPackageToCart = function (itineraryId, products) {
        var mappedProducts = [];

        // ideally the data is already modeled properly but this workflow prevents it from happening
        for (var i = 0; i < products.length; i++) {
            var product = products[i];

            mappedProducts.push({
                name: product.Name,
                id: product.Id,
                price: product.Price,
                brand: product.Brand,
                category: product.Category,
                variant: product.PackageId,
                quantity: product.Quantity,
                coupon: product.Coupon
            });
        }

        pushCartEvent(addToCartEvents.add, itineraryId, mappedProducts);
    }

    var pushRemoveFromCart = function (itineraryId, products, list) {
        pushCartEvent(addToCartEvents.remove, itineraryId, products, list);
    }

    // ----- Checkout -----
    var pushCheckoutStep = function (step, itineraryId, paymentType) {
        var gtmInfo = {
            event: 'gtm4inntopia.checkout',
            ecommerce: {
                checkout: {
                    actionField: {
                        step: step,
                        id: itineraryId,
                        affiliation: window.salesChannelName + ' - ' + window.salesId
                    },
                    products: getCheckoutInfo(step)
                }
            }
        };

        if (paymentType) {
            gtmInfo.ecommerce.checkout.actionField.option = paymentType;
        }

        innDataLayer.push(gtmInfo);
    }

    var pushConfirm = function () {
        var products = [];
        $.each(innDataLayer[0].transactionProducts, function (i, item) {
            products.push(
                {
                    name: item.gtmname,
                    id: item.sku ? item.sku : item.id, //allows either the sku (legacy) or the id (non-legacy) fields to be set for GTM.  GoogleTagManagerECommerceProduct
                    price: item.price,
                    brand: item.brand,
                    category: item.category,
                    variant: item.variant == 0 ? '' : item.variant,
                    quantity: item.quantity
                }
            );
        });

        var gtmInfo = {
            event: 'gtm4inntopia.purchase',
            ecommerce: {
                purchase: {
                    actionField: {
                        id: innDataLayer[0].transactionId,
                        affiliation: innDataLayer[0].transactionAffiliation,
                        revenue: innDataLayer[0].transactionTotal,
                        tax: innDataLayer[0].transactionTax,
                        shipping: innDataLayer[0].transactionShipping,
                        coupon: '',
                        option: window.paymentMethod
                    },
                    products: products
                }
            }
        };
        innDataLayer.push(gtmInfo);
    }

    var getCheckoutInfo = function (step) {  //Scrape HTML instead of SummaryItinerary-Json Call for performance, no need to call same method twice
        var products = [];
        if (step === 5 || step === 6) { //Review page uses tr tags instead of td tags does not use summaryitinerary
             $('tr[id^="itineraryItem-"]').each(function (index, item) {
                 products.push(formatCheckoutProduct(item, step));
            });
        }
        else { //from summaryitinerary widget html scrape
            $('td[id^="itineraryItem-"]').each(function (index, item) {
                products.push(formatCheckoutProduct(item, step));
            });
            //Bundled products
            $('div[id^="itineraryItem-"]').each(function (index, item) {
                products.push(formatCheckoutProduct(item, step));
            });
            //Packaged products
            $('div[id^="packageItineraryItem-"]').each(function (index, item) {
                products.push(formatCheckoutProduct(item, step));
            });
        }

        return products;
    }

    var formatCheckoutProduct = function (item, step) {
        var $item =  $(item);
        var variant = $item.data('package');
        variant = variant ? variant.toString() : '';
        var category = $item.data('category-name');
        if (step === 5 || step === 6)
        {
            category = $item.data('category');
        }
        var product = {
            name: $item.data('name'),
            id: $item.data('supplier-id') + '-' + $item.data('product-id'),
            price: $item.data('price'),
            brand: $item.data('supplier-name'),
            category: category,
            variant: variant,
            quantity: $item.data('quantity')
        };
        return product;
    }

    var pushCheckoutStepJson = function (step) {
        $.ajax({
            type: "POST",
            url: '/Ecomm/widgets/summaryitinerary/json',
            data: {
                sessionId: sessionId,
                language: language,
                output: 'json'
            },
            success: function (rdata) {
                var products = [];
                var packageId = '';
                var itineraryId = rdata.ItineraryId;

                $.each(rdata.NonPackagedItems, function (index, item) {
                    var product = {
                        name: item.ProductName,
                        id: item.SupplierId + '-' + item.ProductId,
                        price: item.Price,
                        brand: item.SupplierName,
                        category: item.CategoryName,
                        variant : '',
                        quantity: item.Quantity,
                };
                    products.push(product);
                });
                $.each(rdata.Packages, function () {
                    packageId = this.PackageId;
                    $.each(this.Components, function () {
                        $.each(this.ItineraryItems, function (index, item) {
                            var product = {
                                name: item.ProductName,
                                id: item.SupplierId + '-' + item.ProductId,
                                price: item.Price,
                                brand: item.SupplierName,
                                category: item.CategoryName,
                                variant : packageId,
                                quantity: item.Quantity,
                            };
                            products.push(product);
                        });
                    });

                });
                
                var gtmInfo = {
                    event: 'gtm4inntopia.checkout',
                    ecommerce: {
                        checkout: {
                            actionField: { step: step, id: itineraryId },
                            products: products
                        }
                    }
                };
                innDataLayer.push(gtmInfo);
            }
        });
    }

    // ----- Product click -----

    var pushProductClickEvent = function (products, viewName) {
        var gtmInfo = {
            event: 'gtm4inntopia.productClick',
            ecommerce: {
                click: {
                    actionField: { 'list': viewName },
                    products: products
                }
            }
        };

        innDataLayer.push(gtmInfo);
    }

    var getClickedProductList = function (elementId) {
        var productsList = [];
        $("#" + elementId).each(function () {
            var data = $(this).data();
            productsList.push({
                'name': data.name || data.productName,
                'id': (data.supplierId || data.supplierid) + "-" + (data.productId || data.productid),
                'price': data.price,
                'brand': data.supplierName || data.productSupplierName,
                'category': data.categoryName || data.productCategoryName,
                'variant': "",
                'position': data.positionOrder || data.productPositionOrder
            });
        });

        return productsList;
    }

    var pushProductClick = function (products, viewName) {
        pushProductClickEvent(products, viewName);
    }

    var pushProductClickFromContainerId = function (containerId, viewName) {
        var products = getClickedProductList(containerId);
        pushProductClickEvent(products, viewName);
    }

    var getProductInfo = function (data) {
        var productName = data.text() + " - " + data.nextUntil(".airOr, .airSegmentTitle").text();
        var airSelectedForm = data.closest('form');
        var carrier = airSelectedForm.find("input[name='carrier']").val();
        var ticketCode = airSelectedForm.find("input[name='ticketingcode']").val();
        var totalPrice = airSelectedForm.find("input[name='totalprice']").val();
        var position = airSelectedForm.attr('id');
        var departureSegment = airSelectedForm.find("input[name='segment_1']:checked").val();
        var departureFlightNumber = $(departureSegment).find("FltNum").text();
        var returnSegment = airSelectedForm.find("input[name='segment_2']:checked").val();
        var returnFlightNumber = $(returnSegment).find("FltNum").text();

        return {
            'name': productName,
            'id': carrier + "-" + departureFlightNumber + "-" + returnFlightNumber + (ticketCode != "" ? "-" + ticketCode : ""),
            'price': totalPrice,
            'brand': carrier,
            'category': 'Air',
            'variant': "",
            'position': position
        }
    }

    return {
        // impressions
        pushImpressions: pushImpressions,

        // cart events: add/remove
        addToCartEvents: addToCartEvents,
        getInsuranceInfo: getInsuranceInfo,
        pushAddToCart: pushAddToCart,
        pushAddPackageToCart: pushAddPackageToCart,
        pushRemoveFromCart: pushRemoveFromCart,

        // checkout step
        pushCheckoutStep: pushCheckoutStep,
        pushCheckoutStepJson: pushCheckoutStepJson,

        // product click
        pushProductClick: pushProductClick,
        pushProductClickFromContainerId: pushProductClickFromContainerId,
        getProductInfo: getProductInfo,

        //Purchase
        pushConfirm: pushConfirm
    }
})();;
const googleAnalyticsFour = (function () {

    const gaFourListNames = {
        'shop-lodging': 'Lodging',
        'shop-activities': 'Activity',
        'shop-merchandise': 'Merchandise',
        'shop-calendar': 'Calendar',
        'listings-supplierdetail': 'Lodging Supplier',
        'activity-shopping': 'Activity Shopping',
        'shop-stay': 'Shop Stay',
        'shop-air': 'Shop Air',
        'packagebuilder': 'Package Builder'
    };

    /*  functions */

    const pushGAFourEvent = async function (event, ecommerce) {
        const eventData = {
            event: event,
            ecommerce
        };
        window.innDataLayer.push(eventData);
        return eventData;
    };

    /* SHOP/LODGING and SHOP/STAY - collect product data from the DOM */
    const pushLodgingItemListView = function (listId) {
        let ecommerce = {};
        ecommerce.item_list_id = listId;
        ecommerce.item_list_name = gaFourListNames[listId];
        ecommerce.items = [];
        $('.supplierTile').each(function (i) {
            const $tile = $(this);
            let item = {};
            item.affiliation = window.salesId + '-' + window.salesChannelName;
            item.currency = window.currencyCode;
            item.item_category = '1';
            item.item_category2 = 'Lodging';
            item.item_category3 = '1';
            item.item_category4 = 'Lodging';
            item.index = i + 1;
            item.item_id = $tile.data('supplier-id').toString();
            item.item_name = $tile.data('name');
            item.item_brand = item.item_id + '-' + item.item_name;
            item.variant = $tile.data('package-id') || null;

            if (ecommerce.item_list_id == 'shop-lodging') {
                const $productPriceTableRow = $tile.find($('.supplierTile__productList tr'));
                if ($productPriceTableRow.length == 0) {
                    item.price = null;
                } else {
                    let priceArray = [];
                    $productPriceTableRow.each(function () {
                        let thisPrice = parseFloat($(this).data('price'));
                        priceArray.push(thisPrice);
                    });
                    item.price = Math.min.apply(Math, priceArray);
                }
            } else {
                item.price = parseFloat($tile.data('price'));
            }

            ecommerce.items.push(item);
        });

        pushGAFourEvent('view_item_list', ecommerce);
    };

    /* SHOP/ACTIVITIES and SHOP/MERCHANDISE - collect product data from the DOM  */
    const pushActMerchItemListView = function (listId) {
        let ecommerce = {};
        ecommerce.item_list_id = listId;
        ecommerce.item_list_name = gaFourListNames[listId];
        ecommerce.items = [];
        const tileType = (ecommerce.item_list_id == 'shop-activities') ? '.activityTile' : '.merchandiseTile';

        const promises = [];
        const $tileType = $(tileType);
        for (let i = 0; i <= $tileType.length - 1; i++) {
            const $tile = $($tileType[i]);
            let item = {};
            item.affiliation = window.salesId + '-' + window.salesChannelName;
            item.currency = window.currencyCode;
            item.index = i + 1;
            item.item_id = $tile.data('product-id').toString();
            item.item_name = $tile.data('name');
            item.item_brand = $tile.data('supplier-id') + '-' + $tile.data('supplier-name');
            item.price = (ecommerce.item_list_id == 'shop-activities') ? parseFloat($tile.data('price')) : parseFloat($tile.data('pricenum'));
            item.variant = $tile.data('package-id') || null;

            promises.push(mapProductCategoryData($tile.data('category'), item, ecommerce));
        }

        Promise.all(promises).then(function () {
            pushGAFourEvent('view_item_list', ecommerce);
        });
    };

    /* SUPPLIERDETAIL - collect product data from the DOM  */
    const pushSuppDetItemListView = function (listId) {
        let ecommerce = {};
        ecommerce.item_list_id = listId;
        ecommerce.item_list_name = gaFourListNames[listId];
        ecommerce.items = [];
        let prodIndex = 0;
        $('.supplierDetailProducts').each(function (i) {
            const $tile = $(this);
            $tile.find('.product-row').each(function (p) {
                let item = {};
                item.affiliation = window.salesId + '-' + window.salesChannelName;
                item.currency = window.currencyCode;
                item.item_category = '1';
                item.item_category2 = 'Lodging';
                item.item_category3 = '1';
                item.item_category4 = 'Lodging';
                let prodName = $tile.data('name');

                let $thisProduct = $(this);
                prodIndex = prodIndex + 1;
                item.index = prodIndex;
                item.item_id = $tile.data('product-id').toString();
                item.item_name = $thisProduct.data('package-name') ? prodName + '-' + $thisProduct.data('package-name') : prodName;
                item.variant = $thisProduct.data('package-id') || null;
                item.item_brand = $tile.data('supplier-id') + '-' + $tile.data('supplier-name');
                item.price = parseFloat($thisProduct.data('price'));

                ecommerce.items.push(item);
            });
        });

        pushGAFourEvent('view_item_list', ecommerce);
    };

    /* SHOP/AIR - collect product data from the DOM  */
    const pushAirItemListView = function (listId) {
        let ecommerce = {};
        ecommerce.item_list_id = listId;
        ecommerce.item_list_name = gaFourListNames[listId];
        ecommerce.items = [];
        let prodIndex = 0;
        $('#mainContent form').each(function (i) {
            const $fare = $(this);
            let item = {};
            item.affiliation = window.salesId + '-' + window.salesChannelName;
            item.currency = window.currencyCode;
            item.item_category = '4';
            item.item_category2 = 'Airfare';
            item.item_category3 = '113';
            item.item_category4 = 'Airfare';

            prodIndex = prodIndex + 1;
            item.index = prodIndex;

            let airfare = $fare.attr('name');
            let airfareId = airfare.split('_')[1];
            item.item_name = airfare;
            item.item_id = airfareId;
            item.item_brand = item.affiliation;
            item.price = parseFloat($fare.find($('input[name=totalprice]')).val());

            ecommerce.items.push(item);
        });

        pushGAFourEvent('view_item_list', ecommerce);
    };

    /*  BROWSE/CATALOG (Gryphon)
        receive item list and selected product data from postmessage
        check if item list is empty - if not, push item list view event
        and then move on to select item event regardless
    */
    const pushItemListViewAndSelectedProduct = function (itemList, selectedProduct) {
        let ecommerce = {
            item_list_id: 'activity-shopping',
            item_list_name: gaFourListNames['activity-shopping'],
            currency: window.currencyCode,
            items: []
        };
        const promises = [];

        if (itemList.length > 0) {
            const itemAffiliation = `${window.salesId}-${window.salesChannelName}`;

            for (let i = 0; i <= itemList.length - 1; i++) {
                const thisItem = {
                    item_id: itemList[i].productId,
                    item_name: itemList[i].productName,
                    affiliation: itemAffiliation,
                    coupon: null,
                    index: itemList[i].listPosition,
                    item_brand: `${itemList[i].supplierId}-${itemList[i].supplierName}`,
                    categoryId: itemList[i].productCategory,
                    price: itemList[i].price,
                    variant: null
                };

                promises.push(mapProductCategoryData(thisItem.categoryId, thisItem, ecommerce));
            }
        }

        Promise.all(promises).then(() => {
            if (ecommerce.items.length > 0) {
                pushGAFourEvent('view_item_list', ecommerce);
            }
            pushGryphonSelectItem(selectedProduct);
        });
    };

    /* SHOP/ACTIVITIES and SHOP/MERCHANDISE - collect product or group data from the DOM  */
    const pushActMerchSelectItem = function (listId, rowSelector) {
        let ecommerce = {};
        ecommerce.item_list_id = listId;
        ecommerce.item_list_name = gaFourListNames[listId];
        ecommerce.items = [];
        const $itemRow = $('#' + rowSelector);

        const promises = [];
        for (let i = 0; i <= $itemRow.length - 1; i++) {
            const $row = $($itemRow[i]);
            let item = {};
            item.affiliation = window.salesId + '-' + window.salesChannelName;
            item.currency = window.currencyCode;
            item.index = parseInt($row.data('position-order'), 10);
            item.item_id = $row.data('product-id').toString();
            item.item_name = $row.data('name');
            item.item_brand = $row.data('supplier-id') + '-' + $row.data('supplier-name');
            item.price = (ecommerce.item_list_id == 'shop-activities') ? parseFloat($row.data('price')) : parseFloat($row.data('pricenum'));
            item.variant = $row.data('package-id');

            promises.push(mapProductCategoryData($row.data('category'), item, ecommerce));
        }

        Promise.all(promises).then(function () {
            pushGAFourEvent('select_item', ecommerce);
        });
    };

    /* SHOP/LODGING - collect supplier data from the DOM  */
    const pushLodgingSelectItem = function (listId, rowSelector) {
        let ecommerce = {};
        ecommerce.item_list_id = listId;
        ecommerce.item_list_name = gaFourListNames[listId];
        ecommerce.items = [];
        const $itemRow = $('#' + rowSelector);
        let item = {};
        item.affiliation = window.salesId + '-' + window.salesChannelName;
        item.currency = window.currencyCode;
        item.item_category = '1';
        item.item_category2 = 'Lodging';
        item.item_category3 = '1';
        item.item_category4 = 'Lodging';
        item.index = $itemRow.data('product-position-order') ? parseInt($itemRow.data('product-position-order'), 10) : parseInt($itemRow.data('position-order'), 10);
        item.item_id = $itemRow.data('supplier-id').toString();
        item.item_name = $itemRow.data('product-supplier-name') ? $itemRow.data('product-supplier-name') : $itemRow.data('name');
        item.item_brand = item.item_id + '-' + item.item_name;
        item.price = $itemRow.data('price') ? parseFloat($itemRow.data('price')) : null;
        item.variant = $itemRow.data('package-id') || null;

        ecommerce.items.push(item);
        pushGAFourEvent('select_item', ecommerce);
    };

    /* SHOP/STAY - collect supplier data from the DOM  */
    const pushLodgingStaySelectItem = function (listId, rowSelector) {
        let ecommerce = {};
        ecommerce.item_list_id = listId;
        ecommerce.item_list_name = gaFourListNames[listId];
        ecommerce.items = [];
        const $itemRow = $('#' + rowSelector);
        $('.supplierTile').each(function (i) {
            if (!$(this).data('position-index')) {
                $(this).attr('data-position-index', i + 1);
            }
        });

        let item = {};
        item.affiliation = window.salesId + '-' + window.salesChannelName;
        item.currency = window.currencyCode;
        item.item_category = '1';
        item.item_category2 = 'Lodging';
        item.item_category3 = '1';
        item.item_category4 = 'Lodging';
        item.index = parseInt($itemRow.data('position-index'), 10);
        item.item_id = $itemRow.data('supplier-id').toString();
        item.item_name = $itemRow.data('name');
        item.item_brand = item.item_id + '-' + item.item_name;
        item.price = parseFloat($itemRow.data('price'));
        item.variant = $itemRow.data('package-id') || null;

        ecommerce.items.push(item);
        pushGAFourEvent('select_item', ecommerce);
    };

    /* BROWSE/CATALOG (Gryphon) */
    const pushGryphonSelectItem = function (ecommData) {
        let ecommerce = {
            item_list_id: 'activity-shopping',
            item_list_name: gaFourListNames['activity-shopping'],
            currency: window.currencyCode,
            items: []
        };

        let thisItem = {
            item_id: ecommData.productId,
            item_name: ecommData.productName,
            affiliation: `${window.salesId}-${window.salesChannelName}`,
            coupon: null,
            index: ecommData.listPosition,
            item_brand: `${ecommData.supplierId}-${ecommData.supplierName}`,
            categoryId: ecommData.productCategory,
            price: ecommData.price,
            variant: null
        };

        mapProductCategoryData(thisItem.categoryId, thisItem, ecommerce);

        pushGAFourEvent('select_item', ecommerce);
    };

    /* SHOP/CALENDAR - collect product data from the DOM  */
    const pushCalendarViewItem = function (listId) {
        let ecommerce = {};
        ecommerce.item_list_id = listId;
        ecommerce.item_list_name = gaFourListNames[listId];
        ecommerce.items = [];

        const promises = [];
        let $listItem = $('#optionsList .product-row:visible');
        for (let i = 0; i <= $listItem.length - 1; i++) {
            const $row = $($listItem[i]);
            let item = {};
            item.affiliation = window.salesId + '-' + window.salesChannelName;
            item.currency = window.currencyCode;
            item.index = i + 1;
            item.item_id = $row.data('product-id').toString();
            item.item_name = $row.data('name');
            item.item_brand = $row.data('supplier-id') + '-' + $row.data('supplier-name');
            item.price = parseFloat($row.data('price'));

            promises.push(mapProductCategoryData($row.data('category-id'), item, ecommerce));
        }

        Promise.all(promises).then(function () {
            pushGAFourEvent('select_item', ecommerce);
        });
    };

    /* SHOP/ACTIVITIES and SHOP/MERCHANDISE - collect product data from the DOM  */
    const pushActMerchViewItem = function (listId) {
        let ecommerce = {};
        ecommerce.item_list_id = listId;
        ecommerce.item_list_name = gaFourListNames[listId];
        ecommerce.items = [];
        let priceAtt = 'price';
        let rowSelector = (ecommerce.item_list_id == 'shop-activities') ? '.activityTileModal__productDetail' : '.merchandiseTileModal__productDetail';

        // if single product in modal, grab data from original product tile
        if ($(rowSelector).length == 1) {
            let $singleRow = $('tr[id^=productDetailRow-]');
            let suppId = $singleRow.data('supplier-id');
            let prodId = $singleRow.data('product-id');
            rowSelector = `#productTile-${suppId}-${prodId}`;
            // merchandise page uses different data attribute for price as number
            if(ecommerce.item_list_id == 'shop-merchandise'){
                priceAtt = 'pricenum';
            }
        }
        const promises = [];
        let $listItem = $(rowSelector);
        for (let i = 0; i <= $listItem.length - 1; i++) {
            const $row = $($listItem[i]);
            const suppId = $row.data('supplier-id');
            const prodId = $row.data('product-id');
            let item = {};
            item.affiliation = window.salesId + '-' + window.salesChannelName;
            item.brand = suppId + '-' + $row.data('supplier-name');
            item.currency = window.currencyCode;
            item.index = i + 1;
            item.item_id = prodId.toString();
            item.item_name = $row.data('name');

            item.price = parseFloat($row.data(priceAtt));
            
            item.variant = $row.data('package-id');

            promises.push(mapProductCategoryData($row.data('category'), item, ecommerce));
        }

        Promise.all(promises).then(function () {
            pushGAFourEvent('view_item', ecommerce);
        });
    };

    /* SHOP/STAY - collect product data from the DOM  */
    const pushLodgingStayViewItem = function (listId) {
        let ecommerce = {};
        ecommerce.item_list_id = listId;
        ecommerce.item_list_name = gaFourListNames[listId];
        ecommerce.items = [];
        $('.modalProductDetail').each(function (i) {
            const $modalItem = $(this);
            let item = {};
            item.affiliation = window.salesId + '-' + window.salesChannelName;
            item.currency = window.currencyCode;
            item.item_category = '1';
            item.item_category2 = 'Lodging';
            item.item_category3 = '1';
            item.item_category4 = 'Lodging';
            item.index = i + 1;
            item.item_id = $modalItem.data('product-id').toString();
            item.item_name = $modalItem.data('product-name');
            item.item_brand = window.supplierId + '-' + window.supplierName;
            item.price = parseFloat($modalItem.data('product-price'));

            ecommerce.items.push(item);
        });

        pushGAFourEvent('view_item', ecommerce);
    };

    /* receive products added and push event */
    const pushAddToCart = function (listId, itineraryId, item) {
        let ecommerce = {};
        
        ecommerce.item_list_id = listId;
        ecommerce.item_list_name = gaFourListNames[listId];
        ecommerce.location_id = itineraryId.toString();
        ecommerce.currency = window.currencyCode;
        ecommerce.items = [];
        ecommerce.value = null;
        const promises = [];
        $.each(item, function (i, v) {
            v.affiliation = window.salesId + '-' + window.salesChannelName;
            let value = v.quantity * v.price;
            ecommerce.value += value;
            let categoryId = v.categoryId || v.item_category3;
            promises.push(mapProductCategoryData(categoryId, v, ecommerce));
        });

        return Promise.all(promises).then(function () {
            return pushGAFourEvent('add_to_cart', ecommerce);
        });
    };

    const pushGryphonAddToCart = function (ecommData) {
        let ecommerce = {
            item_list_id: 'activity-shopping',
            item_list_name: gaFourListNames['activity-shopping'],
            location_id: ecommData.itineraryId,
            currency: window.currencyCode,
            value: ecommData.quantity * ecommData.price,
            items: []
        };

        let thisItem = {
            item_id: ecommData.productId,
            item_name: ecommData.productName,
            affiliation: `${window.salesId}-${window.salesChannelName}`,
            coupon: null,
            index: ecommData.listPosition,
            item_brand: `${ecommData.supplierId}-${ecommData.supplierName}`,
            categoryId: ecommData.productCategory,
            price: ecommData.price,
            quantity: ecommData.quantity,
            variant: null
        };

        mapProductCategoryData(thisItem.categoryId, thisItem, ecommerce);

        pushGAFourEvent('add_to_cart', ecommerce);
    };

    /* receive products added, collect product data from the DOM and push event */
    const pushAirAddToCart = function (listId, itineraryId, item) {
        let ecommerce = {};
        ecommerce.item_list_id = listId;
        ecommerce.item_list_name = gaFourListNames[listId];
        ecommerce.location_id = itineraryId.toString();
        ecommerce.currency = window.currencyCode;
        ecommerce.affiliation = window.salesId + '-' + window.salesChannelName;
        ecommerce.items = [];
        let airItem = {};
        airItem.item_category = '4';
        airItem.item_category2 = 'Airfare';
        airItem.item_category3 = '113';
        airItem.item_category4 = 'Airfare';
        airItem.item_id = item.attr('name');
        airItem.item_brand = ecommerce.affiliation;

        const $airData = $(item);
        let departureSegmentName = 'dep-';
        let returnSegmentName = 'ret-';
        let parser = new DOMParser();
        let depSegmentXml = parser.parseFromString($airData.find("input[name='segment_1']:checked").val(), "application/xml");
        let retSegmentXml = parser.parseFromString($airData.find("input[name='segment_2']:checked").val(), "application/xml");
        $(depSegmentXml).find('AirSegSell').each(function () {
            let airline = $(this).find('Vnd').text();
            let fltNum = $(this).find('FltNum').text();
            departureSegmentName += airline + '-' + fltNum + ' ';
        });
        $(retSegmentXml).find('AirSegSell').each(function () {
            let airline = $(this).find('Vnd').text();
            let fltNum = $(this).find('FltNum').text();
            returnSegmentName += airline + '-' + fltNum + ' ';
        });
        airItem.item_name = departureSegmentName + ':' + returnSegmentName;
        airItem.item_price = parseFloat($airData.find("input[name='price']").val());
        airItem.item_quantity = parseFloat($airData.find("input[name='passengercount']").val());
        ecommerce.value = airItem.item_price;

        ecommerce.items.push(airItem);

        pushGAFourEvent('add_to_cart', ecommerce);
    };

    /* receive products removed and collect product data from the DOM  */
    const pushRemoveFromCart = function (itineraryId, item) {
        let ecommerce = {};
        ecommerce.location_id = itineraryId.toString();
        ecommerce.currency = window.currencyCode;
        ecommerce.items = [];
        ecommerce.value = null;

        const promises = [];
        $.each(item, function (i, v) {
            let value = v.quantity * v.price;
            ecommerce.value += value;

            let thisItem = {};
            thisItem.item_id = v.item_id;
            thisItem.index = v.index;
            thisItem.item_name = v.item_name;
            thisItem.item_brand = v.item_brand;
            thisItem.affiliation = window.salesId + '-' + window.salesChannelName;
            thisItem.price = v.price;
            thisItem.quantity = v.quantity;
            thisItem.variant = v.variant;

            promises.push(mapProductCategoryData(v.productCategory, thisItem, ecommerce));
        });

        Promise.all(promises).then(function () {
            pushGAFourEvent('remove_from_cart', ecommerce);
        });
    };

    /* CHECKOUT/BILLINGINFORMATION - collect product data from the DOM  */
    const pushBeginCheckout = function () {
        let ecommerce = {};
        ecommerce.location_id = $('#itineraryId').text();
        ecommerce.currency = window.currencyCode;
        ecommerce.items = [];
        ecommerce.value = null;



        const promises = [];
        $('.itinerary-item').each(function () {
            let $this = $(this);
            let thisItem = {};
            
            let nights = 1;
            if ($this.data('category') == 1) {
                let itinItemId = $this.attr('id').split('-')[1];
                let $lodgingDateEl = $('#lodgingData-' + itinItemId);
                let ad = moment($lodgingDateEl.data('arrival-date'));
                let dd = moment($lodgingDateEl.data('departure-date'));
                nights = dd.diff(ad, 'days');
            }

            thisItem.item_id = $this.data('product-id').toString();
            thisItem.index = parseInt($this.data('positionindex'), 10);
            thisItem.item_name = $this.data('name');
            thisItem.item_brand = $this.data('supplier-id') + '-' + $this.data('supplier-name');
            thisItem.affiliation = window.salesId + '-' + window.salesChannelName;
            thisItem.price = parseFloat($this.data('price')) / ($this.data('quantity') * nights);
            thisItem.discount = (parseFloat($this.data('original-price') - $this.data('price'))) / nights;
            thisItem.quantity = $this.data('quantity') * nights;
            thisItem.variant = $this.data('package') ? $this.data('package').toString() : null;
            thisItem.coupon = $this.data('promocode') || null;
            let value = thisItem.quantity * thisItem.price;
            ecommerce.value += value;

            promises.push(mapProductCategoryData($this.data('category'), thisItem, ecommerce));
        });

        Promise.all(promises).then(function () {
            pushGAFourEvent('begin_checkout', ecommerce);
        });
    };

    /* CHECKOUT/REVIEW page - two events moved from checkout/billinginformation page */
    const pushAddShippingInfo = function (shippingInfoData) {
        pushGAFourEvent('add_shipping_info', shippingInfoData);
    }

    const pushAddPaymentInfo = function (paymentInfoData) {
        pushGAFourEvent('add_payment_info', paymentInfoData);
    }

    /* CHECKOUT/CONFIRM page */
    const pushPurchase = function (purchaseData) {
        pushGAFourEvent('purchase', purchaseData);
    }

    const mapProductCategoryData = function (categoryId, thisItem, ecommerce) {
        return $.ajax({
            type: "GET",
            url: '/ecomm/api/product/categorytree',
            data: {
                categoryId: categoryId
            }
        })
        .pipe(results => {
            let catTree = {};
            catTree.item_category = results.superCategoryId.toString();
            catTree.item_category2 = results.superCategoryName;
            catTree.item_category3 = results.categoryID.toString();
            catTree.item_category4 = results.categoryName;

            delete thisItem.categoryId;

            Object.assign(thisItem, catTree);
            ecommerce.items.push(thisItem);
        });
    };

    return {
        pushLodgingItemListView: pushLodgingItemListView,
        pushActMerchItemListView: pushActMerchItemListView,
        pushSuppDetItemListView: pushSuppDetItemListView,
        pushAirItemListView: pushAirItemListView,
        pushItemListViewAndSelectedProduct: pushItemListViewAndSelectedProduct,
        pushActMerchSelectItem: pushActMerchSelectItem,
        pushLodgingSelectItem: pushLodgingSelectItem,
        pushLodgingStaySelectItem: pushLodgingStaySelectItem,
        pushCalendarViewItem: pushCalendarViewItem,
        pushActMerchViewItem: pushActMerchViewItem,
        pushLodgingStayViewItem: pushLodgingStayViewItem,
        pushAddToCart: pushAddToCart,
        pushRemoveFromCart: pushRemoveFromCart,
        pushGryphonAddToCart: pushGryphonAddToCart,
        pushAirAddToCart: pushAirAddToCart,
        pushBeginCheckout: pushBeginCheckout,
        pushAddShippingInfo: pushAddShippingInfo,
        pushAddPaymentInfo: pushAddPaymentInfo,
        pushPurchase: pushPurchase
    }
})();;
