PageSourceSearch

https://www.prpwine.com/wp-content/plugins/idstc-acuta/app/app/app.js?ver=3.1.20260923.1

js prpwine.com collected 2026-09-25 20:51:21 UTC 45,088 bytes, 1,126 lines download raw bytes

1var providers = {};
2var idstcApiToken = null;
3
4// Hosted-payment diagnostics: report every write to the cart identity keys together with the
5// stack of whoever made it, so a cart that disappears mid-checkout can be traced to its caller.
6// This runs before the module is defined so no controller or service can write before it.
7(function () {
8  var hostedPaymentDiagnosticVersion = '2026-07-29.3';
9  var watchedCartKeys = ['CartID', 'CustomerCartID', 'JoinCartID', 'CompletedCartID'];
10
11  ['setItem', 'removeItem'].forEach(function (operation) {
12    var originalOperation = Storage.prototype[operation];
13
14    Storage.prototype[operation] = function (key, value) {
15      // Every storage write in the app now passes through here, so a failure to log must never
16      // stop the write itself from happening.
17      try {
18        if (this === window.localStorage && watchedCartKeys.indexOf(key) >= 0) {
19          console.info('[Hosted Payment] Cart identity key ' + operation + '.', {
20            diagnosticVersion: hostedPaymentDiagnosticVersion,
21            key: key,
22            value: operation === 'setItem' ? String(value) : null,
23            page: window.location.pathname + window.location.search,
24            stack: (new Error().stack || '').split('\n').slice(2, 7).join(' | ')
25          });
26        }
27      } catch (e) {
28      }
29
30      return originalOperation.apply(this, arguments);
31    };
32  });
33})();
34
35var app = angular.module('app', ['kendo.directives', 'ui.router', 'ngSanitize'], function ($controllerProvider, $compileProvider, $provide) {
36  providers = {
37    $controllerProvider: $controllerProvider,
38    $compileProvider: $compileProvider,
39    $provide: $provide
40  };
41});
42
43//Expose our idstc object into angular for injection
44app.constant('idstc', window.idstc);
45
46//Add transform from idstc() library
47app.config(function ($httpProvider, idstc) {
48
49  $httpProvider.defaults.withCredentials = true;
50  $httpProvider.defaults.transformResponse.push(function (data, headersGetter) {
51
52    //Handling types such as: application/json; charset=utf-8
53    if (/application\/json;/.test(headersGetter('Content-Type'))) {
54
55      return ProcessIdstcResponseObject(data);
56    } else {
57      return data;
58    }
59  });
60
61  $httpProvider.interceptors.push(function ($q) {
62    return {
63      // optional method
64      'request': function (config) {
65
66        if (idstcApiToken != null) {
67          let apiUrlLowercase = idstc_setting_apiurl.toLowerCase();
68
69          if (config.url.toLowerCase().indexOf(apiUrlLowercase) >= 0) {
70            config.headers.Authorization = 'bearer ' + idstcApiToken;
71          }
72        }
73
74        // do something on success
75        return config;
76      },
77      'response': function (response) {
78        return response;
79      },
80      'requestError': function (rejectReason) {
81      },
82      'responseError': function (response) {
83        if (response.status === 403) {
84          var personType = localStorage.getItem('pesonType');
85          if (personType === 2 && location.href !== '/log-in-customer') {
86            location.href = '/log-in-customer';
87          }
88          if (personType === 1 && location.href !== '/log-in-consultant') {
89            location.href = '/log-in-consultant';
90          }
91        }
92        throw response;
93      }
94    };
95  });
96
97  //Hoisting makes this available to the above transform function
98  function isIdstcResponseObject(o) {
99    if (angular.isObject(o)) {
100      return o.hasOwnProperty('ResultCode') && o.hasOwnProperty('Notifications') && o.hasOwnProperty('ValidationResults');
101    }
102
103    return false;
104  }
105
106  function ProcessIdstcResponseObject(o) {
107
108    if (isIdstcResponseObject(o)) {
109
110      //If we get this far, must have been a success. If not, I modified the standard responseMessage fn to default to 'error'
111      var actualNewObject = {};
112
113      //SD: Not sure the idstc object is doing the right thing here so i'm explicitly setting 'this' to a brand new object
114      return new idstc().responseMessage.call(actualNewObject, o.Notifications, o.Value, o.ResultCode, 'success', o.ValidationResults, o);
115    }
116
117    return o;
118  }
119});
120
121//Decorator pattern to capture errors and put into our notifications. (easier troubleshooting)
122app.config(function ($provide) {
123  $provide.decorator('$exceptionHandler', function ($delegate, $injector) {
124    return function (exception, cause) {
125
126      $delegate(exception, cause);
127
128      var idstc = $injector.get('idstc');
129
130      JL('Angular').fatalException(cause, exception);
131
132      idstc().notify({ message: exception.message, title: 'Error Notification', success: 'error' });
133    };
134  });
135});
136
137// Handle routing for the client support app
138app.config(['$locationProvider', function ($locationProvider) {
139  $locationProvider.html5Mode({
140    enabled: true,
141    requireBase: false,
142    rewriteLinks: false
143  });
144}]);
145
146app.run(['$rootScope', '$location', '$state', '$stateParams', function ($rootScope, $location, $state, $stateParams) {
147  //Client-side security. Server-side framework MUST add it's
148  //own security as well since client-based security is easily hacked
149  $rootScope.$on('$stateChangeStart',
150    function (event, toState, toParams, fromState, fromParams) {
151      $(document).progressStart();
152    }
153  );
154
155  $rootScope.$on('$stateChangeSuccess',
156    function (event, toState, toParams, fromState, fromParams) {
157      $(document).progressFinish();
158    }
159  );
160
161  // It's very handy to add references to $state and $stateParams to the $rootScope
162  // so that you can access them from any scope within your applications.For example,
163  // <li ng-class='{ active: $state.includes('contacts.list') }'> will set the <li>
164  // to active whenever 'contacts.list' or one of its decendents is active.
165  $rootScope.$state = $state;
166  $rootScope.$stateParams = $stateParams;
167}]);
168
169function getParameterByName(name, ignoreCase = false) {
170  name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
171  const flags = ignoreCase ? 'i' : '';
172  const regex = new RegExp('[\\?&]' + name + '=([^&#]*)', flags);
173  const results = regex.exec(location.search);
174  return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
175}
176
177$(document).ready(function ($) {
178
179  var consultant = $.parseJSON(sessionStorage.getItem('consultant'));
180
181  // Auto-apply coupon: capture a coupon code from the query string (?coupon=XXX) on any
182  // landing page and stash it in session storage. It is applied once the shopper reaches
183  // the cart (see viewCartController / subtotalController applyPendingCoupon).
184  var incomingCoupon = getParameterByName('coupon');
185
186  if (incomingCoupon != null && incomingCoupon !== '') {
187    idstc().setExpirableSessionStorageVar('PendingCouponCode', incomingCoupon);
188
189    // Strip the coupon param from the URL so a reload/back/share doesn't re-trigger it
190    // and the code isn't leaked in a bookmarked or shared link.
191    if (window.history && window.history.replaceState && window.URL) {
192      var couponUrl = new URL(window.location.href);
193      couponUrl.searchParams.delete('coupon');
194      window.history.replaceState(null, '', couponUrl.pathname + couponUrl.search + couponUrl.hash);
195    }
196  }
197
198  // Store our _invokeQueue length before loading our controllers/directives/services
199  // This is just so we don't re-register anything
200  var queueLen = angular.module('app')._invokeQueue.length;
201
202  // Load javascript file with controllers/directives/services
203  angular.module('app')
204    .controller('siteController', function ($scope, $rootScope, $http, $q, appService, shoppingCartModel) {
205      var vm = this;
206
207      appService.scope = $scope;
208      vm.appService = appService;
209      vm.shoppingCartModel = shoppingCartModel;
210
211      vm.init = function () {
212        var promises = [appService.makeReady()];
213
214        $q.all(promises).then(function (result) {
215
216        });
217      }
218
219      vm.init();
220    })
221    .factory('appService', function ($http, $q, $sce, $compile, $location, $filter) {
222      var service = this;
223
224      service.consultant = null;
225      service.apiToken = null;
226      service.getAPITokenPromise = null;
227      service.currencyTypePromise = null;
228      service.dateFormatPromise = null;
229      service.timeFormatPromise = null;
230      service.utcOffsetPromise = null;
231      service.businessUnitIDPromise = null;
232      service.getConsultantPromise = null;
233      service.makeReadyPromise = null;
234
235      service.loggedIn = idstc().getExpirableLocalStorageVar('loggedIn', 60);
236      service.personTypeId = idstc().getExpirableLocalStorageVar('personType', 60);
237      service.translatedPageNames = JSON.parse(translatedPageNames);
238
239      // The configData is a JSON representation of the data required to build the URL.
240      service.createShortUrl = function (configData) {
241        if (service.consultant != null) {
242          configData.replicatedSiteUrl = service.consultant.Url;
243        }
244
245        if (service.referringCustomerDisplayId != null) {
246          configData.referringCustomerDisplayId = service.referringCustomerDisplayId;
247        }
248
249        if (php_vars && php_vars.languageCode) {
250          configData.languageCode = php_vars.languageCode;
251        }
252
253        let url = templateUrl + 'api/addShortUrl.php';
254
255        let postVar = {
256          configData: JSON.stringify(configData)
257        }
258
259        return $http.post(url, postVar).then(
260          function (response) {
261            let shareUrl = location.protocol + '//' + location.hostname;
262
263            shareUrl += response.data;
264
265            service.shareUrl = shareUrl;
266          },
267          function (errorResult) {
268            idstc().processError({ error: errorResult, showNotifications: true });
269          }
270        );
271      };
272
273      service.getLanguagePrefix = function (languageCode, countryCode) {
274        let url = '/wp-admin/admin-ajax.php?action=idstc_get_languages';
275
276        return $http.get(url).then(
277          function (successResult) {
278            let siteLanguages = successResult.data;
279            let prefix = '/';
280
281            if (languageCode != null) {
282              let langCode = languageCode;
283
284              if (countryCode != null) {
285                langCode += '-' + countryCode;
286              }
287
288              if (siteLanguages.default != '' && siteLanguages.default != langCode) {
289                if ($filter('filter')(siteLanguages.languages, langCode, true) != null && $filter('filter')(siteLanguages.languages, langCode, true).length > 0) {
290                  prefix += langCode;
291                }
292                else {
293                  langOnly = $filter('filter')(siteLanguages.languages, languageCode, false);
294                  if (langOnly != null && langOnly.length > 0) {
295                    prefix += langOnly[0];
296                  }
297                }
298
299                prefix += '/';
300              }
301            }
302
303            return prefix;
304          },
305          function (errorResult) {
306            idstc().processError({ error: errorResult, showNotifications: true });
307            return '/';
308          }
309        );
310      };
311
312      service.logout = function (gotoHome) {
313        localStorage.removeItem('Authorization');
314        localStorage.removeItem('idstc-cart');
315        localStorage.removeItem('loggedIn');
316        localStorage.removeItem('personType');
317        localStorage.removeItem('CartID');
318        localStorage.removeItem('CustomerCartID');
319        localStorage.removeItem('CartItemQuantity');
320        localStorage.removeItem('displayCategoryId');
321        localStorage.removeItem('subSkuForWeb');
322        localStorage.removeItem('referringCustomerDisplayId');
323        sessionStorage.removeItem('displayCategories');
324        sessionStorage.removeItem('translations');
325        localStorage.removeItem('accountTypeID');
326        localStorage.removeItem('flightCustomFields');
327
328        if (gotoHome == null || gotoHome == true) {
329          service.getLanguagePrefix(localStorage.getItem('languageCode'), localStorage.getItem('countryCode')).then(function (result) {
330            let languagePrefix = result;
331            window.location = languagePrefix;
332          });
333        }
334      };
335
336      if ($location.search().logout == '1') {
337        service.logout();
338      }
339
340      service.collectCustomFieldsFromUrl = function () {
341        service.setCustomField('utm_campaign');
342        service.setCustomField('utm_content');
343        service.setCustomField('utm_medium');
344        service.setCustomField('utm_source');
345        service.setCustomField('utm_term');
346      }
347
348      service.setCustomField = function (field) {
349        let value = getParameterByName(field) || '';
350
351        if (value != '') {
352          let storedItem = localStorage.getItem('flightCustomFields');
353
354          if (storedItem == null) {
355            storedItem = {};
356          }
357          else {
358            storedItem = JSON.parse(storedItem);
359          }
360
361          storedItem[field] = value;
362
363          localStorage.setItem('flightCustomFields', JSON.stringify(storedItem));
364        }
365      }
366
367      service.makeReady = function () {
368        if (service.makeReadyPromise) {
369          return service.makeReadyPromise;
370        }
371
372        var promises = [];
373        service.newAuthToken = localStorage.getItem('newAuthToken');
374
375        service.makeReadyPromise = $q.all(promises).then(function (result) {
376          service.collectCustomFieldsFromUrl();
377
378          if (service.newAuthToken != null || service.tokenValid) {
379            if (service.newAuthToken != null) {
380              service.newAuthToken = service.newAuthToken.replace('bearer ', '');
381
382              idstc().setExpirableLocalStorageVar('Authorization', service.newAuthToken);
383              idstc().setExpirableLocalStorageVar('loggedIn', true);
384
385              localStorage.removeItem('newAuthToken');
386
387              service.apiToken = service.newAuthToken;
388              idstcApiToken = service.newAuthToken;
389              service.loggedIn = true;
390              service.tokenValid = true;
391            }
392          }
393
394          // Try to get replicated site url
395          let repUrl = getParameterByName('u');
396
397          if (repUrl == null || repUrl == '') {
398            if (typeof (pluginReplSite) != 'undefined' && pluginReplSite != null && pluginReplSite != '') {
399              repUrl = pluginReplSite;
400            }
401          }
402
403          // Check to see if you were on a replicated site and now it is changing
404          // if so, clear cart info to avoid person shopping with bad parameters.
405          if (repUrl != null && repUrl != '') {
406            var localRepUrl = localStorage.getItem('replicatedSiteUrl');
407            if (localRepUrl != null && localRepUrl != '' && repUrl != localRepUrl) {
408              var preserveJoinBrowse = typeof window.idstcJoinCartBrowsePreserveContext === 'function' && window.idstcJoinCartBrowsePreserveContext();
409              // "+ Add Products" navigates to /order without the u= parameter, so this drift check
410              // fires on that hop and on every page after it until the site owner is resolved again.
411              // Logged immediately before the clearing branch, so it must not be able to throw
412              // and skip a clear that is supposed to happen.
413              try {
414                console.warn('[Hosted Payment] Replicated site owner drift detected.', {
415                  diagnosticVersion: '2026-07-29.3',
416                  page: window.location.pathname + window.location.search,
417                  storedReplicatedSiteUrl: localRepUrl,
418                  incomingReplicatedSiteUrl: repUrl,
419                  preserveJoinBrowse: preserveJoinBrowse,
420                  cartStorageWillBeCleared: !preserveJoinBrowse,
421                  cartIdPresent: !!localStorage.getItem('CartID'),
422                  joinCartIdPresent: !!localStorage.getItem('JoinCartID')
423                });
424              } catch (e) {
425              }
426              if (!preserveJoinBrowse) {
427                localStorage.removeItem('CartID');
428                localStorage.removeItem('CustomerCartID');
429                localStorage.removeItem('CartItemQuantity');
430                localStorage.removeItem('displayCategoryId');
431                localStorage.removeItem('referringCustomerDisplayId');
432                sessionStorage.removeItem('displayCategories');
433                localStorage.removeItem('accountTypeID');
434                sessionStorage.removeItem('validatedEventID');
435                localStorage.removeItem('idstc-cart');
436              }
437            }
438          }
439
440          if (repUrl == null || repUrl == '') {
441            repUrl = localStorage.getItem('replicatedSiteUrl');
442          }
443
444          // Try to get referring customer display id
445          // First from URL
446          // Second from local storage
447          service.referringCustomerDisplayId = getParameterByName('r');
448
449          if (service.referringCustomerDisplayId == null || service.referringCustomerDisplayId == '') {
450            service.referringCustomerDisplayId = localStorage.getItem('referringCustomerDisplayId');
451          }
452          else {
453            localStorage.setItem('referringCustomerDisplayId', service.referringCustomerDisplayId);
454          }
455
456          if ((repUrl != null && repUrl != '') && (consultant == null || consultant.Url == null || consultant.Url.toLowerCase() != repUrl.toLowerCase())) {
457            promises.push(service.getConsultant(repUrl));
458          }
459          else if (consultant != null) {
460            service.consultant = consultant;
461            flightConsultant = consultant;
462          }
463          else if (idstc_setting_businessunitsenabled) {
464            promises.push(service.getDefaultBusinessUnitID());
465          }
466
467          return $q.all(promises).then(function (result) {
468            if (service.newAuthToken == null || !service.tokenValid) {
469              promises.push(service.getAPIToken());
470            }
471
472            return $q.all(promises).then(function (result) {
473              promises = [service.getCurrencyTypes(), service.getUTCOffset(), service.getDateFormat(), service.getTimeFormat(), service.getCountries()];
474
475              if (service.newAuthToken != null) {
476                var cartId = idstc().getExpirableLocalStorageVar('CartID', idstc_setting_acutacartexpirationseconds);
477
478                // Now try to get the replicated site owner for this customer
479                if (repUrl == null || repUrl == '') {
480                  promises.push(service.getReplicatedSiteOwner());
481                }
482                else {
483                  var keepSiteOwner = localStorage.getItem('keepSiteOwner');
484
485                  if (keepSiteOwner != null) {
486                    service.keepSiteOwner = true;
487                    localStorage.removeItem('keepSiteOwner');
488                  }
489                  else if (!service.keepSiteOwner) {
490                    promises.push(service.getReplicatedSiteOwner());
491                  }
492                }
493
494                promises.push(service.setCurrentPerson(cartId));
495              }
496
497              return $q.all(promises).then(function (result) {
498                if (service.consultant != null && service.consultant.Url != null) {
499                  if (typeof window.idstcAppendQueryParamIfMissing === 'function') {
500                    window.idstcAppendQueryParamIfMissing('u', service.consultant.Url, service.consultant.Url);
501                  }
502                  $('body').addClass(service.consultant.Url.toLowerCase());
503                  $('body').addClass('rank-' + service.consultant.RankTypeID);
504                  //Also - set the body class to let site know we are replicated in case styling should be different
505                  $('body').removeClass('non-replicated');
506                  $('body').addClass('replicated');
507                }
508
509                if (service.referringCustomerDisplayId != null && service.referringCustomerDisplayId != '') {
510                  if (typeof window.idstcAppendQueryParamIfMissing === 'function') {
511                    window.idstcAppendQueryParamIfMissing('r', service.referringCustomerDisplayId, service.referringCustomerDisplayId);
512                  }
513                }
514              });
515            });
516          });
517        });
518
519        return service.makeReadyPromise;
520      }
521
522      service.setCurrentPerson = function (cartId) {
523        if (cartId != null) {
524          return $http.post(apiRoot + 'api/Shopping/SetCurrentPerson?cartId=' + cartId).then(
525            function (results) {
526              // success
527            });
528        }
529      }
530
531      service.getReplicatedSiteOwner = function () {
532        return $http.get(apiRoot + 'api/Shopping/GetReplicatedSiteOwnerUrl').then(
533          function (result) {
534            // The "idstc_setting_corporateconsultanturl" variable is written to page via the php_vars.js (wordpress method of getting server variables to client script).
535            // We will default to the corporate site owner when the newly-logged-in customer's replicated site owner can't be found or is not active (BlockWebsite flag is true).
536            var url = idstc_setting_corporateconsultanturl;
537
538            if (result.data != null && result.data != '') {
539              url = result.data;
540            }
541
542            return service.getConsultant(url);
543          });
544      }
545
546      service.getAndStoreUserAvailableUIElements = function () {
547        return $http.get(apiRoot + 'api/Website/GetUserAvailableUIElements').then(
548          function (result) {
549            storage.set('AvailableUIElements', result.data);
550          });
551      }
552
553      service.getAPIToken = function () {
554        service.apiToken = idstc().getExpirableLocalStorageVar('Authorization', 1440);
555        idstcApiToken = service.apiToken;
556        existingLanguageCode = localStorage.getItem('languageCode');
557
558        // language code comes from polylang and is stored in php_vars variable
559        // the first 2 digits should match the language code in idstc        
560        if (php_vars && php_vars.languageCode && php_vars.languageCode.length > 0) {
561          languageCode = php_vars.languageCode.substring(0, 2);
562        }
563
564        var languageChanged = false;
565        if (languageCode != null && languageCode != existingLanguageCode) {
566          if (!service.loggedIn) {
567            service.apiToken = null;
568            idstcApiToken = null;
569          }
570          sessionStorage.removeItem('translations');
571          sessionStorage.removeItem('displayCategories');
572          service.setLanguageCode(languageCode, 'app.js - getAPIToken - languageCode');
573          languageChanged = true;
574        }
575
576        var existingCountryCode = localStorage.getItem('countryCode');
577
578        // country code comes from polylang and is stored in php_vars variable
579        // the last 2 digits should match the country code abbreviation in idstc
580        // We will not set the countryCode from polylang if setting is enabled
581        if (php_vars && php_vars.languageCode && php_vars.languageCode.length > 0 && idstc_setting_acutacustomcountrycodeenabled != 'on') {
582          countryCode = php_vars.languageCode.substring(3, 5);
583        }
584
585        let countryCodeToLower = null;
586        let existingCountryCodeToLower = null;
587
588        if (countryCode != null) {
589          countryCodeToLower = idstcNormalizeAcutaCountryCode(countryCode);
590        }
591        if (existingCountryCode != null) {
592          existingCountryCodeToLower = idstcNormalizeAcutaCountryCode(existingCountryCode);
593        }
594
595        var countryChanged = false;
596        if (existingCountryCodeToLower != countryCodeToLower) {
597          var preserveJoinBrowseCart = typeof window.idstcJoinCartBrowsePreserveContext === 'function' && window.idstcJoinCartBrowsePreserveContext();
598          var hadStoredCountry = existingCountryCode != null && String(existingCountryCode).trim() !== '';
599
600          if (!preserveJoinBrowseCart && hadStoredCountry) {
601            if (existingCountryCodeToLower == null && localStorage.getItem('RecommendedCartID') != null) {
602
603            }
604            else {
605              localStorage.removeItem('CartID');
606              localStorage.removeItem('idstc-cart');
607              localStorage.removeItem('CustomerCartID');
608            }
609          }
610
611          sessionStorage.removeItem('translations');
612
613          service.setCountryCode(countryCode);
614
615          if (!preserveJoinBrowseCart && hadStoredCountry) {
616            localStorage.removeItem('JoinCartID');
617            localStorage.removeItem('CartItemQuantity');
618            localStorage.removeItem('provinceID');
619          }
620          countryChanged = true;
621        }
622
623        if (service.getAPITokenPromise) {
624          return service.getAPITokenPromise;
625        }
626        else if (service.apiToken && !languageChanged && !countryChanged) {
627          try {
628            var jwtPayload = JSON.parse(atob(service.apiToken.split('.')[1]));
629            if (jwtPayload.exp && (jwtPayload.exp * 1000) < (Date.now() + 60000)) {
630              service.apiToken = null;
631              idstcApiToken = null;
632              localStorage.removeItem('Authorization');
633            } else {
634              return;
635            }
636          } catch (e) {
637            return;
638          }
639        }
640
641        service.getAPITokenPromise = service.getAPITokenFromServer();
642
643        return service.getAPITokenPromise;
644      }
645
646      service.getAPITokenFromServer = function () {
647        var url = apiRoot + 'api/WebsiteSession/GetBaseSiteDataWithCountry?languageCode=' + languageCode;
648        if (typeof countryCode != 'undefined' && countryCode != null && countryCode != '') {
649          url = url + '&countryCode=' + countryCode;
650        }
651        if (idstc_setting_businessunitsenabled) {
652          var businessUnitID = sessionStorage.getItem('businessUnitID');
653          if (typeof businessUnitID != 'undefined' && businessUnitID != null && businessUnitID != '') {
654            url = url + '&businessUnitID=' + businessUnitID;
655          }
656        }
657
658        return $http.get(url).then(
659          function (successResult) {
660            var dto = successResult.data;
661
662            var apiJSONObject = $.parseJSON(dto.APIToken); // needs to be parsed to remove "Access_Token" stuff;
663            if (apiJSONObject.access_token && apiJSONObject.access_token != '') {
664              service.apiToken = apiJSONObject.access_token;
665              idstcApiToken = service.apiToken;
666            }
667
668            idstc().setExpirableLocalStorageVar('Authorization', service.apiToken);
669
670            localStorage.setItem('AvailableUIElements', JSON.stringify(dto.AvailableUIElements));
671            localStorage.setItem('shippingAddressResidentialDefault', dto.ShippingAddressResidentialDefault);
672            service.setLanguageCode(languageCode, 'app.js - getAPITokenFromServer - languageCode');
673
674            service.storeCountries(dto.Countries);
675            service.storeCurrencyTypes(dto.CurrencyTypes);
676            service.storeDateFormat(dto.DateFormat);
677            service.storeTimeFormat(dto.TimeFormat);
678            service.storeUTCOffset(dto.UTCOffset);
679
680            var existingCountryCode = localStorage.getItem('countryCode');
681            // country code comes from polylang and is stored in php_vars variable
682            // the last 2 digits should match the country code abbreviation in idstc
683            // We will not set the countryCode from polylang if setting is enabled
684            if (php_vars && php_vars.languageCode && php_vars.languageCode.length > 0 && idstc_setting_acutacustomcountrycodeenabled != 'on') {
685              countryCode = php_vars.languageCode.substring(3, 5);
686            }
687
688            let countryCodeToLower = null;
689            let existingCountryCodeToLower = null;
690
691            if (countryCode != null) {
692              countryCodeToLower = idstcNormalizeAcutaCountryCode(countryCode);
693            }
694            if (existingCountryCode != null) {
695              existingCountryCodeToLower = idstcNormalizeAcutaCountryCode(existingCountryCode);
696            }
697
698            // if has not changed then just set new person (possibly anonymous) on order
699            // otherwise, clear cart info which will allow new cart to be created
700            if (existingCountryCodeToLower == countryCodeToLower) {
701              var cartId = idstc().getExpirableLocalStorageVar('CartID', idstc_setting_acutacartexpirationseconds);
702              if (typeof cartId != 'undefined' && cartId != null && cartId != '') {
703                return service.setCurrentPerson(cartId);
704              }
705            }
706            else {
707              service.setCountryCode(countryCode);
708              localStorage.removeItem('provinceID');
709            }
710
711            return 'done';
712          });
713      }
714
715      service.getConsultant = function (replSite) {
716        if (replSite != null && replSite != '' && replSite != 'null') {
717          if (service.getConsultantPromise) {
718            return service.getConsultantPromise;
719          }
720
721          service.getConsultantPromise = service.getConsultantFromServer(replSite);
722
723          return service.getConsultantPromise;
724        }
725      }
726
727      service.getConsultantFromServer = function (replSite) {
728        var returnIfBlocked = 'false';
729        if (idstc_setting_proceedtocorpwhenbadreplsite == 'on') {
730          returnIfBlocked = 'true';
731        }
732        return $http.post(apiRoot + 'api/Website/GetConsultantReplicationSiteInfo?url=' + replSite + '&returnIfBlocked=' + returnIfBlocked).then(
733          function (successResult) {
734            if (successResult.data != null && typeof successResult.data.DisplayID != 'undefined' && successResult.data.DisplayID != null && successResult.data.BlockWebsite == false) {
735              service.setConsultant(successResult.data);
736              service.getConsultantPromise = null;
737              return;
738            }
739            else {
740              if (idstc_setting_proceedtocorpwhenbadreplsite == 'on' && successResult.data != null && typeof successResult.data.BlockWebsite != 'undefined' && successResult.data.BlockWebsite == true) {
741                return $http.post(apiRoot + 'api/Website/GetConsultantReplicationSiteInfo?url=' + idstc_setting_corporateconsultanturl + '&returnIfBlocked=false').then(
742                  function (successResult) {
743                    service.setConsultant(successResult.data);
744                    service.getConsultantPromise = null;
745                    return;
746                  });
747              }
748              else {
749                service.getConsultantPromise = null;
750                return;
751              }
752            }
753          });
754      }
755
756      service.getDefaultBusinessUnitID = function () {
757        var businessUnitID = sessionStorage.getItem('businessUnitID');
758
759        if (service.businessUnitIDPromise) {
760          return service.businessUnitIDPromise;
761        }
762
763        if (typeof businessUnitID == 'undefined' || businessUnitID == null || businessUnitID != '') {
764          service.businessUnitIDPromise = service.getAndStoreBusinessUnitID();
765        }
766
767        return service.businessUnitIDPromise;
768      }
769
770      service.getAndStoreBusinessUnitID = function () {
771        return $http.get(apiRoot + 'api/Website/GetDefaultBusinessUnitID').then(
772          function (successResult) {
773            sessionStorage.setItem('businessUnitID', successResult.data);
774          });
775      }
776
777      service.convertJsonToUrlEncoded = function (obj) {
778        var str = [];
779        for (var key in obj) {
780          if (obj.hasOwnProperty(key)) {
781            str.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
782          }
783        }
784        return str.join('&');
785      }
786
787      service.loginPortal = function () {
788        var url = apiRoot + 'api/CustomerPortal/LoginPortal';
789
790        // Generate a new external login provider key for the currently logged in customer via the API
791        $http.post(url, null).then(
792          function (resp) {
793            var loginRootPath = customerPortalRootPath;
794            var loginForm = document.getElementById('loginPortalForm');
795
796            if (loginForm != null) {
797              // Update form inputs and then programmatically post the hidden form to push user to portal
798              document.getElementById('IDSTCPortalProviderKey').value = resp.data.ProviderKey;
799              document.getElementById('IDSTCPortalUserId').value = resp.data.UserId;
800
801              loginForm.action = loginRootPath + 'Account/ExternalLoginRedirectFromForm';
802              loginForm.submit();
803            }
804
805            $(document).progressFinish();
806          },
807          function (err) {
808            idstc().notifyServerResponse(err.data);
809            $(document).progressFinish();
810          });
811      }
812
813      service.setConsultant = function (consultant) {
814        localStorage.setItem('replicatedSiteUrl', consultant.Url);
815        sessionStorage.setItem('consultant', JSON.stringify(consultant));
816        sessionStorage.setItem('businessUnitID', consultant.BusinessUnitID);
817        sessionStorage.removeItem('displayCategories');
818        service.consultant = consultant;
819        flightConsultant = consultant;
820      }
821
822      service.getCurrencyTypes = function (force) {
823        var currencyTypes = JSON.parse(localStorage.getItem('CurrencyTypes'));
824
825        if (service.currencyTypePromise) {
826          return service.currencyTypePromise;
827        }
828
829        if (currencyTypes != null) {
830          var diffTime = new Date().getTime() - currencyTypes.dateTime;
831          var diffInMinutes = Math.floor(diffTime / 1000 / 60); //get minutes from time
832
833          if (diffInMinutes >= 30 && !force) { //cache for 30 minutes
834            service.currencyTypePromise = service.getCurrencyTypes(true);
835          };
836
837          if (localStorage.getItem('CurrencyTypes') == null || !currencyTypes.dateTime || force) { //reset currency types
838            service.currencyTypePromise = service.getAndStoreCurrencyTypes();
839          }
840        }
841        else {
842          service.currencyTypePromise = service.getAndStoreCurrencyTypes();
843        }
844
845        return service.currencyTypePromise;
846      }
847
848      service.getAndStoreCurrencyTypes = function () {
849        return $http.get(apiRoot + 'api/CurrencyTypes/GetCurrencyTypes').then(
850          function (successResult) {
851            service.storeCurrencyTypes(successResult.data);
852          });
853      }
854
855      service.storeCurrencyTypes = function (currencyTypes) {
856        if (currencyTypes == null) {
857          console.log('Warning - Attempt to store CurrencyTypes in LocalStorage as null');
858          return;
859        }
860
861        var valueToSave = {
862          currencyTypes: currencyTypes,
863          dateTime: new Date().getTime()  //set timestamp for cache
864        };
865
866        localStorage.setItem('CurrencyTypes', JSON.stringify(valueToSave));
867      }
868
869      service.getCountries = function (force) {
870        var countries = JSON.parse(localStorage.getItem('Countries'));
871
872        if (service.countryPromise) {
873          return service.countryPromise;
874        }
875
876        if (countries != null) {
877          var diffTime = new Date().getTime() - countries.dateTime;
878          var diffInMinutes = Math.floor(diffTime / 1000 / 60); //get minutes from time
879
880          if (diffInMinutes >= 30 && !force) { //cache for 30 minutes
881            service.countryPromise = service.getCountries(true);
882          };
883
884          if (localStorage.getItem('Countries') == null || !countries.dateTime || force) { //reset currency types
885            service.countryPromise = service.getAndStoreCountries();
886          }
887        }
888        else {
889          service.countryPromise = service.getAndStoreCountries();
890        }
891
892        return service.countryPromise;
893      }
894
895      service.getAndStoreCountries = function () {
896        return $http.get(apiRoot + 'api/CountryProvinces/GetCountriesForDropdown?websiteId=' + idstc_setting_websiteid).then(
897          function (successResult) {
898            service.storeCountries(successResult.data);
899          });
900      }
901
902      service.storeCountries = function (countries) {
903        if (countries == null) {
904          console.log('Warning - Attempt to store Countries in LocalStorage as null');
905          return;
906        }
907
908        var valueToSave = {
909          countries: countries,
910          dateTime: new Date().getTime()  //set timestamp for cache
911        };
912
913        localStorage.setItem('Countries', JSON.stringify(valueToSave));
914      }
915
916      service.getDateFormat = function (force) {
917        var format = JSON.parse(localStorage.getItem('DateFormatString'));
918
919        if (service.dateFormatPromise) {
920          return service.dateFormatPromise;
921        }
922
923        if (format != null) {
924          var diffTime = new Date().getTime() - format.dateTime;
925          var diffInMinutes = Math.floor(diffTime / 1000 / 60); //get minutes from time
926
927          if (diffInMinutes >= 30 && !force) { //cache for 30 minutes
928            service.dateFormatPromise = service.getDateFormat(true);
929          };
930
931          if (localStorage.getItem('DateFormatString') === undefined || !format.dateTime || force) { //reset UTC offset
932            service.dateFormatPromise = service.getAndStoreDateFormat();
933          }
934        }
935        else {
936          service.dateFormatPromise = service.getAndStoreDateFormat();
937        }
938
939        return service.dateFormatPromise;
940      }
941
942      service.getAndStoreDateFormat = function () {
943        return $http.get(apiRoot + 'api/DateTime/GetDateFormatString').then(
944          function (successResult) {
945            service.storeDateFormat(successResult.data);
946          });
947      }
948
949      service.storeDateFormat = function (dateFormat) {
950        if (dateFormat == null) {
951          console.log('Warning - Attempt to store DateFormatString in LocalStorage as null');
952          return;
953        }
954
955        var valueToSave = {
956          dateFormat: dateFormat,
957          dateTime: new Date().getTime()  //set timestamp for cache
958        };
959
960        localStorage.setItem('DateFormatString', JSON.stringify(valueToSave));
961      }
962
963      service.getUTCOffset = function (force) {
964        var offset = JSON.parse(localStorage.getItem('UTCOffset'));
965
966        if (service.utcOffsetPromise) {
967          return service.utcOffsetPromise;
968        }
969
970        if (offset != null) { //offset is in localstorage
971          var diffTime = new Date().getTime() - offset.dateTime;
972          var diffInMinutes = Math.floor(diffTime / 1000 / 60); //get minutes from time
973
974          if (diffInMinutes >= 30 && !force) { //cache offset value for this user for 30 minutes
975            service.utcOffsetPromise = service.getUTCOffset(true);
976          };
977
978          if (localStorage.getItem('UTCOffset') == null || !offset.dateTime || force) { //reset UTC offset
979            service.utcOffsetPromise = service.getAndStoreUTCOffset();
980          }
981        } else { //offset is not in localStorage
982          service.utcOffsetPromise = service.getAndStoreUTCOffset();
983        }
984
985        return service.utcOffsetPromise;
986      }
987
988      service.getAndStoreUTCOffset = function () {
989        return $http.get(apiRoot + 'api/DateTime/GetUTCOffset').then(
990          function (successResult) {
991            service.storeUTCOffset(successResult.data);
992          });
993      }
994
995      service.storeUTCOffset = function (utcOffset) {
996        if (utcOffset == null) {
997          console.log('Warning - Attempt to store UTCOffset in LocalStorage as null');
998          return;
999        }
1000
1001        var valueToSave = {
1002          offset: utcOffset,
1003          dateTime: new Date().getTime()  //set timestamp for cache
1004        };
1005
1006        localStorage.setItem('UTCOffset', JSON.stringify(valueToSave));
1007      }
1008
1009      service.getTimeFormat = function (force) {
1010        var TimeFormat = JSON.parse(localStorage.getItem('TimeFormat'));
1011
1012        if (service.timeFormatPromise) {
1013          return service.timeFormatPromise;
1014        }
1015
1016        if (TimeFormat != null) { //permissions are in localStorage
1017          var diffTime = new Date().getTime() - TimeFormat.dateTime;
1018          var diffInMinutes = Math.floor(diffTime / 1000 / 60); //get minutes from time
1019
1020          if (diffInMinutes >= 30 && !force) { //cache permissions for this user for 30 minutes
1021            service.timeFormatPromise = service.getTimeFormat(true);
1022          };
1023
1024          if (localStorage.getItem('TimeFormat') == null || !TimeFormat.dateTime || force) { //reset UTC offset
1025            service.timeFormatPromise = service.getAndStoreTimeFormat();
1026          }
1027        }
1028        else { //currency types are not in localStorage
1029          service.timeFormatPromise = service.getAndStoreTimeFormat();
1030        }
1031
1032        return service.timeFormatPromise;
1033      }
1034
1035      service.getAndStoreTimeFormat = function () {
1036        return $http.get(apiRoot + 'api/DateTime/GetTimeFormat').then(
1037          function (successResult) {
1038            service.storeTimeFormat(successResult.data);
1039          });
1040      }
1041
1042      service.storeTimeFormat = function (timeFormat) {
1043        if (timeFormat == null) {
1044          console.log('Warning - Attempt to store TimeFormat in LocalStorage as null');
1045          return;
1046        }
1047
1048        var valueToSave = {
1049          timeFormat: timeFormat,
1050          dateTime: new Date().getTime()  //set timestamp for cache
1051        };
1052
1053        localStorage.setItem('TimeFormat', JSON.stringify(valueToSave));
1054      }
1055
1056      service.renderHTML = function (html_code) {
1057        return $sce.trustAsHtml(html_code);
1058      };
1059
1060      service.setCountryCode = function (countryCode, source) {
1061        countryCode = idstcNormalizeAcutaCountryCode(countryCode);
1062
1063        console.log('setCountryCode', countryCode, source);
1064
1065        if (countryCode == null || countryCode == '') {
1066          console.log('Warning - app.js - Attempt to set countryCode to null or empty', countryCode, source);
1067          return;
1068        }
1069
1070        localStorage.setItem('countryCode', countryCode);
1071        document.cookie = 'countryCode=' + countryCode + '; path=/';
1072      }
1073
1074      service.setLanguageCode = function (languageCode, source) {
1075        if (languageCode == null || languageCode == '') {
1076          console.log('Warning - app.js - Attempt to set languageCode to null or empty', countryCode, source);
1077        }
1078
1079        localStorage.setItem('languageCode', languageCode);
1080        document.cookie = 'languageCode=' + languageCode + '; path=/';
1081      }
1082
1083      return service;
1084    })
1085    .directive('testDirective', function () {
1086      return function (scope, elem) {
1087        $(elem).text('Directives also work');
1088      }
1089    });
1090
1091  // Load html file with content which uses above content
1092  $('body').attr('ng-controller', 'siteController as siteCtrl');
1093  $('body').addClass('non-replicated');
1094
1095  $('<div class="body slide" id="SlideBody"><div class="sidebar-wrapper" id="sidebar-wrapper"><span id="notification-wrapper"></span></div></div><div id="screen-overlay"></div><div class="loader"><div class="cp-spinner cp-round"></div><span class="sr-only">Loading...</span></div>').prependTo('body');
1096
1097  // Bootstrap app
1098  angular.bootstrap($('body'), ['app']);
1099
1100  // Register the controls/directives/services we just loaded
1101  var queue = angular.module('app')._invokeQueue;
1102  for (var i = queueLen; i < queue.length; i++) {
1103    var call = queue[i];
1104    // call is in the form [providerName, providerFunc, providerArguments]
1105    var provider = providers[call[0]];
1106    if (provider) {
1107      // e.g. $controllerProvider.register("Ctrl", function() { ... })
1108      provider[call[1]].apply(provider, call[2]);
1109    }
1110  }
1111
1112  // compile the new element
1113  $('body').injector().invoke(function ($compile, $rootScope) {
1114    // CMH:  I thought this would be needed to force the dynamic site-wide angular "app" to compile...but this does not appear to be the case (it is actually causing)
1115    //$compile($('body'))($rootScope);
1116    //$rootScope.$apply();
1117  });
1118});
1119
1120// Polyfill for "startsWith" for Internet Explorer
1121if (!String.prototype.startsWith) {
1122  String.prototype.startsWith = function (searchString, position) {
1123    position = position || 0;
1124    return this.indexOf(searchString, position) === position;
1125  };
1126}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.