saffire.angular.app.directive('sfCartUpsell', ['$rootScope', '$timeout', function ($rootScope, $timeout) {


    function link(scope, element, attrs) {

        scope.siteBaseURL = SITEBASEURL;
        scope.showDetails = false;
        scope.detailItem;

        scope.getPriceRange = function (item) {
            if (item.ProductType == 0 || item.ProductType == 50) {
                return item.DisplayPrice;

            } else if (item.ProductType == 10) {
                var items = [];

                angular.forEach(item.Children, function (subItemChild) {

                    angular.forEach(subItemChild.Children, function (v) {

                        var priceTypeItem = $.grep(items, function (c) {
                            return c.seatmapCategoryID == v.SeatmapCategoryID && c.ticketTypeID == v.TicketTypeID;
                        })[0];

                        if (!priceTypeItem) {
                            var priceTypeItem = {
                                seatmapCategoryID: v.SeatmapCategoryID,
                                ticketTypeID: v.TicketTypeID,
                                price: v.DisplayPrice
                            };

                            items.push(priceTypeItem);

                        } else {
                            priceTypeItem.price += v.DisplayPrice;
                        }
                    })
                })

                var min = Math.min.apply(Math, items.map(function (i) { return i.price }));
                var max = Math.max.apply(Math, items.map(function (i) { return i.price }));
                return [min, max];

            } else {
                var priceTypePrices = [];

                angular.forEach(item.Children, function (optionItem) {
                    priceTypePrices.push(optionItem.DisplayPrice);
                });
                var min = Math.min.apply(Math, priceTypePrices);
                var max = Math.max.apply(Math, priceTypePrices);
                return [min, max];
            }
        }

        scope.addToCart = function ($event, item) {
            if ($event.type === 'click' || $event.type === 'touchend' || $event.which === 13) {
                if ((item.ProductType !== 30) && (item.ProductType !== 50) && (item.ProductType !== 10)) {
                    var addToCartRequest = { itemID: -1, mainProductID: item.ProductID, inCheckout: true, isCartUpsell: true, options: [{ productID: item.ProductID, qty: "1" }] };
                    scope.addCartItem($(this), addToCartRequest);
                } else {  // if ga product
                    if (scope.showDetails === false) { // if product detail not showing
                        scope.showDetails = true;
                        scope.detailItem = item;

                        angular.forEach(item.Children, function (optionItem) {
                            if (!optionItem.selectedQty) {
                                optionItem.selectedQty = "QTY";
                            }
                        });

                    } else { // if product detail are showing / add to cart button clicked from within product details
                        var totalQtyAdded = 0;
                        var addToCartRequest = { itemID: -1, mainProductID: item.ProductID, inCheckout: true, isCartUpsell: true, options: [] }

                        if (item.ProductType == 50) {
                            var qty = "1";

                            addToCartRequest.subProducts = [];
                            addToCartRequest.options.push({ productID: item.ProductID, qty: qty });

                            totalQtyAdded += qty;


                            angular.forEach(item.Children, function (subProductItem) {

                                var subProduct = { productID: subProductItem.ProductID, options: [] };

                                $(subProductItem.Children).each(function (i, ttp) {

                                    subProduct.options.push({ productID: ttp.ProductID, quantity: ttp.Qty });
                                })

                                addToCartRequest.subProducts.push(subProduct);
                            })
                        } else {

                            angular.forEach(item.Children, function (optionItem) {
                                var productID = optionItem.ProductID;
                                var qty = 0;

                                var ddlQty = optionItem.selectedQty;

                                if (ddlQty) {
                                    qty = ddlQty;
                                    if (qty < 0) {
                                        qty = 0;
                                    }
                                }

                                if (qty > 0) {
                                    addToCartRequest.options.push({ productID: productID, qty: qty });
                                    totalQtyAdded = totalQtyAdded + qty;
                                }
                            })
                        }

                        if (totalQtyAdded <= 0) {
                            alert("Quantity is required");
                        } else if (totalQtyAdded > item.MaxQty) {
                            alert(item.MaxQty + " per order limit.");
                        } else {
                            scope.addCartItem($(this), addToCartRequest);
                            scope.showDetails = false;
                        }
                    }

                }
            }
        }

        scope.cancelAddItem = function ($event) {
            if ($event.type === 'click' || $event.type === 'touchend' || $event.which === 13) {
                scope.showDetails = false;
            }
        }

        scope.$watch('swiperOptions.pluginOptions', function (newVal, oldVal) {

            if (scope.swiperOptions && scope.swiperOptions.pluginOptions) {
                if (scope.swiper) {
                    scope.swiper.destroy(true, true);
                }

                $timeout(function () {
                    scope.swiper = new Swiper('.swiper-container-' + scope.swiperOptions.swiperID, scope.swiperOptions.pluginOptions);
                }, 100)

            }
        }, true);


        scope.$watch('isRendered', function (newVal, oldVal) {

            if (scope.isRendered) {

                $timeout(function () {
                    scope.updateSwiper();
                }, 100)

            }

        });

        scope.updateSwiper = function () {

            scope.swiper.update();

            $timeout(function () {
                $('.checkout-upsell__content').css('opacity', 1);
            }, 300)


        }

        scope.$watch('upsellItems', function (newVal, oldVal) {

            $('.checkout-upsell__content').css('opacity', 0);

        });

        //swiperLastUpdated property can be used to update swiper from outside of cart upsell directive,
        //one example is Cart Checkout page, which needs to update swiper depends on its opened in Modal OR Inline

        scope.$watch('swiperOptions.swiperLastUpdated', function (newVal, oldVal) {

		    if (scope.swiper && scope.swiperOptions.swiperLastUpdated && newVal != oldVal) {
                $timeout(function () {
                    scope.swiper.activeIndex = 0;
                    scope.updateSwiper();
                }, 500)
            }

        });


    }

    return {
        scope: {
            cart: '=',
            cartItem: '=',
            upsellItems: '=',
            addCartItem: '=',
            isRendered: '=',
            updateCartItem: '&',
            swiperOptions: '='
        },
        templateUrl: SITEBASEURL + 'core/content/angular/cart/cartUpsell/cartUpsell.html?sv=' + SITEVERSION,
        link: link
    }


}]);

saffire.angular.app.directive('sfCartUpsellItem', ['$timeout', function ($timeout) {

    function link(scope, element, attrs) {

        if (scope.last === true) {
            $timeout(function () {
                scope.$evalAsync(function () {

                    scope.updateSwiper();

                }, 1)
            })
        }

    };

    return {
        restrict: 'A',
        scope: {
            updateSwiper: '=',
            last: '=',
        },
        link: link
    };
}]);

saffire.angular.app.filter('range', function () {
    return function (input, min, max) {
        min = parseInt(min); //Make string input int
        max = parseInt(max);
        input.push("QTY");
        for (var i = min; i <= max; i++)
            input.push(i);
        return input;
    };
});


