forked from jeffharrell/minicart
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminicart.js
More file actions
1677 lines (1348 loc) · 45.3 KB
/
Copy pathminicart.js
File metadata and controls
1677 lines (1348 loc) · 45.3 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
/*!
* The PayPal Mini Cart
* Visit http://www.minicartjs.com/ for details
* Use subject to license agreement as set forth at the link below
*
* @author Jeff Harrell
* @license https://github.com/jeffharrell/MiniCart/blob/master/LICENSE eBay Open Source License Agreement
*/
if (typeof PAYPAL == 'undefined' || !PAYPAL) {
var PAYPAL = {};
}
PAYPAL.apps = PAYPAL.apps || {};
(function () {
/**
* Default configuration
*/
var config = {
/**
* The parent element the cart should "pin" to
*/
parent: document.body,
/**
* Edge of the window to pin the cart to
*/
displayEdge: 'right',
/**
* Distance from the edge of the window
*/
edgeDistance: '50px',
/**
* HTML target property for the checkout form
*/
formTarget: null,
/**
* The base path of your website to set the cookie to
*/
cookiePath: '/',
/**
* Strings used for display text
*/
strings: {
button: '',
subtotal: '',
discount: '',
shipping: '',
processing: ''
},
/**
* Unique ID used on the wrapper element
*/
name: 'PPMiniCart',
/**
* Boolean to determine if the cart should "peek" when it's hidden with items
*/
peekEnabled: true,
/**
* The URL of the PayPal website
*/
paypalURL: 'https://www.paypal.com/cgi-bin/webscr',
/**
* The base URL to the visual assets
*/
assetURL: 'http://www.minicartjs.com/build/',
events: {
/**
* Custom event fired before the cart is rendered
*/
onRender: null,
/**
* Custom event fired after the cart is rendered
*/
afterRender: null,
/**
* Custom event fired before the cart is hidden
*
* @param e {event} The triggering event
*/
onHide: null,
/**
* Custom event fired after the cart is hidden
*
* @param e {event} The triggering event
*/
afterHide: null,
/**
* Custom event fired before the cart is shown
*
* @param e {event} The triggering event
*/
onShow: null,
/**
* Custom event fired after the cart is shown
*
* @param e {event} The triggering event
*/
afterShow: null,
/**
* Custom event fired before a product is added to the cart
*
* @param data {object} Product object
*/
onAddToCart: null,
/**
* Custom event fired after a product is added to the cart
*
* @param data {object} Product object
*/
afterAddToCart: null,
/**
* Custom event fired before a product is removed from the cart
*
* @param data {object} Product object
*/
onRemoveFromCart: null,
/**
* Custom event fired after a product is removed from the cart
*
* @param data {object} Product object
*/
afterRemoveFromCart: null,
/**
* Custom event fired before the checkout action takes place
*
* @param e {event} The triggering event
*/
onCheckout: null,
/**
* Custom event fired before the cart is reset
*/
onReset: null,
/**
* Custom event fired after the cart is reset
*/
afterReset: null
}
};
/**
* Mini Cart application
*/
PAYPAL.apps.MiniCart = (function () {
var minicart = {},
isShowing = false,
isRendered = false;
/** PRIVATE **/
/**
* PayPal form cmd values which are supported
*/
var SUPPORTED_CMDS = { _cart: true, _xclick: true };
/**
* The form origin that is passed to PayPal
*/
var BN_VALUE = 'MiniCart_AddToCart_WPS_US';
/**
* Regex filter for cart settings, which appear only once in a cart
*/
var SETTING_FILTER = /^(?:business|currency_code|lc|paymentaction|no_shipping|cn|no_note|invoice|handling_cart|weight_cart|weight_unit|tax_cart|page_style|image_url|cpp_|cs|cbt|return|cancel_return|notify_url|rm|custom|charset)/;
/**
* Adds the cart's CSS to the page in a <style> element.
* The CSS lives in this file so that it can leverage properties from the config
* and doesn't require an additional down. To override the CSS see the FAQ.
*/
var _addCSS = function () {
var name = config.name,
css = [],
style, head;
css.push('#' + name + ' form { position:fixed; float:none; top:-250px; ' + config.displayEdge + ':' + config.edgeDistance + '; width:265px; margin:0; padding:50px 10px 0; min-height:170px; background:#fff url(' + config.assetURL + 'images/minicart_sprite.png) no-repeat -125px -60px; border:1px solid #999; border-top:0; font:13px/normal arial, helvetica; color:#333; text-align:left; -moz-border-radius:0 0 8px 8px; -webkit-border-radius:0 0 8px 8px; border-radius:0 0 8px 8px; -moz-box-shadow:1px 1px 1px rgba(0, 0, 0, 0.1); -webkit-box-shadow:1px 1px 1px rgba(0, 0, 0, 0.1); box-shadow:1px 1px 1px rgba(0, 0, 0, 0.1); } ');
css.push('#' + name + ' ul { position:relative; overflow-x:hidden; overflow-y:auto; height:130px; margin:0 0 7px; padding:0; list-style-type:none; border-top:1px solid #ccc; border-bottom:1px solid #ccc; } ');
css.push('#' + name + ' li { position:relative; margin:-1px 0 0; padding:6px 5px 6px 0; border-top:1px solid #f2f2f2; } ');
css.push('#' + name + ' li a { display: block; width: 155px; color:#333; text-decoration:none; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } ');
css.push('#' + name + ' li a span { color:#999; font-size:10px; } ');
css.push('#' + name + ' li .quantity { position:absolute; top:.5em; right:78px; width:22px; padding:1px; border:1px solid #83a8cc; text-align:right; } ');
css.push('#' + name + ' li .price { position:absolute; top:.5em; right:4px; } ');
css.push('#' + name + ' li .remove { position:absolute; top:9px; right:60px; width:14px; height:14px; background:url(' + config.assetURL + 'images/minicart_sprite.png) no-repeat -134px -4px; border:0; cursor:pointer; } ');
css.push('#' + name + ' p { margin:0; padding:0 0 0 20px; background:url(' + config.assetURL + 'images/minicart_sprite.png) no-repeat; font-size:13px; font-weight:bold; } ');
css.push('#' + name + ' p:hover { cursor:pointer; } ');
css.push('#' + name + ' p input { float:right; margin:4px 0 0; padding:1px 4px; text-decoration:none; font-weight:normal; color:#333; background:#ffa822 url(' + config.assetURL + 'images/minicart_sprite.png) repeat-x left center; border:1px solid #d5bd98; border-right-color:#935e0d; border-bottom-color:#935e0d; -moz-border-radius:2px; -webkit-border-radius:2px; border-radius:2px; } ');
css.push('#' + name + ' p .shipping { display:block; font-size:10px; font-weight:normal; color:#999; } ');
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css.join('');
} else {
style.appendChild(document.createTextNode(css.join('')));
}
head = document.getElementsByTagName('head')[0];
head.appendChild(style);
};
/**
* Builds the DOM elements required by the cart
*/
var _buildDOM = function () {
var UI = minicart.UI,
cmd, type, bn, parent, version;
UI.wrapper = document.createElement('div');
UI.wrapper.id = config.name;
cmd = document.createElement('input');
cmd.type = 'hidden';
cmd.name = 'cmd';
cmd.value = '_cart';
type = cmd.cloneNode(false);
type.name = 'upload';
type.value = '1';
bn = cmd.cloneNode(false);
bn.name = 'bn';
bn.value = BN_VALUE;
UI.cart = document.createElement('form');
UI.cart.method = 'post';
UI.cart.action = config.paypalURL;
if (config.formTarget) {
UI.cart.target = config.formTarget;
}
UI.cart.appendChild(cmd);
UI.cart.appendChild(type);
UI.cart.appendChild(bn);
UI.wrapper.appendChild(UI.cart);
UI.itemList = document.createElement('ul');
UI.cart.appendChild(UI.itemList);
UI.summary = document.createElement('p');
UI.cart.appendChild(UI.summary);
UI.button = document.createElement('input');
UI.button.type = 'submit';
UI.button.value = config.strings.button || 'Checkout';
UI.summary.appendChild(UI.button);
UI.subtotal = document.createElement('span');
UI.subtotal.innerHTML = config.strings.subtotal || 'Subtotal: ';
UI.subtotalAmount = document.createElement('span');
UI.subtotalAmount.innerHTML = '0.00';
UI.subtotal.appendChild(UI.subtotalAmount);
UI.summary.appendChild(UI.subtotal);
UI.shipping = document.createElement('span');
UI.shipping.className = 'shipping';
UI.shipping.innerHTML = config.strings.shipping || 'does not include shipping & tax';
UI.summary.appendChild(UI.shipping);
// Workaround: IE 6 and IE 7/8 in quirks mode do not support position:fixed in CSS
if (window.attachEvent && !window.opera) {
version = navigator.userAgent.match(/MSIE\s([^;]*)/);
if (version) {
version = parseFloat(version[1]);
if (version < 7 || (version >= 7 && document.compatMode === 'BackCompat')) {
UI.cart.style.position = 'absolute';
UI.wrapper.style[config.displayEdge] = '0';
UI.wrapper.style.setExpression('top', 'x = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop');
}
}
}
parent = (typeof config.parent === 'string') ? document.getElementById(config.parent) : config.parent;
parent.appendChild(UI.wrapper);
};
/**
* Attaches the cart events to it's DOM elements
*/
var _bindEvents =function () {
var ui = minicart.UI,
forms, form, i;
// Look for all "Cart" and "Buy Now" forms on the page and attach events
forms = document.getElementsByTagName('form');
for (i = 0; i < forms.length; i++) {
form = forms[i];
if (form.cmd && SUPPORTED_CMDS[form.cmd.value]) {
minicart.bindForm(form);
}
}
// Hide the Mini Cart for all non-cart related clicks
$.event.add(document, 'click', function (e) {
if (isShowing) {
var target = e.target,
cartEl = ui.cart;
if (!(/input|button|select|option/i.test(target.tagName))) {
while (target.nodeType === 1) {
if (target === cartEl) {
return;
}
target = target.parentNode;
}
minicart.hide(null);
}
}
});
// Run the checkout code when submitting the form
$.event.add(ui.cart, 'submit', function (e) {
_checkout(e);
});
// Show the cart when clicking on the summary
$.event.add(ui.summary, 'click', function (e) {
var target = e.target;
if (target !== ui.button) {
minicart.toggle(e);
}
});
// Update other windows when HTML5 localStorage is updated
if (window.attachEvent && !window.opera) {
$.event.add(document, 'storage', function (e) {
// IE needs a delay in order to properly see the change
setTimeout(_redrawCartItems, 100);
});
} else {
$.event.add(window, 'storage', function (e) {
// Safari, Chrome, and Opera can filter on updated storage key
// Firefox can't so it uses a brute force approach
if ((e.key && e.key == config.name) || !e.key) {
_redrawCartItems();
}
});
}
};
/**
* Parses the userConfig (if applicable) and overwrites the default values
*/
var _parseUserConfig = function (userConfig) {
var key;
// TODO: This should recursively merge the config values
for (key in userConfig) {
if (typeof config[key] !== undefined) {
config[key] = userConfig[key];
}
}
};
/**
* Loads the stored data and builds the cart
*/
var _parseStorage = function () {
var data, length, i;
if ((data = $.storage.load())) {
length = data.length;
for (i = 0; i < length; i++) {
if (_renderProduct(data[i])) {
isShowing = true;
}
}
}
};
/**
* Data parser used for forms
*
* @param form {HTMLElement} An HTML form
* @return {object}
*/
var _parseForm = function (form) {
var raw = form.elements,
data = {},
pair, value, length, i, len;
for (i = 0, len = raw.length; i < len; i++) {
pair = raw[i];
if ((value = $.util.getInputValue(pair))) {
data[pair.name] = value;
}
}
return data;
};
/**
* Massage's a object's data in preparation for adding it to the user's cart
*
* @param data {object} An object of WPS xclick style data to add to the cart. The format is { product: '', settings: '' }.
* @return {object}
*/
var _parseData = function (data) {
var product = {},
settings = {},
existing, option_index, key, len, match, i, j;
// Parse the data into a two categories: product and settings
for (key in data) {
if (SETTING_FILTER.test(key)) {
settings[key] = data[key];
} else {
product[key] = data[key];
}
}
// Check the products to see if this variation already exists
// If it does then reuse the same object
for (i = 0, len = minicart.products.length; i < len; i++) {
existing = minicart.products[i].product;
// Do the product name and number match
if (product.item_name === existing.item_name && product.item_number === existing.item_number) {
// Products are a match so far; Now do all of the products options match?
match = true;
j = 0;
while (existing['os' + j]) {
if (product['os' + j] !== existing['os' + j]) {
match = false;
break;
}
j++;
}
if (match) {
product.offset = existing.offset;
break;
}
}
}
// Normalize the values
product.href = product.href || window.location.href;
product.quantity = product.quantity || 1;
product.amount = product.amount || 0;
// Add Mini Cart specific settings
if (settings['return'] && settings['return'].indexOf('#') == -1) {
settings['return'] += '#' + config.name + '=reset';
}
// Add option amounts to the total amount
option_index = (product.option_index) ? product.option_index : 0;
while (product['os' + option_index]) {
i = 0;
while (typeof product['option_select' + i] != 'undefined') {
if (product['option_select' + i] == product['os' + option_index]) {
product.amount = product.amount + parseFloat(product['option_amount' + i]);
break;
}
i++;
}
option_index++;
}
return {
product: product,
settings: settings
};
};
/**
* Resets the card and renders the products
*/
var _redrawCartItems = function () {
minicart.products = [];
minicart.UI.itemList.innerHTML = '';
minicart.UI.subtotalAmount.innerHTML = '';
_parseStorage();
minicart.updateSubtotal();
};
/**
* Renders the product in the cart
*
* @param data {object} The data for the product
*/
var _renderProduct = function (data) {
var ui = minicart.UI,
cartEl = ui.cart,
product = new ProductNode(data, minicart.UI.itemList.children.length + 1),
offset = data.product.offset,
keyupTimer, hiddenInput, key;
minicart.products[offset] = product;
// Add hidden settings data to parent form
for (key in data.settings) {
if (cartEl.elements[key]) {
if (cartEl.elements[key].value) {
cartEl.elements[key].value = data.settings[key];
} else {
cartEl.elements[key] = data.settings[key];
}
} else {
hiddenInput = document.createElement('input');
hiddenInput.type = 'hidden';
hiddenInput.name = key;
hiddenInput.value = data.settings[key];
cartEl.appendChild(hiddenInput);
}
}
// if the product has no name or number then don't add it
if (product.isPlaceholder) {
return false;
// otherwise, setup the new element
} else {
// Click event for "x"
$.event.add(product.removeInput, 'click', function () {
_removeProduct(product, offset);
});
// Event for changing quantities
var currentValue = product.quantityInput.value;
$.event.add(product.quantityInput, 'keyup', function () {
var that = this;
keyupTimer = setTimeout(function () {
var value = parseInt(that.value, 10);
if (!isNaN(value) && value != currentValue) {
currentValue = value;
product.setQuantity(value);
// Delete the product
if (!product.getQuantity()) {
_removeProduct(product, offset);
}
minicart.updateSubtotal();
$.storage.save(minicart.products);
}
}, 250);
});
// Add the item and fade it in
ui.itemList.insertBefore(product.liNode, ui.itemList.firstChild);
$.util.animate(product.liNode, 'opacity', { from: 0, to: 1 });
return true;
}
};
/**
* Removes a product from the cart
*
* @param product {ProductNode} The product object
* @param offset {Number} The offset for the product in the cart
*/
var _removeProduct = function (product, offset) {
var events = config.events,
onRemoveFromCart = events.onRemoveFromCart,
afterRemoveFromCart = events.afterRemoveFromCart;
if (typeof onRemoveFromCart == 'function') {
if (onRemoveFromCart.call(minicart, product) === false) {
return;
}
}
product.setQuantity(0);
product.quantityInput.style.display = 'none';
$.util.animate(product.liNode, 'opacity', { from: 1, to: 0 }, function () {
$.util.animate(product.liNode, 'height', { from: 18, to: 0 }, function () {
try {
product.liNode.parentNode.removeChild(product.liNode);
} catch (e) {
// fail
}
// regenerate the form element indexes
var products = minicart.UI.cart.getElementsByTagName('li'),
products_len = products.length,
inputs,
inputs_len,
input,
matches,
i, j, k = 1;
for (i = 0 ; i < products_len; i++) {
inputs = products[i].getElementsByTagName('input');
inputs_len = inputs.length;
for (j = 0; j < inputs_len; j++) {
input = inputs[j];
matches = /(.+)_[0-9]+$/.exec(input.name);
if (matches && matches[1]) {
input.name = matches[1] + '_' + k;
}
}
k++;
}
if (typeof afterRemoveFromCart == 'function') {
afterRemoveFromCart.call(minicart, product);
}
});
});
minicart.products[offset].product.item_name = '';
minicart.products[offset].product.item_number = '';
minicart.updateSubtotal();
$.storage.save(minicart.products);
};
/**
* Event when the cart form is submitted
*
* @param e {event} The form submission event
*/
var _checkout = function (e) {
var onCheckout = config.events.onCheckout;
if (typeof onCheckout == 'function') {
if (onCheckout.call(minicart, e) === false) {
e.preventDefault();
return;
}
}
minicart.UI.button.value = config.strings.processing || 'Processing…';
};
/** PUBLIC **/
/**
* Array of ProductNode
*/
minicart.products = [];
/**
* Container for UI elements
*/
minicart.UI = {};
/**
* Renders the cart, creates the configuration and loads the data
*
* @param userConfig {object} User settings which override the default configuration
*/
minicart.render = function (userConfig) {
var events = config.events,
onRender = events.onRender,
afterRender = events.afterRender,
hash, cmd;
if (typeof onRender == 'function') {
if (onRender.call(minicart) === false) {
return;
}
}
if (!isRendered) {
// Overwrite default configuration with user settings
_parseUserConfig(userConfig);
// Render the cart UI
_addCSS();
_buildDOM();
_bindEvents();
// Check if a transaction was completed
// The "return" form param is modified to contain a hash value
// with "PPMiniCart=reset". If this is seen then it's assumed
// that a transaction was completed and we should reset the cart.
hash = location.hash.substring(1);
if (hash.indexOf(config.name + '=') === 0) {
cmd = hash.split('=')[1];
if (cmd == 'reset') {
minicart.reset();
location.hash = '';
}
}
}
// Process any stored data and render it
// TODO: _parseStorage shouldn't be so tightly coupled here and one
// should be able to redraw without re-parsing the storage
_redrawCartItems();
// Trigger the cart to peek on first load if any products were loaded
if (!isRendered) {
if (isShowing) {
setTimeout(function () {
minicart.hide(null);
}, 500);
} else {
$.storage.remove();
}
}
isRendered = true;
if (typeof afterRender == 'function') {
afterRender.call(minicart);
}
};
/**
* Binds a form to the Mini Cart
*
* @param form {HTMLElement} The form element to bind
*/
minicart.bindForm = function (form) {
if (form.add) {
$.event.add(form, 'submit', function (e) {
e.preventDefault(e);
var data = _parseForm(e.target);
minicart.addToCart(data);
});
} else if (form.display) {
$.event.add(form, 'submit', function (e) {
e.preventDefault();
minicart.show(e);
});
} else {
return false;
}
return true;
};
/**
* Adds a product to the cart
*
* @param data {object} Product object. See _parseData for format
* @return {boolean} True if the product was added, false otherwise
*/
minicart.addToCart = function (data) {
var events = config.events,
onAddToCart = events.onAddToCart,
afterAddToCart = events.afterAddToCart,
success = false,
productNode, offset;
if (typeof onAddToCart === 'function') {
if (onAddToCart.call(minicart, data) === false) {
return;
}
}
data = _parseData(data);
offset = data.product.offset;
// Check if the product has already been added; update if so
if ((productNode = (typeof offset !== 'undefined' && minicart.products[offset]))) {
productNode.product.quantity += parseInt(data.product.quantity || 1, 10);
productNode.setPrice(data.product.amount * productNode.product.quantity);
productNode.setQuantity(productNode.product.quantity);
success = true;
// Add a new DOM element for the product
} else {
data.product.offset = minicart.products.length;
success = _renderProduct(data);
}
minicart.updateSubtotal();
minicart.show(null);
$.storage.save(minicart.products);
if (typeof afterAddToCart === 'function') {
afterAddToCart.call(minicart, data);
}
return success;
};
/**
* Iterates over each product and calculates the subtotal
*
* @return {number} The subtotal
*/
minicart.calculateSubtotal = function () {
var amount = 0,
products = minicart.products,
product, item, price, discount, len, i;
for (i = 0, len = products.length; i < len; i++) {
item = products[i];
if ((product = item.product)) {
if (product.quantity && product.amount) {
price = product.amount;
discount = item.getDiscount();
amount += parseFloat((price * product.quantity) - discount);
}
}
}
return amount.toFixed(2);
};
/**
* Updates the UI with the current subtotal and currency code
*/
minicart.updateSubtotal = function () {
var ui = minicart.UI,
cartEl = ui.cart.elements,
subtotalEl = ui.subtotalAmount,
subtotal = minicart.calculateSubtotal(),
level = 1,
currency_code, currency_symbol, hex, len, i;
// Get the currency
currency_code = '';
currency_symbol = '';
if (cartEl.currency_code) {
currency_code = cartEl.currency_code.value || cartEl.currency_code;
} else {
for (i = 0, len = cartEl.length; i < len; i++) {
if (cartEl[i].name == 'currency_code') {
currency_code = cartEl[i].value || cartEl[i];
break;
}
}
}
// Update the UI
subtotalEl.innerHTML = $.util.formatCurrency(subtotal, currency_code);
// Yellow fade on update
(function () {
hex = level.toString(16);
level++;
subtotalEl.style.backgroundColor = '#ff' + hex;
if (level >= 15) {
subtotalEl.style.backgroundColor = 'transparent';
// hide the cart if there's no total
if (subtotal == '0.00') {
minicart.hide(null, true);
}
return;
}
setTimeout(arguments.callee, 30);
})();
};
/**
* Shows the cart
*
* @param e {event} The triggering event
*/
minicart.show = function (e) {
var from = parseInt(minicart.UI.cart.offsetTop, 10),
to = 0,
events = config.events,
onShow = events.onShow,
afterShow = events.afterShow;
if (e && e.preventDefault) { e.preventDefault(); }
if (typeof onShow == 'function') {
if (onShow.call(minicart, e) === false) {
return;
}
}
$.util.animate(minicart.UI.cart, 'top', { from: from, to: to }, function () {
if (typeof afterShow == 'function') {
afterShow.call(minicart, e);
}
});
minicart.UI.summary.style.backgroundPosition = '-195px 2px';
isShowing = true;
};
/**
* Hides the cart off the screen
*
* @param e {event} The triggering event
* @param fully {boolean} Should the cart be fully hidden? Optional. Defaults to false.
*/
minicart.hide = function (e, fully) {
var ui = minicart.UI,
cartEl = ui.cart,
summaryEl = ui.summary,
cartHeight = (cartEl.offsetHeight) ? cartEl.offsetHeight : document.defaultView.getComputedStyle(cartEl, '').getPropertyValue('height'),
summaryHeight = (summaryEl.offsetHeight) ? summaryEl.offsetHeight : document.defaultView.getComputedStyle(summaryEl, '').getPropertyValue('height'),
from = parseInt(cartEl.offsetTop, 10),
events = config.events,
onHide = events.onHide,
afterHide = events.afterHide,
to;
// make the cart fully hidden
if (fully || minicart.products.length === 0 || !config.peekEnabled) {
to = cartHeight * -1;
// otherwise only show a little teaser portion of it
} else {
to = (cartHeight - summaryHeight - 8) * -1;
}
if (e && e.preventDefault) { e.preventDefault(); }
if (typeof onHide == 'function') {
if (onHide.call(minicart, e) === false) {
return;
}
}
$.util.animate(cartEl, 'top', { from: from, to: to }, function () {
if (typeof afterHide == 'function') {
afterHide.call(minicart, e);
}
});