/* Minification failed. Returning unminified contents.
(9545,21-42): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: currentSelectedItemId
(6684,17-27): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: hpciStatus
(6048,2-14): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: StoreLocator
(5427,1-12): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: StoreFinder
(4970,1-17): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: getCheckoutScope
(2970,17-27): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: hpciStatus
 */
/*global GlobalConstants:false */

'use strict';

/**
 * Singleton instance for global constants used in the merchant site
 */
var globalConstants = new GlobalConstants(
/* The following constants should be set per merchant.  There are also default constants in platformConstants.js that can be overridden if desired.
 * These are loaded into Angular and are accessible via siteConfiguration.getValue('rootUrl')
 * If you need to access these constants from non-angular code, you can call this method directly using getSiteConstants().rootUrl
 * See https://docs.orderdynamics.net/projects/OrderDynamics/Dev%20Wiki/Origin%20Change%20Constants.aspx for additional details
*/
(function getSiteConstants() {
    return {
        rootUrl:  '', //'/Mastermind.Web', // ** EMPTY for prod/sandbox **       //  /Mastermind.Web.Phase-1
        searchURL: '', //'/Mastermind.Web', // ** EMPTY for prod/sandbox **       //  /Mastermind.Web.Phase-1
        disableLocationServices: true,
        disableAjaxRequestCache: true,
        currentCenturyYearForCreditCard: 2000,
        digitalGiftCardShippingMethod: "E-Delivery",
        shoppingCartModalPDPTemplateUrl: '/ShoppingCartSpa/CartModalPDP',
        shoppingCartPDPTemplateUrl: '/ShoppingCartSpa/ViewCartPDP',
        miniCartModalTemplateUrl: '/ShoppingCartSpa/MiniCartModal',
        miniCartTemplateUrl: '/ShoppingCartSpa/ViewMiniCart',
        productReviewsTemplateUrl: '/ProductSpa/ProductReviews',
        addGiftCardItemToShoppingCartUrl: '/Api/ShoppingCart/AddGiftCardItem',
        checkoutItemsListingTemplateUrl: '/CheckoutSpa/ItemListing',
        checkoutOrderSummaryTemplateUrl: '/CheckoutSpa/Summary',
        mmtCheckoutButtonTemplateUrl: '/ShoppingCartSpa/MmtCheckoutButton',
        mmtAddressFormTemplateUrl: '/CheckoutSpa/MmtCustomForm',
        mmtBillingAddressFormTemplateUrl:'/CheckoutSpa/MmtBillingForm',
        confirmPaymentTemplateUrl: '/ConfirmSpa/Payment',
        checkCustomerEmailExistUrl: '/Account/CheckEmail',
        giftCardcheckoutTemplateUrl: '/CheckoutSpa/GiftCardCheckout',
        giftcardconfirmationPageUrl: '/Confirm/GiftCard',
        updateAccountUrl: '/api/Account/UpdateAccount',
        updateGuestAccountUrl: '/api/Account/UpdateGuestAccount',
        cartProductConfigTemplateUrl: '/ProductSpa/CartProductConfig',
        giftWrapTemplateUrl: '/ShoppingCartSpa/GiftWrapModal',
        getGiftWrapItemsUrl: '/Api/ShoppingCart/GetGiftWrapItems',
        getGiftWrapDataUrl: '/Api/ShoppingCart/GetGiftWrapData',
        addGiftWrapItemToShoppingCartUrl: '/Api/ShoppingCart/AddGiftWrapItem',
        updateGiftWrapItemUrl: '/Api/ShoppingCart/UpdateGiftWrapItem',
        productCartPersonalizationUrl: '/ProductSpa/ProductCartPersonalization',
        removeGiftWrapItemFromShoppingCartUrl: '/Api/ShoppingCart/RemoveGiftWrapItem',
        confirmGiftCardPageTemplateUrl: '/ConfirmSpa/ViewConfirmGiftCard',
        confirmGiftCardSummaryTemplateUrl: '/ConfirmSpa/GiftCardSummary',
        giftCardcheckoutSummaryTemplateUrl: '/CheckoutSpa/GiftCardCheckoutSummary',
        giftCardModalTemplateUrl: '/ShoppingCartSpa/GiftCardModal',
        digitalGiftCardModalTemplateUrl: '/ShoppingCartSpa/DigitalGiftCardModal',
        getGiftCardItemsUrl: '/Api/ShoppingCart/GetGiftCardItems',
        updatePhysicalGiftCardUrl: '/Api/ShoppingCart/UpdatePhysicalGiftCard',
        getDigitalCardDataUrl: '/Api/ShoppingCart/GetDigitalCardData',
        updateDigitalGiftCardUrl: '/Api/ShoppingCart/UpdateDigitalGiftCard',
        addExistingCreditCardPaymentUrl: '/api/Checkout/AddExistingCreditCardPayment',
        getCustomerAddressesUrl: '/api/Checkout/GetShippingAddressesCheckout',
        newShippingAddressTemplateUrl: '/CheckoutSpa/NewShippingAddress',
        checkoutEditShippingAddressTemplateURL: '/Checkout/EditShippingAddress?shippingId={0}',
        checkoutPaymentPhoneNumberURL: '/api/Checkout/AddOrderPaymentPhoneNumber',
		setCurrentOrderFormApiUrl: '/api/Checkout/SetCurrentOrderForm',
		shoppingCartPageUrl: '/shoppingcart',
        addMMTPayPalOptionUrl: '/api/Checkout/AddMMTPayPalOption',
        proceedToPlaceOrderUrl: '/api/Checkout/ProceedToPlaceOrder',
        subscribeMailChimpUrl: '/Newsletter/SubscribeCreateAccount',
        //Ups - to do
        upsApiUrl: '/api/UpsLocator',
        getNearestUpsLocationApiUrl: '/api/UpsLocator/GetNearestUpsLocation',
        getUpsLocationApiUrl: '/api/UpsLocator/GetUpsLocations',
        upsShippingRateId:14,
        upsShippingRateIdUs:15,
        shippingStoreLocationTemplateUrl: '/CheckoutSpa/ShippingStoreLocation', 
        //RIS
        validateCaptchaUrl: '/api/Recaptcha/ValidateCaptcha',
        risCheckoutItemsListingTemplateUrl: '/CheckoutSpa/RISItemListing',
        risContactTemplateUrl: '/CheckoutSpa/RISContact',
        rIScheckoutTemplateUrl: '/CheckoutSpa/RISCheckout',
        risconfirmationPageUrl: '/Confirm/ReserveInStore',
        rischeckoutSummaryTemplateUrl: '/CheckoutSpa/RISCheckoutSummary',
        risConfirmContactTemplateUrl: '/ConfirmSpa/ContactRIS',
        risConfirmStoreTemplateUrl: '/ConfirmSpa/StoreSelection',
        confirmRISPageTemplateUrl: '/ConfirmSpa/ViewConfirmRIS',
        checkoutRISPhoneNumberURL: '/api/Checkout/AddRISPhoneNumber',	
        addItemToReserveUrl: '/Api/ShoppingCart/AddItemToReserve',
        loadItemsStoreInventoryDataUrl: '/Stores/GetStoresAndInventoryForAllCartItems',
        //Perks, Happy Card
        happyCardTemplateUrl: '/CheckoutSpa/HappyCard',
        redeemAPerkTemplateUrl: '/CheckoutSpa/RedeemAPerk',
        submitPerkCodeUrl: '/api/Checkout/SubmitPerkCode',
        cancelPerkCodeUrl: '/api/Checkout/CancelPerkCode'
		
    };
})());

/**
 * Override platform configuration  provider, so that now we can use our custom constants.
 */
angular.module('appConfiguration', [])
.provider('siteConfiguration',
   function () {
       return {
           $get: function () {
               return globalConstants;
           }
       };
   }
);;
/*global GlobalLocalization:false */
/*global getLocalizations:false */

'use strict';

/**
 * Singleton instance for global localization used in the merchant site
 */
var res = new GlobalLocalization(getLocalizations());

/**
 * Override platform localization  provider, so that now we can use our custom constants.
 */
angular.module('shared').provider('siteRes',
    function () {
        return {
            $get: function () {
                return res;
            }
        };
    });;
/*global getCurrentCulture:false */

'use strict';

//var culture = (function() {
//    return getCurrentCulture();
//})();

/**
 * Override platform culture provider to get the current culture.
 */
angular.module('shared').provider('siteCulture',
    function () {
        return {
            $get: function () {
                return { currentCulture: "en" };
            }
        };
    });;
'use strict';

angular.module('shared')
.provider('appUrlBuilder',
   function () {

       var builder = function (siteConfiguration, siteCulture) {
           return {
               buildUrl: function (key) {
                   return siteConfiguration.rootUrl + siteConfiguration[key];
               },
               buildTemplateUrl: function (key) {
                   if (siteCulture.currentCulture === "en")
                       return siteConfiguration.rootUrl + siteConfiguration[key];
                   return siteConfiguration.rootUrl + '/' + siteCulture.currentCulture + siteConfiguration[key];
               },
               buildUniqueTemplateUrl: function (key) {
                   //Bug 19856: adding a time string at the end to trick IE so it call back every time
                   //Fixed by change set 47733
                   if (siteCulture.currentCulture === "en")
                       return siteConfiguration.rootUrl +  siteConfiguration[key];
                   return siteConfiguration.rootUrl + '/' + siteCulture.currentCulture + siteConfiguration[key];
               }
           };
       };

       return {
           $get: ['siteConfiguration', 'siteCulture', function (siteConfiguration, siteCulture) {
               return builder(siteConfiguration, siteCulture);
           }]
       };
   }
);;
/*global $, CartHelper, res, globalConstants, PasswordHelper:false */
/*exported CartChangedListener */
'use strict';

/**
 * Creating global helper instances. Scope is Origin.
 *      globalCartHelper: Contains methods for adding to cart, toggling cart display, etc.
 *      passwordHelper: Contains methods for toggling the view mode of password elements (plain or masked)
 */

var globalCartHelper;
var passwordHelper;

$(document).ready(function () {
    globalCartHelper = new CartHelper(res, globalConstants);
    passwordHelper = new PasswordHelper();
});

function CartChangedListener(cartData) {
    if (globalCartHelper) {
        globalCartHelper.OnCartChanged(cartData);
    }
};

'use strict';

/**
 * Provides general cart helper methods, e.g. toggling shipping cart display, adding to cart button and change cart event
 */

var CartHelper = (function ($, bsd) {

    var localization;
    var cartAppId;
    var cartModalId;
    var cartSmallBadgeId;
    var cartLargeBadgeId;
    var addToCartButtonIdPrefix;
    var productAppId;


    function CartHelper(localizations, constants) {
        localization = localizations;
        cartAppId = constants.CartAppId;
        productAppId = constants.ProductAppId;
        cartModalId = constants.CartModalId;
        cartSmallBadgeId = constants.CartSmallBadgeId;
        cartLargeBadgeId = constants.CartLargeBadgeId;
        addToCartButtonIdPrefix = constants.AddToCartButtonIdPrefix;
    }

    CartHelper.prototype.ToggleShopingCart = function () {
        var scope = angular.element('#' + cartAppId).scope();

        if (scope.$root && scope.$root.isCartEmpty && scope.$root.isCartEmpty()) {
            bsd.show({
                title: '',
                message: '<h2 class="text-center fade-text">' + localization.CartEmpty + '</h2>',
                buttons: [{ label: 'Close', action: function (dialogItself) { dialogItself.close(); } }],
                onshown: function (dialogRef) {
                    window.setTimeout(function () {
                        if (dialogRef && dialogRef.close) {
                            dialogRef.close();
                        }
                    }, 2000);
                },
            });
            return false;
        }

        scope.showCart();
        return false;
    };

    CartHelper.prototype.TogglePDPShopingCart = function (qty, price, name, img, isGiftCard, giftCardType) {

        var scope = angular.element('#' + cartAppId).scope();

        scope.$root.addedItem = true;
        scope.$root.addedItemName = name;
        scope.$root.addedItemImg = img;
        scope.$root.addedItemQty = qty;
        scope.$root.addedItemPrice = price;
        scope.$root.cartHasGiftCard = isGiftCard;
        scope.$root.cartHasDigitalGiftCard = (isGiftCard && giftCardType.toLowerCase() == 'digital');
        scope.$root.cartHasPhysicalGiftCard = (isGiftCard && giftCardType.toLowerCase() == 'physical');
        scope.$root.giftCardType = giftCardType;
        scope.$root.cart = scope.$root.getCartData();

        scope.showCartPDP();
        return false;
    };

    CartHelper.prototype.ToggleMiniCart = function () {
        var scope = angular.element('#' + cartAppId).scope();

        if (scope != undefined && scope.$root && scope.$root.isCartEmpty && scope.$root.isCartEmpty()) {
            bsd.show({
                title: '',
                message: '<h2 class="text-center fade-text">' + 'Your Cart is empty – so far. <br> You know what to do!' + '</h2>',
                buttons: [{ label: 'Close', action: function (dialogItself) { dialogItself.close(); } }],
                onshown: function (dialogRef) {
                    window.setTimeout(function () {
                        if (dialogRef && dialogRef.close) {
                            dialogRef.close();
                        }
                    }, 4000);
                },
            });
            return false;
        }

        if (scope != undefined && scope.showMiniCart) {
            scope.showMiniCart();
        }

        return false;
    };

    //Array.prototype.move = function (from, to) {
    //    this.splice(to, 0, this.splice(from, 1)[0]);
    //};

    CartHelper.prototype.ToggleMiniCartAddedItem = function (qty, price, name, img, productId, isGiftCard, giftCardType) {
        var scope = angular.element('#' + cartAppId).scope();

        if (scope != undefined && scope.$root) {

            scope.$root.cart = scope.$root.getCartData();
            
            scope.$root.addedItem = true;
            scope.$root.addedItemIsGiftCard = isGiftCard;
            scope.$root.addedItemQty = qty;
            scope.$root.cartHasGiftCard = isGiftCard;
            scope.$root.cartHasDigitalGiftCard = (isGiftCard && giftCardType.toLowerCase() == 'digital');
            scope.$root.cartHasPhysicalGiftCard = (isGiftCard && giftCardType.toLowerCase() == 'physical');
            scope.$root.giftCardType = giftCardType;

            scope.$root.addedItemName = name;
            scope.$root.addedItemProdId = productId;
            scope.$root.addedItemPrice = price;
            scope.$root.addedItemOriginalPrice = price;
            var imgUrl = "";
            //try{
                if (scope.$root.cart.isLoaded && scope.$root.cart.items && scope.$root.cart.items.length > 0) {
                    var addIndex=0;
                    for(var i = 0, l = scope.$root.cart.items.length ; i < l; i ++ ){
                        if (scope.$root.cart.items[i].ProductId === productId && scope.$root.addedItemId === scope.$root.cart.items[i].ItemId) {
                            addIndex = i;
                            var itm = scope.$root.cart.items[i];
                            if( itm.UnitPrice < itm.OriginalPrice){
                                scope.$root.addedItemPrice = itm.UnitPrice;
                                scope.$root.addedItemOriginalPrice = itm.OriginalPrice;
                            }
                            else{
                                scope.$root.addedItemProdId=0; 
                            }

                            if (itm.MarketingHtml != undefined && itm.MarketingHtml.length > 0) {
                                scope.$root.addedItemMarketingHtml = itm.MarketingHtml;
                            }

                            imgUrl = itm.ImagerUrl;
                            break;
                        }
                    }
                    if (addIndex!==0)
                        scope.$root.cart.items.splice(0, 0, scope.$root.cart.items.splice(addIndex, 1)[0]); 
                    //scope.$root.cart.items.move(addIndex,0);
                }
            //}
            //catch (e) {
            //    console.log("ToggleMiniCartAddedItem error:" + e);
            //}
 
            if (imgUrl == "") {
                imgUrl  =  rootRel + 'ImageHandler.axd?ownerTable=products&ownerId=' + productId + '&width=90&height=90&constraint=3&interpolate=7&async=True';
            }

            scope.$root.addedItemImg = imgUrl;
        }

        if (scope.$root.cartHasDigitalGiftCard === true) {
            window.location.href = rootRel + "Checkout/GiftCard";
            return false;
        }


        if (scope != undefined && scope.showMiniCart) {
            scope.showMiniCart();
        }

        return false;
    };

    CartHelper.prototype.IsCartEmpty = function () {
        var scope = angular.element('#' + cartAppId).scope();

        if (scope != undefined && scope.$root && scope.$root.isCartEmpty && scope.$root.isCartEmpty()) {
            return true;
        }

        return false;
    };
    CartHelper.prototype.ReturnCartData = function () {
        var scope = angular.element('#' + cartAppId).scope();
        return scope.$root.getCartData();
    };
    CartHelper.prototype.CartHasGiftCard = function () {
        var scope = angular.element('#' + cartAppId).scope();

        if (scope != undefined && scope.$root && scope.$root.cartHasGiftCard && scope.$root.cartHasGiftCard()) {
            return true;
        }

        return false;
    };

    CartHelper.prototype.CartHasDigitalGiftCard = function () {
        var scope = angular.element('#' + cartAppId).scope();

        if (scope != undefined && scope.$root && scope.$root.cartHasDigitalGiftCard && scope.$root.cartHasDigitalGiftCard()) {
            return true;
        }

        return false;
    };

    CartHelper.prototype.CartHasPhysicalGiftCard = function () {
        var scope = angular.element('#' + cartAppId).scope();

        if (scope != undefined && scope.$root && scope.$root.cartHasPhysicalGiftCard && scope.$root.cartHasPhysicalGiftCard()) {
            return true;
        }

        return false;
    };

    // btnAddToCart
    CartHelper.prototype.AddToCart = function (itemId, productId, hasPersonalization, autoship, quantity, enableItemSelection, price, name, img) {

        var price = (typeof price !== 'undefined') ? price: 0;
        var name  = (typeof name !== 'undefined') ? name : "";
        var img   = (typeof img !== 'undefined') ? img: null;

        if (this.CartHasDigitalGiftCard())
        {
            bsd.show({
                title: '',
                message: '<h2 class="text-center fade-text">' +
                    'Your Shopping Cart has a Digital Gift Card... please proceed to checkout to purchase the gift card first before adding other items.' +
                    '</h2>',
                buttons: [
                    {
                        label: 'Close',
                        action: function (dialogItself) {
                            dialogItself.close();
                        }
                    }
                ]
            });

            return false;
        }
        else if ((window.digitalGiftCardItemIds != null && $.inArray(itemId, window.digitalGiftCardItemIds) > -1) && !this.IsCartEmpty())
        {
            bsd.show({
                title: '',
                message: '<h2 class="text-center fade-text">' +
                    'Your Shopping Cart must be Empty to purchase a Digital Gift Card... please complete checkout first before adding this gift card.' +
                    '</h2>',
                buttons: [
                    {
                        label: 'Close',
                        action: function (dialogItself) {
                            dialogItself.close();
                        }
                    }
                ]
            });

            return false;
        }
        else
        {
            var scope = angular.element('#' + cartAppId).scope();

            scope.$root.addedItemId = itemId;

            scope.addToCart({
                itemId: itemId,
                hasPersonalization: hasPersonalization,
                productId: productId,
                Quantity: quantity,
                Autoship: autoship,
                enableItemSelection: enableItemSelection
            }).then(
                function () {
                    //globalCartHelper.ToggleMiniCart();
                    globalCartHelper.ToggleMiniCartAddedItem(quantity, price, name, img, productId, false, "");   //(quantity, price, name, img, productId, isGiftCard, giftCardType);
                },
                function (error) {
                    if (error !== 'cancel') { //if we canceled - we do not show any error message
                        bsd.show({
                            title: 'You have added ' + quantity + ' items',
                            //message: '<h2 class="text-center fade-text">' + localization.CannotAddToCart + '</h2>',
                            //You cannot add this item to your cart today. It may be out of stock or otherwise unavailable
                            message: '<h2 class="text-center fade-text">' +error + '</h2>',
                            buttons: [
                                {
                                    label: 'Close',
                                    action: function (dialogItself) {
                                        dialogItself.close();
                                    }
                                }
                            ]
                        });
                    }
                });
            return false;
        }
    };

    CartHelper.prototype.AddToCartCarousel = function (itemId, productId, hasPersonalization, autoship, quantity, enableItemSelection) {

        if (this.CartHasDigitalGiftCard())
        {
            bsd.show({
                title: '',
                message: '<h2 class="text-center fade-text">' +
                    'Your Shopping Cart has a Digital Gift Card... please proceed to checkout to purchase the gift card first before adding other items.' +
                    '</h2>',
                buttons: [
                    {
                        label: 'Close',
                        action: function (dialogItself) {
                            dialogItself.close();
                        }
                    }
                ]
            });

            return false;
        }
        else if ((window.digitalGiftCardItemIds != null && $.inArray(itemId, window.digitalGiftCardItemIds) > -1) && !this.IsCartEmpty())
        {
            bsd.show({
                title: '',
                message: '<h2 class="text-center fade-text">' +
                    'Your Shopping Cart must be Empty to purchase a Digital Gift Card... please complete checkout first before adding this gift card.' +
                    '</h2>',
                buttons: [
                    {
                        label: 'Close',
                        action: function (dialogItself) {
                            dialogItself.close();
                        }
                    }
                ]
            });

            return false;
        }
        else
        {
            var scope = angular.element('#' + cartAppId).scope();
            scope.$root.addedItemId = itemId;

            scope.addToCart({
                itemId: itemId,
                hasPersonalization: hasPersonalization,
                productId: productId,
                Quantity: quantity,
                Autoship: autoship,
                enableItemSelection: enableItemSelection
            }).then(
                function () {
                    //globalCartHelper.ToggleMiniCart();
                    globalCartHelper.ToggleMiniCartAddedItem(quantity, 0, "", null, productId, false, "");  //(qty, price, name, img, productId, isGiftCard, giftCardType);
                },
                function (error) {
                    if (error !== 'cancel') { //if we canceled - we do not show any error message
                        bsd.show({
                            title: '',
                            message: '<h2 class="text-center fade-text">' + localization.CannotAddToCart + '</h2>',
                            buttons: [
                                {
                                    label: 'Close',
                                    action: function (dialogItself) {
                                        dialogItself.close();
                                    }
                                }
                            ]
                        });
                    }
                });
            return false;
        }
    };
    
    // btnAddToCart
    CartHelper.prototype.AddGiftCardToCart = function (itemId, productId, price, qty, GiftCard_Message, GiftCard_DeliveryMethod,
                                                       GiftCard_SenderName, GiftCard_RecipientName, GiftCard_RecipientEmail, GiftCard_DeliveryDate) {

        var scope = angular.element('#' + cartAppId).scope();
        scope.$root.addedItemId = itemId;

        scope.addGiftCardToCart({
            itemId: itemId,
            hasPersonalization: false,
            productId: productId,
            Quantity: qty,
            Autoship: false,
            enableItemSelection: false,
            Price: price,
            'GiftCard_Message': GiftCard_Message,
            'GiftCard_DeliveryMethod': GiftCard_DeliveryMethod,
            'GiftCard_SenderName': GiftCard_SenderName,
            'GiftCard_RecipientName': GiftCard_RecipientName,
            'GiftCard_RecipientEmail': GiftCard_RecipientEmail,
            'GiftCard_DeliveryDate': GiftCard_DeliveryDate
        }).then(
            function () {
                //globalCartHelper.ToggleMiniCart();
                globalCartHelper.ToggleMiniCartAddedItem(qty, price, "", null, productId, true, (GiftCard_DeliveryMethod != "" ? "Digital" : "Physical"));  //(qty, price, name, img, productId, isGiftCard, giftCardType);
            },
            function (error) {
                if (error !== 'cancel') { //if we canceled - we do not show any error message
                    bsd.show({
                        title: '',
                        message: '<h2 class="text-center fade-text">' + localization.CannotAddToCart + '</h2>',
                        buttons: [
                            {
                                label: 'Close',
                                action: function (dialogItself) {
                                    dialogItself.close();
                                }
                            }
                        ]
                    });
                }
            });
        return false;
    };

    CartHelper.prototype.AddReserveItemToCart = function (itemId, quantity, reserveStoreId, productId, price, name, img) {
        //console.log("CartHelper > AddReserveItemToCart. ItemId: " + itemId + " | Quantity: " + quantity + " | ReserveStoreId: " + reserveStoreId + " | Img: " + img);

        var scope = angular.element('#' + cartAppId).scope();
        scope.$root.addedItemId = itemId;

        scope.addReserveItemToCart({
            ItemId: itemId,
            ProductId: productId,
            Price: price,
            Quantity: quantity,
            ReserveStoreId: reserveStoreId
        }).then(
            function () {
                globalCartHelper.ToggleMiniCartAddedItem(quantity, price, name, img, productId, false, "");
            },
            function (error) {
                if (error !== 'cancel') { 
                    bsd.show({
                        title: '',
                        message: '<h2 class="text-center fade-text">' + localization.CannotAddToCart + '</h2>',
                        buttons: [
                            {
                                label: 'Close',
                                action: function (dialogItself) {
                                    dialogItself.close();
                                }
                            }
                        ]
                    });
                }
            });
        return false;
    };

    // btnAddToCart
    CartHelper.prototype.OnCartChanged = function (cartData) {
        updateScoppingCartItemsCount(cartData);
        changeAddToCartButtonToAddedToCart(cartData);
        if (cartData.totalItemsCount == 0) {
            $("#appCart").removeClass("container-sm");
            $("#bestSellerCarousels").show();
            $("#cartAccessoriesCarousels").hide();
        } else {
            $("#appCart").addClass("container-sm");
            $("#bestSellerCarousels").hide();
            $("#cartAccessoriesCarousels").show();
        }
    };

    function updateScoppingCartItemsCount(cartData) {
        var value = cartData.totalItemsCount;
        $('#' + cartSmallBadgeId).text(value);
        $('#' + cartLargeBadgeId).text(value);
    }

    function changeAddToCartButtonToAddedToCart(cartData) {

        var pScope = angular.element('#' + productAppId).scope();
        var pScopeUpdated = false;
        angular.forEach(cartData.items, function (v) {
            var productId = v.ProductId;
            var isInTheCart = v.isDeleted !== true;
            var idSelector = '.' + addToCartButtonIdPrefix + productId;
            var btn = $(idSelector);
            if (isInTheCart === true) {
                //This change is not related to #132730. This is to remove the script error on cart page 
                if (pScope && pScope.productData && pScope.productData.selectedItem) {
                    pScope.productData.selectedItem.QuantityInCart = v.Quantity;
                }
                // if text is - added - do not it will change automatically to add another so do not do anything
                if (btn.text() !== localization.Added) {
                    btn.removeClass('btn-add-to-cart');
                    btn.addClass('btn-success');
                    btn.html(localization.AddAnother);
                }
            } else {
                btn.removeClass('btn-success');
                btn.addClass('btn-add-to-cart');
                btn.text(localization.AddToCart);
            }

            if (pScopeUpdated === false && isInTheCart === true && pScope && pScope.productData && pScope.productData.selectedItem && pScope.productData.id === productId) {
                pScope.productData.selectedItem.IsInCart = true;
                pScope.$apply();
                pScopeUpdated = true;
            }
        });

        if (pScopeUpdated === false && pScope && pScope.productData && pScope.productData.selectedItem) {
            pScope.productData.selectedItem.IsInCart = false;
            pScope.$apply();
        }
    }

    return CartHelper;

})(jQuery, BootstrapDialog);;;
angular.module("template/modal/window.html", []).run(["$templateCache", function ($templateCache) {
    $templateCache.put("template/modal/window.html",
      "<div tabindex=\"-1\" role=\"dialog\" class=\"modal fade\" ng-class=\"{in: animate}\" ng-style=\"{'z-index': 1050 + index*10, display: 'block'}\" ng-click=\"close($event)\">\n" +
      "    <div class=\"modal-dialog\" ng-class=\"{'modal-sm': size == 'sm', 'modal-lg': size == 'lg', 'modal-xl': size == 'xl'}\"><div class=\"modal-content\" ng-transclude></div></div>\n" +
      "</div>");
}]);;
'use strict';

/**
 * set the product configuration
 */
angular.module('product').controller('ProductConfigCtrl', ['$scope', '$modal', '$timeout', 'ProductSvc', 'ProductDataStorageService', 'jQueryService', 'siteRes', 'siteConfiguration',
    function ($scope, $modal, $timeout, productSvc, productDataStorageService, jQueryService, siteRes, siteConfiguration) {

        setTimeout(function () { initCustomForms(); }, 50);

        if (currentPageUrl.toLowerCase().indexOf("/shoppingcart") > -1) {
            $scope.showCanvasColor = false;
        } else {
            $scope.showCanvasColor = true;
        }

        //set product data reference to storage.
        $scope.productData = productDataStorageService.productData;
        $scope.selectedAutoShip = productDataStorageService.selectedAutoShip;
        $scope.quantity = productDataStorageService.quantity;

        // custom
        $scope.productData.noItemsFound = false;
        $scope.productData.isSelecting = true;
        $scope.productData.notFound = false;
        $scope.productData.giftCardValue = "A";
        if ($scope.$parent.giftCardType != null) {
            if ($scope.$parent.giftCardType.toLowerCase() === "physical")
                $scope.productData.giftCardValue = 50;
        }

        $scope.productData.giftCardValueNumberInput = false;
        var cartProductImageId = -1;

        /*
         * Get Product Configuration options Information
         * The Information includes:
         *    Items,
         *    Item Categories,
         *    Item Category Items,
         *    Auto ship information
         */
        productSvc.getProductConfig($scope.productId).$promise.then(function (value) {

            var cartHelper = new CartHelper(siteRes, siteConfiguration);
            $scope.productData.isCartEmpty = cartHelper.IsCartEmpty();
            $scope.productData.cartHasGiftCard = cartHelper.CartHasGiftCard();
            $scope.productData.cartHasDigitalGiftCard = cartHelper.CartHasDigitalGiftCard();
            $scope.productData.cartHasPhysicalGiftCard = cartHelper.CartHasPhysicalGiftCard();

            if (value.Items.length == 0)
            {
                $scope.productData.isSelecting = false;
                $scope.productData.noItemsFound = true;
                return;
            }

            if ($scope.defaultItemId) {
                var itemFound = false;

                angular.forEach(value.Items, function (i) {
                    if (i.Id === $scope.defaultItemId) {
                        itemFound = true;
                        $scope.selectedItem = i;
                    }
                });
                if (itemFound !== true) {
                    $scope.selectedItem = value.Items[0];

                }
            } else {
                $scope.selectedItem = value.Items[0];

            }

            $scope.selectedItem.QuantityInCart = 0;

            //error!!!
            //var cartDataLoaded = cartHelper.ReturnCartData();
            //if (cartDataLoaded.isLoaded && cartDataLoaded.items && cartDataLoaded.items.length > 0) {
            //    var addIndex = 0;
            //    for (var i = 0, l = cartDataLoaded.items.length ; i < l; i++) {
            //        if (cartDataLoaded.items[i].ProductId === $scope.selectedItem.ProductId && $scope.selectedItem.Id === cartDataLoaded.items[i].ItemId) {
            //            var itm = cartDataLoaded.items[i];
            //            $scope.selectedItem.QuantityInCart = itm.Quantity;
            //            break;
            //        }
            //    }
            //} 

            $scope.hasItemCategoryItems = value.HasItemCategoryItems;

            if (!value.HasItemCategoryItems) {
                $scope.productData.selectedItem = $scope.selectedItem;
                $scope.productData.singleUnitPrice = $scope.selectedItem.SingleUnitPrice;
            }

            $scope.quantity.value = (value.Items[0].MinQty === null || value.Items[0].MinQty <= 0 ? 1 : value.Items[0].MinQty);
            $scope.quantity.min = (value.Items[0].MinQty === null || value.Items[0].MinQty <= 0 ? 1 : value.Items[0].MinQty);
            $scope.quantity.max = (value.Items[0].MaxQty === null ? 2000000000 : value.Items[0].MaxQty);
            $scope.maxQuantity = value.Items[0].MaxQty||0;

            $scope.productItems = value.Items;
            $scope.itemCategories = value.ItemCategories;
            var pid = -1;
            angular.forEach($scope.itemCategories, function (cat) {

                if ($scope.defaultItemCategories) {

                    var found = false;
                    angular.forEach($scope.defaultItemCategories, function (defaultCat) {
                        if (defaultCat.CategoryId === cat.Id) {
                            if (cat.Items) {
                                angular.forEach(cat.Items, function (c) {
                                    if (c.Id === defaultCat.CategoryItemId) {
                                        found = true;
                                        cat.item = c;
                                        pid = c.Id;
                                    }
                                });
                            }
                        }
                    });
                    if (found !== true) {
                        cat.item = {};
                    }

                } else {
                    cat.item = {};
                }

            });



            $scope.autoships = value.Autoships;
            
            if ($scope.productItems.length == 1) {
                $scope.productData.isSelecting = false;
            }

            //Load color swatches
            $scope.GetProductSwatches($scope.productId);
            var mainImageHero = ""; 
            if (pid !== -1) { 
                angular.forEach($scope.productItems, function (item) {
                    if (item.CategoryMapping == pid) { 
                        $scope.GetProductSwatches($scope.productId);
                        mainImageHero = $('#image' + item.Id);
                        mainImageHero.attr("src", "");
                        $scope.loadImage(item);
                    }
                });
            } 
        });

        /*
         * When The combination of  the item categories changes, it will update the information in description, image and stock check section including:
         *  sale price,
         *  retail price,
         *  web id,
         *  retail price,
         *  image information,
         *  stock item id
         *  
         */
        $scope.handleCategoryItemChange = function () {            
            var selectedCategories = '';
            var count = 1;
            angular.forEach($scope.itemCategories, function (cat) {
                
                selectedCategories += cat.item.Id;
                if (count < $scope.itemCategories.length) {
                    selectedCategories += ',';
                }
                count++;

            });
            var isItemExist = false;
            angular.forEach($scope.productItems, function (item) {

                var selectedCategoriesArr = selectedCategories.split(',');
                var categoryMappingArr = item.CategoryMapping.split(',');

                if (item.CategoryMapping === selectedCategories || (jQueryService(selectedCategoriesArr).not(categoryMappingArr).length === 0 && jQueryService(categoryMappingArr).not(selectedCategoriesArr).length === 0)) {

                    isItemExist = true;

                    $scope.updateBasicInformation(item);
                }
            });
            if (!isItemExist) {
                if (selectedCategories.indexOf('undefined') > -1) {
                    $scope.updateBasicInformation(undefined);
                } else {
                    $scope.updateBasicInformation(null);
                }
            }
        };

        /*
         * When there is no item category, the drop down list of all the items still display and the index change will update related information including:
         *  sale price,
         *  retail price,
         *  web id,
         *  retail price,
         *  image information,
         *  stock item id
         */
        $scope.handleItemChange = function (selectedItem) {
            
            $scope.updateBasicInformation(selectedItem);
            
        };

        $scope.handleQuantityChange = function (userInput) {           
            try {             
                if ($scope.quantity.value == null) {                    
                    userInput = '1';
                }
                var validNumber = parseInt(userInput);
                if (validNumber < 0) {
                    validNumber = validNumber * (-1);
                }
                $scope.quantity.value = Math.round(validNumber);               
            }
            catch (ex) {
                $scope.quantity.value = '1';
            }            
        };

        /*Get Slider Image*/
        var sliderObj = jQuery('.js-slick-product-gallery').find('.slideset');
        var sliderImageObj = jQuery('.js-slick-product-gallery').find('.slideset img');
        /*
         * Update description section by selected item
         */
        $scope.updateBasicInformation = function (item)
        {
            if (item !== null && item !== undefined) {

                $scope.selectedItem = item;

                $scope.productData.selectedItem = item;

                $scope.quantity.value = (item.MinQty === null || item.MinQty <= 0 ? 1 : item.MinQty);
                $scope.quantity.min = (item.MinQty === null || item.MinQty <= 0 ? 1 : item.MinQty);
                $scope.quantity.max = (item.MaxQty === null ? 2000000000 : item.MaxQty);

                $scope.productData.singleUnitPrice = item.SingleUnitPrice;

                if ($scope.fireSelectedItemChanged) {
                    $scope.fireSelectedItemChanged(item);
                }

                $scope.productData.isSelecting = false;
                $scope.productData.notFound = false;

                // change main image with swatch image
                var selectedSwatch = $.grep($scope.mmtSwatches, function (e) { return e.ItemId == item.Id; });
                if (selectedSwatch != null && selectedSwatch != undefined && selectedSwatch.length > 0) {
                    var swatchInfo = selectedSwatch[0]; 
                    var goToIndex = -10;
                    if ($(sliderImageObj).length > 0) {
                        
                        $(sliderImageObj).each(function (index) {
                            if (parseInt($(this).attr("imageid")) === parseInt(swatchInfo.ImageId)) {
                                goToIndex = $(this).closest(".slick-slide").attr("data-slick-index");
                                return false;
                            }
                        });
                        if (goToIndex !== -10) {
                            sliderObj[0].slick.slickGoTo(parseInt(goToIndex));
                        } 
                    }
                    

                    var mainImage = $('#mainProductImage');
                    if (mainImage != undefined) {
                        mainImage.attr("src", swatchInfo.ImageUrlMain);
                    }
                    
                    var mainImageHero = $('#mainProductImageHero');
                    if (mainImageHero != undefined) {
                        mainImageHero.attr("src", swatchInfo.ImageUrlHero);
                    } 
                }

                $scope.changeStockDisplayInfo(item);

            }
            else if (item === undefined) {
                $scope.productData.isSelecting = true;
                $scope.productData.notFound = false;
            }
            else if (item == null) {
                $scope.productData.isSelecting = false;
                $scope.productData.notFound = true;
            }
        };

        $scope.changeStockDisplayInfo = function (item) {
            $("#storeInvModal #itemId").val(item.Id);

            //online inventory
            var inv = $scope.productData.selectedItem.Inventory;
            $("#onlineStockIcon").removeClass("available").removeClass("not-available");
            if (inv > 0) {
                $("#onlineStockIcon").addClass("available");
                $("#onlineStockDisplay").html("In stock online");
            } else {
                $("#onlineStockIcon").addClass("not-available");
                $("#onlineStockDisplay").html("Out stock online");
            }

            //store inventory
            var storeId = $.cookie("MMT-UserDefaultStore");
            if (storeId != "" && storeId != "undefined" && storeId != null && storeId != "0") {
                $.getJSON(rootRel + 'api/stores/GetStoreInventoryforItem?itemId=' + item.Id + '&storeId=' + storeId, {}, function (data) {
                    $scope.$apply(function () {
                        $("#storeStockIcon").removeClass("icon-check-big").removeClass("icon-close");
                        $("#storeStockDisplay").css("padding-left", "10px");

                        if (data == 1) {
                            $("#storeStockIcon").addClass("icon-check-big");
                            $("#storeStockDisplay span").html("Limited quantities");
                        } else if (data > 1) {
                            $("#storeStockIcon").addClass("icon-check-big");
                            $("#storeStockDisplay span").html("In stock");
                        } else {
                            $("#storeStockIcon").addClass("icon-close");
                            $("#storeStockDisplay span").html("Out of stock");
                        }

                        console.log("ItemId: " + item.Id + " | online inventory: " + inv + " | store inventory: " + data);

                    });
                });
            } else {
                console.log("ItemId: " + item.Id + " | online inventory: " + inv + " | store inventory: N/A");
            }

        };

        $scope.loadImage = function (item) {
            if (item !== null && item !== undefined) {
                $scope.selectedItem = item;
                $scope.GetProductSwatches($scope.productId);
                setTimeout(function() {
                    var selectedSwatch = $.grep($scope.mmtSwatches, function (e) { return e.ItemId == item.Id; });
                    if (selectedSwatch != null && selectedSwatch != undefined && selectedSwatch.length > 0) {
                        var swatchInfo = selectedSwatch[0];
                        var mainImageHero = $('#image' + item.Id);
                        if (mainImageHero != undefined) {
                            mainImageHero.attr("src", swatchInfo.ImageUrlMain);
                            mainImageHero.attr("id", 'image' + item.Id);
                            cartProductImageId = item.Id;
                        } 
                    }
                }, 800);
            }
        }

        $scope.GetProductSwatches = function (productId) {
            $.getJSON(rootRel + 'api/Swatch/GetProductSwatches?productId=' + $scope.productId + '&rand=' + Math.floor(Math.random() * 999999), {}, function (data) {
                $scope.$apply(function () {
                    $scope.mmtSwatches = data;
                });
            });
        };

        $scope.swatchSelectClick = function (itemId) {
            angular.forEach($scope.productItems, function (item) {
                if (item.Id == itemId) {
                    setTimeout(function () {
                        $("#selSwatch").val(item.CategoryMapping).change();
                    }, 50);
                    $scope.updateBasicInformation(item);
                }
            });
        };

        $scope.handleGiftCardValueChange = function (value) {
            try {
                var validNumber = parseInt(value);
                if (validNumber < 0) {
                    validNumber = validNumber * (-1);
                }
                $scope.productData.giftCardValue = Math.round(validNumber);
            }
            catch (ex) {
                $scope.productData.giftCardValue = "A";
            }
        };

        $scope.handleGiftCardValueChangeSelect = function (value) {
            try {
                var validNumber = parseInt(value);
                switch(validNumber){
                    case 25:
                    case 50: 
                    case 100:
                        $scope.productData.giftCardValueNumberInput = false;
                        break;
                    default:
                        $scope.productData.giftCardValueNumberInput = true;
                        break;
                }
            }
            catch (ex) {
                $scope.productData.giftCardValue = "A";
            }
        };

        $scope.$watch('productData.giftCardValue', function (number) {
            if (number == 'A')
                return;
            try {
                $scope.productData.giftCardValue = parseInt(number);
            }
            catch (ex) {
                $scope.productData.giftCardValue = "A";
            }
        });

    }
]);

// Post rendering call to style the controls
angular.module('product').directive('post', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            if (!scope.hasItemCategoryItems || scope.$last) {
                $timeout(function () {
                    initCustomForms();
                }, 50);
            }
        }
    }
}]);

angular.module('product').directive('post5', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            $timeout(function () {
                var productId = scope.productId;
                showColorCanvaseOnPageLoad(productId);
                }, 50);
        }
    }
}]);

angular.module('product').directive('post6digital', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        require: 'ngModel',
        priority: 1,
        link: function (scope, elem, attr, ngModelCtrl) {

            if (attr.type === 'radio' || attr.type === 'checkbox') return;
            try { elem.unbind('input'); } catch (e) { }
            try { elem.unbind('keydown'); } catch (e) { }
            try { elem.unbind('change'); } catch (e) { }

            elem.on('blur change', function () {
                var value = elem.val();
                if (value < 5)
                    value = 5;
                if (value > 100)
                    value = 100;
                scope.$apply(function () {
                    ngModelCtrl.$setViewValue(value);
                    ngModelCtrl.$render();
                });
            });
        }
    }
}]);

angular.module('product').directive('post6physical', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        require: 'ngModel',
        priority: 1,
        link: function (scope, elem, attr, ngModelCtrl) {

            if (attr.type === 'radio' || attr.type === 'checkbox') return;
            try { elem.unbind('input'); } catch (e) { }
            try { elem.unbind('keydown'); } catch (e) { }
            try { elem.unbind('change'); } catch (e) { }

            elem.on('blur change', function () {
                var value = elem.val();
                if (value < 5)
                    value = 5;
                if (value > 500)
                    value = 500;
                scope.$apply(function () {
                    ngModelCtrl.$setViewValue(value);
                    ngModelCtrl.$render();
                });
            });
        }
    }
}]);

angular.module('product').directive('post6', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        require: 'ngModel',
        priority: 1,
        link: function (scope, elem, attr, ngModelCtrl) {

            if (attr.type === 'radio' || attr.type === 'checkbox') return;
            try { elem.unbind('input');   } catch (e) { }
            try { elem.unbind('keydown'); } catch (e) { }
            try { elem.unbind('change');  } catch (e) { }

            elem.on('blur change', function () {
                var value = elem.val();
                if (value < 5)
                    value = 5;
                if (value > 500)
                    value = 500;
                scope.$apply(function () {
                    ngModelCtrl.$setViewValue(value);
                    ngModelCtrl.$render();
                });
            });
        }
    }
}]);

angular.module('product').directive('post7', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        require: 'ngModel',
        priority: 1,
        link: function (scope, elem, attr, ngModelCtrl) {

            if (attr.type === 'radio' || attr.type === 'checkbox') return;
            try { elem.unbind('input'); } catch (e) { }
            try { elem.unbind('keydown'); } catch (e) { }
            try { elem.unbind('change'); } catch (e) { }

            elem.bind('change', function () {
                var value = elem.val();
                var maxQuantityValue = Math.min(scope.quantity.max, 99);
				if (scope.selectedItem.QuantityInCart != null && scope.selectedItem.QuantityInCart != undefined) {
                    maxQuantityValue = scope.quantity.max - scope.selectedItem.QuantityInCart;
                }
                if (maxQuantityValue < 1)
                    maxQuantityValue = 1;
                if (value < 1)
                    value = 1;
                if (value > maxQuantityValue)
                    value = maxQuantityValue;
                
                scope.$apply(function () {
                    ngModelCtrl.$setViewValue(value);
                    ngModelCtrl.$render();
                });
            });
        }
    }
}]);

// Post rendering to sync gift value select and textbox
angular.module('product').directive('post2', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            $timeout(function () {
                $('.amount-block #cardAmount').change(function () {
                    $('.amount-block .priceGiftCard').val($(this).val());
                });
            }, 50);

            $('.amount-block .priceGiftCard').blur(function () {
                if ($('.amount-block .priceGiftCard').val() < 5) {
                    $('.amount-block .priceGiftCard').val(5)
                }

                if ($('.amount-block .priceGiftCard').val() > 500) {
                    $('.amount-block .priceGiftCard').val(500)
                }
            });
        }
    }
}]);

// Post rendering for swatches
angular.module('product').directive('post3', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            if (!scope.hasItemCategoryItems || scope.$last) {
                $timeout(function () {
                    $('.swatchImage').each(function () {
                        $(this).click(function () {
                            $('.swatchImage').removeClass("swatchImageSelected");
                            $(this).addClass("swatchImageSelected");
                        });
                    });
                }, 50);
            }
        }
    }
}]);;
'use strict';

/**
*This directive is the button to add product item to shopping cart
*/
angular.module('product')
  .directive('mmtAddtocart', ['siteRes', 'siteConfiguration', 'appUrlBuilder','$timeout',
      function (siteRes, siteConfiguration, appUrlBuilder,$timeout) {
          return {
              restrict: 'A',
              replace: true,
              scope: {
                  item: '=',
                  autoship: '=',
                  isGiftCard: '=',
                  giftCardValue: '=',
                  giftCardType: '='
              },
              templateUrl: appUrlBuilder.buildUniqueTemplateUrl('productAddToCartTemplateUrl'),
              controller: 'ProductAddToCartCtrl',
              link: function (scope, elm, attrs) {
                  scope.isPreOrder = false;
                  scope.addToCartButtonText = attrs.addToCartButtonText;
                  if (attrs.isPreorder === "true") {
                      scope.isPreOrder = true;
                  }
                  scope.giftCardType = attrs.giftCardType;

                    angular.element('.' + siteConfiguration.AddToCartButtonClassIdentifier).click(function (e) {

                        var autoshipId = scope.selectedAutoShip.Value !== undefined && scope.selectedAutoShip.Value !== null ? scope.selectedAutoShip.Value.Id : 0;

                        var giftCardType = scope.giftCardType;
                        var isGiftCard = scope.isGiftCard; 

                        if (isGiftCard == undefined) {
                            isGiftCard = false;
                            giftCardType = '';
                        }

                        var isDigitalCard = (giftCardType.toLowerCase() == 'digital');

                        var qty, price;
                        if (isGiftCard) {
                            if (isDigitalCard) {
                                qty = 1;
                                price = scope.productData.giftCardValue;
                            } else {
                                qty = scope.quantity.value;
                                price = scope.productData.giftCardValue;
                            }
                        } else {
                            qty = scope.quantity.value;
                            price = scope.item.SingleUnitPrice;
                        }

                        var itemName = scope.productData.productName;
                        var itemImg = (scope.productData.images.length > 0 ? scope.productData.images[0].ThumbUrl : (rootRel + 'ImageHandler.axd?ownerTable=Products&ownerId=' + scope.item.ProductId + '&width=100&height=100&constraint=4&interpolate=7&culture=en-US&category=&async=True'));

                        var cartHelper;
                        cartHelper = new CartHelper(siteRes, siteConfiguration);

                        var atc;
                        if (isGiftCard)
                        {
                            if (isDigitalCard) {
                                // get digital gift card details
                                var valid = false;
                                var GiftCard_Message = '';
                                var GiftCard_DeliveryMethod = '';
                                var GiftCard_SenderName = '';
                                var GiftCard_RecipientName = '';
                                var GiftCard_RecipientEmail = '';
                                var GiftCard_DeliveryDate = '';

                                var digitalCardDetails = $('.gift-wrap-block .tabs-block .tab-active');
                                var priceDetails = $('.content');
                                if (priceDetails.html() != undefined) {
                                    valid = $('#price-form')[0].checkValidity();
                                    $('<input type="submit">').hide().appendTo($('#price-form')).click().remove();
                                }
                                if (valid && digitalCardDetails.html() != undefined) {
                                    GiftCard_Message = $('.message-block #message-field').val();
                                    GiftCard_DeliveryMethod = digitalCardDetails.attr('data-method');

                                    if (GiftCard_DeliveryMethod == 'email') {
                                        GiftCard_SenderName = $('#email-tab .delivery-content #yourName-field').val();
                                        GiftCard_RecipientName = $('#email-tab .delivery-content #recipientName-field').val();
                                        GiftCard_RecipientEmail = $('#email-tab .delivery-content #recipientEmail-field').val();
                                        GiftCard_DeliveryDate = $('#email-tab .delivery-content #deliveryDate-field').val();

                                        // validate & trigger validation messages
                                        valid = $('#email-form')[0].checkValidity();
                                        $('<input type="submit">').hide().appendTo($('#email-form')).click().remove();
                                    }
                                    else {
                                        GiftCard_RecipientName = $('#print-tab .delivery-content #recipientName2-field').val();
                                        GiftCard_RecipientEmail = $('#print-tab .delivery-content #yourEmail-field').val();

                                        // validate & trigger validation messages
                                        valid = $('#print-form')[0].checkValidity();
                                        $('<input type="submit">').hide().appendTo($('#print-form')).click().remove();
                                    }
                                }

                                if (valid)
                                {
                                    atc = cartHelper.AddGiftCardToCart(scope.item.Id, scope.item.ProductId, price, qty,
                                                                       GiftCard_Message, GiftCard_DeliveryMethod, GiftCard_SenderName, GiftCard_RecipientName, GiftCard_RecipientEmail, GiftCard_DeliveryDate, false);
                                    //cartHelper.TogglePDPShopingCart(qty, price, itemName, itemImg, isGiftCard, giftCardType);
                                    //cartHelper.ToggleMiniCartAddedItem(qty, price, itemName, itemImg, scope.item.ProductId, isGiftCard, giftCardType);
                                    //window.location.href  = rootRel +"ShoppingCart"; 
                                }
                            }
                            else // physical card
                            {
                                var validPhysicalGiftCard = false;
                                var physicalGiftCardPrice = $('.content');
                                if (physicalGiftCardPrice.html() != undefined) {
                                    validPhysicalGiftCard = $('#physicalGiftCardPrice-form')[0].checkValidity();
                                    $('<input type="submit">').hide().appendTo($('#physicalGiftCardPrice-form')).click().remove();
                                }
                                if (validPhysicalGiftCard) {
                                    atc = cartHelper.AddGiftCardToCart(scope.item.Id, scope.item.ProductId, price, qty, "", "", "", "", "", "", false);
                                    $timeout(function () {
                                        $('.buttons-block').show();
                                    }, 5000);
                                }
                                //cartHelper.TogglePDPShopingCart(qty, price, itemName, itemImg, isGiftCard, giftCardType);
                                //cartHelper.ToggleMiniCartAddedItem(qty, price, itemName, itemImg, scope.item.ProductId, isGiftCard, giftCardType);
                            }
                        }
                        else
                        {
                            atc = cartHelper.AddToCart(scope.item.Id, scope.item.ProductId, scope.productData.hasPersonalization, autoshipId, scope.quantity.value, false, price, itemName, itemImg);
                            if (e.target && e.target.type == "button" && e.target.id && e.target.id.startsWith("btnAddToCart")) {
                                e.target.innerHTML = '<span class="icon-cart"></span><span class="text">Added To Cart</span>';
                                //e.target.innerHTML = '<span class="icon-cart"><span class="icon-check-big"></span></span><span class="text">Added To Cart</span>';

                            }
                            //cartHelper.TogglePDPShopingCart(qty, price, itemName, itemImg, isGiftCard, giftCardType);
                            //cartHelper.ToggleMiniCartAddedItem(qty, price, itemName, itemImg, scope.item.ProductId, isGiftCard, giftCardType);
                        }

                        return atc;
                    });

                  // post angular load -- START

                  initTabs();

                  $('.gift-wrap-form #message-field').keyup(function () {
                      $('.gift-wrap-form .message-block span').html(255 - $('.gift-wrap-form #message-field').val().length);
                  });

                  $("#deliveryDate-field").datepicker({
                      dateFormat: 'mm/dd/yy',
                      minDate: new Date(),
                      defaultDate: new Date()
                  });

                  $("#deliveryDate-field").datepicker("setDate", new Date());

                  // post angular load -- END

              }
          };
      }]);;
;
'use strict';

angular.module('product').controller('ProductReviewsCtrl',
    ['$scope', '$location', 'appUrlBuilder', 'ProductSvc', 'siteRes', 'spinnerFactory', 'siteConfiguration', 'ProductDataStorageService', 'DialogService', 'NavigationService',
    function ($scope, $location, appUrlBuilder, productSvc, siteRes, spinnerFactory, siteConfiguration, productDataStorageService, dialogService, navigationService) {

        //set product data reference to storage.
        $scope.productData = productDataStorageService.productData;
        $scope.limit = 2;

        //process review videos
        setTimeout(function () {
            $("#reviewVideo").each(function() {
                var videoSrc = $(this).attr("data-videoSrc").toString().replace("watch?v=", "embed/");

                if (videoSrc.toLowerCase().indexOf("youtu.be/") > -1) {
                    videoSrc = videoSrc.replace("youtu.be/", "www.youtube.com/embed/");
                }
                if (videoSrc.toLowerCase().indexOf("vimeo.com/") > -1) {
                    videoSrc = videoSrc.replace("vimeo.com/", "player.vimeo.com/video/");
                }
                if (videoSrc.toLowerCase().indexOf("dailymotion.com/") > -1) {
                    videoSrc = videoSrc.replace("www.dailymotion.com/", "www.dailymotion.com/embed/");
                }
                if (videoSrc.toLowerCase().indexOf("dai.ly/") > -1) {
                    videoSrc = videoSrc.replace("dai.ly/", "www.dailymotion.com/embed/video/");
                }
                if (videoSrc.toLowerCase().indexOf("twitch.tv/videos/") > -1) {
                    videoSrc = videoSrc.replace("www.twitch.tv/videos/", "player.twitch.tv/?video=");
                }

                videoSrc = videoSrc.replace("http://", "https://");
                $(this).attr("src", videoSrc);
                console.log("video > " + videoSrc);
            });
        }, 1000);

        $scope.voteProductReview = function (productId, reviewId, reviewStatus) {
            var loggedin = $('#logoutLink').length > 0;
            if (!loggedin) {
                dialogService.show({
                    title: 'Whoops: hang on!',
                    message: "<br>You need to log in before replying to or submitting reviews.<br><br>",
                    buttons: [
                                {
                                    label: "OK",
                                    action: function (dialog) {
                                        dialog.close();
                                    }
                                }
                    ]
                });
                return;
            }

            productSvc.voteProductReview(productId, reviewId, reviewStatus).$promise.then(
                    function (value) {
                        if (value.Status === 'MARKED') {
                            dialogService.alert(siteRes.YouAlreadyMarkedReview);
                        } else {
                            //refresh views, display the new helpful count
                            $scope.productData.reviews = value.Reviews;
                            if (reviewStatus === 2) {
                                dialogService.show({
                                    title: 'Information',
                                    message: "<br>Thanks for your input!<br><br>",
                                    buttons: [
                                                            {
                                                                label: "OK",
                                                                action: function (dialog) {
                                                                    dialog.close();
                                                                }
                                                            }
                                    ]
                                });
                            }
                        }
                    }, function (error) {
                        //Not login in yet, direct to login page
                        if (error.status === siteConfiguration.errorCodeUnauthorized) {

                            var returnUrl = $location.absUrl();
                            navigationService.navigate(appUrlBuilder.buildUrl('signInPageUrl') + '?ReturnUrl=' + returnUrl);
                        }
                        //system error happens
                        if (error.status === siteConfiguration.errorCodeServerError) {
                            dialogService.show({
                                title: 'Error',
                                message: error.statusText,
                            });
                        }
                    });
        };
    }
    ]);;

;
'use strict';

angular.module('product').directive('mmtReviews', [
    'appUrlBuilder', function (appUrlBuilder) {
        return {
            restrict: 'A',
            templateUrl: function (elem, attrs) {
                return appUrlBuilder.buildUrl('productReviewsTemplateUrl') + '/' + attrs.productId;
            },
            controller: 'ProductReviewsCtrl',
            priority: 3
        };
    }
]);;;
'use strict';

/**
 * this is product control, container for all product related directives
 */

angular.module('product').directive('mmtProductConfig', ['$compile', '$http', '$templateCache', 'appUrlBuilder',
    function ($compile, $http, $templateCache, appUrlBuilder) {
        return {
            restrict: 'A',
            priority: 1000,
            scope: {
                productId: '=',
                hideQuantity: '=',
                hideAutoship: '=',
                defaultItemCategories: '=',
                defaultItemId: '=',
                onSelectedItemChanged: '&',
                isStandalone: '=',
                isGiftCard: '=',
                giftCardValue: '=',
                giftCardType: '='
            },
            link: function (scope, element, attrs) {
                scope.giftCardType = attrs.giftCardType;

                var rootUrl = appUrlBuilder.buildUrl('productConfig');
                var childScope;
                attrs.$observe('productId', function (newProductId) {

                    var url = rootUrl + '/' + newProductId;

                    $http.get(url + '?' + new Date().getTime(), { cache: $templateCache }).success(

                        function (html) {
                            element.html(html);
                            $compile(element.contents())(scope);
                        });

                });
            }
        };
    }]);;
;
'use strict';

/**
 * product page add to cart button controller
 */
angular.module('product').controller('ProductAddToCartCtrl', ['$scope', 'ProductDataStorageService', 'siteRes', '$timeout', '$location', 'WishListService', 'NavigationService', 'DialogService', 'siteConfiguration', 'appUrlBuilder',
    function ($scope, productDataStorageService, siteRes, $timeout, $location, wishListService, navigationService, dialogService, siteConfiguration, appUrlBuilder) {
        $scope.productData = productDataStorageService.productData;
        $scope.selectedAutoShip = productDataStorageService.selectedAutoShip;
        $scope.quantity = productDataStorageService.quantity;

        //Button text effect
        $scope.buttonText = siteRes.AddToCart;

        $scope.$watch('item.IsInCart', function (newVal, oldVal) {
            if (newVal !== oldVal && !$scope.isUpdateingAddToCartEffect) {
                if (newVal === true) {
                    $scope.buttonText = siteRes.AddAnother;
                } else {
                    $scope.buttonText = siteRes.AddToCart;
                }

            }
        });

        $scope.isUpdateingAddToCartEffect = false;
        $scope.$watch('item.triggerAddToCartEffect', function (newVal, oldVal) {
            if (newVal && newVal !== oldVal) {
                $scope.isUpdateingAddToCartEffect = true;
                $scope.buttonText = siteRes.Added;
                $timeout(function () {
                    $scope.buttonText = siteRes.AddAnother;
                    $scope.isUpdateingAddToCartEffect = false;
                    $scope.$apply();
                }, 2000);

            }
        });


        $scope.addToWishList = function (signedIn, itemId) {
            $timeout(function () {
                AddProdtoGiftList(signedIn, itemId);
            }, 500);
        }

        $scope.addToReserve = function (item, productData) {
            var quantity = $scope.quantity.value;
            var itemName = productData.productName;
            var itemImg = (productData.images.length > 0 ? productData.images[0].ThumbUrl : (rootRel + 'ImageHandler.axd?ownerTable=Products&ownerId=' + item.ProductId + '&width=100&height=100&constraint=4&interpolate=7&culture=en-US&category=&async=True'));
            console.log("Reserve In-Store > ItemName: " + itemName + " | ItemId: " + item.Id + " | ProductId: " + item.ProductId + " | Price: " + item.SingleUnitPrice + " | Qty: " + quantity);
            var cartHelper = new CartHelper(siteRes, siteConfiguration);
            cartHelper.AddReserveItemToCart(item.Id, quantity, 0, item.ProductId, item.SingleUnitPrice, itemName, itemImg);
        }

        $scope.showToolTipx = function (state) {
            if (!$scope.productData.CanReserveItem) {
                return;
            }

            $timeout(function () {
                if (isMobileDevice || isMobileDeviceJs()) {
                    return;
                }
                
                if (state) {
                    $(".tooltiptext").slideDown(300);
                } else {
                    $(".tooltiptext").hide();
                }
            }, 50);
        }

    }]);;;
'use strict';

/**
 * Responsible for all cart specific communication with the server
 */
angular.module('cart').factory('CartDataService', [
    '$resource', 'appUrlBuilder',
    function ($resource, appUrlBuilder) {

        var resource = $resource(appUrlBuilder.buildUrl('shoppingCartApiUrl'), null, {
            'addToCart': { method: 'PUT', url: appUrlBuilder.buildUrl('addItemToShoppingCartUrl'), isArray: false, responseType: 'json' },
            'addGiftCardToCart': { method: 'PUT', url: appUrlBuilder.buildUrl('addGiftCardItemToShoppingCartUrl'), isArray: false, responseType: 'json' },
            'addItemToReserve': { method: 'PUT', url: appUrlBuilder.buildUrl('addItemToReserveUrl'), isArray: false, responseType: 'json' },
            'restoreItem': { method: 'PUT', url: appUrlBuilder.buildUrl('restoreItemToShoppingCartUrl'), isArray: false, responseType: 'json' },
			'removeFromCart': { method: 'DELETE', url: appUrlBuilder.buildUrl('removeItemFromShoppingCartUrl') + '/:id', isArray: false, responseType: 'json' },
			'removeFromCartRIS': { method: 'DELETE', url: appUrlBuilder.buildUrl('risRemoveItemFromShoppingCartUrl') + '/:id', isArray: false, responseType: 'json' },
            'updateItemQuantity': { method: 'PUT', url: appUrlBuilder.buildUrl('udpateItemQuantityUrl'), isArray: false, responseType: 'json' },
            'updatePricingBonusItem': { method: 'PUT', url: appUrlBuilder.buildUrl('updatePricingBonusItemUrl'), isArray: false, responseType: 'json' },
            'updateDynPromoBonusItem': { method: 'PUT', url: appUrlBuilder.buildUrl('updateDynPromoBonusItemUrl'), isArray: false, responseType: 'json' },
            'updateItem': { method: 'POST', url: appUrlBuilder.buildUrl('updateShoppingCartItemUrl'), isArray: false, responseType: 'json' },
            'addCoupon': { method: 'PUT', url: appUrlBuilder.buildUrl('addCouponToShoppingCartUrl'), isArray: false, responseType: 'json' },
            'removeCoupon': { method: 'DELETE', url: appUrlBuilder.buildUrl('removeCouponFromShoppingCartUrl') + '/:id', isArray: false, responseType: 'json' },
            'listCoupons': { method: 'GET', url: appUrlBuilder.buildUrl('listCouponsUrl'), isArray: true, responseType: 'json' },
            'getGiftWrapItems': { method: 'GET', url: appUrlBuilder.buildUrl('getGiftWrapItemsUrl') , isArray: true, responseType: 'json' },
            'getGiftWrapData': { method: 'GET', url: appUrlBuilder.buildUrl('getGiftWrapDataUrl'), isArray: false, responseType: 'json' },
            'addGiftWrapToCart': { method: 'PUT', url: appUrlBuilder.buildUrl('addGiftWrapItemToShoppingCartUrl'), isArray: false, responseType: 'json' },
            'updateGiftWrap': { method: 'PUT', url: appUrlBuilder.buildUrl('updateGiftWrapItemUrl'), isArray: false, responseType: 'json' },
            'removeGiftWrapFromCart': { method: 'DELETE', url: appUrlBuilder.buildUrl('removeGiftWrapItemFromShoppingCartUrl'), isArray: false, responseType: 'json' },
            'updatePhysicalGiftCard': { method: 'PUT', url: appUrlBuilder.buildUrl('updatePhysicalGiftCardUrl'), isArray: false, responseType: 'json' },
            'getGiftCardItems': { method: 'GET', url: appUrlBuilder.buildUrl('getGiftCardItemsUrl'), isArray: true, responseType: 'json' },
            'getDigitalCardData': { method: 'GET', url: appUrlBuilder.buildUrl('getDigitalCardDataUrl'), isArray: false, responseType: 'json' },
            'updateDigitalGiftCard': { method: 'PUT', url: appUrlBuilder.buildUrl('updateDigitalGiftCardUrl'), isArray: false, responseType: 'json' }
        });

        return {
            addItem: function (productId, itemId, quantity, autoship, personalizationData) {
                var data = { ItemId: itemId, Quantity: quantity, Options: personalizationData, ProductId: productId, Autoship: autoship };
                return resource.addToCart(data);
            },
            addGiftCardItem: function (productId, itemId, quantity, autoship, personalizationData, price,
                GiftCard_Message, GiftCard_DeliveryMethod, GiftCard_SenderName, GiftCard_RecipientName, GiftCard_RecipientEmail, GiftCard_DeliveryDate) {
                var data = {
                    ItemId: itemId, Quantity: quantity, Options: personalizationData, ProductId: productId, Autoship: autoship, Price: price,
                    'GiftCard_Message': GiftCard_Message,
                    'GiftCard_DeliveryMethod': GiftCard_DeliveryMethod, 
                    'GiftCard_SenderName': GiftCard_SenderName, 
                    'GiftCard_RecipientName': GiftCard_RecipientName, 
                    'GiftCard_RecipientEmail': GiftCard_RecipientEmail,
                    'GiftCard_DeliveryDate': GiftCard_DeliveryDate
                };
                return resource.addGiftCardToCart(data);
            },
            updateDigitalGiftCard: function (productId, id, quantity, autoship, personalizationData, price,
             GiftCard_Message, GiftCard_DeliveryMethod, GiftCard_SenderName, GiftCard_RecipientName, GiftCard_RecipientEmail, GiftCard_DeliveryDate) {
                var data = {
                    ItemGuid: id, Quantity: quantity, Options: personalizationData, ProductId: productId, Autoship: autoship, Price: price,
                    'GiftCard_Message': GiftCard_Message,
                    'GiftCard_DeliveryMethod': GiftCard_DeliveryMethod, 
                    'GiftCard_SenderName': GiftCard_SenderName, 
                    'GiftCard_RecipientName': GiftCard_RecipientName, 
                    'GiftCard_RecipientEmail': GiftCard_RecipientEmail,
                    'GiftCard_DeliveryDate': GiftCard_DeliveryDate
                };
                return resource.updateDigitalGiftCard(data);
            },
            restoreItem: function (item) {
                var data = { ItemId: item.ItemId, Quantity: item.Quantity, Options: item.Options, ProductId: item.ProductId, Autoship: item.Autoship, BundleId: item.BundleId };
                return resource.restoreItem(data);
            },
            removeItem: function (itemId) {
                return resource.removeFromCart({ id: itemId });
            },
            removeGiftWrapItem: function (itemId, wrapId) {
                return resource.removeGiftWrapFromCart({ itemId: itemId, wrapId: wrapId });
			},
			removeItemRIS: function (itemId) {
				return resource.removeFromCartRIS({ id: itemId });
			},
            getOrderForm: function () {
                return resource.get();
            },
            updateItemQuantity: function (itemGuid, quantity) {
                var data = { ItemGuid: itemGuid, Quantity: quantity };
                return resource.updateItemQuantity(data);
            },
            updatePricingBonusItem: function (itemGuid, newItemId, quantity) {
                var data = { ItemGuid: itemGuid, NewItemId: newItemId, Quantity: quantity };
                return resource.updatePricingBonusItem(data);
            },
            updateDynPromoBonusItem: function (itemGuid, newItemId, quantity) {
                var data = { ItemGuid: itemGuid, NewItemId: newItemId, Quantity: quantity };
                return resource.updateDynPromoBonusItem(data);
            },
            updateItem: function (updateItemArgs) {
                var data = { ItemGuid: updateItemArgs.ItemGuid, SelectedItemId: updateItemArgs.SelectedItemId, Options: updateItemArgs.Options };
                return resource.updateItem(data);
            },
            addCoupon: function (couponCode) {
                var data = { CouponCode: couponCode };
                return resource.addCoupon(data);
            },
            removeCoupon: function (couponCode) {
                return resource.removeCoupon({ id: couponCode });
            },

            listCoupons: function () {
                return resource.listCoupons();
            },

            getGiftWrapItems: function () {
                return resource.getGiftWrapItems();
            },
            getGiftWrapData: function (guid) {
                return resource.getGiftWrapData({ guid : guid });
            },
            addGiftWrapItem: function (itemId, price, to, from, message, itemToWrap) {
                var data = { ItemId: itemId, Price: price, To: to, From: from, Message: message, ItemGuid: itemToWrap };
                return resource.addGiftWrapToCart(data);
            },
            updateGiftWrapItem: function (to, from, message, wrapGuid, itemId, itemIdChanged) {
                var data = { To: to, From: from, Message: message, WrapItemGuid: wrapGuid, ItemId: itemId, ItemIdChanged: itemIdChanged };
                return resource.updateGiftWrap(data);
            },
            getGiftCardItems: function () {
                return resource.getGiftCardItems();
            },
            updatePhysicalGiftCard: function (productId, itemId, quantity, autoship, personalizationData, price, currentId) {
                var data = {
                    ItemId: itemId,
                    Quantity: quantity,
                    Options: null,
                    ProductId: productId,
                    Autoship: 0,
                    Price: price,
                    CurrentItemId: currentId
                };
                return resource.updatePhysicalGiftCard(data);
            },
            getDigitalCardData: function (guid) {
                return resource.getDigitalCardData({ guid: guid });
            },

            //bvc - new
            addItemToReserve: function (itemId, productId, price, quantity, reserveStoreId) {
                var data = { ItemId: itemId, ProductId: productId, Price: price, Quantity: quantity, ReserveStoreId: reserveStoreId };
                return resource.addItemToReserve(data);
            }
        };
    }
]);;
'use strict';

/**
 * Responsible for all cart specific logic
 */
angular.module('cart').factory('CartService', ['$q', 'CartDataService', 'CartDataStorageService', 'ProductPersonalizationService', 'AppObserver',
    function ($q, cartDataService, cartDataStorageService, productPersonalizationService, appObserver) {

        var addToCart = function (itemData) {

            var deferred = $q.defer();

            var args = { productId: itemData.productId, itemGuid: '', hasPersonalization: itemData.hasPersonalization, enableItemSelection: itemData.enableItemSelection };

            var originalItemsCount = cartDataStorageService.cartData.totalItemsCount;

            productPersonalizationService.openPersonalizationDialog(args)
                .then(
                    function (data) {
                        var id = itemData.itemId;
                        if (data.selectedItem && data.selectedItem.Id) {
                            id = data.selectedItem.Id;
                        }
                        cartDataService.addItem(itemData.productId, id, itemData.Quantity, itemData.Autoship, data.selectedOptions)
                            .$promise.then(
                                function (value) {
                                    if (value.AddCartError && value.AddCartStatus && value.AddCartStatus === -1) {
                                        deferred.reject(value.AddCartError);
                                    }
                                    else {
                                        var itemWasAdded = originalItemsCount !== value.TotalItemsCount;
                                        cartDataStorageService.sync(value, true);
                                        deferred.resolve(itemWasAdded);
                                    }
                                },
                                function (error) {
                                    deferred.reject(error);
                                }
                            );
                    },
                    function (error) {
                        deferred.reject(error);
                    });

            return deferred.promise;
        };

        var addGiftCardToCart = function (itemData) {

            var deferred = $q.defer();

            var args = {
                productId: itemData.productId, itemGuid: '', hasPersonalization: itemData.hasPersonalization, enableItemSelection: itemData.enableItemSelection, price: itemData.Price,
                'GiftCard_Message': itemData.GiftCard_Message,
                'GiftCard_DeliveryMethod': itemData.GiftCard_DeliveryMethod,
                'GiftCard_SenderName': itemData.GiftCard_SenderName,
                'GiftCard_RecipientName': itemData.GiftCard_RecipientName,
                'GiftCard_RecipientEmail': itemData.GiftCard_RecipientEmail,
                'GiftCard_DeliveryDate': itemData.GiftCard_DeliveryDate
            };

            var originalItemsCount = cartDataStorageService.cartData.totalItemsCount;

            productPersonalizationService.openPersonalizationDialog(args)
                .then(
                    function (data) {
                        var id = itemData.itemId;
                        if (data.selectedItem && data.selectedItem.Id) {
                            id = data.selectedItem.Id;
                        }
                        cartDataService.addGiftCardItem(itemData.productId, id, itemData.Quantity, itemData.Autoship, data.selectedOptions, itemData.Price, itemData.GiftCard_Message,
                            itemData.GiftCard_DeliveryMethod, itemData.GiftCard_SenderName, itemData.GiftCard_RecipientName, itemData.GiftCard_RecipientEmail, itemData.GiftCard_DeliveryDate)
                            .$promise.then(
                                function (value) {
                                    var itemWasAdded = originalItemsCount !== value.TotalItemsCount;
                                    cartDataStorageService.sync(value, true);
                                    deferred.resolve(itemWasAdded);
                                },
                                function (error) { deferred.reject(error); }
                            );
                    },
                    function (error) { deferred.reject(error); });

            return deferred.promise;
        };

        var updateDigitalGiftCard = function (itemData) {

            var deferred = $q.defer();

            var args = {
                productId: itemData.productId, itemGuid: itemData.Id, hasPersonalization: false, enableItemSelection: false, price: itemData.Price,
                'GiftCard_Message': itemData.GiftCard_Message,
                'GiftCard_DeliveryMethod': itemData.GiftCard_DeliveryMethod,
                'GiftCard_SenderName': itemData.GiftCard_SenderName,
                'GiftCard_RecipientName': itemData.GiftCard_RecipientName,
                'GiftCard_RecipientEmail': itemData.GiftCard_RecipientEmail,
                'GiftCard_DeliveryDate': itemData.GiftCard_DeliveryDate
            };

            var originalItemsCount = cartDataStorageService.cartData.totalItemsCount;

            productPersonalizationService.openPersonalizationDialog(args)
                .then(
                    function (data) {
                        cartDataService.updateDigitalGiftCard(itemData.productId, itemData.Id, 1, 0, data.selectedOptions, itemData.Price, itemData.GiftCard_Message,
                            itemData.GiftCard_DeliveryMethod, itemData.GiftCard_SenderName, itemData.GiftCard_RecipientName, itemData.GiftCard_RecipientEmail, itemData.GiftCard_DeliveryDate)
                            .$promise.then(
                                function (value) {
                                    //var itemWasAdded = originalItemsCount !== value.TotalItemsCount;
                                    cartDataStorageService.sync(value, true);
                                    deferred.resolve(true);
                                },
                                function (error) { deferred.reject(error); }
                            );
                    },
                    function (error) { deferred.reject(error); });

            return deferred.promise;
        };

        var addGiftWrapToCart = function (itemData) {
            //data check
            //alert(itemData.productId + " | " + itemData.itemId + " | " + itemData.Price + " | " + itemData.To + " | " + itemData.From + " | " + itemData.Message + " | " + itemData.itemToWrap);

            var deferred = $q.defer();
            cartDataService.addGiftWrapItem(itemData.itemId, itemData.Price, itemData.To, itemData.From, itemData.Message, itemData.itemToWrap)
                .$promise.then(
                    function (value) {
                        cartDataStorageService.sync(value, true);
                        deferred.resolve(true);
                    },
                    function (error) { deferred.reject(error); });

            return deferred.promise;
        };

        var updateGiftWrap = function (itemData) {
            //data check
            //alert(itemData.To + " | " + itemData.From + " | " + itemData.Message + " | " + itemData.WrapGuid + " | " + itemData.ItemId + " | " + itemData.ItemIdChanged);

            var deferred = $q.defer();
            cartDataService.updateGiftWrapItem(itemData.To, itemData.From, itemData.Message, itemData.WrapGuid, itemData.ItemId, itemData.ItemIdChanged)
                .$promise.then(
                    function (value) {
                        cartDataStorageService.sync(value, true);
                        deferred.resolve(true);
                    },
                    function (error) { deferred.reject(error); });

            return deferred.promise;
        };


        var updatePhysicalGiftCard = function (itemData) {

            var deferred = $q.defer();

            var args = { productId: itemData.productId, itemGuid: '', hasPersonalization: false, enableItemSelection: false, price: itemData.price };

            var originalItemsCount = cartDataStorageService.cartData.totalItemsCount;

            productPersonalizationService.openPersonalizationDialog(args)
                .then(
                    function (data) {
                        var id = itemData.itemId;
                        if (data.selectedItem && data.selectedItem.Id) {
                            id = data.selectedItem.Id;
                        }
                        cartDataService.updatePhysicalGiftCard(itemData.productId, id, itemData.quantity, false, data.selectedOptions, itemData.price, itemData.currentId)
                            .$promise.then(
                                function (value) {
                                    //var itemWasAdded = originalItemsCount !== value.TotalItemsCount;
                                    cartDataStorageService.sync(value, true);
                                    deferred.resolve(true);
                                },
                                function (error) { deferred.reject(error); }
                            );
                    },
                    function (error) { deferred.reject(error); });

            return deferred.promise;
        };

        var undoRemoveFromCart = function (item) {
            var deferred = $q.defer();
            cartDataService.restoreItem(item).$promise.then(
                function (value) {
                    var restoredItems = { restoredItemId: item.Id };
                    cartDataStorageService.sync(value, true, restoredItems);
                    appObserver.broadcast('reloadShippingRates', {});
                    deferred.resolve({});
                },
                function (error) { deferred.reject(error); });

            return deferred.promise;
        };

        var removeFromCart = function (itemId) {
            var deferred = $q.defer();

            cartDataService.removeItem(itemId).$promise.then(
                function (value) {
                    //cartDataStorageService.sync(value, true);
                    appObserver.broadcast('reloadShippingRates', {});
                    deferred.resolve({});
                },
                function (error) { deferred.reject(error); });

            return deferred.promise;
		};

		var removeFromCartRIS = function (itemId) {
			var deferred = $q.defer();			
			cartDataService.removeItemRIS(itemId).$promise.then(
				function (value) {
					cartDataStorageService.sync(value, true);
					cartDataStorageService.loadCartData();
					//appObserver.broadcast('reloadShippingRates', {});
					deferred.resolve({});
				},
				function (error) { deferred.reject(error); });

			return deferred.promise;
		};

        var removeGiftWrapFromCart = function (itemId, wrapId) {
            var deferred = $q.defer();

            cartDataService.removeGiftWrapItem(itemId, wrapId).$promise.then(
                function (value) {
                    cartDataStorageService.sync(value, true);
                    appObserver.broadcast('reloadShippingRates', {
                    });
                    deferred.resolve({
                    });
                },
                function (error) {
                    deferred.reject(error);
                });

            return deferred.promise;
        };

        var updatePricingBonusItem = function (itemGuid, newItemId, quantity) {
            var deferred = $q.defer();

            cartDataService.updatePricingBonusItem(itemGuid, newItemId, quantity).$promise.then(
                function (value) {
                    cartDataStorageService.sync(value, true);
                    appObserver.broadcast('reloadShippingRates', {});
                    deferred.resolve({});
                },
                function (error) { deferred.reject(error); });

            return deferred.promise;
        };

        var updateDynPromoBonusItem = function (itemGuid, newItemId, quantity) {
            var deferred = $q.defer();

            cartDataService.updateDynPromoBonusItem(itemGuid, newItemId, quantity).$promise.then(
                function (value) {
                    cartDataStorageService.sync(value, true);
                    appObserver.broadcast('reloadShippingRates', {});
                    deferred.resolve({});
                },
                function (error) { deferred.reject(error); });

            return deferred.promise;
        };

        var updateItemQuantity = function (itemId, quantity) {

            var deferred = $q.defer();

            cartDataService.updateItemQuantity(itemId, quantity).$promise.then(
                function (value) {
                    //cartDataStorageService.sync(value, true);
                    appObserver.broadcast('reloadShippingRates', {});
                    deferred.resolve({});
                },
                function (error) { deferred.reject(error); });

            return deferred.promise;
        };

        var updateItem = function (updateItemArgs) {

            var deferred = $q.defer();

            cartDataService.updateItem(updateItemArgs).$promise.then(
                function (value) {
                    var restoredItems = { restoredItemId: updateItemArgs.ItemGuid };
                    //cartDataStorageService.sync(value, true, restoredItems);
                    appObserver.broadcast('reloadShippingRates', {});
                    deferred.resolve({});
                },
                function (error) { deferred.reject(error); });

            return deferred.promise;
        };

        var addCoupon = function (couponCode) {
            var deferred = $q.defer();
            if (couponCode !== '') {
                cartDataService.addCoupon(couponCode).$promise.then(
                    function (value) {
                        //cartDataStorageService.sync(value, false);
                        appObserver.broadcast('reloadShippingRates', {});
                        deferred.resolve(value);
                    },
                    function (error) { deferred.reject(error); });
            } else {
                deferred.resolve({});
            }
            return deferred.promise;
        };
        var removeCoupon = function (couponCode) {
            var deferred = $q.defer();
            cartDataService.removeCoupon(couponCode).$promise.then(
                function (value) {
                    //cartDataStorageService.sync(value, false);
                    appObserver.broadcast('reloadShippingRates', {});
                    deferred.resolve({});
                },
                function (error) { deferred.reject(error); });
            return deferred.promise;
        };

        var listCoupons = function () {
            var deferred = $q.defer();
            cartDataService.listCoupons().$promise.then(
                function (value) {
                    deferred.resolve(value);
                },
                function (error) { deferred.reject(error); });
            return deferred.promise;
        };

        var getGiftWrapItems = function () {
            var deferred = $q.defer();
            cartDataService.getGiftWrapItems().$promise.then(
                function (value) {
                    deferred.resolve(value);
                },
                function (error) { deferred.reject(error); });
            return deferred.promise;
        };

        var getGiftCardItems = function () {
            var deferred = $q.defer();
            cartDataService.getGiftCardItems().$promise.then(
                function (value) {
                    deferred.resolve(value);
                },
                function (error) { deferred.reject(error); });
            return deferred.promise;
        };


        var getDigitalCardData = function (guid) {
            var deferred = $q.defer();
            cartDataService.getDigitalCardData(guid).$promise.then(
                function (value) {
                    deferred.resolve(value);
                    },
                function (error) { deferred.reject(error); });
            return deferred.promise;
          };

        var getGiftWrapData = function (guid) {
              var deferred = $q.defer();
              cartDataService.getGiftWrapData(guid).$promise.then(
                  function (value) {
                      deferred.resolve(value);
                  },
                  function (error) { deferred.reject(error); });
              return deferred.promise;
        };

        var addReserveItemToCart = function (itemData) {
            var deferred = $q.defer();
            cartDataService.addItemToReserve(itemData.ItemId, itemData.ProductId, itemData.Price, itemData.Quantity, itemData.ReserveStoreId)
                .$promise.then(
                    function (value) {
                        cartDataStorageService.sync(value, true);
                        deferred.resolve(true);
                    },
                    function (error) { deferred.reject(error); });

            return deferred.promise;
        };

        return {
            addToCart: addToCart,
            addGiftCardToCart: addGiftCardToCart,
            addReserveItemToCart: addReserveItemToCart,
            undoRemoveFromCart: undoRemoveFromCart,
			removeFromCart: removeFromCart,
			removeFromCartRIS: removeFromCartRIS,
            updateItemQuantity: updateItemQuantity,
            updatePricingBonusItem: updatePricingBonusItem,
            updateDynPromoBonusItem: updateDynPromoBonusItem,
            updateItem: updateItem,
            addCoupon: addCoupon,
            listCoupons: listCoupons,
            getGiftWrapItems: getGiftWrapItems,
            getGiftWrapData: getGiftWrapData,
            addGiftWrapToCart: addGiftWrapToCart,
            updateGiftWrap: updateGiftWrap,
            removeCoupon: removeCoupon,
            removeGiftWrapFromCart: removeGiftWrapFromCart,
            getGiftCardItems: getGiftCardItems,
            updatePhysicalGiftCard: updatePhysicalGiftCard,
            getDigitalCardData: getDigitalCardData,
            updateDigitalGiftCard: updateDigitalGiftCard
        };
    }
]);;
'use strict';

angular.module('cart').controller('ShoppingCartModalCtrl', ['$scope', '$q', '$modal', '$window', 'appUrlBuilder', 'CartDataStorageService', 'CartService','$timeout','$log','$location',
    function ($scope, $q, $modal, $window, appUrlBuilder, cartDataStorageService, cartService, $timeout, $log, $location) {
        
        $scope.loadCounter = cartDataStorageService.loadCounter;
        $scope.cartData = cartDataStorageService.cartData;

        $scope.preloadData = function () {
            if ($("#appProduct").length > 0) {
                cartDataStorageService.loadCartData();
            }
        };

        $scope.$root.showCart = function () {
            $modal.open({
                templateUrl: appUrlBuilder.buildTemplateUrl('shoppingCartModalTemplateUrl'),
                backdrop: 'static',
                controller: 'ShoppingCartModalInstanceCtrl',
                windowClass: 'modal-vertical-centered',
                size: 'lg'
            });
        };

        $scope.$root.showCartPDP = function () {
            $modal.open({
                    templateUrl: appUrlBuilder.buildTemplateUrl('shoppingCartModalPDPTemplateUrl'),
                    backdrop: 'static',
                    controller: 'ShoppingCartModalInstanceCtrl',
                    windowClass: 'modal-vertical-centered pdpcart-modal-dialog',
                    size: 'xl'
            });
        };


        var paddingModal = function (event,animate) {
            var isIphone = (navigator.platform.indexOf("iPhone") != -1);
            if ($(window).width() <= 576) isIphone = true;


            var $iconcart = $('#header .icon-cart');
            var rt = ($(window).width() - ($iconcart.offset().left + $iconcart.outerWidth()));
            rt = rt > 30 ? rt - 30 : rt;
            if (isIphone)
                rt = 10;
            var carttop = $iconcart.offset().top - $(window).scrollTop();
            if (carttop < 0)
                carttop = 50;
            var scrolltop = isIphone ? "20px" : (carttop+20) + "px";
            if (animate) {
                var ele = jQuery(".modal-dialog.modal-xl").hide().css("top", "-100px");
                ele.css("margin-right", rt);
                ele.delay(500).show()
                .animate({ opacity: 1, top: scrolltop },  {duration: 1000, easing: 'easeOutBounce'});

            } else {
                ele = jQuery(".modal-dialog.modal-xl").hide();
                ele.css("margin-right", rt);
                ele.css("margin-top", scrolltop);
                ele.show();
            }
            //jQuery("#minicartpopup").hide().css("top", "-100px").delay(10).show().animate({ opacity: 1, top: scrolltop }, 'slow');

        }

        $scope.$root.showMiniCart = function () {
             var modal = $modal.open({
                templateUrl: appUrlBuilder.buildTemplateUrl('miniCartModalTemplateUrl'),
                backdrop: 'static',
                controller: 'ShoppingCartModalInstanceCtrl',
                windowClass: 'modal-vertical-centered miniCart-modal-dialog',
                size: 'xl'
            });


            modal.opened.then(function () {

                setTimeout(function () {
                    if ($scope.cartData.totalItemsCount > 0) {
                        var itemCount = 0;
                        for (var i = 0, len = $scope.cartData.items.length; i < len; i++) {
                            if ($scope.cartData.items[i].isDeleted != true)
                                itemCount++;
                        }

                        var isPromo = ($scope.$root.addedItem &&
                            $scope.$root.addedItemProdId &&
                            $scope.$root.addedItemProdId > 0 &&
                            !$scope.$root.addedItemIsGiftCard ? true : false);

                        if (itemCount <= (isPromo?2:3))
                            $("#minicartpopup .gallery .gallery-holder").css("padding-left", "8px");
                    }

                    paddingModal(true);
                    angular.element(window).on('resize', paddingModal);
                }, 200);


                $timeout(function () {
                    try {
                      modal.close();
                    } catch (err) { }
                }, 7000);
            }, function () {
                $log.info('Modal dismissed at: ' + new Date());
            });

        };

        $scope.$root.isCartEmpty = function () {
            return $scope.cartData.items.length < 1;
        };

        $scope.$root.getCartData = function () {
            return $scope.cartData;
        };

        $scope.$root.cartHasGiftCard = function () {
            for (var i = 0; i < $scope.cartData.items.length; i++) {
                if ($scope.cartData.items[i].AutoshipMessage.toLowerCase().indexOf("gift card|") > -1) {
                    return true;
                }
            }

            return false;
        };

        $scope.$root.cartHasDigitalGiftCard = function () {
            for (var i = 0; i < $scope.cartData.items.length; i++) {
                if ($scope.cartData.items[i].AutoshipMessage.toLowerCase().indexOf("gift card|digital") > -1) {
                    return true;
                }
            }

            return false;
        };

        $scope.$root.cartHasPhysicalGiftCard = function () {
            for (var i = 0; i < $scope.cartData.items.length; i++) {
                if ($scope.cartData.items[i].AutoshipMessage.toLowerCase().indexOf("gift card|physical") > -1) {
                    return true;
                }
            }

            return false;
        };

        $scope.$root.addToCart = function (itemData) {

            var deferred = $q.defer();

            cartService.addToCart(itemData).then(function (value) {
                if (value) {
                    deferred.resolve({});
                } else {
                    deferred.reject('nothing was added');
                }
            }, function (error) { deferred.reject(error); });

            return deferred.promise;
        };

        $scope.$root.addGiftCardToCart = function (itemData) {

            var deferred = $q.defer();
            cartService.addGiftCardToCart(itemData).then(function (value) {
                if (value) {
                    deferred.resolve({});
                } else {
                    deferred.reject('nothing was added');
                }
            }, function (error) { deferred.reject(error); });

            return deferred.promise;
        };

        //bvc - new
        $scope.$root.addReserveItemToCart = function (itemData) {
            var deferred = $q.defer();
            cartService.addReserveItemToCart(itemData).then(function (value) {
                if (value) {
                    deferred.resolve({});
                } else {
                    deferred.reject('nothing was added');
                }
            }, function (error) { deferred.reject(error); });

            return deferred.promise;
        };

        //Pop up cart if query string contains 'showCart=True'
        if ($window.location.search.indexOf('showCart=True') > 0) {
            $scope.$root.showCart();
        }

        //Pop up cart if query string contains 'showCartPDP=True'
        if ($window.location.search.indexOf('showCartPDP=True') > 0) {
            $scope.$root.showCartPDP();
        }

        //Pop up cart if query string contains 'showCartPDP=True'
        if ($window.location.search.indexOf('showMiniCart=True') > 0) {
            $scope.$root.showMiniCart();
        }
    }]);



// Post rendering call to init the carousel
//angular.module('cart').directive('postRender', ['$timeout', function ($timeout) {
//    return {
//        restrict: 'A',
//        link: function (scope, elem, attrs) {
//            if (scope.$last) {
//                $timeout(function () {
//                   // initPDPCartSlickGallary();
//                }, 2000);
//            }
//        }
//    }

//}]);;
/**
* This is platform implemented shopping cart.
* This directive is watching for shopping cart changes and updates all external elements, that are not part of the shoppingCart module, so that
* external elements reflect changes in the cart.  Update are done via handlers.  If you want to extend this, you should write your custom handlers
* handlers that accept scope.cartData as a parameter
*/
angular.module('cart').directive('pdpShoppingCart', ['$window', 'appUrlBuilder', function ($window, appUrlBuilder) {
    return {
        restrict: 'A',
        templateUrl: appUrlBuilder.buildTemplateUrl('shoppingCartPDPTemplateUrl'),
        scope: {
            onCartChanged: '@',
            preloadData: '@'
        },
        controller: 'CartCtrl',
        link: function (scope, element) {

            // We could watch for  scope.cartData.totalItemsCount and  scope.$root.$watchCollection for  scope.cartData.items
            // but it is pretty expensive, so we will watch for the load counter instead, to make it lightweight

            var watcher = scope.$watch('loadCounter.count', function () {

                if (scope.onCartChanged && typeof ($window[scope.onCartChanged]) !== 'undefined') {
                    $window[scope.onCartChanged](scope.cartData);
                }

            });


            element.on('$destroy', function () {
                // Dispose watcher
                watcher();
            });

            scope.loadData();
        }
    };
}]);;
'use strict';;
'use strict';
angular.module('cart').directive('miniShoppingCart', ['$window', 'appUrlBuilder', function ($window, appUrlBuilder) {
    
    return {
        restrict: 'A',
        template: '<div ng-include="getMiniCartTemplateUrl()"></div>',
        //templateUrl: appUrlBuilder.buildTemplateUrl('miniCartTemplateUrl'),
        scope: {
            onCartChanged: '@',
            preloadData: '@'
        },
        controller: 'CartCtrl',
        link: function (scope, element, attrs) {
            scope.getMiniCartTemplateUrl = function () {
                var tmpurl = appUrlBuilder.buildTemplateUrl('miniCartTemplateUrl');
                if (scope.$root.addedItem &&
                    scope.$root.addedItemProdId &&
                    scope.$root.addedItemProdId > 0 &&
                    !scope.$root.addedItemIsGiftCard) {
                    tmpurl += "?addedprodId=" + scope.$root.addedItemProdId;
                }
                return tmpurl;
            }

            // We could watch for  scope.cartData.totalItemsCount and  scope.$root.$watchCollection for  scope.cartData.items
            // but it is pretty expensive, so we will watch for the load counter instead, to make it lightweight
            var watcher = scope.$watch('loadCounter.count', function () {

                if (scope.onCartChanged && typeof ($window[scope.onCartChanged]) !== 'undefined') {
                    $window[scope.onCartChanged](scope.cartData);
                }

            });


            element.on('$destroy', function () {
                // Dispose watcher
                watcher();
            });

            scope.loadData();
        }
    };
}]);

// Post rendering call to style the controls
angular.module('cart').directive('loadComplete', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            if (scope.$last) {
                $timeout(function () {
                    initMiniCartSlider();
                }, 0);
            }
        }
    }
}]);


angular.module('cart').directive('mmtCheckoutButton', ['$window', 'appUrlBuilder', 'NavigationService', function ($window, appUrlBuilder, navigationService) {
       return {
           restrict: 'A',
           replace: true,
           templateUrl: appUrlBuilder.buildTemplateUrl('mmtCheckoutButtonTemplateUrl'),
           controller: 'CartCtrl',
           scope: {
               showPayPal: '='
           },

           link: function (scope) {
               scope.SubmitPayPalExpress = function () {
                   navigationService.navigate(appUrlBuilder.buildUrl('submitPayPalExpressUrl'));
               };

               scope.isValidForCheckout = function () {
                   var count = 0;
                   if (scope.cartData.IsOrderFormOrderable === true) {
                       for (var i = 0; i < scope.cartData.items.length; i++) {
                           if (scope.cartData.items[i].isDeleted !== true) {
                               count += 1;
                           }
                       }
                       if (count > 0) {
                           return true;
                       }
                   }
                   return false;
               };

               scope.signInCheckout = function () {
                   if (!scope.isValidForCheckout()) {
                       return;
                   }
                   if (scope.cartData.signedIn) {
                       navigationService.navigate(appUrlBuilder.buildUrl('checkoutPageUrl'));
                   } else {
                       navigationService.navigate(appUrlBuilder.buildUrl('checkoutPageUrl'));
                   }
               };

               scope.checkout = function () {
                   if (!scope.isValidForCheckout()) {
                       return;
                   }
                   navigationService.navigate(appUrlBuilder.buildUrl('checkoutPageUrl'));
               };

           }
       };
    }]);;
'use strict';

/**
 * this is service that stores cart data, shared across multiple cart directives
 */

angular.module('checkout').factory('CheckoutDataStorageService',
    function () {
        var checkoutState = {
            billingSec: false,
            checkoutState: true,
            createAccountSec: false,
            accountPasswordSec: false,
            sumitCartErrorSec: false,
            paymentSec: true,
            addressSec: false,
            receiverSec: false,
            deliverToSec: false,
            shipUsingSec: false,
            shippingMethodSec: false,
            phoneEmailSec: false,
            contactSec: false,
            billingAddressSec: false,

            show3Ds: false,
            threeDsNotifierUrl: '',
            pass3Ds: false,

            hpciProcessed: false,

            shippingSelected: false,
            hasExistingCards: false,

			currentStage: 2,
			risCurrentStage: 1,

            paymentType: 0,

            errorMessage: '',

            giftCards: [],

            creditCardData: {},
            showCscForExistingCard: true,
            invalidCscForExistingCard: false,
            invalidCardForExistingCard: false,
            signedIn: false,
            newCreditCardError: false,


            customerShippingAddresses: {},
            IsShippingRateUPSAccessLocation:false

    };

        return {
            checkoutState: checkoutState
        };
    });;
/**
* This is platform implemented checkout
*/
angular.module('checkout').directive('mmtCheckout',
    ['$window', 'appUrlBuilder', 'CheckoutSvc', 'NavigationService',
    function ($window, appUrlBuilder, checkoutSvc, navigationService) {
        return {
            restrict: 'A',
            templateUrl: appUrlBuilder.buildTemplateUrl('checkoutTemplateUrl'),
            scope: {
            },
            controller: 'CheckoutCtrl',
            link: function (scope) {
                scope.stores = {};
                scope.preSelectedCreditCard = false;
                scope.confirmCancel = function () {
                    checkoutSvc.confirmDialog();
                };
                scope.goBackToStore = function () {
                    navigationService.navigate(appUrlBuilder.buildUrl('homePageUrl'));
                };

                scope.preloadData();
            }
        };
    }]);;
'use strict';

angular.module("checkout").requires.push('ui.mask');


/**
 * Responsible for all checkout specific logic
 */
angular.module('checkout').controller('CheckoutCtrl', ['$scope', '$window', 'CheckoutSvc', 'CartDataStorageService', 'ShippingService', 'AppObserver', 'AddressDataHelper', 'siteConfiguration', 'siteRes', 'CheckoutDataStorageService', 'CheckoutSubmitCartSvc', 'CheckoutHelperService', 'CheckoutCreditCardValidationService', 'anchorHelper', 'spinnerFactory', '$timeout', '$modal', 'appUrlBuilder', 'NavigationService', 'UpsSvc',
    function ($scope, $window, checkoutSvc, cartDataStorageService, shippingService, appObserver, addressDataHelper, siteConfiguration, siteRes, checkoutDataStorageService, checkoutSubmitCartSvc, checkoutHelperService, checkoutCreditCardValidationService, anchorHelper, spinnerFactory, $timeout, $modal, appUrlBuilder, navigationService, upsSvc) {
        $scope.contactInfoBtn = "Next";
        $scope.shippingMethodBtn = "Next";
        $scope.cartData = cartDataStorageService.cartData;
        $scope.checkoutState = checkoutDataStorageService.checkoutState;
        $scope.addressBtn = "Next";
        $scope.identityName = 'CheckoutCtrl';
        $scope.password = '';
        $scope.editShippingAddressId = 0;
        //for paypal
        $scope.firstName = '';
        $scope.lastName = '';
        $scope.updateShippingAddressSuccess = true;
        $scope.emailRegex = siteConfiguration.emailRegex;
        $scope.billingIncomplete = false;
		// Store the selected Nearest UPS Location
        var selectedUpsLocation = {};
        var isUpsLocationSelected = false;


        //Ups
        $scope.checkoutState.upsShippingRateId = [];
        $scope.checkoutState.upsShippingRateId.push(siteConfiguration.upsShippingRateId);
        $scope.checkoutState.upsShippingRateId.push(siteConfiguration.upsShippingRateIdUs);
        $scope.checkoutState.ModalSelectedUps = false;
        //console.log("Ups Shipping rate: " + siteConfiguration.upsShippingRateId);
        // use the below propery to show/hide the "same as shipping" option/checkbox on checkout to the user for billing address when he has selected UPS access point shipping rate
        $scope.checkoutState.IsShippingRateUPSAccessLocation = false;
        // var shippingAddressIsEmpty = true;

        $scope.preloadData = function () {
            //preload cart data
            cartDataStorageService.loadCartData().then(function () {
                // updateScoppingCartItemsCount($scope.cartData);
                if ($scope.cartData.signedIn) {
                    $scope.checkoutState.signedIn = true;

                    spinnerFactory.show("Please wait...");
                    disableScrollOnSpinnerShow();

                    checkoutSvc.getCustomerAddresses()
                        .$promise.then(function (value) {
                            $scope.checkoutState.customerShippingAddresses = value;
                            $scope.checkoutState.hasShippingAddresses = true;

                            enableScrollOnSpinnerHide();
                            spinnerFactory.hide();
                        },
                        function (error) {
                            console.log('Error for GetCustomerAddresses()', error);

                            enableScrollOnSpinnerHide();
                            spinnerFactory.hide();
                        });

                }

                //stage = 3 means come from PayPal express
                $scope.PayPalExpress = checkoutSvc.parseQueryString($window.location.search, 'stage') === '3';
                //var lastOrderInfo = $scope.cartData.addressInfo.LastOrderInfo;
                var currentOrderInfo = $scope.cartData.addressInfo.CurrentOrderInfo;
                if (!$scope.cartData.signedIn) {
                    $scope.clearAddress($scope.cartData.addressInfo.ShippingAddress);
                    $scope.clearAddress($scope.cartData.addressInfo.BillingAddress);
                }
                //var sAddress = $scope.cartData.signedIn && !$scope.PayPalExpress ? lastOrderInfo.ShippingAddress : $scope.cartData.addressInfo.ShippingAddress;
                //shippingAddressIsEmpty = sAddress.Address1 === '' && sAddress.City === '' && sAddress.Province === '';
                //if ($scope.cartData.signedIn && shippingAddressIsEmpty) {
                //    sAddress = $scope.cartData.addressInfo.BillingAddress;
                //}
                var sAddress = $scope.cartData.addressInfo.ShippingAddress;
                var bAddress = $scope.cartData.addressInfo.BillingAddress;
                var shippingAddress = checkoutHelperService.addressDataMap(sAddress);
                var billingAddress = checkoutHelperService.addressDataMap(bAddress);
                $scope.addressData = { shippingData: shippingAddress, billingData: billingAddress };

                //for guest user: only show address section, hide all other sections
                //for registered user: user's last shipping address, payment method and shipping method use to pre-populate the existing form
                if (!$scope.cartData.signedIn) {
                    // $scope.shippingRate = currentOrderInfo.ShipperId;
                }
                if ($scope.cartData.signedIn) {

                    //bvc
                    if ($scope.addressData.billingData.address1 == "") {
                        $scope.billingIncomplete = true;
                    }

                    //  $scope.updateShippingAddress(shippingAddress, true);

                    //$scope.cartData.phone = shippingAddressIsEmpty ? $scope.cartData.customer.Phone : lastOrderInfo.Phone;
                    $scope.cartData.phone = $scope.cartData.customer.Phone;
                    var orderPhoneNumber = $scope.cartData.phone;
                    //orderPhoneNumber = orderPhoneNumber.length >= 10 ? orderPhoneNumber.replace(/(\d{3})(\d{3})(\d{4})?/, "$1-$2-$3") : orderPhoneNumber;
                    $scope.checkoutState.OrderPhoneNumber = orderPhoneNumber;
                    //$scope.cartData.email = shippingAddressIsEmpty ? $scope.cartData.customer.Email : lastOrderInfo.Email;
                    $scope.cartData.email = $scope.cartData.customer.Email;
                    //$scope.shippingRate = currentOrderInfo.ShipperId === 0 ? lastOrderInfo.ShipperId : currentOrderInfo.ShipperId;
                    // Note: ReceiverName is deprecated since we have it in the AddressInfo of the shipping object
                    $scope.cartData.receiverName = '';
                    $scope.firstName = $scope.cartData.customer.FirstName;
                    $scope.lastName = $scope.cartData.customer.LastName;

                    $scope.cartData.isGift = currentOrderInfo.IsGift;
                    $scope.cartData.giftNote = currentOrderInfo.GiftNote;
                    //$scope.checkoutState.paymentType = $scope.PayPalExpress ? 2 : lastOrderInfo.PaymentType;
                    $scope.checkoutState.addressSec = false;
                    $scope.checkoutState.receiverSec = false;
                    $scope.checkoutState.deliverToSec = true;
                    //$scope.checkoutState.shippingMethodSec = true;
                    $scope.checkoutState.shipUsingSec = false;
                    $scope.checkoutState.contactSec = true;
                    //$scope.checkoutState.currentStage = 3;
                    if ($scope.cartData.ExistingCreditCards != null && $scope.cartData.ExistingCreditCards.length > 0) {
                        //$scope.checkoutState.paymentType = 3;
                        $scope.preSelectedCreditCard = true;
                        $scope.checkoutState.hasExistingCards = true;
                        //$scope.paymentMethods.showExistingCreditCardChecked = true;
                        //if ($scope.cartData.ExistingCreditCards.length === 1) {
                        //    $scope.checkoutState.existingCreditCardData = $scope.cartData.ExistingCreditCards[0];
                        //}
                        $scope.checkoutState.existingCreditCardData = $scope.cartData.ExistingCreditCards[0];
                    }
                    jQuery('.accordion').slideAccordion({
                        opener: '.accordion-opener',
                        slider: '.accordion-slide',
                        animSpeed: 400
                    });
                } else {
                    $scope.checkoutState.addressSec = true;
                }
                //$scope.paymentMethods.showCreditCardChecked = $scope.checkoutState.paymentType === 1;
            });
        };

        $scope.clearAddress = function (address) {
            address.FirstName = '';
            address.LastName = '';
            address.Address1 = '';
            address.Address2 = '';
            address.Address3 = '';
            address.City = '';
            address.Province = '';
            address.PostalCode = '';
            if (address.Country !== null) {
                address.Country.CountryCode = '';
                address.Country.CountryName = '';
                address.Country.CountryId = -1;
            }
        };

        $scope.updateShippingAddress = function (data, isInit) {
            spinnerFactory.show("Please wait...");
            disableScrollOnSpinnerShow();
            $scope.addressData.shippingData = data;
            addressDataHelper.updateShippingData(data);

            //display shipping rates
            $scope.getShippingRates(data);

            addressDataHelper.updateBillingData(data);
            shippingService.updateShippingAddress(data.country.countryId, data.postalCode, false, data.province, data.city, data.address1, data.address2, data.address3).$promise.then(
                function (value) {
                    cartDataStorageService.loadCartData();
                    $scope.updateShippingAddressSuccess = true;
                    if (!value.Success) {
                        console.log(value.Message);
                    }
                    $scope.checkoutState.addressSec = false;
                    $scope.checkoutState.receiverSec = isInit ? !$scope.cartData.signedIn : true;
                    spinnerFactory.hide();
                    enableScrollOnSpinnerHide();
                }, function () {
                    $scope.updateShippingAddressSuccess = false;
                    console.log('updateShippingAddress error occur');
                    spinnerFactory.hide();
                    enableScrollOnSpinnerHide();
                });
            
        };

        $scope.editBillingInfo = function () {
            $scope.checkoutState.billingSec = false;
            $scope.checkoutState.paymentSec = true;
            $scope.checkoutState.createAccountSec = false;
            $scope.checkoutState.accountPasswordSec = false;
            $scope.checkoutState.retryEmailSec = false;
            if ($scope.checkoutState.newCreditCardError === false) {
                $scope.checkoutState.sumitCartErrorSec = false;
            } else {
                $scope.checkoutState.sumitCartErrorSec = true;
            }

            if (checkoutSvc.hpciEnabled()) {
                hpciStatus = "";
                $scope.checkoutState.hpciProcessed = false;
            }
            if ($scope.cartData.signedIn) {
                $scope.preSelectedCreditCard = false;

                //bvc
                if ($scope.checkoutState.newCreditCardError === false) {
                    $scope.checkoutState.creditCardData.cardNumber = "";
                    $scope.checkoutState.creditCardData.expireMonth = "";
                    $scope.checkoutState.creditCardData.expireYear = "";
                    $scope.checkoutState.creditCardData.name = "";
                    $scope.checkoutState.creditCardData.cardType = "";
                    $scope.checkoutState.creditCardData.cardTypeId = 0;
                    $scope.checkoutState.creditCardData.cardValidation = "";
                    setTimeout(function () {
                        $("#cardChkBox").parent().click();
                    }, 20);
                }


            }

        };

        $scope.goToCreditCardList = function () {
            if ($scope.cartData.signedIn) {
                if ($scope.cartData.ExistingCreditCards != null && $scope.cartData.ExistingCreditCards.length > 0) {
                    $scope.checkoutState.paymentType = 3;
                    $scope.preSelectedCreditCard = true;
                    setTimeout(function () {
                        $("#preCardChkBox").parent().click();
                    }, 20);
                    $scope.checkoutState.hasExistingCards = true;
                    $scope.paymentMethods.showExistingCreditCardChecked = true;
                }
            }
        };
        $scope.checkExpiredYearMonth = function () {
            if ($scope.checkoutState.creditCardData.expireMonth === undefined) return false;
            if ($scope.checkoutState.creditCardData.expireYear === undefined) return true;
            if ($scope.checkoutState.creditCardData.expireYear <= 0) return false;
            if ($scope.checkoutState.creditCardData.expireMonth <= 0) return false;
            var today = new Date();
            var expired = new Date($scope.checkoutState.creditCardData.expireYear, $scope.checkoutState.creditCardData.expireMonth, today.getDate());
            if (expired.getTime() < today.getTime())
                return false;
            return true;
        }
        //Region payment

        $scope.onPhoneNumberChanged = function () {
            $scope.checkoutState.isPhoneNoValid = $scope.checkoutState.OrderPhoneNumber === undefined || $scope.checkoutState.OrderPhoneNumber.length <= 0 ? false : true;
            $scope.checkoutState.isPhoneNoDirty = !$scope.isPhoneNoValid;
            //if ($scope.checkoutState.isPhoneNoValid) {
            //    $scope.checkoutState.isPhoneNoFormatValid = $scope.phoneNumberPattern.test($scope.checkoutState.OrderPhoneNumber);
            //}
        };
        $scope.checkoutState.isPhoneNoFormatValid = function () {
            if (!$scope.checkoutState.OrderPhoneNumber) return false;
            return /^\+?\d{3}-?\d{3}-?\d{4}$/.test($scope.checkoutState.OrderPhoneNumber);
        }

        //$scope.phoneNumberPattern = (function () {
        //    var regexp = /^\+?\d{3}-?\d{3}-?\d{4}$/;
        //    return {
        //        test: function (value) {
        //            return regexp.test(value);
        //        }
        //    };
        //})();

        $scope.onSubmitCart = function () {
            if (!$scope.shippingRate) {
                $scope.checkoutState.sumitCartErrorSec = true;
                $scope.checkoutState.errorMessage = siteRes.SelectShippingRate;
                return false;
            }

            if ($scope.cartData.signedIn && !$scope.paymentMethods.showExistingCreditCardChecked && !$scope.paymentMethods.showPayPalChecked && !$scope.paymentMethods.showCreditCardChecked && !$scope.paymentMethods.showGiftCardChecked && !$scope.paymentMethods.showHappyCardChecked && $scope.cartData.total > 0) {
                $scope.checkoutState.sumitCartErrorSec = true;
                $scope.checkoutState.errorMessage = "Please select payment option";
                return false;
            }
            else if ($scope.cartData.signedIn && ($scope.paymentMethods.showExistingCreditCardChecked || $scope.paymentMethods.showExistingCreditCardChecked)) {
                $scope.checkoutState.sumitCartErrorSec = false;
            }

            if ($scope.cartData.signedIn && $scope.checkoutState.hasExistingCards && $scope.checkoutState.showCscForExistingCard && $scope.paymentMethods.showExistingCreditCardChecked) {
                if ($scope.checkoutState.existingCreditCardData == null) {
                    $scope.checkoutState.invalidCardForExistingCard = true;
                    $scope.checkoutState.invalidCscForExistingCard = true;
                    return false;
                }
                if ($scope.checkoutState.existingCreditCardData.CreditCardId == '' || $scope.checkoutState.existingCreditCardData.CreditCardId == undefined) {
                    $scope.checkoutState.invalidCardForExistingCard = true;
                    return false;
                }
                if ($scope.checkoutState.existingCreditCardData.Csc == '' || $scope.checkoutState.existingCreditCardData.Csc == undefined) {
                    $scope.checkoutState.invalidCscForExistingCard = true;
                    return false;
                }
            }
            //if ($scope.cartData.signedIn && $scope.paymentMethods.showExistingCreditCardChecked && ($scope.checkoutState.OrderPhoneNumber === undefined || $scope.checkoutState.OrderPhoneNumber.length <= 0)) {
            //    $scope.checkoutState.sumitCartErrorSec = true;
            //    $scope.checkoutState.errorMessage = "Please enter phone number";
            //    $scope.checkoutState.isPhoneNoValid = false;
            //    $scope.checkoutState.isPhoneNoDirty = !$scope.checkoutState.isPhoneNoValid;
            //    $scope.payementForm.OrderPhoneNumber.$pristine = false;
            //    $scope.payementForm.OrderPhoneNumber.$setViewValue($scope.checkoutState.OrderPhoneNumber === "" ? undefined : "");
            //    return false;
            //} else if ($scope.cartData.signedIn && $scope.paymentMethods.showExistingCreditCardChecked && !$scope.checkoutState.isPhoneNoFormatValid()) {

            //if (!$scope.checkoutState.isPhoneNoFormatValid()) {
            if ($scope.checkoutState.OrderPhoneNumber == "") {
                $scope.checkoutState.sumitCartErrorSec = true;
                //$scope.checkoutState.errorMessage = "Please enter phone number";
                $scope.checkoutState.errorPhoneMessage = "Please enter phone number";
                //$scope.checkoutState.isPhoneNoFormatValid = false;
                $scope.payementForm.OrderPhoneNumber.$pristine = false;
                //$scope.payementForm.OrderPhoneNumber.$setViewValue($scope.checkoutState.OrderPhoneNumber === "" ? undefined : "");
                return false;
            }

            if (($scope.paymentMethods.showCreditCardChecked === true && $scope.preSelectedCreditCard === false)) {
                $scope.checkoutState.creditCardsuccess = true;
                if ($scope.checkoutState.creditCardData.cardTypeId === 0 || $scope.checkoutState.creditCardData.cardTypeId === undefined ||
                    $scope.checkoutState.creditCardData.expireMonth === "" || $scope.checkoutState.creditCardData.expireMonth === undefined ||
                    $scope.checkoutState.creditCardData.expireYear === "" || $scope.checkoutState.creditCardData.expireYear === undefined ||
                    $scope.checkoutState.creditCardData.name === "" || $scope.checkoutState.creditCardData.name === undefined ||
                    $scope.checkoutState.hpciCCValidValue !== "Y") {
                    $scope.checkoutState.sumitCartErrorSec = true;
                    $scope.checkoutState.errorMessage = "Please enter credit card details";

                    if ($scope.checkoutState.creditCardData.cardTypeId === 0 || $scope.checkoutState.creditCardData.cardTypeId === undefined) {
                        $scope.payementForm.cardType.$pristine = false;
                        $scope.payementForm.cardType.$setViewValue($scope.payementForm.cardType.$viewValue);
                        //$scope.checkoutState.errorMessage += "Card type,";
                    }
                    if ($scope.checkoutState.creditCardData.name === "" || $scope.checkoutState.creditCardData.name === undefined) {
                        $scope.payementForm.cardholdername.$pristine = false;
                        $scope.payementForm.cardholdername.$setViewValue($scope.payementForm.cardholdername.$viewValue);
                        //$scope.checkoutState.errorMessage += "Cardholder name,";
                    }
                    if ($scope.checkoutState.hpciCCValidValue !== "Y") {
                        //$scope.checkoutState.errorMessage += "Card number,";
                        sendHPCIChangeStyleMsg("ccNum", "border-color", "#d73a47");
                        sendHPCIValidationMsg_NUM("block");

                    }
                    if ($scope.checkoutState.hpciCVVValidValue !== "Y") {
                        // $scope.checkoutState.errorMessage += "Security code,";
                        sendHPCIChangeStyleMsg("ccCVV", "border-color", "#d73a47");
                        sendHPCIValidationMsg_CVV("block");

                    }
                    if ($scope.checkoutState.creditCardData.expireYear === "" || $scope.checkoutState.creditCardData.expireYear === undefined) {

                        $scope.payementForm.year.$pristine = false;
                        $scope.payementForm.year.$setViewValue($scope.checkoutState.creditCardData.expireYear === "" ? undefined : "");

                        //$scope.checkoutState.errorMessage += "Expire year,";
                    }
                    if ($scope.checkoutState.creditCardData.expireMonth === "" || $scope.checkoutState.creditCardData.expireMonth === undefined) {
                        $scope.payementForm.month.$pristine = false;
                        $scope.payementForm.month.$setViewValue($scope.checkoutState.creditCardData.expireMonth === "" ? undefined : "");
                        //$scope.checkoutState.errorMessage += "Expire month,";
                    }
                    if ($scope.checkoutState.OrderPhoneNumber === undefined || $scope.checkoutState.OrderPhoneNumber.length <= 0) {
                        $scope.checkoutState.isPhoneNoValid = false;
                        $scope.checkoutState.isPhoneNoDirty = !$scope.checkoutState.isPhoneNoValid;
                        $scope.payementForm.OrderPhoneNumber.$pristine = false;
                        $scope.payementForm.OrderPhoneNumber.$setViewValue($scope.checkoutState.OrderPhoneNumber === "" ? undefined : "");
                    }
                    //else if ($scope.checkoutState.OrderPhoneNumber === undefined || $scope.checkoutState.OrderPhoneNumber.length <= 0 || !$scope.checkoutState.isPhoneNoFormatValid()) {
                    //    //$scope.checkoutState.isPhoneNoFormatValid = false;
                    //    $scope.payementForm.OrderPhoneNumber.$pristine = false;
                    //    //$scope.payementForm.OrderPhoneNumber.$setViewValue($scope.checkoutState.OrderPhoneNumber === "" ? undefined : "");
                    //}
                    if (!$scope.cartData.signedIn && !$scope.billingSame && !$scope.checkoutState.billingAddressSec &&
                        ($scope.payementForm.billingAddressForm.$invalid || (!$scope.payementForm.billingAddressForm.isFormSubmitted || !$scope.payementForm.billingAddressForm.isFormUpdated))) {
                        if ($scope.payementForm.billingAddressForm.fullForm_firstName.$invalid) {
                            $scope.payementForm.billingAddressForm.fullForm_firstName.$pristine = false;
                            $scope.payementForm.billingAddressForm.fullForm_firstName.$setViewValue($scope.payementForm.billingAddressForm.fullForm_firstName.$viewValue);
                        }
                        if ($scope.payementForm.billingAddressForm.fullForm_lastName.$invalid) {
                            $scope.payementForm.billingAddressForm.fullForm_lastName.$pristine = false;
                            $scope.payementForm.billingAddressForm.fullForm_lastName.$setViewValue($scope.payementForm.billingAddressForm.fullForm_lastName.$viewValue);
                        }
                        if ($scope.payementForm.billingAddressForm.fullForm_address1.$invalid) {
                            $scope.payementForm.billingAddressForm.fullForm_address1.$pristine = false;
                            $scope.payementForm.billingAddressForm.fullForm_address1.$setViewValue($scope.payementForm.billingAddressForm.fullForm_address1.$viewValue);
                        }
                        if ($scope.payementForm.billingAddressForm.fullForm_country.$invalid) {
                            $scope.payementForm.billingAddressForm.fullForm_country.$pristine = false;
                            $scope.payementForm.billingAddressForm.fullForm_country.$setViewValue($scope.payementForm.billingAddressForm.country.$viewValue);
                        }

                        if ($scope.payementForm.billingAddressForm.fullForm_postalCode.$invalid) {
                            $scope.payementForm.billingAddressForm.fullForm_postalCode.$pristine = false;
                            $scope.payementForm.billingAddressForm.fullForm_postalCode.$setViewValue($scope.payementForm.billingAddressForm.fullForm_postalCode.$viewValue);
                        }
                        if ($scope.payementForm.billingAddressForm.fullForm_city.$invalid) {
                            $scope.payementForm.billingAddressForm.fullForm_city.$pristine = false;
                            $scope.payementForm.billingAddressForm.fullForm_city.$setViewValue($scope.payementForm.billingAddressForm.fullForm_city.$viewValue);
                        }
                        if ($scope.payementForm.billingAddressForm.fullForm_province.$invalid) {
                            $scope.payementForm.billingAddressForm.fullForm_province.$pristine = false;
                            $scope.payementForm.billingAddressForm.fullForm_province.$setViewValue($scope.payementForm.billingAddressForm.fullForm_province.$viewValue);
                        }
                        if ($scope.payementForm.billingAddressForm.phone.$invalid) {
                            $scope.payementForm.billingAddressForm.phone.$pristine = false;
                            $scope.payementForm.billingAddressForm.phone.$setViewValue($scope.payementForm.billingAddressForm.phone.$viewValue);
                        }
                    }
                    return false;
                }
                if ($scope.paymentMethods.showCreditCardChecked === true && $scope.preSelectedCreditCard === false && !$scope.checkExpiredYearMonth()) {
                    $scope.checkoutState.sumitCartErrorSec = true;
                    $scope.checkoutState.errorMessage = "Please enter valid expiry";
                    return false;
                }

                if (!$scope.cartData.signedIn && !$scope.billingSame && !$scope.checkoutState.billingAddressSec &&
                    ($scope.payementForm.billingAddressForm.$invalid || (!$scope.payementForm.billingAddressForm.isFormSubmitted || !$scope.payementForm.billingAddressForm.isFormUpdated))) {
                    $scope.checkoutState.sumitCartErrorSec = true;
                    $scope.checkoutState.errorMessage = "Please enter billing address detail";
                    if ($scope.payementForm.billingAddressForm.fullForm_firstName.$invalid) {
                        $scope.payementForm.billingAddressForm.fullForm_firstName.$pristine = false;
                        $scope.payementForm.billingAddressForm.fullForm_firstName.$setViewValue($scope.payementForm.billingAddressForm.fullForm_firstName.$viewValue);
                    }
                    if ($scope.payementForm.billingAddressForm.fullForm_lastName.$invalid) {
                        $scope.payementForm.billingAddressForm.fullForm_lastName.$pristine = false;
                        $scope.payementForm.billingAddressForm.fullForm_lastName.$setViewValue($scope.payementForm.billingAddressForm.fullForm_lastName.$viewValue);
                    }
                    if ($scope.payementForm.billingAddressForm.fullForm_address1.$invalid) {
                        $scope.payementForm.billingAddressForm.fullForm_address1.$pristine = false;
                        $scope.payementForm.billingAddressForm.fullForm_address1.$setViewValue($scope.payementForm.billingAddressForm.fullForm_address1.$viewValue);
                    }
                    if ($scope.payementForm.billingAddressForm.fullForm_country.$invalid) {
                        $scope.payementForm.billingAddressForm.fullForm_country.$pristine = false;
                        $scope.payementForm.billingAddressForm.fullForm_country.$setViewValue($scope.payementForm.billingAddressForm.country.$viewValue);
                    }

                    if ($scope.payementForm.billingAddressForm.fullForm_postalCode.$invalid) {
                        $scope.payementForm.billingAddressForm.fullForm_postalCode.$pristine = false;
                        $scope.payementForm.billingAddressForm.fullForm_postalCode.$setViewValue($scope.payementForm.billingAddressForm.fullForm_postalCode.$viewValue);
                    }
                    if ($scope.payementForm.billingAddressForm.fullForm_city.$invalid) {
                        $scope.payementForm.billingAddressForm.fullForm_city.$pristine = false;
                        $scope.payementForm.billingAddressForm.fullForm_city.$setViewValue($scope.payementForm.billingAddressForm.fullForm_city.$viewValue);
                    }
                    if ($scope.payementForm.billingAddressForm.fullForm_province.$invalid) {
                        $scope.payementForm.billingAddressForm.fullForm_province.$pristine = false;
                        $scope.payementForm.billingAddressForm.fullForm_province.$setViewValue($scope.payementForm.billingAddressForm.fullForm_province.$viewValue);
                    }
                    if ($scope.payementForm.billingAddressForm.phone.$invalid) {
                        $scope.payementForm.billingAddressForm.phone.$pristine = false;
                        $scope.payementForm.billingAddressForm.phone.$setViewValue($scope.payementForm.billingAddressForm.phone.$viewValue);
                    } else if (!$scope.payementForm.billingAddressForm.isFormSubmitted || !$scope.payementForm.billingAddressForm.isFormUpdated) {
                        $scope.checkoutState.errorMessage = "Please submit billing address form";
                    }
                    return false;
                }
            }

            //new happy card
            if ($scope.paymentMethods.showHappyCardChecked === true) {
                $scope.PopulateHappyCardInfo();
            }

            //bvc
            if ($scope.paymentMethods.showGiftCardChecked && $scope.checkoutState.giftCards.length <= 0) {
                $scope.checkoutState.sumitCartErrorSec = true;
                $scope.checkoutState.errorMessage = "Please complete your gift card payment information.";
                return false;
            } else {
                $scope.checkoutState.sumitCartErrorSec = false;
            }

            //if (($scope.paymentMethods.showCreditCardChecked || $scope.paymentMethods.showExistingCreditCardChecked) && $scope.paymentMethods.showGiftCardChecked) {
            //    if ($scope.checkoutState.giftCards.length <= 0) {
            //        $scope.checkoutState.sumitCartErrorSec = true;
            //        $scope.checkoutState.errorMessage = "Please complete all payment info.";
            //        return false;
            //    }
            //    else {
            //        $scope.checkoutState.sumitCartErrorSec = false;
            //    }
            //}

            if (!$scope.paymentMethods.showGiftCardChecked && $scope.checkoutState.giftCards.length > 0) {
                $scope.checkoutState.sumitCartErrorSec = true;
                if ($scope.paymentMethods.showHappyCardChecked) {
                    $scope.checkoutState.errorMessage = "These payment methods cannot be combined.";
                } else {
                    $scope.checkoutState.errorMessage = "Please remove gift card amount.";
                }
                return false;
            }
            else {
                $scope.checkoutState.sumitCartErrorSec = false;
            }

            //if (!$scope.cartData.signedIn) {

            //    spinnerFactory.show("Please wait...");
            //    disableScrollOnSpinnerShow();

            //    var storeDataTimeout;
            //    $.ajax({
            //        url: rootRel + 'Stores/ListAllStores?countryCode=' + $scope.addressData.shippingData.country.countryCode,
            //        success: function (data) {
            //            if (data) {
            //                storeDataTimeout = $timeout(function () {
            //                    $scope.stores = data;
            //                    spinnerFactory.hide();
            //                    enableScrollOnSpinnerHide();
            //                }, 250);
            //            }
            //        }
            //    });
            //}

            //spinnerFactory.show("Please wait...");
            //disableScrollOnSpinnerShow();

            //console.log($scope.checkoutState.OrderPhoneNumber);
            checkoutSubmitCartSvc.addPaymentPhoneNumber($scope.checkoutState.OrderPhoneNumber);

            //remove the OOS items from the cart and check if can proceed to place order.
            if ($scope.cartData.signedIn) {
                if ($scope.ArrayContains($scope.checkoutState.upsShippingRateId, $scope.checkoutState.SelectedShippingRateId)) {
                    $scope.SetUpsAddressAsShippingAdderess();
                }
                checkoutSvc.addAddressDataToOrderForm(addressDataHelper.getShippingData(), addressDataHelper.getBillingData(), addressDataHelper.getSameAsShippingAddress()).$promise.then(
                    function () {
                        if (!addressDataHelper.getSameAsShippingAddress()) {
                            cartDataStorageService.loadCartData();
                        }
                        checkoutSubmitCartSvc.submitOrder($scope.checkoutState, $scope.cartData);

                    }, function (error) {
                        console.log(error);
                    });
            } else {

                checkoutSubmitCartSvc.submitOrder($scope.checkoutState, $scope.cartData);
            }

            return true;
        };

        //try to submit a card on hpci processed, this method is called externally, from hpci handler
        $scope.onHpciProcessed = function () {
            //bvc hpci check
            console.log("hpci check > " + $scope.checkoutState.newCreditCardError + "|" + $scope.checkoutState.paymentType + "|" + $scope.checkoutState.creditCardData.cardNumber + "|" + $scope.checkoutState.hpciProcessed);

            if ($scope.checkoutState.hpciProcessed === true) {
                checkoutSubmitCartSvc.processCreditCardPayment($scope.checkoutState, $scope.cartData);
            }
        };

        //EndRegion payment

        //Region 3ds

        $scope.verify3Ds = function () {
            return checkoutSubmitCartSvc.verify3Ds($scope.checkoutState);
        };

        //EndRegion 3ds

        $scope.phoneEmailSecDone = function () {
            $scope.$broadcast('show-errors-check-validity', 'phoneEmailForm');
            $scope.isPhoneFormSubmitted = true;
            if ($scope.phoneEmailForm.$invalid) {
                return;
            }
            // Note: ReceiverName (name field in the following object) is deprecated 
            // since we have it in the AddressInfo of the shipping object
            var receiverMiscInfo = {
                name: '',
                isGift: $scope.cartData.isGift,
                giftNote: $scope.cartData.giftNote
            };
            checkoutSvc.addReceiverMiscInfoToOrderForm(receiverMiscInfo).$promise.then(
                function () {
                    $scope.checkoutState.phoneEmailSec = false;
                    $scope.checkoutState.contactSec = true;
                    $('input[name=receiverNameFirst]').val($scope.firstName);
                    $('input[name=receiverNameLast]').val($scope.lastName);
                    setTimeout(function () {
                        $('input[name=receiverNameFirst]').change();
                        $('input[name=receiverNameLast]').change();
                    }, 100);
                    jcf.setOptions('Select', {
                        wrapNative: false,
                        wrapNativeOnMobile: false,
                        fakeDropInBody: false
                    });
                    jcf.replaceAll();
                },
                function () {
                    console.log('addReceiverMiscInfoToOrderForm fail');
                });
        };

        $scope.togglePassword = function () {

            if ($scope.passwordType === 'password') {
                $scope.passwordType = 'text';
            } else {
                $scope.passwordType = 'password';
            }
        };

        $scope.showAccountPasswordSection = function () {
            $scope.checkoutState.createAccountSec = false;
            $scope.checkoutState.accountPasswordSec = true;
        };

        $scope.toggleShippingAddress = function (selectedAddress) {
            $scope.editShippingAddressId = selectedAddress.id;
            $scope.updateShippingAddress(selectedAddress, false);
            $scope.checkoutState.shippingMethodSec = true;
            $scope.checkoutState.shipUsingSec = false;
        }


        $scope.submitGuestOrder = function (generateUserId) {
            var customerData = {};
            //when userId provided means user click on register later button, will create account use default value, don't need validation those three fields
            if (generateUserId) {
                customerData.userId = checkoutHelperService.guid();
            } else {
                $scope.$broadcast('show-errors-check-validity', 'accountPasswordForm');
                if ($scope.accountPasswordForm.$invalid) {
                    return;
                }
            }
            //SK: why????
            if ($scope.password.trim() === '') {
                $scope.password = Math.random().toString(36).slice(-8);
            }
            if ($scope.firstName.trim() === '') {
                $scope.firstName = 'Guest';
            }
            if ($scope.lastName.trim() === '') {
                $scope.lastName = 'Guest';
            }

            if ($scope.cartData.phone === undefined || $scope.cartData.phone.trim() === '') {
                $scope.cartData.phone = $scope.checkoutState.OrderPhoneNumber;
            }

            customerData.email = $scope.cartData.email;
            customerData.phone = $scope.cartData.phone;
            customerData.firstName = $scope.firstName;
            customerData.lastName = $scope.lastName;
            customerData.password = $scope.password;
            customerData.EmailOptIn = $scope.cartData.signupNewsletter;
            customerData.address = addressDataHelper.getBillingData();

            //new happy card
            if ($scope.paymentMethods.showHappyCardChecked === true) {
                $scope.PopulateHappyCardInfo();
            }

            disableScrollOnSpinnerShow();

            if ($scope.ArrayContains($scope.checkoutState.upsShippingRateId, $scope.checkoutState.SelectedShippingRateId)) {
                $scope.SetUpsAddressAsShippingAdderess();
            }
            checkoutSubmitCartSvc.submitGuestOrder(customerData, $scope.checkoutState, $scope.cartData);
            if ($scope.checkoutState.retryEmailSec) {
                enableScrollOnSpinnerHide();
            }
        };

        $scope.paymentMethods = {
            showCreditCardChecked: $scope.checkoutState.paymentType === 1,
            showPayPalChecked: $scope.checkoutState.paymentType === 2,
            showExistingCreditCardChecked: $scope.checkoutState.paymentType === 3,
            showGiftCardChecked: false
        };

        $scope.paymentSectionDone = function () {
            $scope.checkoutState.billingSec = true;
            $scope.checkoutState.paymentSec = false;
            $scope.checkoutState.createAccountSec = true;
        };

        $scope.togglePaymentMethod = function (paymentType) {

            $scope.checkoutState.paymentType = 0;

            // if ($scope.paymentMethods.showCreditCardChecked === true || $scope.paymentMethods.showPayPalChecked === true || $scope.paymentMethods.showExistingCreditCardChecked === true || $scope.paymentMethods.showHappyCardChecked === true) {
            switch (paymentType) {
                case 0://gift card
                    $scope.paymentMethods.showHappyCardChecked = false;
                    break;
                case 1://new card
                    $scope.paymentMethods.showPayPalChecked = false;
                    $scope.paymentMethods.showExistingCreditCardChecked = false;
                    $scope.paymentMethods.showHappyCardChecked = false;
                    break;
                case 2://paypal
                    $scope.paymentMethods.showCreditCardChecked = false;
                    $scope.paymentMethods.showExistingCreditCardChecked = false;
                    $scope.paymentMethods.showHappyCardChecked = false;
                    break;
                case 3://existing card
                    $scope.paymentMethods.showPayPalChecked = false;
                    $scope.paymentMethods.showCreditCardChecked = false;
                    $scope.paymentMethods.showHappyCardChecked = false;
                    break;
                case 4://happy card
                    $scope.paymentMethods.showPayPalChecked = false;
                    $scope.paymentMethods.showCreditCardChecked = false;
                    $scope.paymentMethods.showExistingCreditCardChecked = false;
                    $scope.paymentMethods.showGiftCardChecked = false;
                    break;
                default:
                    break;
                // }
            }

            if ($scope.paymentMethods.showCreditCardChecked === true) {
                $scope.checkoutState.paymentType = 1;

                //happy card workaround
                setTimeout(function () {
                    if ($('#hpciNewCreditCard').html() == "") {
                        $('#hpciHappyCard').contents().appendTo('#hpciNewCreditCard');
                        if (isMobileDevice) {
                            $(window).scrollTop(0);
                        }
                    }
                }, 200);

            }
            else if ($scope.paymentMethods.showPayPalChecked === true) {
                $scope.checkoutState.paymentType = 2;
            }
            else if ($scope.paymentMethods.showExistingCreditCardChecked === true) {
                $scope.checkoutState.paymentType = 3;
            }
            else if ($scope.paymentMethods.showHappyCardChecked === true) {
                $scope.checkoutState.paymentType = 4;

                //happy card workaround
                setTimeout(function () {
                    if ($('#hpciHappyCard').html() == "") {
                        $('#hpciNewCreditCard').contents().appendTo('#hpciHappyCard');
                        if (isMobileDevice) {
                            $(window).scrollTop(0);
                        }
                    }
                }, 200);
                
            }
            else {
                $scope.checkoutState.paymentType = 0;
            }

            if ($scope.paymentMethods.showCreditCardChecked === false && $scope.paymentMethods.showPayPalChecked === false && $scope.paymentMethods.showExistingCreditCardChecked === false) {
                $scope.checkoutState.paymentType = 0;
            }
            //$scope.checkoutState.paymentSec = true;


        };

        $scope.selectCheckBox = function (paymentType) {
            switch (paymentType) {
                case 0://gift card
                    $timeout(function () {
                        $scope.paymentMethods.showGiftCardChecked = true;
                        $("#giftCardChkBox").prop('checked', true);
                        $("#happyCardChkBox").prop('checked', false);
                        $scope.togglePaymentMethod(paymentType);
                        jcf.getInstance($('#giftCardChkBox')).refresh();
                        jcf.getInstance($('#happyCardChkBox')).refresh();
                    }, 0);
                    break;
                case 1://new card
                    $timeout(function () {
                        $scope.paymentMethods.showCreditCardChecked = true;
                        $("#cardChkBox").prop('checked', true);
                        $("#paypalChkBox").prop("checked", false);
                        $("#happyCardChkBox").prop('checked', false);
                        $scope.togglePaymentMethod(paymentType);
                        jcf.getInstance($('#cardChkBox')).refresh();
                        jcf.getInstance($('#paypalChkBox')).refresh();
                        jcf.getInstance($('#happyCardChkBox')).refresh();
                    }, 0);
                    break;
                case 2://paypal
                    $timeout(function () {
                        $scope.paymentMethods.showPayPalChecked = true;
                        $("#paypalChkBox").prop('checked', true);
                        $("#cardChkBox").prop("checked", false);
                        $("#preCardChkBox").prop("checked", false);
                        $("#happyCardChkBox").prop('checked', false);
                        $scope.togglePaymentMethod(paymentType);
                        jcf.getInstance($('#cardChkBox')).refresh();
                        jcf.getInstance($('#paypalChkBox')).refresh();
                        jcf.getInstance($('#preCardChkBox')).refresh();
                        jcf.getInstance($('#happyCardChkBox')).refresh();
                    }, 0);
                    break;
                case 3://existing card
                    $timeout(function () {
                        $scope.paymentMethods.showExistingCreditCardChecked = true;
                        $("#preCardChkBox").prop('checked', true);
                        $("#paypalChkBox").prop("checked", false);
                        $("#happyCardChkBox").prop('checked', false);
                        $scope.togglePaymentMethod(paymentType);
                        jcf.getInstance($('#preCardChkBox')).refresh();
                        jcf.getInstance($('#paypalChkBox')).refresh();
                        jcf.getInstance($('#happyCardChkBox')).refresh();
                    }, 0);
                    break;
                case 4://happy card
                    $timeout(function () {
                        $scope.paymentMethods.showHappyCardChecked = true;
                        $("#happyCardChkBox").prop('checked', true);
                        $("#paypalChkBox").prop('checked', false);
                        $("#cardChkBox").prop("checked", false);
                        $("#preCardChkBox").prop("checked", false);
                        $("#giftCardChkBox").prop('checked', false);
                        $scope.togglePaymentMethod(paymentType);
                        jcf.getInstance($('#happyCardChkBox')).refresh();
                        jcf.getInstance($('#cardChkBox')).refresh();
                        jcf.getInstance($('#paypalChkBox')).refresh();
                        jcf.getInstance($('#preCardChkBox')).refresh();
                        jcf.getInstance($('#giftCardChkBox')).refresh();
                    }, 0);
                    break;
                case 5://redeem a perk
                    $timeout(function () {
                        $scope.paymentMethods.showPerkChecked = true;
                        $("#perkCheckBox").prop('checked', true);
                        $scope.togglePaymentMethod(paymentType);
                        jcf.getInstance($('#perkCheckBox')).refresh();
                        jcf.getInstance($('#happyCardChkBox')).refresh();
                        jcf.getInstance($('#cardChkBox')).refresh();
                        jcf.getInstance($('#paypalChkBox')).refresh();
                        jcf.getInstance($('#preCardChkBox')).refresh();

                    }, 0);
                    break;
                default:
                    break;
            }
        }

        $scope.checkBoxClick = function (paymentType) {

            switch (paymentType) {
                case 0://new card
                    $timeout(function () {
                        if ($("#giftCardChkBox").prop('checked') == true) {
                            $('#giftCardChkBox').parents('div.accordion-opener').trigger('click');
                        }
                    }, 0);
                    break;
                case 1://new card

                    $timeout(function () {
                        if ($("#cardChkBox").prop('checked') == true) {
                            $('#cardChkBox').parents('div.accordion-opener').trigger('click');
                        }
                    }, 0);
                    break;
                case 2://paypal

                    $timeout(function () {
                        if ($("#paypalChkBox").prop('checked') == true) {
                            $('#paypalChkBox').parents('div.accordion-opener').trigger('click');
                        }
                    }, 0);
                    break;
                case 3://existing card

                    $timeout(function () {
                        if ($("#preCardChkBox").prop('checked') == true) {
                            $('#preCardChkBox').parents('div.accordion-opener').trigger('click');
                        }
                    }, 0);
                    break;
                case 4://happy card
                    $timeout(function () {
                        if ($("#happyCardChkBox").prop('checked') == true) {
                            $('#happyCardChkBox').parents('div.accordion-opener').trigger('click');
                        }
                    }, 0);
                    break;
                case 5://redeem a perk
                    $timeout(function () {
                        if ($("#perkCheckBox").prop('checked') == true) {
                            $('#perkCheckBox').parents('div.accordion-opener').trigger('click');
                        }
                    }, 0);
                    break;
                default:
                    break;
            }
        }


        $scope.receiverSecDone = function () {
            //spinnerFactory.show();
            $scope.$broadcast('show-errors-check-validity', 'receiverForm');
            if ($scope.receiverForm.$invalid) {
                return;
            } else {
                var data = $scope.addressData.shippingData;
                shippingService.updateShippingAddress(data.country.countryId, data.postalCode, false, data.province, data.city, data.address1, data.address2, data.address3, data.FirstName, data.LastName).$promise.then(
                    function () {
                        if ($scope.ArrayContains($scope.checkoutState.upsShippingRateId, $scope.checkoutState.SelectedShippingRateId)) {
                            $scope.GetNearestUpsLocation();
                        }
                        $scope.checkoutState.receiverSec = false;
                        $scope.checkoutState.deliverToSec = true;
                        $scope.checkoutState.shippingMethodSec = true;
                        //spinnerFactory.hide();
                    });
            }

        };

        $scope.editShippingInfo = function () {
            if ($scope.cartData.signedIn) {
                if ($scope.editShippingAddressId > 0) {
                    $scope.showEditShippingAddressModal();
                }
            } else {
                $scope.checkoutState.addressSec = true;
                $scope.checkoutState.receiverSec = false;
                $scope.checkoutState.deliverToSec = false;
                $scope.checkoutState.shippingMethodSec = false;
                $scope.checkoutState.shipUsingSec = false;
                $scope.checkoutState.phoneEmailSec = false;
                $scope.addressBtn = "Update";
            }
        };

        $scope.editContactInfo = function () {
            $scope.checkoutState.contactSec = false;
            $scope.contactInfoBtn = "Update";
        };

        $scope.shippingMethodSecDone = function () {
            //if user has selected UPS access location shipping rate, then show him the UPS selected location as his shipping address not the one which he entered to find the near by UPS locations
            //and also hide the entered shipping address by the user.
            if ($scope.ArrayContains($scope.checkoutState.upsShippingRateId, $scope.checkoutState.SelectedShippingRateId)) {
                $('#originalShippingAddresses').hide();
                $('#csr-link-edit-shipping-info').hide();
                $('#textSelectedUPSAddress').show();
                $scope.checkoutState.IsShippingRateUPSAccessLocation = true;
                var upsAccessLocation = $scope.checkoutState.SelectedUpsLocation;
				selectedUpsLocation = upsAccessLocation;
				isUpsLocationSelected = true;
                var data = $scope.addressData.shippingData;
                var fn = '';
                var ln = '';
                if (data.firstName != null || data.firstName != undefined) { fn = data.firstName; }
                else { fn = data.firstname }
                if (data.lastName != null || data.lastName != undefined) { ln = data.lastName; }
                else { ln = data.lastname }

                $('#textSelectedUPSAddress').html('<br />' + fn + ' ' + ln + '<br />' + upsAccessLocation.AddressKeyFormat.ConsigneeName + '<br />' + upsAccessLocation.AddressKeyFormat.AddressLine + '<br />' +
                    upsAccessLocation.AddressKeyFormat.PoliticalDivision2 + ' ' + upsAccessLocation.AddressKeyFormat.PoliticalDivision1
                    + ' ' + upsAccessLocation.AddressKeyFormat.PostcodePrimaryLow
                );

            }
            else {
                $('#originalShippingAddresses').show();
                $('#csr-link-edit-shipping-info').show();
                $('#textSelectedUPSAddress').hide();
                $scope.checkoutState.IsShippingRateUPSAccessLocation = false;
            }
            $scope.shippingMethodBtn = "Update";
            $scope.checkoutState.shippingMethodSec = false;
            $scope.checkoutState.shipUsingSec = true;
            //$scope.checkoutState.phoneEmailSec = true;
            if ($scope.cartData.signedIn) {
                if ($scope.cartData.ExistingCreditCards != null && $scope.cartData.ExistingCreditCards.length > 0) {

                    //$scope.paymentMethods.showExistingCreditCardChecked = true;
                    $timeout(function () {
                        //$("#preCardChkBox").prop('checked', true);
                        //jcf.getInstance($('#preCardChkBox')).refresh();
                        $scope.togglePaymentMethod(3);
                        $scope.setBillingAddressDefault();
                    }, 0);


                }
                else {
                    //$scope.paymentMethods.showCreditCardChecked = true;
                    $timeout(function () {
                        //$("#cardChkBox").prop('checked', true);
                        jcf.getInstance($('#cardChkBox')).refresh();
                        $scope.togglePaymentMethod(1);
                        $scope.setBillingAddressDefault();
                    }, 0);

                }
            }
            // update scope variables with selected shipping info
            angular.forEach($scope.shippingRates, function (rate) {
                if (rate.Id == $scope.checkoutState.SelectedShippingRateId) {
                    $scope.updateShippingRate(rate, false);
                }
            });
            $scope.checkoutState.currentStage = 3;
            jQuery('.accordion').slideAccordion({
                opener: '.accordion-opener',
                slider: '.accordion-slide',
                animSpeed: 400
            });
            jQuery(window).resize();
        };

        $scope.setBillingAddressDefault = function () {
            addressDataHelper.updateSameAsShippingAddress(false);
            var data = $scope.cartData.addressInfo.BillingAddress;
            addressDataHelper.updateBillingData(data);
            checkoutSvc.addAddressDataToOrderForm(addressDataHelper.getShippingData(), addressDataHelper.getBillingData(), addressDataHelper.getSameAsShippingAddress()).$promise.then(
                function () {
                    if (!addressDataHelper.getSameAsShippingAddress()) {
                        cartDataStorageService.loadCartData();
                    }
                }, function (error) {
                    console.log(error);
                });
        };

        $scope.editShippingUsing = function () {
            $scope.checkoutState.shippingMethodSec = true;
            $scope.checkoutState.shipUsingSec = false;
            $('#originalShippingAddresses').show();
            $('#csr-link-edit-shipping-info').show();
            $('#textSelectedUPSAddress').hide();
        };

        $scope.getShippingRates = function (shippingData) {
            var shippingCountry = shippingData.country.countryId;
            var shippingProvince = shippingData.province || '';
            var shippingPostalCode = shippingData.postalCode;
            console.log("Get shipping rates. Info > " + shippingCountry + "|" + shippingProvince + "|" + shippingPostalCode);

            shippingService.getShippingRates(shippingCountry, shippingProvince, shippingPostalCode, false).$promise.then(function (value) {

                var rates = [];
                var giftCardShippingMethodName = globalConstants.digitalGiftCardShippingMethod;
                var upsShippingRate = undefined;
                angular.forEach(value.shippingRates, function (rate) {
                    if ($scope.ArrayContains($scope.checkoutState.upsShippingRateId, rate.Id)) {
                        rate.Name = rate.Name.indexOf('-') > 0 ? rate.Name.split('-')[0] : rate.Name;
                        upsShippingRate = rate;
                    } else {
                        if (rate.Name.indexOf(giftCardShippingMethodName) == -1) {
                            rates.push(rate);
                        }
                    }

                    //console.log("Rate > " + rate.Name + "|" + rate.Rate);
                });
                if (upsShippingRate !== undefined) {
                    rates.push(upsShippingRate);
                }

                $scope.shippingRates = rates;

                //pre-select first rate logic
                if (rates.length > 0) {
                    var preSelectRate = true;
                    if ($scope.shippingRate != undefined) {
                        angular.forEach(rates,
                            function (rate) {
                                if (rate.Id == $scope.shippingRate) {
                                    preSelectRate = false;
                                    $scope.checkoutState.SelectedShippingRateId = rate.Id;
                                    if ($scope.ArrayContains($scope.checkoutState.upsShippingRateId, $scope.checkoutState.SelectedShippingRateId)) {
                                        $scope.GetNearestUpsLocation();
                                    }
                                }
                            });
                    }
                    if (preSelectRate) {
                        var rate = rates[0];
                        $scope.shippingRate = rate.Id;
                        $scope.shippingMethod = rate.Name;
                        $scope.shippingAmount = rate.Rate;
                        $scope.leadTimeMessage = rate.LeadTimeMessage;
                        $scope.checkoutState.shippingSelected = true;
                        $scope.updateShippingRate({
                            Name: $scope.shippingMethod,
                            Rate: $scope.shippingAmount,
                            Id: $scope.shippingRate,
                            LeadTimeMessage: $scope.leadTimeMessage
                        },
                            false);
                    }
                }
                //

            });
        };

        $scope.updateShippingRate = function (rate, initLoad) {
            //alert(initLoad);
            //update cart shipper id & reload cart data after rate change
            spinnerFactory.show("Please wait...");
            disableScrollOnSpinnerShow();
            shippingService.updateShippingRate($scope.shippingRate).$promise.then(
                function () {
                    cartDataStorageService.loadCartData();

                    $scope.checkoutState.SelectedShippingRateId = rate.Id;
                    if ($scope.ArrayContains($scope.checkoutState.upsShippingRateId, $scope.checkoutState.SelectedShippingRateId)) {
                        $scope.GetNearestUpsLocation();
                    }
                    //broadcast shippingRateChanged event, then summary controller can do something when shipping rate change(current beheavior is fade in: could change the behavior by modify fade-in class in common.less)
                    //and the ship via will display rate base on this
                    if (!initLoad) {
                        $scope.shippingMethod = rate.Name;
                        $scope.shippingAmount = rate.Rate;
                        $scope.leadTimeMessage = rate.LeadTimeMessage;
                        $scope.checkoutState.shippingSelected = $scope.ArrayContains($scope.checkoutState.upsShippingRateId, $scope.checkoutState.SelectedShippingRateId) ? false : true;
                        //$scope.checkoutState.shippingMethodSec = true;
                        appObserver.broadcast('shippingRateChanged', rate);
                        spinnerFactory.hide();
                        enableScrollOnSpinnerHide();
                        //gotoShippingRateListPosition();
                    }
                }
            );
        };

        $scope.$watch("checkoutState.retryEmailSec", function handleEmailErrorChange(newValue, oldValue) {
            if (newValue === true) {
                enableScrollOnSpinnerHide();
            }
        }
        );

        $scope.$watch("checkoutState.sumitCartErrorSec", function handleEmailErrorChange(newValue, oldValue) {
            if (newValue === true) {
                enableScrollOnSpinnerHide();
            }
        }
        );

        $scope.showShippingAddressModal = function () {
            $modal.open({
                templateUrl: appUrlBuilder.buildTemplateUrl('newShippingAddressTemplateUrl'),
                backdrop: 'static',
                controller: 'mmtcheckoutInstanceCtrl',
                windowClass: 'modal-vertical-centered',
                scope: $scope
            });

        };

        $scope.showEditShippingAddressModal = function () {
            $modal.open({
                templateUrl: appUrlBuilder.buildTemplateUrl('checkoutEditShippingAddressTemplateURL').replace('{0}', $scope.editShippingAddressId),
                backdrop: 'static',
                controller: 'mmtcheckoutInstanceCtrl',
                windowClass: 'modal-vertical-centered',
                scope: $scope
            });

        };


        $scope.updateSelectedCreditCard = function (card) {

            if (card === null || card === undefined) {
                $scope.checkoutState.invalidCardForExistingCard = true;
                $scope.checkoutState.invalidCscForExistingCard = true;
            } else {
                $scope.checkoutState.invalidCardForExistingCard = false;
                $scope.checkoutState.invalidCscForExistingCard = false;
                $scope.checkoutState.existingCreditCardData.DisplayText = card.DisplayText;
                $scope.checkoutState.existingCreditCardData.CreditCardId = card.CreditCardId;
            };
        }

        $scope.totalAfterGiftcardPayment = function () {
            var cartTotal = 0;
            if ($scope.cartData && $scope.cartData.total && $scope.cartData.total > 0) {
                cartTotal = $scope.cartData.total;
                if ($scope.checkoutState && $scope.checkoutState.giftCards && $scope.checkoutState.giftCards.length > 0) {
                    var totalAmount = 0;

                    for (var i = 0, length = $scope.checkoutState.giftCards.length; i < length; i++) {
                        totalAmount += Number($scope.checkoutState.giftCards[i].Amount);
                    }
                    cartTotal -= totalAmount;
                }
            }
            return cartTotal;
        }
        $scope.needPayAfterGiftcardPayment = function () {
            return $scope.totalAfterGiftcardPayment() > 0.0001;
        }



        //UPS - to do
        $scope.GetNearestUpsLocation = function () {
            $scope.checkoutState.shippingSelected = false;
            upsSvc.getNearestUpsLocation(addressDataHelper.getShippingData()).$promise.then(
                function (data) {
                    spinnerFactory.show("Please wait...");
                    disableScrollOnSpinnerShow();
                    if (data.Response.ResponseStatusCode == 1) {
                        if (data.SearchResults.DropLocations.length > 0) {
                            if (isUpsLocationSelected) {
                                $scope.checkoutState.SelectedUpsLocation = selectedUpsLocation;
                            }
                            else
                            {
                                $scope.checkoutState.SelectedUpsLocation = data.SearchResults.DropLocations[0];
                            } 
                            var standardHoursOfOperation =
                                $scope.checkoutState.SelectedUpsLocation.StandardHoursOfOperation;
                            $scope.checkoutState.SelectedUpsLocation.UpsStoreTimes = [];
                            angular.forEach(standardHoursOfOperation.split(';'),
                                function (value, key) {
                                    $scope.checkoutState.SelectedUpsLocation.UpsStoreTimes.push({
                                        'day': value.split(': ')[0],
                                        'time': value.split(': ')[1]
                                    });
                                });
                            $scope.checkoutState.SelectedUpsLocation.ResponseStatusCode = data.Response.ResponseStatusCode;

                            var latitude = data.SearchResults.DropLocations[0].Geocode.Latitude;
                            var longitude = data.SearchResults.DropLocations[0].Geocode.Longitude;
                            var apiKey = $('#staticMapApiKey').val();
                            var thumbnailImage = " https://maps.google.com/maps/api/staticmap?center=" +
                                latitude +
                                "," +
                                longitude +
                                "&zoom=11&size=300x300&markers=icon:http://cdn.agilitycms.com/mastermind-toys/LOGO_S.png|" +
                                latitude +
                                "," +
                                longitude +
                                "&sensor=false&key=" +
                                apiKey;
                            $scope.checkoutState.UPSStoreStaticMap = thumbnailImage;
                            $scope.checkoutState.shippingSelected = true;
                        } else {
                            $scope.checkoutState.SelectedUpsLocation = {};
                            $scope.checkoutState.SelectedUpsLocation.ResponseStatusCode = -1;
                            $scope.checkoutState.SelectedUpsLocation
                                .ResponseStatusDescription = CustomResponse.StoreNotFound;
                            //"Either shipping zipcode is not valid or UPS store is not found";
                            $scope.checkoutState.shippingSelected = false;
                        }
                    } else if (data.Response.ResponseStatusCode == 0) {
                        $scope.checkoutState.SelectedUpsLocation = {};
                        $scope.checkoutState.SelectedUpsLocation.ResponseStatusCode = -1;
                        $scope.checkoutState.SelectedUpsLocation
                            .ResponseStatusDescription = CustomResponse.ContactAdmin;
                        // "Not able to get UPS location, Please contact administrator.";
                        $scope.checkoutState.shippingSelected = false;
                    } else {
                        $scope.checkoutState.SelectedUpsLocation = {};
                        $scope.checkoutState.SelectedUpsLocation.ResponseStatusCode = -1;
                        $scope.checkoutState.SelectedUpsLocation
                            .ResponseStatusDescription = CustomResponse.StoreNotFound;
                        //"Either shipping zipcode is not valid or UPS store is not found";
                        $scope.checkoutState.shippingSelected = false;
                    }
                    spinnerFactory.hide();
                    enableScrollOnSpinnerHide();
                }
            );
        };

        $scope.GetUpsLocation = function () {
            $scope.checkoutState.ModalSelectedUps = false;
            upsSvc.getUpsLocations(addressDataHelper.getShippingData()).$promise.then(
                function (data) {
                    $scope.UpsLocations = data.SearchResults.DropLocations;
                }
            );
        };

        $scope.SetUpsAddressAsShippingAdderess = function () {
            var upsAccessLocation = $scope.checkoutState.SelectedUpsLocation;
            var shippingData = addressDataHelper.getShippingData();
            //sending conginee name sent to shipping address 2 as per Masterminds request
            shippingData.address1 = upsAccessLocation.AddressKeyFormat.AddressLine;
            shippingData.address2 = upsAccessLocation.AddressKeyFormat.ConsigneeName;
            shippingData.address3 = "";
            shippingData.nickname = 'THE UPS STORE : ' + upsAccessLocation.AccessPointInformation.PublicAccessPointID;
            shippingData.id = "";
            shippingData.country.countryCode = upsAccessLocation.AddressKeyFormat.CountryCode;
            shippingData.country.countryId = upsAccessLocation.AddressKeyFormat.CountryCode.toLowerCase() == "ca" ? 1 : 2;
            shippingData.country.countryName = upsAccessLocation.AddressKeyFormat.CountryCode.toLowerCase() == "ca" ? "Canada" : "United States";

            shippingData.city = upsAccessLocation.AddressKeyFormat.PoliticalDivision2;
            shippingData.province = upsAccessLocation.AddressKeyFormat.PoliticalDivision1;
            shippingData.postalCode = upsAccessLocation.AddressKeyFormat.PostcodePrimaryLow;
            //shippingData.isdefaultaddress = "";

            addressDataHelper.updateShippingData(shippingData);
        };

        $scope.shippingStoreLocationModel = function () {
            if (!$('body').hasClass('store-checkout')) {
                $('body').addClass('store-checkout');
            }
            $modal.open({
                templateUrl: appUrlBuilder.buildTemplateUrl('shippingStoreLocationTemplateUrl'),
                backdrop: 'static',
                controller: 'mmtcheckoutUpsInstanceCtrl',
                windowClass: 'modal-vertical-centered',
                scope: $scope,
                size: 'lg'
            });
        };

        $scope.initMap = function () {
            spinnerFactory.show();
            upsSvc.getUpsLocations(addressDataHelper.getShippingData()).$promise.then(
                function (data) {
                    $scope.UpsLocations = data.SearchResults.DropLocations;

                    var stores = $scope.UpsLocations;
                    $('#map_canvas_store').show();
                    var currentShippingAddress = addressDataHelper.getShippingData();
                    var address = currentShippingAddress.city + ", " + currentShippingAddress.province + ", " + currentShippingAddress.postalCode;

                    var geocoder = new google.maps.Geocoder();
                    geocoder.geocode({ 'address': address + "," + currentShippingAddress.country.countryName }, function (results, status) {

                        if (status == google.maps.GeocoderStatus.OK) {
                            var lat = results[0].geometry.location.lat();
                            var long = results[0].geometry.location.lng();
                            $scope.MapUserLocation = new google.maps.LatLng(lat, long);

                            var mapLocation = new google.maps.LatLng(lat, long);
                            var mapOptions = {
                                mapTypeControl: false,
                                disableDefaultUI: true,
                                streetViewControl: false,
                                zoomControl: true,
                                panControl: true,
                                zoom: 11,
                                center: mapLocation,
                                mapTypeId: google.maps.MapTypeId.ROADMAP
                            };

                            var mapdiv = $('#map_canvas_store');
                            if (mapdiv === undefined) {
                                return;
                            }
                            var mapdivFirst = $('#map_canvas_store')[0];
                            if (mapdivFirst === undefined) {
                                return;
                            }
                            $scope.map = new google.maps.Map($('#map_canvas_store')[0], mapOptions);
                            var marker;
                            if (stores == null) {
                                console.log('stores in initmap null: ' + stores);
                                return;
                            }

                            stores.forEach(function (store) {
                                mapLocation = new google.maps.LatLng(store.Geocode.Latitude, store.Geocode.Longitude);
                                marker = new google.maps.Marker({
                                    position: mapLocation,
                                    map: $scope.map,
                                    title: store.AddressKeyFormat.ConsigneeName,
                                    icon: globalConstants.rootUrl + '/Content/images/locationPins/LOGO_S.png'
                                });
                            });
                            spinnerFactory.hide();
                        } else {
                            spinnerFactory.hide();
                        }
                    });
                }
            );
        };

        $scope.changeShippingStoreLocation = function (upsLocation) {
            $scope.checkoutState.ModalSelectedUps = true;
            $scope.checkoutState.MoadlSelectedUpsLocation = upsLocation;
        };

        $scope.SubmitUpsStoreLocation = function () {
            $scope.checkoutState.ModalSelectedUps = true;
            $scope.checkoutState.SelectedUpsLocation = $scope.checkoutState.MoadlSelectedUpsLocation;
            var standardHoursOfOperation = $scope.checkoutState.SelectedUpsLocation.StandardHoursOfOperation;
            $scope.checkoutState.SelectedUpsLocation.UpsStoreTimes = [];
            angular.forEach(standardHoursOfOperation.split(';'), function (value, key) {
                $scope.checkoutState.SelectedUpsLocation.UpsStoreTimes.push({ 'day': value.split(': ')[0], 'time': value.split(': ')[1] });
            });

            $scope.checkoutState.SelectedUpsLocation.ResponseStatusCode = 1;
            var latitude = $scope.checkoutState.SelectedUpsLocation.Geocode.Latitude;
            var longitude = $scope.checkoutState.SelectedUpsLocation.Geocode.Longitude;
            var apiKey = $('#staticMapApiKey').val();
            var thumbnailImage = " https://maps.google.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=11&size=300x300&markers=icon:http://cdn.agilitycms.com/mastermind-toys/LOGO_S.png|" + latitude + "," + longitude + "&sensor=false&key=" + apiKey;
            $scope.checkoutState.UPSStoreStaticMap = thumbnailImage;
            $scope.checkoutState.shippingSelected = true;
        };

        $scope.ArrayContains = function (arr, value) {
            var i = arr.length;
            while (i--) {
                if (arr[i] === value) return true;
            }
            return false;
        };

        $scope.PopulateHappyCardInfo = function () {
            var d = new Date();
            var year = d.getFullYear() + 1;
            $scope.checkoutState.paymentType = 4;
            $scope.checkoutState.creditCardData.expireMonth = "12";
            $scope.checkoutState.creditCardData.expireYear = year;
            $scope.checkoutState.creditCardData.name = "Happy Card";
            $scope.checkoutState.creditCardData.cardType = "Visa";
            $scope.checkoutState.creditCardData.cardTypeId = 3;
        };

        //$scope.RefreshCCUI = function () {
        //    setTimeout(function () {
        //        var newWidth = $window.innerWidth;
        //         if (newWidth < 767) {
        //            $window.sendHPCIChangeStyleMsg("lbl_ccNum", "font-size", "12px");
        //            $window.sendHPCIChangeStyleMsg("lbl_ccCvv", "font-size", "12px");
        //            $window.sendHPCIChangeStyleMsg("ccNum", "height", "20px");
        //            $window.sendHPCIChangeStyleMsg("ccCVV", "height", "20px");
        //            $window.sendHPCIChangeStyleMsg("ccNum", "border-width", "1px");
        //            $window.sendHPCIChangeStyleMsg("ccCVV", "border-width", "1px");
        //            $window.sendHPCIChangeStyleMsg("ccNum", "border-radius", "5px");
        //            $window.sendHPCIChangeStyleMsg("ccCVV", "border-radius", "5px");
        //            $window.sendHPCIChangeStyleMsg("ccNum", "width", "230px");
        //        }
        //    }, 700);
        //};

    }
]);

//Prevent Scrolling of page when Spinner is visible
function disableScrollOnSpinnerShow() {
    $('body').css('overflow', 'hidden');
    $('body').mousedown(function (e) { if (e.button === 1) return false });
}

function enableScrollOnSpinnerHide() {
    $('body').css('overflow', 'auto');
    $('body').mousedown(function (e) { if (e.button === 1) return true });
}

function gotoShippingRateListPosition() {
    $('html, body').animate({
        scrollTop: jQuery("#shippingRateList").offset().top
    }, 2000);
};
'use strict';

/**
* This is platform product listing in the cart
*/
angular.module('checkout').directive('checkoutItemListing', ['appUrlBuilder', function (appUrlBuilder) {
    return {
        restrict: 'A',
        templateUrl: appUrlBuilder.buildTemplateUrl('checkoutItemsListingTemplateUrl'),
        controller: 'CartItemsListingCtrl',
        priority: 1100,
        scope: {
            isDisabled: '=',
            hideStockInfo: '='
        }
    };
}]);

angular.module('checkout').directive('checkoutOrderSummary', ['appUrlBuilder', 'AppObserver', function (appUrlBuilder, appObserver) {
    return {
        restrict: 'A',
        templateUrl: appUrlBuilder.buildTemplateUrl('checkoutOrderSummaryTemplateUrl'),
        priority: 1001,
        scope: {
            cart: '=',
            //in shipping estimate page is true
            estimate: '=',
            giftCards: '='
        },
        link: function (scope, element) {
            scope.blinkGiftCardblinkItem = false;
            //change blinItem value to trigger odBlinkElement Directive when shippingRateChanged event occur
            var shippingRateChangedListener = appObserver.subscribe('shippingRateChanged', scope, function () {
                scope.blinkItem = !scope.blinkItem;
            });

            //get latest postalCode from postalCodeChanged event
            var postalCode = (typeof scope.cart === 'undefined' || scope.cart === undefined || typeof scope.cart.addressInfo === 'undefined' || scope.cart.addressInfo === undefined) ? '' : scope.cart.addressInfo.ShippingAddress.PostalCode;
            var postalCodeChangedListener = appObserver.subscribe('postalCodeChanged', scope, function (message) {
                postalCode = message.postalCode;
            });

            //decide show generic tax or detail tax 
            scope.showGenericTax = function () {
                //in shipping estimate page when change country or postal code is empty will display generic tax, 
                //in checkout page will display specific tax if shipping postal code not empty
                //reassign postalCode after scope.cart value assigned, use for checkout page to correct display generic or specific tax
                if (!scope.estimate && postalCode === '' && !(typeof scope.cart === 'undefined' || scope.cart === undefined || typeof scope.cart.addressInfo === 'undefined' || scope.cart.addressInfo === undefined)) {
                    postalCode = scope.cart.addressInfo.ShippingAddress.PostalCode;
                }
                if (postalCode === '') {
                    return true;
                } else {
                    return (scope.cart.taxes !== null && scope.cart.taxes.length === 0 || scope.cart.addressInfo.ShippingAddress.PostalCode === '');
                }
            };

           scope.cardBlink = false;
            var cardBlinkListener = appObserver.subscribe('giftCardBlinkListener', scope, function () {
                scope.cardBlink = !scope.cardBlink;
            });

            //Unbind listeners when scope is destroyed
            scope.$on('$destroy', function () {
                shippingRateChangedListener();
                postalCodeChangedListener();
                cardBlinkListener();
                element.remove();
            });
        }
    };
}]);

angular.module('checkout').directive('loadGallery', ['$timeout', function ($timeout) {
    return {

        restrict: 'A',
        link: function (scope, elem, attrs) {
            if (scope.$last) {
                $timeout(function () {
                  initCarousel();
                }, 0);
            }
        }
    }

}]);

;
'use strict';
/**
 * Responsible for Address module behavior as per new design
 */
var zipRegex = /^(?!.*[DFIOQUdfioqu])[A-VXYa-vxy][0-9][A-Za-z] ?[0-9][A-Za-z][0-9]$/;
var zipUsRegex = /^([0-9]{5})(?:[-\s]*([0-9]{4}))?$/;
angular.module('address')
    .directive('mmtAddressForm', ['appUrlBuilder', 'AddressSvc',
        function (appUrlBuilder, addressSvc) {
            return {
                restrict: 'A',
                templateUrl: appUrlBuilder.buildTemplateUrl('mmtAddressFormTemplateUrl'),
                scope: {
                    addressData: '=',
                    onDone: '&',
                    onEdit: '&',
                    doneButtonLabelKey: '@',
                    triggerDoneButtonEvent: '=',
                    addressBtn: '='
                },

                link: function (scope) {

                    scope.zipcodePattern = zipRegex;

                    scope.selectedCountry = {};

                    scope.showDoneButton = false;
                    scope.enableDoneButton = true;
                    scope.showEditButton = false;

                    addressSvc.getCountryInfos().$promise.then(
                        function (data) {
                            scope.countryInfos = data.countryInfos;
                            scope.setSelectedCountry();
                        }
                    );

                    scope.$watch('addressData', function () {
                        if (scope.addressData) {
                            scope.setSelectedCountry();
                        }
                    });

                    scope.setSelectedCountry = function () {
                        
                        if (scope.addressData) {
                            if (scope.countryInfos && scope.addressData.country) {

                                angular.forEach(scope.countryInfos, function (countryInfo) {
                                    if (scope.selectedCountry.countryCode == countryInfo.countryCode) {
                                        scope.addressData.country = scope.selectedCountry;
                                    }
                                });
                            }
                        }
                    };

                    scope.$watch('selectedCountry', function (selectedCountry) {

                        scope.setSelectedCountry();
                        scope.provinces = {};
                        if (selectedCountry.countryCode != undefined) {
                            addressSvc.getCountryProvinces(selectedCountry.countryCode).$promise.then(
                                function (data) {
                                    scope.provinces = data.provinces.filter(function (el) {
                                        el.name = (el.name.toLowerCase() === "northern territory" || el.name.toLowerCase() === "northwest territory") ? "Northwest Territories" : el.name;
                                        return (el.code !== "AK" && el.code !== "PR" && el.code !== "HI");
                                    });
                                }
                            );
                            if (selectedCountry.countryCode === 'CA') {
                                $("#customForm-postalCode").text("Postal Code");
                                //$("#customForm-postalcode-val-msg").text("Postal code is required.");
                                $("#customForm-postalcode-val-msg").text("Invalid Postal Code");
                                $("#customForm-province").text("Province");
                                $("#customForm-province-val-msg").text("Province is required.");
                                scope.zipcodePattern = zipRegex;
                            } else if (selectedCountry.countryCode === 'US') {
                                $("#customForm-postalCode").text("Zip Code");
                                //$("#customForm-postalcode-val-msg").text("Zip code is required.");
                                $("#customForm-postalcode-val-msg").text("Invalid Zip Code.");
                                $("#customForm-province").text("State");
                                $("#customForm-province-val-msg").text("State is required.");
                                scope.zipcodePattern = zipUsRegex;
                            }
                        } else {
                            $("#customForm-postalCode").text("Postal/Zip Code");
                            $("#customForm-postalcode-val-msg").text("Postal/Zip code is required.");
                            $("#customForm-province").text("Province/State");
                            $("#customForm-province-val-msg").text("Province or State is required.");
                        }
                        if (scope.addressForm.addressForm_postalCode.$dirty) {
                            if (!scope.zipcodePattern.test($('#fullForm_postalCode').val())) {
                                scope.addressForm.addressForm_postalCode.$setValidity('pattern', false)
                                $('#customForm-postalcode-val-msg').removeClass("ng-hide");
                                $('#fullForm_postalCode').parent().removeClass("invalid-field").addClass("invalid-field");
                            }
                            else {
                                scope.addressForm.addressForm_postalCode.$setValidity('pattern', true)
                                $('#customForm-postalcode-val-msg').addClass("ng-hide");
                                $('#fullForm_postalCode').parent().removeClass("invalid-field");
                            }
                        }

                        //$('#fullForm_postalCode').trigger('change');
                    });

                    scope.done = function () {
                        if (scope.addressForm.$invalid) {
                            return;
                        }
                        scope.addressData = angular.copy(scope.fullForm);
                        if (scope.selectedCountry) {
                            scope.addressData.country = angular.copy(scope.selectedCountry);
                        }
                        scope.onDone({ data: scope.addressData });
                        scope.enableDoneButton = true;
                    };

                    scope.editForm = function () {

                        if (scope.lockFields === true) {
                            scope.onEdit();
                        }
                    };

                    scope.showPostalError = function () {
                        if ($('#fullForm_postalCode').val() == "") {
                            $("#postalErrorMsg").text("Postal/Zip Code is required.");
                        } else if (scope.addressForm.addressForm_postalCode.$invalid) {
                            if (scope.selectedCountry.countryCode === 'CA') {
                                $("#postalErrorMsg").text("Invalid Postal Code.");
                            } else if (scope.selectedCountry.countryCode === 'US') {
                                $("#postalErrorMsg").text("Invalid Zip Code.");
                            } else {
                                $("#postalErrorMsg").text("Invalid Postal/Zip Code.");
                            }
                        } else {
                            $("#postalErrorMsg").text("");
                        }
                    };

                    scope.hidePostalError = function () {
                        $("#postalErrorMsg").text("");
                    }
                }
            };
        }]);

// Post rendering call to style the controls
angular.module('address').directive('loadComplete', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            if (scope.$last) {
                $timeout(function () {
                    initCustomForms();
                }, 1000);
            }
        }
    }

}]);

;
'use strict';
/**
 * Responsible for Address module behavior as per new design
 */

angular.module('address')
    .directive('mmtBillingAddressForm', ['appUrlBuilder', 'AddressSvc',
        function (appUrlBuilder, addressSvc) {
            return {
                restrict: 'A',
                templateUrl: appUrlBuilder.buildTemplateUrl('mmtBillingAddressFormTemplateUrl'),
                scope: {
                    addressData: '=',
                    onDone: '&',
                    onEdit: '&',
                    doneButtonLabelKey: '@',
                    triggerDoneButtonEvent: '=',
                    billingAddressBtn: '=',
                    isFormUpdated: '='
                },

                link: function (scope) {

                    scope.selectedCountry = {};
                    scope.phone = '';
                    scope.showDoneButton = false;
                    scope.enableDoneButton = true;
                    scope.showEditButton = false;
                    scope.billingAddressForm.fullForm_firstName.$pristine = true;
                    scope.billingAddressForm.fullForm_lastName.$pristine = true;
                    scope.billingAddressForm.fullForm_address1.$pristine = true;
                    scope.billingAddressForm.fullForm_postalCode.$pristine = true;
                    scope.billingAddressForm.fullForm_country.$pristine = true;
                    scope.billingAddressForm.fullForm_city.$pristine = true;
                    scope.billingAddressForm.fullForm_province.$pristine = true;
                    scope.billingAddressForm.isFormSubmitted = false;
                    
                    scope.billingAddressForm.phone.$pristine = true;
                    
                    addressSvc.getCountryInfos().$promise.then(
                        function (data) {
                            scope.countryInfos = data.countryInfos;
                            scope.setSelectedCountry();
                        }
                    );

                    scope.$watch('addressData', function () {
                        if (scope.addressData) {
                            scope.setSelectedCountry();
                        }
                    });

                    scope.setSelectedCountry = function () {

                        if (scope.addressData) {
                            if (scope.countryInfos && scope.addressData.country) {

                                angular.forEach(scope.countryInfos, function (countryInfo) {
                                    if (scope.selectedCountry.countryCode == countryInfo.countryCode) {
                                        scope.addressData.country = scope.selectedCountry;
                                    }
                                });
                            }
                        }
                    };

                    scope.$watch('selectedCountry', function (selectedCountry) {

                        scope.setSelectedCountry();
                        scope.provinces = {};
                        if (selectedCountry.countryCode != undefined) {
                            addressSvc.getCountryProvinces(selectedCountry.countryCode).$promise.then(
                                function (data) {
                                    scope.provinces = data.provinces.filter(function (el) {
                                        el.name = (el.name.toLowerCase() === "northern territory" || el.name.toLowerCase() === "northwest territory") ? "Northwest Territories" : el.name;
                                        return (el.code !== "AK" && el.code !== "PR" && el.code !== "HI");
                                    });
                                }
                            );
                            if (selectedCountry.countryCode === 'CA') {
                                $("#fullForm-postalCode-label").text("Postal Code");
                                $("#fullForm-postalCode-val-msg").text("Postal code is required.");
                                $("#fullForm-province-label").text("Province");
                                $("#fullForm-province-val-msg").text("Province is required.");
                            } else if (selectedCountry.countryCode === 'US') {
                                $("#fullForm-postalCode-label").text("Zip Code");
                                $("#fullForm-postalCode-val-msg").text("Zip code is required.");
                                $("#fullForm-province-label").text("State");
                                $("#fullForm-province-val-msg").text("State is required.");
                            }
                        } else {
                            $("#fullForm-postalCode-label").text("Postal/Zip Code");
                            $("#fullForm-postalCode-val-msg").text("Postal/Zip code is required.");
                            $("#fullForm-province-label").text("Province/State");
                            $("#fullForm-province-val-msg").text("Province or State is required.");
                        }
                    });

                    scope.done = function () {
                        scope.billingAddressForm.isFormSubmitted = false;
                        scope.billingAddressForm.isFormUpdated = false;
                        if (scope.billingAddressForm.$invalid) {
                            return;
                        }
                        scope.billingAddressForm.isFormSubmitted = true;
                        if ($("#btn-autocomplete-done").val() === "Update") {
                            scope.billingAddressForm.isFormUpdated = true;
                        }
                        scope.addressData = angular.copy(scope.fullForm);
                        scope.$parent.cartData.phone = scope.phone;
                        if (scope.selectedCountry) {
                            scope.addressData.country = angular.copy(scope.selectedCountry);
                        }
                        scope.onDone({ data: scope.addressData });
                        scope.enableDoneButton = true;
                    };

                    scope.editForm = function () {

                        if (scope.lockFields === true) {
                            scope.onEdit();
                        }
                    };

                }
            };
        }]);

;
'use strict';

angular.module('checkout')
    .controller('CreditCardCtrl', ['$scope', '$q', 'CheckoutSvc', 'siteRes', 'AddressDataHelper', 'CartDataStorageService', 'CheckoutDataStorageService', 'CheckoutCreditCardValidationService', 'anchorHelper',
    function ($scope, $q, checkoutSvc, siteRes, addressDataHelper, cartDataStorageService, checkoutDataStorageService, checkoutCreditCardValidationService, anchorHelper) {

        $scope.checkoutState = checkoutDataStorageService.checkoutState;
        $scope.cartData = cartDataStorageService.cartData;
        $scope.card = checkoutCreditCardValidationService.card;
          
        $scope.billingAddressBtn = "Next";
        $scope.initalize = function () {
            $scope.identityName = 'CreditCardCtrl';

            $scope.checkoutState.creditCardData.cardNumber = '';
            $scope.checkoutState.creditCardData.expireMonth = "";
            $scope.checkoutState.creditCardData.expireYear = "";
            $scope.checkoutState.creditCardData.cardValidation = '';
            $scope.checkoutState.creditCardData.name = '';

            $scope.useShippingAddress = false;
            if ($scope.cartData.isDigitalGiftCardOrder || $scope.cartData.signedIn) {
                $scope.useShippingAddress = true;
            }

            $scope.CreditCardInputType = 'password';
            $scope.CvvInputType = 'password';

            $scope.isCardNumberValid = false;
            $scope.isExpireMonthValid = false;
            $scope.isExpireYearValid = false;
            $scope.isCardTypeValid = false;
            $scope.isCardValidationValid = false;
            $scope.isNameValid = false;

            $scope.isCardTypeDirty = false;
            $scope.isNameDirty = false;
            $scope.isExpireMonthDirty = false;
            $scope.isExpireYearDirty = false;

            $scope.monthes = [
                { id: 1, name: siteRes.li_Jan },
                { id: 2, name: siteRes.li_Feb },
                { id: 3, name: siteRes.li_Mar },
                { id: 4, name: siteRes.li_Apr },
                { id: 5, name: siteRes.li_May },
                { id: 6, name: siteRes.li_Jun },
                { id: 7, name: siteRes.li_Jul },
                { id: 8, name: siteRes.li_Aug },
                { id: 9, name: siteRes.li_Sep },
                { id: 10, name: siteRes.li_Oct },
                { id: 11, name: siteRes.li_Nov },
                { id: 12, name: siteRes.li_Dec }
            ];

            $scope.years = [];
            var startLYear = new Date().getFullYear();
            for (var i = 0; i < 10; i++) {
                $scope.years.push(startLYear);
                startLYear = startLYear + 1;
            }

            $scope.getCreditCardTypes();
            $scope.hpciEnabled = checkoutSvc.hpciEnabled();
        };

        $scope.cardType = null;
        $scope.onCardTypeChanged = function () {
            if ($scope.cardType === null || $scope.cardType===undefined) {
                $scope.checkoutState.creditCardData.cardTypeId = 0;
                $scope.checkoutState.creditCardData.cardType = '';
            } else {
                $scope.checkoutState.creditCardData.cardTypeId = $scope.cardType._id;
                $scope.checkoutState.creditCardData.cardType = $scope.cardType._cardType;
            }
            $scope.checkoutState.creditCardType = $scope.cardType;
            if ($scope.cardType === null || $scope.cardType === undefined) {
                $scope.isCardTypeValid = false;
            }
            else
                $scope.isCardTypeValid = checkoutCreditCardValidationService.validateCardType($scope.checkoutState);
            $scope.isCardTypeDirty = !$scope.isCardTypeValid;
        };
        $scope.checkExpiredYearMonth = function () {
            if ($scope.checkoutState.creditCardData.expireMonth === undefined) return false;
            if ($scope.checkoutState.creditCardData.expireYear === undefined) return true;
            if ($scope.checkoutState.creditCardData.expireYear <= 0 ) return false;
            if ($scope.checkoutState.creditCardData.expireMonth <= 0) return false;
            var today = new Date();
            var expired = new Date($scope.checkoutState.creditCardData.expireYear, $scope.checkoutState.creditCardData.expireMonth, today.getDate());
            if (expired.getTime() < today.getTime())
                return false;
            return true;            
        }
        $scope.month = null;
        $scope.onMonthChanged = function () {
            if ($scope.month !== null && $scope.month !== undefined) {
                $scope.checkoutState.creditCardData.expireMonth = $scope.month.id;
            } else {
                $scope.checkoutState.creditCardData.expireMonth = 0;
            }

            $scope.isExpireMonthValid = checkoutCreditCardValidationService.validateMonth($scope.checkoutState);
            if ($scope.isExpireMonthValid && $scope.checkoutState.creditCardData.expireYear) {
                $scope.isExpireMonthValid = $scope.checkExpiredYearMonth();
            }
            $scope.isExpireMonthDirty = !$scope.isExpireMonthValid;
        };

        $scope.onYearChanged = function () {
            $scope.isExpireYearValid = checkoutCreditCardValidationService.validateYear($scope.checkoutState);
            $scope.isExpireYearDirty = !$scope.isExpireYearValid;

            if ($scope.isExpireMonthValid && $scope.isExpireYearValid && ($scope.checkoutState.creditCardData.expireMonth === undefined || $scope.checkoutState.creditCardData.expireMonth > 0)) {
                $scope.isExpireMonthValid = $scope.checkExpiredYearMonth();
                $scope.isExpireMonthDirty = !$scope.isExpireMonthValid;
            }

        };

        $scope.onCvvChanged = function () {
            $scope.isCardValidationValid = checkoutCreditCardValidationService.validateCardValidation($scope.checkoutState);
        };

        $scope.onNameChanged = function () {
            $scope.isNameValid = checkoutCreditCardValidationService.validateName($scope.checkoutState);
            $scope.isNameDirty = !$scope.isNameValid;
        };

        $scope.onCardNumberChanged = function (allowEmpty) {
            $scope.isCardNumberValid = checkoutCreditCardValidationService.validateCardNumber($scope.checkoutState, allowEmpty);
            $scope.setCardType($scope.checkoutState);
        };

        $scope.onPhoneNumberChanged = function () {
            //$scope.checkoutState.isPhoneNoFormatValid = false;
            $scope.checkoutState.isPhoneNoValid = $scope.checkoutState.OrderPhoneNumber === undefined || $scope.checkoutState.OrderPhoneNumber.length <= 0 ? false : true;
            $scope.checkoutState.isPhoneNoDirty = !$scope.isPhoneNoValid;
            //if ($scope.checkoutState.isPhoneNoValid) {
            //    $scope.checkoutState.isPhoneNoFormatValid = $scope.phoneNumberPattern.test($scope.checkoutState.OrderPhoneNumber);
            //}         
        };
        $scope.checkoutState.isPhoneNoFormatValid = function () {
            if (!$scope.checkoutState.OrderPhoneNumber) return false;
            return /^\+?\d{3}-?\d{3}-?\d{4}$/.test($scope.checkoutState.OrderPhoneNumber);
        }
        //$scope.phoneNumberPattern = (function () {
        //    var regexp = /^\+?\d{3}-\d{3}-\d{4}$/;
        //    return {
        //        test: function (value) {
        //            return regexp.test(value);
        //        }
        //    };
        //})();

        //Functions

        $scope.setCardType = function (checkoutState) {
            $.each($scope.cardTypes, function (i, cardType) {
                var match = checkoutState.creditCardData.cardNumber.match(cardType._binRegex);
                if (match != undefined && match != null) {
                    $scope.checkoutState.creditCardData.cardTypeId = cardType._id;
                    $scope.checkoutState.creditCardData.cardType = cardType._cardType;
                }
            });
        };

        $scope.getCreditCardTypes = function () {
            var deferred = $q.defer();
            checkoutSvc.getCreditCardTypes().$promise.then(
                function (value) {
                    $scope.cardTypes = value;
                    $scope.cardType = null; //$scope.cardTypes[0];
                }, function (error) {
                    deferred.reject(error);
                });
            return deferred.promise;
        };

        $scope.switchCCMask = function () {
            if ($scope.CreditCardInputType === 'password') {
                $scope.CreditCardInputType = 'text';
            } else {
                $scope.CreditCardInputType = 'password';
            }

        };

        $scope.switchCvvMask = function () {
            if ($scope.CvvInputType === 'password') {
                $scope.CvvInputType = 'text';
            } else {
                $scope.CvvInputType = 'password';
            }
        };

        $scope.billingAddressDone = function (data) {
            addressDataHelper.updateBillingData(data);
            addressDataHelper.updateSameAsShippingAddress($scope.useShippingAddress);
            checkoutSvc.addAddressDataToOrderForm(addressDataHelper.getShippingData(), addressDataHelper.getBillingData(), addressDataHelper.getSameAsShippingAddress()).$promise.then(
                function () {
                    if (!addressDataHelper.getSameAsShippingAddress()) {
                        cartDataStorageService.loadCartData();
                    }
                }, function (error) {
                    console.log(error);
                });
            //anchorHelper.setAnchor('billingAnchor');
               
            $scope.checkoutState.billingAddressSec = true;
        };

        $scope.editBillingInfo = function () {
            $scope.checkoutState.billingAddressSec = false;
            $scope.billingAddressBtn = "Update";
            $scope.isFormUpdated = false;
        };
       $scope.sameAsShipping = function (value) {
           $scope.billingSame = value;
       addressDataHelper.updateSameAsShippingAddress(value);
       if ($scope.cartData.signedIn) {
           if (value == false)
           {
              var data = $scope.cartData.addressInfo.BillingAddress;
              //data.FirstName = "";
              //data.LastName = ""
              $scope.billingAddressDone(data);
            }
            else if (value ==true)
            {
                var adddata = addressDataHelper.getShippingData();
               addressDataHelper.updateBillingData(adddata);
            }
       }
     };

        setTimeout(function () { $scope.initalize(); }, 500);

    }]);;
'use strict';

/**
* This directive is loading cart data and displaying summary on the page.
*/
angular.module('checkout').directive('mmtCheckoutCreditCard', ['$q', 'CheckoutSvc', 'appUrlBuilder', '$window',function ($q, checkoutSvc, appUrlBuilder, $window) {
    function resizeProcess() {
        var newWidth = $window.innerWidth;
        var oldWidth = window.oldWindowWidth;
        $window.sendHPCIChangeStyleMsg("ccNum", "color", "#002751");
        $window.sendHPCIChangeStyleMsg("ccCVV", "color", "#002751");
        if (newWidth < 767) {
           // if (!oldWidth || oldWidth > 767) {
                $window.sendHPCIChangeStyleMsg("lbl_ccNum", "font-size", "12px");
                $window.sendHPCIChangeStyleMsg("lbl_ccCvv", "font-size", "12px");
                $window.sendHPCIChangeStyleMsg("csc-validator", "font-size", "9px");
                $window.sendHPCIChangeStyleMsg("cc-validator", "font-size",  "9px");
                $window.sendHPCIChangeStyleMsg("ccNum", "height", "20px");
                $window.sendHPCIChangeStyleMsg("ccCVV", "height", "20px");
                $window.sendHPCIChangeStyleMsg("ccNum", "border-width", "1px");
                $window.sendHPCIChangeStyleMsg("ccCVV", "border-width", "1px");
                $window.sendHPCIChangeStyleMsg("ccNum", "border-radius", "5px");
                $window.sendHPCIChangeStyleMsg("ccCVV", "border-radius", "5px");
                $window.sendHPCIChangeStyleMsg("ccNum", "width", "210px");
                $('.hpciCheckout iframe').height(185);
                $window.oldWindowWidth = newWidth;
           // }
        }
        else if (newWidth <= 1299) {
          //  if (!oldWidth || oldWidth < 767 || oldWidth > 1299) {
                //$window.sendHPCIChangeStyleMsg("lbl_ccNum", "font-size", "20px");
                //$window.sendHPCIChangeStyleMsg("lbl_ccCvv", "font-size", "20px");
                //$window.sendHPCIChangeStyleMsg("csc-validator", "font-size", "11px");
                //$window.sendHPCIChangeStyleMsg("cc-validator" , "font-size", "11px");
                $window.sendHPCIChangeStyleMsg("ccNum", "height", "30px");
                $window.sendHPCIChangeStyleMsg("ccCVV", "height", "30px");
                $window.sendHPCIChangeStyleMsg("ccNum", "border-width", "2px");
                $window.sendHPCIChangeStyleMsg("ccCVV", "border-width", "2px");
                $window.sendHPCIChangeStyleMsg("ccNum", "border-radius", "10px");
                $window.sendHPCIChangeStyleMsg("ccCVV", "border-radius", "10px");
                $window.sendHPCIChangeStyleMsg("ccNum", "width", "300px");
                $window.oldWindowWidth = newWidth;
                $('.hpciCheckout iframe').height(208);

          //  }
        }
        else {
           // if (!oldWidth || oldWidth <= 1299) {
                //$window.sendHPCIChangeStyleMsg("lbl_ccNum", "font-size", "24px");
                //$window.sendHPCIChangeStyleMsg("lbl_ccCvv", "font-size", "24px");
                $window.sendHPCIChangeStyleMsg("csc-validator", "font-size", "14px");
                $window.sendHPCIChangeStyleMsg("cc-validator", "font-size",  "14px");
                $window.sendHPCIChangeStyleMsg("ccNum", "height", "35px");
                $window.sendHPCIChangeStyleMsg("ccCVV", "height", "35px");
                $window.sendHPCIChangeStyleMsg("ccNum", "border-width", "2px");
                $window.sendHPCIChangeStyleMsg("ccCVV", "border-width", "2px");
                $window.sendHPCIChangeStyleMsg("ccNum", "border-radius", "10px");
                $window.sendHPCIChangeStyleMsg("ccCVV", "border-radius", "10px");
                $window.sendHPCIChangeStyleMsg("ccNum", "width", "350px");

                $window.oldWindowWidth = newWidth;
                $('.hpciCheckout iframe').height(235);
            //}
        }
    }

    return {
        restrict: 'A',
        replace: true,
        templateUrl: appUrlBuilder.buildTemplateUrl('checkoutCreditCardTemplateUrl'),
        controller: 'CreditCardCtrl',
        scope: {
            addressData: '=',
            billingSame: '=',
        },

        link: function (scope) {
            scope.useShippingAddress = true;

            if ($window.sendHPCIChangeStyleMsg) {
                angular.element(window).on('resize', resizeProcess);
                angular.element(window).on('scroll', resizeProcess);
            }

        }
    };
}]);

angular.module('checkout').directive('cardDataload', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            if (true) {
                $timeout(function () {
                    initCustomForms();
                }, 1000);
            }
        }
    }
}]);;
/*Override the getCheckoutScope function to use MmtCheckoutCtrl*/

//ar origetCheckoutScope = getCheckoutScope;
getCheckoutScope = function () {
    var scope = angular.element(document.getElementById('appCheckout')).scope();
    var ccScope = '';
	for (var cs = scope.$$childHead; cs; cs = cs.$$nextSibling) {
		if (cs.identityName !== undefined && (cs.identityName === 'CheckoutCtrl' || cs.identityName === 'MmtGiftCardCheckoutCtrl' || cs.identityName ==='mmtRISCheckoutCtrl')) {
            ccScope = cs;
            break;
        }
    }
    return ccScope;
};
'use strict';

angular.module('confirm')
    .controller('MmtConfirmCtrl', ['$scope', 'MmtConfirmPageDataStorageService', 'CartDataStorageService', 'AddressDataHelper', 'mmtAccountSvc','$timeout', 'spinnerFactory',
        function ($scope, mmtConfirmPageDataStorageService, cartDataStorageService, addressDataHelper, mmtAccountSvc, $timeout, spinnerFactory) {
            spinnerFactory.show("Please wait...");
            disableScrollOnSpinnerShow();
            $scope.error = false;
            $scope.isCardToSave = false;
            $scope.cartData = mmtConfirmPageDataStorageService.cartData;
            $scope.loadCartData = function () {
                mmtConfirmPageDataStorageService.loadData($scope.orderId).then(
                    function () {
                        cartDataStorageService.sync($scope.cartData, false);
                    },
                    function () {
                        $scope.error = true;
                    });
            };

            //preload cart data
            $scope.loadCartData();

            $scope.password = '';
            $scope.confirmpassword = '';

            $scope.isDisabled = true;
            $scope.confirmPasswordChangedInit = false;

            // Flag to enable or disable order cancel link
            $scope.disableCancelOrder = false;
            $scope.elapsedTime = '';
            $scope.cancelTime = 60;
            $scope.cancelCommitTime = $scope.cancelTime * 60000;

            // Flag to enable or disable account creation successful section
            $scope.isSuccess = false;

            //Validate form
            $scope.validateModel = function () {
                $scope.serverErrorMsg = '';

                $scope.isSuccess = false;

                var passwordNotEmpty = false;
                var confirmpasswordNotEmpty = false;
                var isPasswordMatched = false;

                if ($scope.password) {
                    passwordNotEmpty = true;
                    if (!$scope.passwordChangedInit) {
                        $scope.passwordChangedInit = true;
                    }
                }

                if ($scope.confirmpassword) {
                    confirmpasswordNotEmpty = true;
                    if (!$scope.confirmPasswordChangedInit) {
                        $scope.confirmPasswordChangedInit = true;
                    }
                }

                if ($scope.password === $scope.confirmpassword) {
                    isPasswordMatched = true;
                }
                // set isDisabled(create button status)
                if (passwordNotEmpty && confirmpasswordNotEmpty && isPasswordMatched) {
                    $scope.isDisabled = false;
                }
                else {
                    $scope.isDisabled = true;
                }
            };

            // Create Guest Customer by updating its entry
            $scope.createGuestCustomerAccount = function () {
                $scope.submitted = true;
                if ($scope.accountForm.$valid) {
                    var customerData = {};

                    customerData.email = $scope.cartData.customer.Email;
                    customerData.password = $scope.password.trim() === '' ? $scope.cartData.customer.password : $scope.password;
                    customerData.userId = $scope.cartData.customer.UserId;


                    $.ajax({
                        url: rootRel + 'Account/IsUserIdExist',
                        data: { userId: $scope.cartData.customer.Email },
                        type: "POST",
                        success: function(result) { 
                            if (result === "True") {
                                //UserId exists
                                $("#isUserExists").show();
                                $("#isUserExists").attr("style", "visibility: visible;");
                            } else {
                                mmtAccountSvc.updateGuestAccount(customerData).$promise.then(
                                   function (result) {
                                       // To enable or disable account creation successful section
                                       $scope.isSuccess = result;
                                       if(!$scope.isCardToSave && result) {
                                           var data = $scope.cartData.CreditCardInfo._id;
                                           $.ajax({
                                               type: "post",
                                               data: {id: $scope.cartData.CreditCardInfo._id},
                                               url: rootRel + 'Account/CreditCardRemove',
                                               success: function (response) {
                                                   if (response == 'done') {
                                                       $scope.isSuccess = result;
                                                   }
                                               },
                                               error: function (e) {
                                                   console.log(e.responseJSON.ExceptionMessage);
                                               }
                                           });
                                       }
                                   });
                            }
                        }
                    });
                }
            };

            $scope.orderCancel = function () {
                $.ajax({
                    url: rootRel + 'Account/OrderCancel',
                    data: { id: $scope.orderId },
                    type: "POST",
                    success: function (data) {
                        if (data != null && data === true) {
                            $scope.$apply(function () {
                                $scope.disableCancelOrder = data;
                            });
                            ShowConfirmModal("Cancellation successful",
                                        "You have cancelled your order – you will receive a confirmation email shortly.");
                        }
                    },
                    error: function (e) {

                    }
                });
            };

            $scope.orderCancelTime = function () {
                $.ajax({
                    url: rootRel + 'Account/EnableCancelLinkFor',
                    data: { id: $scope.orderId },
                    type: "POST",
                    success: function (data) {
                        if (data != null) {
                            $scope.elapsedTime = data;
                        }
                        if ($scope.elapsedTime < $scope.cancelTime) {
                            $scope.cancelCommitTime = ($scope.cancelTime - $scope.elapsedTime) * 60000;
                        } else {
                            $scope.$apply(function () {
                                $scope.disableCancelOrder = true;
                            });
                        }
                    },
                    error: function (e) {

                    }
                });
            };

            $scope.orderCancelTime();

            $timeout(function () {
                $scope.$apply(function () {
                    $scope.disableCancelOrder = true;
                });
            }, $scope.cancelCommitTime);

            $scope.toggleSaveCard = function (isChkboxChecked) {
                if (isChkboxChecked) {
                    $scope.isCardToSave = true;
                }
                else {
                    $scope.isCardToSave = false;
                }
            };

            spinnerFactory.hide();
            enableScrollOnSpinnerHide();
        }
    ]);

//Prevent Scrolling of page when Spinner is visible
function disableScrollOnSpinnerShow() {
    $('body').css('overflow', 'hidden');
    $('body').mousedown(function (e) { if (e.button === 1) return false });
}

function enableScrollOnSpinnerHide() {
    $('body').css('overflow', 'auto');
    $('body').mousedown(function (e) { if (e.button === 1) return true });
}


;
'use strict';

angular.module('confirm').directive('mmtConfirm', ['appUrlBuilder',
    function (appUrlBuilder) {
        return {
            restrict: 'A',
            templateUrl: appUrlBuilder.buildTemplateUrl('confirmPageTemplateUrl'),
            scope: {
                orderId: '@'
            },
            controller: 'MmtConfirmCtrl'
        };

    }]);


//Confirm password functionality on confirm page
angular.module('confirm').directive('pwCheck', [function () {
    return {
        require: 'ngModel',
        scope: {
            confirmpassword: '@'
        },
        link: function (scope, elem, attrs, ctrl) {
            var firstPassword = '#' + attrs.pwCheck;
            elem.add(firstPassword).on('keyup', function () {
                scope.$apply(function () {
                    var v = elem.val() === $(firstPassword).val();
                    ctrl.$setValidity('pwmatch', v);
                });
            });
        }
    }
}]);


/*Load Checkbox with styles*/
angular.module('confirm').directive('loadFormCheckbox', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            if (true) {
                $timeout(function () {
                    initCustomForms();
                }, 1000);
            }
        }
    }
}]);

;
'use strict';

angular.module('confirm').factory('MmtConfirmPageDataStorageService', ['$q', 'ConfirmSvc',
    function ($q, confirmSvc) {
        var cartData = { items: [] };

        var loadData = function (orderId) {
            var deferred = $q.defer();
            confirmSvc.getOrder(orderId).$promise.then(
                function (freshCartData) {
                    sync(freshCartData, false);
                    deferred.resolve({});
                },
                function (error) { deferred.reject(error); });
            return deferred.promise;
        };

        var sync = function (freshCartData) {
            cartData.total = freshCartData.Total;
            cartData.subtotal = freshCartData.SubTotal;
            cartData.giftWrapSubTotal = freshCartData.GiftWrapSubTotal;
            cartData.totalShipping = freshCartData.TotalShipping;
            cartData.totalTax = freshCartData.TotalTax;
            cartData.TotalDiscounts = freshCartData.TotalDiscounts;
            cartData.ShippingDiscount = freshCartData.ShippingDiscount;
            cartData.Surcharge = freshCartData.Surcharge;
            cartData.USCustoms = freshCartData.USCustoms;
            cartData.taxes = freshCartData.Taxes;
            cartData.showShippingMarketing = freshCartData.ShowShippingMarketing;
            cartData.signedIn = freshCartData.SignedIn;
            cartData.shippingAddress = freshCartData.ShippingAddress;
            cartData.customer = freshCartData.Customer;
            cartData.selectedStore = freshCartData.SelectedStore;
            cartData.items = freshCartData.LineItems;
            cartData.Payments = freshCartData.Payments;
            cartData.CreditCardInfo = freshCartData.CreditCardInfo;
            cartData.ShippingRateInfo = freshCartData.ShippingRateInfo;
            cartData.GiftCardDetails = freshCartData.GiftCardDetails;
            cartData.OrderDateTime = freshCartData.OrderDateTime;
            cartData.GiftCardImageUrl = freshCartData.GiftCardImageUrl;
            cartData.OrderCancelled = freshCartData.OrderCancelled;
            cartData.totalSavings = freshCartData.TotalSavings;
            cartData.perkCode = freshCartData.PerkCode;
            cartData.perkDiscount = freshCartData.PerkDiscount;
            cartData.totalDiscountsExPerk = freshCartData.TotalDiscountsExPerk;
            cartData.perkTotalSavings = freshCartData.PerkTotalSavings;
        };

        return {
            cartData: cartData,
            loadData: loadData,
            sync: sync
        };

    }]);;
'use strict';

angular.module('confirm').directive('mmtConfirmSummary', ['appUrlBuilder', 'AppObserver', function (appUrlBuilder, appObserver) {
    return {
        restrict: 'A',
        templateUrl: appUrlBuilder.buildTemplateUrl('checkoutOrderSummaryTemplateUrl'),
        priority: 1001,
        scope: {
            cart: '=',
            //in shipping estimate page is true
            estimate: '=',
            giftCards: '='
        },
        link: function (scope, element) {
            scope.blinkGiftCardblinkItem = false;
            //change blinItem value to trigger odBlinkElement Directive when shippingRateChanged event occur
            var shippingRateChangedListener = appObserver.subscribe('shippingRateChanged', scope, function () {
                scope.blinkItem = !scope.blinkItem;
            });

            //get latest postalCode from postalCodeChanged event
            var postalCode = (typeof scope.cart === 'undefined' || scope.cart === undefined || typeof scope.cart.addressInfo === 'undefined' || scope.cart.addressInfo === undefined) ? '' : scope.cart.addressInfo.ShippingAddress.PostalCode;
            var postalCodeChangedListener = appObserver.subscribe('postalCodeChanged', scope, function (message) {
                postalCode = message.postalCode;
            });

            //decide show generic tax or detail tax 
            scope.showGenericTax = function () {
                //in shipping estimate page when change country or postal code is empty will display generic tax, 
                //in checkout page will display specific tax if shipping postal code not empty
                //reassign postalCode after scope.cart value assigned, use for checkout page to correct display generic or specific tax
                if (!scope.estimate && postalCode === '' && !(typeof scope.cart === 'undefined' || scope.cart === undefined || typeof scope.cart.addressInfo === 'undefined' || scope.cart.addressInfo === undefined)) {
                    postalCode = scope.cart.addressInfo.ShippingAddress.PostalCode;
                }
                if (postalCode === '') {
                    return true;
                } else {
                    return (scope.cart.taxes !== null && scope.cart.taxes.length === 0 || scope.cart.addressInfo.ShippingAddress.PostalCode === '');
                }
            };

            scope.cardBlink = false;
            var cardBlinkListener = appObserver.subscribe('giftCardBlinkListener', scope, function () {
                scope.cardBlink = !scope.cardBlink;
            });

            //Unbind listeners when scope is destroyed
            scope.$on('$destroy', function () {
                shippingRateChangedListener();
                postalCodeChangedListener();
                cardBlinkListener();
                element.remove();
            });
        }
    };
}]);
;
'use strict';

angular.module('confirm')
    .controller('MmtItemsListingCtrl', ['$scope', 'MmtConfirmPageDataStorageService',
        function ($scope, mmtConfirmPageDataStorageService) {
            $scope.cartData = mmtConfirmPageDataStorageService.cartData;
        }]);;
'use strict';

angular.module('confirm').directive('mmtConfirmItemsListing', ['appUrlBuilder', function (appUrlBuilder) {
    return {
        restrict: 'A',
        templateUrl: appUrlBuilder.buildTemplateUrl('confirmItemsListingTemplateUrl'),
        controller: 'MmtItemsListingCtrl',
        scope: {
        }
    };
}]);;
'use strict';

angular.module('confirm')
    .controller('MmtContactCtrl', ['$scope', 'MmtConfirmPageDataStorageService', function ($scope, mmtConfirmPageDataStorageService) {
        $scope.cartData = mmtConfirmPageDataStorageService.cartData;
    }]);;
'use strict';

angular.module('confirm').directive('mmtConfirmContact', ['appUrlBuilder',
    function (appUrlBuilder) {
        return {
            restrict: 'A',
            templateUrl: appUrlBuilder.buildTemplateUrl('confirmContactTemplateUrl'),
            scope: {
            },
            controller: 'MmtContactCtrl'
        };

    }]);;
'use strict';

angular.module('confirm')
    .controller('MmtShippingCtrl', ['$scope', 'MmtConfirmPageDataStorageService', function ($scope, mmtConfirmPageDataStorageService) {
        $scope.cartData = mmtConfirmPageDataStorageService.cartData;
    }]);;
'use strict';

angular.module('confirm').directive('mmtConfirmShipping', ['appUrlBuilder',
    function (appUrlBuilder) {
        return {
            restrict: 'A',
            templateUrl: appUrlBuilder.buildTemplateUrl('confirmShippingTemplateUrl'),
            scope: {
            },
            controller: 'MmtShippingCtrl'
        };

    }]);
;
'use strict';

angular.module('confirm')
    .controller('MmtPaymentCtrl', ['$scope', 'MmtConfirmPageDataStorageService', function ($scope, mmtConfirmPageDataStorageService) {
        $scope.cartData = mmtConfirmPageDataStorageService.cartData;
    }]);;
'use strict';

angular.module('confirm').directive('mmtConfirmPayment', ['appUrlBuilder',
    function (appUrlBuilder) {
        return {
            restrict: 'A',
            templateUrl: appUrlBuilder.buildTemplateUrl('confirmPaymentTemplateUrl'),
            scope: {
            },
            controller: 'MmtPaymentCtrl'
        };
    }]);;
/*global BootstrapDialog:false */
/*exported StoreFinder */
'use strict';


/**
 * The store finder has logic that allows end users to find stores based on a location (latitude/longitude)
 */
StoreFinder = (function ($, dialog) {

    var locationSearch = '';
    var imageTagFormat = "<img src=\"{0}\" alt=\"{1}\"/>";

    //constructor
    function StoreFinder(StoreLocator, constants, localization) {
        this.StoreLocator = StoreLocator;
        this.constants = constants;
        this.localization = localization;
    }

    /*
     * Display store information in a table
     */
    StoreFinder.prototype.addStoreRow = function (store) {
        if (store) {
            var inputStoreTimes = store.StoreHours;
            var htmlString = "<div>" + inputStoreTimes + "</div>";
            var isTimeSame = false;
            var initalTime = "";
            var outputStoreTimes = "";
            var startDay = 1;
            var holidayHours = "";
            var stringHolidayHours = "";
            if (inputStoreTimes.search("Sunday: Closed") > 0) {
                startDay = 0;
            }
            $('time', htmlString).each(function (index) {
                var storeTime = $(this).text().replace(/\s/g, '').substring($(this).text().replace(/\s/g, '').indexOf(":") + 1).toLowerCase();

                if (index === startDay) {
                    initalTime = storeTime;
                    outputStoreTimes = storeTime;
                }
                if (index > 6) {
                    var holidayString = $(htmlString).find('time').eq(index).html();
                    var holidayName = holidayString.substring(0, holidayString.indexOf(":"));
                    var holidayHrs = holidayString.substring(holidayString.indexOf(":") + 1, holidayString.length);
                    holidayHours += '<dt>' + holidayName + '</dt>';
                    holidayHours += '<dd><time itemprop="openingHours" datetime="Holiday: ' + holidayName + '">' + holidayHrs + '</time></dd>';
                }                
                if (index >= startDay + 1 && index <= startDay + 4) {
                    if (initalTime === storeTime.toLowerCase()) {
                        initalTime = storeTime;
                        isTimeSame = true;
                    } else {
                        isTimeSame = false;
                        return false;
                    }
                }
                return true;
            });
            var splitedStringHoursArray = $(htmlString).html().split("<b>");
            if (splitedStringHoursArray.length > 0) {
                stringHolidayHours = SplitHolidayHours(splitedStringHoursArray);                
            }
            if (isTimeSame) {
                var weekTime = initalTime.split("-")[0] + " - " + initalTime.split("-")[1];
                var sundayTime = '';
                if (startDay == 1) {
                    sundayTime = $(htmlString).find('time').eq(0).html();
                } else {
                    sundayTime = 'Sunday: Closed';
                }

                var saturday = '';
                if (inputStoreTimes.search("Saturday: Closed") > 0) {
                    saturday = 'Saturday: Closed';
                } else {
                    saturday = $(htmlString).find('time').eq(startDay + 5).html();
                }
                outputStoreTimes = '<dl>';
                outputStoreTimes += '<dt>Monday-Friday</dt>';
                outputStoreTimes += '<dd><time itemprop="openingHours" datetime="Mon-Fri: ' + weekTime + '">' + weekTime + '</time></dd>';
                outputStoreTimes += '<dt>Saturday</dt>';
                outputStoreTimes += '<dd><time itemprop="openingHours" datetime="' + saturday + '">' + saturday.replace('Saturday:', '') + '</time></dd>';
                outputStoreTimes += '<dt>Sunday</dt>';
                outputStoreTimes += '<dd><time itemprop="openingHours" datetime="' + sundayTime + '">' + sundayTime.replace('Sunday:', '') + '</time></dd>';
                outputStoreTimes += holidayHours;
                outputStoreTimes += stringHolidayHours;
                outputStoreTimes += '</dl>';
            } else {
                outputStoreTimes = inputStoreTimes;
            }

            var newsSection = '';
            if (store.StoreNews.length > 0) {
                newsSection += '<div class="location-item location-text alignright" itemprop="description">';
                newsSection += '<strong class="location-title">Store News</strong>';
                newsSection += store.StoreNews + '</div>';
            }

            var getDirectionLink = 'https://maps.google.com/maps?saddr={0}&daddr={1}{2},{3}&hl=en'.format(locationSearch, store.Address, store.CityProvince, store.Country);

            var yourStoreText = "<a id='myStore" + store.StoreId + "' href='javascript:makemystore(\"" + store.StoreId + "\")' class='arrow-right'>Set as My Store</a>";
            if ($.cookie("MMT-UserDefaultStore") == store.StoreId) {
                yourStoreText = "<a id='myStore" + store.StoreId + "' href='javascript:makemystore(\"" + store.StoreId + "\")' class='arrow-right'>Your Store</a>";
            }
            var htmlRow = '';
            htmlRow += '<div class="location-description">';
            htmlRow += '<div class="location-holder" itemscope itemtype="http://schema.org/Store">';
            htmlRow += '<div class="location-item location-headline">';
            htmlRow += '<span class="location-icon-text"><i class="icon-location"></i><span class="text">' + store.Num + '</span></span>';
            htmlRow += '<div class="location-distance">';
            htmlRow += '<p>' + store.Distance.toLocaleString() + ' km</p></div>';
            htmlRow += '<h5><span itemprop="name"><a style="color:inherit;" class="storeDetail-Popup" data-fancybox-type="ajax" id="' + store.StoreId + '" href="#">' + store.StoreName + '</a></span></h5></div>';
            htmlRow += '<div class="location-item location-address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">';
            htmlRow += '<address><span itemprop="streetAddress">';
            if (store.Address.indexOf("||") > -1) {
                var splitAddress = store.Address.split("||");
                if (splitAddress.length >= 1) {
                    htmlRow += splitAddress[0];
                }
                if (splitAddress.length >= 2) {
                    htmlRow += splitAddress[1].length > 0 ? ' <br> ' + splitAddress[1] : splitAddress[1];
                }
                if (splitAddress.length >= 3) {
                    htmlRow += splitAddress[2].length > 0 ? ' <br> ' + splitAddress[2] : splitAddress[2];
                }
            } else {
                htmlRow += store.Address;
            }
            htmlRow += ' </span> <br> <span itemprop="addressLocality">' + store.CityProvince + '</span> </address> </div>';

            htmlRow += '<div class="location-item phone-block"><a href="tel:' + store.LocalPhone + '"><i class="icon-phone"></i><span itemprop="telephone" content="' + store.LocalPhone + '">' + store.LocalPhone + '</span></a></div>';

            if (store.StoreId) {
                htmlRow += '<div class="location-item visual-block"> <div class="location-visual">';
                htmlRow += '<picture><img src="' + rootRel + 'ImageHandler.axd?ownerTable=StoreLocations&ownerId=' + store.StoreId + '&width=251&height=120&constraint=4&interpolate=7&async=True" /></picture></div></div>';
            }
            htmlRow += "<div class='location-item buttons-holder'><a href='" + getDirectionLink + "' target='_blank' class='arrow-right'>Get directions</a>" + yourStoreText + "</div>";
            htmlRow += "<div class='location-item schedule-block'>" + outputStoreTimes + "</div>";

            htmlRow += newsSection + '</div></div>';
            //htmlRow += '<script>function makemystore(id){var obj = $("#myStore" + id);obj.text("Your Store");obj.bind("click", false);var objB = $("#myStoreB" + id);objB.text("Your Store");objB.bind("click", false);if(id != $.cookie("MMT-UserDefaultStore")){var previousObj = $("#myStore" + $.cookie("MMT-UserDefaultStore"));previousObj.text("Set as My Store");previousObj.unbind("click", false);var previousObjB = $("#myStoreB" + $.cookie("MMT-UserDefaultStore"));previousObjB.text("Set as My Store");previousObjB.unbind("click", false);$.cookie("MMT-UserDefaultStore", id, { expires: 365, path:"/" });initHeaderStoreInitialization();}$.cookie("setDefaultStore", id, {expires: 365,path: "/"});}';
            //htmlRow += '</script>';
            $('#storeInformation').append(htmlRow);
        }
    };

    StoreFinder.prototype.addStoreRowWithIndex = function (store, index) {
        if (store) {
            var inputStoreTimes = store.StoreHours;
            var htmlString = "<div>" + inputStoreTimes + "</div>";
            var isTimeSame = false;
            var initalTime = "";
            var outputStoreTimes = "";
            var startDay = 1;
            var holidayHours = "";
            var stringHolidayHours = "";
            if (inputStoreTimes.search("Sunday: Closed") > 0) {
                startDay = 0;
            }
            $('time', htmlString).each(function (index) {
                var storeTime = $(this).text().replace(/\s/g, '').substring($(this).text().replace(/\s/g, '').indexOf(":") + 1).toLowerCase();

                if (index === startDay) {
                    initalTime = storeTime;
                    outputStoreTimes = storeTime;
                }
                if (index > 6) {
                    var holidayString = $(htmlString).find('time').eq(index).html();
                    var holidayName = holidayString.substring(0, holidayString.indexOf(":"));
                    var holidayHrs = holidayString.substring(holidayString.indexOf(":") + 1, holidayString.length);
                    holidayHours += '<dt>' + holidayName + '</dt>';
                    holidayHours += '<dd><time itemprop="openingHours" datetime="Holiday: ' + holidayName + '">' + holidayHrs + '</time></dd>';
                }               
                if (index >= startDay + 1 && index <= startDay + 4) {
                    if (initalTime === storeTime.toLowerCase()) {
                        initalTime = storeTime;
                        isTimeSame = true;
                    } else {
                        isTimeSame = false;
                        return false;
                    }
                }
                return true;
            });
            var splitedStringHoursArray = $(htmlString).html().split("<b>");
            if (splitedStringHoursArray.length > 0) {
                stringHolidayHours = SplitHolidayHours(splitedStringHoursArray);                
            }
            if (isTimeSame) {
                var weekTime = initalTime.split("-")[0] + " - " + initalTime.split("-")[1];
                var sundayTime = '';
                if (startDay == 1) {
                    sundayTime = $(htmlString).find('time').eq(0).html();
                } else {
                    sundayTime = 'Sunday: Closed';
                }

                var saturday = '';
                if (inputStoreTimes.search("Saturday: Closed") > 0) {
                    saturday = 'Saturday: Closed';
                } else {
                    saturday = $(htmlString).find('time').eq(startDay + 5).html();
                }
                outputStoreTimes = '<dl>';
                outputStoreTimes += '<dt>Monday-Friday</dt>';
                outputStoreTimes += '<dd><time itemprop="openingHours" datetime="Mon-Fri: ' + weekTime + '">' + weekTime + '</time></dd>';
                outputStoreTimes += '<dt>Saturday</dt>';
                outputStoreTimes += '<dd><time itemprop="openingHours" datetime="' + saturday + '">' + saturday.replace('Saturday:', '') + '</time></dd>';
                outputStoreTimes += '<dt>Sunday</dt>';
                outputStoreTimes += '<dd><time itemprop="openingHours" datetime="' + sundayTime + '">' + sundayTime.replace('Sunday:', '') + '</time></dd>';
                outputStoreTimes += holidayHours;
                outputStoreTimes += stringHolidayHours;
                outputStoreTimes += '</dl>';
            } else {
                outputStoreTimes = inputStoreTimes;
            }

            var newsSection = '';
            if (store.StoreNews.length > 0) {
                newsSection += '<div class="location-item location-text alignright" itemprop="description">';
                newsSection += '<strong class="location-title">Store News</strong>';
                newsSection += store.StoreNews + '</div>';
            }

            var getDirectionLink = 'https://maps.google.com/maps?saddr={0}&daddr={1}{2},{3}&hl=en'.format(locationSearch, store.Address, store.CityProvince, store.Country);

            var yourStoreText = "<a id='myStore" + store.StoreId + "' href='javascript:makemystore(\"" + store.StoreId + "\")' class='arrow-right'>Set as My Store</a>";
            if ($.cookie("MMT-UserDefaultStore") == store.StoreId) {
                yourStoreText = "<a id='myStore" + store.StoreId + "' href='javascript:makemystore(\"" + store.StoreId + "\")' class='arrow-right'>Your Store</a>";
            }
            var htmlRow = '';
            if (index > 1) {
                htmlRow += '<div class="location-description loadmorestores">';
            } else {
                htmlRow += '<div class="location-description">';
            }
            htmlRow += '<div class="location-holder" itemscope itemtype="http://schema.org/Store">';
            htmlRow += '<div class="location-item location-headline">';
            htmlRow += '<span class="location-icon-text"><i class="icon-location"></i><span class="text">' + store.Num + '</span></span>';
            htmlRow += '<div class="location-distance">';
            htmlRow += '<p>' + store.Distance.toLocaleString() + ' km</p></div>';
            htmlRow += '<h5><span itemprop="name"><a style="color:inherit;" class="storeDetail-Popup" data-fancybox-type="ajax" id="' + store.StoreId + '" href="#">' + store.StoreName + '</a></span></h5></div>';
            htmlRow += '<div class="location-item location-address" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">';
            htmlRow += '<address><span itemprop="streetAddress">';
            if (store.Address.indexOf("||") > -1) {
                var splitAddress = store.Address.split("||");
                if (splitAddress.length >= 1) {
                    htmlRow += splitAddress[0];
                }
                if (splitAddress.length >= 2) {
                    htmlRow += splitAddress[1].length > 0 ? ' <br> ' + splitAddress[1] : splitAddress[1];
                }
                if (splitAddress.length >= 3) {
                    htmlRow += splitAddress[2].length > 0 ? ' <br> ' + splitAddress[2] : splitAddress[2];
                }
            } else {
                htmlRow += store.Address;
            }
            htmlRow += ' </span> <br> <span itemprop="addressLocality">' + store.CityProvince + '</span> </address> </div>';

            htmlRow += '<div class="location-item phone-block"><a href="tel:' + store.LocalPhone + '"><i class="icon-phone"></i><span itemprop="telephone" content="' + store.LocalPhone + '">' + store.LocalPhone + '</span></a></div>';

            if (store.StoreId) {
                htmlRow += '<div class="location-item visual-block"> <div class="location-visual">';
                htmlRow += '<picture><img src="' + rootRel + 'ImageHandler.axd?ownerTable=StoreLocations&ownerId=' + store.StoreId + '&width=251&height=120&constraint=4&interpolate=7&async=True" /></picture></div></div>';
            }
            htmlRow += "<div class='location-item buttons-holder'><a href='" + getDirectionLink + "' target='_blank' class='arrow-right'>Get directions</a>" + yourStoreText + "</div>";
            htmlRow += "<div class='location-item schedule-block'>" + outputStoreTimes + "</div>";

            htmlRow += newsSection + '</div></div>';
            //htmlRow += '<script>function makemystore(id){var obj = $("#myStore" + id);obj.text("Your Store");obj.bind("click", false);var objB = $("#myStoreB" + id);objB.text("Your Store");objB.bind("click", false);if(id != $.cookie("MMT-UserDefaultStore")){var previousObj = $("#myStore" + $.cookie("MMT-UserDefaultStore"));previousObj.text("Set as My Store");previousObj.unbind("click", false);var previousObjB = $("#myStoreB" + $.cookie("MMT-UserDefaultStore"));previousObjB.text("Set as My Store");previousObjB.unbind("click", false);$.cookie("MMT-UserDefaultStore", id, { expires: 365, path:"/" });initHeaderStoreInitialization();}$.cookie("setDefaultStore", id, {expires: 365,path: "/"});}';
            //htmlRow += '</script>';
            if (index == 1) {
                htmlRow += '<div class=\"btn-load-more desktop-hidden\"><a href=\"#\" onclick=\"return loadMoreclick();\"><span class=\"icon-check rounded\"></span>Load more locations</a></div>';
                htmlRow += '<script>function loadMoreclick(){ $(".loadmorestores").removeClass(\"loadmorestores\"); $(\'.btn-load-more\').hide(); setTimeout(function () { initCustomForms(); }, 50); $(\'\html, body\').animate({scrollTop: $(\".btn-load-more\").offset().top}, 2000); return true;}</script>';
            }
            $('#storeInformation').append(htmlRow);

        }
    };

    /*

    * Get store list information by latitude, longitude and range
    */
    StoreFinder.prototype.getStores = function (lat, lng, range) {
        if ($("#searchLatitude").length > 0) {
            $("#searchLatitude").val(lat);
        }
        if ($("#searchLongitude").length > 0) {
            $("#searchLongitude").val(lng);
        }

        $('#storeInformation').html('');

        var root = this;
        root.StoreLocator.addCurrentLocationMarker(lat, lng);
        $.ajax({
            url: rootRel + 'Stores/getStores?lat=' + lat + '&lng=' + lng + '&range=' + range,
            dataType: "json",
            success: function (data) {
                if (data) {
                    var maxDistance = 0;                    
                    $.each(data, function (index, store) {
                        var latitude = store.Latitude;
                        var longitude = store.Longitude;
                        var title = store.Title;
                        var getDirectionLink = 'https://maps.google.com/maps?saddr={0}&daddr={1}{2},{3}&hl=en'.format(locationSearch, store.Address, store.CityProvince, store.Country);

                        var inputStoreTimes = store.StoreHours;
                        var htmlString = "<div>" + inputStoreTimes + "</div>";
                        var isTimeSame = false;
                        var initalTime = "";
                        var outputStoreTimes = "";
                        var startDay = 1;
                        var holidayHours = "";
                        var stringHolidayHours = "";
                        if (inputStoreTimes.search("Sunday: Closed") > 0) {
                            startDay = 0;
                        }
                        $('time', htmlString).each(function (index) {
                            var storeTime = $(this).text().replace(/\s/g, '').substring($(this).text().replace(/\s/g, '').indexOf(":") + 1).toLowerCase();

                            if (index === startDay) {
                                initalTime = storeTime;
                                outputStoreTimes = storeTime;
                            }
                            if (index > 6) {
                                var holidayString = $(htmlString).find('time').eq(index).html();
                                var holidayName = holidayString.substring(0, holidayString.indexOf(":"));
                                var holidayHrs = holidayString.substring(holidayString.indexOf(":") + 1, holidayString.length);
                                holidayHours += '<dt>' + holidayName + '</dt>';
                                holidayHours += '<dd><time itemprop="openingHours" datetime="Holiday: ' + holidayName + '">' + holidayHrs + '</time></dd>';
                            }                            
                            if (index >= startDay + 1 && index <= startDay + 4) {
                                if (initalTime === storeTime.toLowerCase()) {
                                    initalTime = storeTime;
                                    isTimeSame = true;
                                } else {
                                    isTimeSame = false;
                                    return false;
                                }
                            }
                            return true;
                        });
                        var splitedStringHoursArray = $(htmlString).html().split("<b>");
                        if (splitedStringHoursArray.length > 0) {
                            stringHolidayHours=SplitHolidayHours(splitedStringHoursArray);                            
                        }
                        if (isTimeSame) {
                            var weekTime = initalTime.split("-")[0] + " - " + initalTime.split("-")[1];
                            var sundayTime = '';
                            if (startDay == 1) {
                                sundayTime = $(htmlString).find('time').eq(0).html();
                            } else {
                                sundayTime = 'Sunday: Closed';
                            }

                            var saturday = '';
                            if (inputStoreTimes.search("Saturday: Closed") > 0) {
                                saturday = 'Saturday: Closed';
                            } else {
                                saturday = $(htmlString).find('time').eq(startDay + 5).html();
                            }
                            outputStoreTimes = '<dl>';
                            outputStoreTimes += '<dt>Monday-Friday</dt>';
                            outputStoreTimes += '<dd><time itemprop="openingHours" datetime="Mon-Fri: ' + weekTime + '">' + weekTime + '</time></dd>';
                            outputStoreTimes += '<dt>Saturday</dt>';
                            outputStoreTimes += '<dd><time itemprop="openingHours" datetime="' + saturday + '">' + saturday.replace('Saturday:', '') + '</time></dd>';
                            outputStoreTimes += '<dt>Sunday</dt>';
                            outputStoreTimes += '<dd><time itemprop="openingHours" datetime="' + sundayTime + '">' + sundayTime.replace('Sunday:', '') + '</time></dd>';
                            outputStoreTimes += holidayHours;
                            outputStoreTimes += stringHolidayHours;
                            outputStoreTimes += '</dl>';
                        } else {
                            outputStoreTimes = inputStoreTimes;
                        }
                        var newsSection = '';
                        newsSection += '<div class="location-item location-text alignright" itemprop="description">';
                        if (store.StoreNews.length > 0) {
                            newsSection += '<strong class="location-title">Store News</strong>';
                            newsSection += store.StoreNews;
                        }
                        newsSection += '</div>';
                        var yourStoreText = "<a id='myStoreB" + store.StoreId + "' href='javascript:makemystore(\"" + store.StoreId + "\")' class='arrow-right'>Set as My Store</a>";
                        if ($.cookie("MMT-UserDefaultStore") == store.StoreId) {
                            yourStoreText = "<a id='myStoreB" + store.StoreId + "' href='javascript:makemystore(\"" + store.StoreId + "\")' class='arrow-right'>Your Store</a>";
                        }
                        var content = '';
                        content += '<div class="location-description inline-location">';
                        content += '<div class="location-holder" itemscope="" itemtype="http://schema.org/Store">';

                        if (store.StoreId) {
                            content += '<div class="location-item visual-block alignright" style="width: 100%;">';
                            content += '<div class="location-visual">';
                            content += '<picture><img src="' + rootRel + 'ImageHandler.axd?ownerTable=StoreLocations&ownerId=' + store.StoreId + '&width=251&height=120&constraint=4&interpolate=7&async=True" /></picture></div></div>';
                        }
                        content += '<div class="location-item location-headline">';
                        content += '<span class="location-icon-text icon-shadow"><i class="icon-location bordered"></i><span class="text">' + store.Num + '</span></span>';
                        content += '<div class="location-distance"><p>' + store.Distance.toLocaleString() + ' km</p></div>';
                        content += '<h5><span itemprop="name"><a style="color:inherit;" href="' + rootRel + "stores/" + store.StoreId + "-" + store.StoreName.replace(/ /g, '').replace(/[^\w]/gi, + '') + '.aspx' + '">' + store.StoreName + '</a></span></h5></div>';
                        content += '<div class="location-item location-address" itemprop="address" itemscope="" itemtype="http://schema.org/PostalAddress">';
                        content += '<address> <span itemprop="streetAddress">';
                        if (store.Address.indexOf("||") > -1) {
                            var splitAddress = store.Address.split("||");
                            if (splitAddress.length >= 1) {
                                content += splitAddress[0];
                            }
                            if (splitAddress.length >= 2) {
                                content += splitAddress[1].length > 0 ? ' <br> ' + splitAddress[1] : splitAddress[1];
                            }
                            if (splitAddress.length >= 3) {
                                content += splitAddress[2].length > 0 ? ' <br> ' + splitAddress[2] : splitAddress[2];
                            }
                        } else {
                            content += store.Address;
                        }
                        content += ' </span> <br>';
                        content += ' <span itemprop="addressLocality">' + store.CityProvince + '</span></address></div>';

                        content += '<div class="location-item phone-block"><a href="tel:' + store.LocalPhone + '"><i class="icon-phone"></i><span itemprop="telephone" content="' + store.LocalPhone + '">' + store.LocalPhone + '</span></a></div>';

                        content += "<div class='location-item buttons-holder'><a href='" + getDirectionLink + "' target='_blank' class='arrow-right'>Get directions</a>";
                        content += yourStoreText + "</div>";
                        content += newsSection;
                        content += '<div class="location-item schedule-block">' + outputStoreTimes + '</div>';

                        content += '</div></div>';
                        content += '<a id="mapCloseIcon" class="close icon-close"></a>';

                        var num = store.Num;
                        if (maxDistance < store.Distance) {
                            maxDistance = store.Distance;
                        }
                        root.StoreLocator.addMarkerAndInfoWindow(latitude, longitude, title, content, num);
                        if (index >= 1) {
                            root.addStoreRowWithIndex.call(root, store, index);
                        } else {
                            root.addStoreRow.call(root, store);
                        }
                    });

                    var zoom = 0;
                    if (maxDistance <= 5) {
                        zoom = 14;
                    } else if (maxDistance <= 10) {
                        zoom = 12;
                    } else if (maxDistance <= 20) {
                        zoom = 10;
                    } else if (maxDistance <= 50) {
                        zoom = 9;
                    } else if (maxDistance <= 100) {
                        zoom = 8;
                    } else if (maxDistance <= 150) {
                        zoom = 7;
                    } else if (maxDistance <= 200) {
                        zoom = 6;
                    }

                    root.StoreLocator.setMapLocation(lat, lng, zoom);
                }
                setTimeout(function () { initCustomForms(); }, 50);
            }
        });
    };

    function SplitHolidayHours(splitedStringHoursArray) {
        var stringHolidayHours = "";
        var i = 0
        for (i = 0; i < splitedStringHoursArray.length; i++) {
            var indexOsStratOfStringHolidays = 0;//$(htmlString).html().indexOf("<b>");
            var indexOsEndOfStringHolidays = splitedStringHoursArray[i].indexOf("</b>");
            var stringHolidays = "";
            
            stringHolidays = splitedStringHoursArray[i].substring(indexOsStratOfStringHolidays, indexOsEndOfStringHolidays)

            var holidayName = stringHolidays.substring(0, stringHolidays.indexOf(":"));
            var holidayHrs = stringHolidays.substring(stringHolidays.indexOf(":") + 1, stringHolidays.length);
            stringHolidayHours += '<dt>' + holidayName + '</dt>';
            stringHolidayHours += '<dd><time itemprop="openingHours" datetime="Holiday: ' + holidayName + '">' + holidayHrs + '</time></dd>';
            
        }
        return stringHolidayHours;
}
    /*
     * Get location from the user input including country, postal and address
     */
    StoreFinder.prototype.GetUserLocation = function (country, address) {
        var root = this;
        var range = $('#Range').val();
        var geocoder = new google.maps.Geocoder();
        console.log("Address sent to Google :" + "address: " + address + ", " + country);
        geocoder.geocode({ 'address': address + "," + country }, function (results, status) {
            console.log("Latitude from Google: " + results[0].geometry.location.lat());
            console.log("Longitude from Google: " + results[0].geometry.location.lng());
            if (status == google.maps.GeocoderStatus.OK) {
                var lat = results[0].geometry.location.lat();
                var lng = results[0].geometry.location.lng();
                locationSearch = "{0},{1}".format(address, country);
                root.getStores.call(root, lat, lng, range);
            }
        });

    };
    StoreFinder.prototype.noPosition = function () {
        var root = this;

        //root.getStores('', '', -1); 
        $('span.current-location-spinner').hide();
        dialog.alert(root.localization.StoreFinderCannotGetYourCurrentLocation);
    };
    StoreFinder.prototype.getCurrentPosition = function (options) {
        var root = this;

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                function (pos) {
                    var crd = pos.coords;
                    var range = $('#Range').val();
                    locationSearch = "{0},{1}".format(crd.latitude, crd.longitude);
                    root.getStores.call(root, crd.latitude, crd.longitude, range);
                },
                function () {
                    StoreFinder.prototype.noPosition.call(root);
                },
                options);
        }
        else {
            StoreFinder.prototype.noPosition.call(root);
        }

    };

    /*begin: email signup store locator*/
    StoreFinder.prototype.getCurrentPositionEmailSignUp = function (options,  range) {
        if (navigator.geolocation) {             
            navigator.geolocation.getCurrentPosition(
                function (pos) {                    
                    var crd = pos.coords;
                    GetStoreResultsEmailSignUp(crd.latitude, crd.longitude, range);
                },
                function () {
                    $.ajax({
                        type: "get",
                        url: rootRel + 'Newsletter/GetStoresList',
                        success: function (response) {
                            $('#emailSignUpStoreListPlace').html(response);
                            $('#emailSignUpStoreListPlaceEmailSIgnUp').html(response);
                             $('#divSelectedStoreText').hide();
                        },
                        error: function (e) {

                        }
                    });
                    
                    console.log("Geolocatoion service is not available");
                },
                options);
        }
        else {
            console.log("Geolocatoion service is not available");
        }
    };
    StoreFinder.prototype.getUserLocationStoreEmailSignUp = function (country, address, range) {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'address': address + "," + country }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var lat = results[0].geometry.location.lat();
                var lng = results[0].geometry.location.lng();               
                GetStoreResultsEmailSignUp(lat, lng, 'FindByPostalCode');
            } else {
                $("#storeResultsNotFoundEmailSignUp").html(storeNotFoundNearBy);
            }
        });
    };
    /*end: email signup store locator*/
    //bvc store inventory
    StoreFinder.prototype.getCurrentPositionStoreInv = function (options, itemId, range) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                function (pos) {
                    var crd = pos.coords;
                    GetStoreInvResults(itemId, crd.latitude, crd.longitude, range);
                },
                function () {
                    console.log("Geolocatoion service is not available");
                },
                options);
        }
        else {
            console.log("Geolocatoion service is not available");
        }
    };

    StoreFinder.prototype.getUserLocationStoreInv = function (country, address, itemId, range) {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'address': address + "," + country }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var lat = results[0].geometry.location.lat();
                var lng = results[0].geometry.location.lng();
                GetStoreInvResults(itemId, lat, lng, range);
            } else {
                $("#storeInvResults").html(storeInvErrorMsg);
            }
        });
    };
    //bvc store inventory


    return StoreFinder;

})(jQuery, BootstrapDialog);;
/*global google:false */
/*exported StoreLocator */

var map;
var mapOptions;
var mapLocation;
var marker;
var currentMarkers = [];
var infoWindow;
var currentInfoWindows = [];

/**
 * The store locator provides the interface to Google Maps and any manipulation of the results.
 */
 StoreLocator = (function ($, ggl) {

    //constructor
    function StoreLocator(constants, localization) {
        this.constants = constants;
      
        this.localization = localization;
    }

    /*
     * Initialize the google map
     */
    StoreLocator.prototype.initialize = function(lat, lng) {
        mapLocation = new ggl.maps.LatLng(lat, lng);
        mapOptions = {
            mapTypeControl: false,
            streetViewControl: false,
            zoomControl: true,
            panControl: true,
            zoom: 4,
            center: mapLocation,
            mapTypeId: ggl.maps.MapTypeId.ROADMAP
        };

        map = new ggl.maps.Map(document.getElementById('map_canvas'), mapOptions);
        $('div').on('touchstart', '.gmnoprint div[title^=Pan]', function() {
            $(this).trigger('click');
            return false;
        });
    };
    
    /*
     * Add Pin and popup information popup in the map for each store
     */
    StoreLocator.prototype.addMarkerAndInfoWindow = function(latitude, longitude, title, content, num) {

        mapLocation = new ggl.maps.LatLng(latitude, longitude);

        marker = new ggl.maps.Marker({
            position: mapLocation,
            animation: ggl.maps.Animation.DROP,
            icon: this.constants.rootUrl + '/Content/images/locationPins/' + num + '.png',
            map: map,
            title: title.toString(),
        });

        currentMarkers.push(marker);

        infoWindow = new ggl.maps.InfoWindow({
            position: mapLocation,
            content: content.toString(),
            disableAutoPan: false,
            pixelOffset: new ggl.maps.Size(0, -25)
        });

        currentInfoWindows.push(infoWindow);

        

        this.listenToMarkerClick.call(this, marker, infoWindow, content);
    };
    
    /*
     * Add Pin to the position which the user input according to the longitude and latitude
     */
    StoreLocator.prototype.addCurrentLocationMarker = function (latitude, longitude) {
        mapLocation = new ggl.maps.LatLng(latitude, longitude);
      
        marker = new ggl.maps.Marker({
            position: mapLocation,
            clickable: true,
            icon: this.constants.rootUrl + '/Content/images/icons-png/locationPin.png',
            map: map,
            title: this.localization.StoreLocatorPinMsg
        });
        currentMarkers.push(marker);
        map.setCenter(mapLocation);
    };

    /*
     * Add Listener to the Pin in google map, when it is clicked, popup the detail information of the store
     */
    StoreLocator.prototype.listenToMarkerClick = function (marker, infoWindow) {
        var root = this;

        ggl.maps.event.addListener(marker, 'click', function () {
            root.removeAllInfoWindows.call(root);
            root.zoomMap.call(root, map, 15);
            root.setCenter.call(root, map, infoWindow.getPosition());
            infoWindow.open(map);
            var iwOuter = $('.gm-style-iw');
            var iwBackground = iwOuter.prev();

            // Removes background shadow DIV
            iwBackground.children(':nth-child(2)').css({ 'display': 'none' });

            //Cone above marker
            iwBackground.children(':nth-child(3)').children(':nth-child(1)').css({ 'top': '-8px' });
            iwBackground.children(':nth-child(3)').children(':nth-child(2)').css({ 'top': '-8px' });

            // Removes white background DIV
            iwBackground.children(':nth-child(4)').css({ 'display': 'none' });
            iwOuter.css({ 'background': '#fff none repeat scroll 0 0' });
            iwOuter.css({ 'border-radius' : '15px' });
            iwOuter.css({ 'box-shadow': '0 0 5px rgba(0, 0, 0, 0.15) inset' });
            iwOuter.css({ 'margin': '0' });


            iwOuter.parent().children(':nth-child(3)').css({ 'display': 'none' });

           
            $( "#mapCloseIcon" ).click(function() {
                iwOuter.parent().css({ 'display': 'none' });
            });
           
        });
        
    };

    /*
     * Set Map center position and zoom level
     */
    StoreLocator.prototype.setMapLocation = function (latitude, longitude, zoom) {
        var coords = new ggl.maps.LatLng(latitude, longitude);
        map.setZoom(zoom);
        map.setCenter(coords);
    };

    /*
     * Remove all the popup information window from the google map
     */
    StoreLocator.prototype.removeAllInfoWindows = function () {
        for (var i in currentInfoWindows) {
            currentInfoWindows[i].setMap(null);
        }
    };
    
    /*
     * Remove all the Pins and popup information window from the google map
     */
    StoreLocator.prototype.removeAllMarkersAndInfoWindows = function () {
        for (var i in currentInfoWindows) {
            currentInfoWindows[i].setMap(null);
        }

        for (i in currentMarkers) {
            currentMarkers[i].setMap(null);
        }
    };

    /*
     * Popup the information window
     */
    StoreLocator.prototype.openInfoWindow = function (latitude, longitude) {
        for (var i in currentInfoWindows) {
            if (this.roundToDecimal.call(this, currentInfoWindows[i].getPosition().lat(), 5) == latitude &&
                this.roundToDecimal.call(this, currentInfoWindows[i].getPosition().lng(), 5) == longitude) {
                currentInfoWindows[i].open(map);
                break;
            }
        }
    };

    /*
     * Set zoom level for google map
     */
    StoreLocator.prototype.zoomMap = function (map, latlng) {
        map.setZoom(latlng);
    };

    /*
     * Set center position of the google map
     */
    StoreLocator.prototype.setCenter = function (map, number) {
        map.setCenter(number);
    };

    StoreLocator.prototype.roundToDecimal = function (value, decimalPlaces) {
        return Math.round(value * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);
    };

    return StoreLocator;

})(jQuery, google);
;
var StoreDetail = (function ($) {

    //constructor
    function StoreDetail(storeLocator, constants) {
        this.storeLocator = storeLocator;
        this.constants = constants;
    }

    StoreDetail.prototype.GetStore = function (storeid) {
        var root = this;

        $.ajax({
            url: root.constants.rootUrl + '/api/stores/GetStoreDetail?storeid=' + storeid,
            success: function (data) {
                if (data) {
                    var store = data;

                    var latitude = store.Latitude;
                    var longitude = store.Longitude;
                    var title = store.Title;
                    var storeName = store.StoreName;
                    var getDirectionLink = 'https://maps.google.com/maps?daddr={0}{1},{2}&hl=en'.format(store.Address, store.CityProvince, store.Country);
                    var imageTagFormat = "<img src=\"{0}\" alt=\"{1}\"/>";

                    var inputStoreTimes = store.StoreHours;
                    var htmlString = "<div>" + inputStoreTimes + "</div>";
                    var isTimeSame = false;
                    var initalTime = "";
                    var outputStoreTimes = "";
                    var startDay = 1;
                    if (inputStoreTimes.search("Sunday: Closed") > 0) {
                        startDay = 0;
                    }
                    $('time', htmlString).each(function (index) {
                        var storeTime = $(this).text().replace(/\s/g, '').substring($(this).text().replace(/\s/g, '').indexOf(":") + 1).toLowerCase();

                        if (index === startDay) {
                            initalTime = storeTime;
                            outputStoreTimes = storeTime;
                        }
                        if (index >= startDay + 1 && index <= startDay + 4) {
                            if (initalTime === storeTime.toLowerCase()) {
                                initalTime = storeTime;
                                isTimeSame = true;
                            } else {
                                isTimeSame = false;
                                return false;
                            }
                        }
                        return true;
                    });
                    if (isTimeSame) {
                        var weekTime = initalTime.split("-")[0] + " - " + initalTime.split("-")[1];
                        var sundayTime = '';
                        if (startDay == 1) {
                            sundayTime = $(htmlString).find('time').eq(0).html();
                        } else {
                            sundayTime = 'Sunday: Closed';
                        }

                        var saturday = '';
                        if (inputStoreTimes.search("Saturday: Closed") > 0) {
                            saturday = 'Saturday: Closed';
                        } else {
                            saturday = $(htmlString).find('time').eq(startDay + 5).html();
                        }
                        outputStoreTimes = '<dl>';
                        outputStoreTimes += '<dt>Mon-Fri</dt>';
                        outputStoreTimes += '<dd><time itemprop="openingHours" datetime="Mon-Fri: ' + weekTime + '">' + weekTime + '</time></dd>';
                        outputStoreTimes += '<dt>Saturday</dt>';
                        outputStoreTimes += '<dd><time itemprop="openingHours" datetime="' + saturday + '">' + saturday.replace('Saturday:', '') + '</time></dd>';
                        outputStoreTimes += '<dt>Sunday</dt>';
                        outputStoreTimes += '<dd><time itemprop="openingHours" datetime="' + sundayTime + '">' + sundayTime.replace('Sunday:', '') + '</time></dd>';
                        outputStoreTimes += '</dl>';
                    } else {
                        outputStoreTimes = inputStoreTimes;
                    }

                    var yourStoreText = "<a id='myStoreB" + store.StoreId + "' href='javascript:makemystore(\"" + store.StoreId + "\")' class='arrow-right'>Set as My Store</a>";
                    if ($.cookie("MMT-UserDefaultStore") == store.StoreId) {
                        yourStoreText = "<a id='myStoreB" + store.StoreId + "' href='javascript:makemystore(\"" + store.StoreId + "\")' class='arrow-right'>Your Store</a>";
                    }
                    var content = '';
                    content += '<div class="location-description inline-location">';
                    content += '<div class="location-holder" itemscope="" itemtype="http://schema.org/Store">';
                    if (store.StoreId) {
                        content += '<div class="location-item visual-block alignright">';
                        content += '<div class="location-visual">';
                        content += '<picture><img src="' + rootRel + 'ImageHandler.axd?ownerTable=StoreLocations&ownerId=' + store.StoreId + '&width=232&height=232&constraint=4&interpolate=7&async=True" /></picture></div></div>';
                    }
                    content += '<div class="location-item location-headline">';
                    content += '<span class="location-icon-text icon-shadow"><i class="icon-location bordered"></i><span class="text"></span></span>';
                    content += '<h5><span itemprop="name"><a style="color:inherit;" href="' + rootRel + "stores/" + store.StoreId + "-" + store.StoreName.replace(/ /g, '').replace(/[^\w]/gi, + '') + '.aspx' + '">' + store.StoreName + '</a></span></h5></div>';
                    content += '<div class="location-item location-address" itemprop="address" itemscope="" itemtype="http://schema.org/PostalAddress">';
                    content += '<address> <span itemprop="streetAddress">' + store.Address + ' </span> <br>';
                    content += ' <span itemprop="addressLocality">' + store.CityProvince + '</span></address></div>';

                    content += '<div class="location-item phone-block"><a href="tel:' + store.LocalPhone + '"><i class="icon-phone"></i><span itemprop="telephone" content="' + store.LocalPhone + '">' + store.LocalPhone + '</span></a></div>';

                    content += "<div class='location-item buttons-holder'><a href='" + getDirectionLink + "' target='_blank' class='arrow-right'>Get directions</a>";
                    content += yourStoreText + "</div>";
                    content += '<div class="location-item schedule-block schedule-block-details">' + outputStoreTimes + '</div>';

                    content += '</div></div>';
                    content += '<a id="mapCloseIcon" class="close icon-close"></a>';


                    var num = store.Num;

                    root.storeLocator.addMarkerAndInfoWindow(latitude, longitude, storeName, content, 0);
                    var zoom = 15;
                    root.storeLocator.setMapLocation(latitude, longitude, zoom);
                }
            }
        });
    };

    return StoreDetail;

})(jQuery);;
'use strict';

/**
 * Lists the products that are in the cart.  Implements logic around changing of product details, such as the quantity.
 */
angular.module('checkout').controller('RISCartItemsListingCtrl',
    ['$scope', '$window', '$location', 'CartService', 'CartDataStorageService', 'AppObserver', 'spinnerFactory', 'WishListService', 'siteConfiguration', 'appUrlBuilder', 'DialogService', 'NavigationService',
    function ($scope, $window, $location, cartService, cartDataStorageService, appObserver, spinnerFactory, wishListService, siteConfiguration, appUrlBuilder, dialogService, navigationService) {

        $scope.productData = cartDataStorageService.cartData;		
        $scope.updateItemQuantity = function (itemId, quantity) {
           
            if (quantity === '' || quantity === '0') {
                $scope.removeFromCart(itemId);
            } else {
                //if any item in the cart quantity changed, will broadcast reloadShippingRates event
                var hasItemQuantityChanged = false;
                for (var i = 0; i < $scope.productData.items.length; i++) {
                    var item = $scope.productData.items[i];
                    if (item.Id === itemId && item.QuantityChanged === true) {
                        hasItemQuantityChanged = true;
                        spinnerFactory.show("Please wait...");
                        disableScrollOnSpinnerShow();

                        //for some weird reason 'jshint ignore:start - jshint ignore:end' does not work
                        cartService.updateItemQuantity(itemId, quantity).then( // jshint ignore:line
                            function() { spinnerFactory.hide();
                                enableScrollOnSpinnerHide();
                            }, // jshint ignore:line
                            function() { spinnerFactory.hide();
                                enableScrollOnSpinnerHide();
                            } // jshint ignore:line
                        ); // jshint ignore:line
                        
                    }
                }
                //if (hasItemQuantityChanged) {
                //    //broadcast reloadShippingRates event, current shippingEstimate controller listening on this in order to refresh the shipping rate
                //    appObserver.broadcast('reloadShippingRates', {});
                //}
            }
        };


        $scope.undoRemoveFromCart = function (item) {
            cartService.undoRemoveFromCart(item);

        };

		$scope.removeFromCartRIS = function (itemId) {			
			cartService.removeFromCartRIS(itemId);
		};

        $scope.addToWishList = function (itemId) {
            wishListService.addItem(itemId, function () {

                $scope.$apply(function () {
                    var addedProductId = 0;
                    angular.forEach($scope.productData.items, function (value) {
                        if (value.ItemId == itemId) {
                            addedProductId = value.ProductId;

                        }
                    });



                    angular.forEach($scope.productData.items, function (value) {
                        if (value.ProductId == addedProductId) {
                            value.IsInWishList = true;
                        }
                    });
                });

                var baseLen = $location.protocol().length + $location.host().length + siteConfiguration.rootUrl.length + 3;
                var retUrl = $location.absUrl().substring(baseLen);

                //if we add item to wishlist via cart on the wishlist page - we have to refresh wishlist page in order to show added items
                if (retUrl.toLowerCase().indexOf(siteConfiguration.wishListUrl.toLowerCase()) === 0) {
                    navigationService.navigate($location.absUrl() + '?showCart=True');
                }

            }, function (request, status, error) {
                if (error == 'Forbidden') {
                    navigationService.navigate(appUrlBuilder.buildUrl('signInPageUrl') + '?ReturnUrl=' + encodeURIComponent('~/ShoppingCart?addToWishList=' + itemId));
                } else {
                    dialogService.alert($window.res.GeneralError);
                }

            });
        };

        $scope.selectedPricingBonusItemChanged = function (itemGuid, newItemId, quantity) {
            cartService.updatePricingBonusItem(itemGuid, newItemId, quantity);
        };

        $scope.selectedDynPromoBonusItemChanged = function (itemGuid, newItemId, quantity) {
            cartService.updateDynPromoBonusItem(itemGuid, newItemId, quantity);
        };

        $scope.quantityChanged = function (itemId) {
            for (var i = 0; i < $scope.productData.items.length; i++) {
                var item = $scope.productData.items[i];
                if (item.Id === itemId) {
                    item.QuantityChanged = true;
                    break;
                }
            }
        };
    }
]);;
/**
* This is platform implemented checkout
*/
angular.module('checkout').directive('giftcardCheckout',
    ['$window', 'appUrlBuilder', 'CheckoutSvc', 'NavigationService',
    function ($window, appUrlBuilder, checkoutSvc, navigationService) {
        return {
            restrict: 'A',
            templateUrl: appUrlBuilder.buildTemplateUrl('giftCardcheckoutTemplateUrl'),
            scope: {
            },
            controller: 'MmtGiftCardCheckoutCtrl',
            link: function (scope) {
                scope.stores = {};
                scope.preSelectedCreditCard = false;
                scope.confirmCancel = function () {
                    checkoutSvc.confirmDialog();
                };
                scope.goBackToStore = function () {
                    navigationService.navigate(appUrlBuilder.buildUrl('homePageUrl'));
                };

                scope.preloadData();
            }
        };
    }]);;
/**
* This is platform implemented checkout
*/
angular.module('checkout').directive('risCheckout',
    ['$window', 'appUrlBuilder', 'CheckoutSvc', 'NavigationService',
    function ($window, appUrlBuilder, checkoutSvc, navigationService) {
        return {
            restrict: 'A',
			templateUrl: appUrlBuilder.buildTemplateUrl('rIScheckoutTemplateUrl'),
            scope: {
            },
			controller: 'mmtRISCheckoutCtrl',
            link: function (scope) {
                scope.stores = {};
                scope.preSelectedCreditCard = false;
                scope.confirmCancel = function () {
                    checkoutSvc.confirmDialog();
                };
                scope.goBackToStore = function () {
                    navigationService.navigate(appUrlBuilder.buildUrl('homePageUrl'));
                };

                scope.preloadData();
            }
        };
    }]);;
'use strict';
/**
 * Responsible for all checkout specific logic
 */
angular.module('checkout').controller('MmtGiftCardCheckoutCtrl', ['$scope', '$window', 'CheckoutSvc', 'CartDataStorageService', 'ShippingService', 'AppObserver', 'AddressDataHelper', 'siteConfiguration', 'siteRes', 'CheckoutDataStorageService', 'MmtGiftCardCheckoutSubmitCartSvc', 'CheckoutHelperService', 'CheckoutCreditCardValidationService', 'anchorHelper', 'spinnerFactory', '$timeout', '$modal', 'appUrlBuilder',
    function ($scope, $window, checkoutSvc, cartDataStorageService, shippingService, appObserver, addressDataHelper, siteConfiguration, siteRes, checkoutDataStorageService, checkoutSubmitCartSvc, checkoutHelperService, checkoutCreditCardValidationService, anchorHelper, spinnerFactory, $timeout, $modal, appUrlBuilder) {
        $scope.contactInfoBtn = "Next";
        $scope.shippingMethodBtn = "Next";
        $scope.cartData = cartDataStorageService.cartData;
        $scope.checkoutState = checkoutDataStorageService.checkoutState;
        $scope.addressBtn = "Next";
        $scope.identityName = 'MmtGiftCardCheckoutCtrl';
        $scope.password = '';
        //for paypal
        $scope.firstName = '';
        $scope.lastName = '';
        $scope.updateShippingAddressSuccess = true;
        $scope.billingIncomplete = false;
        $scope.emailRegex = siteConfiguration.emailRegex;
       // var shippingAddressIsEmpty = true;

        $scope.preloadData = function () {
            //preload cart data
            cartDataStorageService.loadCartData().then(function () {
                //updateScoppingCartItemsCount($scope.cartData);
                if ($scope.cartData.signedIn) {
                    checkoutSvc.getCustomerAddresses().$promise.then(function (value) {
                        $scope.checkoutState.customerShippingAddresses = value;
                        $scope.checkoutState.hasShippingAddresses = true;
                    }, function (error) {
                        console.log('Error for GetCustomerAddresses()', error);
                    });
                }
                //stage = 3 means come from PayPal express
                $scope.PayPalExpress = checkoutSvc.parseQueryString($window.location.search, 'stage') === '3';
                //var lastOrderInfo = $scope.cartData.addressInfo.LastOrderInfo;
                var currentOrderInfo = $scope.cartData.addressInfo.CurrentOrderInfo;
                if (!$scope.cartData.signedIn) {
                    $scope.clearAddress($scope.cartData.addressInfo.ShippingAddress);
                    $scope.clearAddress($scope.cartData.addressInfo.BillingAddress);
                }
                //var sAddress = $scope.cartData.signedIn && !$scope.PayPalExpress ? lastOrderInfo.ShippingAddress : $scope.cartData.addressInfo.ShippingAddress;
                //shippingAddressIsEmpty = sAddress.Address1 === '' && sAddress.City === '' && sAddress.Province === '';
                //if ($scope.cartData.signedIn && shippingAddressIsEmpty) {
                //    sAddress = $scope.cartData.addressInfo.BillingAddress;
                //}
                //var sAddress = $scope.cartData.addressInfo.ShippingAddress;
                //var shippingAddress = checkoutHelperService.addressDataMap(sAddress);
                //use billing address as shipping which is not required
                var bAddress = $scope.cartData.addressInfo.BillingAddress;
                var shippingAddress = checkoutHelperService.addressDataMap(bAddress); 
                var billingAddress = checkoutHelperService.addressDataMap(bAddress);
                $scope.addressData = { shippingData: shippingAddress, billingData: billingAddress };

                //for guest user: only show address section, hide all other sections
                //for registered user: user's last shipping address, payment method and shipping method use to pre-populate the existing form
                if (!$scope.cartData.signedIn) {
                    $scope.shippingRate = currentOrderInfo.ShipperId;
                }
                if ($scope.cartData.signedIn) {
                    //bvc
                    if ($scope.addressData.billingData.address1 == "") {
                        $scope.billingIncomplete = true;
                    }

                    $scope.updateShippingAddress(shippingAddress, true);
                    //$scope.cartData.phone = shippingAddressIsEmpty ? $scope.cartData.customer.Phone : lastOrderInfo.Phone;
                    $scope.cartData.phone = $scope.cartData.customer.Phone;
                    var orderPhoneNumber = $scope.cartData.phone;
                    orderPhoneNumber = orderPhoneNumber.length >= 10 ? orderPhoneNumber.replace(/(\d{3})(\d{3})(\d{4})?/, "$1-$2-$3") : orderPhoneNumber;
                    $scope.checkoutState.OrderPhoneNumber = orderPhoneNumber;
                    $scope.cartData.email = $scope.cartData.customer.Email;
                    //$scope.cartData.email = shippingAddressIsEmpty ? $scope.cartData.customer.Email : lastOrderInfo.Email;
                    //$scope.shippingRate = currentOrderInfo.ShipperId === 0 ? lastOrderInfo.ShipperId : currentOrderInfo.ShipperId;
                    // Note: ReceiverName is deprecated since we have it in the AddressInfo of the shipping object
                    $scope.cartData.receiverName = '';
                    $scope.firstName = $scope.cartData.customer.FirstName;
                    $scope.lastName = $scope.cartData.customer.LastName;
                    $scope.cartData.isGift = currentOrderInfo.IsGift;
                    $scope.cartData.giftNote = currentOrderInfo.GiftNote;
                   //$scope.checkoutState.paymentType = $scope.PayPalExpress ? 2 : lastOrderInfo.PaymentType;
                    $scope.checkoutState.addressSec = false;
                    $scope.checkoutState.receiverSec = false;
                    $scope.checkoutState.deliverToSec = true;
                    $scope.checkoutState.shippingMethodSec = true;
                    $scope.checkoutState.shipUsingSec = false;
                    $scope.checkoutState.contactSec = true;
                    //$scope.checkoutState.currentStage = 3;
                    if ($scope.cartData.ExistingCreditCards != null && $scope.cartData.ExistingCreditCards.length > 0) {
                        //$scope.checkoutState.paymentType = 3;
                        $scope.preSelectedCreditCard = true;
                        $scope.checkoutState.hasExistingCards = true;
                        //$scope.paymentMethods.showExistingCreditCardChecked = true;
                        //if ($scope.cartData.ExistingCreditCards.length === 1) {
                        //    $scope.checkoutState.existingCreditCardData = $scope.cartData.ExistingCreditCards[0];
                        //}
                        $scope.checkoutState.existingCreditCardData = $scope.cartData.ExistingCreditCards[0];
                    }
                    jQuery('.accordion').slideAccordion({
                        opener: '.accordion-opener',
                        slider: '.accordion-slide',
                        animSpeed: 400
                    });
                } else {
                    $scope.checkoutState.addressSec = true;
                }
                //$scope.paymentMethods.showCreditCardChecked = $scope.checkoutState.paymentType === 1;
            });
        };

        $scope.clearAddress = function (address) {
            address.FirstName = '';
            address.LastName = '';
            address.Address1 = '';
            address.Address2 = '';
            address.Address3 = '';
            address.City = '';
            address.Province = '';
            address.PostalCode = '';
            if (address.Country !== null) {
                address.Country.CountryCode = '';
                address.Country.CountryName = '';
                address.Country.CountryId = -1;
            }
        };

        $scope.updateShippingAddress = function (data, isInit) {
            //spinnerFactory.show();
            //disableScrollOnSpinnerShow();
            $scope.addressData.shippingData = data;
            addressDataHelper.updateShippingData(data);

            $scope.getShippingRates(data);

            addressDataHelper.updateBillingData(data);
            shippingService.updateShippingAddress(data.country.countryId, data.postalCode, false, data.province, data.city, data.address1, data.address2, data.address3).$promise.then(
                function (value) {
                    cartDataStorageService.loadCartData();
                    $scope.updateShippingAddressSuccess = true;
                    if (!value.Success) {
                        console.log(value.Message);
                    }
                    $scope.checkoutState.addressSec = false;
                    $scope.checkoutState.receiverSec = isInit ? !$scope.cartData.signedIn : true;
                    //spinnerFactory.hide();
                    //enableScrollOnSpinnerHide();
                }, function () {
                    $scope.updateShippingAddressSuccess = false;
                    console.log('updateShippingAddress error occur');
                    //spinnerFactory.hide();
                    //enableScrollOnSpinnerHide();
                });
        };

        $scope.editBillingInfo = function () {
            $scope.checkoutState.billingSec = false;
            $scope.checkoutState.paymentSec = true;
            $scope.checkoutState.createAccountSec = false;
            $scope.checkoutState.accountPasswordSec = false;
            $scope.checkoutState.retryEmailSec = false;

            if ($scope.checkoutState.newCreditCardError === false) {
                $scope.checkoutState.sumitCartErrorSec = false;
            } else {
                $scope.checkoutState.sumitCartErrorSec = true;
            }

            if (checkoutSvc.hpciEnabled()) {
                hpciStatus = "";
                $scope.checkoutState.hpciProcessed = false;
            }
            if ($scope.cartData.signedIn) {
                $scope.preSelectedCreditCard = false;

                if ($scope.checkoutState.newCreditCardError === false) {
                    $scope.checkoutState.creditCardData.cardNumber = "";
                    $scope.checkoutState.creditCardData.expireMonth = "";
                    $scope.checkoutState.creditCardData.expireYear = "";
                    $scope.checkoutState.creditCardData.name = "";
                    $scope.checkoutState.creditCardData.cardType = "";
                    $scope.checkoutState.creditCardData.cardTypeId = 0;
                    $scope.checkoutState.creditCardData.cardValidation = "";
                    setTimeout(function() {
                            $("#cardChkBox").parent().parent().click();
                        },
                        20);
                }

            }
        };

        $scope.goToCreditCardList = function () {
            if ($scope.cartData.signedIn) {
                if ($scope.cartData.ExistingCreditCards != null && $scope.cartData.ExistingCreditCards.length > 0) {
                    $scope.checkoutState.paymentType = 3;
                    $scope.preSelectedCreditCard = true;
                    $scope.checkoutState.hasExistingCards = true;
                    $scope.paymentMethods.showExistingCreditCardChecked = true;
                    setTimeout(function () {
                        $("#preCardChkBox").parent().parent().click();
                    }, 20);
                }
            }
        };

        $scope.checkExpiredYearMonth = function () {
            if ($scope.checkoutState.creditCardData.expireMonth === undefined) return false;
            if ($scope.checkoutState.creditCardData.expireYear === undefined) return true;
            if ($scope.checkoutState.creditCardData.expireYear <= 0) return false;
            if ($scope.checkoutState.creditCardData.expireMonth <= 0) return false;
            var today = new Date();
            var expired = new Date($scope.checkoutState.creditCardData.expireYear, $scope.checkoutState.creditCardData.expireMonth, today.getDate());
            if (expired.getTime() < today.getTime())
                return false;
            return true;
        }
        //Region payment

        $scope.onPhoneNumberChanged = function () {
            $scope.checkoutState.isPhoneNoValid = $scope.checkoutState.OrderPhoneNumber === undefined || $scope.checkoutState.OrderPhoneNumber.length <= 0 ? false : true;
            $scope.checkoutState.isPhoneNoDirty = !$scope.isPhoneNoValid;
            //if ($scope.checkoutState.isPhoneNoValid) {
            //    $scope.checkoutState.isPhoneNoFormatValid = $scope.phoneNumberPattern.test($scope.checkoutState.OrderPhoneNumber);
            //}
        };
        $scope.checkoutState.isPhoneNoFormatValid = function () {
            if (!$scope.checkoutState.OrderPhoneNumber) return false;
            return /^\+?\d{3}-?\d{3}-?\d{4}$/.test($scope.checkoutState.OrderPhoneNumber);
        }
        //$scope.phoneNumberPattern = (function () {
        //    var regexp = /^\+?\d{3}-\d{3}-\d{4}$/;
        //    return {
        //        test: function (value) {
        //            return regexp.test(value);
        //        }
        //    };
        //})();

        $scope.onSubmitCart = function () {
            $scope.checkoutState.sumitCartErrorSec = false;
            if (!$scope.shippingRate) {
                $scope.checkoutState.sumitCartErrorSec = true;
                $scope.checkoutState.errorMessage = siteRes.SelectShippingRate;
                return false;
            }

            if ($scope.cartData.signedIn && !$scope.paymentMethods.showExistingCreditCardChecked && !$scope.paymentMethods.showPayPalChecked && !$scope.paymentMethods.showCreditCardChecked) {
                $scope.checkoutState.sumitCartErrorSec = true;
                $scope.checkoutState.errorMessage = "Please select payment option";
                return false;
            }
            else if ($scope.cartData.signedIn && ($scope.paymentMethods.showExistingCreditCardChecked || $scope.paymentMethods.showExistingCreditCardChecked)) {
                $scope.checkoutState.sumitCartErrorSec = false;
            }

            if ($scope.cartData.signedIn && $scope.checkoutState.hasExistingCards && $scope.checkoutState.showCscForExistingCard && $scope.paymentMethods.showExistingCreditCardChecked) {
                if ($scope.checkoutState.existingCreditCardData == null) {
                    $scope.checkoutState.invalidCardForExistingCard = true;
                    $scope.checkoutState.invalidCscForExistingCard = true;
                    return false;
                }
                if ($scope.checkoutState.existingCreditCardData.CreditCardId == '' || $scope.checkoutState.existingCreditCardData.CreditCardId == undefined) {
                    $scope.checkoutState.invalidCardForExistingCard = true;
                    return false;
                }
                if ($scope.checkoutState.existingCreditCardData.Csc == '' || $scope.checkoutState.existingCreditCardData.Csc == undefined) {
                    $scope.checkoutState.invalidCscForExistingCard = true;
                    return false;
                }
            }
            //if ($scope.cartData.signedIn && $scope.paymentMethods.showExistingCreditCardChecked && ($scope.checkoutState.OrderPhoneNumber === undefined || $scope.checkoutState.OrderPhoneNumber.length <= 0)) {
            //    $scope.checkoutState.sumitCartErrorSec = true;
            //    $scope.checkoutState.errorMessage = "Please enter phone number";
            //    $scope.checkoutState.isPhoneNoValid = false;
            //    $scope.checkoutState.isPhoneNoDirty = !$scope.checkoutState.isPhoneNoValid;
            //    $scope.payementForm.OrderPhoneNumber.$pristine = false;
            //    $scope.payementForm.OrderPhoneNumber.$setViewValue($scope.checkoutState.OrderPhoneNumber === "" ? undefined : "");
            //    return false;
            //}

            //if (!$scope.checkoutState.isPhoneNoFormatValid()) {
            if ($scope.checkoutState.OrderPhoneNumber == "") {
                $scope.checkoutState.sumitCartErrorSec = true;
                //$scope.checkoutState.errorMessage = "Please enter phone number";
                $scope.checkoutState.errorPhoneMessage = "Please enter phone number";
                //$scope.checkoutState.isPhoneNoFormatValid = false;
                $scope.payementForm.OrderPhoneNumber.$pristine = false;
                return false;
            }

            if (($scope.paymentMethods.showCreditCardChecked === true && $scope.preSelectedCreditCard === false)) {
                $scope.checkoutState.creditCardsuccess = true;
                if ($scope.checkoutState.creditCardData.cardTypeId === 0 || $scope.checkoutState.creditCardData.cardTypeId === undefined ||
                    $scope.checkoutState.creditCardData.expireMonth === "" || $scope.checkoutState.creditCardData.expireMonth === 0 ||
                    $scope.checkoutState.creditCardData.expireMonth === undefined ||
                    $scope.checkoutState.creditCardData.expireYear === "" || $scope.checkoutState.creditCardData.expireYear === 0 ||
                    $scope.checkoutState.creditCardData.expireYear === undefined ||
                    $scope.checkoutState.creditCardData.name === "" || $scope.checkoutState.creditCardData.name === undefined ||
                    $scope.checkoutState.hpciCCValidValue !== "Y") {

                    $scope.checkoutState.sumitCartErrorSec = true;
                    $scope.checkoutState.errorMessage = "Please enter credit card details";

                    if ($scope.checkoutState.creditCardData.cardTypeId === 0 || $scope.checkoutState.creditCardData.cardTypeId === undefined) {
                        $scope.payementForm.cardType.$pristine = false;
                        $scope.payementForm.cardType.$setViewValue($scope.payementForm.cardType.$viewValue);
                    }
                    if ($scope.checkoutState.creditCardData.name === "" || $scope.checkoutState.creditCardData.name === undefined) {
                        $scope.payementForm.cardholdername.$pristine = false;
                        $scope.payementForm.cardholdername.$setViewValue($scope.payementForm.cardholdername.$viewValue);
                    }
                    if ($scope.checkoutState.hpciCCValidValue !== "Y") {
                        sendHPCIChangeStyleMsg("ccNum", "border-color", "#d73a47");
                        sendHPCIValidationMsg_NUM("block");

                    }
                    if ($scope.checkoutState.hpciCVVValidValue !== "Y") {
                        sendHPCIChangeStyleMsg("ccCVV", "border-color", "#d73a47");
                        sendHPCIValidationMsg_CVV("block");

                    }
                    if ($scope.checkoutState.creditCardData.expireYear === "" || $scope.checkoutState.creditCardData.expireYear === undefined) {

                        $scope.payementForm.year.$pristine = false;
                        $scope.payementForm.year.$setViewValue($scope.checkoutState.creditCardData.expireYear === "" ? undefined : "");
                    }
                    if ($scope.checkoutState.creditCardData.expireMonth === "" || $scope.checkoutState.creditCardData.expireMonth === undefined) {
                        $scope.payementForm.month.$pristine = false;
                        $scope.payementForm.month.$setViewValue($scope.checkoutState.creditCardData.expireMonth === "" ? undefined : "");
                    }
                    if ($scope.checkoutState.OrderPhoneNumber === undefined || $scope.checkoutState.OrderPhoneNumber.length <= 0) {
                        $scope.checkoutState.isPhoneNoValid = false;
                        $scope.checkoutState.isPhoneNoDirty = !$scope.checkoutState.isPhoneNoValid;
                        $scope.payementForm.OrderPhoneNumber.$pristine = false;
                        $scope.payementForm.OrderPhoneNumber.$setViewValue($scope.checkoutState.OrderPhoneNumber === "" ? undefined : "");
                    }
                    //else if ($scope.checkoutState.OrderPhoneNumber === undefined || $scope.checkoutState.OrderPhoneNumber.length <= 0 || !$scope.checkoutState.isPhoneNoFormatValid()) {
                    //    //$scope.checkoutState.isPhoneNoFormatValid = false;
                    //    $scope.payementForm.OrderPhoneNumber.$pristine = false;
                    //}
                    return false;
                }
            }


            if ($scope.paymentMethods.showCreditCardChecked === true && $scope.preSelectedCreditCard === false && !$scope.checkExpiredYearMonth()) {
                $scope.checkoutState.sumitCartErrorSec = true;
                $scope.checkoutState.errorMessage = "Please enter valid expiry";
                return false;
            }

            //if (!$scope.cartData.signedIn) {
            //    spinnerFactory.show();
            //    disableScrollOnSpinnerShow();
            //    var storeDataTimeout;
            //    $.ajax({
            //        url: 'https://' + location.host + rootRel + 'Stores/ListAllStores?countryCode=' + $scope.addressData.shippingData.country.countryCode,
            //        success: function (data) {
            //            if (data) {
            //                storeDataTimeout = $timeout(function () {
            //                    $scope.stores = data;
            //                    spinnerFactory.hide();
            //                    enableScrollOnSpinnerHide();
            //                }, 250);
            //            }
            //        }
            //    });
            //}
            //spinnerFactory.show("Please wait...");
            //disableScrollOnSpinnerShow();

            //console.log($scope.checkoutState.OrderPhoneNumber);
            //checkoutSubmitCartSvc.addPaymentPhoneNumber($scope.checkoutState.OrderPhoneNumber);
            //setTimeout(function () {
            //    checkoutSubmitCartSvc.submitOrder($scope.checkoutState, $scope.cartData);
            //}, 1000);

            checkoutSubmitCartSvc.addPaymentPhoneNumber($scope.checkoutState.OrderPhoneNumber).$promise.then(
                function () {
                    checkoutSubmitCartSvc.submitOrder($scope.checkoutState, $scope.cartData);
                });

            if (!$scope.checkoutState.sumitCartErrorSec) {
                spinnerFactory.hide();
                enableScrollOnSpinnerHide();
            }

            return true;
        };

        //try to submit a card on hpci processed, this method is called externally, from hpci handler
        $scope.onHpciProcessed = function () {
            //bvc hpci check
            console.log($scope.checkoutState.newCreditCardError + "|" + $scope.checkoutState.paymentType + "|" + $scope.checkoutState.creditCardData.cardNumber);

            if ($scope.checkoutState.hpciProcessed === true) {
                checkoutSubmitCartSvc.processCreditCardPayment($scope.checkoutState, $scope.cartData);
            }
        };

        //EndRegion payment

        //Region 3ds
        $scope.verify3Ds = function () {
            return checkoutSubmitCartSvc.verify3Ds($scope.checkoutState);
        };
        //EndRegion 3ds

        $scope.phoneEmailSecDone = function () {
            $scope.$broadcast('show-errors-check-validity', 'phoneEmailForm');
            $scope.isPhoneFormSubmitted = true;
            if ($scope.phoneEmailForm.$invalid) {
                return;
            }
            // Note: ReceiverName (name field in the following object) is deprecated 
            // since we have it in the AddressInfo of the shipping object
            var receiverMiscInfo = {
                name: '',
                isGift: $scope.cartData.isGift,
                giftNote: $scope.cartData.giftNote
            };
            checkoutSvc.addReceiverMiscInfoToOrderForm(receiverMiscInfo).$promise.then(
                function () {
                    $scope.checkoutState.phoneEmailSec = false;
                    $scope.checkoutState.contactSec = true;
                    $('input[name=receiverNameFirst]').val($scope.firstName);
                    $('input[name=receiverNameLast]').val($scope.lastName);
                    setTimeout(function () {
                        $('input[name=receiverNameFirst]').change();
                        $('input[name=receiverNameLast]').change();
                    }, 100);
                    jcf.setOptions('Select', {
                        wrapNative: false,
                        wrapNativeOnMobile: false,
                        fakeDropInBody: false
                    });
                    jcf.replaceAll();
                },
                function () {
                    console.log('addReceiverMiscInfoToOrderForm fail');
                });
        };

        $scope.togglePassword = function () {

            if ($scope.passwordType === 'password') {
                $scope.passwordType = 'text';
            } else {
                $scope.passwordType = 'password';
            }
        };

        $scope.showAccountPasswordSection = function () {
            $scope.checkoutState.createAccountSec = false;
            $scope.checkoutState.accountPasswordSec = true;
        };


        $scope.toggleShippingAddress = function (selectedAddress) {
            $scope.updateShippingAddress(selectedAddress, false);
            $scope.checkoutState.shippingMethodSec = true;
            $scope.checkoutState.shipUsingSec = false;
        }

        $scope.submitGuestOrder = function (generateUserId) {
            var customerData = {};
            //when userId provided means user click on register later button, will create account use default value, don't need validation those three fields
            if (generateUserId) {
                customerData.userId = checkoutHelperService.guid();
            } else {
                $scope.$broadcast('show-errors-check-validity', 'accountPasswordForm');
                if ($scope.accountPasswordForm.$invalid) {
                    return;
                }
            }
            //SK: why????
            if ($scope.password.trim() === '') {
                $scope.password = Math.random().toString(36).slice(-8);
            }
            if ($scope.firstName.trim() === '') {
                $scope.firstName = 'Guest';
            }
            if ($scope.lastName.trim() === '') {
                $scope.lastName = 'Guest';
            }
            if ($scope.cartData.phone === undefined || $scope.cartData.phone.trim() === '') {
                $scope.cartData.phone = $scope.checkoutState.OrderPhoneNumber;
            }
            customerData.email = $scope.cartData.email;
            customerData.phone = $scope.cartData.phone;
            customerData.firstName = $scope.firstName;
            customerData.lastName = $scope.lastName;
            customerData.password = $scope.password;
            customerData.EmailOptIn = $scope.cartData.signupNewsletter;
            customerData.address = addressDataHelper.getBillingData();

            

            disableScrollOnSpinnerShow();
            checkoutSubmitCartSvc.submitGuestOrder(customerData, $scope.checkoutState, $scope.cartData);
            if ($scope.checkoutState.retryEmailSec) {
                enableScrollOnSpinnerHide();
            }
        };

        $scope.paymentMethods = {
            showCreditCardChecked: $scope.checkoutState.paymentType === 1,
            showPayPalChecked: $scope.checkoutState.paymentType === 2,
            showExistingCreditCardChecked: $scope.checkoutState.paymentType === 3
        };

        $scope.paymentSectionDone = function () {
            $scope.checkoutState.billingSec = true;
            $scope.checkoutState.paymentSec = false;
            $scope.checkoutState.createAccountSec = true;
        };

        $scope.togglePaymentMethod = function (paymentType) {
            $scope.checkoutState.paymentType = 0;

            if ($scope.paymentMethods.showCreditCardChecked === true || $scope.paymentMethods.showPayPalChecked === true || $scope.paymentMethods.showExistingCreditCardChecked === true) {
                switch (paymentType) {
                    case 1://new card
                        $scope.paymentMethods.showPayPalChecked = false;
                        $scope.paymentMethods.showExistingCreditCardChecked = false;
                        break;
                    case 2://paypal
                        $scope.paymentMethods.showCreditCardChecked = false;
                        $scope.paymentMethods.showExistingCreditCardChecked = false;
                        break;
                    case 3://existing card
                        $scope.paymentMethods.showPayPalChecked = false;
                        $scope.paymentMethods.showCreditCardChecked = false;
                        break;
                    default:
                        break;
                }
            }

            if ($scope.paymentMethods.showCreditCardChecked === true) {
                $scope.checkoutState.paymentType = 1;
            }
            else if ($scope.paymentMethods.showPayPalChecked === true) {
                $scope.checkoutState.paymentType = 2;
            }
            else if ($scope.paymentMethods.showExistingCreditCardChecked === true) {
                $scope.checkoutState.paymentType = 3;
            } else {
                $scope.checkoutState.paymentType = 0;
            }

            if ($scope.paymentMethods.showCreditCardChecked === false && $scope.paymentMethods.showPayPalChecked === false && $scope.paymentMethods.showExistingCreditCardChecked === false) {
                $scope.checkoutState.paymentType = 0;
            }
            //$scope.checkoutState.paymentSec = true;
        };

        $scope.selectCheckBox = function (paymentType) {
            switch (paymentType) {
                case 1://new card
                    $scope.paymentMethods.showCreditCardChecked = true;

                    $timeout(function () {
                        $("#cardChkBox").prop('checked', true);
                        $("#paypalChkBox").prop("checked", false);
                        jcf.getInstance($('#cardChkBox')).refresh();
                        jcf.getInstance($('#paypalChkBox')).refresh();
                        $scope.togglePaymentMethod(paymentType);
                    }, 0);
                    break;
                case 2://paypal
                    $scope.paymentMethods.showPayPalChecked = true;
                    $timeout(function () {
                        $("#paypalChkBox").prop('checked', true);
                        $("#cardChkBox").prop("checked", false);
                        $("#preCardChkBox").prop("checked", false);

                        jcf.getInstance($('#cardChkBox')).refresh();
                        jcf.getInstance($('#paypalChkBox')).refresh();
                        jcf.getInstance($('#preCardChkBox')).refresh();
                        $scope.togglePaymentMethod(paymentType);
                    }, 0);
                    break;
                case 3://existing card
                    $scope.paymentMethods.showExistingCreditCardChecked = true;
                    $timeout(function () {
                        $("#preCardChkBox").prop('checked', true);
                        $("#paypalChkBox").prop("checked", false);

                        jcf.getInstance($('#preCardChkBox')).refresh();
                        jcf.getInstance($('#paypalChkBox')).refresh();
                        $scope.togglePaymentMethod(paymentType);
                    }, 0);
                    break;
                default:
                    break;
            }
        }


        $scope.checkBoxClick = function (paymentType) {
            switch (paymentType) {
                case 1://new card
                    $timeout(function () {
                        if ($("#cardChkBox").prop('checked') == false) {
                            $scope.paymentMethods.showCreditCardChecked = false;
                            $("#cardChkBox").prop('checked', false);
                            $("#paypalChkBox").prop("checked", false);
                        }
                        else {
                            $scope.paymentMethods.showCreditCardChecked = true;
                            $("#cardChkBox").prop('checked', true);
                            $("#paypalChkBox").prop("checked", false);
                            $scope.togglePaymentMethod(paymentType);
                        }

                        jcf.getInstance($('#cardChkBox')).refresh();
                        jcf.getInstance($('#paypalChkBox')).refresh();

                    }, 0);
                    break;
                case 2://paypal
                    $timeout(function () {
                        if ($("#paypalChkBox").prop('checked') == false) {
                            $scope.paymentMethods.showPayPalChecked = false;
                            $("#paypalChkBox").prop('checked', false);
                            $("#cardChkBox").prop("checked", false);
                            $("#preCardChkBox").prop("checked", false);
                        }
                        else {
                            $scope.paymentMethods.showPayPalChecked = true;
                            $("#paypalChkBox").prop('checked', true);
                            $("#cardChkBox").prop("checked", false);
                            $("#preCardChkBox").prop("checked", false);
                            $scope.togglePaymentMethod(paymentType);
                        }
                        jcf.getInstance($('#cardChkBox')).refresh();
                        jcf.getInstance($('#paypalChkBox')).refresh();
                        jcf.getInstance($('#preCardChkBox')).refresh();

                    }, 0);
                    break;
                case 3://existing card
                    $timeout(function () {
                        if ($("#preCardChkBox").prop('checked') == false) {
                            $scope.paymentMethods.showExistingCreditCardChecked = false;
                            $("#preCardChkBox").prop('checked', false);
                            $("#paypalChkBox").prop("checked", false);
                        }
                        else {
                            $scope.paymentMethods.showExistingCreditCardChecked = true;
                            $("#preCardChkBox").prop('checked', true);
                            $("#paypalChkBox").prop("checked", false);
                            $scope.togglePaymentMethod(paymentType);
                        }
                        jcf.getInstance($('#preCardChkBox')).refresh();
                        jcf.getInstance($('#paypalChkBox')).refresh();

                    }, 0);
                    break;
                default:
                    break;
            }
        }


        $scope.$watch("checkoutState.sumitCartErrorSec", function handleEmailErrorChange(newValue, oldValue) {
            if (newValue === true) {
                spinnerFactory.hide();
                enableScrollOnSpinnerHide();
            }
        }
        );
        $scope.receiverSecDone = function () {
           // spinnerFactory.show();
            $scope.$broadcast('show-errors-check-validity', 'receiverForm');
            if ($scope.receiverForm.$invalid) {
                return;
            } else {
                var data = $scope.addressData.shippingData;
                shippingService.updateShippingAddress(data.country.countryId, data.postalCode, false, data.province, data.city, data.address1, data.address2, data.address3, data.FirstName, data.LastName).$promise.then(
                    function () {
                        $scope.checkoutState.receiverSec = false;
                        $scope.checkoutState.deliverToSec = true;
                        $scope.checkoutState.shippingMethodSec = true;
                       // spinnerFactory.hide();
                    });
            }
        };

        $scope.editShippingInfo = function () {
            jcf.setOptions('Select', {
                wrapNative: false,
                wrapNativeOnMobile: false,
                fakeDropInBody: false
            });
            jcf.replaceAll();
            $scope.addressBtn = "Update";
            $scope.checkoutState.addressSec = true;
            $scope.checkoutState.receiverSec = false;
            $scope.checkoutState.deliverToSec = false;
            $scope.checkoutState.shippingMethodSec = false;
            $scope.checkoutState.shipUsingSec = false;
            $scope.checkoutState.phoneEmailSec = false;

        };

        $scope.editContactInfo = function () {
            $scope.checkoutState.contactSec = false;
            $scope.contactInfoBtn = "Update";
        };

        $scope.shippingMethodSecDone = function () {
            $scope.shippingMethodBtn = "Update";
            $scope.checkoutState.shippingMethodSec = false;
            $scope.checkoutState.shipUsingSec = true;
            //$scope.checkoutState.phoneEmailSec = true;
            if ($scope.cartData.signedIn) {
                if ($scope.cartData.ExistingCreditCards != null && $scope.cartData.ExistingCreditCards.length > 0) {
                    //$scope.paymentMethods.showExistingCreditCardChecked = true;
                    $timeout(function () {
                        //$("#preCardChkBox").prop('checked', true);
                        //jcf.getInstance($('#preCardChkBox')).refresh();
                        $scope.togglePaymentMethod(3);
                        $scope.setBillingAddressDefault();
                    }, 0);
                }
                else {
                    //$scope.paymentMethods.showCreditCardChecked = true;
                    $timeout(function () {
                        //$("#cardChkBox").prop('checked', true);
                        jcf.getInstance($('#cardChkBox')).refresh();
                        $scope.togglePaymentMethod(1);
                        $scope.setBillingAddressDefault();
                    }, 0);
                }
            }
            $scope.checkoutState.currentStage = 3;
            jQuery('.accordion').slideAccordion({
                opener: '.accordion-opener',
                slider: '.accordion-slide',
                animSpeed: 400
            });
        };

        $scope.setBillingAddressDefault = function () {
            addressDataHelper.updateSameAsShippingAddress(false);
            var data = $scope.cartData.addressInfo.BillingAddress;
            addressDataHelper.updateBillingData(data);
            checkoutSvc.addAddressDataToOrderForm(addressDataHelper.getShippingData(), addressDataHelper.getBillingData(), addressDataHelper.getSameAsShippingAddress()).$promise.then(
               function () {
                   if (!addressDataHelper.getSameAsShippingAddress()) {
                       cartDataStorageService.loadCartData();
                   }
               }, function (error) {
                   console.log(error);
               });
        };

        $scope.editShippingUsing = function () {
            $scope.checkoutState.shippingMethodSec = true;
            $scope.checkoutState.shipUsingSec = false;
        };

        $scope.getShippingRates = function (shippingData) {

            var shippingCountry = shippingData.country.countryId;
            var shippingProvince = shippingData.province || '';
            var shippingPostalCode = shippingData.postalCode;
            shippingService.getShippingRates(shippingCountry, shippingProvince, shippingPostalCode, false).$promise.then(function (value) {
                var rates = [];
                var giftCardShippingMethodName = globalConstants.digitalGiftCardShippingMethod;
                angular.forEach(value.shippingRates, function (rate) {
                    if (rate.Name.indexOf(giftCardShippingMethodName) > -1) {
                        rates.push(rate);
                    }
                });

                $scope.shippingRates = rates;


                // default is nothing selected
                if ($scope.shippingRate) {
                    angular.forEach($scope.shippingRates, function (rate) {
                        if (rate.Id == $scope.shippingRate) {
                            $scope.shippingMethod = rate.Name;
                            $scope.shippingAmount = rate.Rate;
                            $scope.leadTimeMessage = rate.LeadTimeMessage;
                            $scope.checkoutState.shippingSelected = true;
                        }
                    });
                    $scope.updateShippingRate({ Name: $scope.shippingMethod, Rate: $scope.shippingAmount, Id: $scope.shippingRate, LeadTimeMessage: $scope.leadTimeMessage }, true);
                }
            });
        };

        $scope.updateShippingRate = function (rate, initLoad) {
            //update cart shipper id & reload cart data after rate change
            shippingService.updateShippingRate($scope.shippingRate).$promise.then(
                function () {
                    cartDataStorageService.loadCartData();
                    //broadcast shippingRateChanged event, then summary controller can do something when shipping rate change(current beheavior is fade in: could change the behavior by modify fade-in class in common.less)
                    //and the ship via will display rate base on this
                    if (!initLoad) {
                        $scope.shippingMethod = rate.Name;
                        $scope.shippingAmount = rate.Rate;
                        $scope.leadTimeMessage = rate.LeadTimeMessage;
                        $scope.checkoutState.shippingSelected = true;
                        $scope.checkoutState.shippingSelected = true;
                        $scope.checkoutState.shippingMethodSec = true;
                        appObserver.broadcast('shippingRateChanged', rate);
                        $scope.shippingMethodSecDone();
                    }
                }
            );
        };

        $scope.$watch("checkoutState.retryEmailSec", function handleretryEmailSecChange(newValue, oldValue) {
            if (newValue === true) {
                enableScrollOnSpinnerHide();
            }
        }
       );

        $scope.$watch("shippingRates", function handleshippingRatesChange(newValue, oldValue) {
            if (newValue != undefined && newValue.length > 0) {
                $scope.shippingRate = newValue[0].Id;
                $scope.updateShippingRate(newValue[0]);

                $scope.shippingMethodSecDone();
            }
        }
          );

        $scope.showShippingAddressModal = function () {
            $modal.open({
                templateUrl: appUrlBuilder.buildTemplateUrl('newShippingAddressTemplateUrl'),
                backdrop: 'static',
                controller: 'mmtcheckoutInstanceCtrl',
                windowClass: 'modal-vertical-centered',
                scope: $scope
            });

        };

        $scope.updateSelectedCreditCard = function (card) {

            if (card === null || card === undefined) {
                $scope.checkoutState.invalidCardForExistingCard = true;
                $scope.checkoutState.invalidCscForExistingCard = true;
            } else {
                $scope.checkoutState.invalidCardForExistingCard = false;
                $scope.checkoutState.invalidCscForExistingCard = false;
                $scope.checkoutState.existingCreditCardData.DisplayText = card.DisplayText;
                $scope.checkoutState.existingCreditCardData.CreditCardId = card.CreditCardId;
            };
        }

    }
]);

//function updateScoppingCartItemsCount(cartData) {
//    var value = cartData.totalItemsCount;
//    $('#shoppingCartLargeBadge').text(value);
//}

//Prevent Scrolling of page when Spinner is visible
function disableScrollOnSpinnerShow() {
    $('body').css('overflow', 'hidden');
    $('body').mousedown(function (e) { if (e.button === 1) return false });
}

function enableScrollOnSpinnerHide() {
    $('body').css('overflow', 'auto');
    $('body').mousedown(function (e) { if (e.button === 1) return true });
};
'use strict';
/**
 * Responsible for all checkout specific logic
 */
angular.module('checkout').controller('mmtRISCheckoutCtrl', ['$scope', '$window', 'CheckoutSvc', 'CartDataStorageService', 'ShippingService', 'AppObserver', 'AddressDataHelper', 'siteConfiguration', 'siteRes', 'CheckoutDataStorageService', 'mmtRISCheckoutSubmitCartSvc', 'CheckoutHelperService', 'CheckoutCreditCardValidationService', 'anchorHelper', 'spinnerFactory', '$timeout', '$modal', 'appUrlBuilder', 'CartService',
    function ($scope, $window, checkoutSvc, cartDataStorageService, shippingService, appObserver, addressDataHelper, siteConfiguration, siteRes, checkoutDataStorageService, checkoutSubmitCartSvc, checkoutHelperService, checkoutCreditCardValidationService, anchorHelper, spinnerFactory, $timeout, $modal, appUrlBuilder, cartService) {
        $scope.cartData = cartDataStorageService.cartData;
        $scope.checkoutState = checkoutDataStorageService.checkoutState;
        $scope.firstName = '';
        $scope.lastName = '';
        $scope.phoneNumber1 = '';
        $scope.phoneNumber2 = '';
        $scope.phoneNumber3 = '';
        $scope.emailRegex = siteConfiguration.emailRegex;
        $scope.itemsStoreInventoryData = '';
        $scope.selectedRISStore = '';
        $scope.checkoutState.risCurrentStage = 1;
        $scope.isRISStoreSelected = false;
        $scope.isContactCompleted = false;
        $scope.currentLat = '';
        $scope.currentLng = '';

        var options = {
            enableHighAccuracy: false,
            timeout: 10000,
            maximumAge: 0
        };

        //load google captcha 
        $scope.recaptchaError = false;
        if (enableRecaptcha) {
            setTimeout(function () {
                onloadCallback();
            }, 1000);
        }

        //enter key press for search store
        setTimeout(function () {
            $('#risStoreInvModal #Address').keypress(function (e) {
                if (e.which == 13) {
                    $scope.getUserLocationStoreInv();
                    e.preventDefault();
                }
            });
        }, 500);


        $scope.preloadData = function () {
            //preload cart data
            cartDataStorageService.loadCartData().then(function () {
                //bug fix for veritcal scroll
                setTimeout(function () {
                    if($scope.cartData.items.length > 3)
                    {
                        $(".icon-slider-arrow-bottom").removeClass("disabled");
                    }
                }, 1000);

                //bvc reload store info after login
                if (risSelectedStoreId > -1) {
                    var coords = $.cookie("RISStoresCoordinates").split("|");
                    $scope.LoadStoreInv(coords[0], coords[1], risSelectedStoreId);
                    //console.log("risSelectedStoreId > " + risSelectedStoreId + " | " + coords);
                } else {
                    //get user current location
                    $scope.getCurrentPosition();
                }

                $('#risStoreInvModal #searchLongitude').change(function () {
                    var lat = $('#risStoreInvModal #searchLatitude').val();
                    var lng = $("#risStoreInvModal #searchLongitude").val();
                    $scope.LoadStoreInv(lat, lng, -1);
                });

                if ($scope.cartData.signedIn) {
                    var customerPhoneNumber = $scope.cartData.customer.Phone;
                    $scope.checkoutState.OrderPhoneNumber = customerPhoneNumber;
                    $scope.cartData.email = $scope.cartData.customer.Email;
                    $scope.firstName = $scope.cartData.customer.FirstName;
                    $scope.lastName = $scope.cartData.customer.LastName;

                    var phoneNums = customerPhoneNumber.replace(/\D/g, '');
                    if (phoneNums.length === 10) {
                        $scope.phoneNumber1 = phoneNums.substring(0, 3);
                        $scope.phoneNumber2 = phoneNums.substring(3, 6);
                        $scope.phoneNumber3 = phoneNums.substring(6, 10);
                    }
                }
            });
        };

        $scope.removeFromCartRIS = function (itemId) {
            cartService.removeFromCartRIS(itemId).then(function () {
                //resfresh display
                $('#shoppingCartLargeBadge').text($scope.cartData.totalItemsCount);
                $scope.LoadStoreInv($scope.currentLat, $scope.currentLng, -1);
            });
        };

        $scope.LoadStoreInv = function (lat, lng, storeId) {
            $scope.currentLat = lat;
            $scope.currentLng = lng;
            //console.log("Total items: " + $scope.cartData.totalItemsCount + " | Order total: " + $scope.cartData.total);
            checkoutSvc.loadItemsStoreInventoryData(lat, lng, "").$promise.then(function (value) {
                $scope.itemsStoreInventoryData = value;
                if (storeId > -1) {
                    angular.forEach($scope.itemsStoreInventoryData, function (store) {
                         if (store.StoreId == storeId) {
                            $scope.selectRISStore(store);
                            return;
                        }
                    });
                }
            });

        };

        $scope.getUserLocationStoreInv = function () {
            var address = $("#risStoreInvModal #Address").val().trim();
            if (address == "") {
                return;
            }
            var country = 'Canada';
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({ 'address': address + "," + country }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    var lat = results[0].geometry.location.lat();
                    var lng = results[0].geometry.location.lng();
                    $scope.LoadStoreInv(lat, lng, -1);
                    //saved coordinates
                    var coords = lat + "|" + lng;
                    $.cookie("RISStoresCoordinates", coords, { expires: 1, path: "/" });
                } else {
                    $("#storeInvResults").html(storeInvErrorMsg);
                }
            });
        };

        $scope.getCurrentPosition = function () {
            $("#risStoreInvModal #Address").val("");
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    function (pos) {
                        var crd = pos.coords;
                        $("#risStoreInvModal #searchLatitude").val(crd.latitude);
                        $("#risStoreInvModal #searchLongitude").val(crd.longitude).trigger('change');
                        //saved coordinates
                        var coords = crd.latitude + "|" + crd.longitude;
                        $.cookie("RISStoresCoordinates", coords, { expires: 1, path: "/" });
                    },
                    function () {
                        console.log("Geolocatoion service is not available");
                    },
                    options);
            }
            else {
                console.log("Geolocatoion service is not available");
            }
        };

        $scope.selectRISStore = function (selectedStore) {
            if (selectedStore.InventoryStringId == '2') {
                ShowConfirmModal("Some items not available", "Please delete the items that are not available before continuing.");
            }
            else {

                //BVC add RIS store to order
                var selectedStoreId = selectedStore.StoreId;
                checkoutSvc.selectStoreRIS(selectedStoreId).$promise.then(function (value) {
                    //console.log("selectStoreRIS > Added storeId to RIS order. StoreId: " + selectedStoreId);
                    $scope.selectedRISStore = selectedStore;
                    $scope.isRISStoreSelected = true;
                    $scope.checkoutState.risCurrentStage = 2;

                    //updating shipping address
                    $scope.updateShippingAddress(selectedStore.PostalCode);

                    //scroll to top
                    $("html, body").animate({ scrollTop: 0 }, 500);

                });
            }
        };

        $scope.updateShippingAddress = function (shipPostalCode) {
            var countryId = 1; //canada only
            shippingService.updateShippingAddress(countryId, shipPostalCode, true, '', '', '', '', '').$promise.then(function (value) {
                if (value.Success) {
                    cartDataStorageService.sync(value, true);
                    cartDataStorageService.loadCartData();
                    //console.log("updateShippingAddress successful. postal code: " + shipPostalCode);
                }
            }, function () {
            });
        };

        $scope.editSelectAStoreInfo = function () {
            $scope.checkoutState.risCurrentStage = 1;
            $scope.isRISStoreSelected = false;
            $scope.checkoutState.sumitCartErrorSec = false;
        };

        $scope.editContactInfo = function () {
            $scope.checkoutState.risCurrentStage = 2;
            $scope.isContactCompleted = false;
            $scope.contactInfoBtn = "Update";
            $scope.checkoutState.sumitCartErrorSec = false;
        };

        $scope.phoneNumberKeyUp = function (phoneNumberImput) {
            var orderPhoneNumber = $scope.phoneNumber1 + $scope.phoneNumber2 + $scope.phoneNumber3;
            $scope.checkoutState.OrderPhoneNumber = orderPhoneNumber;
            $scope.onPhoneNumberChanged();

            switch (phoneNumberImput) {
                case 'phoneNumber1':
                    if ($scope.phoneNumber1 != undefined && $scope.phoneNumber1.length == 3) {
                        $('#phoneNumber2').focus();
                    }
                    break;
                case 'phoneNumber2':
                    if ($scope.phoneNumber2 != undefined && $scope.phoneNumber2.length == 3) {
                        $('#phoneNumber3').focus();
                    }
                    break;
                default:

            }
        }

        $scope.onPhoneNumberChanged = function () {
            $scope.checkoutState.isPhoneNoValid = $scope.checkoutState.OrderPhoneNumber === undefined || $scope.checkoutState.OrderPhoneNumber.length <= 0 ? false : true;
            $scope.checkoutState.isPhoneNoDirty = !$scope.isPhoneNoValid;
        };

        $scope.checkoutState.isPhoneNoFormatValid = function () {
            if (!$scope.checkoutState.OrderPhoneNumber) return false;
            return /^\+?\d{3}-?\d{3}-?\d{4}$/.test($scope.checkoutState.OrderPhoneNumber);
        }

        $scope.risPhoneEmailSecDone = function () {
            $scope.isPhoneFormSubmitted = true;
            $scope.contactEmailError = false;
            $scope.contactInfoError = false;

            $scope.$broadcast('show-errors-check-validity', 'risPhoneEmailForm');
            if ($scope.risPhoneEmailForm.$invalid) {
                if (!$scope.risPhoneEmailForm.email.$error.pattern) {
                    $scope.contactInfoError = true;
                } else {
                    $scope.contactEmailError = true;
                }
                return;
            }

            $scope.checkoutState.risCurrentStage = 3;
            $scope.isContactCompleted = true;
        };

        $scope.onSubmitCartRIS = function () {
            //console.log("enableRecaptcha > " + enableRecaptcha);
            if (enableRecaptcha) {
                var response = $("#g-recaptcha-response").val();
                //console.log("ReCaptcha > Response: " + response);
                checkoutSvc.validateCaptcha(response).$promise.then(
                    function (value) {
                        //console.log("ReCaptcha > Success: " + value.Success);
                        if (value.Success) {
                            if ($scope.cartData.signedIn) {
                                $scope.onSubmitCart();
                            } else {
                                $scope.submitGuestOrder();
                            }
                        } else {
                            $scope.recaptchaError = true;
                        }
                    });
            } else {
                //skip recaptcha - testing only
                if ($scope.cartData.signedIn) {
                    $scope.onSubmitCart();
                } else {
                    $scope.submitGuestOrder();
                }
            }
        }

        $scope.onSubmitCart = function () {
            $scope.checkoutState.sumitCartErrorSec = false;
            checkoutSubmitCartSvc.addRISPhoneNumber($scope.checkoutState.OrderPhoneNumber).$promise.then(
                function () {
                    checkoutSubmitCartSvc.submitOrder();
                });
        };


        $scope.submitGuestOrder = function () {
            console.log("RIS submitGuestOrder. Email: " + $scope.cartData.email + " | FirstName: " + $scope.firstName + " | LastName: " + $scope.lastName + " | Phone: " + $scope.checkoutState.OrderPhoneNumber);

            var customerData = {};
            customerData.email = $scope.cartData.email;
            customerData.firstName = $scope.firstName;
            customerData.lastName = $scope.lastName;
            customerData.phone = $scope.checkoutState.OrderPhoneNumber;

            $scope.checkoutState.sumitCartErrorSec = false;
            checkoutSubmitCartSvc.submitGuestOrder(customerData, $scope.checkoutState, $scope.cartData);
        };
        
       
    }
]);

;
'use strict';

/**
 * Responsible for all cart specific communication with the server
 */
angular.module('checkout').factory('MmtGiftCardCheckoutSubmitCartSvc', ['$q', '$timeout', 'appUrlBuilder', 'siteConfiguration', 'siteRes', 'CheckoutSvc', 'CheckoutDataStorageService', 'spinnerFactory', 'NavigationService', 'AddressDataHelper', 'CheckoutCreditCardValidationService', 'accountSvc', 'CartDataStorageService', 'CheckoutHelperService', '$resource',
    function ($q, $timeout, appUrlBuilder, siteConfiguration, siteRes, checkoutSvc, checkoutDataStorageService, spinnerFactory, navigationService, addressDataHelper, checkoutCreditCardValidationService, accountSvc, cartDataStorageService, checkoutHelperService,$resource) {
        
        var resource = $resource(appUrlBuilder.buildUrl('checkoutApiUrl'), null, {
            'addPaymentPhoneNumber': { method: 'PUT', url: appUrlBuilder.buildUrl('checkoutPaymentPhoneNumberURL'), isArray: false, responseType: 'json' }
        });
        var addPaypalOption = function (signedIn, giftCards) {
            spinnerFactory.show("Please wait...");
            if (signedIn) {
                if (giftCards !== undefined && giftCards !== null && giftCards.length > 0) {
                    addGiftCardsPayPalPaymentThenSubmit(giftCards);
                } else {
                    addPayPalPaymentThenSubmit();
                }
            } else {
                checkoutDataStorageService.checkoutState.createAccountSec = true;
                spinnerFactory.hide();
            }
        };

        var addPayPalPaymentThenSubmit = function () {
            var deferred = $q.defer();
            checkoutSvc.addPaypalOption().$promise.then(
                function () {
                    navigationService.navigate(appUrlBuilder.buildUrl('PayPalSubmitCartUrl'));
                }, function (error) {
                    spinnerFactory.hide();
                    deferred.reject(error);
                });
        };

        var addGiftCardsPayPalPaymentThenSubmit = function (giftCards) {
            addGiftCards(giftCards).then(
                function () {
                    spinnerFactory.hide();
                    addPayPalPaymentThenSubmit();
                },
                function (error) {
                    spinnerFactory.hide();
                    checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;
                    checkoutDataStorageService.checkoutState.errorMessage = error;
                });
        };

        var addGiftCards = function (giftCardData) {
            var deferred = $q.defer();
            spinnerFactory.show("Please wait...");
            checkoutSvc.addGiftCardsToOrderForm(giftCardData).$promise.then(
                function (value) {
                    deferred.resolve(value);
                }, function (error) {
                    deferred.reject(error);
                });
            return deferred.promise;
        };

        var addGiftCardsCreditCardPaymentThenSubmit = function (giftCards, creditCardData, cartData) {
            addGiftCards(giftCards).then(
                function () {
                    spinnerFactory.hide();
                    addCreditCardPaymentThenSubmit(creditCardData, cartData);
                },
                function (error) {
                    spinnerFactory.hide();
                    checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;
                    checkoutDataStorageService.checkoutState.errorMessage = error;
                });
        };

        var addCreditCardPaymentThenSubmit = function (creditCardData, cartData) {
            addCreditCardPayment(creditCardData).then(
                function () {
                    spinnerFactory.hide();
                    var paymentInfo = {
                        guestAccount: !cartData.signedIn,
                        paymentType: 1,
                        paymentAdded: true,
                        ignore3Ds: false
                    };
                    submitCart(paymentInfo);
                },
                function (error) {
                    spinnerFactory.hide();
                    checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;
                    checkoutDataStorageService.checkoutState.errorMessage = siteRes.SubmitCartFailByCreditCard + error;
                    console.log(error);
                });
        };

        var addCreditCardPayment = function (creditCardData) {
            var deferred = $q.defer();
            spinnerFactory.show("Please wait...");
            checkoutSvc.addCreditCardPayment(creditCardData).$promise.then(
                function (value) {
                    deferred.resolve(value);
                }, function (error) {
                    deferred.reject(error);
                });
            return deferred.promise;
        };

        var payByGiftValidate = function (giftCards, cartData) {
            if (giftCards !== undefined && giftCards !== null && giftCards.length > 0) {
                if (checkoutHelperService.getGiftCardAmounts(giftCards) >= Number(cartData.total)) {
                    return true;
                } else {
                    checkoutDataStorageService.checkoutState.errorMessage = siteRes.GiftCardAmountLessThanCartTotal;
                    return false;
                }
            } else {
                checkoutDataStorageService.checkoutState.errorMessage = siteRes.EnterGiftCard;
                return false;
            }
        };

        var addGiftCardsPaymentThenSubmit = function (giftCards, cartData) {
            var paymentInfo = {
                guestAccount: !cartData.signedIn,
                paymentType: 0,
                paymentAdded: true,
                ignore3Ds: false
            };
            if (payByGiftValidate(giftCards, cartData)) {
                addGiftCards(giftCards).then(
                    function () {
                        spinnerFactory.hide();
                        submitCart(paymentInfo);
                    },
                    function (error) {
                        spinnerFactory.hide();
                        checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;
                        checkoutDataStorageService.checkoutState.errorMessage = siteRes.SubmitCartFailByCreditCard + error;
                    });
            } else {
                submitCartFail(paymentInfo);
            }
        };



        var submitCartFail = function (paymentInfo, error) {
            checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;
            if (error) {
                checkoutDataStorageService.checkoutState.errorMessage = error;
            }
            if (paymentInfo.guestAccount && paymentInfo.paymentType == 1) {
                console.log('submit cart return value is false, need error message here');
            } else {
                //paypal fa
            }
            checkoutDataStorageService.checkoutState.billingSec = false;
            checkoutDataStorageService.checkoutState.paymentSec = true;
            checkoutDataStorageService.checkoutState.createAccountSec = false;
            checkoutDataStorageService.checkoutState.accountPasswordSec = false;
            checkoutDataStorageService.checkoutState.retryEmailSec = false;
        };

        var checkOrderStatus = function (orderId, tries) {
            var deferred = $q.defer();
            checkoutSvc.checkOrderStatus(orderId).$promise.then(
                function (value) {
                    if (value.Success === true) {
                            navigationService.navigate(appUrlBuilder.buildUrl('giftcardconfirmationPageUrl') + '/' + value.OrderId);
                    } else {
                        if (tries === 0) {
                            //bvc - checkout changes
                            checkoutSvc.setCurrentOrderForm(orderId).$promise.then(
                                    function (d) {
                                        if (!d.Success) {
                                            spinnerFactory.hide();
                                            checkoutDataStorageService.checkoutState.newCreditCardError = true;
                                            if (checkoutDataStorageService.checkoutState.paymentType === 1) {
                                                $timeout(function () {
                                                    $(".editCCPaymentLink").click();
                                                    },
                                                    500);
                                            }
                                            submitCartFail({ guestAccount: false, paymentType: 1, ignore3Ds: true }, d.Error);
                                        } else {
                                            navigationService.navigate(appUrlBuilder.buildUrl('giftcardconfirmationPageUrl') + '/' + orderId);
                                        }
                                    });

                        } else {
                            $timeout(function () {
                                tries = tries - 1;
                                checkOrderStatus(value.OrderId, tries);
                            }, 10000);
                        }
                    }
                },
                function (error) {
                    spinnerFactory.hide();
                    submitCartFail({ guestAccount: false, paymentType: 1, ignore3Ds: true }, error);
                    deferred.reject(error);
                }
            );
            return deferred.promise;
        };

        var submitCart = function (paymentInfo) {
            var deferred = $q.defer();
            spinnerFactory.show("Please wait...");
            disableScrollOnSpinnerShow();
            checkoutSvc.submitCart(paymentInfo.ignore3Ds).$promise.then(
                function (value) {
                    if (value.Success === true) {
                        //Check order status and wait until it successfully
                        checkOrderStatus(value.OrderId, siteConfiguration.timesToCheckSubmitedOrder);
                    } else {
                        spinnerFactory.hide();
                        enableScrollOnSpinnerHide();

                        if (value.Enforce3Ds === true) {
                            checkoutDataStorageService.checkoutState.show3Ds = true;
                            checkoutDataStorageService.checkoutState.threeDsNotifierUrl = checkoutSvc.getThreeDsNotifierUrl();
                        } else {
                            submitCartFail(paymentInfo, value.ErrorMessage);
                        }
                    }
                },
                function (error) {
                    spinnerFactory.hide();
                    enableScrollOnSpinnerHide();
                    //to do : go back to payment section in checkoutpage
                    deferred.reject(error);
                }
            );
            return deferred.promise;
        };

        var readyToPay = function (checkoutState, cartData) {
            if (checkoutState.paymentType === 1 || checkoutState.paymentType === 0) {
                if (checkoutState.paymentType === 1 && checkoutCreditCardValidationService.isCardValid(checkoutState) || checkoutState.paymentType === 0) {
                    processCreditCardPayment(checkoutState, cartData);
                }
            }
            if (checkoutState.paymentType === 2) {
                addPaypalOption(cartData.signedIn, checkoutState.giftCards);
            }
            if (checkoutState.paymentType === 3) {
                processExistingCreditCardPayment(checkoutState, cartData);
            }
        };


        var processExistingCreditCardPayment = function (checkoutState, cartData) {
            //hide payment section show billing section
            checkoutState.paymentSec = false;
            checkoutState.billingSec = true;
            if (cartData.signedIn) {
                //debugger;
                if (addressDataHelper.getSameAsShippingAddress()) {
                    checkoutSvc.addAddressDataToOrderForm(addressDataHelper.getShippingData(), addressDataHelper.getBillingData(), addressDataHelper.getSameAsShippingAddress()).$promise.then(
                        function () {
                            addGiftCardsExistingCreditCardPaymentThenSubmit(checkoutState.giftCards, checkoutState.existingCreditCardData, cartData, checkoutState);
                        }, function (error) {
                            console.log(error);
                        });
                } else {
                    addGiftCardsExistingCreditCardPaymentThenSubmit(checkoutState.giftCards, checkoutState.existingCreditCardData, cartData, checkoutState);
                }
            } else {
                accountSvc.createAccount(checkoutState.customerData).$promise.then(
                      function () {
                          if (addressDataHelper.getSameAsShippingAddress()) {
                              checkoutSvc.addAddressDataToOrderForm(addressDataHelper.getShippingData(), addressDataHelper.getBillingData(), addressDataHelper.getSameAsShippingAddress()).$promise.then(
                                  function () {
                                      addGiftCardsExistingCreditCardPaymentThenSubmit(checkoutState.giftCards, checkoutState.existingCreditCardData, cartData, checkoutState);
                                  }, function (error) {
                                      console.log(error);
                                  });
                          } else {
                              addGiftCardsExistingCreditCardPaymentThenSubmit(checkoutState.giftCards, checkoutState.existingCreditCardData, cartData, checkoutState);
                          }

                      }, function (error) {
                          console.log(error);
                      });
            }
            //window.scrollNextStep('step-4');
            //checkoutState.bouclairCheckoutCurrentStage = 3;
        };
        //public methods
        var addGiftCardsExistingCreditCardPaymentThenSubmit = function (giftCards, existingCreditCardData, cartData, checkoutState) {
            addGiftCards(giftCards).then(
                function () {
                    spinnerFactory.hide();
                    addExistingCreditCardPaymentThenSubmit(existingCreditCardData, cartData, checkoutState);
                },
                function (error) {
                    spinnerFactory.hide();
                    checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;
                    checkoutDataStorageService.checkoutState.errorMessage = error;
                });
        };

        var addExistingCreditCardPaymentThenSubmit = function (existingCreditCardData, cartData, checkoutState) {
            checkoutSvc.addExistingCreditCardPayment(existingCreditCardData).$promise.then(
                function () {
                    spinnerFactory.hide();
                    var paymentInfo = {
                        guestAccount: !cartData.signedIn,
                        paymentType: 1,
                        paymentAdded: true,
                        ignore3Ds: false
                    };
                    submitCart(paymentInfo, checkoutState);
                },
                function (error) {

                    spinnerFactory.hide();
                    checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;

                    checkoutDataStorageService.checkoutState.errorMessage = siteRes.SubmitCartFailByCreditCard + error;
                    console.log(error);
                });
        };

        var submitGuestOrder = function (customerData, checkoutState, cartData) {
            accountSvc.createAccount(customerData).$promise.then(
                function () {
                    checkoutSvc.addAddressDataToOrderForm(addressDataHelper.getShippingData(), addressDataHelper.getBillingData(), addressDataHelper.getSameAsShippingAddress()).$promise.then(
                        function () {
                            if (!addressDataHelper.getSameAsShippingAddress()) {
                                cartDataStorageService.loadCartData();
                            }
                            checkoutState.accountPasswordSec = false;
                            checkoutState.retryEmailSec = false;

                            if (checkoutState.giftCards !== undefined && checkoutState.giftCards.length > 0) {
                                if (checkoutState.paymentType === 0) {
                                    addGiftCardsPaymentThenSubmit(checkoutState.giftCards, cartData);
                                }
                                if (checkoutState.paymentType === 1) {
                                    addGiftCardsCreditCardPaymentThenSubmit(checkoutState.giftCards, checkoutState.creditCardData, cartData);
                                }
                                if (checkoutState.paymentType === 2) {
                                    addGiftCardsPayPalPaymentThenSubmit(checkoutState.giftCards);
                                }
                            } else {
                                if (checkoutState.paymentType === 1) {
                                    addCreditCardPaymentThenSubmit(checkoutState.creditCardData, cartData);
                                }
                                if (checkoutState.paymentType === 2) {
                                    addPayPalPaymentThenSubmit();
                                }
                            }
                        }, function (error) {
                            console.log(error);
                        });

                }, function (error) {
                    //todo when create account fail let user reEnter email if email exists already
                    console.log(error);
                    checkoutState.accountPasswordSec = false;
                    checkoutState.retryEmailSec = true;
                });
        };

        var submitOrder = function (checkoutState, cartData) {
            if (checkoutState.paymentType === 0) {
                if (cartData.signedIn) {
                    checkoutState.paymentSec = false;
                    checkoutState.billingSec = true;
                    addGiftCardsPaymentThenSubmit(checkoutState.giftCards, cartData);
                } else {
                    if (payByGiftValidate(checkoutState.giftCards, cartData)) {
                        readyToPay(checkoutState, cartData);
                    } else {
                        checkoutState.sumitCartErrorSec = true;
                    }
                }
            } else {
                readyToPay(checkoutState, cartData);
            }
        };

        var processCreditCardPayment = function (checkoutState, cartData) {
            if (checkoutState.paymentType === 1 && checkoutSvc.hpciEnabled() === true && checkoutState.hpciProcessed === false) {
                checkoutSvc.processHpci(function (e) {
                    checkoutSvc.alertDialog(e);
                });
            } else {
                //hide payment section show billing section
                checkoutState.paymentSec = false;
                checkoutState.billingSec = true;
                if (cartData.signedIn) {
                    if (addressDataHelper.getSameAsShippingAddress()) {
                        checkoutSvc.addAddressDataToOrderForm(addressDataHelper.getShippingData(), addressDataHelper.getBillingData(), addressDataHelper.getSameAsShippingAddress()).$promise.then(
                            function () {
                                addGiftCardsCreditCardPaymentThenSubmit(checkoutState.giftCards, checkoutState.creditCardData, cartData);
                            }, function (error) {
                                console.log(error);
                            });
                    } else {
                        addGiftCardsCreditCardPaymentThenSubmit(checkoutState.giftCards, checkoutState.creditCardData, cartData);
                    }
                } else {
                    //show create account section  when payment info added
                    checkoutState.createAccountSec = true;
                }
            }
        };

        var verify3Ds = function (checkoutState) {
            var deferred = $q.defer();
            checkoutSvc.verifyThreeDs().$promise.then(
                function (value) {
                    if (value.submitCart === true) {
                        checkoutState.show3Ds = false;
                        checkoutState.pass3Ds = true;
                        submitCart({ guestAccount: false, paymentType: 1, ignore3Ds: true });
                    } else {
                        checkoutState.sumitCartErrorSec = true;
                        checkoutState.billingSec = false;
                        checkoutState.paymentSec = true;
                        checkoutState.createAccountSec = false;
                        checkoutState.accountPasswordSec = false;
                        checkoutState.retryEmailSec = false;
                        checkoutState.show3Ds = false;
                        checkoutState.pass3Ds = false;
                        checkoutSvc.alert3DsError();
                        checkoutState.threeDsNotifierUrl = '';
                    }
                    deferred.resolve(value);
                }, function (error) {
                    deferred.reject(error);
                });
            return deferred.promise;
        };

        return {
            processCreditCardPayment: processCreditCardPayment,
            verify3Ds: verify3Ds,
            submitGuestOrder: submitGuestOrder,
            submitOrder: submitOrder,
            addPaymentPhoneNumber: function (paymentPhoneNumer) {
                return resource.addPaymentPhoneNumber({ PaymentPhoneNumber: paymentPhoneNumer });
            }
        };
    }
]);;
'use strict';

/**
 * Responsible for all cart specific communication with the server
 */
angular.module('checkout').factory('mmtRISCheckoutSubmitCartSvc', ['$q', '$timeout', 'appUrlBuilder', 'siteConfiguration', 'siteRes', 'CheckoutSvc', 'CheckoutDataStorageService', 'spinnerFactory', 'NavigationService', 'AddressDataHelper', 'CheckoutCreditCardValidationService', 'accountSvc', 'CartDataStorageService', 'CheckoutHelperService', '$resource',
    function ($q, $timeout, appUrlBuilder, siteConfiguration, siteRes, checkoutSvc, checkoutDataStorageService, spinnerFactory, navigationService, addressDataHelper, checkoutCreditCardValidationService, accountSvc, cartDataStorageService, checkoutHelperService,$resource) {
        
        var resource = $resource(appUrlBuilder.buildUrl('checkoutApiUrl'), null, {
            'addRISPhoneNumber': { method: 'PUT', url: appUrlBuilder.buildUrl('checkoutRISPhoneNumberURL'), isArray: false, responseType: 'json' }
        });

        var submitCartFail = function (errorMessage) {
            checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;
            console.log("RIS submit order failed. Error: " + errorMessage);
        };

        var checkOrderStatus = function (orderId, tries) {
            var deferred = $q.defer();
            checkoutSvc.checkOrderStatus(orderId).$promise.then(
                function (value) {
                    if (value.Success === true) {
                        navigationService.navigate(appUrlBuilder.buildUrl('risconfirmationPageUrl') + '/' + value.OrderId);
                    } else {
                        if (tries === 0) {
                            checkoutSvc.setCurrentOrderForm(orderId).$promise.then(
                                function (d) {
                                    if (!d.Success) {
                                        spinnerFactory.hide();
                                        submitCartFail(d.Error);
                                    } else {
                                        navigationService.navigate(appUrlBuilder.buildUrl('risconfirmationPageUrl') + '/' + orderId);
                                    }
                                });

                        } else {
                            $timeout(function () {
                                tries = tries - 1;
                                checkOrderStatus(value.OrderId, tries);
                            }, 10000);
                        }
                    }
                },
                function (error) {
                    spinnerFactory.hide();
                    submitCartFail(error);
                    deferred.reject(error);
                }
            );
            return deferred.promise;
        };
        
        var submitCart = function () {
            var deferred = $q.defer();
            spinnerFactory.show("Please wait...");
            disableScrollOnSpinnerShow();
            checkoutSvc.submitCartRIS().$promise.then(
                function (value) {
                    if (value.Success === true) {
                        checkOrderStatus(value.OrderId, siteConfiguration.timesToCheckSubmitedOrder);
                    } else {
                        submitCartFail(value.ErrorMessage);
                        spinnerFactory.hide();
                        enableScrollOnSpinnerHide();
                    }
                },
                function (error) {
                    submitCartFail(error);
                    spinnerFactory.hide();
                    enableScrollOnSpinnerHide();
                    deferred.reject(error);
                }
            );
            return deferred.promise;
        };

        var submitOrder = function () {
            submitCart();
        };

        var submitGuestOrder = function (customerData, checkoutState, cartData) {
            checkoutSvc.createRISGuestAccount(customerData).$promise.then(
                function () {
                    submitCart();
                }, function (error) {
                    console.log(error);
                });
        };
        
        return {
            submitGuestOrder: submitGuestOrder,
            submitOrder: submitOrder,
            addRISPhoneNumber: function (paymentPhoneNumer) {
                return resource.addRISPhoneNumber({ PaymentPhoneNumber: paymentPhoneNumer });
            }
        };
    }
]);;
'use strict';

/**
 * this is account control....
 */

angular.module('account').directive('mmtAccount', ['appUrlBuilder', function (appUrlBuilder) {
    return {
        restrict: 'A',
        templateUrl: appUrlBuilder.buildUniqueTemplateUrl('createAccountTemplateUrl'),
        scope: {
            // returnUrl: '=returnUrl'
            returnUrl: '@'
        },
        controller: 'MmtAccountCtrl',
        replace: true
    };
}]);;



'use strict';
/**
 * Responsible for most behaviour within the Account Module such as:
 */
angular.module('account')
    .controller('MmtAccountCtrl', ['$http', '$scope', '$q', '$modal', 'accountSvc', 'appUrlBuilder', 'NavigationService', 'siteConfiguration', 'PasswordHelper', 'mmtUpdateAccountSvc', 'spinnerFactory',
function ($http, $scope, $q, $modal, accountSvc, appUrlBuilder, navigationService, siteConfiguration, passwordHelper, mmtUpdateAccountSvc, spinnerFactory) {

    $scope.newCustomer = {};
    $scope.emailExists = false;

    $.ajax({
        url: rootRel + 'api/stores/GetMMTSimpleStores',
        success: function (data) {
            if (data) {
                $scope.stores = data;
            }
        }
    });
    $(document).ready(function () { 
        ShowSearchStores();        
    });
    $('#linkSelectStoreAccountPage').on('click', function () {       
         ShowSearchStores();
     });
     
    //Methos to show search stores options to the user on create account page.
    function ShowSearchStores() {     

         $('#fromWhichPage').val('CreateAccount');
         $.ajax({
             type: "get",
             url: rootRel + 'Newsletter/ShowEmailSignUpStoreLocator',
             success: function (response) {
                 $('#emailSignUpStoreListPlace').html(response);
                 $('#divSelectedStoreText').hide();
                 $('#emailSignUpStoreListPlace').show();
                 $('#yourSearchStoreOptions').hide();
                 $('#creatAccountStoreSearchOptions').show();
             },
             error: function (e) {

             }
         });
         $('#yourSearchStoreOptions').css('display', 'none')
     }


    $scope.validateModel = function () {

        $scope.emailExists = false;
        $scope.selectedStoreError = false;       
        var isStoreSelected = $('#hdnCreateAccountSlectedStore').val();
                
        if ($scope.newCustomer.EmailOptIn === true && (isStoreSelected === null || isStoreSelected === undefined || isStoreSelected == '')) {
            $scope.selectedStoreError = true;
        }
    };


    $scope.createAccount = function (itemData) {
       // alert($('#hdnCreateAccountSlectedStore').val());
        $scope.accountSubmitted = true;
        var isStoreSelected = $('#hdnCreateAccountSlectedStore').val();
        if ($scope.newCustomer.EmailOptIn === true && (isStoreSelected === null || isStoreSelected === undefined || isStoreSelected == '')) {
            $scope.selectedStoreError = true;
            return false;
        }

        if ($scope.accountForm.$valid) {

            var address = new Object();
            var country = new Object();

            country.CountryCode = "CA";
            country.CountryId = 1;
            country.CountryName = "Canada";
            address.Address1 = "";
            address.Address2 = "";
            address.City = "";
            address.Country = country;
            address.FirstName = itemData.firstName;
            address.LastName = itemData.lastName;
            address.Province = "";
            address.ZipCode = "";

            itemData.address = address;
            itemData.phone = "0";
            itemData.returnUrl = '';

            if ($scope.returnUrl) {
                var objFromJson = angular.fromJson($scope.returnUrl);
                if (objFromJson && objFromJson.key) {
                    itemData.returnUrl = objFromJson.key;
                }
            }            

            //check email exists
            var url = rootRel + "Account/CheckEmail/?email=" + itemData.email;
            jQuery.ajax({
                url: url,
                type: 'GET',
                success: function (data) {
                    $scope.emailExists = data;
                    $scope.$apply();                    
                    if (!data) {

                        //create account in system
                        accountSvc.createAccount(itemData).$promise.then(
                        function (data) {                            
                            //mail chimp subsribe
                            if ($scope.newCustomer.EmailOptIn === true) {
                                var hdnCreateAccountSlectedStore= $('#hdnCreateAccountSlectedStore').val();
                                $("#preferredStore").val(hdnCreateAccountSlectedStore);
                                $("#EmailAddress").val(itemData.email);
                                var form = $("#createAccountSignUpForm");
                                console.log(globalConstants.rootUrl);
                                console.log(form.serialize());                                                              
                                accountSvc.subscribeMailChimp(itemData.firstName, itemData.lastName, itemData.email, hdnCreateAccountSlectedStore);                               
                            }

                            //redirect                           
                            if (data.returnUrl == undefined) {
                                data.returnUrl = itemData.returnUrl;
                            }
                            if (data.returnUrl) {
                                navigationService.navigate(data.returnUrl);
                            } else {
                                navigationService.navigate(appUrlBuilder.buildUrl('mainPageMyAccountUrl'));
                            }
                        },
                        function (failMessage) {
                        });

                    }

                },
                error: function () {
                }
            });


        }
    };

}
    ]);



/*Confirm Password*/
angular.module('account')
  .directive('pwCheck', [function () {
      return {
          require: 'ngModel',
          scope: {
              confirmpassword: '@'
          },
          link: function (scope, elem, attrs, ctrl) {
              var firstPassword = '#' + attrs.pwCheck;
              elem.add(firstPassword).on('keyup', function () {
                  scope.$apply(function () {
                      var v = elem.val() === $(firstPassword).val();
                      ctrl.$setValidity('pwmatch', v);
                  });
              });
          }
      }
  }]);


/*Load Checkbox*/
angular.module('account').directive('loadFormCheckbox', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            if (true) {
                $timeout(function () {
                    initCustomForms();
                }, 500);
            }
        }
    }
}]);


angular.module('account').factory('mmtUpdateAccountSvc', ['$resource', 'appUrlBuilder',
    function ($resource, appUrlBuilder) {

        var resource = $resource(appUrlBuilder.buildUrl('mainPageMyAccountUrl'), null, {
            'updateAccount': { method: 'PUT', url: appUrlBuilder.buildUrl('updateAccountUrl'), isArray: false, responseType: 'json' },
            'updateGuestAccount': { method: 'PUT', url: appUrlBuilder.buildUrl('updateGuestAccountUrl'), isArray: false, responseType: 'json' }

        });

        return {
            updateAccount: function (data) {
                var args = { email: data.email, password: data.password, userId: data.email, EmailOptIn: data.EmailOptIn };
                return resource.updateAccount(args);
            },
            updateGuestAccount: function (data) {
                var args = { email: data.email, password: data.password, userId: data.email, EmailOptIn: data.EmailOptIn };
                return resource.updateGuestAccount(args);
            }
        };
    }
]);;
'use strict';
/**
 * Responsible for creating confirm page Module specific communication with the server: Updates customer and creates guest user's account
 */
angular.module('confirm').factory('mmtAccountSvc', ['$resource', 'appUrlBuilder',
    function ($resource, appUrlBuilder) {

        var resource = $resource(appUrlBuilder.buildUrl('mainPageMyAccountUrl'), null, {
            'updateAccount': { method: 'PUT', url: appUrlBuilder.buildUrl('updateAccountUrl'), isArray: false, responseType: 'json' },
            'updateGuestAccount': { method: 'PUT', url: appUrlBuilder.buildUrl('updateGuestAccountUrl'), isArray: false, responseType: 'json' }
        });

        return {
            updateAccount: function (data) {
                var args = { email: data.email, password: data.password, userId: data.email };
                return resource.updateAccount(args);
            },
            updateGuestAccount: function (data) {
                var args = { email: data.email, password: data.password, userId: data.userId };
                return resource.updateGuestAccount(args);
            }
        };
    }
]);;
'use strict';

angular.module('checkout').directive('giftcardSummary', ['appUrlBuilder',
    function (appUrlBuilder) {
        return {
            restrict: 'A',
            templateUrl: appUrlBuilder.buildTemplateUrl('giftCardcheckoutSummaryTemplateUrl'),
            scope: {
            },
            controller: 'MmtGiftCardSummaryCtrl'
        };
    }]);;
'use strict';

angular.module('checkout').directive('risCheckoutItemListing', ['appUrlBuilder', function (appUrlBuilder) {
	return {
		restrict: 'A',
		templateUrl: appUrlBuilder.buildTemplateUrl('risCheckoutItemsListingTemplateUrl'),
		controller: 'RISCartItemsListingCtrl',
		priority: 1100,
		scope: {
			isDisabled: '=',
			hideStockInfo: '='
		}
	};
}]);

angular.module('checkout').directive('risSummary', ['appUrlBuilder', 'AppObserver', function (appUrlBuilder, appObserver) {
	return {
		restrict: 'A',
		templateUrl: appUrlBuilder.buildTemplateUrl('rischeckoutSummaryTemplateUrl'),
		priority: 1001,
		scope: {
			cart: '=',
			giftCards: '='		
		}
	};
}]);


angular.module('checkout').directive('risContact', ['appUrlBuilder', function (appUrlBuilder) {
    return {
        restrict: 'A',
        replace: true,
        templateUrl: appUrlBuilder.buildTemplateUrl('risContactTemplateUrl')
    };
}]);


//angular.module('checkout').directive('risContact', ['appUrlBuilder', 'AppObserver', function (appUrlBuilder, appObserver) {
//    return {
//        restrict: 'A',
//        templateUrl: appUrlBuilder.buildTemplateUrl('risContactTemplateUrl'),
//        controller: 'mmtRISCheckoutCtrl',
//        priority: 1001,
//        scope: {
//            cart: '=',
//            giftCards: '='
//        }
//    };
//}]);
;
angular.module('checkout')
    .controller('MmtGiftCardSummaryCtrl', ['$scope', '$window', '$modal', '$location', 'CartService', 'CartDataStorageService', 'AppObserver', 'spinnerFactory', 'WishListService', 'siteConfiguration', 'appUrlBuilder', 'DialogService', 'NavigationService',
    function ($scope, $window, $modal, $location, cartService, cartDataStorageService, appObserver, spinnerFactory, wishListService, siteConfiguration, appUrlBuilder, dialogService, navigationService) {
        $scope.cartData = cartDataStorageService.cartData;
        $scope.showGiftCardModal = function () {
            if ($scope.cartData.items[0].GiftCardType.toLowerCase() == "physical") {
                $modal.open({
                    templateUrl: appUrlBuilder.buildTemplateUrl('giftCardModalTemplateUrl'),
                    backdrop: 'static',
                    controller: 'cartItemGiftCardCheckoutCtrl',
                    windowClass: 'modal-vertical-centered giftcard-modal',
                    scope: $scope
                });
            } else {
                var modal = $modal.open({
                    templateUrl: appUrlBuilder.buildTemplateUrl('digitalGiftCardModalTemplateUrl'),
                    backdrop: 'static',
                    controller: 'cartItemGiftCardCheckoutCtrl',
                    windowClass: 'modal-vertical-centered giftcard-modal',
                    scope: $scope
                });
                //modal.opened.then(function () {

                //    setTimeout(function () {
                //        $("#GiftCard_DeliveryDate").datepicker({
                //            dateFormat: 'mm/dd/yy',
                //            minDate: new Date(),
                //            defaultDate: new Date()
                //        });
                //    }, 200);

                //}, function () {
                //    $log.info('Modal dismissed at: ' + new Date());
                //});
            }
        };

        $scope.datefunction = function (date) {
            return new Date(date);
        }
    }]);
;
'use strict';
/**
 * Lists the products that are in the cart.  Implements logic around changing of product details, such as the quantity.
 */
angular.module('checkout').controller('cartItemGiftCardCheckoutCtrl',
    ['$scope', '$window', '$modal', '$location', 'CartService', '$modalInstance', '$q', 'CartDataStorageService', 'AppObserver', 'spinnerFactory', 'WishListService', 'siteConfiguration', 'appUrlBuilder', 'DialogService', 'NavigationService',
    function ($scope, $window, $modal, $location, cartService, $modalInstance, $q, cartDataStorageService, appObserver, spinnerFactory, wishListService, siteConfiguration, appUrlBuilder, dialogService, navigationService) {
        $scope.giftCardItems = {};
        $scope.giftCardItem = {};
        $scope.digitalCardItem = {};
        $scope.giftCardItem.ItemId = $scope.cartData.items[0].ItemId;
        //$scope.giftCardItem.giftCardValue = $scope.cartData.items[0].ItemSubtotal; /* error */
        $scope.giftCardItem.giftCardValue = $scope.cartData.items[0].UnitPrice;
        $scope.giftCardItem.otherOption = (function () {
            switch ($scope.giftCardItem.giftCardValue) {
                case 25:
                case 50:
                case 100:
                    return 35;
                default:
                    return $scope.giftCardItem.giftCardValue;
            }
        }());
        $scope.giftCardType = $scope.cartData.items[0].GiftCardType;
        $scope.todayDate = new Date();
        $scope.dd = $scope.todayDate.getDate();
        $scope.mm = $scope.todayDate.getMonth() + 1;
        $scope.yy = $scope.todayDate.getFullYear();
        $scope.pastdate = false;
        $scope.errorDateMessage = "Delivery date should be greater than or equal to today's date";
        if ($scope.dd < 10)
            $scope.dd = "0" + $scope.dd;
        if ($scope.mm < 10)
            $scope.mm = "0" + $scope.mm;

        $scope.SelectAvailableOptions = [
             { value: 25, name: '$25' },
             { value: 50, name: '$50' },
             { value: 100, name: '$100' },
             { value: $scope.giftCardItem.otherOption, name: 'Other' }
        ];
        //$scope.$watch('giftCardItem.giftCardValue', function (number) {
        //    $scope.giftCardItem.giftCardValue = Number(number);
        //});


        $scope.getDigitalCardData = function (guid) {
            cartService.getDigitalCardData(guid).then(function (value) {
                $scope.digitalCardItem = value;
                if ($scope.digitalCardItem.giftcard_deliverymethod == 'print') {
                    $scope.digitalCardItem.giftcard_sendername = 'N.A.';
                    $scope.digitalCardItem.giftcard_deliverydate = $scope.mm + "/" + $scope.dd + "/" + $scope.yy;
                }
            });
        };


        $scope.getGiftCardItems = function () {
            cartService.getGiftCardItems().then(function (value) {
                $scope.giftCardItems = value;
            });
        };

        $scope.updateDigitalGiftCard = function (valid, data) {
            if (valid) {
                var itemData = {};
                if (data) {
                    itemData.GiftCard_Message = data.GiftCard_Message;
                    itemData.GiftCard_DeliveryMethod = data.GiftCard_DeliveryMethod;
                    itemData.GiftCard_SenderName = data.GiftCard_DeliveryMethod == 'print' ? "N.A." : data.GiftCard_SenderName;
                    itemData.GiftCard_RecipientName = data.GiftCard_RecipientName;
                    itemData.GiftCard_RecipientEmail = data.GiftCard_RecipientEmail;
                    itemData.GiftCard_DeliveryDate = data.GiftCard_DeliveryMethod == 'print' ? "11/11/1111" : data.GiftCard_DeliveryDate;
                    itemData.Id = $scope.cartData.items[0].Id;
                    itemData.productId = $scope.cartData.items[0].ProductId;
                    itemData.Price = data.Price;

                    if (itemData.Id != null && itemData.Id != '') {
                        var deferred = $q.defer();
                        cartService.updateDigitalGiftCard(itemData).then(function (value) {
                            if (value) {
                                deferred.resolve({});
                                $scope.close();
                            } else {
                                deferred.reject('nothing was added');
                            }
                        }, function (error) { deferred.reject(error); });

                        return deferred.promise;
                    }
                }
            }


        };

  $scope.addGiftCardToCart = function (data) {
            var itemData = {};
            if (data) {
                angular.forEach($scope.giftCardItems, function(value)
                {
                    if (value.Items[0]._id == data.ItemId) {
                        itemData.price = data.giftCardValue;
                        itemData.productId = value.Items[0]._productId;
                        itemData.itemId = data.ItemId;
                        itemData.quantity = $scope.$parent.item.Quantity;
                        itemData.currentId = $scope.$parent.item.Id;
                    }
                });


                if (itemData.itemId != null && itemData.itemId != '') {
                    var deferred = $q.defer();
                    cartService.updatePhysicalGiftCard(itemData).then(function (value) {
                        if (value) {
                            deferred.resolve({});
                            $scope.close();
                        } else {
                            deferred.reject('nothing was added');
                        }
                    }, function (error) { deferred.reject(error); });

                    return deferred.promise;
                }
            } 
        
        };
    
        $scope.close = function () {
            $modalInstance.close();
        };


        if ($scope.giftCardType.toLowerCase() == 'digital') {
            $scope.getDigitalCardData($scope.cartData.items[0].Id);
        } else {
            $scope.getGiftCardItems();
        }

        $scope.checkPastDate = function () {
            var dateArr = $scope.digitalCardItem.GiftCard_DeliveryDate.split("/");
            $scope.pastdate = false;
            $scope.errorDateMessage = "Delivery date should be greater than or equal to today's date";
            if (dateArr.length >= 3) {
                var month = dateArr[0];
                var dd = dateArr[1];
                var year = dateArr[2];
                if (month > 12 || month < 0) {
                    $scope.pastdate = true;
                    $scope.errorDateMessage = "Please enter the delivery date in this format MM/DD/YYYY.";
                } else if (dd < 1 || dd > 31) {
                    $scope.pastdate = true;
                    $scope.errorDateMessage = "Please enter the delivery date in this format MM/DD/YYYY.";
                } else if (year >= $scope.yy) {
                    switch (month) {
                        case "01":
                        case "03":
                        case "05":
                        case "07":
                        case "08":
                        case "10":
                        case "12":
                            if (dd > 31) {
                                $scope.pastdate = true;
                                $scope.errorDateMessage = "Please enter the delivery date in this format MM/DD/YYYY.";
                            }
                            break;
                        case "02":
                            var x = (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
                            if ((x && dd > 29) || (!x && dd > 28)) {
                                $scope.pastdate = true;
                                $scope.errorDateMessage = "Please enter the delivery date in this format MM/DD/YYYY.";
                            }
                            break;
                        case "04":
                        case "06":
                        case "09":
                        case "11":
                            if (dd > 30) {
                                $scope.pastdate = true;
                                $scope.errorDateMessage = "Please enter the delivery date in this format MM/DD/YYYY.";
                            }
                            break;
                    }
                    if (!$scope.pastdate) {
                        if (month < 10)
                            month = "0" + month;
                        if (dd < 10)
                            dd = "0" + dd;
                        var enteredDate = new Date(month + "/" + dd + "/" + year);
                        var pasedTodayDate = Date.parse($scope.mm + "/" + $scope.dd + "/" + $scope.yy);
                        if (new Date(enteredDate) < new Date(pasedTodayDate)) {
                            $scope.pastdate = true;
                        }
                    }
                } else {
                    $scope.pastdate = true;
                }
            } else {
                $scope.pastdate = true;
            }
        }

    }
    ]);




// Post rendering call to style the controls
angular.module('checkout').directive('post', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            if (!scope.hasItemCategoryItems || scope.$last) {
                $timeout(function () {
                    initCustomForms();

                }, 1000);
            }
        }
    }

}]);

// Post rendering to sync gift value select and textbox
angular.module('checkout').directive('post2', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            $timeout(function () {
                $('.amount-block #cardAmount').change(function () {
                    $('.amount-block .priceGiftCard').val($(this).val());
                });
            }, 0);

            $('.amount-block .priceGiftCard').blur(function () {
                if ($('.amount-block .priceGiftCard').val() < 5) {
                    $('.amount-block .priceGiftCard').val(5);
                }

                if ($('.amount-block .priceGiftCard').val() > 500) {
                    $('.amount-block .priceGiftCard').val(500);
                }
            });
        }
    }
}]);

// Post rendering to sync gift value select and textbox
angular.module('checkout').directive('convertToNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            ngModel.$parsers.push(function (val) {
                return val != null ? parseInt(val, 10) : null;
            });
            ngModel.$formatters.push(function (val) {
                return val != null ? '' + val : null;
            });
        }
    };
});

;
'use strict';

angular.module('confirm')
    .controller('MmtConfirmGiftCardCtrl', ['$scope', 'MmtConfirmPageDataStorageService', 'CartDataStorageService', 'AddressDataHelper', 'mmtAccountSvc', '$timeout',
        function ($scope, mmtConfirmPageDataStorageService, cartDataStorageService, addressDataHelper, mmtAccountSvc, $timeout) {
            $scope.error = false; 
            $scope.isCardToSave = false;
            $scope.cartData = mmtConfirmPageDataStorageService.cartData;
            $scope.loadCartData = function () {
                mmtConfirmPageDataStorageService.loadData($scope.orderId).then(
                    function () {
                        cartDataStorageService.sync($scope.cartData, false);
                    },
                    function () {
                        $scope.error = true;
                    });
            };

            //preload cart data
            $scope.loadCartData();

            $scope.password = '';
            $scope.confirmpassword = '';

            $scope.isDisabled = true;
            $scope.confirmPasswordChangedInit = false;

            // Flag to enable or disable order cancel link
            $scope.disableCancelOrder = false;
            $scope.elapsedTime = '';
            $scope.cancelTime = 60;
            $scope.cancelCommitTime = $scope.cancelTime * 60000;

            // Flag to enable or disable account creation successful section
            $scope.isSuccess = false;

            //Validate form
            $scope.validateModel = function () {
                $scope.serverErrorMsg = '';

                $scope.isSuccess = false;

                var passwordNotEmpty = false;
                var confirmpasswordNotEmpty = false;
                var isPasswordMatched = false;

                if ($scope.password) {
                    passwordNotEmpty = true;
                    if (!$scope.passwordChangedInit) {
                        $scope.passwordChangedInit = true;
                    }
                }

                if ($scope.confirmpassword) {
                    confirmpasswordNotEmpty = true;
                    if (!$scope.confirmPasswordChangedInit) {
                        $scope.confirmPasswordChangedInit = true;
                    }
                }

                if ($scope.password === $scope.confirmpassword) {
                    isPasswordMatched = true;
                }
                // set isDisabled(create button status)
                if (passwordNotEmpty && confirmpasswordNotEmpty && isPasswordMatched) {
                    $scope.isDisabled = false;
                }
                else {
                    $scope.isDisabled = true;
                }
            };

            // Create Guest Customer by updating its entry
            $scope.createGuestCustomerAccount = function () {
                $scope.submitted = true;
                if ($scope.accountForm.$valid) {
                    var customerData = {};

                    customerData.email = $scope.cartData.customer.Email;
                    customerData.password = $scope.password.trim() === '' ? $scope.cartData.customer.password : $scope.password;
                    customerData.userId = $scope.cartData.customer.UserId;

                    $.ajax({
                        url: rootRel + 'Account/IsUserIdExist',
                        data: {userId:$scope.cartData.customer.Email},
                        type: "POST",
                        success: function(result) {
                            if (result === "True"){
                                //UserId exists
                                $("#isUserExists").show();
                                $("#isUserExists").attr("style", "visibility: visible;");
                            } else {
                                //no userId exists 
                                mmtAccountSvc.updateGuestAccount(customerData).$promise.then(
                                    function (result) {
                                        // To enable or disable account creation successful section 
                                        $scope.isSuccess = result;
                                        if (!$scope.isCardToSave && result) {
                                            var data = $scope.cartData.CreditCardInfo._id;
                                            $.ajax({
                                                type: "post",
                                                data: { id: $scope.cartData.CreditCardInfo._id },
                                                url: rootRel + 'Account/CreditCardRemove',
                                                success: function (response) {
                                                    if (response == 'done') {
                                                        $scope.isSuccess = result;
                                                    }
                                                },
                                                error: function (e) {
                                                    console.log(e.responseJSON.ExceptionMessage);
                                                }
                                            });
                                        }
                                    }
                                );
                            }
                        }
                    });
                }
            };

            $scope.orderCancel = function () {
                $.ajax({
                    url: rootRel + 'Account/OrderCancel',
                    data: { id: $scope.orderId },
                    type: "POST",
                    success: function (data) {
                        if (data != null && data === true) {
                            $scope.$apply(function () {
                                $scope.disableCancelOrder = data;
                            });
                            ShowConfirmModal("Cancellation successful",
                                        "You have cancelled your order – you will receive a confirmation email shortly.");
                        }
                    },
                    error: function (e) {
                        
                    }
                });
            };

            $scope.orderCancelTime = function () {
                $.ajax({
                    url: rootRel + 'Account/EnableCancelLinkFor',
                    data: { id: $scope.orderId },
                    type: "POST",
                    success: function (data) {
                        if (data != null) {
                            $scope.elapsedTime = data;
                        }
                        if ($scope.elapsedTime < $scope.cancelTime) {
                            $scope.cancelCommitTime = ($scope.cancelTime - $scope.elapsedTime) * 60000;
                        } else {
                            $scope.$apply(function () {
                                $scope.disableCancelOrder = true;
                            });
                        }
                    },
                    error: function (e) {
                        
                    }
                });
            };

            $scope.orderCancelTime();

            $timeout(function () {
                $scope.$apply(function () {
                    $scope.disableCancelOrder = true;
                });
            }, $scope.cancelCommitTime);

            $scope.toggleSaveCard = function (isChkboxChecked) {
                if (isChkboxChecked) {
                    $scope.isCardToSave = true;
                }
                else {
                    $scope.isCardToSave = false;
                }
            };

        }
    ]);


;
'use strict';

angular.module('confirm').directive('mmtConfirmGiftCard', ['appUrlBuilder',
    function (appUrlBuilder) {
        return {
            restrict: 'A',
            templateUrl: appUrlBuilder.buildTemplateUrl('confirmGiftCardPageTemplateUrl'),
            scope: {
                orderId: '@'
            },
            controller: 'MmtConfirmGiftCardCtrl'
        };

    }]);;
angular.module('confirm')
    .controller('mmtConfirmGiftCardSummaryCtrl', ['$scope', 'MmtConfirmPageDataStorageService', function ($scope, mmtConfirmPageDataStorageService) {
        $scope.cartData = mmtConfirmPageDataStorageService.cartData;
    }]);;
'use strict';

angular.module('confirm').directive('mmtConfirmGiftCardSummary', ['appUrlBuilder',
    function (appUrlBuilder) {
        return {
            restrict: 'A',
            templateUrl: appUrlBuilder.buildTemplateUrl('confirmGiftCardSummaryTemplateUrl'),
            scope: {
            },
            controller: 'mmtConfirmGiftCardSummaryCtrl'
        };
    }]);;
'use strict';

angular.module('confirm')
    .controller('MmtConfirmRISCtrl', ['$scope', 'MmtConfirmPageDataStorageService', 'CartDataStorageService', 'AddressDataHelper', 'mmtAccountSvc','$timeout', 'spinnerFactory',
        function ($scope, mmtConfirmPageDataStorageService, cartDataStorageService, addressDataHelper, mmtAccountSvc, $timeout, spinnerFactory) {
            spinnerFactory.show("Please wait...");
            disableScrollOnSpinnerShow();
            $scope.error = false;
            $scope.isCardToSave = false;
            $scope.cartData = mmtConfirmPageDataStorageService.cartData;
            $scope.loadCartData = function () {
                mmtConfirmPageDataStorageService.loadData($scope.orderId).then(
                    function () {
                        cartDataStorageService.sync($scope.cartData, false);
                    },
                    function () {
                        $scope.error = true;
                    });
            };

            //preload cart data
            $scope.loadCartData();

            $scope.password = '';
            $scope.confirmpassword = '';

            $scope.isDisabled = true;
            $scope.confirmPasswordChangedInit = false;

            // Flag to enable or disable order cancel link
            $scope.disableCancelOrder = false;
            $scope.elapsedTime = '';
            $scope.cancelTime = 60;
            $scope.cancelCommitTime = $scope.cancelTime * 60000;

            // Flag to enable or disable account creation successful section
            $scope.isSuccess = false;

            //Validate form
            $scope.validateModel = function () {
                $scope.serverErrorMsg = '';

                $scope.isSuccess = false;

                var passwordNotEmpty = false;
                var confirmpasswordNotEmpty = false;
                var isPasswordMatched = false;

                if ($scope.password) {
                    passwordNotEmpty = true;
                    if (!$scope.passwordChangedInit) {
                        $scope.passwordChangedInit = true;
                    }
                }

                if ($scope.confirmpassword) {
                    confirmpasswordNotEmpty = true;
                    if (!$scope.confirmPasswordChangedInit) {
                        $scope.confirmPasswordChangedInit = true;
                    }
                }

                if ($scope.password === $scope.confirmpassword) {
                    isPasswordMatched = true;
                }
                // set isDisabled(create button status)
                if (passwordNotEmpty && confirmpasswordNotEmpty && isPasswordMatched) {
                    $scope.isDisabled = false;
                }
                else {
                    $scope.isDisabled = true;
                }
            };

            // Create Guest Customer by updating its entry
            $scope.createGuestCustomerAccount = function () {
                $scope.submitted = true;
                if ($scope.accountForm.$valid) {
                    var customerData = {};

                    customerData.email = $scope.cartData.customer.Email;
                    customerData.password = $scope.password.trim() === '' ? $scope.cartData.customer.password : $scope.password;
                    customerData.userId = $scope.cartData.customer.UserId;


                    $.ajax({
                        url: rootRel + 'Account/IsUserIdExist',
                        data: { userId: $scope.cartData.customer.Email },
                        type: "POST",
                        success: function(result) { 
                            if (result === "True") {
                                //UserId exists
                                $("#isUserExists").show();
                                $("#isUserExists").attr("style", "visibility: visible;");
                            } else {
                                mmtAccountSvc.updateGuestAccount(customerData).$promise.then(
                                   function (result) {
                                       // To enable or disable account creation successful section
                                       $scope.isSuccess = result;
                                       if(!$scope.isCardToSave && result) {
                                           var data = $scope.cartData.CreditCardInfo._id;
                                           $.ajax({
                                               type: "post",
                                               data: {id: $scope.cartData.CreditCardInfo._id},
                                               url: rootRel + 'Account/CreditCardRemove',
                                               success: function (response) {
                                                   if (response == 'done') {
                                                       $scope.isSuccess = result;
                                                   }
                                               },
                                               error: function (e) {
                                                   console.log(e.responseJSON.ExceptionMessage);
                                               }
                                           });
                                       }
                                   });
                            }
                        }
                    });
                }
            };

            $scope.orderCancel = function () {
                $.ajax({
                    url: rootRel + 'Account/OrderCancel',
                    data: { id: $scope.orderId },
                    type: "POST",
                    success: function (data) {
                        if (data != null && data === true) {
                            $scope.$apply(function () {
                                $scope.disableCancelOrder = data;
                            });
                            ShowConfirmModal("Cancellation successful",
                                        "You have cancelled your order – you will receive a confirmation email shortly.");
                        }
                    },
                    error: function (e) {

                    }
                });
            };

            $scope.orderCancelTime = function () {
                $.ajax({
                    url: rootRel + 'Account/EnableCancelLinkFor',
                    data: { id: $scope.orderId },
                    type: "POST",
                    success: function (data) {
                        if (data != null) {
                            $scope.elapsedTime = data;
                        }
                        if ($scope.elapsedTime < $scope.cancelTime) {
                            $scope.cancelCommitTime = ($scope.cancelTime - $scope.elapsedTime) * 60000;
                        } else {
                            $scope.$apply(function () {
                                $scope.disableCancelOrder = true;
                            });
                        }
                    },
                    error: function (e) {

                    }
                });
            };

            $scope.orderCancelTime();

            $timeout(function () {
                $scope.$apply(function () {
                    $scope.disableCancelOrder = true;
                });
            }, $scope.cancelCommitTime);

            $scope.toggleSaveCard = function (isChkboxChecked) {
                if (isChkboxChecked) {
                    $scope.isCardToSave = true;
                }
                else {
                    $scope.isCardToSave = false;
                }
            };

            spinnerFactory.hide();
            enableScrollOnSpinnerHide();
        }
    ]);

//Prevent Scrolling of page when Spinner is visible
function disableScrollOnSpinnerShow() {
    $('body').css('overflow', 'hidden');
    $('body').mousedown(function (e) { if (e.button === 1) return false });
}

function enableScrollOnSpinnerHide() {
    $('body').css('overflow', 'auto');
    $('body').mousedown(function (e) { if (e.button === 1) return true });
}


;
'use strict';

angular.module('confirm').directive('mmtconfirmris', ['appUrlBuilder',
    function (appUrlBuilder) {
        return {
            restrict: 'A',
            templateUrl: appUrlBuilder.buildTemplateUrl('confirmRISPageTemplateUrl'),
            scope: {
                orderId: '@'
            },
            controller: 'MmtConfirmRISCtrl'
        };

    }]);;
'use strict';

angular.module('confirm')
    .controller('MmtContactRISCtrl', ['$scope', 'MmtConfirmPageDataStorageService', function ($scope, mmtConfirmPageDataStorageService) {
        $scope.cartData = mmtConfirmPageDataStorageService.cartData;
    }]);;
'use strict';

angular.module('confirm').directive('mmtconfirmcontactris', ['appUrlBuilder',
    function (appUrlBuilder) {
        return {
            restrict: 'A',
            templateUrl: appUrlBuilder.buildTemplateUrl('risConfirmContactTemplateUrl'),
            scope: {
            },
            controller: 'MmtContactRISCtrl'
        };

    }]);;
'use strict';

angular.module('confirm')
    .controller('MmtStoreRISCtrl', ['$scope', 'MmtConfirmPageDataStorageService', function ($scope, mmtConfirmPageDataStorageService) {
        $scope.cartData = mmtConfirmPageDataStorageService.cartData;
    }]);;
'use strict';

angular.module('confirm').directive('mmtconfirmstoreris', ['appUrlBuilder',
    function (appUrlBuilder) {
        return {
            restrict: 'A',
            templateUrl: appUrlBuilder.buildTemplateUrl('risConfirmStoreTemplateUrl'),
            scope: {
            },
            controller: 'MmtStoreRISCtrl'
        };

    }]);;
'use strict';

/**
 * this is service that stores cart data, shared across multiple cart directives
 */


angular.module('cart')
    /**
    * This controller manages the lifecycle and groups all of the various services related to the shopping cart.
    * 
    * All of the functions it exposes are on the $rootScope because they need to be accessed by other controllers
     */
    .controller('CartCtrl', ['$scope', 'CartDataStorageService',
        function ($scope, cartDataStorageService) {

            $scope.cartData = cartDataStorageService.cartData;
            $scope.loadCounter = cartDataStorageService.loadCounter;

            $scope.loadData = function () {
                //bvc - not necessary
                //if ($scope.preloadData !== false && $scope.preloadData !== 'false') {
                //    cartDataStorageService.loadCartData();
                //}
            };
        }
    ]);;

angular.module('cart').factory('CartDataStorageService', ['$q', 'CartDataService', 'CartHelperService', '$filter', 'spinnerFactory',
function ($q, cartDataSvc, cartHelperService, $filter, spinnerFactory) {
        var cartData = { items: [] };
        var loadCounter = { count: 1 };
        cartData.isShippingPostalCodeValid = false;
        var intialLoad = true;

        var loadCartData = function () {
            if (intialLoad) {
                spinnerFactory.show("Please wait...");
                disableScrollOnSpinnerShow();
            }

            var deferred = $q.defer();
            cartDataSvc.getOrderForm().$promise.then(
                function (freshCartData) {
                    sync(freshCartData, false);
                    deferred.resolve({});

                    if (intialLoad) {
                        enableScrollOnSpinnerHide();
                        spinnerFactory.hide();
                        intialLoad = false;
                    }
                },
                function (error) { deferred.reject(error); });
            return deferred.promise;
        };

        var sync = function (freshCartData, mergeItems, restoredItems) {
            cartData.isLoaded = true;
            cartData.total = freshCartData.Total;
            cartData.subtotal = freshCartData.SubTotal;
            cartData.giftWrapSubTotal = freshCartData.GiftWrapSubTotal;
            cartData.totalShipping = freshCartData.TotalShipping;
            cartData.totalItemsCount = freshCartData.TotalItemsCount,
            cartData.totalTax = freshCartData.TotalTax;
            cartData.TotalDiscounts = freshCartData.TotalDiscounts;
            cartData.ShippingDiscount = freshCartData.ShippingDiscount;
            cartData.Surcharge = freshCartData.Surcharge;
            cartData.USCustoms = freshCartData.USCustoms;
            cartData.taxes = freshCartData.Taxes;
            cartData.showShippingMarketing = freshCartData.ShowShippingMarketing;
            cartData.upsellMessage = freshCartData.UpsellMessage;
            cartData.addressInfo = freshCartData.AddressInfo;
            cartData.ShippingAddressPostalCode = freshCartData.ShippingAddressPostalCode;
            cartData.customer = freshCartData.Customer;
            cartData.signedIn = freshCartData.SignedIn;
            cartData.appliedPromotions = freshCartData.AppliedPromotions;
            cartData.HasAppliedPromotions = freshCartData.HasAppliedPromotions;
            cartData.creditMemoAmount = freshCartData.CreditMemoAmount;
            cartData.IsOrderFormOrderable = freshCartData.IsOrderFormOrderable;
            cartData.CreditCardInfo = freshCartData.CreditCardInfo;
            cartData.ExistingCreditCards = freshCartData.ExistingCreditCards;
            cartData.isDigitalGiftCardOrder = freshCartData.IsDigitalGiftCardOrder;
            cartData.isGiftCardsOnly = freshCartData.IsGiftCardsOnly;
            cartData.checkoutCartError = freshCartData.CheckoutCartError;
            cartData.reserveCartError = freshCartData.ReserveCartError; 
            cartData.totalSavings = freshCartData.TotalSavings;
            cartData.perkCode = freshCartData.PerkCode;
            cartData.perkDiscount = freshCartData.PerkDiscount;
            cartData.totalDiscountsExPerk = freshCartData.TotalDiscountsExPerk;
            cartData.perkTotalSavings = freshCartData.PerkTotalSavings;

            if (freshCartData.GiftCardDetails != null) {
                cartData.GiftCard_Message = freshCartData.GiftCardDetails.giftcard_message;
                cartData.GiftCard_SenderName = freshCartData.GiftCardDetails.giftcard_sendername;
                cartData.GiftCard_RecipientName = freshCartData.GiftCardDetails.giftcard_recipientname;
                cartData.GiftCard_RecipientEmail = freshCartData.GiftCardDetails.giftcard_recipientemail;
                cartData.GiftCard_DeliveryDate = freshCartData.GiftCardDetails.giftcard_deliverydate;
                if (!cartData.GiftCard_DeliveryDate)
                    cartData.GiftCard_DeliveryDate = new Date();
            }
            if (freshCartData.GiftCardImageUrl != null) {
                cartData.GiftCardImageUrl = freshCartData.GiftCardImageUrl;
            }
            if (mergeItems !== true) {
                cartData.items = freshCartData.LineItems;
            } else {
                cartHelperService.mergeCartDataItems(cartData.items, freshCartData.LineItems, restoredItems);
            }
            if (cartData.ShippingAddressPostalCode) {
                cartData.isShippingPostalCodeValid=true;
            }
            loadCounter.count++;

        };

        return {
            cartData: cartData,
            loadCartData: loadCartData,
            sync: sync,
            loadCounter: loadCounter
        };

    }]);
;
'use strict';

/**
 * Lists the products that are in the cart.  Implements logic around changing of product details, such as the quantity.
 */
angular.module('cart').controller('CartItemsListingCtrl',
    ['$scope', '$window', '$modal', '$timeout', '$location', 'CartService', 'CartDataStorageService', 'AppObserver', 'spinnerFactory', 'WishListService', 'siteConfiguration', 'appUrlBuilder', 'DialogService', 'NavigationService', 'CartDataService',
    function ($scope, $window, $modal, $timeout, $location, cartService, cartDataStorageService, appObserver, spinnerFactory, wishListService, siteConfiguration, appUrlBuilder, dialogService, navigationService, CartDataService) {

        $scope.productData = cartDataStorageService.cartData;
 
        $scope.updateItemQuantity = function (itemId, quantity) {

              for (var it = 0; it < $scope.productData.items.length; it++) {
                var itm = $scope.productData.items[it];
                if (itm.Id === itemId) {
                    itm.QuantityChanged = true;
                    break;
                }
            }

              if (quantity === '' || quantity === '0' || quantity == null) {
                  quantity = 1;
              }
            //if any item in the cart quantity changed, will broadcast reloadShippingRates event
                var hasItemQuantityChanged = false;
                for (var i = 0; i < $scope.productData.items.length; i++) {
                    var item = $scope.productData.items[i];
                    if (item.Id === itemId && item.QuantityChanged === true) {
                        hasItemQuantityChanged = true;
                        spinnerFactory.show("Please wait...");

                        //for some weird reason 'jshint ignore:start - jshint ignore:end' does not work
                        cartService.updateItemQuantity(itemId, quantity).then( // jshint ignore:line
                            function () { spinnerFactory.hide(); }, // jshint ignore:line
                            function () { spinnerFactory.hide(); } // jshint ignore:line
                        ); // jshint ignore:line

                    }
                }
                if (hasItemQuantityChanged) {
                    //broadcast reloadShippingRates event, current shippingEstimate controller listening on this in order to refresh the shipping rate
                    appObserver.broadcast('reloadShippingRates', {});
                }
            //}
        };


        $scope.undoRemoveFromCart = function (item) {
            cartService.undoRemoveFromCart(item);

        };

        $scope.removeFromCart = function (itemId) { 
           cartService.removeFromCart(itemId);
        };

        //new
        $scope.addToGiftList = function (signedIn, itemId, id) {
            $timeout(function () {
                if (signedIn) {
                    AddProdtoGiftList(signedIn, itemId);
                    $scope.removeFromCart(id);

                    //$scope.$apply(function () {
                    //    var addedProductId = 0;
                    //    angular.forEach($scope.productData.items, function (value) {
                    //        if (value.ItemId == itemId) {
                    //            addedProductId = value.ProductId;
                    //        }
                    //    });
                    //    angular.forEach($scope.productData.items, function (value) {
                    //        if (value.ProductId == addedProductId) {
                    //            value.IsInWishList = true;
                    //        }
                    //    });
                    //});

                } else {
                    currentSelectedItemId = -999; //shopping cart
                    $('#giftListSigninModal').modal('show');    
                }

            }, 500);
        };

        //old
        $scope.addToWishList = function (itemId, id) {
            wishListService.addItem(itemId, function () {

                $scope.$apply(function () {
                    var addedProductId = 0;
                    angular.forEach($scope.productData.items, function (value) {
                        if (value.ItemId == itemId) {
                            addedProductId = value.ProductId;

                        }
                    });



                    angular.forEach($scope.productData.items, function (value) {
                        if (value.ProductId == addedProductId) {
                            value.IsInWishList = true;
                        }
                    });
                });

                var baseLen = $location.protocol().length + $location.host().length + siteConfiguration.rootUrl.length + 3;
                var retUrl = $location.absUrl().substring(baseLen);

                //if we add item to wishlist via cart on the wishlist page - we have to refresh wishlist page in order to show added items
                if (retUrl.toLowerCase().indexOf(siteConfiguration.wishListUrl.toLowerCase()) === 0) {
                    navigationService.navigate($location.absUrl() + '?showCart=True');
                }

            }, function (request, status, error) {
                if (error == 'Forbidden') {
                    navigationService.navigate(appUrlBuilder.buildUrl('signInPageUrl') + '?ReturnUrl=' + encodeURIComponent('~/ShoppingCart?addToWishList=' + itemId));
                } else {
                    dialogService.alert($window.res.GeneralError);
                }

            });

            $scope.removeFromCart(id);
        };

        $scope.selectedPricingBonusItemChanged = function (itemGuid, newItemId, quantity) {
            cartService.updatePricingBonusItem(itemGuid, newItemId, quantity);
        };

        $scope.selectedDynPromoBonusItemChanged = function (itemGuid, newItemId, quantity) {
            cartService.updateDynPromoBonusItem(itemGuid, newItemId, quantity).then(function () {
                $scope.slide(newItemId);
                   }
            );
        };

        $scope.quantityChanged = function (itemId) {
            for (var i = 0; i < $scope.productData.items.length; i++) {
                var item = $scope.productData.items[i];
                if (item.Id === itemId) {
                    item.QuantityChanged = true;
                    break;
                }
            }
        };

        $scope.slide = function (itemId) {
            var freeGiftSlider= $(".freeGiftSlider" + itemId);
            if (freeGiftSlider.css("position") == "absolute") {
                freeGiftSlider.css("position", "static");
                initPDPCartSlickGallary();
                return;
            }
                
            freeGiftSlider.slideToggle("slow", function () {
                // Animation complete.
            });
            return false;
        } 
        $scope.giftCardData = CartDataService.getOrderForm();
        $scope.datefunction= function(date) {
          return  new Date(date);
        }

    }
    ]);


// Post rendering call to style the controls
angular.module('cart').directive('post', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            if (!scope.hasItemCategoryItems || scope.$last) {
                $timeout(function () {
                    initCustomForms();
                }, 0);
            }
        }
    }

}]); ;
'use strict';

/**
 * Will control the lifecyle of the product personalization
 */
angular.module('cart')
    .directive('mmtEditCartItem', ['ProductPersonalizationService', 'CartService', 'appUrlBuilder', function (productPersonalizationService, cartService, appUrlBuilder) {
        return {
            restrict: 'A', // Only matches attribute name
            templateUrl: appUrlBuilder.buildTemplateUrl('productCartPersonalizationUrl'),
            scope: {
                itemGuid: '=',
                itemCategories: '=',
                productId: '=',
                itemId: '=',
                hasPersonalization: '=',
                enableItemSelection: '=',
                disabled: '=',
                imageUrl: '=',
                switchImages: '='
            },
            link: function (scope, element) {
                scope.switchImageIndex = 0;
                scope.switchImage = function () {
                    if (scope.switchImages.length > 0) {
                        if (scope.switchImageIndex + 1 < scope.switchImages.length) {
                            scope.switchImageIndex++;
                        } else {
                            scope.switchImageIndex = 0;
                        }
                        scope.imageUrl = scope.switchImages[scope.switchImageIndex];
                    }
                };
                //there is no personalization at all - do not show popup and return immediately
                if (scope.hasPersonalization.toString().toLowerCase() !== 'true' &&
                    scope.enableItemSelection.toString().toLowerCase() !== 'true') {
                    scope.isEditable = false;
                } else {
                    scope.isEditable = true;
                }

                scope.onSelectedItemChanged = function (item) {
                    scope.selectedItem = item;
                    scope.onSubmit({});
                };

                scope.onSubmit = function (data) {

                    if (scope.enableItemSelection === true && (scope.selectedItem.Id === undefined || scope.selectedItem.Id === null)) {
                        return false;
                    }
                    //var result = { selectedItem: scope.selectedItem, selectedOptions: data };

                    cartService.updateItem({ ItemGuid: scope.itemGuid, SelectedItemId: scope.selectedItem.Id, Options: data.selectedOptions });

                };

                //if (scope.isEditable !== false && scope.disabled !== true) {
                //    element.bind('click', function () {
                //        var args = {
                //            productId: scope.productId,
                //            itemGuid: scope.itemGuid,
                //            hasPersonalization: scope.hasPersonalization,
                //            enableItemSelection: scope.enableItemSelection,
                //            itemCategories: scope.itemCategories,
                //            itemId: scope.itemId
                //        };

                //        //productPersonalizationService.openPersonalizationDialog(args).then(function (data) {
                //            var id;
                //            if (data.selectedItem && data.selectedItem.Id) {
                //                id = data.selectedItem.Id;
                //            }
                //            cartService.updateItem({ ItemGuid: scope.itemGuid, SelectedItemId: id, Options: data.selectedOptions });
                //        });
                //    //});
                //}
            }
        };
    }]);;
'use strict';

angular.module('cart').directive('mmtCartItemDetails', ['appUrlBuilder', function (appUrlBuilder) {
    return {
        restrict: 'A',
        priority: 1000,
        scope: {
            isDisabled: '=',
            hideStockInfo: '=',
            item: '=',
            onQuantityChanged: '&',
            onItemQuantityUpdateRequired: '&',
            onSelectedPricingBonusItemChanged: '&',
            onSelectedDynPromoBonusItemChanged: '&'
       
        },
        controller: 'cartItemDetailsCtrl',
        templateUrl: appUrlBuilder.buildTemplateUrl('cartItemDetailsTemplateUrl'),
        link: function (scope, elem, attrs, ngModelCtrl) {
            scope.quantityChanged = function (itemId) {
                var val = angular.element('#cid-inpt-qty-' + scope.item.ItemId).val()
                if (scope.item.Quantity === undefined && scope.item.MaxQuantity > 0 && scope.item.MaxQuantity < 1000) {
                    if (val > scope.item.MaxQuantity) {
                        val = scope.item.MaxQuantity;
                        scope.item.Quantity = scope.item.MaxQuantity;
                        angular.element('#cid-inpt-qty-' + scope.item.ItemId).val(scope.item.Quantity);
                    }
                }

                scope.onQuantityChanged({ itemId: itemId });

                scope.updateItemQuantity(itemId, val);
            };
            scope.updateItemQuantity = function (itemId, quantity) {
                scope.onItemQuantityUpdateRequired({ itemId: itemId, quantity: quantity });
            };
            scope.selectedPricingBonusItemChanged = function () {
                var bonustItemGuid = scope.item.BonusItemsAddedViaPricing.Id;
                var bonustItemId = scope.item.BonusItemsAddedViaPricing.CurrentItemId;
                var quantity = scope.item.BonusItemsAddedViaPricing.Quantity;

                scope.onSelectedPricingBonusItemChanged({ itemGuid: bonustItemGuid, newItemId: bonustItemId, quantity: quantity });
            };
            scope.selectedDynamicPromoBonusItemChanged = function () {
                var itemGuid = scope.item.BonusItemsAddedViaDynamicPromotion.Id;
                var itemId = scope.item.BonusItemsAddedViaDynamicPromotion.CurrentItemId;
                var quantity = scope.item.BonusItemsAddedViaDynamicPromotion.Quantity;

                scope.onSelectedDynPromoBonusItemChanged({ itemGuid: itemGuid, newItemId: itemId, quantity: quantity });
            };

            //setTimeout(function () {
            //    //addNumberJcf(jQuery, 'input[type="number-jcf"]');
            //    $('[data-toggle="tooltip"]').tooltip();
            //    //$('.free-gift-block .gift-intro .opener').click();

            //}, 50);

        }
    };
}]);;
'use strict';

/**
 * Lists the products that are in the cart.  Implements logic around changing of product details, such as the quantity.
 */
angular.module('cart').controller('cartItemDetailsCtrl',
    ['$scope', '$window', '$modal', '$location', 'CartService', 'CartDataStorageService', 'AppObserver', 'spinnerFactory', 'WishListService', 'siteConfiguration', 'appUrlBuilder', 'DialogService', 'NavigationService',"$timeout",
function ($scope, $window, $modal, $location, cartService, cartDataStorageService, appObserver, spinnerFactory, wishListService, siteConfiguration, appUrlBuilder, dialogService, navigationService,$timeout) {

        $scope.showGiftWrapModal = function (wrapId) {

            if (wrapId != null) {
                $scope.CurrentWrapId = wrapId;
                $scope.ModalTitle = "Edit Gift Wrap";
            } else {
                $scope.CurrentWrapId = null;
                $scope.ModalTitle = "Add Gift Wrap";
            }

            $modal.open({
                templateUrl: appUrlBuilder.buildTemplateUrl('giftWrapTemplateUrl'),
                backdrop: 'static',
                controller: 'cartItemWrapCtrl',
                windowClass: 'modal-vertical-centered giftwrap-modal',
                scope: $scope
            });
        };

        $scope.showGiftCardModal = function () {
            if ($scope.item.GiftCardType.toLowerCase() == "physical") {
                $modal.open({
                    templateUrl: appUrlBuilder.buildTemplateUrl('giftCardModalTemplateUrl'),
                    backdrop: 'static',
                    controller: 'cartItemGiftCardCtrl',
                    windowClass: 'modal-vertical-centered giftcard-modal',
                    scope: $scope
                });
            } else {
                $modal.open({
                    templateUrl: appUrlBuilder.buildTemplateUrl('digitalGiftCardModalTemplateUrl'),
                    backdrop: 'static',
                    controller: 'cartItemGiftCardCtrl',
                    windowClass: 'modal-vertical-centered giftcard-modal',
                    scope: $scope
                });
            }
        };

        $scope.removeGiftWrapFromCart = function (itemId, wrapId) {
            cartService.removeGiftWrapFromCart(itemId, wrapId);
        };
        $scope.doblur = function ($event) {
            $timeout(function () { $("#" + $event.target.id).trigger("blur"); }, 100);
        };
    }
    ]);;
'use strict';

/**
 * Lists the products that are in the cart.  Implements logic around changing of product details, such as the quantity.
 */
angular.module('cart').controller('cartItemWrapCtrl',
    ['$scope', '$window', '$modal', '$location', 'CartService', '$modalInstance', '$q',
    function ($scope, $window, $modal, $location, cartService, $modalInstance, $q) {

        $scope.giftWrapItems = '';
        $scope.giftWrapItem = {};
        $scope.showRadioError = false;
        $scope.showToError = false;
        $scope.isSubmitClick = true;

        $scope.getGiftWrapItems = function () {
            cartService.getGiftWrapItems().then(function (value) {
                $scope.giftWrapItems = value;
            });
        };

        $scope.getGiftWrapData = function (guid) {
            cartService.getGiftWrapData(guid).then(function (value) {
                $scope.giftWrapItem = value;
                $scope.giftWrapItem.WrapGuid = guid;
                $scope.giftWrapItem.currentItemId = value.ItemId;
            });
        };

        $scope.submitGiftWrapItem = function (data) {
            $scope.isSubmitClick = false;
            if ($scope.giftWrapModalCheckValidity()) {
                if (data.WrapGuid == null) {
                    $scope.addGiftWrapToCart(data);
                } else {
                    $scope.updateGiftWrapItem(data);
                }
            }
        }

        $scope.giftWrapModalCheckValidity = function () {
            var isCheckd = false;
            $('input:radio').each(function () {
                if ($(this).is(':checked')) {
                    isCheckd = true;
                }
            });
            var toValid = $scope.giftWrapItem.To && $scope.giftWrapItem.To.length > 0;

            $scope.showRadioError = !isCheckd;
            $scope.showToError = !toValid;

            if (!isCheckd || !toValid  ) {
                $scope.isSubmitClick = true;
                return false;
            }
            return true;
        }
       
        $scope.addGiftWrapToCart = function (data) {
            var itemData = {};

            angular.forEach($scope.giftWrapItems, function (value) {
                if (value.ItemId == data.ItemId) {
                    itemData.To = data.To;
                    itemData.From = data.From;
                    itemData.Message = data.Message;
                    itemData.Price = value.Price;
                    itemData.itemId = value.ItemId;
                    itemData.itemToWrap = $scope.$parent.item.Id;
                }
            });

            var deferred = $q.defer();
            cartService.addGiftWrapToCart(itemData).then(function (value) {
                if (value) {
                    deferred.resolve({});
                    $scope.close();
                } else {
                    deferred.reject('nothing was added');
                }
            }, function (error) { deferred.reject(error); });

            return deferred.promise;
        }

        $scope.updateGiftWrapItem = function (data) {
            var itemData = {};
            itemData.ItemIdChanged = false;

            angular.forEach($scope.giftWrapItems, function (value) {
                if (value.ItemId == data.ItemId) {
                    itemData.WrapGuid = data.WrapGuid;
                    itemData.To = data.To;
                    itemData.From = data.From;
                    itemData.Message = data.Message;
                    itemData.ItemId = value.ItemId;

                    if (itemData.ItemId != data.currentItemId) {
                        itemData.ItemIdChanged = true;
                    }
                }
            });

            var deferred = $q.defer();
            cartService.updateGiftWrap(itemData).then(function (value) {
                if (value) {
                    deferred.resolve({});
                    $scope.close();
                } else {
                    deferred.reject('nothing was added');
                }
            }, function (error) { deferred.reject(error); });

            return deferred.promise;
        }

        $scope.close = function () {
            $modalInstance.close();
        };

        $scope.getGiftWrapItems();

        if ($scope.CurrentWrapId != null) {
            $scope.getGiftWrapData($scope.CurrentWrapId);
        }
    }
    ]);

;
'use strict';

/**
 * Exposes the functionality that allows an end user to calculate the cost of shipping the items in the cart before purchasing it.
 */
angular.module('cart').controller('ShippingEstimateCtrl', ['$scope', 'ShippingService', 'spinnerFactory', 'AppObserver', 'CartDataStorageService',
function ($scope, shippingService, spinnerFactory, appObserver, cartDataStorageService) {

    setTimeout(function () {
        initOpenClose();
    }, 500);

    $scope.cartData = cartDataStorageService.cartData;
    $scope.estShipTaxBox = true;

    //broadcast postalCodeIsEmpty so the summary controller can show different taxes title (general: Taxes, specific: ON HST)
    var setPostalCode = function (value) {
        $scope.shippingPostalCode = value;
        appObserver.broadcast('postalCodeChanged', {
            postalCode: value
        });
    };
    //change shipping rate when reloadShippingRates event occur
    var cartItemListener = appObserver.subscribe('reloadShippingRates', $scope, function () {
        $scope.getShippingRates($scope.shippingRate);
    });

    $scope.initLoad = true;
    //setPostalCode($scope.cartData.addressInfo ? $scope.cartData.addressInfo.BillingAddress.PostalCode : '');
    setPostalCode($scope.cartData.addressInfo ? $scope.cartData.addressInfo.ShippingAddress.PostalCode : '');
    // use to control display postal code error message
    $scope.shippingPostalCodeValid = true;


    $scope.getShippingRates = function (shippingRateId) {
        shippingService.getShippingRates($scope.shippingCountry, '', $scope.shippingPostalCode, true).$promise.then(function (value) {
            $scope.shippingRates = value.shippingRates;
            // set first rate as default & update cart shipping amount
            if (shippingRateId && shippingService.ratesContain($scope.shippingRates, shippingRateId)) {
                $scope.shippingRate = shippingRateId;
            } else {
                $scope.shippingRate = $scope.shippingRates[0].Id;
            }
            $scope.updateShippingRate();
        });
    };

    $scope.shippingCountryChange = function () {
        setPostalCode('');
        $scope.shippingPostalCodeValid = true;
        $scope.getShippingRates($scope.shippingRate);
    };

    $scope.getShippingCountries = function () {
        shippingService.getShippingCountries().$promise.then(function (value) {
            $scope.shippingCountries = value.shippingCountries;
            // set first country as default if customer not sign in & reload shipping rate by calling getShippingRates();
            //var countryId = $scope.cartData.addressInfo ? $scope.cartData.addressInfo.BillingAddress.Country.CountryId : $scope.shippingCountries[0].Id;
            var countryId = $scope.getCountryIdAsPerZipCode($scope.shippingPostalCode);
            if (shippingService.countryContain($scope.shippingCountries, countryId)) {
                $scope.shippingCountry = countryId;
            } else {
                $scope.shippingCountry = $scope.shippingCountries[0].Id;
            }
            $scope.getShippingRates($scope.shippingRate);
        });
    };

    $scope.updateShippingAddress = function () {
        var countryId = $scope.getCountryIdAsPerZipCode($scope.shippingPostalCode);
        if (shippingService.countryContain($scope.shippingCountries, countryId)) {
            $scope.shippingCountry = countryId;
        } else {
            $scope.shippingCountry = $scope.shippingCountries[0].Id;
        }
        setPostalCode($scope.shippingPostalCode);
        shippingService.updateShippingAddress($scope.shippingCountry, $scope.shippingPostalCode, true, '', '', '', '', '').$promise.then(function (value) {
            if (value.Success) {
                $scope.getShippingRates($scope.shippingRate);
                $scope.shippingPostalCodeValid = true;

            } else {
                $scope.shippingPostalCodeValid = false;
                // this error message might need show up in the front
                console.log(value.Message);
            }
        }, function () {
            // console.log('updateShippingAddress error occur');
            $scope.shippingPostalCodeValid = false;
            // this error message might need show up in the front
            console.log("No results returned");
        });
    };

    $scope.updateShippingRate = function () {
        //update cart shipper id & reload cart data after rate change
        shippingService.updateShippingRate($scope.shippingRate).$promise.then(
            function (value) {
                //we have to merge cart items, because some of them might be reloaded
                cartDataStorageService.sync(value, true);
                spinnerFactory.hide();
                //don't broadcast shipping rate change when cart initial load
                if ($scope.initLoad) {
                    $scope.initLoad = false;
                } else {
                    //broadcast shippingRateChanged event, then summary controller can do something on shipping rate (fade in default: could change the behavior by modify fade-in class in common.less)
                    appObserver.broadcast('shippingRateChanged', {});
                }

                /* open estimate shipping and taxes if available on landing */               
                //if ($scope.cartData.totalShipping > 0 || $scope.cartData.totalTax > 0 || $scope.cartData.taxes.length > 0) {
                //    if (!$scope.estShipTaxBox) {
                //        $scope.estShipTaxBox = true;
                //    }
                //}
                //else if (!$scope.estShipTaxBox && $scope.cartData.totalTax == 0) {
                //        setTimeout(function () {
                //            $("#estShipTaxLink").click();
                //        }, 500);
                //        $scope.estShipTaxBox = true;
                //}

 
            },
            function () {
                spinnerFactory.hide();
            }
        );
    };

    //first time page initial load countries
    $scope.getShippingCountries();

    //Unbind listeners when scope is destroyed
    $scope.$on('$destroy', function () {
        cartItemListener();
    });

    $scope.getCountryIdAsPerZipCode = function (zipcode) {
        var canadaZipCodeRegExp = new RegExp('^(?!.*[DFIOQUdfioqu])[A-VXYa-vxy][0-9][A-Za-z] ?[0-9][A-Za-z][0-9]$');
        var usZipCodeRegExp = new RegExp('^([0-9]{5})(?:[-\s]*([0-9]{4}))?$');
        var counrtyId = $scope.shippingCountries[0].Id;
        if (canadaZipCodeRegExp.test(zipcode)) {
            counrtyId = $scope.getCountryId("Canada");
        }else if (usZipCodeRegExp.test(zipcode)) {
            counrtyId = $scope.getCountryId("United States");
        } else if ($scope.cartData.addressInfo != undefined) {
            counrtyId = $scope.cartData.addressInfo.BillingAddress.Country.CountryId;
        }
        return counrtyId;
    };

    $scope.getCountryId = function(countryName) {
        var countryId = 0;
        angular.forEach($scope.shippingCountries, function(shippingCountry) {
            if (shippingCountry.Name == countryName) {
                countryId = shippingCountry.Id;
            }
        });
        return countryId;
    };

}]);;
'use strict';

angular.module('cart').controller('CouponCtrl', [
    '$scope', 'CartService', 'siteRes',
    function ($scope, cartService, siteRes) {
        $scope.InvalidCouponCode = '';
        $scope.couponCode = '';
        $scope.coupons = '';
        $scope.applied = false;
        $scope.couponChecking = "";

        $scope.addCoupon = function () {
            if ($scope.couponCode === "") {
                $scope.couponChecking = "<span class='txtMsgRed'>Please enter your code</span>";
                return;
            }

            $scope.couponChecking = "<span class='txtMsgGreen'>Validating code, please wait...</span>";
            $scope.InvalidCouponCode = '';
            cartService.addCoupon($scope.couponCode).then(function (v) {
                if (v.Success) {
                    listCoupons(false);
                } else {
                    $scope.couponChecking = "<span class='txtMsgRed'>" + v.Message + "</span>";
                    $scope.couponCode = '';
                    $scope.InvalidCouponCode = $scope.couponCode + ' ' + siteRes.IsInvalid;
                }
            });
        };

        $scope.removeCoupon = function (couponCode) {
            cartService.removeCoupon(couponCode).then(function () {
                listCoupons(false);
            });
        };

        var listCoupons = function (startup) {
            cartService.listCoupons().then(function (value) {
                //debugger;
                if (!startup) {
                    $scope.applied = true;
                    var isFound = $scope.couponCode === ''; //if there is no coupon code - nothing was addded

                    angular.forEach(value, function (v) {
                        if (v.IsPerkOffer) {
                            console.log("IsPerkOffer: " + v.IsPerkOffer + " | PerkOfferCode: " + v.PerkOfferCode + " | PerkOfferDescription: " + v.PerkOfferDescription);
                        } else {
                            console.log("IsPerkOffer: " + v.IsPerkOffer + " | CouponCode: " + v.CouponCode);
                        }

                        if (v.CouponCode === $scope.couponCode ||
                            v.PerkOfferCode === $scope.couponCode ||
                            (v.PerkOfferCode !=='' &&$scope.couponCode.indexOf(v.PerkOfferCode) > -1)) {
                            isFound = true;
                        } 
                    });
                    
                    if (!isFound) {
                        $scope.InvalidCouponCode = $scope.couponCode + ' ' + siteRes.IsInvalid;
                        $scope.couponChecking = "<span class='txtMsgRed'>The code entered is invalid</span>";
                    } else {
                        $scope.couponChecking = "";
                    }
                }
                $scope.coupons = value;
                $scope.couponCode = '';

            });
        };

        listCoupons(true);
    }]);
;
'use strict';

/**
 * Lists the products that are in the cart.  Implements logic around changing of product details, such as the quantity.
 */
angular.module('cart').controller('cartItemGiftCardCtrl',
    ['$scope', '$window', '$modal', '$location', 'CartService', '$modalInstance', '$q', 'CartDataStorageService', 'AppObserver', 'spinnerFactory', 'WishListService', 'siteConfiguration', 'appUrlBuilder', 'DialogService', 'NavigationService',
    function ($scope, $window, $modal, $location, cartService, $modalInstance, $q, cartDataStorageService, appObserver, spinnerFactory, wishListService, siteConfiguration, appUrlBuilder, dialogService, navigationService) {

      
        $scope.giftCardItems = {};
        $scope.giftCardItem = {};
        $scope.digitalCardItem = {};
        $scope.giftCardItem.ItemId = $scope.$parent.item.ItemId;
        //$scope.giftCardItem.giftCardValue = $scope.$parent.item.ItemSubtotal; /* error */
        $scope.giftCardItem.giftCardValue = $scope.$parent.item.UnitPrice;
        $scope.giftCardItem.otherOption = (function () {
            switch ($scope.giftCardItem.giftCardValue) {
                case 25:
                case 50:
                case 100:
                    return 35;
                default:
                    return $scope.giftCardItem.giftCardValue;
            }
         }());
        $scope.giftCardType = $scope.$parent.item.GiftCardType;
        $scope.todayDate = new Date();
        $scope.dd = $scope.todayDate.getDate();
        $scope.mm = $scope.todayDate.getMonth() + 1;
        $scope.yy = $scope.todayDate.getFullYear();
        $scope.pastdate = false;
        $scope.errorDateMessage = "Delivery date should be greater than or equal to today's date";
        if ($scope.dd < 10)
            $scope.dd = "0" + $scope.dd;
        if ($scope.mm < 10)
            $scope.mm = "0" + $scope.mm;

        $scope.SelectAvailableOptions = [
             { value: 25, name: '$25' },
             { value: 50, name: '$50' },
             { value: 100, name: '$100' },
             { value: $scope.giftCardItem.otherOption, name: 'Other' }
        ];
        //$scope.$watch('giftCardItem.giftCardValue', function (number) {
        //    $scope.giftCardItem.giftCardValue = Number(number);
        //});


        $scope.getDigitalCardData = function (guid) {
            cartService.getDigitalCardData(guid).then(function (value) {
                $scope.digitalCardItem = value;
                if ($scope.digitalCardItem.GiftCard_DeliveryMethod == 'print') {
                    $scope.digitalCardItem.GiftCard_SenderName = 'N.A.';
                    $scope.digitalCardItem.GiftCard_DeliveryDate = $scope.mm +"/" + $scope.dd + "/" + $scope.yy;
                }
            });
        };


        $scope.getGiftCardItems = function () {
            cartService.getGiftCardItems().then(function (value) {
                $scope.giftCardItems = value;
            });
        };

        $scope.updateDigitalGiftCard = function (valid, data) {
            if (valid) {
                var itemData = {};
                if (data) {
                    itemData.GiftCard_Message = data.GiftCard_Message;
                    itemData.GiftCard_DeliveryMethod = data.GiftCard_DeliveryMethod;
                    itemData.GiftCard_SenderName = data.GiftCard_DeliveryMethod ==  'print' ? "N.A." :  data.GiftCard_SenderName;
                    itemData.GiftCard_RecipientName = data.GiftCard_RecipientName;
                    itemData.GiftCard_RecipientEmail = data.GiftCard_RecipientEmail;
                    itemData.GiftCard_DeliveryDate = data.GiftCard_DeliveryMethod == 'print' ? "11/11/1111" : data.GiftCard_DeliveryDate;
                    itemData.Id = $scope.$parent.item.Id;
                    itemData.productId = $scope.$parent.item.ProductId;
                    itemData.Price = data.Price;

                    if (itemData.Id != null && itemData.Id != '') {
                        var deferred = $q.defer();
                        cartService.updateDigitalGiftCard(itemData).then(function (value) {
                            if (value) {
                                deferred.resolve({});
                                $scope.close();
                                $window.location.reload();
                            } else {
                                deferred.reject('nothing was added');
                            }
                        }, function (error) { deferred.reject(error); });

                        return deferred.promise;
                    }
                }
            }


        };

        $scope.addGiftCardToCart = function (data) {
            var itemData = {};
            if (data) {
                angular.forEach($scope.giftCardItems, function(value)
                {
                    if (value.Items[0]._id == data.ItemId) {
                        itemData.price = data.giftCardValue;
                        itemData.productId = value.Items[0]._productId;
                        itemData.itemId = data.ItemId;
                        itemData.quantity = $scope.$parent.item.Quantity;
                        itemData.currentId = $scope.$parent.item.Id;
                    }
                });


                if (itemData.itemId != null && itemData.itemId != '') {
                    var deferred = $q.defer();
                    cartService.updatePhysicalGiftCard(itemData).then(function (value) {
                        if (value) {
                            deferred.resolve({});
                            $scope.close();
                        } else {
                            deferred.reject('nothing was added');
                        }
                    }, function (error) { deferred.reject(error); });

                    return deferred.promise;
                }
            } 
        
        };
    
        $scope.close = function () {
            $modalInstance.close();
        };

       
        if ($scope.giftCardType.toLowerCase() == 'digital') {
            $scope.getDigitalCardData($scope.$parent.item.Id);
        } else {
            $scope.getGiftCardItems();
        }

        $scope.checkPastDate = function () {
            var dateArr = $scope.digitalCardItem.GiftCard_DeliveryDate.split("/");
            $scope.pastdate = false;
            $scope.errorDateMessage = "Delivery date should be greater than or equal to today's date";
            if (dateArr.length >= 3) {
                var month = dateArr[0];
                var dd = dateArr[1];
                var year = dateArr[2];
                if (month > 12 || month < 0) {
                    $scope.pastdate = true;
                    $scope.errorDateMessage = "Please enter the delivery date in this format MM/DD/YYYY.";
                } else if (dd < 1 || dd > 31) {
                    $scope.pastdate = true;
                    $scope.errorDateMessage = "Please enter the delivery date in this format MM/DD/YYYY.";
                } else if (year >= $scope.yy) {
                    switch (month) {
                    case "01":
                    case "03":
                    case "05":
                    case "07":
                    case "08":
                    case "10":
                    case "12":
                        if (dd > 31) {
                            $scope.pastdate = true;
                            $scope.errorDateMessage = "Please enter the delivery date in this format MM/DD/YYYY.";
                        }
                        break;
                    case "02":
                        var x = (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
                        if ((x && dd > 29) || (!x && dd > 28)) {
                            $scope.pastdate = true;
                            $scope.errorDateMessage = "Please enter the delivery date in this format MM/DD/YYYY.";
                        }
                        break;
                    case "04":
                    case "06":
                    case "09":
                    case "11":
                        if (dd > 30) {
                            $scope.pastdate = true;
                            $scope.errorDateMessage = "Please enter the delivery date in this format MM/DD/YYYY.";
                        }
                        break;
                    }
                    if (!$scope.pastdate) {
                        if (month < 10)
                            month = "0" + month;
                        if (dd < 10)
                            dd = "0" + dd;
                        var enteredDate = new Date(month + "/" + dd + "/" + year);
                        var pasedTodayDate = Date.parse($scope.mm + "/" + $scope.dd + "/" + $scope.yy);
                        if (new Date(enteredDate) < new Date(pasedTodayDate)) {
                            $scope.pastdate = true;
                        }
                    }
                } else {
                    $scope.pastdate = true;
                }
            } else {
                $scope.pastdate = true;
            }
        }

    }
    ]);




// Post rendering call to style the controls
angular.module('cart').directive('post', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            if (!scope.hasItemCategoryItems || scope.$last) {
                $timeout(function () {
                    initCustomForms();

                }, 1000);
            }
        }
    }

}]);

angular.module('cart').directive('post6', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            if (!scope.hasItemCategoryItems || scope.$last) {
                $timeout(function () {
                    $("#GiftCard_DeliveryDate").datepicker();
                }, 1000);
            }
        }
    }

}]);



// Post rendering to sync gift value select and textbox
angular.module('cart').directive('post2', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            $timeout(function () {
                $('.amount-block #cardAmount').change(function () {
                    $('.amount-block .priceGiftCard').val($(this).val());
                });
            }, 0);

            $('.amount-block .priceGiftCard').blur(function () {
                if ($('.amount-block .priceGiftCard').val() < 5) {
                    $('.amount-block .priceGiftCard').val(5);
                }

                if ($('.amount-block .priceGiftCard').val() > 500) {
                    $('.amount-block .priceGiftCard').val(500);
                }
            });
        }
    }
}]);

// Post rendering to sync gift value select and textbox
angular.module('cart').directive('convertToNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            ngModel.$parsers.push(function (val) {
                return val != null ? parseInt(val, 10) : null;
            });
            ngModel.$formatters.push(function (val) {
                return val != null ? '' + val : null;
            });
        }
    };
});


;
/*exported WishList, sendWishListToFriend */
'use strict';

/**
 * WishList
 */
var WishList = (function ($, show, hide) {

    //constructor
    function WishList(constants, localization, dialogService) {
        this.constants = constants;
        this.localization = localization;
        this.dialogService = dialogService;
    }

    WishList.prototype.AddItem = function (itemId, onSuccess, onError) {

        var model = JSON.stringify({
            'ItemId': itemId
        });

        $.ajax({
            type: 'POST',
            url: window.rootRel + 'api/WishList/AddItem',
            contentType: 'application/json; charset=utf-8',
            data: model,
            dataType: 'json',
            success: function (data) {
                if (data.Success !== undefined && data.Success) {
                    onSuccess(data);
                }
                else {
                    onError(data);
                }
            },
            error: function (request, status, error) {
                onError(request, status, error);
            }
        });
    };

    var sendEmailToMyself = function (onSuccess, onError) {
        $.ajax({
            type: 'POST',
            url: window.rootRel + 'api/WishList/SendEmailToMySelf',
            contentType: 'application/json; charset=utf-8',
            data: {},
            dataType: 'json',
            success: function (data) {
                if (data !== undefined && data) {
                    onSuccess();
                }
                else {
                    onError();
                }
            },
            error: function (request, status, error) { // jshint ignore:line
                onError();
            }
        });
    };

    WishList.prototype.sendEmailToMyself = function () {
        var dialogService = this.dialogService;
        var localization = this.localization;
        show();
        sendEmailToMyself(function () {
            hide();
            ShowConfirmModal("Email sent successfully", localization.EmailWishlistSuccess);
            //dialogService.alert(localization.EmailWishlistSuccess);
        }, function () {
            hide();
            ShowConfirmModal("Unable to send email", localization.EmailWishlistError);
            //dialogService.alert(localization.EmailWishlistError);
        });
    };

    WishList.prototype.sendEmailToFriend = function (yourname, recipientName, recipientEmail) {
        var dialogService = this.dialogService;
        var localization = this.localization;

        show();
        sendEmailToFriend(yourname, recipientName, recipientEmail, function () {
            hide();
            //dialogService.alert(localization.EmailWishlistSuccess);
            ShowConfirmModal("Email sent successfully", localization.EmailWishlistSuccess);
        }, function () {
            hide();
            //dialogService.alert(localization.EmailWishlistError);
            ShowConfirmModal("Unable to send email", localization.EmailWishlistError);
        });
    };

    var sendEmailToFriend = function (yourname, recipientName,recipientEmail, onSuccess, onError) {
        var model = JSON.stringify({
            'YourName': yourname,
            'RecipientName': recipientName,
            'RecipientEmail': recipientEmail,
        });
        $.ajax({
            type: 'POST',
            url: window.rootRel + 'api/WishList/SendWishEmailToFriend',
            contentType: 'application/json; charset=utf-8',
            data: model,
            dataType: 'json',
            success: function (data) {
                if (data.Success !== undefined && data.Success) {
                    onSuccess();
                }
                else {
                    onError();
                }
            },
            error: function (request, status, error) { 
                onError();
            }
        });
    };

    return WishList;

})(jQuery, window.openSpinner, window.closeSpinner);


$(".wish-friend-popup .toFriend").click(function (e) {
    e.preventDefault();
    var ancester = $(this).closest(".wish-friend-popup");

    var _this = $(this);
    var _form = _this.closest("form");
    var validator = _form.validate();
    var anyError = false;

    _form.find("input").each(function () {
        if (!validator.element(this)) {
            anyError = true;
            var errormsg = $(this).attr("data-val-required");
            if ($(this).attr("type") == "email" && $(this).val() != "") {
                errormsg = $(this).attr("data-val-regex");
            }
            $(this).parent().find("span").text(errormsg);
        }
    });

    if (!anyError) {
        var yourname = ancester.find('#txtYourname').val()
        var recipientName = ancester.find('#txtRecipientName').val();
        var recipientEmail = ancester.find('#txtRecipientEmail').val();

        ancester.find(".close").trigger("click");
        var wishList = new WishList(window.globalConstants, window.res, window.BootstrapDialog);
        wishList.sendEmailToFriend(yourname, recipientName, recipientEmail);
    }

    return false;
});

$(".wish-friend-popup .toMyself").click(function (e) {
    e.preventDefault();
    var ancester = $(this).closest(".wish-friend-popup");

    ancester.find(".close").trigger("click");
    var wishList = new WishList(window.globalConstants, window.res, window.BootstrapDialog);
    wishList.sendEmailToMyself();
    return false;
});;
'use strict';

/**
 * Responsible for all cart specific communication with the server
 */
angular.module('checkout').factory('CheckoutSvc', ['$resource', 'appUrlBuilder', 'siteRes', 'DialogService', 'NavigationService',
	function ($resource, appUrlBuilder, siteRes, dialogService, navigationService) {

		var resource = $resource(appUrlBuilder.buildUrl('checkoutApiUrl'), null, {
            'submitCart': { method: 'GET', url: appUrlBuilder.buildUrl('submitCartApiUrl'), isArray: false, responseType: 'json' },
            'submitCartRIS': { method: 'GET', url: appUrlBuilder.buildUrl('submitCartRISApiUrl'), isArray: false, responseType: 'json' },
            'createRISGuestAccount': { method: 'PUT', url: appUrlBuilder.buildUrl('createRISGuestAccountUrl'), isArray: false, responseType: 'json' },
            'selectStoreRIS': { method: 'GET', url: appUrlBuilder.buildUrl('selectStoreRISApiUrl'), isArray: false, responseType: 'json' },
			'checkOrderStatus': { method: 'GET', url: appUrlBuilder.buildUrl('checkOrderStatusApiUrl'), isArray: false, responseType: 'json' },
			'addCreditCardPayment': { method: 'PUT', url: appUrlBuilder.buildUrl('addCreditCardPaymentUrl'), isArray: false, responseType: 'json' },
			'addExistingCreditCardPayment': { method: 'PUT', url: appUrlBuilder.buildUrl('addExistingCreditCardPaymentUrl'), isArray: false, responseType: 'json' },
			'addPayPalOption': { method: 'PUT', url: appUrlBuilder.buildUrl('addMMTPayPalOptionUrl'), isArray: false, responseType: 'json' },
			'getCreditCardTypes': { method: 'GET', url: appUrlBuilder.buildUrl('getCreditCardTypesApiUrl'), isArray: true, responseType: 'json' },
			'verifyThreeDs': { method: 'GET', url: appUrlBuilder.buildUrl('threeDsVerifyApiUrl'), isArray: false, responseType: 'json' },
			'getGiftCardSettings': { method: 'GET', url: appUrlBuilder.buildUrl('getGiftCardSettingsApiUrl'), isArray: false, responseType: 'json' },
			'getOrderFormGiftcards': { method: 'GET', url: appUrlBuilder.buildUrl('getOrderFormGiftcardsApiUrl'), isArray: true, responseType: 'json' },
			'getOrderFormPayments': { method: 'GET', url: appUrlBuilder.buildUrl('getOrderFormPaymentsApiUrl'), isArray: true, responseType: 'json' },
			'getGiftCardBalance': { method: 'GET', url: appUrlBuilder.buildUrl('getGiftCardBalanceApiUrl'), isArray: false, responseType: 'json' },
			'addGiftCardsToOrderForm': { method: 'PUT', url: appUrlBuilder.buildUrl('addGiftCardsToOrderFormApiUrl'), isArray: false, responseType: 'json' },
			'addReceiverMiscInfoToOrderForm': { method: 'PUT', url: appUrlBuilder.buildUrl('addReceiverMiscInfoToOrderFormApiUrl'), isArray: false, responseType: 'json' },
			'addAddressDataToOrderForm': { method: 'PUT', url: appUrlBuilder.buildUrl('addAddressDataToOrderFormApiUrl'), isArray: false, responseType: 'json' },
			'getCustomerCheckoutAddresses': { method: 'GET', url: appUrlBuilder.buildUrl('getCustomerAddressesUrl'), isArray: true, responseType: 'json' },
			'setCurrentOrderForm': { method: 'GET', url: appUrlBuilder.buildUrl('setCurrentOrderFormApiUrl'), isArray: false, responseType: 'json' },
			'proceedToPlaceOrder': { method: 'GET', url: appUrlBuilder.buildUrl('proceedToPlaceOrderUrl'), isArray: false, responseType: 'json' },
			'loadItemsStoreInventoryData': { method: 'GET', url: appUrlBuilder.buildUrl('loadItemsStoreInventoryDataUrl'), isArray: true, responseType: 'json' },
            'validateCaptcha': { method: 'GET', url: appUrlBuilder.buildUrl('validateCaptchaUrl'), isArray: false, responseType: 'json' },
            'submitPerkCode': { method: 'GET', url: appUrlBuilder.buildUrl('submitPerkCodeUrl'), isArray: false, responseType: 'json' },
            'cancelPerkCode': { method: 'GET', url: appUrlBuilder.buildUrl('cancelPerkCodeUrl'), isArray: false, responseType: 'json' }
		});

		return {
			submitCart: function (ignore3Ds) {
				return resource.submitCart({ ignore3Ds: ignore3Ds });
            },
			submitCartRIS: function () {
			    return resource.submitCartRIS();
            },
			selectStoreRIS: function (storeId) {
                return resource.selectStoreRIS({ storeId: storeId });
			},
			checkOrderStatus: function (orderId) {
				return resource.checkOrderStatus({ orderId: orderId });
			},
			addCreditCardPayment: function (card) {
				return resource.addCreditCardPayment(card);
			},
			addExistingCreditCardPayment: function (card) {
				return resource.addExistingCreditCardPayment(card);
			},
			addPaypalOption: function () {
				return resource.addPayPalOption();
			},
			getCreditCardTypes: function () {
				return resource.getCreditCardTypes();
			},
			confirmDialog: function () {
				dialogService.show({
					title: siteRes.CheckoutReally,
					message: siteRes.CheckoutCancelMessage,
					buttons: [
						{
							label: siteRes.CheckoutGoback,
							cssClass: 'btn-primary',
							action: function (dialog) {
								dialog.close();
							}
						}, {
							label: siteRes.CheckoutSaveforlater,
							cssClass: 'btn-default',
							action: function () {
								navigationService.navigate(appUrlBuilder.buildUrl('homePageUrl'));
							}
						}
					]
				});
			},
			hpciEnabled: function () {
				//Instead of make another call to WebApi we just check if the 'sendHPCI' function exists.
				return (typeof (window.sendHPCI) == 'function');
			},
			processHpci: function (callBack) {
				window.sendHPCI(callBack);
			},
			alertDialog: function (errorMessage) {
				dialogService.alert(errorMessage);
			},
			verifyThreeDs: function () {
				return resource.verifyThreeDs();
			},
			getThreeDsNotifierUrl: function () {
				return appUrlBuilder.buildUrl('threeDsNotifierUrl');
			},
			getThreeDsVerificationUrl: function () {
				return appUrlBuilder.buildUrl('threeDsVerifierUrl');
			},
			getGiftCardSettings: function () {
				return resource.getGiftCardSettings();
			},
			parseQueryString: function (querystring, key) {
				key = key.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
				var regex = new RegExp('[\\?&]' + key + '=([^&#]*)'),
					results = regex.exec(querystring);
				return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
			},
			getOrderFormPayments: function () {
				return resource.getOrderFormPayments();
			},
			getOrderFormGiftcards: function () {
				return resource.getOrderFormGiftcards();
			},
			getGiftCardBalance: function (cardNumber, cardPin) {
				return resource.getGiftCardBalance({ cardNumber: cardNumber, cardPin: cardPin });
			},
			addGiftCardsToOrderForm: function (cards) {
				return resource.addGiftCardsToOrderForm(cards);
			},
			addReceiverMiscInfoToOrderForm: function (receiverMiscInfo) {
				return resource.addReceiverMiscInfoToOrderForm(receiverMiscInfo);
			},
			addAddressDataToOrderForm: function (shippingAddress, billingAddress, sameAsShippingAddress) {
				return resource.addAddressDataToOrderForm({
					shippingAddress: shippingAddress, billingAddress: billingAddress, sameAsShippingAddress: sameAsShippingAddress
				});
			},
			alert3DsError: function () {
				dialogService.alert(siteRes.ThreeDSAuthFailedMessage);
			},
			getCustomerAddresses: function () {
				return resource.getCustomerCheckoutAddresses();
			},
			setCurrentOrderForm: function (orderId) {
				return resource.setCurrentOrderForm({ orderId: orderId });
			},
			proceedToPlaceOrder: function () {
				return resource.proceedToPlaceOrder();
			},
			loadItemsStoreInventoryData: function (lat, lng, items) {
				var data = resource.loadItemsStoreInventoryData({ itemIds: items, lat: lat, lng: lng, range: 30 });
				return data;
			},
			validateCaptcha: function (response) {
				var data = resource.validateCaptcha({ response: response });
				return data;
            },
			createRISGuestAccount: function (data) {
			    var args = { email: data.email, firstname: data.firstName, lastname: data.lastName, phone: data.phone };
			    return resource.createRISGuestAccount(args);
            },
			submitPerkCode: function (code) {
                return resource.submitPerkCode({ code: code });
            },
			cancelPerkCode: function (code) {
			    return resource.cancelPerkCode({ code: code });
			}
		};
	}
]);;
'use strict';

/**
 * Responsible for all cart specific communication with the server
 */
angular.module('checkout').factory('CheckoutSubmitCartSvc', ['$q', '$timeout', 'appUrlBuilder', 'siteConfiguration', 'siteRes', 'CheckoutSvc', 'CheckoutDataStorageService', 'spinnerFactory', 'NavigationService', 'AddressDataHelper', 'CheckoutCreditCardValidationService', 'accountSvc', 'CartDataStorageService', 'CheckoutHelperService', '$resource',
    function ($q, $timeout, appUrlBuilder, siteConfiguration, siteRes, checkoutSvc, checkoutDataStorageService, spinnerFactory, navigationService, addressDataHelper, checkoutCreditCardValidationService, accountSvc, cartDataStorageService, checkoutHelperService, $resource) {

        var resource = $resource(appUrlBuilder.buildUrl('checkoutApiUrl'), null, {
            'addPaymentPhoneNumber': { method: 'PUT', url: appUrlBuilder.buildUrl('checkoutPaymentPhoneNumberURL'), isArray: false, responseType: 'json' }
        });

        var addPaypalOption = function (signedIn, giftCards) {
            spinnerFactory.show("Please wait...");
            if (signedIn) {
                if (giftCards !== undefined && giftCards !== null && giftCards.length > 0) {
                    addGiftCardsPayPalPaymentThenSubmit(giftCards);
                } else {
                    addPayPalPaymentThenSubmit();
                }
            } else {
                checkoutDataStorageService.checkoutState.createAccountSec = true;
                spinnerFactory.hide();
            }
        };

        var addPayPalPaymentThenSubmit = function () {            
            var deferred = $q.defer();
            checkoutSvc.addPaypalOption().$promise.then(
                function (value) {
                    navigationService.navigate(appUrlBuilder.buildUrl('PayPalSubmitCartUrl'));
                }, function (error) {
                    spinnerFactory.hide();
                    deferred.reject(error);
                });
        };

        var addGiftCardsPayPalPaymentThenSubmit = function (giftCards) {
            addGiftCards(giftCards).then(
                function () {
                    spinnerFactory.hide();
                    addPayPalPaymentThenSubmit();
                },
                function (error) {
                    spinnerFactory.hide();
                    checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;
                    checkoutDataStorageService.checkoutState.errorMessage = error;
                });
        };

        var addGiftCards = function (giftCardData) {
            var deferred = $q.defer();
            spinnerFactory.show("Please wait...");
            checkoutSvc.addGiftCardsToOrderForm(giftCardData).$promise.then(
                function (value) {
                    deferred.resolve(value);
                }, function (error) {
                    deferred.reject(error);
                });
            return deferred.promise;
        };

        var addGiftCardsCreditCardPaymentThenSubmit = function (giftCards, creditCardData, cartData) {
            addGiftCards(giftCards).then(
                function () {
                    spinnerFactory.hide();
                    addCreditCardPaymentThenSubmit(creditCardData, cartData);
                },
                function (error) {
                    spinnerFactory.hide();
                    checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;
                    checkoutDataStorageService.checkoutState.errorMessage = error;
                });
        };

        var addCreditCardPaymentThenSubmit = function (creditCardData, cartData) {
            addCreditCardPayment(creditCardData).then(
                function () {
                    spinnerFactory.hide();
                    var paymentInfo = {
                        guestAccount: !cartData.signedIn,
                        paymentType: 1,
                        paymentAdded: true,
                        ignore3Ds: false
                    };
                    submitCart(paymentInfo);
                },
                function (error) {
                    spinnerFactory.hide();
                    checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;
                    checkoutDataStorageService.checkoutState.errorMessage = siteRes.SubmitCartFailByCreditCard + error;
                    console.log(error);
                });
        };

        var addCreditCardPayment = function (creditCardData) {
            var deferred = $q.defer();
            spinnerFactory.show("Please wait...");
            checkoutSvc.addCreditCardPayment(creditCardData).$promise.then(
                function (value) {
                    deferred.resolve(value);
                }, function (error) {
                    deferred.reject(error);
                });
            return deferred.promise;
        };

        var payByGiftValidate = function (giftCards, cartData) {
            if (giftCards !== undefined && giftCards !== null && giftCards.length > 0) {
                if (checkoutHelperService.getGiftCardAmounts(giftCards) >= Number(cartData.total)) {
                    return true;
                } else {
                    checkoutDataStorageService.checkoutState.errorMessage = siteRes.GiftCardAmountLessThanCartTotal;
                    return false;
                }
            } else {
                checkoutDataStorageService.checkoutState.errorMessage = siteRes.EnterGiftCard;
                return false;
            }
        };

        var addGiftCardsPaymentThenSubmit = function (giftCards, cartData) {
            var paymentInfo = {
                guestAccount: !cartData.signedIn,
                paymentType: 0,
                paymentAdded: true,
                ignore3Ds: false
            };
            if (payByGiftValidate(giftCards, cartData)) {
                addGiftCards(giftCards).then(
                    function () {
                        spinnerFactory.hide();
                        submitCart(paymentInfo);
                    },
                    function (error) {
                        spinnerFactory.hide();
                        checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;
                        checkoutDataStorageService.checkoutState.errorMessage = siteRes.SubmitCartFailByCreditCard + error;
                    });
            } else {
                submitCartFail(paymentInfo);
                spinnerFactory.hide();
            }
        };



        var submitCartFail = function (paymentInfo, error) {           
            checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;
            if (error) {                
                checkoutDataStorageService.checkoutState.errorMessage = error;
            }
            if (paymentInfo.guestAccount && paymentInfo.paymentType == 1) {
                console.log('submit cart return value is false, need error message here');
            } else {
                //paypal fa
            }
            checkoutDataStorageService.checkoutState.billingSec = false;
            checkoutDataStorageService.checkoutState.paymentSec = true;
            checkoutDataStorageService.checkoutState.createAccountSec = false;
            checkoutDataStorageService.checkoutState.accountPasswordSec = false;
            checkoutDataStorageService.checkoutState.retryEmailSec = false;
        };

        var checkOrderStatus = function (orderId, tries) {
            var deferred = $q.defer();
            checkoutSvc.checkOrderStatus(orderId).$promise.then(
                function (value) {
                    if (value.Success === true) {
                        navigationService.navigate(appUrlBuilder.buildUrl('confirmationPageUrl') + '/' + value.OrderId);
                    } else {
                        if (tries === 0) {

                            //bvc - checkout changes
                            checkoutSvc.setCurrentOrderForm(orderId).$promise.then(
                                function (d) {
                                    if (!d.Success) {
                                        spinnerFactory.hide();
                                        checkoutDataStorageService.checkoutState.newCreditCardError = true;
                                        if (checkoutDataStorageService.checkoutState.paymentType === 1 || checkoutDataStorageService.checkoutState.paymentType === 4) {
                                            $timeout(function () {
                                                $(".editCCPaymentLink").click();
                                            }, 500);
                                        }
                                        submitCartFail({ guestAccount: false, paymentType: 1, ignore3Ds: true }, d.Error);
                                    } else {
                                        navigationService.navigate(appUrlBuilder.buildUrl('confirmationPageUrl') + '/' + orderId);
                                    }
                                });

                        } else {
                            $timeout(function () {
                                tries = tries - 1;
                                checkOrderStatus(value.OrderId, tries);
                            }, 10000); 
                        }
                    }
                },
                function (error) {
                    spinnerFactory.hide();
                    submitCartFail({ guestAccount: false, paymentType: 1, ignore3Ds: true }, error);
                    deferred.reject(error);
                }
            );
            return deferred.promise;
        };

        var submitCart = function (paymentInfo) {
            var deferred = $q.defer();
            spinnerFactory.show("Please wait...");
            disableScrollOnSpinnerShow();
            //spinnerFactory.show(siteRes.OrderSubmitMessage);
            checkoutSvc.submitCart(paymentInfo.ignore3Ds).$promise.then(
                function (value) {
                    if (value.Success === true) {                         
                        //Check order status and wait until it successfully
                        checkOrderStatus(value.OrderId, siteConfiguration.timesToCheckSubmitedOrder);
                    } else {                        

                        if (value.Enforce3Ds === true) {
                            checkoutDataStorageService.checkoutState.show3Ds = true;
                            checkoutDataStorageService.checkoutState.threeDsNotifierUrl = checkoutSvc.getThreeDsNotifierUrl();
                        } else {
                            if (value.ErrorMessage == "CartError") {
                                navigationService.navigate(appUrlBuilder.buildUrl('shoppingCartPageUrl'));
                            } else {
                                submitCartFail(paymentInfo, value.ErrorMessage);
                            }
                        }

                        spinnerFactory.hide();
                        enableScrollOnSpinnerHide();
                    }
                },
                function (error) {                    
                    spinnerFactory.hide();
                    enableScrollOnSpinnerHide();
                    //to do : go back to payment section in checkoutpage
                    deferred.reject(error);
                }
            );
            return deferred.promise;
        };

        var readyToPay = function (checkoutState, cartData) {
            if (checkoutState.paymentType === 1 || checkoutState.paymentType === 0) {
                if (checkoutState.paymentType === 1 && checkoutCreditCardValidationService.isCardValid(checkoutState) || checkoutState.paymentType === 0) {
                    processCreditCardPayment(checkoutState, cartData);
                }
            }
            if (checkoutState.paymentType === 2) {
                addPaypalOption(cartData.signedIn, checkoutState.giftCards);
            }
            if (checkoutState.paymentType === 3) {
                processExistingCreditCardPayment(checkoutState, cartData);
            }

            //happy card
            if (checkoutState.paymentType === 4) {
                processCreditCardPayment(checkoutState, cartData);
            }
        };

        var processExistingCreditCardPayment = function (checkoutState, cartData) {
            //hide payment section show billing section
            checkoutState.paymentSec = false;
            checkoutState.billingSec = true;            
            if (cartData.signedIn) {
                //debugger;
                if (addressDataHelper.getSameAsShippingAddress()) {
                    checkoutSvc.addAddressDataToOrderForm(addressDataHelper.getShippingData(), addressDataHelper.getBillingData(), addressDataHelper.getSameAsShippingAddress()).$promise.then(
                        function () {
                            addGiftCardsExistingCreditCardPaymentThenSubmit(checkoutState.giftCards, checkoutState.existingCreditCardData, cartData, checkoutState);
                        }, function (error) {
                            console.log(error);
                        });
                } else {
                    addGiftCardsExistingCreditCardPaymentThenSubmit(checkoutState.giftCards, checkoutState.existingCreditCardData, cartData, checkoutState);
                }
            } else {
                accountSvc.createAccount(checkoutState.customerData).$promise.then(
                    function () {
                        if (addressDataHelper.getSameAsShippingAddress()) {
                            checkoutSvc.addAddressDataToOrderForm(addressDataHelper.getShippingData(), addressDataHelper.getBillingData(), addressDataHelper.getSameAsShippingAddress()).$promise.then(
                                function () {
                                    addGiftCardsExistingCreditCardPaymentThenSubmit(checkoutState.giftCards, checkoutState.existingCreditCardData, cartData, checkoutState);
                                }, function (error) {
                                    console.log(error);
                                });
                        } else {
                            addGiftCardsExistingCreditCardPaymentThenSubmit(checkoutState.giftCards, checkoutState.existingCreditCardData, cartData, checkoutState);
                        }

                    }, function (error) {
                        console.log(error);
                    });
            }
            //window.scrollNextStep('step-4');
            //checkoutState.bouclairCheckoutCurrentStage = 3;
        };

        var addGiftCardsExistingCreditCardPaymentThenSubmit = function (giftCards, existingCreditCardData, cartData, checkoutState) {
            addGiftCards(giftCards).then(
                function () {
                    spinnerFactory.hide();
                    addExistingCreditCardPaymentThenSubmit(existingCreditCardData, cartData, checkoutState);
                },
                function (error) {
                    spinnerFactory.hide();
                    checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;
                    checkoutDataStorageService.checkoutState.errorMessage = error;
                });
        };

        var addExistingCreditCardPaymentThenSubmit = function (existingCreditCardData, cartData, checkoutState) {
            checkoutSvc.addExistingCreditCardPayment(existingCreditCardData).$promise.then(
                function () {
                    spinnerFactory.hide();
                    var paymentInfo = {
                        guestAccount: !cartData.signedIn,
                        paymentType: 1,
                        paymentAdded: true,
                        ignore3Ds: false
                    };
                    submitCart(paymentInfo, checkoutState);
                },
                function (error) {                    
                    spinnerFactory.hide();
                    checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;

                    checkoutDataStorageService.checkoutState.errorMessage = siteRes.SubmitCartFailByCreditCard + error;
                    console.log(error);
                });
        };
        //public methods

        var submitGuestOrder = function (customerData, checkoutState, cartData) {
            accountSvc.createAccount(customerData).$promise.then(
                function () {
                    checkoutSvc.addAddressDataToOrderForm(addressDataHelper.getShippingData(), addressDataHelper.getBillingData(), addressDataHelper.getSameAsShippingAddress()).$promise.then(
                        function () {
                            if (!addressDataHelper.getSameAsShippingAddress()) {
                                cartDataStorageService.loadCartData();
                            }
                            checkoutState.accountPasswordSec = false;
                            checkoutState.retryEmailSec = false;

                            if (checkoutState.giftCards !== undefined && checkoutState.giftCards.length > 0) {
                                if (checkoutState.paymentType === 0) {
                                    addGiftCardsPaymentThenSubmit(checkoutState.giftCards, cartData);
                                }
                                if (checkoutState.paymentType === 1) {
                                    addGiftCardsCreditCardPaymentThenSubmit(checkoutState.giftCards, checkoutState.creditCardData, cartData);
                                }
                                if (checkoutState.paymentType === 2) {
                                    addGiftCardsPayPalPaymentThenSubmit(checkoutState.giftCards);
                                }
                            } else {
                                if (checkoutState.paymentType === 1) {
                                    addCreditCardPaymentThenSubmit(checkoutState.creditCardData, cartData);
                                }
                                if (checkoutState.paymentType === 2) {
                                    addPayPalPaymentThenSubmit();
                                }

                                //happy card
                                if (checkoutState.paymentType === 4) {
                                    addCreditCardPaymentThenSubmit(checkoutState.creditCardData, cartData);
                                }

                            }
                        }, function (error) {
                            console.log(error);
                        });

                }, function (error) {
                    //todo when create account fail let user reEnter email if email exists already
                    console.log(error);
                    checkoutState.accountPasswordSec = false;
                    checkoutState.retryEmailSec = true;
                });
        };

        var submitOrder = function (checkoutState, cartData) {

            if (cartData.signedIn && cartData.total === 0) {
                //bvc perk new - no payment required if order total is 0
                var paymentInfo = {
                    guestAccount: false,
                    paymentType: 2,
                    paymentAdded: false,
                    ignore3Ds: false
                };
                submitCart(paymentInfo, checkoutState);

            } else if (checkoutState.paymentType === 0) {
                if (cartData.signedIn) {
                    checkoutState.paymentSec = false;
                    checkoutState.billingSec = true;
                    addGiftCardsPaymentThenSubmit(checkoutState.giftCards, cartData);
                } else {
                    if (payByGiftValidate(checkoutState.giftCards, cartData)) {
                        readyToPay(checkoutState, cartData);
                    } else {
                        checkoutState.sumitCartErrorSec = true;
                    }
                }
            } else {
                readyToPay(checkoutState, cartData);
            }
        };

        var processCreditCardPayment = function (checkoutState, cartData) {
            if ((checkoutState.paymentType === 1 || checkoutState.paymentType === 4) && checkoutSvc.hpciEnabled() === true && checkoutState.hpciProcessed === false) {
                checkoutSvc.processHpci(function (e) {
                    checkoutSvc.alertDialog(e);
                });
            } else {
                //hide payment section show billing section
                checkoutState.paymentSec = false;
                checkoutState.billingSec = true;
                if (cartData.signedIn) {
                    if (addressDataHelper.getSameAsShippingAddress()) {
                        checkoutSvc.addAddressDataToOrderForm(addressDataHelper.getShippingData(), addressDataHelper.getBillingData(), addressDataHelper.getSameAsShippingAddress()).$promise.then(
                            function () {
                                addGiftCardsCreditCardPaymentThenSubmit(checkoutState.giftCards, checkoutState.creditCardData, cartData);
                            }, function (error) {
                                console.log(error);
                            });
                    } else {
                        addGiftCardsCreditCardPaymentThenSubmit(checkoutState.giftCards, checkoutState.creditCardData, cartData);
                    }
                } else {
                    //show create account section  when payment info added
                    checkoutState.createAccountSec = true;
                }
            }
        };

        var verify3Ds = function (checkoutState) {
            var deferred = $q.defer();
            checkoutSvc.verifyThreeDs().$promise.then(
                function (value) {
                    if (value.submitCart === true) {
                        checkoutState.show3Ds = false;
                        checkoutState.pass3Ds = true;
                        submitCart({ guestAccount: false, paymentType: 1, ignore3Ds: true });
                    } else {
                        checkoutState.sumitCartErrorSec = true;
                        checkoutState.billingSec = false;
                        checkoutState.paymentSec = true;
                        checkoutState.createAccountSec = false;
                        checkoutState.accountPasswordSec = false;
                        checkoutState.retryEmailSec = false;
                        checkoutState.show3Ds = false;
                        checkoutState.pass3Ds = false;
                        checkoutSvc.alert3DsError();
                        checkoutState.threeDsNotifierUrl = '';
                    }
                    deferred.resolve(value);
                }, function (error) {
                    deferred.reject(error);
                });
            return deferred.promise;
        };

        return {
            processCreditCardPayment: processCreditCardPayment,
            verify3Ds: verify3Ds,
            submitGuestOrder: submitGuestOrder,
            submitOrder: submitOrder,
            addPaymentPhoneNumber: function (paymentPhoneNumer) {
                return resource.addPaymentPhoneNumber({ PaymentPhoneNumber: paymentPhoneNumer });
            }
        };
    }
]);;
'use strict';

/**
 * Instance of a shopping cart modal window. 
 */
angular.module('checkout').controller('mmtcheckoutInstanceCtrl', ['$scope', '$modalInstance',
    function ($scope, $modalInstance) {
        $scope.close = function () {
            $modalInstance.close();
            jQuery('body').attr('style', 'overflow:auto');
        };
    }]);

/**
 * Instance of a shopping cart modal window. 
 */
angular.module('checkout').controller('mmtcheckoutUpsInstanceCtrl', ['$scope', '$modalInstance','$timeout',
    function ($scope, $modalInstance,$timeout) {

        $scope.GetUpsLocation();
        $scope.initMap();

        $scope.submit = function () {
            $scope.SubmitUpsStoreLocation();
            $timeout(function () {
                $scope.close();
            }, 100);
        };
        $scope.close = function () {
            if ($('body').hasClass('store-checkout')) {
                $('body').removeClass('store-checkout');
            }
            $modalInstance.close();
            jQuery('body').attr('style', 'overflow:auto');
        };
    }]);;
'use strict';

angular.module('checkout').controller('GiftCardCtrl',
    ['$scope', '$q', 'appUrlBuilder', 'CheckoutSvc', 'siteConfiguration', 'AppObserver', 'CheckoutDataStorageService', 'CheckoutHelperService',
    function ($scope, $q, appUrlBuilder, checkoutSvc, siteConfiguration, appObserver, checkoutDataStorageService, checkoutHelperService) {

        $scope.imageUrl = appUrlBuilder.buildUrl('giftCardGrayImageUrl');

        $scope.data = {};
        $scope.checkoutState = checkoutDataStorageService.checkoutState;
        $scope.data.cardNumber = '';
        $scope.data.pin = '';
        $scope.isGiftCardFormSubmitted = false;

        $scope.giftCardSetting = {};

        $scope.cardNumber = '';
        $scope.balance = 0;
        $scope.amountToApply = 0;
        $scope.applyType = 'all';
        $scope.pin = '';
        $scope.editCardNumber = '';
        $scope.isAmountValid = true;

        $scope.isGiftCardValid = true;
        $scope.isGiftCardBalanceZero = false;
        $scope.balanceOverAmount = false;

        $scope.loadGiftCardSetting = function () {
            var deferred = $q.defer();
            checkoutSvc.getGiftCardSettings().$promise.then(
                 function (value) {

                     $scope.giftCardSetting.EnableGiftCard = value.EnableGiftCard;
                     $scope.giftCardSetting.EnablePinSupport = value.EnablePinSupport;
                     $scope.giftCardSetting.EnableMultipleGiftCard = value.EnableMultipleGiftCard;
                     if (value.EnableMultipleGiftCard === true) {
                         $scope.giftCardSetting.MaxCardsSupported = value.MaxCardsSupported;
                     } else {
                         $scope.giftCardSetting.MaxCardsSupported = 1;
                     }
                     deferred.resolve(value);
                 }, function (error) {
                     deferred.reject(error);
                 });
            return deferred.promise;
        };

        $scope.getOrderFormGiftcards = function () {
            var deferred = $q.defer();
            checkoutSvc.getOrderFormGiftcards().$promise.then(
                 function (value) {
                     $scope.checkoutState.giftCards = value;
                     deferred.resolve(value);
                 }, function (error) {
                     deferred.reject(error);
                 });
            return deferred.promise;
        };

        $scope.getGiftCardBalance = function () {
            $scope.isGiftCardFormSubmitted = false;

            //in case it is in edit mode;
            $scope.editCardNumber = '';
            $scope.isGiftCardValid = true;
            $scope.isGiftCardBalanceZero = false;
            $scope.balanceOverAmount = false;
            if ($scope.data.cardNumber.length === 0 || ($scope.giftCardSetting.EnablePinSupport === true && $scope.data.pin.length === 0)) {
                $scope.isGiftCardFormSubmitted = true;
                return null;
            }

            var deferred = $q.defer();
            checkoutSvc.getGiftCardBalance($scope.data.cardNumber, $scope.data.pin).$promise.then(
                 function (value) {

                     if (value.Balance === 0) {
                         if (value.Type === 'Approved') {
                             $scope.isGiftCardBalanceZero = true;
                             $scope.isGiftCardValid = true;
                         } else {
                             $scope.isGiftCardBalanceZero = false;
                             $scope.isGiftCardValid = false;
                         }

                     } else {
                         $scope.balance = value.Balance;
                         $scope.applyType = 'all';

                         var totalGcAmount = $scope.getGiftCardAmounts();
                         if ($scope.roundNum(value.Balance) > $scope.roundNum($scope.cartTotal - totalGcAmount)) {
                             $scope.amountToApply = $scope.roundNum($scope.cartTotal - totalGcAmount);
                             $scope.applyType = '';
                             $scope.balanceOverAmount = true;

                         } else {
                             $scope.amountToApply = value.Balance;

                         }

                         $scope.cardNumber = $scope.data.cardNumber;
                         $scope.data.cardNumber = '';
                         $scope.pin = $scope.data.pin;
                         $scope.data.pin = '';
                     }
                     deferred.resolve(value);
                 }, function (error) {
                     $scope.isGiftCardValid = false;
                     deferred.reject(error);
                 });
            return deferred.promise;
        };

        $scope.addGiftCard = function () {
            $scope.updateGiftCard($scope.cardNumber, $scope.pin, $scope.amountToApply, $scope.balance);
            $scope.clearAddGiftCard();
        };

        $scope.clearAddGiftCard = function () {
            $scope.balance = 0;
            $scope.pin = '';
            $scope.amountToApply = 0;
            $scope.cardNumber = '';
        };

        $scope.updateGiftCard = function (cardNumber, pin, amountToApply, balance) {
            if ($scope.checkoutState.giftCards === undefined) {
                $scope.checkoutState.giftCards = [];
            }
            var totalValidAmount = $scope.getGiftCardAmounts();

            if (amountToApply > balance) {
                amountToApply = balance;
            }

            amountToApply = $scope.roundNum(amountToApply);
            var updated = false;
            for (var i = 0; i < $scope.checkoutState.giftCards.length; i++) {
                if ($scope.checkoutState.giftCards[i].CardNumber === cardNumber) {
                    if (amountToApply <= 0) {
                        $scope.checkoutState.giftCards.splice(i, 1);
                    } else {
                        $scope.checkoutState.giftCards[i].Pin = pin;

                        if ($scope.cartTotal < totalValidAmount) {
                            amountToApply = amountToApply - (totalValidAmount - $scope.cartTotal);
                        }

                        $scope.checkoutState.giftCards[i].Amount = $scope.roundNum(amountToApply);
                        $scope.checkoutState.giftCards[i].Balance = balance;

                        appObserver.broadcast('giftCardBlinkListener', {});

                    }
                    updated = true;
                    break;
                }
            }

            if (!updated && amountToApply > 0) {
                if ($scope.cartTotal - totalValidAmount < amountToApply) {
                    amountToApply = $scope.roundNum($scope.cartTotal - totalValidAmount);
                }
                if (amountToApply > 0) {
                    var giftCard = { CardNumber: cardNumber, Pin: pin, Amount: amountToApply, Balance: balance };
                    $scope.checkoutState.giftCards.push(giftCard);
                    appObserver.broadcast('giftCardBlinkListener', {});


                }
            }

            $scope.editCardNumber = '';

        };

        $scope.editGiftCard = function (cardNumber) {
            $scope.editCardNumber = cardNumber;
            $scope.cardNumber = '';
        };

        $scope.changeApplyTypeToEmpty = function () {
            $scope.applyType = '';
        };

        $scope.getGiftCardAmounts = function () {
            return checkoutHelperService.getGiftCardAmounts($scope.checkoutState.giftCards);
        };

        $scope.$watch('data.cardNumber', function (newValue) {

            if (newValue.length > 0 && (!$scope.giftCardSetting.EnablePinSupport || $scope.data.pin.length > 0)) {
                $scope.imageUrl = appUrlBuilder.buildUrl('giftCardImageUrl');
            } else {
                $scope.imageUrl = appUrlBuilder.buildUrl('giftCardGrayImageUrl');
            }
            if (($scope.isGiftCardValid === false || $scope.isGiftCardBalanceZero) && (newValue.length === 0 || $scope.data.pin.length === 0)) {
                $scope.isGiftCardValid = true;
                $scope.isGiftCardBalanceZero = false;
            }
        });

        $scope.$watch('data.pin', function (newValue) {

            if (newValue.length > 0 && $scope.data.cardNumber.length > 0) {
                $scope.imageUrl = appUrlBuilder.buildUrl('giftCardImageUrl');
            } else {
                $scope.imageUrl = appUrlBuilder.buildUrl('giftCardGrayImageUrl');
            }
            if (($scope.isGiftCardValid === false || $scope.isGiftCardBalanceZero) && (newValue.length === 0 || $scope.data.cardNumber.length === 0)) {
                $scope.isGiftCardValid = true;
                $scope.isGiftCardBalanceZero = false;
            }
        });

        $scope.$watch('applyType', function (newValue) {
            if (newValue === 'all') {
                $scope.amountToApply = $scope.balance;
            }
        });

        $scope.$watch('amountToApply', function (newValue) {
            var totalGcAmount = $scope.getGiftCardAmounts();

            if ($scope.roundNum(newValue) > $scope.roundNum($scope.balance) || $scope.roundNum(newValue) > $scope.roundNum($scope.cartTotal - totalGcAmount)) {
                $scope.isAmountValid = false;
            } else {
                $scope.isAmountValid = true;

            }
        });

        $scope.roundNum = function (num) {
            return checkoutHelperService.roundNum(num);
        };

        $scope.setMaxBalance = function () {
            var applyAmount = $(this)[0].gc.Amount;
            var gcBalance = $(this)[0].gc.Balance;
            if (applyAmount > gcBalance) {
                applyAmount = gcBalance;
            }
            $(this)[0].gc.Amount = applyAmount;
        };

        //Initialize
        $scope.loadGiftCardSetting();
        $scope.getOrderFormGiftcards();


    }
    ]);;;
'use strict';

/**
 * Responsible for all UPS specific communication with the server
 * Ups - to do
 */
angular.module('checkout').factory('UpsSvc', ['$resource', 'appUrlBuilder',
    function ($resource, appUrlBuilder) {

        var resource = $resource(appUrlBuilder.buildUrl('upsApiUrl'), null, {
            'getNearestUpsLocation': { method: 'GET', url: appUrlBuilder.buildUrl('getNearestUpsLocationApiUrl'), isArray: false, responseType: 'json' },
            'getUpsLocations': { method: 'GET', url: appUrlBuilder.buildUrl('getUpsLocationApiUrl'), isArray: false, responseType: 'json' }
        });

        return {
            getNearestUpsLocation: function (shippingAddress) {
                var data = {
                    addressLine: shippingAddress.address1,
                    city: shippingAddress.city,
                    zipCode: shippingAddress.postalCode,
                    province: shippingAddress.province,
                    countryCode: shippingAddress.country.countryCode
                };
                return resource.getNearestUpsLocation(data);
            },
            getUpsLocations: function (shippingAddress) {
                var data = {
                    addressLine: shippingAddress.address1,
                    city: shippingAddress.city,
                    zipCode: shippingAddress.postalCode,
                    province: shippingAddress.province,
                    countryCode: shippingAddress.country.countryCode
                };
                return resource.getUpsLocations(data);
            }
        };
    }
]);;
/**
* This is platform implemented checkout
*/
angular.module('checkout').directive('redeemPerkCheckout',
    ['$window', 'appUrlBuilder', 'CheckoutSvc', 'NavigationService',
    function ($window, appUrlBuilder, checkoutSvc, navigationService) {
        return {
            restrict: 'A',
			templateUrl: appUrlBuilder.buildTemplateUrl('redeemAPerkTemplateUrl'),
            scope: {
            },
			controller: 'RedeemPerkCtrl',
            link: function (scope) {
            
            }
        };
    }]);;
'use strict';

angular.module('checkout').controller('RedeemPerkCtrl',
    ['$scope', '$q', 'appUrlBuilder', 'CheckoutSvc', 'siteConfiguration', 'AppObserver', 'CheckoutDataStorageService', 'CheckoutHelperService', 'spinnerFactory', 'CartDataStorageService', '$timeout',
        function ($scope, $q, appUrlBuilder, checkoutSvc, siteConfiguration, appObserver, checkoutDataStorageService, checkoutHelperService, spinnerFactory, cartDataStorageService, $timeout) {

            $scope.data = {};
            $scope.cartData = cartDataStorageService.cartData;
			$scope.checkoutState = checkoutDataStorageService.checkoutState;
            $scope.data.perkNumber = '';
		    $scope.enableRedeemAPerk = true;
            $scope.isPerkFormSubmitted = false;
			$scope.isPerkNumberValid = false;
            $scope.perkButtonText = "Submit Perk";
            $scope.perkDisplayMsg = '';

            //check if perk was applied
            $timeout(function () {
                if ($scope.cartData.perkCode != 'undefined' && $scope.cartData.perkCode != undefined && $scope.cartData.perkCode != '') {
                    $scope.data.perkNumber = $scope.cartData.perkCode;
                    $scope.isPerkNumberValid = true;
                    $scope.perkButtonText = "Cancel Perk";

                    $("#perkCheckBox").click();
                    console.log("perk code applied > " + $scope.cartData.perkCode);
                } 
            }, 5000);

            $scope.submitPerk = function () {

                if ($scope.data.perkNumber == '') {
                    $scope.perkDisplayMsg = "Please enter your perk number";
                } else if ($scope.isPerkNumberValid) {
                    $scope.cancelPerk($scope.data.perkNumber);
                } else {

                    checkoutSvc.submitPerkCode($scope.data.perkNumber).$promise.then(
                        function(value) {
                            console.log("submit perk > Number: " + $scope.data.perkNumber + " | Response: " + value.Success);
                            if (value.Success) {
                                $scope.perkDisplayMsg = "";
                                $scope.isPerkNumberValid = true;
                                $scope.perkButtonText = "Cancel Perk";
                                cartDataStorageService.loadCartData();
                            } else {
                                //$scope.perkDisplayMsg = "The perk number you have entered is not valid. Please try again.";
                                $scope.perkDisplayMsg = value.ErrorMessage;
                                $scope.isPerkNumberValid = false;
                            }
                        },
                        function() {
                            console.log('submitPerkCode error');
                            //api error
                        });
                }
            };
            
		    $scope.cancelPerk = function () {
		        checkoutSvc.cancelPerkCode($scope.data.perkNumber).$promise.then(
		            function (value) {
                        console.log("cancel perk > Number: " + $scope.data.perkNumber + " | Response: " + value.Success);
                        if (value.Success) {
                            $scope.isPerkNumberValid = false;
                            $scope.data.perkNumber = '';
                            $scope.perkDisplayMsg = '';
                            $scope.perkButtonText = "Submit Perk";
                            cartDataStorageService.loadCartData();
		                } 
		            },
		            function () {
                        console.log('cancelPerkCode error');
		                //api error
		            });
		    };

		}
	]);;
/**
* This is platform implemented checkout
*/
angular.module('checkout').directive('happyCardCheckout',
    ['$window', 'appUrlBuilder', 'CheckoutSvc', 'NavigationService',
    function ($window, appUrlBuilder, checkoutSvc, navigationService) {
        return {
            restrict: 'A',
			templateUrl: appUrlBuilder.buildTemplateUrl('happyCardTemplateUrl'),
            scope: {
            },
			controller: 'HappyCardCtrl',
            link: function (scope) {
            
            }
        };
    }]);;
'use strict';

angular.module('checkout').controller('HappyCardCtrl',
	['$scope', '$q', 'appUrlBuilder', 'CheckoutSvc', 'siteConfiguration', 'AppObserver', 'CheckoutDataStorageService', 'CheckoutHelperService', '$timeout',
		function ($scope, $q, appUrlBuilder, checkoutSvc, siteConfiguration, appObserver, checkoutDataStorageService, checkoutHelperService, $timeout) {

			//$scope.imageUrl = appUrlBuilder.buildUrl('giftCardGrayImageUrl');

			$scope.data = {};
			$scope.checkoutState = checkoutDataStorageService.checkoutState;
			$scope.data.happyCardNumber = '';
			$scope.data.cvv2 = '';
			$scope.isHappyCardSubmitted = false;

			$scope.happyCardNumber = '';
			$scope.cvv2 = '';
			$scope.enableHappyCard = true;
			$scope.isHappyCardValid = false;

			$scope.submitHappyCard = function () { };
			$scope.hcCustomerServicePhone = '1-XXX-XXX-XXXX';

			$scope.showToolTipx = function (state) {
				$timeout(function () {
					if (isMobileDevice || isMobileDeviceJs()) {
						return;
					}

					if (state) {
						$(".tooltiptext").slideDown(300);
					} else {
						$(".tooltiptext").hide();
					}
				}, 50);
			}
		}
	]);;
