-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcheckoutapi.js
More file actions
3014 lines (2601 loc) · 98.1 KB
/
checkoutapi.js
File metadata and controls
3014 lines (2601 loc) · 98.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Change log
// 2.2.0 - Updated the jQuery library to 1.11.1. It was time. 1.4.2 is ancient history, and 1.4.2 had a funky
// version of jQuery.getJSON, which storeCard() uses. So it's time to update.
// Added the storeCard method to upload the credit card number automatically to the token server.
// The example library now uses json2.js instead jquery-json.
//
// 2.1.9 Added method to remove an item at an index instead of by item id. This will
// prevent the removal of other items by the same item id. Also, the add items will
// now compare the existing items and if the items match based on item id *AND* options,
// then the quantity is incremented instead of creating a separate line item.
//
// 2.1.8 This change came direct from Capital Media. Here's their change log:
//We've modified version 2.1.7 of the API so that field IDs are no longer
//hard-coded. This meant modifying the ucPopulateFieldElements function so
//that it would accept the config variable as a parameter. This change should
//be backwards compatible, and would makes sense to incorporate in version
//2.1.8 of the API. Here are the changes:
//
//*Line 639:*
//Passing *config* as a parameter to ucPopulateFieldElements
//
//*Line 718:*
//Updated ucPopulateFieldElements to accept *config* as a parameter
//
//*Line 727:*
//Using config.cartFieldMapping, rather than a hard coded string in
//getElementById
//
//*Line 740:*
//Using config.cartFieldMapping, rather than a hard coded string in
//getElementById
//
//*Line 750:*
//Using config.cartFieldMapping, rather than a hard coded string in
//getElementById
//
//*Line 758:*
//Using config.cartFieldMapping, rather than a hard coded string in
//getElementById
//
// 2.1.7 Added header caching statement to ajax call to prevent iPad from caching getCart calls.
// 2.1.6 fixed incorrect field name on lastShippingEstimate. (Thanks Capital Media!)
// 2.1.5 replaced jQuery-json plugin with Crockford's json2.js implementation. The new implementation should be faster given the
// native use if available.
// 2.1.4 Fix for applyGiftCertificate(). It was not updating the internal cart variable with the return value
// 2.1.3 Added an override to the return parameter used in checkout(). If there are errors, we were just redirecting back
// to document.URL. But, if the page uses query parameters to add product on the initial load, we don't want that url
// to be redisplayed, adding more product.
// Example Usage: ultraCart.init({thisPageUrl: location.protocol + '//' + location.hostname + location.pathname}); // there would normally be other config parameters here...
// 2.1.2 Added a config option to disable shipping calls for those carts that are virtual only. The config option is 'disableShippingCalls'
// 2.1.1 Added a check in ucPopulateFieldElements to see if the credit card types is a select box or not. some recent
// sites are getting fancy with the card types and don't use a drop down. If that's the case, the card type logic is
// skipped over.
// 2.1.0
// Bug fixes. Most importantly, updateCart now precedes the call to estimateShipping in
// ucUpdateShippingMethodsForAddressChange()
// Also, set flag doNotNotify during the cart update after saving off the email. Before, saving off the email was
// firing a cart change which was making a useless call to estimateShipping
//
// 2.0.12
// added setAffiliateId(cart, affiliateId, subId) the API
// added the array prototypes needed to shove countries to the top of the list so US or Canada can appear at the top of an otherwise alphabetical listing.
// getParameter() and getParameterValue() are now case-insensitive
// 2.0.11
// added config section 'parameter mapping' to allow query parameters to map to cart objects. useful for affiliate tracking.
// 2.0.10
// added config.useCheapestShipping to select the first shipping method in the list (allows for hiding of shipping choices altogether
// 2.0.9
// Removed cache prevention on the installation check. wasn't needed.
// 2.0.8
// saveFieldElements: changed the checkbox behavior to avoid getting 'undefined' as a value.
// added check for correct configuration in the case of null carts.
// Add String helper method to the string object to make life easier.
if (typeof String.prototype.trim === 'undefined') {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
if (typeof String.prototype.startsWith === 'undefined') {
String.prototype.startsWith = function (str) {
return (this.indexOf(str) === 0);
};
}
if (typeof String.prototype.endsWith === 'undefined') {
String.prototype.endsWith = function (str) {
return (this.length - str.length) == this.lastIndexOf(str);
}
}
if (typeof Array.prototype.findIndex === 'undefined') {
Array.prototype.findIndex = function (value) {
var ctr = "";
for (var i = 0; i < this.length; i++) {
// use === to check for Matches. ie., identical (===), ;
if (this[i] == value) {
return i;
}
}
return ctr;
};
}
if (typeof Array.prototype.move === 'undefined') {
Array.prototype.move = function (pos1, pos2) {
// local variables
var i, tmp;
// cast input parameters to integers
pos1 = parseInt(pos1, 10);
pos2 = parseInt(pos2, 10);
// if positions are different and inside array
if (pos1 !== pos2 && 0 <= pos1 && pos1 <= this.length && 0 <= pos2 && pos2 <= this.length) {
// save element from position 1
tmp = this[pos1];
// move element down and shift other elements up
if (pos1 < pos2) {
for (i = pos1; i < pos2; i++) {
this[i] = this[i + 1];
}
}
// move element up and shift other elements down
else {
for (i = pos1; i > pos2; i--) {
this[i] = this[i - 1];
}
}
// put element from position 1 to destination
this[pos2] = tmp;
}
}
}
var ultraCart;
ultraCart = (function () {
var ULTRACART_SITE = "secure.ultracart.com";
var ULTRACART_ERROR_PARAM = 'ucError';
var SHIPPING_ADDRESS_IS_PRIORITY = 'shipping';
var BILLING_ADDRESS_IS_PRIORITY = 'billing';
var checkoutSite = ULTRACART_SITE;
var thisPageUrl = document.URL; // default.
var merchantId = "";
var version = "1.1"; //server side, not client. this might not match version number in this file's name.
var remoteApiUrl = "https://" + ULTRACART_SITE + "/cgi-bin/UCCheckoutAPIJSON";
var debugMode = false; // if you have trouble reading some of the logging, copy the json log output and visit jsbeautifier.org to pretty it up.
var verboseAjax = false;
var updateShippingOnAddressChange = false;
var screenBrandingThemeCode = null;
var shippingCountries = null;
var billingCountries = null;
var noBillingFieldsOnPage = false;
var isCheckoutPage = false;
var disableShippingCalls = false;
var addressPriority = SHIPPING_ADDRESS_IS_PRIORITY;
// Global cart variable
var cart = null;
// Shipping methods variable
var shippingMethods = null; // an array of the current shipping methods available and their price
var shippingChoice = null; // the shipping choice currently selected. this is a transient variable and not stored anywhere
var lastShippingEstimate = {
shipToAddress1: null,
shipToAddress2: null,
shipToCity: null,
shipToState: null,
shipToPostalCode: null,
shipToCountry: null
};
var cartFieldMap = {
shipToAddress1: null, shipToAddress2: null, shipToCity: null, shipToCompany: null, shipToCountry: null, shipToEveningPhone: null, shipToFirstName: null,
shipToLastName: null, shipToPhone: null, shipToPostalCode: null, shipToResidential: null, shipToState: null, shipToTitle: null, email: null,
billToAddress1: null, billToAddress2: null, billToCity: null, billToCompany: null, billToCountry: null, billToDayPhone: null, billToEveningPhone: null,
billToFirstName: null, billToLastName: null, billToPostalCode: null, billToState: null, billToTitle: null,
creditCardExpirationMonth: null,
creditCardExpirationYear: null,
creditCardNumber: null,
creditCardType: null,
creditCardVerificationNumber: null,
purchaseOrderNumber: null,
mailingListOptIn: null,
customField1: null, customField2: null, customField3: null, customField4: null, customField5: null, customField6: null, customField7: null
};
// Background timer
var updateCartTimer;
function getCart() {
return cart;
}
// Static data used by the getStateProvinces() and getStateProvinceCodes()
var ucStateProvinces = [
{
'country': 'United States',
'stateProvinces': ["Alabama", "Alaska", "American Samoa", "Arizona", "Arkansas", "Armed Forces Africa", "Armed Forces Americas", "Armed Forces Canada", "Armed Forces Europe", "Armed Forces Middle East", "Armed Forces Pacific", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia", "Federated States of Micronesia", "Florida", "Georgia", "Guam", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Marshall Islands", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Northern Mariana Islands", "Ohio", "Oklahoma", "Oregon", "Palau", "Pennsylvania", "Puerto Rico", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virgin Islands", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"],
'codes': ["AL", "AK", "AS", "AZ", "AR", "AE", "AA", "AE", "AE", "AE", "AP", "CA", "CO", "CT", "DE", "DC", "FM", "FL", "GA", "GU", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MH", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "MP", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VI", "VA", "WA", "WV", "WI", "WY"]
},
{
'country': 'Canada',
'stateProvinces': ["Alberta", "British Columbia", "Manitoba", "New Brunswick", "Newfoundland", "Northwest Territories", "Nova Scotia", "Nunavut", "Ontario", "Prince Edward Island", "Quebec", "Saskatchewan", "Yukon Territory"],
'codes': ["AB", "BC", "MB", "NB", "NF", "NT", "NS", "NU", "ON", "PE", "QC", "SK", "YT"]
}
];
/**
* This method makes the actual call to the remote server.
* @param functionName name of the remote function to execute
* @param params remote function parameters
* @param opts optional ucRemoteCall options
* OPTIONS:
* async=true/false => if true, method is executed async
* onComplete=callback => if true, this callback will be run on completion.
* (the next two are mostly used internal to make sure the cart varaible is kept up to date. I doubt whoever reads this will need to make use of them.)
* cartChange=true/false => if true, before onComplete runs, a cart will be checked for in result and internal variable set if possible
* resultIsCart => if true, the cart assignment will be cart = result instead of cart = result.cart. (inconsistent legacy API...)
*/
function ucRemoteCall(functionName, params, opts) {
var result = null;
if (debugMode && verboseAjax) {
ucLogInfo('ucRemoteCall functionName:' + functionName);
for (var p in params) {
if (params.hasOwnProperty(p)) {
ucLogDebug('ucRemoteCall param[' + p + "]=" + params[p]);
}
}
}
// jsonify all the parameters. if we don't, jquery will take our cart object and create numerous parameters for each property. not desired.
// won't need to do this with the upcoming REST API
for (var prop in params) {
if (params.hasOwnProperty(prop)) {
params[prop] = JSON.stringify(params[prop]);
}
}
// add the function name and meta data to the params for remote execution
params['functionName'] = functionName;
params['merchantId'] = merchantId;
params['version'] = version;
// Do we want async?
var async = false;
var onComplete;
var cartChange = false;
var resultIsCart = false;
if (opts != undefined && opts.async != undefined) {
if (debugMode && verboseAjax) {
ucLogDebug("ucRemoteCall: executing async");
}
async = opts.async;
}
if (opts && opts.onComplete) {
onComplete = opts.onComplete;
ucLogDebug("ucRemoteCall: onComplete method provided.");
}
cartChange = (opts && opts.cartChange);
resultIsCart = (opts && opts.resultIsCart);
jQuery.ajax(
{
url: remoteApiUrl,
async: async,
cache: false,
headers: { "cache-control": "no-cache" },
dataType: 'json',
global: true,
data: params,
type: 'POST',
success: function (jsonResult) {
// Store the result into our variable.
if (debugMode && verboseAjax) {
ucLogDebug("ucRemoteCall: success");
}
result = jsonResult;
// Call their function
if (async) {
if (cartChange && result != null) {
// there are two ways a cart can come back. need to check for the expected result and handle.
if (resultIsCart) {
ucSetCart(result, opts && opts.doNotNotify);
} else if (result.cart != null) {
ucSetCart(result.cart);
}
}
if (onComplete != undefined) {
ucLogDebug("ucRemoteCall: calling onComplete now.");
onComplete(result);
}
}
},
error: function (xhr, textStatus, errorThrown) {
if (debugMode && verboseAjax) {
var errMsg = '';
if (textStatus) {
errMsg += textStatus;
}
if (errorThrown) {
errMsg += '[errorThrown=' + errorThrown + "]";
}
ucLogError("ajax call failed:" + errMsg);
}
}
});
return result;
}
/**
* This method makes a request to the remote server and sends to arguments, expecting a ping message back.
* @return true if connection was made, false if otherwise.
*/
function pingRemoteServer() {
var result = false;
if (debugMode && verboseAjax) {
ucLogInfo('Begin Connection Test');
}
var async = false;
jQuery.ajax(
{
url: remoteApiUrl,
async: async,
// cache: false,
dataType: 'json',
global: true,
type: 'GET',
success: function (jsonResult) {
// Store the result into our variable.
if (debugMode && verboseAjax) {
ucLogDebug("ucRemoteCall: success");
}
if (jsonResult) {
result = (jsonResult && jsonResult.result);
if (debugMode) {
ucLogInfo("The Remote Server Connection Test returned the following:");
ucLogInfo(jsonResult.welcomeMessage);
ucLogInfo(jsonResult.helpMessage);
ucLogInfo(jsonResult.additionalInformation);
}
}
},
error: function (xhr, textStatus, errorThrown) {
if (debugMode && verboseAjax) {
var errMsg = '';
if (textStatus) {
errMsg += textStatus;
}
if (errorThrown) {
errMsg += '[errorThrown=' + errorThrown + "]";
}
ucLogError("ajax call failed:" + errMsg);
}
result = false;
}
});
if (debugMode && verboseAjax) {
ucLogInfo('End Connection Test');
}
return result;
}
/**
* retrieves a shopping cart object from the remote server
* @param opts optional ucRemoteCall options(async=true/false,onComplete=callback)
* @return cart object
*/
function ucCreateCart(opts) {
return ucRemoteCall('createCart', {}, opts);
}
/**
* retrieves a shopping cart object from the remote server using a cartId from cookie
* @param cartId string, cart id for current customer
* @param opts optional ucRemoteCall options(async=true/false,onComplete=callback)
* @return cart object
*/
function ucGetCart(cartId, opts) {
return ucRemoteCall('getCart', { 'parameter1': cartId}, opts);
}
/**
* updates the local cart instance with a server version. many api calls affect the cart and
* the updated cart is the return value. Those api calls will call ucSetCart() to synchronize the
* local cart object with the server.
* @param updatedCart
*/
function ucSetCart(updatedCart, doNotNotify) {
// Let's make sure we have a valid cart object.
if (updatedCart == null || updatedCart.cartId == null) {
return;
}
cart = updatedCart;
if (!doNotNotify) {
cartTarget.fire(EVENT_CART_CHANGE);
}
}
/**
* some credit card information can lose type during the json process. This method fixes that.
*/
function ucSanitizeDataTypes() {
try {
// Make sure the integer fields are actually set as a number of serialization purposes
if (cart && cart.creditCardExpirationMonth !== 'undefined' && typeof cart.creditCardExpirationMonth === 'string') {
cart.creditCardExpirationMonth = isNaN(cart.creditCardExpirationMonth) ? 0 : parseInt(cart.creditCardExpirationMonth);
}
if (cart && cart.creditCardExpirationYear !== 'undefined' && typeof cart.creditCardExpirationYear === 'string') {
cart.creditCardExpirationYear = isNaN(cart.creditCardExpirationYear) ? 0 : parseInt(cart.creditCardExpirationYear);
}
} catch (e) {
}
}
/**
* pushes changes from the local cart up to the server.
* @param opts optional ucRemoteCall options(async=true/false,onComplete=callback)
*/
function updateCart(opts) {
ucLogDebug("updateCart()");
backgroundTimer(false);
ucSanitizeDataTypes();
if (opts && opts.async) {
opts.cartChange = true;
opts.resultIsCart = true;
}
// if async, be sure to set the cart.
var result = ucRemoteCall('updateCart', { 'parameter1': cart}, opts);
if (result != null) {
ucSetCart(result, opts && opts.doNotNotify);
}
return cart;
}
/**
* used to save any user input changes to the server. This method uses the local cart to
* update the server, but does not touch the local cart to avoid stomping on anything since
* this method is called via a timer.
* @param opts optional ucRemoteCall options(async=true/false,onComplete=callback)
*/
function ucBackgroundUpdateCart(opts) {
ucSanitizeDataTypes();
ucRemoteCall('backgroundUpdateCart', { 'parameter1': cart}, opts);
}
/**
* turns the background update on and off
* @param status true starts the timer, false turns it off.
*/
function backgroundTimer(status) {
ucLogDebug("backgroundTime(" + status + ")");
if (status) {
window.clearTimeout(updateCartTimer);
try {
updateCartTimer = window.setTimeout("ucBackgroundUpdateCart({'async': true})", 2500);
} catch (e) {
}
} else {
try {
window.clearTimeout(updateCartTimer);
} catch (e) {
}
}
}
/**
* this method should be called first, every time. It sets up the cart configuration and creates a local
* copy of the cart.
* @param config (debugMode, verboseAjax, checkoutSite, remoteApiUrl )
*/
function init(config) {
if (config.debugMode) {
debugMode = true;
ucInitConsole();
ucLogInfo("init: debugMode->" + config.debugMode);
}
if (config.verboseAjax) {
verboseAjax = true;
ucLogInfo("init: verboseAjax->" + config.verboseAjax);
}
if (config.merchantId) {
merchantId = config.merchantId;
} else {
ucLogError("Fatal Condition: config.merchantId is a required config value to init is was not found. Nothing further will work.");
}
if (config.screenBrandingThemeCode) {
screenBrandingThemeCode = config.screenBrandingThemeCode;
} else {
ucLogInfo("No screen branding theme provided. This is only a warning.");
}
if (config.checkoutSite) {
checkoutSite = config.checkoutSite;
ucLogInfo("init: checkoutSite->" + config.checkoutSite);
} else {
ucLogInfo("init: checkoutSite-> using default value [" + checkoutSite + "]");
}
if (config.remoteApiUrl) {
remoteApiUrl = config.remoteApiUrl;
} else {
remoteApiUrl = "https://" + ULTRACART_SITE + "/cgi-bin/UCCheckoutAPIJSON";
}
ucLogInfo("init: remoteApiUrl->" + remoteApiUrl);
if (config.thisPageUrl) {
thisPageUrl = config.thisPageUrl;
ucLogInfo("overriding this page's url from " + document.URL + " => " + thisPageUrl);
}
var successfulConnection = true;
var testRemoteConnection = !config.doNotTestRemoteConnection; // double negative so if config is absent, it's tested.
if (testRemoteConnection) {
var pingResult = pingRemoteServer();
if (!pingResult) {
successfulConnection = false;
ucLogError("COULD NOT CONNECT TO REMOTE SERVER! PLEASE VERIFY merchantCartConfig.remoteApiUrl is configured correctly.");
ucLogError("You should expect to see additional errors below.");
}
}
if (config.numberFormatConfig) {
numberFormat.init(config.numberFormatConfig);
}
cartTarget.clear(); // needed in case of re-initialization
// window dressing for a checkout page. ignore if this is a lightweight page like an item display page.
if (config.isCheckoutPage) {
isCheckoutPage = true;
}
if (config.disableShippingCalls) {
disableShippingCalls = true;
}
if (isCheckoutPage) {
if (config.updateShippingOnAddressChange) {
updateShippingOnAddressChange = true;
}
if (config.noBillingFieldsOnPage) {
noBillingFieldsOnPage = true;
}
if (config.addressPriority) {
if (config.addressPriority != SHIPPING_ADDRESS_IS_PRIORITY && config.addressPriority != BILLING_ADDRESS_IS_PRIORITY) {
ucLogError('invalid addressPriority (' + config.addressPriority + '), only "shipping" and "billing" are valid values.');
} else {
addressPriority = config.addressPriority;
}
}
if (config.listeners) {
for (var evt in config.listeners) {
if (config.listeners.hasOwnProperty(evt)) {
if (evt == EVENT_CART_CHANGE || evt == EVENT_SHIPPING_CHANGE || evt == EVENT_ADDRESS_CHANGE || evt == EVENT_SHIPPING_METHODS_CHANGE || evt == EVENT_CART_READY || evt == EVENT_PROFILE_CHANGE) {
var funcs = config.listeners[evt];
for (var i = 0; i < funcs.length; i++) {
cartTarget.addListener(evt, funcs[i]);
}
} else {
ucLogError('unknown ultracart event: ' + evt);
}
}
}
}
// this is for re-initialization. clean up no matter what so a cart can go from having events to not cleanly.
for (var f in cartFieldMap) {
if (cartFieldMap.hasOwnProperty(f)) {
if (cartFieldMap[f] != null) {
ucLogDebug("unbinding all events for " + f);
jQuery(cartFieldMap[f]).unbind('.ultraCart');
cartFieldMap[f] = null;
}
}
}
if (config.cartFieldMapping) {
for (var fld in config.cartFieldMapping) {
if (config.cartFieldMapping.hasOwnProperty(fld)) {
if (!config.cartFieldMapping[fld]) {
continue;
/* ignore null values and such */
}
var el = document.getElementById(config.cartFieldMapping[fld]);
if (el == null) {
ucLogError('config.cartFieldMapping[' + fld + '] is pointing to element.id=' + config.cartFieldMapping[fld] + ', but there is no html element with that id. cannot map cart field.');
continue;
}
cartFieldMap[fld] = el; // need this later for the field>cart procedure.
// bind cart handles element->cart mappings
// bind shipping creates triggers to update shipping when specific values change
ucBindCartField(fld, el);
if (lastShippingEstimate.hasOwnProperty(fld)) {
ucBindShippingField(fld, el);
}
} else {
ucLogError('unknown ultracart field mapping (' + fld + ')');
}
}
}
if (updateShippingOnAddressChange && !disableShippingCalls) {
cartTarget.addListener(EVENT_ADDRESS_CHANGE, ucUpdateShippingMethodsForAddressChange, true);
}
ucInitCartInstance();
if (config.shippingCountries) {
shippingCountries = config.shippingCountries;
} else {
shippingCountries = getAllowedCountries();
}
if (config.billingCountries) {
billingCountries = config.billingCountries
} else {
billingCountries = shippingCountries;
}
if (cart.shippingMethod) {
shippingChoice = cart.shippingMethod;
}
if (screenBrandingThemeCode && cart && screenBrandingThemeCode != cart.screenBrandingThemeCode) {
cart.screenBrandingThemeCode = screenBrandingThemeCode; // if this isn't set already, then shipping isn't set either. it'll get updated together.
}
ucPopulateFieldElements(config);
if (config.cartParameterMapping) {
for (fld in config.cartParameterMapping) {
if (config.cartParameterMapping.hasOwnProperty(fld)) {
ucLogDebug('cart parameter mapping request (' + fld + "=>" + config.cartParameterMapping[fld] + ")");
if (cartFieldMap.hasOwnProperty(fld)) {
if (!config.cartParameterMapping[fld]) {
continue;
/* ignore null values and such */
}
var val = getParameterValue(config.cartParameterMapping[fld]);
if (val) {
ucLogDebug('setting cart field ' + fld + " to parameter " + config.cartParameterMapping[fld] + ", value was " + val);
cart[fld] = val;
} else {
ucLogDebug('no value found in parameters for ' + fld + "=>" + config.cartParameterMapping[fld] + " parameter mapping");
}
} else {
ucLogError('unknown ultracart field mapping (' + fld + ')');
}
}
}
}
if (!disableShippingCalls) {
ucUpdateShippingMethodsAsync({async: true, onComplete: function () {
if (shippingChoice && shippingChoice != cart.shippingMethod) {
cart.shippingMethod = shippingChoice;
updateCart({async: true});
} else if (config.useCheapestShipping) {
if (shippingMethods && shippingMethods.length > 0) {
shippingChoice = shippingMethods[0].name;
cart.shippingMethod = shippingChoice;
updateCart({async: true});
}
}
cartTarget.fire(EVENT_SHIPPING_CHANGE); // fire regardless to update the summary with the proper shipping amount initially.
cartTarget.addListener(EVENT_CART_CHANGE, ucUpdateShippingMethodsAsync, true); // register only now to avoid forever-loop.
}});
}
} else { // just initialize the cart.
ucInitCartInstance();
} //end-if isCheckoutPage==true/false
// lastly (to avoid lagging anything)
if (config.unifiedAffiliateTracking) {
ucLogDebug("tracking affiliates");
ucTrackAffiliates();
}
ucLogDebug("init finished. (async calls may still finish)");
cartTarget.fire(EVENT_CART_READY);
if (!successfulConnection) {
ucLogError("There was a problem communicating with the UltraCart remote server. This is almost *always* a configuration error. Please scroll up and see additional messages.");
}
}
function addOptionToSelect(select, text, value) {
// good grief. I hate MSIE.
var opt = document.createElement("option");
var opt_txt = document.createTextNode(text);
opt.appendChild(opt_txt);
opt.setAttribute("value", value);
select.appendChild(opt);
}
function deleteOptions(select) {
while (select.childNodes.length > 0) {
select.removeChild(select.childNodes[0]);
}
}
function ucPopulateFieldElements(config) {
if (cart == null || !config || !config.cartFieldMapping) {
return;
}
// populate the credit card types select box.
if (cart != null) {
var cardTypes = cart.creditCardTypes;
var ccType = document.getElementById(config.cartFieldMapping['creditCardType']);
if (ccType && cardTypes && ccType.tagName.toLowerCase() == 'select') {
deleteOptions(ccType);
addOptionToSelect(ccType, "Select Type", "");
for (var j = 0; j < cardTypes.length; j++) {
addOptionToSelect(ccType, cardTypes[j], cardTypes[j]);
}
}
}
// populate the credit card expiration year select box. 25 years.
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var ccExpYear = document.getElementById(config.cartFieldMapping['creditCardExpirationYear']);
if (ccExpYear && ccExpYear.tagName.toLowerCase() == 'select') {
deleteOptions(ccExpYear);
addOptionToSelect(ccExpYear, "Year", "");
for (var i = 0; i < 25; i++) {
addOptionToSelect(ccExpYear, (currentYear + i), (currentYear + i));
}
}
// hard code countries to just US for this cart.
var scSelect = document.getElementById(config.cartFieldMapping['shipToCountry']);
if (scSelect && scSelect.tagName.toLowerCase() == 'select') {
deleteOptions(scSelect);
for (var b = 0; b < shippingCountries.length; b++) {
addOptionToSelect(scSelect, shippingCountries[b], shippingCountries[b]);
}
}
var bcSelect = document.getElementById(config.cartFieldMapping['billToCountry']);
if (bcSelect && bcSelect.tagName.toLowerCase() == 'select') {
deleteOptions(bcSelect);
for (var c = 0; c < billingCountries.length; c++) {
addOptionToSelect(bcSelect, billingCountries[c], billingCountries[c]);
}
}
ucLogDebug("populating field elements with cart values");
for (var fieldName in cartFieldMap) {
if (cartFieldMap.hasOwnProperty(fieldName)) {
if (!cart.hasOwnProperty(fieldName)) {
continue;
/* should never happen, but safety check */
}
var el = cartFieldMap[fieldName];
if (!el) {
ucLogDebug("[cart>elements]: no mapping for " + fieldName);
continue;
}
if (!cart[fieldName]) {
ucLogDebug("[cart>elements]: cart has no value for " + fieldName);
continue;
}
var fld = jQuery(el);
if (!fld) {
ucLogDebug("[cart>elements]: jQuery could not wrap element for field " + fieldName);
continue;
}
ucLogDebug("[cart>elements]: " + fieldName + "=>" + cart[fieldName]);
if (fld.is('input:checkbox')) {
fld.attr("checked", cart[fieldName] || false);
} else if (fld.is('input')) {
fld.val(cart[fieldName]);
} else if (fld.is('select')) {
// try to set value first, then text.
fld.val(cart[fieldName]);
// if nothing was set, try the text value.
if (!fld.val()) {
jQuery('option', fld).each(function () {
this.selected = (this.text == cart[fieldName]);
});
}
}
}
}
}
/**
* uses the map to transfer all the field values to the cart, calls updateCart async,
* and then runs the callback handler, if provided. This will allow the merchant to
* chain the async update with another function - probably a handoff call.
* @param callback
*/
function saveFieldElements(callback) {
if (cart == null) {
return;
}
ucLogDebug("populating cart values with field elements");
for (var fieldName in cartFieldMap) {
if (cartFieldMap.hasOwnProperty(fieldName)) {
if (!cart.hasOwnProperty(fieldName)) {
continue;
/* should never happen, but safety check */
}
var el = cartFieldMap[fieldName];
if (!el) {
ucLogDebug("[cart>elements]: no mapping for " + fieldName);
continue;
}
var fld = jQuery(el);
if (!fld) {
ucLogDebug("[cart>elements]: jQuery could not wrap the field element for " + fieldName);
continue;
}
if (fld.is('input:checkbox')) {
cart[fieldName] = fld.attr('checked') ? true : false;
} else if (fld.is('input')) {
cart[fieldName] = fld.val() || '';
} else if (fld.is('select')) {
cart[fieldName] = fld.val() || '';
}
}
}
// copy shipping to billing where missing
if (addressPriority == SHIPPING_ADDRESS_IS_PRIORITY) {
if (!cart.billToAddress1 || noBillingFieldsOnPage) {
cart.billToAddress1 = cart.shipToAddress1;
}
if (!cart.billToAddress2 || noBillingFieldsOnPage) {
cart.billToAddress2 = cart.shipToAddress2;
}
if (!cart.billToCity || noBillingFieldsOnPage) {
cart.billToCity = cart.shipToCity;
}
if (!cart.billToState || noBillingFieldsOnPage) {
cart.billToState = cart.shipToState;
}
if (!cart.billToCountry || noBillingFieldsOnPage) {
cart.billToCountry = cart.shipToCountry;
}
if (!cart.billToPostalCode || noBillingFieldsOnPage) {
cart.billToPostalCode = cart.shipToPostalCode;
}
if (!cart.billToFirstName || noBillingFieldsOnPage) {
cart.billToFirstName = cart.shipToFirstName;
}
if (!cart.billToLastName || noBillingFieldsOnPage) {
cart.billToLastName = cart.shipToLastName;
}
if (!cart.billToPhone || noBillingFieldsOnPage) {
cart.billToDayPhone = cart.shipToPhone;
}
if (!cart.billToCompany || noBillingFieldsOnPage) {
cart.billToCompany = cart.shipToCompany;
}
} else {
if (!cart.shipToAddress1) {
cart.shipToAddress1 = cart.billToAddress1;
}
if (!cart.shipToAddress2) {
cart.shipToAddress2 = cart.billToAddress2;
}
if (!cart.shipToCity) {
cart.shipToCity = cart.billToCity;
}
if (!cart.shipToState) {
cart.shipToState = cart.billToState;
}
if (!cart.shipToCountry) {
cart.shipToCountry = cart.billToCountry;
}
if (!cart.shipToPostalCode) {
cart.shipToPostalCode = cart.billToPostalCode;
}
if (!cart.shipToFirstName) {
cart.shipToFirstName = cart.billToFirstName;
}
if (!cart.shipToLastName) {
cart.shipToLastName = cart.billToLastName;
}
if (!cart.shipToPhone) {
cart.shipToPhone = cart.billToDayPhone;
}
if (!cart.shipToCompany) {
cart.shipToCompany = cart.billToCompany;
}
}
updateCart({async: true, onComplete: callback});
}
/**
* searches a catalog for items based on 'search' criteria
* @param catalogHost see https://secure.ultracart.com/merchant/catalog/chooseHostLoad.do
* @param search search string
* @param itemsPerPage limits the number of items returned, used for chunking result sets
* @param currentPage page offset (currentPage * itemsPerPage = starting item returned, etc...)
* @param opts optional ucRemoteCall options(async=true/false,onComplete=callback)
* @returns a json object, an object with the following properties: currentPage:int, totalPages:int, totalResults:int, items:array of item objects
*/
function search(catalogHost, search, itemsPerPage, currentPage, opts) {
return ucRemoteCall('search', { 'parameter1': catalogHost, 'parameter2': search, 'parameter3': itemsPerPage, 'parameter4': currentPage}, opts);
}
/**
* It's best to call addItems synchronously since the shipping is reset when items are added.
* @param items
* @param opts
*/
function addItems(items, opts) {
// try to consolidate with existing items (then update) first. If that doesn't
// work, then do an update.
if (cart != null && cart.items && cart.items.length > 0 && items && items.length) {
// create a copy of the items array so that if we reach a failure at any point we haven't corrupted the actual cart items.
var itemsCopy = [];
for (var k = 0; k < cart.items.length; k++) {
itemsCopy.push(jQuery.extend(true, {}, cart.items[k]));
}
// loop through each item in the items parameter and see if a match can be found for both item id and all options.
var doUpdate = true;
for (var m = 0; m < items.length; m++) {
var foundMatch = false;
for (var n = 0; n < itemsCopy.length; n++) {
if (itemIdAndOptionsMatch(items[m], itemsCopy[n])) {
foundMatch = true;
itemsCopy[n].quantity = parseInt(itemsCopy[n].quantity) + parseInt(items[m].quantity);