/*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: '/Henrys.Responsive', // Developers will need to set this to the base if the site is not in the root
		rootUrl: '', 
        getStoreStockDataUrl: '/api/Product/GetStoreStockData',
        getExistingCreditCardsUrl: '/api/Checkout/GetExistingCreditCards',
        addExistingCreditCardPaymentUrl: '/api/Checkout/AddExistingCreditCardPayment',
        getCustomerAddressesUrl: '/api/checkout/GetShippingAddressesCheckout',
        updateCustomerPhoneNumberUrl: '/api/Checkout/UpdateCustomerPhoneNumber',
        checkCustomerExistsApiUrl: '/api/Checkout/CheckCustomerExists',
        addCommentsUrl: '/api/Checkout/AddComments',
        updateEmailOptIn: '/api/Checkout/UpdateEmailOptIn',
        getGeoCodeForPostalCodeApiUrl: '/api/Checkout/GetGeoCodeForPostalCode',
        getDpoStoressUrl: '/api/Checkout/GetStoresDpo',
        disableLocationServices: true,
        disableAjaxRequestCache: true,
        postalCodeRegex: /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/,
        resetDpoUrl: '/api/Checkout/ResetDpo',
        postCartDpoUrl: '/api/Checkout/PostCartDpo',
        getStoreInventoryCustomUrl: '/api/Product/GetStoreInventoryCustom',
        checkoutGoBackDialogTitle: '',
        checkoutGoBackDialogMessage: 'Are you sure want to go back?'

};
})());

/**
 * 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: culture };
            }
        };
    });;
'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) {
                   return siteConfiguration.rootUrl + 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
                   return siteConfiguration.rootUrl + 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";angular.module("slick",[]).directive("slick",["$timeout",function(n){return{restrict:"AEC",scope:{initOnload:"@",data:"=",currentIndex:"=",accessibility:"@",arrows:"@",autoplay:"@",autoplaySpeed:"@",centerMode:"@",centerPadding:"@",cssEase:"@",dots:"@",draggable:"@",easing:"@",fade:"@",infinite:"@",lazyLoad:"@",onBeforeChange:"&",onAfterChange:"&",onInit:"&",onReInit:"&",pauseOnHover:"@",responsive:"&",slide:"@",slidesToShow:"@",slidesToScroll:"@",speed:"@",swipe:"@",touchMove:"@",touchThreshold:"@",vertical:"@"},link:function(t,i){var r,u;return r=function(){return n(function(){var n,r;return r=$(i),t.currentIndex!=null&&(n=t.currentIndex),r.slick({accessibility:t.accessibility!=="false",arrows:t.arrows!=="false",autoplay:t.autoplay==="true",autoplaySpeed:t.autoplaySpeed!=null?parseInt(t.autoplaySpeed,10):3e3,centerMode:t.centerMode==="true",centerPadding:t.centerPadding||"50px",cssEase:t.cssEase||"ease",dots:t.dots==="true",draggable:t.draggable!=="false",easing:t.easing||"linear",fade:t.fade==="true",infinite:t.infinite!=="false",lazyLoad:t.lazyLoad||"ondemand",onBeforeChange:t.onBeforeChange||null,onAfterChange:function(i,r){return t.onAfterChange&&t.onAfterChange(),n!=null?t.$apply(function(){return n=r,t.currentIndex=r}):void 0},onInit:function(i){return t.onInit&&t.onInit(),n!=null?i.slideHandler(n):void 0},onReInit:t.onReInit||null,pauseOnHover:t.pauseOnHover!=="false",responsive:t.responsive()||null,slide:t.slide||"div",slidesToShow:t.slidesToShow!=null?parseInt(t.slidesToShow,10):1,slidesToScroll:t.slidesToScroll!=null?parseInt(t.slidesToScroll,10):1,speed:t.speed!=null?parseInt(t.speed,10):300,swipe:t.swipe!=="false",touchMove:t.touchMove!=="false",touchThreshold:t.touchThreshold?parseInt(t.touchThreshold,10):5,vertical:t.vertical==="true"}),t.$watch("currentIndex",function(t){if(n!=null&&t!=null&&t!==n)return r.slickGoTo(t)})})},t.initOnload?(u=!1,t.$watch("data",function(n){if(n!=null&&!u)return r(),u=!0})):r()}}}]);
/*
//# sourceMappingURL=slick.min.js.map
*/;
'use strict';
/**
 * Responsible for most behaviour within the Account Module such as:
 */
angular.module('account')
    .controller('accountCtrl', ['$scope', '$q', '$modal', 'accountSvc', 'appUrlBuilder', 'NavigationService', 'siteConfiguration', 'PasswordHelper',
    function ($scope, $q, $modal, accountSvc, appUrlBuilder, navigationService, siteConfiguration, passwordHelper) {

        $scope.newCustomer = {};
        $scope.newCustomer.email = $scope.email;
        $scope.newCustomer.address = {};
        $scope.newCustomer.address.country = { "countryCode": "CA", "countryId": 1, "countryName": "Canada" }
        $scope.serverErrorMsg = '';
        $scope.addressDone = null;
        $scope.isDisabled = true; // create account button's status (enabled or disabled)

        $scope.phoneNumberRegex = siteConfiguration.phoneNumberRegex;
        $scope.firstNameChangedInit = false;
        $scope.lastNameChangedInit = false;
        $scope.emailChangedInit = false;
        $scope.emailValidInit = false;
        $scope.phoneChangedInit = false;
        $scope.passwordChangedInit = false;

        //for address form to use to decide whether or not automatically trigger done button click event without user clicks after user clicks on validate button
        $scope.triggerDoneButtonEvent = true;

        $scope.validateModel = function () {
            $scope.serverErrorMsg = '';

            var firstNameNotEmpty = false;
            var lastNameNotEmpty = false;
            var emailNotEmpty = false;
            var emailValidFormat = false;
            var phoneNotEmpty = false;
            var passwordNotEmpty = false;

            if ($scope.newCustomer.firstName) {
                firstNameNotEmpty = true;
                if (!$scope.firstNameChangedInit) {
                    $scope.firstNameChangedInit = true;
                }
            }

            if ($scope.newCustomer.lastName) {
                lastNameNotEmpty = true;
                if (!$scope.lastNameChangedInit) {
                    $scope.lastNameChangedInit = true;
                }
            }

            if ($scope.newCustomer.email) {
                emailNotEmpty = true;
                if (!$scope.emailChangedInit) {
                    $scope.emailChangedInit = true;
                }

                // email validation check
                emailValidFormat = $scope.isEmailAddress($scope.newCustomer.email);
                $scope.emailValidInit = emailValidFormat;
            }

            if ($scope.newCustomer.phone) {
                phoneNotEmpty = true;
                if (!$scope.phoneChangedInit) {
                    $scope.phoneChangedInit = true;
                }
            }

            if ($scope.newCustomer.password) {
                passwordNotEmpty = true;
                if (!$scope.passwordChangedInit) {
                    $scope.passwordChangedInit = true;
                }
            }

            // set isDisabled(create button status)
            if (firstNameNotEmpty && lastNameNotEmpty && emailNotEmpty && phoneNotEmpty && passwordNotEmpty && emailValidFormat && $scope.addressDone !== null) {
                $scope.isDisabled = false;
                $scope.createAccount($scope.newCustomer);
            }
            else {
                $scope.isDisabled = true;
            }
        };

        $scope.isEmailAddress = function (str) {
            var pattern = siteConfiguration.emailRegex;
            return pattern.test(str); // returns a boolean 
        };


        $scope.$watch('addressDone', function () {
            $scope.validateModel();
        });

        // event handler from address directive
        $scope.customerAddressDone = function () {
            var scope = angular.element(document.getElementById('fullForm_FirstName')).scope();
            var data = scope.fullForm;
            if ($scope.newCustomer) {
                $scope.newCustomer.address = data;
                $scope.newCustomer.firstName = data.FirstName;
                $scope.newCustomer.lastName = data.LastName;
                $scope.newCustomer.phone = data.PhoneNumber;
            }

            //enable create account button
            $scope.addressDone = data;
        };

        // event handler from address directive
        $scope.customerAddressEdit = function () {
            //disable create account button
            $scope.addressDone = null;
        };

        $scope.createAccount = function (itemData) {

            itemData.returnUrl = '';
            if ($scope.returnUrl) {
                var objFromJson = angular.fromJson($scope.returnUrl);
                if (objFromJson && objFromJson.key) {
                    itemData.returnUrl = objFromJson.key;
                }
            }

            accountSvc.createAccount(itemData).$promise.then(
                function (data) { // success
                    $scope.serverErrorMsg = '';
                    if (data.returnUrl) {
                        navigationService.navigate(data.returnUrl);
                    } else {
                        navigationService.navigate(appUrlBuilder.buildUrl('mainPageMyAccountUrl'));
                    }
                },
                function (failMessage) {
                    //failure
                    $scope.isDisabled = true;

                    // note: if serverErrorMsg not empty, then error message will be presented from resource file to the view.
                    // below is just for developer's purpose
                    $scope.serverErrorMsg = failMessage.statusText + ' [ ' + failMessage.data + ' ] ';
                }
            );
        };

        $scope.togglePasswordView = function (inputName) {
            passwordHelper.TogglePasswordView(inputName);
        };
    }
    ]);;
'use strict';

/**
 * this is account control....
 */

angular.module('account').directive('henrysAccount', ['appUrlBuilder', function (appUrlBuilder) {
    return {
        restrict: 'A',
        templateUrl: appUrlBuilder.buildUniqueTemplateUrl('createAccountTemplateUrl'),
        scope: {
            // returnUrl: '=returnUrl'
            returnUrl: '@',
            email: '@'
        },
        controller: 'accountCtrl',
        replace: true
    };
}]);;
'use strict';

/**
 * this is product image directive, container for product image section
 * working with jquery plugin (jquery.main.js)
 */



angular.module('product').directive('henrysProductImage', ['$window', '$compile', '$http', '$timeout', 'appUrlBuilder', function ($window, $compile, $http, $timeout, appUrlBuilder) {
    return {
        restrict: 'A',
        templateUrl: appUrlBuilder.buildTemplateUrl('productImageTemplateUrl'),
        controller: 'ProductImageCtrl',
        priority: 4,
        transclude: true,
        link: function (scope) {
            scope.updateShowImage = function(image) {
                scope.productData.currentImage = image;
                scope.selectedThumbImageUrl = image.ThumbUrl;
                angular.element('.slide1').removeClass("active");
                if (angular.element('.zoomer-image').length > 0) {
                    angular.element('.zoomer-image').attr('src', image.ShowUrl);
                    angular.element('.zoomer-image').attr('alt', image.PublicDescription);
                } else {
                    angular.element('#mainImg').attr('src', image.ShowUrl);
                    angular.element('#mainImg').attr('alt', image.PublicDescription);
                }
               
            };

            
            scope.onLoad = function() {
                scope.$apply(function () {

                    if (!scope.imageLoaded) {
                         initProductPageCarousel();
                        initZoom();
						zoomcheck();
                    }
                  

                    scope.productData.isImageRendered = true;

                    scope.imageLoaded = true;
                });
            };
        }
        
      
    };
}]);;
'use strict';

/**
 * Get the product details
 */
angular.module('product').controller('ProductRootCtrl',
    ['$scope', '$modal', '$window', '$location', 'ProductDataStorageService', 'siteRes', 'WishListService', 'siteConfiguration', 'appUrlBuilder', 'DialogService', 'NavigationService', 'ProductSvc', 'MyStoreCookieSvc',
    function ($scope, $modal, $window, $location, productDataStorageService, siteRes, wishListService, siteConfiguration, appUrlBuilder, dialogService, navigationService, productSvc, myStoreCookieSvc) {

        $scope.error = false;

        //set the reference of product data to data stored in storage
        $scope.productData = productDataStorageService.productData;
        $scope.selectedStoreName = myStoreCookieSvc.ReadMyStoreFromCookie(); //productDataStorageService.selectedStoreName;

        $scope.getMyStoredata = function (storeId, itemId) {
            productSvc.getStoreStockData(storeId, itemId).$promise.then(function (value) {
                $scope.MyStoreData = value;
                $scope.selectedStoreName = storeId;
            });
        };


        //pre load product data
        $scope.loadProductData = function (productId) {
            $scope.productId = productId;
            productDataStorageService.loadProductData($scope.productId).then(
                function () {

                    if ($scope.selectedStoreName.length > 0) {
                        if (angular.isUndefined($scope.productData.selectedItem)) {


                            $scope.getMyStoredata($scope.selectedStoreName, $scope.productData.firstItemId);
                        } else {

                            $scope.getMyStoredata($scope.selectedStoreName, $scope.productData.selectedItem.Id);
                        }
                    }



                }, function (error) {
                    if (error.status === siteConfiguration.errorCodeServerError) {
                        $scope.error = true;
                    }
                });
        };
        //Start: In store stock implementation-------------------------------------------------------------------
        var firstload = true;
        $(document).ready(function () {            
            $(document).on('mouseenter', '.instoreLink', function () {
                $scope.openStoreStock();
                if (!firstload) ShowFlyout($(this), $('.inStore-flyout'));
            });
            $(document).on('mouseleave', '.inStore-flyout', function () {
                HideFlyout($('.inStore-flyout'));
            });

            $(document).on('mouseenter', '.inStore-flyout', function () {
                //$scope.openStoreStock();
                ShowFlyout($('.instoreLink'), $(this));
            });
            $(document).on('mouseleave', '.closeinstoreLink', function () {
                HideFlyout($('.inStore-flyout'));
            });
        });

        var tempToggleName = "";
        var strStoreAvailablity = "Store Availablity";
        function ShowFlyout(container, element) {
            $(element).show();
            var heightAdjust = $(element).height() / 2;
            var pos = $(container).position();
            var width = $(container).textWidth() + 25;
            if ($(window).width() > 767 && $(window).width() < 1092) {
                width = width - 110;                
            }

            $(element).css({ 'top': pos.top - heightAdjust + 'px', 'left': pos.left + width + 'px' });

            if ($(window).width() > 767) {
                $('.hoverArrow').show();
                $('.hoverArrow').css({ 'top': pos.top - 25 + 'px', 'left': pos.left + width - 16 + 'px', 'positiion': 'relative' });
            }
            else if ($(window).width() < 768) {
                if ($('.changeTextOnHover').text() != strStoreAvailablity) tempToggleName = $('.changeTextOnHover').text();
                $('.changeTextOnHover').text(strStoreAvailablity);
                $('#closeIcon').show();
            }

        }
        function HideFlyout(element) {
            $('.hoverArrow').hide();
            $(element).hide();    
            if (tempToggleName != "") $('.changeTextOnHover').text(tempToggleName);
            $('#closeIcon').hide();
        }

        $scope.openStoreStock = function () {
            if ($scope.productData.selectedItem.Id === undefined || $scope.productData.selectedItem.Id === null) {
                dialogService.alert(siteRes.StoreInventorySelectItemValidationMessage);

            } else {
                productSvc.getStoreInventoryCustom($scope.productId).$promise.then(function (_storeList) {
                    if (_storeList) {
                        var storeListCustom = '';
                        if ($(window).width() > 767) {
                            storeListCustom = storeListCustom + '<strong style="width:100%;display: block;">' + strStoreAvailablity + '</strong>'
                        }
                        if (_storeList.length == 0) {
                            storeListCustom = storeListCustom + '<span style="width:100%;">This item is unavailable for in-store shopping.</span>'
                        }
                        else {
                            storeListCustom = storeListCustom + '<span style="width:100%;">This item is available for in-store shopping at the following locations:</span>'
                            storeListCustom = storeListCustom + '<ul style="margin-top: 7px; -moz-column-count: 2;-webkit-column-count: 2;column-count: 2;list-style-type: none; padding-left:0px;">';
                            $.each(_storeList, function (index, store) {
                                //debugger;
                                var storeName = store.StoreName;
                                var storeUrl = globalConstants.rootUrl + store.StoreUrl;
                                storeListCustom = storeListCustom + '<li><a style="border-bottom: 1px solid;" href=' + storeUrl + '>' + storeName + '</a></li>'
                            });
                            storeListCustom = storeListCustom + '</ul>';
                        }
                        $('.inStore-flyout').html(storeListCustom);
                        if (firstload) {
                            firstload = false;
                            ShowFlyout($('.instoreLink'), $('.inStore-flyout'));
                        }
                    }
                });

            }
        };              
        $.fn.textWidth = function () {
            var html_org = $(this).html();
            var html_calc = '<span>' + html_org + '</span>';
            $(this).html(html_calc);
            var width = $(this).find('span:first').width();
            $(this).html(html_org);
            return width;
        };
        //End: In store stock implementation-----------------------------------------------------------------------

        $scope.addToWishList = function (itemId) {
            wishListService.addItem(itemId, function () {
                $scope.$apply(function () {
                    $scope.productData.isInWishList = true;
                });
            }, function (request, status, error) {
                if (error == 'Unauthorized') {
                    var baseLen = $location.protocol().length + $location.host().length + siteConfiguration.rootUrl.length + 4;

                    var retUrl = $location.absUrl().substring(baseLen);
                    if (retUrl.indexOf('?') >= 0) {
                        retUrl = retUrl + '&addToWishList=' + itemId;
                    } else {
                        retUrl = retUrl + '?addToWishList=' + itemId;
                    }

                    navigationService.navigate(appUrlBuilder.buildUrl('signInPageUrl') + '?ReturnUrl=' + encodeURIComponent('~/' + retUrl));
                } else {
                    dialogService.alert(error);
                }

            });
        };

        $scope.loadQuickView = function (id) {
            $scope.QuickView = $modal.open({
                templateUrl: globalConstants.rootUrl + '/Product/ShowQuickView?id=' + id,
                controller: 'ProductRootCtrl',
                windowClass: 'product-modal quickview-modal'
            });
        };

        $scope.closeQuickView = function () {
            $scope.$close();
        };
    }
    ]);;
'use strict';

/**
 * this is service that stores product data, shared across multiple product directives
 */

angular.module('product').factory('ProductDataStorageService', ['$q', '$sce', 'ProductSvc', 'MyStoreCookieSvc',
    function ($q, $sce, productSvc, myStoreCookieSvc) {
        var productData = {};
        var selectedAutoShip = {};
        var quantity = {};
        var selectedStoreName = myStoreCookieSvc.ReadMyStoreFromCookie();

        var loadProductData = function (productId) {

            var deferred = $q.defer();

            productSvc.getProduct(productId).$promise.then(
                function (value) {
                    /*
                     * Description section
                     */
                    productData.id = value.Id;
                    productData.productName = value.ProductName;
                    productData.averageRating = value.AverageRating;
                    productData.ratingNumber = value.RatingNumber;

                    productData.singleUnitPrice = value.SingleUnitPrice;
                    productData.retailPrice = value.RetailPrice;


                    productData.dynamicPromotion = $sce.trustAsHtml(value.DynamicPromotion);

                    productData.shortDescription = value.ShortDescription;
                    productData.customText1 = $sce.trustAsHtml(value.CustomText1);

                    productData.hasPersonalization = value.HasPersonalization;


                    /*
                     * Image section
                     */

                    productData.currentImage = value.DefaultImage;
                    if (productData.currentImage === null) {
                        productData.currentImage = {
                            ShowUrl: value.DefaultImageUrl

                        };
                    }
                    if (productData.currentImage.ShowUrl === '') {
                        productData.currentImage.ShowUrl = value.DefaultImageUrl;
                    }
                    productData.images = value.Images;

                    /*
                     * Tabs section
                     */
                    //Description Tab
                    productData.longDescription = $sce.trustAsHtml(value.LongDescription);

                    //Specification Tab
                    productData.specs = value.Specs;

                    //Reviews Tab
                    productData.ratingBreakdowns = value.RatingBreakdowns.reverse();
                    productData.reviews = value.Reviews;

                    //Related Products Tab
                    productData.relatedProductsCount = value.RelatedProductsCount;

                    //Buy Together Tab
                    productData.bundlesCount = value.BundlesCount;

                    productData.isInWishList = value.IsInWishList;
                    productData.firstItemId = value.FirstItemId;
                    //just resolving
                    deferred.resolve({});

                }, function (error) {
                    deferred.reject(error);
                });

            return deferred.promise;
        };

        return {
            productData: productData,
            selectedAutoShip: selectedAutoShip,
            quantity: quantity,
            loadProductData: loadProductData,
            selectedStoreName: myStoreCookieSvc.ReadMyStoreFromCookie()
        };

    }]);;
'use strict';

/**
 * Responsible for order confirmation page to communication with the server
 */
angular.module('product').factory('ProductSvc', ['$resource', 'appUrlBuilder',
    function ($resource, appUrlBuilder) {

        var resource = $resource(appUrlBuilder.buildUrl('productApiUrl'), null, {
            'getProduct': { method: 'GET', url: appUrlBuilder.buildUrl('getProductApiUrl') + '/:id', isArray: false, responseType: 'json' },
            'voteProductReview': { method: 'PUT', url: appUrlBuilder.buildUrl('voteProductReviewApiUrl'), isArray: false, responseType: 'json' },
            'getProductConfig': { method: 'GET', url: appUrlBuilder.buildUrl('getProductConfigApiUrl') + '/:id', isArray: false, responseType: 'json' },
            'getStoreStockData': { method: 'GET', url: appUrlBuilder.buildUrl('getStoreStockDataUrl'), isArray: false, responseType: 'json' },
            'getStoreInventoryCustom': { method: 'GET', url: appUrlBuilder.buildUrl('getStoreInventoryCustomUrl'), isArray: true, responseType: 'json' }
        });

        return {

            getProduct: function (productId) {
                return resource.getProduct({ id: productId });
            },

            voteProductReview: function (productId, reviewId, reviewStatus) {
                var data = { ProductId: productId, ReviewId: reviewId, VoteReportStatus: reviewStatus };

                return resource.voteProductReview(data);
            },
            getProductConfig: function (productId) {
                return resource.getProductConfig({ id: productId });
            },
            getStoreStockData: function (storeId, itemId) {
                var data = { StoreId: storeId, ItemId: itemId };
                return resource.getStoreStockData(data);
            },
            getStoreInventoryCustom: function (productId) {
                var _storeList = { productId: productId };
                return resource.getStoreInventoryCustom(_storeList);
            },

        };
    }
]);;
'use strict';

/**
*This directive is for store stock check.
*/
angular.module('product')
    .directive('henrysProductStock', ['$window', '$http', '$modal', 'ProductDataStorageService', 'appUrlBuilder', 'siteConfiguration', 'siteRes', 'StoreLocatorService', 'StoreInventoryService',
      function ($window, $http, $modal, productDataStorageService, appUrlBuilder, siteConfiguration, siteRes, storeLocatorService, storeInventoryService) {
          return {
              restrict: 'A',
              scope: {
                  itemId: '='
              },
              link: function (scope, element) {
                  //set product data reference to storage.
                  scope.productData = productDataStorageService.productData;
                  var url = appUrlBuilder.buildUrl('storeStockLocatorTemplateUrl') + '?' + new Date().getTime();

                  $http.get(url).success(function (data) {
                      element.html(data);
                      if (storeLocatorService.map === null || storeLocatorService.map === undefined) {
                          storeLocatorService.initialize(54.470038, -98.971875);
                      }
                      window.angular.element('.locationSubmit').click(function (e) {
                        
                          var address;
                          var province;
                          var city;
                          var postal = window.angular.element('#postal').val().replace(/\s+/g, '');

                          if ($(".lstCity")[0].selectedIndex !== 0 && $(".lstProvinces")[0].selectedIndex !== 0) {
                              city = $(".lstCity").val().trim();
                              province = $(".lstProvinces").val().trim();
                              address = city + ", " + province;
                          }
                          else {
                              address = '';
                          }

                          storeLocatorService.removeAllMarkersAndInfoWindows();

                          if (postal == '' && address == '') {
                              BootstrapDialog.alert('Please enter a postal code or province/city');
                              e.preventDefault();
                              return;
                          }

                          if (postal !== '') {
                              storeInventoryService.GetUserLocation(scope.itemId, 'CA', postal, address);
                              window.userCurrentLocation = postal;
                          } else if ($(".lstCity")[0].selectedIndex !== 0) {
                              storeInventoryService.GetUserLocationByCity(scope.itemId, address);
                          }

                          e.preventDefault();
                      });

                      window.angular.element('#Range').change(function (e) {
                         var address;
                          var province;
                          var city;
                          var postal = window.angular.element('#postal').val().replace(/\s+/g, '');

                          if ($(".lstCity")[0].selectedIndex !== 0 && $(".lstProvinces")[0].selectedIndex !== 0) {
                              city = $(".lstCity").val().trim();
                              province = $(".lstProvinces").val().trim();
                              address = city + ", " + province;
                          }
                          else {
                              address = '';
                          }

                          storeLocatorService.removeAllMarkersAndInfoWindows();

                          if (postal == '' && address == '') {
                              //BootstrapDialog.alert('Please enter a postal code or province/city');
                              //e.preventDefault();
                              //return;
                              storeInventoryService.getCurrentPosition(options, scope.productData.selectedItem.Id);
                              e.preventDefault();
                              return;
                          }

                          if (postal !== '') {
                              storeInventoryService.GetUserLocation(scope.itemId, 'CA', postal, address);
                              window.userCurrentLocation = postal;
                          } else if ($(".lstCity")[0].selectedIndex !== 0) {
                              storeInventoryService.GetUserLocationByCity(scope.itemId, address);
                          } else {
                              BootstrapDialog.alert('Please enter a postal code or province/city');
                              e.preventDefault();
                              return;
                          }
                          e.preventDefault();
                      });

                      var options = {
                          enableHighAccuracy: false,
                          timeout: 10000,
                          maximumAge: 0
                      };
                      storeInventoryService.getCurrentPosition(options, scope.productData.selectedItem.Id);

                      window.angular.element('.closeStoreStock').click(function () {

                          scope.productData.stockModal.dismiss();
                      });


                      window.angular.element(".lstCity").change(function (e) {
                          storeLocatorService.removeAllMarkersAndInfoWindows();
                          var city = $(".lstCity").val().trim();
                          var province = $(".lstProvinces").val().trim();
                          if (city != 'City') {
                              var address = city + ", " + province;
                              storeInventoryService.GetUserLocationByCity(scope.itemId, address);
                          }
                          e.preventDefault();
                      });

                      window.angular.element('#postal').keydown(function (e) {
                          if (e.keyCode === 13) {
                              var postal = window.angular.element('#postal').val().replace(/\s+/g, '');
                              var city = $(".lstCity").val().trim();
                              var province = $(".lstProvinces").val().trim();
                              if (city != 'City') {
                                  var address = city + ", " + province;
                                  storeInventoryService.GetUserLocation(scope.itemId, 'CA', postal, address);
                              }
                              e.preventDefault();
                          }
                      });
                  });

                  hideSpinner();
              }
          };
      }]);;
/*exported CartHelper */
/*global BootstrapDialog:false */
'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();

        scope.showCart();
        return false;
    };

    // btnAddToCart
    CartHelper.prototype.AddToCart = function (itemId, productId, hasPersonalization, autoship, quantity, enableItemSelection) {
        var scope = angular.element('#' + cartAppId).scope();
        scope.addToCart({
            itemId: itemId,
            hasPersonalization: hasPersonalization,
            productId: productId,
            Quantity: quantity,
            Autoship: autoship,
            enableItemSelection: enableItemSelection
        }).then(
            function () {
                var pScope = angular.element('#' + productAppId).scope();

                if (pScope && pScope.productData && pScope.productData.selectedItem) {
                    pScope.productData.selectedItem.triggerAddToCartEffect = !pScope.productData.selectedItem.triggerAddToCartEffect;
                    pScope.$apply();
                }

                var idSelector = '.' + addToCartButtonIdPrefix + productId;
                var btn = $(idSelector);
                btn.removeClass('btn-add-to-cart');
                btn.addClass('btn-success');
                btn.text(localization.Added);
                window.setTimeout(function () { btn.text(localization.AddAnother); }, 2000);  

            },
            function (error) {
                if (error !== 'cancel') { //if we canceled - we do not show any error message
                    bsd.show({
                        title: "<span class=\"logo-img\"><img src=\"/content/images/logo.png\" alt=\"Henry's\"></span><span class=\"text\" style=\"color:#fff;\">Canada’s Greatest Camera Store</span>",
                        cssClass: 'Henrys-dialog',
                        message: '<p style="font-size:16px;">' + localization.CannotAddToCart + '.</p>',
                        buttons: [
                            {
                                label: 'Close',
                                action: function (dialogItself) {
                                    dialogItself.close();
                                }
                            }
                        ]
                    });
                }
            });
        //Enhanced commerce prodct data fire event
        FireProductData(productId, "AddToCart");
        return false;
    };

    // btnAddToCart
    CartHelper.prototype.AddVariablePriceToCart = function (id, amt) {
        $.ajax({
            url: globalConstants.rootUrl + '/api/shoppingCart/addVariablePriceProduct?id=' + id + '&amount=' + amt,
            method: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                var value = data;
                $('#' + cartSmallBadgeId).text(value);
                $('#' + cartLargeBadgeId).text(value);
              
            }
        });
        return false;
    };

    // btnAddToCart
    CartHelper.prototype.AddToWishList = function (id) {
        $.ajax({
            url: globalConstants.rootUrl + '/api/wishList/AddToWishlist?itemId=' + id,
            method: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                $("#btnWishList" + id).popover('show');
                $('.another-look #btnWishList' + id).popover('show');
                $('.experts-recommend #btnWishList' + id).popover('show');
                $('.product-compare-item #btnWishList' + id).popover('show');
                $('.kit-footer #btnWishList' + id).popover('show');
            },
            error: function (data) {
                var value = data;
                if (value.statusText == 'Unauthorized') {
                    var baseLen = window.location.protocol.length + window.location.host.length + globalConstants.rootUrl.length + 3;

                    var retUrl = window.location.href.substring(baseLen);
                    if (retUrl.indexOf('?') >= 0) {
                        retUrl = retUrl + '&addToWishList=' + id;
                    } else {
                        retUrl = retUrl + '?addToWishList=' + id;
                    }

                    window.location = globalConstants.rootUrl + '/account/signin?ReturnUrl=' + encodeURIComponent('~/' + retUrl);
                } else {
                    showHenrysMsg("We were unable to add this item to your wishlist.");
                }
            }
        });
        return false;
    };

    // btnAddToCart
    CartHelper.prototype.OnCartChanged = function (cartData) {
        updateScoppingCartItemsCount(cartData);
        changeAddToCartButtonToAddedToCart(cartData);
    };

    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) {
                // 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.text(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);;
'use strict';

/**
 * Controller that allows to open shopping cart in a modal window. 
 */
angular.module('cart').controller('ShoppingCartModalCtrl', ['$scope', '$q', '$modal', '$window', 'appUrlBuilder', 'CartDataStorageService', 'CartService',
    function ($scope, $q, $modal, $window, appUrlBuilder, cartDataStorageService, cartService) {

        $scope.loadCounter = cartDataStorageService.loadCounter;
        $scope.cartData = cartDataStorageService.cartData;

        $scope.preloadData = function () {
            cartDataStorageService.loadCartData();          
        };

        $scope.$root.showCart = function () {
            $modal.open({
                templateUrl: appUrlBuilder.buildTemplateUrl('shoppingCartModalTemplateUrl'),
                controller: 'ShoppingCartModalInstanceCtrl',
                windowClass: 'cart-Modal'
            });
        };

        $scope.$root.isCartEmpty = function () {
            return $scope.cartData.items.length < 1;
        };

        $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;
        };

        //Pop up cart if query string contains 'showCart=True'
        if ($window.location.search.toUpperCase().indexOf('SHOWCART=TRUE') > 0) {
            $scope.$root.showCart();
        }

    }]);;
'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) {

    $scope.cartData = cartDataStorageService.cartData;

    //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 : '');
    // 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;
            if (shippingService.countryContain($scope.shippingCountries, countryId)) {
                $scope.shippingCountry = countryId;
            } else {
                $scope.shippingCountry = $scope.shippingCountries[0].Id;
            }
            $scope.getShippingRates($scope.shippingRate);
        });
    };

    $scope.updateShippingAddress = function () {
        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('updateShippingAddress error occur');
        });
    };

    $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', {});
                }
            },
            function () {
                spinnerFactory.hide();
            }
        );
    };

    //first time page initial load countries
    $scope.getShippingCountries();

    //Unbind listeners when scope is destroyed
    $scope.$on('$destroy', function () {
        cartItemListener();
    });
}]);;
'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', '$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;

       var range = [];
        for (var i = 1; i < 100; i++) {
            range.push(i);
        }
        $scope.range = range;

        $scope.updateQuantity = function (itemId, quantity) {
            $scope.quantityChanged(itemId);
            $scope.updateItemQuantity(itemId, quantity);
        }

        $scope.updateItemQuantity = function(itemId, quantity) {


            //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();

                    //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);
        };

        $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 == 'Unauthorized') {
                    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;
                }
            }
        };
    }
    ]);;
'use strict';

/**
* This directive is loading cart data and displaying summary on the page.
*/
angular.module('cart').directive('henrysCheckoutButton', ['appUrlBuilder', 'NavigationService', 
    function (appUrlBuilder, navigationService) {
        return {
            restrict: 'A',
            replace: true,
            templateUrl: appUrlBuilder.buildTemplateUrl('checkoutButtonTemplateUrl'),
            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) {
                        FireCheckoutClickDataEvent(scope.cartData.items, 0);
                      navigationService.navigate(appUrlBuilder.buildUrl('checkoutPageUrl'));
                    } else {
                        FireCheckoutClickDataEvent(scope.cartData.items, 0);
                        navigationService.navigate(appUrlBuilder.buildUrl('signInPageUrl') + '?ReturnUrl=' + encodeURIComponent(appUrlBuilder.buildUrl('checkoutPageUrl')));
                    }
                };

                scope.checkout = function () {
                    if (!scope.isValidForCheckout()) {
                        return;
                    }
                    navigationService.navigate(appUrlBuilder.buildUrl('checkoutPageUrl'));
                };

            }
        };
    }]);
;
/*exported productCompare */
'use strict';

/**
 * Provides helper methods for product compare elements.
 */

var productCompare = (function ($) {

    function productCompare() {

    }

    productCompare.prototype.onclickRemove = function (obj) {
        // Unchecked the compare check box
        var idProd = obj.id.toString();
        var prodCheckbox = document.getElementById('checkbox-ProdId-' + idProd);
        if (prodCheckbox) {
            prodCheckbox.checked = false;
        }

        //clean up container
        var node = obj.parentNode;
        while (node.hasChildNodes() >= 1) {
            node.removeChild(node.firstChild);
        }
        $(node).html('<span class="add-more hidden-sm hidden-xs">Add up to 4 items to compare.</span><span class="add-more visible-sm">Add up to 2 items to compare.</span>').addClass("empty");

        updateProductArray();
    
    };

    var addCompareProduct = function(Id, Name, n) {

        var imgThumb = '<div class="img-holder compareContainer"><img id="img-CompareProdId-' + Id + '" src="' + window.rootRel +
            'ImageHandler.axd?ownerTable=Products&ownerId=' + Id +
            '&width=90&height=66&constraint=4&interpolate=7&async=true" height="66" width="66" alt="' + (Name.toString().length > 40 ? Name.toString().replace('"', '&quot;').substring(0, 40) + '...' : Name) +'"></div><div class="text">' +
            (Name.toString().length > 40 ? Name.toString().substring(0, 40) + "..." : Name) + '</div><a id="' + Id +
            '" onclick= "pCompare.onclickRemove(this)"><span class="remove"></span><span class="sr-only">close</span></a>';

        //append to container
        var compContainer = $('#compareContainer' + n);
        compContainer.html(imgThumb);
        compContainer.removeClass("empty");

        return true;
    };

    var updateProductArray = function() {
        var ids = '';
        var data = '';
        var compareContainer = $('.compareContainer');
        compareContainer.children().each(function() {
            var prod = $(this);
            var id = prod.attr('id');
            var name = prod.attr('alt');
            if (id.indexOf('img-CompareProdId-') >= 0) {
                var prodId = prod.attr('id').replace('img-CompareProdId-', '');
                data += '|' + prodId + '$' + name.replace('"', '&quot;');
                ids += '|' + prodId;
            }
        });
        data = data.substring(1);

        var idTemp = data.split('|');
        var compBut = $('#btnCompareProducts');
        var compLink = $('.compareLink');

        if (idTemp.length > 1) {
           
            compBut.attr('onclick', 'pCompare.CompareProdView("' + ids + '");return false;');
            compLink.each(function() {
                $(this).attr('onclick', 'pCompare.CompareProdView("' + ids + '");return false;');
            });
        } else {
            compBut.attr('onclick', 'showHenrysMsg("' + window.res.ProductCompareError + '");return false;');        
        }
        $.cookie('previousPage', window.location.href, { path: '/' });
        $.cookie('prodCompIDs', data, { path: '/' });

        if (data === '') {
            $(".popup-wrap").css("display", "none");
        } else {
            $(".popup-wrap").css("display", "block");
        }

    };

    productCompare.prototype.ProductComparisonInit = function() {
        var idProdTemp = $.cookie('prodCompIDs');
        if (idProdTemp) {
            var idProd = idProdTemp.split('|');

            var k = 1;
            for (var i in idProd) {
                var n = parseInt(i) + 1;
                var Id = idProd[n - 1];
                var data = Id.split("$");
                if (data[0] > 0) {
                    addCompareProduct(data[0], data[1], k);
                    $('#checkbox-ProdId-' + data[0]).attr('checked', true);
                    k++;
                }
            }
        } 

        updateProductArray();
    };

    productCompare.prototype.check_checkBox = function(Id) {
        var obj = document.getElementById('checkbox-ProdId-' + Id);
        if (!obj.checked) {
            obj.checked = true;
        } else {
            obj.checked = false;
        }
        this.onclick_CheckboxCompare(obj);
    };

    productCompare.prototype.onclick_CheckboxCompare = function(obj) {
        var productLimit = 4;
        var idProd = obj.id.toString().replace('checkbox-ProdId-', '');
        var prodName = $("#lblName-" + idProd).attr("rel").replace('"', '&quot;');

        if (obj.checked === true) {
            var success = false;
            for (var n = 1; n <= productLimit; n++) {
                var compContainer = $('#compareContainer' + n);
                if ($.trim(compContainer.html()).indexOf('add-more') > -1) {
                    success = addCompareProduct(idProd,prodName, n);
                    break;
                }
            }

            if (!success) {
                obj.checked = false;
                showHenrysMsg(window.res.ProductCompareOverLimit.format(productLimit));
            } else {
                $(".popup-wrap").css("display", "block");
            }

        } else {
            $('#img-CompareProdId-' + idProd).parent().parent().html(' <span class="add-more hidden-sm hidden-xs">Add up to 4 items to compare.</span><span class="add-more visible-sm">Add up to 2 items to compare.</span>').addClass("empty");
        
        }

        updateProductArray();
    };

    productCompare.prototype.CompareProdView = function(ids) {
        var page = window.rootRel + 'ProductCompare/' + ids;
        BootstrapDialog.show({
            cssClass: 'product-modal compare-product-modal',
            message: $('<div></div>').load(page),
            type: BootstrapDialog.defaultMessage
    });
    };

    return productCompare;
})(jQuery);;
'use strict';
/**
 * Responsible for most behavior within the Address Module such as:
 *  - Displaying the Country list and calling the sub-form directive
 *  - Returning data from sub-form
 */
angular.module('address')
    .directive('henrysAddressForm', ['$compile', '$http', '$modal', 'AddressSvc', 'appUrlBuilder', 'DialogService', 'siteRes',
       function ($compile, $http, $modal, addressSvc, appUrlBuilder, dialogService, siteRes) {
            return {
                restrict: 'A',
                templateUrl: appUrlBuilder.buildTemplateUrl('addressFormTemplateUrl'),
                scope: {
                    addressData: '=',
                    onDone: '&',
                    onEdit: '&',
                    doneButtonLabelKey: '@',
                    isShippingForm: '@',
                    isAccountForm: '@',
                    triggerDoneButtonEvent: '=',
                },

                link: function (scope,element) {

                    scope.selectedCountry = {};
                    var rootUrl = appUrlBuilder.buildUrl('addressFormTemplateUrl');
                    var childScope;
                    var addressData = scope.addressData;

                    addressSvc.getCountryInfos().$promise.then(
                        function (data) {
                            scope.countryInfos = data.countryInfos;
                            scope.setSelectedCountry();
                        }
                    );

                    scope.done = function (data) {
                        scope.onDone({ data: data });
                    };

                    scope.edit = function () {
                        scope.onEdit();
                    };

                    scope.$watch('addressData', function () {
                        if (scope.addressData) {
                            scope.setSelectedCountry();
                        }
                    });

                    scope.changeCountry = function(country) {
                        if (country) {
                            scope.selectedCountry = country;
                        }
                    }


                    scope.setSelectedCountry = function () {

                        if (scope.addressData) {
                            if (scope.countryInfos && scope.addressData.country) {
                                if (scope.addressData.country.countryCode == '') {
                                    scope.addressData.country = scope.countryInfos[0];
                                }
                                angular.forEach(scope.countryInfos, function (countryInfo) {
                                    if (scope.addressData.country.countryCode == countryInfo.countryCode) {
                                        scope.selectedCountry = countryInfo;
                                    }
                                    if (scope.addressData.country.countryId == countryInfo.countryId) {
                                        scope.selectedCountry = countryInfo;
                                    }
                                });
                            }
                        }
                    };

                    scope.$watch('selectedCountry', function(selectedCountry) {
                        //disable "Create Account" button
                        scope.onEdit();

                        var url = rootUrl;
                        if (selectedCountry.countryCode) {
                            url += '?Country=' + selectedCountry.countryCode +
                                '&DoneButtonLabelKey=' + scope.doneButtonLabelKey +
                                '&isShippingForm=' + scope.isShippingForm +
                                '&isAccountForm=' + scope.isAccountForm;
                            addressData = scope.addressData;

                        $http.get(url, {
                        
                        }).success(
                            function(html) {
                                if (childScope) {
                                    childScope.$destroy();
                                }
                                element.html(html);

                                childScope = scope.$new();

                                childScope.showValidateButton = false;
                                childScope.enableValidateButton = true;
                                childScope.showDoneButton = true;
                                childScope.enableDoneButton = true;
                                childScope.showEditButton = false;
                                childScope.lockFields = false;

                                childScope.addressData = addressData;
                                childScope.selectedCountry = selectedCountry;
                                childScope.triggerDoneButtonEvent = scope.triggerDoneButtonEvent ? scope.triggerDoneButtonEvent : false;
                                childScope.provinces = {};

                                if (childScope.addressData && (childScope.selectedCountry && childScope.addressData.country.countryCode === childScope.selectedCountry.countryCode)) {
                                    childScope.fullForm = angular.copy(childScope.addressData);
                                    childScope.fullForm.country = childScope.selectedCountry;
                                } else {
                                    if (childScope.selectedCountry) {
                                        childScope.fullForm = { country: childScope.selectedCountry };
                                    }
                                }

                                if (childScope.selectedCountry.countryCode) {
                                    //If mode is not "no lookup"
                                    childScope.showValidateButton = true;
                                    //Other buttons such as lookup
                                    childScope.showLookupButton = true;
                                    childScope.enableLookupButton = true;

                                    //in the future maybe dynamically call the following web api based on the field in the json file
                                    //have not finalized it yet and will revisit it
                                    if (selectedCountry.countryCode == 'CA' || selectedCountry.countryCode == 'US') {
                                        addressSvc.getCountryProvinces(selectedCountry.countryCode).$promise.then(
                                            function(data) {
                                                childScope.provinces = data.provinces;
                                            }
                                        );
                                    }

                                }


                                childScope.validateForm = function() {

                                    childScope.enableValidateButton = false;

                                    addressSvc.validateAddress(childScope).$promise.then(
                                        function(value) {

                                            childScope.gasResponse = angular.copy(value);
                                            if (childScope.gasResponse.length > 0) {
                                                var modalInstance = $modal.open({
                                                    templateUrl: appUrlBuilder.buildTemplateUrl('addressValidateModalUrl'),
                                                    controller: 'addressValidateCtrl',
                                                    backdrop: 'static',
                                                    resolve: {
                                                        addressList: function() {
                                                            return childScope.gasResponse;
                                                        },
                                                        enteredAddress: function() {
                                                            return childScope.fullForm;
                                                        }
                                                    }
                                                });

                                                modalInstance.result.then(function(selectedAddress) {
                                                    childScope.fullForm = selectedAddress;
                                                    childScope.lockFullForm();
                                                    childScope.enableValidateButton = true;
                                                    childScope.triggerDoneButtonEventIfNeeded(childScope.triggerDoneButtonEvent);
                                                }, function() {
                                                    //Canceled or Closed
                                                    childScope.enableValidateButton = true;
                                                });
                                            } else {
                                                dialogService.alert(siteRes.ValAdd_NoMatch);
                                                console.log('Validate Address: No match returned.');
                                                childScope.enableValidateButton = true;
                                            }

                                        }, function() {
                                            dialogService.alert(siteRes.ValAdd_Error);
                                            console.log('Validate Address: error occured.');
                                            childScope.enableValidateButton = true;
                                            childScope.showDoneButton = true;
                                        }
                                    );


                                };

                                childScope.triggerDoneButtonEventIfNeeded = function(triggerDoneButtonEvent) {
                                    if (triggerDoneButtonEvent) {
                                        childScope.done();
                                    }
                                };

                                childScope.lookupForm = function() {

                                    childScope.enableLookupButton = false;

                                    addressSvc.lookupAddress(childScope).$promise.then(
                                        function(value) {
                                            childScope.gasResponse = angular.copy(value);
                                            if (childScope.gasResponse.length > 0) {
                                                var modalInstance = $modal.open({
                                                    templateUrl: appUrlBuilder.buildTemplateUrl('addressLookupModalUrl'),
                                                    controller: 'addressLookupCtrl',
                                                    backdrop: 'static',
                                                    resolve: {
                                                        addressList: function() {
                                                            return childScope.gasResponse;
                                                        },
                                                        enteredAddress: function() {
                                                            return childScope.fullForm;
                                                        }
                                                    }
                                                });

                                                modalInstance.result.then(function(selectedAddress) {
                                                    childScope.fullForm = selectedAddress;
                                                    childScope.lockFullForm();
                                                    childScope.enableLookupButton = true;
                                                    childScope.triggerDoneButtonEventIfNeeded(childScope.triggerDoneButtonEvent);
                                                }, function() {
                                                    //Canceled or Closed
                                                    childScope.enableLookupButton = true;
                                                });
                                            } else {
                                                dialogService.alert(siteRes.ValAdd_NoMatch);
                                                console.log('Lookup Address: No match returned.');
                                                childScope.enableLookupButton = true;
                                            }
                                        }, function() {
                                            dialogService.alert(siteRes.LookupAdd_Error);
                                            console.log('Lookup Address: error occured.');
                                            childScope.enableLookupButton = true;
                                            childScope.showDoneButton = true;
                                        }
                                    );
                                };
                                //Other functions such as lookup and autocomplete.

                                childScope.done = function() {
                                    scope.enableDoneButton = false;

                                    if (!angular.isUndefined(childScope.orderComments)) {
                                        scope.$parent.checkoutState.orderComments = childScope.orderComments;
                                    }
                                   
                                    scope.addressData = angular.copy(childScope.fullForm);
                                    if (childScope.selectedCountry) {
                                        scope.addressData.country = angular.copy(childScope.selectedCountry);
                                    }
                                    scope.done(scope.addressData);
                                    scope.enableDoneButton = true;
                                };
                                childScope.lockFullForm = function() {
                                    childScope.lockFields = true;
                                    childScope.showEditButton = true;
                                    childScope.showValidateButton = false;
                                };
                                childScope.editForm = function() {
                                    if (childScope.lockFields === true) {
                                        childScope.showValidateButton = true;
                                        childScope.lockFields = false;
                                        childScope.showEditButton = false;
                                        scope.edit();
                                    }
                                };

                                $compile(element.contents())(childScope);
                            }
                        );
                    }
                    });

                }
            };
        }]);

;
'use strict';

angular.module('address')
    .controller('addressAutocompleteCtrl', ['$scope',
        function ($scope) {
            $scope.onAutocompleteAddressSelected = function ($item, $model) {
                $scope.fullForm = {
                    FirstName: $scope.fullForm.FirstName,
                    LastName: $scope.fullForm.LastName,
                    address1: $model._address1,
                    address2: $model._address2,
                    address3: $model._address3,
                    city: $model._city,
                    province: $model._state,
                    postalCode: $model._zipCode,
                    country: {
                        countryCode: $model._country._countryCode,
                        countryId: $model._country._id,
                        countryName: $model._country._name,
                    },
                   PhoneNumber: $scope.fullForm.PhoneNumber,
                };
                $scope.lockFullForm();
            };
        }]);;
'use strict';
/**
 * Responsible for all checkout specific logic
 */
angular.module('checkout').controller('CheckoutCtrl', ['$scope', '$window', 'CheckoutSvc', 'CartDataStorageService', 'ShippingService', 'AppObserver', 'AddressDataHelper', 'siteConfiguration', 'siteRes', 'CheckoutDataStorageService', 'CheckoutSubmitCartSvc', 'CheckoutHelperService', 'anchorHelper',"DialogService",
    function ($scope, $window, checkoutSvc, cartDataStorageService, shippingService, appObserver, addressDataHelper, siteConfiguration, siteRes, checkoutDataStorageService, checkoutSubmitCartSvc, checkoutHelperService, anchorHelper,dialogService) {

        $scope.cartData = cartDataStorageService.cartData;
        $scope.checkoutState = checkoutDataStorageService.checkoutState;
        $scope.checkoutState.useExistingCard = false;
        $scope.identityName = 'CheckoutCtrl';
        $scope.password = '';
        $scope.checkoutState.existingCreditCardData = '';
        $scope.checkoutState.invalidCscForExistingCard = true;
        $scope.checkoutState.selectedAddress = 0;
        $scope.checkoutState.customerShippingAddresses = '';
        $scope.checkoutState.checkoutTermsChecked = false;
        $scope.isDisabled = false;
        $scope.hpciEnabled = checkoutSvc.hpciEnabled();
        $scope.checkoutState.orderComments = '';
        $scope.EnableDPO = false;
        $scope.DPOSelected = false;
        $scope.postalCodeRegex = siteConfiguration.postalCodeRegex;
        $scope.emailRegex = siteConfiguration.emailRegex;
        $scope.firstName = '';
        $scope.lastName = '';
        $scope.updateShippingAddressSuccess = true;
        var shippingAddressIsEmpty = true;
        $scope.storeLocatorPostalCode = '';
        $scope.storeLocatorPostalCodeHasGeocode = false;
        $scope.map = '';
        $scope.mapDpo = '';
        $scope.userLocation = {};//used only if for any reason user shipping address postal code is not considered valid
        $scope.MapUserLocation;//user for marking the users current position on map, it could be based on postal code entered in storelocator or geolocation see initmap and initmapdpo below
        $scope.storeLocatorLongitude = '';
        $scope.storeLocatorLatitude = '';
        $scope.storeLocatorKmRange = 50;
        $scope.storeLocatorPostalCode = '';
        $scope.selectedPO = {};

        AddHistoryUrl(-1, "checkout", "");
        $scope.showConfirmDialog = function () {
            dialogService.show({
                title: globalConstants.checkoutGoBackDialogTitle,
                closable: false,
                message: globalConstants.checkoutGoBackDialogMessage,
                buttons: [
                    {
                        label: "Yes",
                        cssClass: 'btn-primary',
                        action: function (dialog) {
                            history.go(-2);
                            dialog.close();
                        }
                    }, {
                        label: "No",
                        cssClass: 'btn-default',
                        action: function (dialog) {
                            AddHistoryUrl(2, "Shipping Address", "shippingAddressAnchor");
                            dialog.close();
                        }
                    }
                ]
            });

        };

        $scope.loadcheckoutstep = function(step) {
            switch (step.currentStage) {
                case 2:
                    $scope.editShippingInfo();
                    break;
                case 3:
                    $scope.editShippingUsing();
                    break;
                case 4:
                    $scope.editPaymentInfo();
                    break;
                case 5:
                    $scope.editBillingInfo();
                    break;
                case 6:
                    $scope.billingSectionDone();
                    break;
            default:
            }
        };

        $scope.preloadData = function () {
            //preload cart data
            cartDataStorageService.loadCartData().then(function () {
                //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);
                }

                //if the address was updated use what they updated
                //else use the last order address
                //else use empty
                var sAddress;
                if ($scope.cartData.addressInfo.ShippingAddress.address1 != '' && $scope.cartData.addressInfo.ShippingAddress.City != '') {
                    sAddress = $scope.cartData.addressInfo.ShippingAddress;
                } else {
                    sAddress = $scope.cartData.signedIn && !$scope.PayPalExpress ? lastOrderInfo.ShippingAddress : $scope.cartData.addressInfo.ShippingAddress;
                }
              
                //if its empty and signed in use billing
                shippingAddressIsEmpty = sAddress.Address1 === '' && sAddress.City === '' && sAddress.Province === '';
                if ($scope.cartData.signedIn && shippingAddressIsEmpty) {
                    sAddress = $scope.cartData.addressInfo.BillingAddress;
                }
                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
                $scope.shippingRate = currentOrderInfo.ShipperId;
                if ($scope.cartData.signedIn) {
                    shippingAddress.PhoneNumber = billingAddress.PhoneNumber =  $scope.cartData.phone = shippingAddressIsEmpty ? $scope.cartData.customer.Phone : lastOrderInfo.Phone;
                    $scope.cartData.email = shippingAddressIsEmpty ? $scope.cartData.customer.Email : lastOrderInfo.Email;
                    $scope.updateShippingAddress(shippingAddress, true);
                    // Note: ReceiverName is deprecated since we have it in the AddressInfo of the shipping object
                    $scope.cartData.receiverName = '';
                    $scope.cartData.isGift = currentOrderInfo.IsGift;
                    $scope.cartData.giftNote = currentOrderInfo.GiftNote;
                    $scope.checkoutState.paymentType = $scope.PayPalExpress ? 2 : 0;
                    $scope.checkoutState.addressSec = true;
                    $scope.checkoutState.paymentSec = false;
                    $scope.checkoutState.shippingMethodSec = false;
                    $scope.checkoutState.createAccountSec = false;
                    $("#shipping-detail-section").click();
                    if ($scope.cartData.items) {
                        // FireCheckoutClickDataEvent($scope.cartData.items,0);
                        FireCheckoutClickDataEvent($scope.cartData.items, 1);
                    }
                    //get existing credit cards
                    checkoutSvc.getExistingCreditCards().$promise.then(function (value) {
                        $scope.checkoutState.customerExistingCreditCards = value;

                        if ($scope.checkoutState.customerExistingCreditCards != undefined && $scope.checkoutState.customerExistingCreditCards.length > 0) {
                            //$scope.checkoutState.hasExistingCards = true;
                            $scope.checkoutState.existingCreditCardData = $scope.checkoutState.customerExistingCreditCards[0];
                            $scope.checkoutState.useExistingCard = true;
                            window.setTimeout(function () {
                                initCustomForms();
                            }, 1000);
                        }
                    }, function (error) {
                        console.log('Error for getExistingCreditCards()', error);
                    });

                    $scope.checkoutState.currentStage = 3;
                } else {
                    checkoutSvc.checkCustomerExists($scope.cartData.email).$promise.then(
                        function (value) {
                            $scope.checkoutState.createAccountSec = !value.exists;
                        }, function (error) {
                            $scope.checkoutState.createAccountSec = false;
                        });

                    $scope.checkoutState.addressSec = true;
                    $scope.checkoutState.shippingMethodSec = false;
                    $scope.checkoutState.paymentSec = false;
                    $("#shipping-detail-section").click();
                    if ($scope.cartData.items) {
                      //  FireCheckoutClickDataEvent($scope.cartData.items,0);
                        FireCheckoutClickDataEvent($scope.cartData.items, 1);
                    }
                }
                $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.toggleTermsCheckout = function () {
            if ($scope.checkoutState.checkoutTermsChecked === true) {
                $scope.checkoutState.checkoutTermsChecked = false;
            } else {
                $scope.checkoutState.checkoutTermsChecked = true;
            }
        };

        $scope.updateSelectedCreditCard = function (card) {
            $scope.checkoutState.existingCreditCardData.Csc = '';
            $scope.checkoutState.invalidCscForExistingCard = true;
        }

        $scope.updateSelectedCreditCardCSC = function (csc) {
            if (csc === null || csc === undefined || csc == '') {
                $scope.checkoutState.invalidCscForExistingCard = true;
            } else {
                $scope.checkoutState.invalidCscForExistingCard = false;
            }
        }

        $scope.paymentSectionDone = function () {
            $scope.checkoutState.paymentSec = false;
            $scope.checkoutState.billingSec = true;

            //if they choose CC payments hide QC from billing section
            if ($scope.checkoutState.paymentType === 1) {
                //$(".billing-address-form #fullForm_province option:contains('Quebec')").remove();
                //$(".address-form #fullForm_province option:contains('Quebec')").remove();
                $(".address-form #country").val(0);
                $(".address-form #country").prop('disabled', true);
                $(".billing-address-form #country").val(0);
                $(".billing-address-form #country").prop('disabled', true);
            } else {
            
                $(".address-form #country").prop('disabled', false);
                $(".billing-address-form #country").prop('disabled', false);
            }
      
           
            delayClick("#billing-section");
            //anchorHelper.setAnchor('billing-address');
            if ($scope.cartData.items)
                {
                    FireCheckoutClickDataEvent($scope.cartData.items, 4);
                }
        }

        $scope.updateShippingAddress = function (data, isInit) {
            showSpinner("Updating shipping information...");
            $scope.addressData.shippingData = data;
            addressDataHelper.updateShippingData(data);
            $scope.cartData.phone = data.PhoneNumber;

            if ($scope.cartData.phone != '') {
                checkoutSvc.updateCustomerPhoneNumber($scope.cartData.phone);
            }

            if ($scope.checkoutState.orderComments != '') {
                checkoutSvc.addComments($scope.checkoutState.orderComments);
            }

            $scope.storeLocatorPostalCode = data.postalCode;        

            addressDataHelper.updateBillingData(data);
            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 (value) {
                    $scope.getShippingRates(data);
                    //anchorHelper.setAnchor('shippingAddressAnchor');
                    $scope.updateShippingAddressSuccess = true;
                    if (!value.Success) {
                        console.log(value.Message);
                    }
                   
                    if (!isInit) {
                        $scope.checkoutState.addressSec = false;
                        $scope.checkoutState.shippingMethodSec = true;
                        delayClick("#shipping-method-section");
                        if ($scope.cartData.items) {
                            FireCheckoutClickDataEvent($scope.cartData.items, 2);
                        }
                    }
                   
                    hideSpinner();

                }, function () {
                    $scope.updateShippingAddressSuccess = false;
                    console.log('updateShippingAddress error occur');
                hideSpinner();
            });
        };

        $scope.billingSectionDone = function () {
            $scope.checkoutState.billingSec = false;
            $scope.checkoutState.finalSec = true;
            delayClick("#final-section");
    if ($scope.cartData.items)
        { FireCheckoutClickDataEvent($scope.cartData.items, 5); }
        }

       

        $scope.billingAddressDone = function (data) {
            addressDataHelper.updateBillingData(data);
            $scope.addressData.billingData = addressDataHelper.getBillingData();
            checkoutSvc.addAddressDataToOrderForm(addressDataHelper.getShippingData(), addressDataHelper.getBillingData(), addressDataHelper.getSameAsShippingAddress()).$promise.then(
                function () {
                    if (!addressDataHelper.getSameAsShippingAddress()) {
                        cartDataStorageService.loadCartData();
                    }
                }, function (error) {
                    console.log(error);
                });
            delayClick("#final-section");
            if ($scope.cartData.items)
            { FireCheckoutClickDataEvent($scope.cartData.items, 5); }
            $scope.checkoutState.billingSec = false;
            $scope.checkoutState.finalSec = true;
            $scope.firstName = data.FirstName;
            $scope.lastName = data.LastName;
            //anchorHelper.setAnchor('billing-address');
           
        };

        $scope.editBillingInfo = function () {
            // anchorHelper.setAnchor('billing-address');
            $scope.checkoutState.finalSec = false;
            $scope.checkoutState.paymentSec = false;
            $scope.checkoutState.billingSec = true;
            delayClick("#billing-section");
            //if ($scope.cartData.items) {
            //    FireCheckoutClickDataEvent($scope.cartData.items, 4);
            //}
        };

        $scope.sameAsShipping = function (value) {
            $scope.billingSame = value;
            addressDataHelper.updateSameAsShippingAddress(value);
           
        };

        //Region payment

        $scope.onSubmitCart = function () {
            $scope.isDisabled = true;
            if (!$scope.shippingRate) {
                $scope.checkoutState.sumitCartErrorSec = true;
                $scope.checkoutState.errorMessage = siteRes.SelectShippingRate;
                $scope.isDisabled = false;
                return false;
            }

            if (!$scope.cartData.signedIn) {
                $scope.cartData.customerData = {};
                if ($scope.checkoutState.createAccountSec && $scope.checkoutState.accountPasswordSec) {
                    //$scope.submitGuestOrder(false);
                    $scope.$broadcast('show-errors-check-validity', 'accountPasswordForm');
                    if ($scope.accountPasswordForm.$invalid || $scope.password != $scope.confirmPassword) {
                        $scope.isDisabled = false;
                        return false;
                    }

                    $scope.cartData.customerData.password = $scope.password;

                } else {
                    //$scope.submitGuestOrder(true);
                    $scope.cartData.customerData.userId = checkoutHelperService.guid();
                    $scope.cartData.customerData.password = $scope.password = Math.random().toString(36).slice(-8);
                }
                $scope.cartData.customerData.email = $scope.cartData.email;
                $scope.cartData.customerData.phone = $scope.cartData.phone;
                $scope.cartData.customerData.firstName = $scope.firstName;
                $scope.cartData.customerData.lastName = $scope.lastName;
                $scope.cartData.customerData.password = $scope.password;
                $scope.cartData.customerData.address = addressDataHelper.getBillingData();
                $scope.cartData.customerData.EmailOptIn = $scope.cartData.signupNewsletter;

            }

            if ($scope.cartData.signupNewsletter) {
                var optIn = "true";
                checkoutSvc.addEmailOptIn(optIn);
            }
             
            console.log($scope.addressData.billingData);
            console.log($scope.addressData.shippingData);
            console.log($scope.checkoutState.paymentType);

            var proceedCheckout = true;
            if ($scope.checkoutState.paymentType == 1) {
                if ($scope.addressData.billingData.country.countryId != 1 ||
                    $scope.addressData.shippingData.country.countryId != 1) {
                    $scope.checkoutState.paymentSec = true;
                    $scope.togglePaymentMethod(2);
                    $scope.paymentMethods.showPayPalChecked = true;
                     proceedCheckout = false;
                    delayClick("#payment-method-section");
alert("Please proceede with Paypall becuase we do not accept International credit cards");
                } 
            }

            if (proceedCheckout) {
                checkoutSubmitCartSvc.submitOrder($scope.checkoutState, $scope.cartData);

                if (!$scope.checkoutState.sumitCartErrorSec) {
                    $scope.checkoutState.finalSec = false;
                    $scope.checkoutState.paymentSec = true;
                    delayClick("#payment-method-section");

                }
            }
            $scope.isDisabled = false;
            return true;
        };

        //try to submit a card on hpci processed, this method is called externally, from hpci handler
        $scope.onHpciProcessed = function () {
            if ($scope.checkoutState.hpciProcessed === true) {
                //alert('yes');
                checkoutSubmitCartSvc.processCreditCardPayment($scope.checkoutState, $scope.cartData);
            }
        };

        //EndRegion payment

        //Region 3ds

        $scope.verify3Ds = function () {
            return checkoutSubmitCartSvc.verify3Ds($scope.checkoutState);
        };

        //EndRegion 3ds

        $scope.phoneEmailSecDone = function () {
            //anchorHelper.setAnchor('shippingMethodAnchor');
            $scope.$broadcast('show-errors-check-validity', 'phoneEmailForm');
            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;
                    $scope.checkoutState.currentStage = 3;
                },
                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;
            if ($scope.checkoutState.accountPasswordSec) {
                $scope.checkoutState.accountPasswordSec = false;
            } else {
                $scope.checkoutState.accountPasswordSec = true;
            }

        };

        $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;
                }
            }
    

            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.toString().trim() === '') {
                $scope.cartData.phone = '555-555-5555';
            }
            customerData.email = $scope.cartData.email;
            customerData.phone = $scope.cartData.phone;
            customerData.firstName = $scope.firstName;
            customerData.lastName = $scope.lastName;
            customerData.password = $scope.password;
            customerData.address = addressDataHelper.getBillingData();

            checkoutSubmitCartSvc.submitGuestOrder(customerData, $scope.checkoutState, $scope.cartData);
        };

        $scope.paymentMethods = {
            showCreditCardChecked: $scope.checkoutState.paymentType === 1,
            showPayPalChecked: $scope.checkoutState.paymentType === 2
        };

        $scope.toggleNewCard = function () {
            if ($scope.checkoutState.useExistingCard) {
                $scope.checkoutState.useExistingCard = false;
            } else {
                $scope.checkoutState.useExistingCard = true;
            }
        }

        $scope.togglePaymentMethod = function (paymentType) {

            if (paymentType === 1) {
                $scope.paymentMethods.showCreditCardChecked = true;
                if ($scope.checkoutState.customerExistingCreditCards != undefined && $scope.checkoutState.customerExistingCreditCards.length > 0) {
                    $scope.checkoutState.existingCreditCardData = $scope.checkoutState.customerExistingCreditCards[0];
                    $scope.checkoutState.useExistingCard = true;
                    window.setTimeout(function () {
                        initCustomForms();
                    }, 500);
                }
            } else if(paymentType === 2) {
                $scope.paymentMethods.showPayPalChecked = true;
                $scope.checkoutState.useExistingCard = false;
            }
          


            if ($scope.paymentMethods.showCreditCardChecked === true && $scope.paymentMethods.showPayPalChecked === true) {
                switch (paymentType) {
                    case 1:
                        $scope.paymentMethods.showPayPalChecked = false;
                        break;
                    case 2:
                        $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 {
                $scope.checkoutState.paymentType = 0;
            }
            $scope.checkoutState.paymentSec = true;
        };

        $scope.receiverSecDone = function () {
            $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 () {
                        //anchorHelper.setAnchor('shippingMethodAnchor');
                        $scope.checkoutState.receiverSec = false;
                        $scope.checkoutState.deliverToSec = true;
                        $scope.checkoutState.shippingMethodSec = true;
                    });
            }
        };

        $scope.editShippingInfo = function () {
            $scope.checkoutState.finalSec = false;
            $scope.checkoutState.addressSec = true;
            delayClick("#shipping-detail-section");
        };

        $scope.shippingMethodSecDone = function () {
            $scope.checkoutState.shippingMethodSec = false;
            $scope.checkoutState.paymentSec = true;
            delayClick("#payment-method-section");
            $scope.checkoutState.currentStage = 3;
               if ($scope.cartData.items)
                   {
                    FireCheckoutClickDataEvent($scope.cartData.items, 3);
                   }
        };

        $scope.editShippingUsing = function () {
            $scope.checkoutState.finalSec = false;
            $scope.checkoutState.addressSec = false;
            $scope.checkoutState.shippingMethodSec = true;
            delayClick("#shipping-method-section");
        };

        $scope.editPaymentInfo = function () {
            $scope.checkoutState.finalSec = false;
            $scope.checkoutState.shippingMethodSec = false;
            $scope.checkoutState.paymentSec = true;
            delayClick("#payment-method-section");
        }

        $scope.getShippingRates = function (shippingData) {
            showSpinner("Getting shipping rates...");
            var shippingCountry = shippingData.country.countryId;
            var shippingProvince = shippingData.province || '';
            var shippingPostalCode = shippingData.postalCode;
            shippingService.getShippingRates(shippingCountry, shippingProvince, shippingPostalCode, false).$promise.then(function (value) {
                $scope.shippingRates = value.shippingRates;
                // default is nothing selected
                    if ($scope.shippingRate) {
                        angular.forEach($scope.shippingRates, function (rate) {
                            if (rate.Id == $scope.shippingRate) {
                                $scope.shippingMethod = rate.Name;
                                $scope.checkoutState.shippingSelected = true;

                                 if (rate.EnableShipToPostOffice) {
                                    $scope.EnableDPO = true;
                                 } else {
                                     $scope.EnableDPO = false;
                                 }
                            }
                    });               
                        $scope.updateShippingRate({ Name: $scope.shippingMethod, Id: $scope.shippingRate }, true);
                    }
            });

            hideSpinner();
        };

        $scope.updateShippingRate = function (rate, initLoad) {
            showSpinner("Updating shipping rate...");
            //update cart shipper id & reload cart data after rate change
            shippingService.updateShippingRate($scope.shippingRate).$promise.then(
                function () {
                    $scope.DPOSelected = false;
                    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.checkoutState.shippingSelected = true;

                        appObserver.broadcast('shippingRateChanged', rate);
                        if (rate.EnableShipToPostOffice) {
                            $scope.EnableDPO = true;
                        } else {
                            $scope.EnableDPO = false;
                            checkoutSvc.resetDpo();
                        }
                    }
                    if ($scope.EnableDPO) {
                        $("#rdoShipHome").prop("checked", true);
                    }

                    hideSpinner();
                }
            );
        };

        $scope.shipToHome = function() {
            $scope.checkoutState.shippingSelected = true;
            checkoutSvc.resetDpo();
        };

        $scope.getDpoStores = function () {
            showSpinner("Searching for post offices near you...");
            checkoutSvc.getGeoCodeForPostalCode($scope.storeLocatorPostalCode).$promise.then(
                function (value) {
                    if (value.postalcodeExists) {
                        $scope.storeLocatorPostalCodeHasGeocode = true;
                        $scope.storeLocatorLongitude = value.Longitude;
                        $scope.storeLocatorLatitude = value.Latitude;
                        return;
                    } else {
                        $scope.storeLocatorPostalCodeHasGeocode = false;
                        return;
                    }

                });

            checkoutSvc.getDpoStores($scope.shippingRate, $scope.cartData.addressInfo.BillingAddress.Country.CountryCode, $scope.storeLocatorPostalCode, $scope.storeLocatorKmRange).$promise.then(function (value) {
                $scope.DpoStores = value.allStores;
                if ($scope.storeLocatorPostalCodeHasGeocode) {
                    $scope.initMapDpo();
                } else {
                    $scope.GetUsersCurrentPosition();
                }
              
            });
            $scope.checkoutState.shippingSelected = false;
            
        };

        $scope.getUpdatedDpoList = function (postalCode) {
            showSpinner("Searching for post offices near you...");
         
            if (postalCode === '' || postalCode === undefined) {
                return false;
            }
            if (!$scope.postalCodeRegex.test(postalCode)) {
                return false;
            }

            checkoutSvc.getGeoCodeForPostalCode(postalCode).$promise.then(
                function (value) {
                    if (value.postalcodeExists) {
                        $scope.storeLocatorPostalCodeHasGeocode = true;
                        $scope.storeLocatorLongitude = value.Longitude;
                        $scope.storeLocatorLatitude = value.Latitude;
                        return false;
                    } else {
                        $scope.storeLocatorPostalCodeHasGeocode = false;
                        return false;
                    }

                }, function (error) {
                    $scope.storeLocatorPostalCodeHasGeocode = false;
                });

            checkoutSvc.getDpoStores($scope.shippingRate,$scope.cartData.addressInfo.ShippingAddress.Country.CountryCode, postalCode, $scope.storeLocatorKmRange).$promise.then(function (value) {
                $scope.DpoStores = value.allStores;
                $scope.initMapDpo();
            });

        };

           $scope.initMapDpo = function () {
            var stores = $scope.DpoStores;
            var lat;
            var longitude;
            if ($scope.storeLocatorPostalCodeHasGeocode) {
                lat = $scope.storeLocatorLatitude;
                longitude = $scope.storeLocatorLongitude;
                $scope.MapUserLocation = new google.maps.LatLng(lat, longitude);
            }
            else {
             
                if ($scope.userLocation && $scope.userLocation.length > 0) {
                    lat = $scope.userLocation.lat();
                    longitude = $scope.userLocation.lng();
                    $scope.MapUserLocation = new google.maps.LatLng(lat, longitude);
                } else if (stores != undefined && stores[0] != null) {
                    lat = stores[0].Latitude;
                    longitude = stores[0].Longitude;
                    $scope.MapUserLocation = new google.maps.LatLng(lat, longitude);
                } else {
                    return;
                }
            }

            var mapLocation = new google.maps.LatLng(lat, longitude);
            var mapOptions = {
                mapTypeControl: false,
                disableDefaultUI: true,
                streetViewControl: false,
                zoomControl: true,
                panControl: true,
                zoom: 9,
                center: mapLocation,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var mapdiv = $('#map_canvas');
            if (mapdiv === undefined) {
                return;
            }
            var mapdivFirst = $('#map_canvas')[0];
            if (mapdivFirst === undefined) {
                return;
            }
            $scope.mapDpo = new google.maps.Map($('#map_canvas')[0], mapOptions);
            var marker;
            if (stores === undefined || stores === null) {
                return;
            }
            stores.forEach(function (store) {
                mapLocation = new google.maps.LatLng(store.Latitude, store.Longitude);
                marker = new google.maps.Marker({
                    position: mapLocation,
                    map: $scope.mapDpo,
                    icon: globalConstants.rootUrl + '/Content/images/pins/pin' +store.Marker +'.png'
                });
                $scope.addInfoWindowDpo(marker, store.infoWindowHtml.toString());
            });

            var markerUser = new google.maps.Marker(
            {
                position: $scope.MapUserLocation,
                map: $scope.mapDpo,
                icon: globalConstants.rootUrl + '/Content/images/user-pin2.png'
               });

            var bounds = new google.maps.LatLngBounds();
            bounds.extend(marker.position);
            bounds.extend(markerUser.position);

            $scope.mapDpo.fitBounds(bounds);
               hideSpinner();
           };

                $scope.addInfoWindowDpo = function (marker, content) {
            var infoWindow = new google.maps.InfoWindow({
                content: content
            });

            google.maps.event.addListener(marker, 'click', function () {
                infoWindow.open($scope.mapDpo, marker);
            });
        };

          $scope.GetUsersCurrentPosition = function () {

            var options = {
                enableHighAccuracy: false,
                timeout: 10000,
                maximumAge: 0
            };

            navigator.geolocation.getCurrentPosition(
                function (pos) {

                    var crd = pos.coords;
                    $scope.userLocation = new google.maps.LatLng(crd.latitude, crd.longitude);
                    console.log('current position: ' + $scope.userLocation.lat() + ':' + $scope.userLocation.lng());
                    $scope.initMapDpo();
                },
                function () {
                    $scope.initMapDpo();
                },
                options);
          }

          $scope.addMapMarkerDpo = function (store) {
              var lat = store.Address._latitude;
              var longitude = store.Address._longitude;
              var markerId = store.Marker;

              var mapLocation = new google.maps.LatLng(lat, longitude);
              var mapOptions = {
                  mapTypeControl: false,
                  disableDefaultUI: true,
                  streetViewControl: false,
                  zoomControl: true,
                  panControl: true,
                  zoom: 11,
                  center: mapLocation,
                  mapTypeId: google.maps.MapTypeId.ROADMAP
              };

              $scope.mapDpo = new google.maps.Map($('#map_canvas')[0], mapOptions);
              var marker = new google.maps.Marker({
                  position: mapLocation,
                  map: $scope.mapDpo,
                  icon: globalConstants.rootUrl + '/Content/images/pins/pin' + markerId + '.png'
              });

              $scope.addInfoWindowDpo(marker, store.infoWindowHtml.toString());

              var markerUser = new google.maps.Marker(
              {
                  position: $scope.MapUserLocation,
                  map: $scope.mapDpo,
                  icon: globalConstants.rootUrl + '/Content/images/user-pin2.png'
              });
          };

          $scope.updateCartDpoStore = function (store) {
              var dpoUpdateStore = {
                  Id: store.Id,
                  Name: store.Name,
                  AddressLine1: store.Address._addressLine1,
                  City: store.Address._city,
                  PostalZipCode: store.Address._postalZipCode,
                  ProvinceState: store.Address._provinceState,
                  Location: store.Address._location,
                  Latitude: store.Latitude,
                  Longitude: store.Longitude,
                  ProximityInKm: store.ProximityInKm
              };

              checkoutSvc.postCartDpoStore(dpoUpdateStore).$promise.then(function (status) {

                  $scope.shippingPostOffice = store;
              });

              $scope.shippingPostOffice = store;
              $scope.shippingToPostOffice = true;

              $scope.checkoutState.shippingSelected = true;
          };
    }
]);
;
'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.initalize = function () {

            $scope.identityName = 'creditCardCtrl';

            $scope.checkoutState.creditCardData.cardNumber = '';
            $scope.checkoutState.creditCardData.expireMonth = 0;
            $scope.checkoutState.creditCardData.expireYear = 0;
            $scope.checkoutState.creditCardData.cardValidation = '';
            $scope.checkoutState.creditCardData.name = '';

            $scope.useShippingAddress = true;

            $scope.CreditCardInputType = 'password';
            $scope.CvvInputType = 'password';

            //$scope.isCardNumberValid = true;
            $scope.isExpireMonthValid = true;
            $scope.isExpireYearValid = true;
            //$scope.isCardTypeValid = true;
            //$scope.isCardValidationValid = true;
            $scope.isNameValid = true;

            $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.hpciEnabled = checkoutSvc.hpciEnabled();
        };

        $scope.validateForm = function () {
            if ($scope.checkoutState.CVVDataEntered == true &&
                $scope.checkoutState.CCDataEntered == true &&
                $scope.checkoutState.creditCardData.expireYear > 0 &&
                $scope.checkoutState.creditCardData.expireMonth > 0 &&
                $scope.checkoutState.creditCardData.name !== '' 
                ) {
                $scope.checkoutState.paymentSec = false;
                $scope.checkoutState.billingSec = true;
                delayClick("#billing-section");
                if ($scope.cartData.items) {
                    FireCheckoutClickDataEvent($scope.cartData.items, 4);
                }
                //anchorHelper.setAnchor('billing-address');
            }
        }

        //$scope.cardType = null;
        //$scope.onCardTypeChanged = function () {
        //    if ($scope.cardType === undefined) {
        //        $scope.isCardTypeValid = false;

        //    } else {
        //        if ($scope.cardType === null) {
        //            $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;

        //        $scope.isCardTypeValid = checkoutCreditCardValidationService.validateCardType($scope.checkoutState);
        //    }
           
        //};

        $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);
        };

        $scope.onYearChanged = function () {
            $scope.isExpireYearValid = checkoutCreditCardValidationService.validateYear($scope.checkoutState);
        };

        $scope.onCvvChanged = function () {
            $scope.isCardValidationValid = checkoutCreditCardValidationService.validateCardValidation($scope.checkoutState);
        };

        $scope.onNameChanged = function () {
            $scope.isNameValid = checkoutCreditCardValidationService.validateName($scope.checkoutState);
        };

        $scope.onCardNumberChanged = function (allowEmpty) {
            $scope.isCardNumberValid = checkoutCreditCardValidationService.validateCardNumber($scope.checkoutState, allowEmpty);
        };

        //Functions
        //$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);
            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.billingSec = false;
            $scope.checkoutState.finalSec = false;
        };

        $scope.editBillingInfo = function () {
            $scope.checkoutState.billingAddressSec = false;
        };
        $scope.sameAsShipping = function (value) {
            $scope.billingSame = value;
            addressDataHelper.updateSameAsShippingAddress(value);
        };


        $scope.initalize();
       
    }]);;
'use strict';

/**
* This is platform implemented checkout
*/
angular.module('checkout').directive('henrysCheckout',
    ['$window', 'appUrlBuilder', 'CheckoutSvc', 'NavigationService',
    function ($window, appUrlBuilder, checkoutSvc, navigationService) {
        return {
            restrict: 'A',
            templateUrl: appUrlBuilder.buildTemplateUrl('checkoutTemplateUrl'),
            scope: {
                email: '@'
            },
            controller: 'CheckoutCtrl',
            link: function (scope) {
                scope.confirmCancel = function () {
                    checkoutSvc.confirmDialog();
                };
                scope.goBackToStore = function () {
                    navigationService.navigate(appUrlBuilder.buildUrl('homePageUrl'));
                };

                scope.cartData.email = scope.email;
                scope.preloadData();
            }
        };
    }]);;
'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' },
            'checkOrderStatus': { method: 'GET', url: appUrlBuilder.buildUrl('checkOrderStatusApiUrl'), isArray: false, responseType: 'json' },
            'addCreditCardPayment': { method: 'PUT', url: appUrlBuilder.buildUrl('addCreditCardPaymentUrl'), isArray: false, responseType: 'json' },
            'addPayPalOption': { method: 'PUT', url: appUrlBuilder.buildUrl('addPayPalOptionUrl'), 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' },
            'getExistingCreditCards': { method: 'GET', url: appUrlBuilder.buildUrl('getExistingCreditCardsUrl'), isArray: true, responseType: 'json' },
            'addExistingCreditCardPayment': { method: 'PUT', url: appUrlBuilder.buildUrl('addExistingCreditCardPaymentUrl'), isArray: false, responseType: 'json' },
            'getCustomerCheckoutAddresses': { method: 'GET', url: appUrlBuilder.buildUrl('getCustomerAddressesUrl'), isArray: true, responseType: 'json' },
            'updateCustomerPhoneNumber': { method: 'PUT', url: appUrlBuilder.buildUrl('updateCustomerPhoneNumberUrl'), isArray: false, responseType: 'json' },
            'checkCustomerExists': { method: 'GET', url: appUrlBuilder.buildUrl('checkCustomerExistsApiUrl'), isArray: false, responseType: 'json' },
            'addComments': { method: 'PUT', url: appUrlBuilder.buildUrl('addCommentsUrl'), isArray: false, responseType: 'json' },
            'addEmailOptIn': { method: 'PUT', url: appUrlBuilder.buildUrl('updateEmailOptIn'), isArray: false, responseType: 'json' },
            'getGeoCodeForPostalCode': { method: 'GET', url: appUrlBuilder.buildUrl('getGeoCodeForPostalCodeApiUrl'), isArray: false, responseType: 'json' },
            'getDpoStores': { method: 'GET', url: appUrlBuilder.buildUrl('getDpoStoressUrl'), isArray: false, responseType: 'json' },
            'postCartDpoStore': { method: 'PUT', url: appUrlBuilder.buildUrl('postCartDpoUrl'), isArray: false, responseType: 'json' },
            'resetDpo': { method: 'PUT', url: appUrlBuilder.buildUrl('resetDpoUrl'), isArray: false, responseType: 'json' },
        });

        return {
            submitCart: function (ignore3Ds) {
                return resource.submitCart({ ignore3Ds: ignore3Ds });
            },
            checkOrderStatus: function (orderId) {
                return resource.checkOrderStatus({ orderId: orderId });
            },
            addCreditCardPayment: function (card) {
                return resource.addCreditCardPayment(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 () {
                showHenrysMsg('<h3>Authentication failed.</h3> Your financial institution has indicated that it could not successfully authenticate this transaction. To protect against unauthorized use, this card cannot be used to complete your purchase. <p>You may complete the purchase by selecting another form of payment.</p>');
            },
            getExistingCreditCards: function () {
                return resource.getExistingCreditCards();
            },
            addExistingCreditCardPayment: function (card) {
                return resource.addExistingCreditCardPayment(card);
            },
            getCustomerAddresses: function () {
                return resource.getCustomerCheckoutAddresses();
            },
            updateCustomerPhoneNumber: function (phone) {
                return resource.updateCustomerPhoneNumber(phone);
            },
            checkCustomerExists: function (email) {
                return resource.checkCustomerExists({ email: email });
            },
            addComments: function (comments) {
                return resource.addComments(JSON.stringify(comments));
            },
            addEmailOptIn: function (optIn) {
                return resource.addEmailOptIn(JSON.stringify(optIn));
            },
            getGeoCodeForPostalCode: function (postalCode) {
                return resource.getGeoCodeForPostalCode({ postalCode: postalCode });
            },
            getDpoStores: function (rateId,countryCode, postalCode, radiusInKm) {

                return resource.getDpoStores({ rateId: rateId, countryCode: countryCode, postalCode: postalCode, radiusInKm: radiusInKm });
            },
            postCartDpoStore: function (dpoUpdateStore) {
                return resource.postCartDpoStore(dpoUpdateStore);
            },
            resetDpo: function () {
                return resource.resetDpo();
            }
        };
    }
]);;
'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',
    function ($q, $timeout, appUrlBuilder, siteConfiguration, siteRes, checkoutSvc, checkoutDataStorageService, spinnerFactory, navigationService, addressDataHelper, checkoutCreditCardValidationService, accountSvc, cartDataStorageService, checkoutHelperService) {

        var addPaypalOption = function (signedIn, giftCards, cartData, checkoutState) {
            spinnerFactory.show();
            if (signedIn) {
                if (giftCards !== undefined && giftCards !== null && giftCards.length > 0) {
                    addGiftCardsPayPalPaymentThenSubmit(giftCards);
                } else {
                    addPayPalPaymentThenSubmit();
                }
            } else {
                submitGuestOrder(cartData.customerData, checkoutState, cartData);
            }
        };

        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();
            checkoutSvc.addGiftCardsToOrderForm(giftCardData).$promise.then(
                function (value) {
                    deferred.resolve(value);
                }, function (error) {
                    deferred.reject(error);
                });
            return deferred.promise;
        };

        var addGiftCardsCreditCardPaymentThenSubmit = function (giftCards, creditCardData, cartData, useExistingCard) {
            addGiftCards(giftCards).then(
                function () {
                    spinnerFactory.hide();
                    addCreditCardPaymentThenSubmit(creditCardData, cartData, useExistingCard);
                },
                function (error) {
                    spinnerFactory.hide();
                    checkoutDataStorageService.checkoutState.sumitCartErrorSec = true;
                    checkoutDataStorageService.checkoutState.errorMessage = error;
                });
        };

        var addCreditCardPaymentThenSubmit = function (creditCardData, cartData, useExistingCard) {
            addCreditCardPayment(creditCardData, useExistingCard).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, useExistingCard) {
            var deferred = $q.defer();
            spinnerFactory.show();
            if (useExistingCard) {
                checkoutSvc.addExistingCreditCardPayment(creditCardData).$promise.then(
              function (value) {
                  deferred.resolve(value);
              }, function (error) {
                  deferred.reject(error);
              });
            } else {
                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('confirmationPageUrl') + '/' + value.OrderId);
                    } else {
                        if (tries === 0) {
                            navigationService.navigate(appUrlBuilder.buildUrl('confirmationPageUrl') + '/' + value.OrderId);
                        } else {
                            $timeout(function () {
                                tries = tries - 1;
                                checkOrderStatus(value.OrderId, tries);
                            }, 5000);
                        }
                    }
                },
                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(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 {
                        spinnerFactory.hide();
                        if (value.Enforce3Ds === true) {
                            checkoutDataStorageService.checkoutState.show3Ds = true;
                            checkoutDataStorageService.checkoutState.threeDsNotifierUrl = checkoutSvc.getThreeDsNotifierUrl();
                        } else {
                            submitCartFail(paymentInfo, value.ErrorMessage);
                        }
                    }
                },
                function (error) {
                    spinnerFactory.hide();
                    //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 && checkoutState.useExistingCard || checkoutState.paymentType === 0) {
                    processCreditCardPayment(checkoutState, cartData);
                } else {
                    if (checkoutState.paymentType === 1 && checkoutCreditCardValidationService.isCardValid(checkoutState) || checkoutState.paymentType === 0) {
                        processCreditCardPayment(checkoutState, cartData);
                    }
                }
                
            }
            if (checkoutState.paymentType === 2) {
                addPaypalOption(cartData.signedIn, checkoutState.giftCards, cartData, checkoutState);
            }
        };

        //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.useExistingCard ? checkoutState.existingCreditCardData : checkoutState.creditCardData, cartData, checkoutState.useExistingCard);
                                }
                                if (checkoutState.paymentType === 2) {
                                    addGiftCardsPayPalPaymentThenSubmit(checkoutState.giftCards);
                                }
                            } else {
                                if (checkoutState.paymentType === 1) {
                                    addCreditCardPaymentThenSubmit(checkoutState.useExistingCard ? checkoutState.existingCreditCardData : checkoutState.creditCardData, cartData, checkoutState.useExistingCard);
                                }
                                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 && checkoutState.useExistingCard == 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.useExistingCard ? checkoutState.existingCreditCardData : checkoutState.creditCardData, cartData, checkoutState.useExistingCard);
                            }, function (error) {
                                console.log(error);
                            });
                    } else {
                        addGiftCardsCreditCardPaymentThenSubmit(checkoutState.giftCards, checkoutState.useExistingCard ? checkoutState.existingCreditCardData : checkoutState.creditCardData, cartData, checkoutState.useExistingCard);
                    }
                } else {
                    submitGuestOrder(cartData.customerData, checkoutState, cartData);
                }
            }
        };

        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 {
                        hpciStatusReset();
                        checkoutState.hpciProcessed = false;
                        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
        };
    }
]);;
'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.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 () {

            //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)) {
                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', {});


                }
            }

            if (totalValidAmount + amountToApply >= $scope.cartTotal) {
                $scope.checkoutState.paymentType = 0;
            }

            $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');
            }
        });

        $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');
            }
        });

        $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);
        };

        //Initialize
        $scope.loadGiftCardSetting();
        $scope.getOrderFormGiftcards();


    }
    ]);;
'use strict';

/**
 * this is service that stores cart data, shared across multiple cart directives
 */

angular.module('confirm').factory('ConfirmPageDataStorageService', ['$q','$sce', 'ConfirmSvc',
    function ($q, $sce, confirmSvc) {
        var cartData = { items: [] };

        var loadData = function (orderId) {
            var deferred = $q.defer();
            confirmSvc.getOrder(orderId).$promise.then(
                function (freshCartData) {
                    sync(freshCartData, false);
                    deferred.resolve({});
                    
                    var googleItems = [];
                    var criteoProducts = [];
                    for (var x = 0; x < cartData.items.length; x++) {
                        if (cartData.items[x].ItemCode != '889EHF021') {
                            googleItems.push({
                                'id': cartData.items[x].ItemCode,
                                'name': cartData.items[x].ProductDisplayName,
                                'price': cartData.items[x].UnitPrice.toFixed(2),
                                'quantity': cartData.items[x].Quantity,
                                'brand': cartData.items[x].BrandName,
                                'category': cartData.items[x].CategoryString
                            });
                            criteoProducts.push({
                                'childid': cartData.items[x].ProductId,
                                'price': cartData.items[x].UnitPrice.toFixed(2),
                                'quantity': cartData.items[x].Quantity
                            });
                        }
                    }

                    dataLayer.push({
                        'ecommerce': {
                            'purchase': {
                                'actionField': {
                                    'id': orderId,
                                    'affiliation': 'Henrys',
                                    'revenue': cartData.subtotal.toFixed(2),
                                    'tax': cartData.totalTax.toFixed(2),
                                    'shipping': cartData.totalShipping.toFixed(2)
                                },
                                'products': googleItems
                            }
                        },
                        'criteoProducts':criteoProducts,
                        'event': 'transactionComplete'
                    });

                    //Taken out on deloitte's request for Enhanced E-commerce ticket
                    //dataLayer.push({
                    //    'event': 'ecommReady',
                    //});
                    //BV PIXEL
                    //load Transaction event and parameters
                    var items = [];
                    for (var y = 0; y < cartData.items.length; y++) {
                       items.push({
                            "price": cartData.items[y].UnitPrice.toFixed(2).replace('$',''),
                            "quantity": cartData.items[y].Quantity,
                           "sku": cartData.items[y].ProductId,
                            "name": cartData.items[y].ProductDisplayName
                        });
                    }
                  
                    BV.pixel.trackTransaction({
                        "currency": "CAD",
                        "orderId": orderId,
                        "total": cartData.subtotal.toFixed(2),
                        "items": items,
                        "shipping": cartData.totalShipping.toFixed(2),
                        "tax": cartData.totalTax.toFixed(2),
                        "email": cartData.customer.Email
                    });
                   
                },
                function (error) { deferred.reject(error); });
            return deferred.promise;
        };

        var sync = function (freshCartData) {
            cartData.total = freshCartData.Total;
            cartData.subtotal = freshCartData.SubTotal;
            cartData.totalShipping = freshCartData.TotalShipping;
            cartData.totalTax = freshCartData.TotalTax;
            cartData.TotalDiscounts = freshCartData.TotalDiscounts;
            cartData.taxes = freshCartData.Taxes;
            cartData.showShippingMarketing = freshCartData.ShowShippingMarketing;
            cartData.signedIn = freshCartData.SignedIn;
            cartData.shippingAddress = freshCartData.ShippingAddress;
            cartData.billingAddress = freshCartData.BillingAddress;
            cartData.customer = freshCartData.Customer;
            cartData.items = freshCartData.LineItems;
            cartData.shippingMethod = freshCartData.ShippingMethod;
            cartData.paymentMehtodString = $sce.trustAsHtml(freshCartData.PaymentMehtodString);
        };

        return {
            cartData: cartData,
            loadData: loadData,
            sync: sync,
        };

    }]);;
/*global BootstrapDialog:false */
/*exported storeFinder, StoreInventory */
'use strict';

/**
 * The store finder has logic that allows end users to find stores based on a location (latitude/longitude)
 */
var StoreInventory = (function ($, dialog) {

    //constructor
    function StoreInventory(storeLocator, constants, localization) {
        this.storeLocator = storeLocator;
        this.constants = constants;
        this.localization = localization;
    }
  


    StoreInventory.prototype.setStoreCookie = function (storeId) {

        var name = 'HenrysMyStoreCookie';
        $.cookie(name, storeId, { path: "/" });
    };


    return StoreInventory;

})(jQuery, BootstrapDialog);

function MarkAsMyStore(StoreId, itemId) {
    debugger;
    var scope = angular.element('.stock-availability').scope();
    if (scope != null) {
        scope.selectedStoreName = StoreId;
        scope.getMyStoredata(StoreId, itemId);
        var name = 'HenrysMyStoreCookie';
        $.cookie(name, StoreId, { path: "/" });
        scope.productData.stockModal.dismiss();
        getStoreData();

        if (scope.QuickView) {
            scope.QuickView.close();
            scope.loadQuickView(scope.productData.id);
        }
      
    }
};
/*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)
 */

var StoreFinder = (function ($, dialog) {

    //constructor
    function StoreFinder(storeLocator, constants, localization) {
        this.storeLocator = storeLocator;
        this.constants = constants;
        this.localization = localization;
    }
    var isFromRISPage = $("#isFromRISPage").val();
    /*
    * Get store list information by latitude, longitude and range
    */
    StoreFinder.prototype.getStoreList = function () {
        
        var root = this;
        var province;
        $.ajax({
            url: root.constants.rootUrl + '/api/stores/getStoreList',
            success: function (data) {
                if (data.length > 0) {
                    $('#filteredStoresContainer').html('');
                    province = data[0].Province;
                    var htmlRow = '';
                    htmlRow += '<h2>' + data[0].Province + '</h2>';
                    htmlRow += '<div class="row same-height">';


                    $.each(data, function (index, store) {
                        //root.addStoreRow.call(root, store);
                        if (store) {
                            if (store.Province != province) {
                                province = store.Province;
                                htmlRow += '</div>';
                                htmlRow += '<h2>' + store.Province + '</h2>';
                                htmlRow += '<div class="row">';
                            }
                            //var defaultStore = "'" + store.PostalCode.replace(/ /g, '') + "'";
                            var myStoreCookieValue = '';
                            if ($.cookie('HenrysMyStoreCookie') != null) {
                                myStoreCookieValue = $.cookie('HenrysMyStoreCookie');
                            }

                            htmlRow += '<div class="col-xs-12 col-md-4 col-sm-4 ">';
                            htmlRow += '<div class="location-item-box" itemscope itemtype="http://schema.org/Store">';
                            htmlRow += '<strong class="name" itemprop="name">' + store.StoreName + '</strong>';
                            htmlRow += '<address itemscope itemtype="http://schema.org/PostalAddress" itemprop="addressLocality">' + store.Address + ',<br /> ' + store.CityProvince + ' <br />' + store.PostalCode + '</address>';
                            htmlRow += '<div class="tel-wrap">';
                            htmlRow += 'Phone: <a href="tel: ' + store.LocalPhone + '" class="tel link">' + store.LocalPhone + '</a>';
                            htmlRow += '</div>';
                            htmlRow += '<div class="email-wrap">';
                            htmlRow += 'Email: <a class="link" href="mailto:' + store.Email + '">' + store.Email + '</a>';
                            htmlRow += '</div>';

                            htmlRow += '<div class="link-wrap">';
                            htmlRow += '<a href="' + store.Url + '" class="primary"><i class="fa fa-info-circle"></i> <span>Store Details</span></a>';
                            if (isFromRISPage == undefined || isFromRISPage == null || isFromRISPage == "false") {
                                htmlRow += store.StoreId == myStoreCookieValue ? '<a style="cursor:pointer;" class="my-store" onclick="setMyStoreCookie(' + store.StoreId + ');" id="myStoreLnk' + store.StoreId + '"><i class="icon-map-marker"></i><span style="padding-left: 3px;">My Store</span></a>' :
                                    '<a onclick="setMyStoreCookie(' + store.StoreId + ');" style="cursor:pointer;" class="primary myStoreLink" id="myStoreLnk' + store.StoreId + '" ><i class="icon-map-marker"></i><span style="padding-left: 3px;">Set As My Store</span></a>';
                            }
                            else if (isFromRISPage != undefined && isFromRISPage != null && isFromRISPage == "true") {
                                htmlRow += store.StoreId == myStoreCookieValue ? '<a style="cursor:pointer;" class="my-store" onclick="setMyStoreCookie(' + store.StoreId + ');" id="myStoreLnk' + store.StoreId + '"><i class="icon-map-marker"></i><span style="padding-left: 3px;">My Store</span></a>' :
                                   '<a onclick="setMyStoreCookie(' + store.StoreId + ');" style="cursor:pointer;" class="primary myStoreLink" id="myStoreLnk' + store.StoreId + '" ><i class="icon-map-marker"></i><span style="padding-left: 3px;">Set As Pick Up Location</span></a>';
                            }
                            htmlRow += '</div>';
                            htmlRow += '</div>';
                            htmlRow += '</div>';

                        }
                    });


                    htmlRow += '</div>';

                    $('#filteredStoresContainer').append(htmlRow);

                }
            }
        });
    };

    return StoreFinder;

})(jQuery, BootstrapDialog);

function setMyStoreCookie(storeId) {
    //alert('cookie');
    var name = 'HenrysMyStoreCookie';
    $.cookie(name, storeId, { path: "/" });
    $("a[id^='myStoreLnk']").removeClass("my-store").addClass("primary");
    $("a[id^='myStoreLnk'] span").text("Set As My Store");
    $("#myStoreLnk" + storeId + " span").text("My Store");
    $("#myStoreLnk" + storeId).removeClass("primary").addClass("my-store");
    getStoreData();
    SetDefaultStoreLocationRIS();   
};

function SetDefaultStoreLocationRIS() {
    var defaultPostalCode = $('#hdnDefaultPostalCode').val();
   // alert(defaultPostalCode);
    if (defaultPostalCode != undefined && defaultPostalCode != null) {
        $.ajax({
            url: '../ShoppingCart/GetStoreListByPostalCode',
            type: 'GET',
            data: { postalCode: defaultPostalCode, origin: 1 },
            success: function (result) {
                //alert('fav store changed');
                //window.location.href = window.location;
                window.location.reload(true);
                BootstrapDialog.closeAll();
                //  alert(result);
            },
            error: function () {
                //alert("error");
            }
        });
    }
}
;
/*global BootstrapDialog:false */
'use strict';

/**
 * This is the helper service that wraps bootstrap dialog, so that dialog can be used in Angular
  */

angular.module('shared').factory('MyStoreCookieSvc',
    function () {
        return new StoreCookieHelper();
    });
;
var StoreCookieHelper = (function ($) {


    function StoreCookieHelper() {
    }

    StoreCookieHelper.prototype.ReadMyStoreFromCookie = function () {
        var name = 'HenrysMyStoreCookie';

        var scope = angular.element('.stock-availability').scope();

        var myStoreCookieValue = '';

        if ($.cookie(name) != null) {
            myStoreCookieValue = $.cookie(name);
        }

        // scope.$parent.selectedStoreName = myStoreCookieValue;
        return myStoreCookieValue;
    };

    StoreCookieHelper.prototype.ReadCookie = function (name) {
        var value = '';

        if ($.cookie(name) != null) {
            value = $.cookie(name);
        }

        // scope.$parent.selectedStoreName = myStoreCookieValue;
        return value;
    };


    StoreCookieHelper.prototype.AddMyStoreCookie = function (cookieValue) {
        // //debugger;
        // var name = 'BouclairMyStoreCookie';
        // $.cookie(name, cookieValue, { path: "/" });

        //// var scope = angular.element('#store-holder').scope();

        // scope.$parent.selectedStoreName = cookieValue;
    };

    return StoreCookieHelper;

})(jQuery);;
/*global google:false */
/*exported StoreLocator */


/**
 * The store locator provides the interface to Google Maps and any manipulation of the results.
 */
var StoreLocator = (function ($) {

    //constructor
    function StoreLocator(constants, localization) {
        this.constants = constants;
      
        this.localization = localization;
    }

    return StoreLocator;

})(jQuery);
;
/*global BootstrapDialog:false */
/*exported storeFinder, StoreInventory */
'use strict';

/**
 * The store finder has logic that allows end users to find stores based on a location (latitude/longitude)
 */
var StoreInventory = (function ($, dialog) {

    //constructor
    function StoreInventory(storeLocator, constants, localization) {
        this.storeLocator = storeLocator;
        this.constants = constants;
        this.localization = localization;
    }


    return StoreInventory;

})(jQuery, BootstrapDialog);;
