/* Minification failed. Returning unminified contents.
(763,63-64): run-time error JS1195: Expected expression: .
(763,101-102): run-time error JS1003: Expected ':': )
(764,17-21): run-time error JS1009: Expected '}': this
(764,17-21): run-time error JS1006: Expected ')': this
(784,9-15): run-time error JS1194: Expected ',' or ']': $scope
(784,9-15): run-time error JS1006: Expected ')': $scope
(1057,5-6): run-time error JS1002: Syntax error: }
(1057,6-7): run-time error JS1195: Expected expression: ]
(1057,7-8): run-time error JS1195: Expected expression: )
 */
;(function () {

    $.productData = {
    };


    $.productAppLoad = function (data) {
        $.productData = data;        
    };


    $.productUtility = {

        productImage:function(id){
            
            if (res.IMAGESERVER) {
                return res.IMAGESERVER + '/images/products/large/pdt_' + id + '.png?width=200&height=200';
            }
            else {
                return "https://img.creative.com/images/products/large/pdt_" + id + ".png?width=200&height=200";
            }
        },
        productSmallImage: function (id) {
            if (res.IMAGESERVER) {
                return res.IMAGESERVER + '/images/products/large/pdt_' + id + '.png?width=120&height=120';
            }
            else {
                return "https://img.creative.com/images/products/large/pdt_" + id + ".png?width=120&height=120";
            }
        }

    };
})();;
"use strict";

angular.module('ngProductApp', ['ngAnimate', 'ngMaterial', 'ngMessages', 'ngStorage', 'angular-creative'])
.config(['$mdThemingProvider', '$locationProvider', function ($mdThemingProvider, $locationProvider) {
    $mdThemingProvider.theme('default')
      .primaryPalette('red', {
          'default': '800'
      })
    .accentPalette(
    'blue', {
        'default': '500'
    });

    $locationProvider.html5Mode(false);
}])
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });
}])
.directive('productbuy', function () {
    return {
        restrict: 'AE',
        scope: true,
        templateUrl: '/ngtemplate/?v=Buy'
    }
})
.directive('productnotify', function () {
    return {
        restrict: 'AE',
        scope: true,
        templateUrl: '/ngtemplate/?v=Notify'
    }
})
.directive('productredirect', function () {
    return {
        restrict: 'AE',
        scope: true,
        templateUrl: '/ngtemplate/?v=BuyRedirect'
    }
})
;

;
"use strict";

var Country = {
    India: 91,
    Malaysia: 60
}

var StoreType = {
    UK: 12,
    US: 15,
    RSUAsia: 19,
    GR: 41
}

var ProductType = {
    SXFICarrier: 23448,
    AirV3: 23725
}

var urlAppend = (window.location.href.indexOf('localhost') !== -1) ? '/landingpages' : '';
var urlAPI = (window.location.href.indexOf('localhost') !== -1 || window.location.href.indexOf('stage') !== -1) ? '.stage' : '';
var subscribe = [2, 3, 4, 15, 29, 36, 38, 42].includes(global.store.id);

angular.module('ngProductApp')
    .controller('NotifyButtonController', ['$scope', 'ngApp', '$location', '$timeout', function ($scope, ngApp, $location, $timeout) {
        $scope.show = false;
        $scope.ngApp = ngApp;
        $scope.uiInit = function (pid) {

            //use this scriptlet to show notify me form on pdt page or do geolocation detection on specific country
            // if (pid === ProductType.SXFICarrier && (global.store.id === StoreType.RSUAsia))
            // {
            //     if (global.store.id === StoreType.RSUAsia) {
            //       $.get(urlAppend + "/apis/geolocate/" + window.location.search, function(data, status) {
            //           this.show = (status === "success" && data.ipCountry === Country.India);
            //         })
            //     }
            // }

            // if (pid === ProductType.AirV3 && (global.store.id === StoreType.GR)) {
            //     this.show = true;
            // }

        }
        $scope.notify = function () {
            ngApp.showBtnLoading();
            location.hash = '#buy';
        }
        $scope.base = location.pathname;
    }])
    .controller('BuyButtonController', ['$rootScope', '$scope', 'ngApp', '$location', '$timeout', '$http', function ($rootScope, $scope, ngApp, $location, $timeout, $http) {
        $scope.listPrice = '';
        $scope.price = '';
        $scope.loading = true;
        $scope.show = false;
        $scope.cartItemCount = 0;
        $scope.cartTotal = 0;
        $scope.ngApp = ngApp;
        $scope.uiInit = function () {
            if ($.productData) {
                var pdata = $.productData.Products[0];
                for (var i = 1; i < $.productData.Products.length; i++)
                    if ($.productData.Products[i].Price > 0.01 && pdata.Price > $.productData.Products[i].Price)
                        pdata = $.productData.Products[i];

                if (pdata.Price > 0.01) {
                    this.price = pdata.PriceFormat;
                    if (pdata.Price < pdata.ListPrice) this.listPrice = pdata.ListPriceFormat;
                    this.lowestPrice = pdata.LowestPriceFormat;
                    this.cartItemCount = $.productData.CartItemCount;
                    this.cartTotal = $.productData.CartTotal;
                    this.loading = false;
                    this.show = true;
                    if (global.store.id === 38) $scope.convertMYR(pdata.Price);
                    // special handling for Japan
                    if (global.store.id === 2) this.price += '(税込)';
                }
            }
        }

        $scope.buy = function () {
            ngApp.showBtnLoading();
            location.hash = '#buy';
            $rootScope.$broadcast('buybtn:click', {});
        }

        $scope.convertMYR = function (price) {
            if (price && price > 0)
                $http({
                    method: 'GET',
                    url: '/products/getcurrencyexchangerate?baseCurrency=USD&symbols=MYR'
                }).success(function (data) {
                    if (data && data.rate && data.rate > 0) {
                        $scope.price += ' (~RM' + parseInt(price * data.rate).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,') + ')';
                    }
                });
        }

        $scope.base = location.pathname;
    }]).controller('NotifyController', ['$scope', '$location', '$http', '$timeout', 'ngApp', '$element', function ($scope, $location, $http, $timeout, ngApp, $element) {
        $scope.productid = 0;
        $scope.productName = '';
        $scope.notifyData = {
            name: '',
            email: '',
            phone: '',
            countryid: '1',
            showCountry: false,
            showPhone: false,
            marketingEmail: subscribe,
            thirdPartyEmail: false
        };



        $scope.countries = [{ "name": "Afghanistan", "id": "93" },
        { "name": "Albania", "id": "355" },
        { "name": "Algeria", "id": "213" },
        { "name": "Andorra", "id": "376" },
        { "name": "Angola", "id": "244" },
        { "name": "Anguilla", "id": "101" },
        { "name": "Antigua", "id": "102" },
        { "name": "Argentina", "id": "54" },
        { "name": "Armenia", "id": "374" },
        { "name": "Aruba", "id": "297" },
        { "name": "Australia", "id": "61" },
        { "name": "Austria", "id": "43" },
        { "name": "Azerbaijan", "id": "994" },
        { "name": "Bahamas", "id": "103" },
        { "name": "Bahrain", "id": "973" },
        { "name": "Bangladesh", "id": "880" },
        { "name": "Barbados", "id": "104" },
        { "name": "Belarus", "id": "375" },
        { "name": "Belgium", "id": "32" },
        { "name": "Belize", "id": "501" },
        { "name": "Benin", "id": "229" },
        { "name": "Bermuda", "id": "105" },
        { "name": "Bhutan", "id": "975" },
        { "name": "Bolivia", "id": "591" },
        { "name": "Bosnia and Herzegovina", "id": "387" },
        { "name": "Botswana", "id": "267" },
        { "name": "Brazil", "id": "55" },
        { "name": "British Virgin Islands", "id": "106" },
        { "name": "Brunei", "id": "673" },
        { "name": "Bulgaria", "id": "359" },
        { "name": "Burkina Faso", "id": "226" },
        { "name": "Burundi", "id": "257" },
        { "name": "Cameroon", "id": "237" },
        { "name": "Canada", "id": "107" },
        { "name": "Cape Verde Islands", "id": "238" },
        { "name": "Central African Republic", "id": "236" },
        { "name": "Chad", "id": "235" },
        { "name": "Chile", "id": "56" },
        { "name": "China", "id": "86" },
        { "name": "Christmas Island", "id": "672" },
        { "name": "Cocos-Keeling Islands", "id": "6101" },
        { "name": "Colombia", "id": "57" },
        { "name": "Comoros", "id": "2691" },
        { "name": "Congo", "id": "242" },
        { "name": "Congo, Democratic Republic of the", "id": "243" },
        { "name": "Costa Rica", "id": "506" },
        { "name": "Croatia", "id": "385" },
        { "name": "Cuba", "id": "53" },
        { "name": "Cyprus", "id": "357" },
        { "name": "Czech Republic", "id": "420" },
        { "name": "Denmark", "id": "45" },
        { "name": "Djibouti", "id": "253" },
        { "name": "Dominica", "id": "109" },
        { "name": "Ecuador", "id": "593" },
        { "name": "Egypt", "id": "20" },
        { "name": "El Salvador", "id": "503" },
        { "name": "Equatorial Guinea", "id": "240" },
        { "name": "Eritrea", "id": "291" },
        { "name": "Estonia", "id": "372" },
        { "name": "Ethiopia", "id": "251" },
        { "name": "Falkland Islands", "id": "500" },
        { "name": "Faroe Islands", "id": "298" },
        { "name": "Fiji Islands", "id": "679" },
        { "name": "Finland", "id": "358" },
        { "name": "Former Yugoslav Republic of Macedonia", "id": "389" },
        { "name": "France", "id": "33" },
        { "name": "French Guiana", "id": "594" },
        { "name": "French Polynesia", "id": "689" },
        { "name": "Gabon", "id": "241" },
        { "name": "Gambia", "id": "220" },
        { "name": "Georgia", "id": "995" },
        { "name": "Germany", "id": "49" },
        { "name": "Ghana", "id": "233" },
        { "name": "Gibraltar", "id": "350" },
        { "name": "Greece", "id": "30" },
        { "name": "Greenland", "id": "299" },
        { "name": "Grenada", "id": "111" },
        { "name": "Guadeloupe", "id": "590" },
        { "name": "Guam", "id": "124" },
        { "name": "Guatemala", "id": "502" },
        { "name": "Guinea", "id": "224" },
        { "name": "Guinea-Bissau", "id": "245" },
        { "name": "Guyana", "id": "592" },
        { "name": "Haiti", "id": "509" },
        { "name": "Honduras", "id": "504" },
        { "name": "Hong Kong SAR, PRC", "id": "852" },
        { "name": "Hungary", "id": "36" },
        { "name": "Iceland", "id": "354" },
        { "name": "India", "id": "91" },
        { "name": "Indonesia", "id": "62" },
        { "name": "Iran", "id": "98" },
        { "name": "Iraq", "id": "964" },
        { "name": "Ireland", "id": "353" },
        { "name": "Israel", "id": "972" },
        { "name": "Italy", "id": "39" },
        { "name": "Jamaica", "id": "112" },
        { "name": "Japan", "id": "81" },
        { "name": "Jordan", "id": "962" },
        { "name": "Kazakhstan", "id": "705" },
        { "name": "Kenya", "id": "254" },
        { "name": "Kiribati Republic", "id": "686" },
        { "name": "Korea (North)", "id": "850" },
        { "name": "Korea (Republic of)", "id": "82" },
        { "name": "Kuwait", "id": "965" },
        { "name": "Kyrgyz Republic", "id": "706" },
        { "name": "Lao P.D.R.", "id": "856" },
        { "name": "Latvia", "id": "371" },
        { "name": "Lebanon", "id": "961" },
        { "name": "Lesotho", "id": "266" },
        { "name": "Liberia", "id": "231" },
        { "name": "Libya", "id": "218" },
        { "name": "Liechtenstein", "id": "4175" },
        { "name": "Lithuania", "id": "370" },
        { "name": "Luxembourg", "id": "352" },
        //  {"name": "Macau", "id": "853"},
        { "name": "Madagascar", "id": "261" },
        { "name": "Malawi", "id": "265" },
        { "name": "Malaysia", "id": "60" },
        { "name": "Maldives", "id": "960" },
        { "name": "Mali", "id": "223" },
        { "name": "Malta", "id": "356" },
        { "name": "Marshall Islands", "id": "692" },
        { "name": "Martinique", "id": "596" },
        { "name": "Mauritania", "id": "222" },
        { "name": "Mauritius", "id": "230" },
        { "name": "Mayotte Island", "id": "269" },
        { "name": "Mexico", "id": "52" },
        { "name": "Micronesia, Federated States of", "id": "691" },
        { "name": "Moldova", "id": "373" },
        { "name": "Monaco", "id": "377" },
        { "name": "Mongolia", "id": "976" },
        { "name": "Montserrat", "id": "113" },
        { "name": "Morocco", "id": "212" },
        { "name": "Mozambique", "id": "258" },
        { "name": "Myanmar", "id": "95" },
        { "name": "Namibia", "id": "264" },
        { "name": "Nepal", "id": "977" },
        { "name": "Netherlands", "id": "31" },
        { "name": "Netherlands Antilles", "id": "599" },
        { "name": "New Caledonia", "id": "687" },
        { "name": "New Zealand", "id": "64" },
        { "name": "Nicaragua", "id": "505" },
        { "name": "Niger", "id": "227" },
        { "name": "Nigeria", "id": "234" },
        { "name": "Niue", "id": "683" },
        { "name": "Norfolk Island", "id": "6722" },
        { "name": "Norway", "id": "47" },
        { "name": "Oman", "id": "968" },
        { "name": "Pakistan", "id": "92" },
        { "name": "Palau", "id": "680" },
        { "name": "Panama", "id": "507" },
        { "name": "Papua New Guinea", "id": "675" },
        { "name": "Paraguay", "id": "595" },
        { "name": "Peru", "id": "51" },
        { "name": "Philippines", "id": "63" },
        { "name": "Poland", "id": "48" },
        { "name": "Portugal", "id": "351" },
        { "name": "Puerto Rico", "id": "121" },
        { "name": "Qatar", "id": "974" },
        { "name": "Reunion Island", "id": "262" },
        { "name": "Romania", "id": "40" },
        { "name": "Russia", "id": "7" },
        { "name": "Rwanda", "id": "250" },
        { "name": "Saint Kitts & Nevis Anguilla", "id": "114" },
        { "name": "Saint Lucia", "id": "122" },
        { "name": "San Marino", "id": "378" },
        { "name": "Sao Tome and Principe", "id": "239" },
        { "name": "Saudi Arabia", "id": "966" },
        { "name": "Senegal Republic", "id": "221" },
        { "name": "Serbia and Montenegro", "id": "381" },
        { "name": "Seychelle Islands", "id": "248" },
        { "name": "Sierra Leone", "id": "232" },
        { "name": "Singapore", "id": "65" },
        { "name": "Slovak Republic", "id": "421" },
        { "name": "Slovenia", "id": "386" },
        { "name": "Solomon Islands", "id": "677" },
        { "name": "Somalia", "id": "252" },
        { "name": "South Africa", "id": "27" },
        { "name": "Spain", "id": "34" },
        { "name": "Sri Lanka", "id": "94" },
        { "name": "St. Pierre and Miquelon", "id": "508" },
        { "name": "St. Vincent and the Grenadines", "id": "116" },
        { "name": "Sudan", "id": "249" },
        { "name": "Suriname", "id": "597" },
        { "name": "Swaziland", "id": "268" },
        { "name": "Sweden", "id": "46" },
        { "name": "Switzerland", "id": "41" },
        { "name": "Syria", "id": "963" },
        // {"name": "Taiwan", "id": "886"},
        { "name": "Tajikistan", "id": "708" },
        { "name": "Tanzania", "id": "255" },
        { "name": "Thailand", "id": "66" },
        { "name": "Togo", "id": "228" },
        { "name": "Tokelau", "id": "690" },
        { "name": "Tonga", "id": "676" },
        { "name": "Trinidad and Tobago", "id": "117" },
        { "name": "Turkey", "id": "90" },
        { "name": "Turks and Caicos Islands", "id": "118" },
        { "name": "Ukraine", "id": "380" },
        { "name": "United Arab Emirates", "id": "971" },
        { "name": "United Kingdom", "id": "44" },
        { "name": "United States of America", "id": "1" },
        { "name": "United States Virgin Islands", "id": "123" },
        { "name": "Uruguay", "id": "598" },
        { "name": "Uzbekistan", "id": "711" },
        { "name": "Vatican City", "id": "379" },
        { "name": "Venezuela", "id": "58" },
        { "name": "Vietnam", "id": "84" },
        { "name": "Yemen", "id": "967" },
        { "name": "Zambia", "id": "260" },
        { "name": "Zimbabwe", "id": "263,1,2" }];

        $scope.noScroll = function (on) {

            if (on) {
                $("html").addClass("no-scroll");
            }
            else {
                $("html").removeClass("no-scroll");
            }
        };

        $scope.reLocate = function () {
            var select = $element.find('md-select');
            var container = $("#" + select.attr('aria-owns'))
            var top = select.offset().top - window.scrollY
            container.css('top', top);
            $timeout(function () {
                container.css('top', top);
            }, 100)
        };

        $scope.notifyMeLoading = false;
        $scope.uiInit = function (pid, pname) {
            $scope.productid = pid;
            $scope.productName = pname;
            if (pid === ProductType.SXFICarrier && (global.store.id === StoreType.US || global.store.id === StoreType.RSUAsia)) {
                $scope.notifyData.showCountry = true;   // To list out only for US

                if (global.store.id === StoreType.RSUAsia) {
                    $.get(urlAppend + "/apis/geolocate/" + window.location.search, function (data, status) {
                        if (status === "success" && data.ipCountry === Country.India) {
                            $scope.notifyData.showPhone = true;
                            $scope.notifyData.countryid = Country.India;
                        }
                    })
                    $scope.notifyData.showCountry = false;
                }
            }
        }
        $scope.close = function () { }
        $scope.notifyMeSubmit = function () {
            if ($scope.notifyData.showCountry == true) {
                if (!$scope.notifyData.name || !$scope.notifyData.email || !$scope.notifyData.countryid) return;
                if ($scope.productid <= 0) return;
                $scope.notifyMeLoading = true;
                $http({
                    method: 'GET',
                    url: $.cartUtility.secureUrl('/notifyme/add?Name=' + $scope.notifyData.name + '&Email=' + $scope.notifyData.email + '&Phone=' + $scope.notifyData.phone + '&ProductID=' + $scope.productid + '&MarketingEmail=' + $scope.notifyData.marketingEmail + '&ThirdPartyEmail=' + $scope.notifyData.thirdPartyEmail + '&CountryId=' + $scope.notifyData.countryid)
                }
                ).success(function (data) {
                    $scope.notifyMeLoading = false;
                    if (data.status == 'success') $scope.messageType = 'success';
                    else $scope.messageType = 'error';
                    notificationBar.show('<span class="' + (data.status == 'success' ? 'i-check-circle' : 'i-cross-circle') + '"></span>' + data.message.replace("{0}", $scope.productName), 4000);
                });
            } else {
                if (!$scope.notifyData.name || !$scope.notifyData.email) return;
                if ($scope.productid <= 0) return;
                $scope.notifyMeLoading = true;
                $http({
                    method: 'GET',
                    url: $.cartUtility.secureUrl('/notifyme/add?Name=' + $scope.notifyData.name + '&Email=' + $scope.notifyData.email + '&Phone=' + $scope.notifyData.phone + '&ProductID=' + $scope.productid + '&MarketingEmail=' + $scope.notifyData.marketingEmail + '&ThirdPartyEmail=' + $scope.notifyData.thirdPartyEmail + '&CountryId=' + $scope.notifyData.countryid)
                }
                ).success(function (data) {
                    $scope.notifyMeLoading = false;
                    if (data.status == 'success') $scope.messageType = 'success';
                    else $scope.messageType = 'error';
                    notificationBar.show('<span class="' + (data.status == 'success' ? 'i-check-circle' : 'i-cross-circle') + '"></span>' + data.message.replace("{0}", $scope.productName), 4000);
                });
            }

        }
    }])
    .controller('ProductRedirectController', ['$rootScope', '$scope', '$location', '$http', '$timeout', 'ngApp', function ($rootScope, $scope, $location, $http, $timeout, ngApp) {
        $scope.productName = '';
        $scope.image = '';
        $scope.storeUrl = '';
        $scope.productUrl = '';

        $rootScope.$on('buybtn:click', function (e) {
            $timeout(function () { $scope.redirect($scope.productUrl); }, 1000 * 8);
        });

        $scope.uiInit = function () {
            $scope.refresh();
        }

        $scope.refresh = function () {
            if ($.productData) {
                $scope.productName = $.productData.MasterProductName;
                $scope.image = $.productUtility.productSmallImage($.productData.MasterProductID);
            }
        }

        $scope.infoInit = function (storeUrl) {
            $scope.storeUrl = storeUrl;
            $scope.productUrl = location.href.replace(/(.*?)\/p\//, storeUrl + '/p/');
        }

        $scope.redirect = function (url) {
            console.log(url)
            if (url && url.length > 0 && location.href.indexOf('#buy-menu') === -1 && location.href.indexOf('#buy') > 0) location.href = url;
        }

        $scope.close = function () { }
    }])
    .controller('ProductController', ['$scope', '$location', '$http', '$timeout', 'ngApp', function ($scope, $location, $http, $timeout, ngApp) {
        $scope.height = 0;
        $scope.top = 0;
        $scope.price = '';
        $scope.priceMYR = '';
        $scope.listPrice = '';
        $scope.lowestPrice = '';
        $scope.available = '';
        $scope.memberPoints = 0;
        $scope.productid = 0;
        $scope.image = '';
        $scope.productName = '';
        $scope.added = false;
        $scope.addtocartDisabled = true;
        $scope.loading = false;
        $scope.cartTotal = '';
        $scope.cartItemCount = 0;
        $scope.freeShipThreshold = '';
        $scope.message = '';
        $scope.messageType = '';
        $scope.freeItems = [];
        $scope.hasFreeItems = false;
        $scope.freeItemRecord = [];
        $scope.freeItemAutoAdded = false;
        $scope.crossSell = [];
        $scope.cartItemID = 0;
        $scope.promoMessage = [];
        $scope.notifyMe = false;
        $scope.showNotifyMe = false;
        $scope.notifyData = {
            name: '',
            email: '',
            marketingEmail: subscribe,
            thirdPartyEmail: false
        }
        $scope.notifyMeLoading = false;
        $scope.shippingData = {
            freeShipping: false,
            shippingCharge: ''
        }
        $scope.staff = false;
        $scope.membershipEnable = true;
        $scope.selectFreeItemMessage = false;
        $scope.modelNo = '';
        $scope.res = window.res;
        $scope.isCLESite = false;

        $scope.uiInit = function () {
            if (typeof global.store.customer === 'object' && global.store.customer.email.length > 0) {
                $scope.notifyData.name = global.store.customer.firstname + " " + global.store.customer.lastname;
                $scope.notifyData.email = global.store.customer.email;
            }
            $scope.initSelector();
            $scope.refresh();
            $.cartUtility.productSelect($.productData, $.productData.SelectedID);

            const storeId = global.store.id;
            const isCLE = (
                (storeId >= 7 && storeId <= 12) ||
                (storeId === 37) ||
                (storeId >= 39 && storeId <= 41));

            this.isCLESite = isCLE;
        }

        $scope.initSelector = function () {
            if ($.productData) {
                if ($.productData.SelectedID <= 0
                    && $.productData.Products.length > 0
                ) $.productData.SelectedID = $.productData.Products[0].ProductID;

                var needToChange = false;
                var targetID = 0;
                var included = false;
                for (var i = 0; i < $.productData.Products.length; i++) {
                    if ($.productData.SelectedID == $.productData.Products[i].ProductID) {
                        included = true;
                        if (!$.productData.Products[i].InStock) needToChange = true;
                    }
                    if ($.productData.Products[i].InStock) targetID = $.productData.Products[i].ProductID;
                }
                if ((needToChange && targetID > 0) || !included) $.productData.SelectedID = targetID;
            }
        }

        $scope.refresh = function () {
            if ($.productData) {
                for (var i = 0; i < $.productData.Products.length; i++) {
                    if ($.productData.SelectedID == $.productData.Products[i].ProductID) {
                        $scope.setupProduct($.productData.Products[i]);
                        break;
                    }
                }
                $scope.cartTotal = $.productData.CartTotal;
                $scope.cartItemCount = $.productData.CartItemCount;
                if ($.productData.FreeShipThreshold > 0)
                    $scope.freeShipThreshold = $.productData.FreeShipThresholdFormat;
                if ($scope.CartItemCount > 0) {
                    $scope.updateCartItem($scope.CartItemCount);
                }
                $scope.staff = $.productData.Staff;
                $scope.membershipEnable = $.productData.MembershipEnable;
                $scope.productName = $.productData.MasterProductName;
            }
        }

        $scope.close = function () { }

        $scope.addToCart = function () {

            if ($scope.productid && $scope.productid > 0) {

                if ($scope.added) {
                    location.href = '/shoppingcart/#/shipping';
                    return;
                }

                //check free item is selected
                if ($scope.freeItems != null && $scope.freeItems.length > 0) {
                    for (var r = 0; r < $scope.freeItemRecord.length; r++) {
                        if ($scope.freeItemRecord[r].pid == 0) {
                            $scope.selectFreeItemMessage = true;
                            $timeout(function () { $scope.selectFreeItemMessage = false; }, 1000 * 5);
                            return;
                        }
                    }
                }

                $scope.loading = true;
                $scope.addtocartDisabled = true;
                var url = '/shoppingcart/addproduct/?productid=' + $scope.productid;
                if ($scope.freeItemRecord && $scope.freeItemRecord.length > 0) {
                    var idstr = '';
                    for (var i = 0; i < $scope.freeItemRecord.length; i++) {
                        idstr += $scope.freeItemRecord[i].pid;
                        if (i < $scope.freeItemRecord.length - 1)
                            idstr += ',';
                    }
                    url += "&freeitem=" + idstr;
                }

                $http({
                    url: url,
                    method: 'GET'
                }).success(function (data) {
                    $scope.loading = false;
                    $scope.addtocartDisabled = false;
                    if (data.status == 'success') {
                        $scope.cartTotal = data.total;
                        $scope.cartItemCount = data.count;
                        $scope.updateCartItem(data.count);
                        $scope.added = true;
                        $scope.productAdded(data.itemid);
                        $scope.cartItemID = data.itemid;
                    }

                    notificationBar.show('<span class="' + (data.status == 'success' ? 'i-check-circle' : 'i-cross-circle') + '"></span>' + data.message, 1000 * 10);
                    $scope.setupCrossSell();

                    const masterProductId = document.querySelector(`meta[name='x-masterproduct-id']`).getAttribute('content');
                    const productName = document.querySelector(`meta[property='og:title']`).getAttribute('content');
                    const price = parseFloat(document.querySelector('.product-price').innerText.replace(/[^\d\,\.]/, ''));
                    const productCategory = document.querySelector(`meta[itemprop='category']`).getAttribute('content');

                    if (window.Moengage) {
                        Moengage.track_event("Add to Cart", {
                            "Store Code": global.store.storeCode,
                            "Quantity": 1,
                            "Product Name": productName,
                            "Category Description": productCategory,
                            "Product ID": $scope.productid,
                            "Master Product ID": masterProductId,
                            "price": price
                        });
                    }

                    const productData = $.productData;

                    const productId = productData.SelectedID;
                    const product = productData.Products.filter(p => p.ProductID === productId)[0];
                    const variant = productData.ProductAttributes.flatMap(attr => attr.Attributes)
                        .find(attribute => attribute.ProductIDs.includes(productId));

                    // Track the add to cart event
                    dataLayer.push({
                        'event': 'add_to_cart',
                        'ecommerce': {
                            'items': [
                                {
                                    'item_name': product.ProductName,
                                    'item_id': productId.toString(),
                                    'price': global.store.storeCode === 'JP' ? price.toString() : price.toFixed(2),
                                    'item_brand': 'Creative',
                                    'item_category': productCategory,
                                    'item_variant': (variant !== undefined ? variant.Name : '') || '',
                                    'quantity': 1
                                }
                            ]
                        },
                    });
                });
            }
        }

        $scope.addToCartAndCheckout = function () {

        }

        $scope.updateCartItem = function (i) {
            $.updateCartCount(i);
        }

        $scope.setupProduct = function (data) {
            this.price = data.PriceFormat;
            if (data.Price < data.ListPrice) this.listPrice = data.ListPriceFormat; else this.listPrice = '';
            this.lowestPrice = data.LowestPriceFormat;
            this.available = data.Available;
            this.memberPoints = data.MemberPoints;
            if (data.IsBundle) this.memberPoints = 0;
            this.productid = data.ProductID;
            this.image = $.productUtility.productImage(data.ProductID);
            this.addtocartDisabled = false;
            this.added = data.Added;
            this.freeItems = data.FreeItems;
            this.cartItemID = data.CartItemID;
            this.setupFreeItem(true);
            if (this.freeItems != null && this.freeItems.length > 0) this.hasFreeItems = true; else this.hasFreeItems = false;
            this.freeItemAutoAdded = this.freeItemAutoLoad();
            this.crossSell = data.CrossSell;
            this.setupCrossSell();
            if (this.crossSell != null && this.crossSell.length > 0) this.hasCrossSell = true; else this.hasCrossSell = false;
            if (data.Message != null && data.Message.length > 0) this.promoMessage = data.Message; else this.promoMessage = [];
            this.showNotifyMe = false;
            if (data.InStock) this.notifyMe = false; else this.notifyMe = true;
            this.shippingData = {
                freeShipping: data.FreeShipping,
                shippingCharge: data.ShippingCost
            }
            if (data.Price <= 0.01) {
                this.price = "Not available";
                this.available = "Not available";
                this.addtocartDisabled = true;
                this.notifyMe = true;
            }
            this.modelNo = data.ModelNo;

            // Coming Soon pdt list - '{pdtid as string key}': new Set([{storeid list as number able join multiple using comma}])            
            const arr_pdtComingSoon = {
               '24373': new Set([4])
            };
            const masterProductId = document.querySelector(`meta[name='x-masterproduct-id']`).getAttribute('content');
            // Check if the current product and store is match and not in stock
            if (arr_pdtComingSoon[masterProductId.toString()]?.has(global.store.id) && !data.InStock) {
                this.available = res.ProductComingSoon;
            }

            // if (data.ProductID === 23273 || data.ProductID === 23274)
            // {
            //     if (global.store.id === 1 || global.store.id === 15) {
            //         var avail = this.available;
            //         if (data.InStock)
            //             avail = this.available.replace('Available from ', 'Due to popular demand, the earlier batches of SXFI AIR have been sold out. Pre-order now for delivery from ')
            //                 .replace('. <br/>Pre-order now.', ' onwards.');
            //         else avail = 'Due to popular demand, the earlier batches of SXFI AIR have been sold out. Click Notify Me to be informed when new stock arrives.';
            //         this.available = avail;
            //     }
            // }
            // Convert Malaysia store price
            if (global.store.id === 38) this.convertMYR(data.Price);
            // special handling for Japan
            if (global.store.id === 2) this.price += '(税込)';
        }

        $scope.productAdded = function (id) {
            if ($scope.productid && $scope.productid > 0) {
                for (var i = 0; i < $.productData.Products.length; i++) {
                    if ($.productData.Products[i].ProductID == $scope.productid) {
                        $.productData.Products[i].Added = true;
                        $.productData.Products[i].CartItemID = id;
                        break;
                    }
                }
            }
        }

        $scope.messageTimeout = null;
        $scope.updateMessage = function (m) {
            if (m && m.length > 0) {
                $scope.message = m;
                if ($scope.messageTimeout != null) $timeout.cancel($scope.messageTimeout);
                $scope.messageTimeout = $timeout(function () { $scope.updateMessage(''); }, 1000 * 8);
            }
            else $scope.message = '';

        }

        $scope.getAttribute = function () {
            return $.cartUtility.attribute($.productData, 'master');
        }

        $scope.notifyme = function () {
            $scope.showNotifyMe = true;
        }

        $scope.closeNotifyMe = function () {
        }

        $scope.notifyMeSubmit = function () {
            if (!$scope.notifyData.name || !$scope.notifyData.email) return;
            if ($scope.productid <= 0) return;
            $scope.notifyMeLoading = true;
            $http({
                method: 'GET',
                url: $.cartUtility.secureUrl('/notifyme/add?Name=' + $scope.notifyData.name + '&Email=' + $scope.notifyData.email + '&ProductID=' + $scope.productid + '&MarketingEmail=' + $scope.notifyData.marketingEmail + '&ThirdPartyEmail=' + $scope.notifyData.thirdPartyEmail)
            }
            ).success(function (data) {
                $scope.notifyMeLoading = false;
                if (data.status == 'success') {
                    $scope.closeNotifyMe();
                    $scope.messageType = 'success';
                }
                else $scope.messageType = 'error';
                notificationBar.show('<span class="' + (data.status == 'success' ? 'i-check-circle' : 'i-cross-circle') + '"></span>' + data.message.replace("{0}", $scope.productName), 4000);
            });
        }

        $scope.updateAttr = function (updatetype, index, key, value, mpid) {
            if (updatetype == 'master') {
                var pid = $.cartUtility.userSelectGetProduct($.productData, key, value);
                $.cartUtility.userSelect($.productData, key, value);
                if (pid > 0) {
                    $.productData.SelectedID = pid;
                    $scope.refresh();
                }
            }

            if (updatetype == 'free') {
                var freeData = null;
                for (var i = 0; i < $scope.freeItems.length; i++) {
                    if ($scope.freeItems[i].MasterProductID == mpid) {
                        freeData = $scope.freeItems[i];
                        break;
                    }
                }
                var pid = $.cartUtility.userSelectGetProduct(freeData, key, value);
                $.cartUtility.userSelect(freeData, key, value);
                if (pid > 0 && !freeData.MasterModel) {
                    $scope.freeItemSelected(freeData.MasterProductID, pid);
                    $scope.setupFreeItem(false);
                    $scope.refresh();
                }
                else if (pid > 0 && freeData.MasterModel) {
                    $scope.setupFreeItemChildProduct(freeData.MasterProductID, pid);
                }
            }
        }

        $scope.getAttributeForFree = function (masterID) {
            for (var i = 0; i < $scope.freeItems.length; i++) if ($scope.freeItems[i].MasterProductID == masterID) return $.cartUtility.attribute($scope.freeItems[i], 'FREE');
        }

        $scope.getAttributeForPWP = function (masterID) {
            for (var i = 0; i < $scope.crossSell.length; i++) if ($scope.crossSell[i].MasterProductID == masterID) return $.cartUtility.attribute($scope.crossSell[i], 'PWP');

        }

        $scope.freeItemSelected = function (mid, pid) {
            for (var i = 0; i < $scope.freeItemRecord.length; i++) {
                if ($scope.freeItemRecord[i].mid == mid) {
                    $scope.freeItemRecord[i].pid = pid;
                    return;
                }
            }
            var maxMaster = $scope.freeItems[0].MaxQty;
            if ($scope.freeItemRecord.length >= maxMaster) {
                var newlist = [];
                for (var i = ($scope.freeItemRecord.length - maxMaster + 1); i < $scope.freeItemRecord.length; i++) {
                    newlist.push($scope.freeItemRecord[i]);
                }
                $scope.freeItemRecord = newlist;
            }
            $scope.freeItemRecord.push({ mid: mid, pid: pid });
            return;
        }

        $scope.crossSellSelected = function (mid, pid) {
            for (var i = 0; i < $scope.crossSell.length; i++) {
                if ($scope.crossSell[i].MasterProductID == mid) {
                    $scope.crossSell[i].selectedID = pid;
                }
            }
        }

        $scope.setupFreeItemChildProduct = function (mid, pid) {
            if ($scope.freeItems != null && $scope.freeItems.length > 0)
                for (var i = 0; i < $scope.freeItems.length; i++)
                    if ($scope.freeItems[i].MasterProductID == mid) {
                        $scope.freeItems[i].UserSelectID = pid;
                        $scope.freeItems[i].image = $.productUtility.productSmallImage(pid);
                        $scope.freeItems[i].Selected = false;
                        //reset record
                        for (var i = 0; i < $scope.freeItemRecord.length; i++)
                            if ($scope.freeItemRecord[i].mid == mid) $scope.freeItemRecord[i].pid = 0;
                    }
        }

        $scope.setupFreeItem = function (preSelect) {
            if ($scope.freeItems != null && $scope.freeItems.length > 0) {
                var maxQty = $scope.freeItems[0].MaxQty;
                //user has selected free item
                if ($scope.freeItemRecord.length > 0 && maxQty >= $scope.freeItemRecord.length) preSelect = false;
                for (var i = 0; i < $scope.freeItems.length; i++) {
                    var selectID = 0;
                    //select freeitem from record
                    for (var f = 0; f < $scope.freeItemRecord.length; f++) {
                        if ($scope.freeItemRecord[f].mid == $scope.freeItems[i].MasterProductID) {
                            selectID = $scope.freeItemRecord[f].pid;
                            break;
                        }
                    }
                    //pre-select freeitem
                    if (selectID == 0 && maxQty > 0 && preSelect) selectID = $scope.freeItems[i].ProductID;
                    if (selectID > 0) {
                        $scope.freeItems[i].UserSelectID = selectID;
                        $scope.freeItems[i].image = $.productUtility.productSmallImage(selectID);
                        $.cartUtility.productSelect($scope.freeItems[i], selectID);
                        $scope.freeItems[i].Selected = true;
                        $scope.freeItemSelected($scope.freeItems[i].MasterProductID, selectID);
                        maxQty--;
                    }
                    else {
                        $scope.freeItems[i].image = $.productUtility.productSmallImage($scope.freeItems[i].ProductID);
                        $.cartUtility.clearSelect($scope.freeItems[i]);
                        $scope.freeItems[i].Selected = false;
                    }
                }
            }
        }

        $scope.setupCrossSell = function () {
            if ($scope.crossSell != null)
                for (var i = 0; i < $scope.crossSell.length; i++) {
                    if ($scope.crossSell[i].selectedID && $scope.crossSell[i].selectedID > 0) {
                        $scope.crossSell[i].image = $.productUtility.productImage($scope.crossSell[i].selectedID);
                        if ($scope.added) $scope.crossSell[i].disabled = false;
                        else $scope.crossSell[i].disabled = true;
                    }
                    else {
                        if ($scope.added) $scope.crossSell[i].disabled = false;
                        else $scope.crossSell[i].disabled = true;
                        if ($scope.crossSell[i].ChildProductIDs.length > 1) {
                            $scope.crossSell[i].image = $.productUtility.productImage($scope.crossSell[i].MasterProductID);
                            $scope.crossSell[i].isSingleProduct = false;
                            $scope.crossSell[i].disabled = true;
                        }
                        else {
                            $scope.crossSell[i].image = $.productUtility.productImage($scope.crossSell[i].ChildProductID);
                            $scope.crossSell[i].isSingleProduct = true;
                            $scope.crossSell[i].selectedID = $scope.crossSell[i].ChildProductID;
                            if ($scope.added) $scope.crossSell[i].disabled = false;
                        }
                    }
                    $scope.crossSell[i].loading = false;
                }
        }

        $scope.checkFreeItem = function () {
            if ($scope.freeItemAutoLoad()) return true;
            if ($scope.freeItems.length > 0) {
                var maxMaster = $scope.freeItems[0].MaxQty;
                return ($scope.freeItemRecord.length >= maxMaster)
            }
            return true;
        }

        $scope.freeItemAutoLoad = function () {
            if ($scope.freeItems.length > 0) {
                var maxMaster = $scope.freeItems[0].MaxQty;
                var freeSingle = true;
                for (var i = 0; i < $scope.freeItems.length; i++)
                    if ($scope.freeItems[i].MasterModel) {
                        freeSingle = false;
                        break;
                    }
                return (freeSingle && maxMaster == $scope.freeItems.length)
            }
            return true;
        }

        $scope.freeItemClick = function (item) {
            if (!item.MasterModel) $scope.freeItemSelected(item.MasterProductID, item.ProductID);
            else $scope.freeItemSelected(item.MasterProductID, item.UserSelectID);
            $scope.refresh();
            return;
        }

        $scope.addPWP = function (mid) {
            console.log(mid + "," + $scope.cartItemID);
            if ($scope.cartItemID && $scope.cartItemID > 0) {
                for (var i = 0; i < $scope.crossSell.length; i++) {
                    console.log($scope.crossSell[i].selectedID);
                    if ($scope.crossSell[i].MasterProductID == mid
                        && $scope.crossSell[i].selectedID
                        && $scope.crossSell[i].selectedID > 0) {
                        $scope.crossSell[i].loading = true;
                        var url = "/shoppingcart/addcrosssell?index=" + $scope.cartItemID + "&productid=" + $scope.crossSell[i].selectedID + "&masterproductid=" + mid;
                        $http({
                            method: 'GET',
                            url: url
                        })
                            .success(function (data) {
                                if (data.status == 'success') {
                                    $scope.messageType = 'success';
                                }
                                else {
                                    $scope.messageType = 'error';
                                }
                                $scope.updateMessage(data.message);
                                $scope.setupCrossSell();
                            });
                        break;
                    }
                }
            }
        }

        $scope.getFreeItemTitle = function () {
            if ($scope.freeItemAutoAdded) return res.FreeItems;
            else {
                if ($scope.freeItems != null && $scope.freeItems.length > 0)
                    return res.txt_selectfreeitem.replace("{0}", $scope.freeItems[0].MaxQty);
                else return '';
            }
        }

        $scope.convertMYR = function (price) {
            if (price && price > 0)
                $http({
                    method: 'GET',
                    url: '/products/getcurrencyexchangerate?baseCurrency=USD&symbols=MYR'
                }).success(function (data) {
                    if (data && data.rate && data.rate > 0) {
                        $scope.priceMYR = 'RM' + parseInt(price * data.rate).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
                    }
                });
        }
    }]);

;
"use strict";

angular.module('ngProductApp').service('ngApp', ['$rootScope', '$location', function ($rootScope, $location) {
    var _self = this;

    this.buttonDisabled = false;
    this.buttonLoading = false;

    this.showBtnLoading = function () {
        this.buttonDisabled = true;
        this.buttonLoading = true;
    };

    this.hideBtnLoading = function () {
        this.buttonDisabled = false;
        this.buttonLoading = false;
    };

}]);;
;
