forked from wojodesign/simplecart-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simpleCart.js
executable file
·1931 lines (1629 loc) · 55.9 KB
/
simpleCart.js
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
/*~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
Copyright (c) 2012 Brett Wejrowski
wojodesign.com
simplecartjs.org
http://github.com/wojodesign/simplecart-js
VERSION 3.0.5
Dual licensed under the MIT or GPL licenses.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~*/
/*jslint browser: true, unparam: true, white: true, nomen: true, regexp: true, maxerr: 50, indent: 4 */
(function (window, document) {
/*global HTMLElement */
var typeof_string = typeof "",
typeof_undefined = typeof undefined,
typeof_function = typeof function () {},
typeof_object = typeof {},
isTypeOf = function (item, type) { return typeof item === type; },
isString = function (item) { return isTypeOf(item, typeof_string); },
isUndefined = function (item) { return isTypeOf(item, typeof_undefined); },
isFunction = function (item) { return isTypeOf(item, typeof_function); },
isObject = function (item) { return isTypeOf(item, typeof_object); },
//Returns true if it is a DOM element
isElement = function (o) {
return typeof HTMLElement === "object" ? o instanceof HTMLElement : typeof o === "object" && o.nodeType === 1 && typeof o.nodeName === "string";
},
generateSimpleCart = function (space) {
// stealing this from selectivizr
var selectorEngines = {
"MooTools" : "$$",
"Prototype" : "$$",
"jQuery" : "*"
},
// local variables for internal use
item_id = 0,
item_id_namespace = "SCI-",
sc_items = {},
namespace = space || "simpleCart",
selectorFunctions = {},
eventFunctions = {},
baseEvents = {},
// local references
localStorage = window.localStorage,
console = window.console || { msgs: [], log: function (msg) { console.msgs.push(msg); } },
// used in views
_VALUE_ = 'value',
_TEXT_ = 'text',
_HTML_ = 'html',
_CLICK_ = 'click',
// Currencies
currencies = {
"USD": { code: "USD", symbol: "$", name: "US Dollar" },
"AUD": { code: "AUD", symbol: "$", name: "Australian Dollar" },
"BRL": { code: "BRL", symbol: "R$", name: "Brazilian Real" },
"CAD": { code: "CAD", symbol: "$", name: "Canadian Dollar" },
"CZK": { code: "CZK", symbol: " Kč", name: "Czech Koruna", after: true },
"DKK": { code: "DKK", symbol: "DKK ", name: "Danish Krone" },
"EUR": { code: "EUR", symbol: "€", name: "Euro" },
"HKD": { code: "HKD", symbol: "$", name: "Hong Kong Dollar" },
"HUF": { code: "HUF", symbol: "Ft", name: "Hungarian Forint" },
"ILS": { code: "ILS", symbol: "₪", name: "Israeli New Sheqel" },
"JPY": { code: "JPY", symbol: "¥", name: "Japanese Yen", accuracy: 0 },
"MXN": { code: "MXN", symbol: "$", name: "Mexican Peso" },
"NOK": { code: "NOK", symbol: "NOK ", name: "Norwegian Krone" },
"NZD": { code: "NZD", symbol: "$", name: "New Zealand Dollar" },
"PLN": { code: "PLN", symbol: "PLN ", name: "Polish Zloty" },
"GBP": { code: "GBP", symbol: "£", name: "Pound Sterling" },
"SGD": { code: "SGD", symbol: "$", name: "Singapore Dollar" },
"SEK": { code: "SEK", symbol: "SEK ", name: "Swedish Krona" },
"CHF": { code: "CHF", symbol: "CHF ", name: "Swiss Franc" },
"THB": { code: "THB", symbol: "฿", name: "Thai Baht" },
"BTC": { code: "BTC", symbol: " BTC", name: "Bitcoin", accuracy: 4, after: true }
},
// default options
settings = {
checkout : { type: "PayPal", email: "you@yours.com" },
currency : "USD",
language : "english-us",
cartStyle : "div",
cartColumns : [
{ attr: "name", label: "Name" },
{ attr: "price", label: "Price", view: 'currency' },
{ view: "decrement", label: false },
{ attr: "quantity", label: "Qty" },
{ view: "increment", label: false },
{ attr: "total", label: "SubTotal", view: 'currency' },
{ view: "remove", text: "Remove", label: false }
],
excludeFromCheckout : ['thumb'],
shippingFlatRate : 0,
shippingQuantityRate : 0,
shippingTotalRate : 0,
shippingCustom : null,
taxRate : 0,
taxShipping : false,
data : {}
},
// main simpleCart object, function call is used for setting options
simpleCart = function (options) {
// shortcut for simpleCart.ready
if (isFunction(options)) {
return simpleCart.ready(options);
}
// set options
if (isObject(options)) {
return simpleCart.extend(settings, options);
}
},
// selector engine
$engine,
// built in cart views for item cells
cartColumnViews;
// function for extending objects
simpleCart.extend = function (target, opts) {
var next;
if (isUndefined(opts)) {
opts = target;
target = simpleCart;
}
for (next in opts) {
if (Object.prototype.hasOwnProperty.call(opts, next)) {
target[next] = opts[next];
}
}
return target;
};
// create copy function
simpleCart.extend({
copy: function (n) {
var cp = generateSimpleCart(n);
cp.init();
return cp;
}
});
// add in the core functionality
simpleCart.extend({
isReady: false,
// this is where the magic happens, the add function
add: function (values, opt_quiet) {
var info = values || {},
newItem = new simpleCart.Item(info),
addItem = true,
// optionally supress event triggers
quiet = opt_quiet === true ? opt_quiet : false,
oldItem;
// trigger before add event
if (!quiet) {
addItem = simpleCart.trigger('beforeAdd', [newItem]);
if (addItem === false) {
return false;
}
}
// if the new item already exists, increment the value
oldItem = simpleCart.has(newItem);
if (oldItem) {
oldItem.increment(newItem.quantity());
newItem = oldItem;
// otherwise add the item
} else {
sc_items[newItem.id()] = newItem;
}
// update the cart
simpleCart.update();
if (!quiet) {
// trigger after add event
simpleCart.trigger('afterAdd', [newItem, isUndefined(oldItem)]);
}
// return a reference to the added item
return newItem;
},
// iteration function
each: function (array, callback) {
var next,
x = 0,
result,
cb,
items;
if (isFunction(array)) {
cb = array;
items = sc_items;
} else if (isFunction(callback)) {
cb = callback;
items = array;
} else {
return;
}
for (next in items) {
if (Object.prototype.hasOwnProperty.call(items, next)) {
result = cb.call(simpleCart, items[next], x, next);
if (result === false) {
return;
}
x += 1;
}
}
},
find: function (id) {
var items = [];
// return object for id if it exists
if (isObject(sc_items[id])) {
return sc_items[id];
}
// search through items with the given criteria
if (isObject(id)) {
simpleCart.each(function (item) {
var match = true;
simpleCart.each(id, function (val, x, attr) {
if (isString(val)) {
// less than or equal to
if (val.match(/<=.*/)) {
val = parseFloat(val.replace('<=', ''));
if (!(item.get(attr) && parseFloat(item.get(attr)) <= val)) {
match = false;
}
// less than
} else if (val.match(/</)) {
val = parseFloat(val.replace('<', ''));
if (!(item.get(attr) && parseFloat(item.get(attr)) < val)) {
match = false;
}
// greater than or equal to
} else if (val.match(/>=/)) {
val = parseFloat(val.replace('>=', ''));
if (!(item.get(attr) && parseFloat(item.get(attr)) >= val)) {
match = false;
}
// greater than
} else if (val.match(/>/)) {
val = parseFloat(val.replace('>', ''));
if (!(item.get(attr) && parseFloat(item.get(attr)) > val)) {
match = false;
}
// equal to
} else if (!(item.get(attr) && item.get(attr) === val)) {
match = false;
}
// equal to non string
} else if (!(item.get(attr) && item.get(attr) === val)) {
match = false;
}
return match;
});
// add the item if it matches
if (match) {
items.push(item);
}
});
return items;
}
// if no criteria is given we return all items
if (isUndefined(id)) {
// use a new array so we don't give a reference to the
// cart's item array
simpleCart.each(function (item) {
items.push(item);
});
return items;
}
// return empty array as default
return items;
},
// return all items
items: function () {
return this.find();
},
// check to see if item is in the cart already
has: function (item) {
var match = false;
simpleCart.each(function (testItem) {
if (testItem.equals(item)) {
match = testItem;
}
});
return match;
},
// empty the cart
empty: function () {
// remove each item individually so we see the remove events
var newItems = {};
simpleCart.each(function (item) {
// send a param of true to make sure it doesn't
// update after every removal
// keep the item if the function returns false,
// because we know it has been prevented
// from being removed
if (item.remove(true) === false) {
newItems[item.id()] = item
}
});
sc_items = newItems;
simpleCart.update();
},
// functions for accessing cart info
quantity: function () {
var quantity = 0;
simpleCart.each(function (item) {
quantity += item.quantity();
});
return quantity;
},
total: function () {
var total = 0;
simpleCart.each(function (item) {
total += item.total();
});
return total;
},
grandTotal: function () {
return simpleCart.total() + simpleCart.tax() + simpleCart.shipping();
},
// updating functions
update: function () {
simpleCart.save();
simpleCart.trigger("update");
},
init: function () {
simpleCart.load();
simpleCart.update();
simpleCart.ready();
},
// view management
$: function (selector) {
return new simpleCart.ELEMENT(selector);
},
$create: function (tag) {
return simpleCart.$(document.createElement(tag));
},
setupViewTool: function () {
var members, member, context = window, engine;
// Determine the "best fit" selector engine
for (engine in selectorEngines) {
if (Object.prototype.hasOwnProperty.call(selectorEngines, engine) && window[engine]) {
members = selectorEngines[engine].replace("*", engine).split(".");
member = members.shift();
if (member) {
context = context[member];
}
if (typeof context === "function") {
// set the selector engine and extend the prototype of our
// element wrapper class
$engine = context;
simpleCart.extend(simpleCart.ELEMENT._, selectorFunctions[engine]);
return;
}
}
}
},
// return a list of id's in the cart
ids: function () {
var ids = [];
simpleCart.each(function (item) {
ids.push(item.id());
});
return ids;
},
// storage
save: function () {
simpleCart.trigger('beforeSave');
var items = {};
// save all the items
simpleCart.each(function (item) {
items[item.id()] = simpleCart.extend(item.fields(), item.options());
});
localStorage.setItem(namespace + "_items", JSON.stringify(items));
simpleCart.trigger('afterSave');
},
load: function () {
// empty without the update
sc_items = {};
var items = localStorage.getItem(namespace + "_items");
if (!items) {
return;
}
// we wrap this in a try statement so we can catch
// any json parsing errors. no more stick and we
// have a playing card pluckin the spokes now...
// soundin like a harley.
try {
simpleCart.each(JSON.parse(items), function (item) {
simpleCart.add(item, true);
});
} catch (e){
simpleCart.error( "Error Loading data: " + e );
}
simpleCart.trigger('load');
},
// ready function used as a shortcut for bind('ready',fn)
ready: function (fn) {
if (isFunction(fn)) {
// call function if already ready already
if (simpleCart.isReady) {
fn.call(simpleCart);
// bind if not ready
} else {
simpleCart.bind('ready', fn);
}
// trigger ready event
} else if (isUndefined(fn) && !simpleCart.isReady) {
simpleCart.trigger('ready');
simpleCart.isReady = true;
}
},
error: function (message) {
var msg = "";
if (isString(message)) {
msg = message;
} else if (isObject(message) && isString(message.message)) {
msg = message.message;
}
try { console.log("simpleCart(js) Error: " + msg); } catch (e) {}
simpleCart.trigger('error', [message]);
}
});
/*******************************************************************
* TAX AND SHIPPING
*******************************************************************/
simpleCart.extend({
// TODO: tax and shipping
tax: function () {
var totalToTax = settings.taxShipping ? simpleCart.total() + simpleCart.shipping() : simpleCart.total(),
cost = simpleCart.taxRate() * totalToTax;
simpleCart.each(function (item) {
if (item.get('tax')) {
cost += item.get('tax');
} else if (item.get('taxRate')) {
cost += item.get('taxRate') * item.total();
}
});
return parseFloat(cost);
},
taxRate: function () {
return settings.taxRate || 0;
},
shipping: function (opt_custom_function) {
// shortcut to extend options with custom shipping
if (isFunction(opt_custom_function)) {
simpleCart({
shippingCustom: opt_custom_function
});
return;
}
var cost = settings.shippingQuantityRate * simpleCart.quantity() +
settings.shippingTotalRate * simpleCart.total() +
settings.shippingFlatRate;
if (isFunction(settings.shippingCustom)) {
cost += settings.shippingCustom.call(simpleCart);
}
simpleCart.each(function (item) {
cost += parseFloat(item.get('shipping') || 0);
});
return parseFloat(cost);
}
});
/*******************************************************************
* CART VIEWS
*******************************************************************/
// built in cart views for item cells
cartColumnViews = {
attr: function (item, column) {
return item.get(column.attr) || "";
},
currency: function (item, column) {
return simpleCart.toCurrency(item.get(column.attr) || 0);
},
link: function (item, column) {
return "<a href='" + item.get(column.attr) + "'>" + column.text + "</a>";
},
decrement: function (item, column) {
return "<a href='javascript:;' class='" + namespace + "_decrement'>" + (column.text || "-") + "</a>";
},
increment: function (item, column) {
return "<a href='javascript:;' class='" + namespace + "_increment'>" + (column.text || "+") + "</a>";
},
image: function (item, column) {
return "<img src='" + item.get(column.attr) + "'/>";
},
input: function (item, column) {
return "<input type='text' value='" + item.get(column.attr) + "' class='" + namespace + "_input'/>";
},
remove: function (item, column) {
return "<a href='javascript:;' class='" + namespace + "_remove'>" + (column.text || "X") + "</a>";
}
};
// cart column wrapper class and functions
function cartColumn(opts) {
var options = opts || {};
return simpleCart.extend({
attr : "",
label : "",
view : "attr",
text : "",
className : "",
hide : false
}, options);
}
function cartCellView(item, column) {
var viewFunc = isFunction(column.view) ? column.view : isString(column.view) && isFunction(cartColumnViews[column.view]) ? cartColumnViews[column.view] : cartColumnViews.attr;
return viewFunc.call(simpleCart, item, column);
}
simpleCart.extend({
// write out cart
writeCart: function (selector) {
var TABLE = settings.cartStyle.toLowerCase(),
isTable = TABLE === 'table',
TR = isTable ? "tr" : "div",
TH = isTable ? 'th' : 'div',
TD = isTable ? 'td' : 'div',
THEAD = isTable ? 'thead' : 'div',
cart_container = simpleCart.$create(TABLE),
thead_container = simpleCart.$create(THEAD),
header_container = simpleCart.$create(TR).addClass('headerRow'),
container = simpleCart.$(selector),
column,
klass,
label,
x,
xlen;
container.html(' ').append(cart_container);
cart_container.append(thead_container);
thead_container.append(header_container);
// create header
for (x = 0, xlen = settings.cartColumns.length; x < xlen; x += 1) {
column = cartColumn(settings.cartColumns[x]);
klass = "item-" + (column.attr || column.view || column.label || column.text || "cell") + " " + column.className;
label = column.label || "";
// append the header cell
header_container.append(
simpleCart.$create(TH).addClass(klass).html(label)
);
}
// cycle through the items
simpleCart.each(function (item, y) {
simpleCart.createCartRow(item, y, TR, TD, cart_container);
});
return cart_container;
},
// generate a cart row from an item
createCartRow: function (item, y, TR, TD, container) {
var row = simpleCart.$create(TR)
.addClass('itemRow row-' + y + " " + (y % 2 ? "even" : "odd"))
.attr('id', "cartItem_" + item.id()),
j,
jlen,
column,
klass,
content,
cell;
container.append(row);
// cycle through the columns to create each cell for the item
for (j = 0, jlen = settings.cartColumns.length; j < jlen; j += 1) {
column = cartColumn(settings.cartColumns[j]);
klass = "item-" + (column.attr || (isString(column.view) ? column.view : column.label || column.text || "cell")) + " " + column.className;
content = cartCellView(item, column);
cell = simpleCart.$create(TD).addClass(klass).html(content);
row.append(cell);
}
return row;
}
});
/*******************************************************************
* CART ITEM CLASS MANAGEMENT
*******************************************************************/
simpleCart.Item = function (info) {
// we use the data object to track values for the item
var _data = {},
me = this;
// cycle through given attributes and set them to the data object
if (isObject(info)) {
simpleCart.extend(_data, info);
}
// set the item id
item_id += 1;
_data.id = _data.id || item_id_namespace + item_id;
while (!isUndefined(sc_items[_data.id])) {
item_id += 1;
_data.id = item_id_namespace + item_id;
}
function checkQuantityAndPrice() {
// check to make sure price is valid
if (isString(_data.price)) {
// trying to remove all chars that aren't numbers or '.'
_data.price = parseFloat(_data.price.replace(simpleCart.currency().decimal, ".").replace(/[^0-9\.]+/ig, ""));
}
if (isNaN(_data.price)) {
_data.price = 0;
}
if (_data.price < 0) {
_data.price = 0;
}
// check to make sure quantity is valid
if (isString(_data.quantity)) {
_data.quantity = parseInt(_data.quantity.replace(simpleCart.currency().delimiter, ""), 10);
}
if (isNaN(_data.quantity)) {
_data.quantity = 1;
}
if (_data.quantity <= 0) {
me.remove();
}
}
// getter and setter methods to access private variables
me.get = function (name, skipPrototypes) {
var usePrototypes = !skipPrototypes;
if (isUndefined(name)) {
return name;
}
// return the value in order of the data object and then the prototype
return isFunction(_data[name]) ? _data[name].call(me) :
!isUndefined(_data[name]) ? _data[name] :
isFunction(me[name]) && usePrototypes ? me[name].call(me) :
!isUndefined(me[name]) && usePrototypes ? me[name] :
_data[name];
};
me.set = function (name, value) {
if (!isUndefined(name)) {
_data[name.toLowerCase()] = value;
if (name.toLowerCase() === 'price' || name.toLowerCase() === 'quantity') {
checkQuantityAndPrice();
}
}
return me;
};
me.equals = function (item) {
for( var label in _data ){
if (Object.prototype.hasOwnProperty.call(_data, label)) {
if (label !== 'quantity' && label !== 'id') {
if (item.get(label) !== _data[label]) {
return false;
}
}
}
}
return true;
};
me.options = function () {
var data = {};
simpleCart.each(_data,function (val, x, label) {
var add = true;
simpleCart.each(me.reservedFields(), function (field) {
if (field === label) {
add = false;
}
return add;
});
if (add) {
data[label] = me.get(label);
}
});
return data;
};
checkQuantityAndPrice();
};
simpleCart.Item._ = simpleCart.Item.prototype = {
// editing the item quantity
increment: function (amount) {
var diff = amount || 1;
diff = parseInt(diff, 10);
this.quantity(this.quantity() + diff);
if (this.quantity() < 1) {
this.remove();
return null;
}
return this;
},
decrement: function (amount) {
var diff = amount || 1;
return this.increment(-parseInt(diff, 10));
},
remove: function (skipUpdate) {
var removeItemBool = simpleCart.trigger("beforeRemove", [sc_items[this.id()]]);
if (removeItemBool === false ) {
return false;
}
delete sc_items[this.id()];
if (!skipUpdate) {
simpleCart.update();
}
return null;
},
// special fields for items
reservedFields: function () {
return ['quantity', 'id', 'item_number', 'price', 'name', 'shipping', 'tax', 'taxRate'];
},
// return values for all reserved fields if they exist
fields: function () {
var data = {},
me = this;
simpleCart.each(me.reservedFields(), function (field) {
if (me.get(field)) {
data[field] = me.get(field);
}
});
return data;
},
// shortcuts for getter/setters. can
// be overwritten for customization
// btw, we are hiring at wojo design, and could
// use a great web designer. if thats you, you can
// get more info at http://wojodesign.com/now-hiring/
// or email me directly: brett@wojodesign.com
quantity: function (val) {
return isUndefined(val) ? parseInt(this.get("quantity", true) || 1, 10) : this.set("quantity", val);
},
price: function (val) {
return isUndefined(val) ?
parseFloat((this.get("price",true).toString()).replace(simpleCart.currency().symbol,"").replace(simpleCart.currency().delimiter,"") || 1) :
this.set("price", parseFloat((val).toString().replace(simpleCart.currency().symbol,"").replace(simpleCart.currency().delimiter,"")));
},
id: function () {
return this.get('id',false);
},
total:function () {
return this.quantity()*this.price();
}
};
/*******************************************************************
* CHECKOUT MANAGEMENT
*******************************************************************/
simpleCart.extend({
checkout: function () {
if (settings.checkout.type.toLowerCase() === 'custom' && isFunction(settings.checkout.fn)) {
settings.checkout.fn.call(simpleCart,settings.checkout);
} else if (isFunction(simpleCart.checkout[settings.checkout.type])) {
var checkoutData = simpleCart.checkout[settings.checkout.type].call(simpleCart,settings.checkout);
// if the checkout method returns data, try to send the form
if( checkoutData.data && checkoutData.action && checkoutData.method ){
// if no one has any objections, send the checkout form
if( false !== simpleCart.trigger('beforeCheckout', [checkoutData.data]) ){
simpleCart.generateAndSendForm( checkoutData );
}
}
} else {
simpleCart.error("No Valid Checkout Method Specified");
}
},
extendCheckout: function (methods) {
return simpleCart.extend(simpleCart.checkout, methods);
},
generateAndSendForm: function (opts) {
var form = simpleCart.$create("form");
form.attr('style', 'display:none;');
form.attr('action', opts.action);
form.attr('method', opts.method);
simpleCart.each(opts.data, function (val, x, name) {
form.append(
simpleCart.$create("input").attr("type","hidden").attr("name",name).val(val)
);
});
simpleCart.$("body").append(form);
form.el.submit();
form.remove();
}
});
simpleCart.extendCheckout({
PayPal: function (opts) {
// account email is required
if (!opts.email) {
return simpleCart.error("No email provided for PayPal checkout");
}
// build basic form options
var data = {
cmd : "_cart"
, upload : "1"
, currency_code : simpleCart.currency().code
, business : opts.email
, rm : opts.method === "GET" ? "0" : "2"
, tax_cart : (simpleCart.tax()*1).toFixed(2)
, handling_cart : (simpleCart.shipping()*1).toFixed(2)
, charset : "utf-8"
},
action = opts.sandbox ? "https://www.sandbox.paypal.com/cgi-bin/webscr" : "https://www.paypal.com/cgi-bin/webscr",
method = opts.method === "GET" ? "GET" : "POST";
// check for return and success URLs in the options
if (opts.success) {
data['return'] = opts.success;
}
if (opts.cancel) {
data.cancel_return = opts.cancel;
}
if (opts.notify) {
data.notify_url = opts.notify;
}
// add all the items to the form data
simpleCart.each(function (item,x) {
var counter = x+1,
item_options = item.options(),
optionCount = 0,
send;
// basic item data
data["item_name_" + counter] = item.get("name");
data["quantity_" + counter] = item.quantity();
data["amount_" + counter] = (item.price()*1).toFixed(2);
data["item_number_" + counter] = item.get("item_number") || counter;
// add the options
simpleCart.each(item_options, function (val,k,attr) {
// paypal limits us to 10 options
if (k < 10) {
// check to see if we need to exclude this from checkout
send = true;
simpleCart.each(settings.excludeFromCheckout, function (field_name) {
if (field_name === attr) { send = false; }
});
if (send) {
optionCount += 1;
data["on" + k + "_" + counter] = attr;
data["os" + k + "_" + counter] = val;
}
}
});
// options count
data["option_index_"+ x] = Math.min(10, optionCount);
});
// return the data for the checkout form
return {
action : action
, method : method
, data : data
};