-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.store.js
649 lines (514 loc) · 19.7 KB
/
jquery.store.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
(function( $ ) {
$.Shop = function( element ) {
this.$element = $( element );
this.init();
};
$.Shop.prototype = {
init: function() {
// Properties
this.cartPrefix = "Furniture-"; // Prefix string to be prepended to the cart's name in the session storage
this.cartName = this.cartPrefix + "cart"; // Cart name in the session storage
this.shippingRates = this.cartPrefix + "shipping-rates"; // Shipping rates key in the session storage
this.total = this.cartPrefix + "total"; // Total key in the session storage
this.storage = sessionStorage; // shortcut to the sessionStorage object
this.$formAddToCart = this.$element.find( "form.add-to-cart" ); // Forms for adding items to the cart
this.$formCart = this.$element.find( "#shopping-cart" ); // Shopping cart form
this.$checkoutCart = this.$element.find( "#checkout-cart" ); // Checkout form cart
this.$checkoutOrderForm = this.$element.find( "#checkout-order-form" ); // Checkout user details form
this.$shipping = this.$element.find( "#sshipping" ); // Element that displays the shipping rates
this.$subTotal = this.$element.find( "#stotal" ); // Element that displays the subtotal charges
this.$shoppingCartActions = this.$element.find( "#shopping-cart-actions" ); // Cart actions links
this.$updateCartBtn = this.$shoppingCartActions.find( "#update-cart" ); // Update cart button
this.$emptyCartBtn = this.$shoppingCartActions.find( "#empty-cart" ); // Empty cart button
this.$userDetails = this.$element.find( "#user-details-content" ); // Element that displays the user information
this.$paypalForm = this.$element.find( "#paypal-form" ); // PayPal form
this.currency = "€"; // HTML entity of the currency to be displayed in the layout
this.currencyString = "€"; // Currency symbol as textual string
this.paypalCurrency = "EUR"; // PayPal's currency code
this.paypalBusinessEmail = "[email protected]"; // Your Business PayPal's account email address
this.paypalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr"; // The URL of the PayPal's form
// Object containing patterns for form validation
this.requiredFields = {
expression: {
value: /^([\w-\.]+)@((?:[\w]+\.)+)([a-z]){2,4}$/
},
str: {
value: ""
}
};
// Method invocation
this.createCart();
this.handleAddToCartForm();
this.handleCheckoutOrderForm();
this.emptyCart();
this.updateCart();
this.displayCart();
this.deleteProduct();
this.displayUserDetails();
this.populatePayPalForm();
},
// Public methods
// Creates the cart keys in the session storage
createCart: function() {
if( this.storage.getItem( this.cartName ) == null ) {
var cart = {};
cart.items = [];
this.storage.setItem( this.cartName, this._toJSONString( cart ) );
this.storage.setItem( this.shippingRates, "0" );
this.storage.setItem( this.total, "0" );
}
},
// Appends the required hidden values to the PayPal's form before submitting
populatePayPalForm: function() {
var self = this;
if( self.$paypalForm.length ) {
var $form = self.$paypalForm;
var cart = self._toJSONObject( self.storage.getItem( self.cartName ) );
var shipping = self.storage.getItem( self.shippingRates );
var numShipping = self._convertString( shipping );
var cartItems = cart.items;
var singShipping = Math.floor( numShipping / cartItems.length );
$form.attr( "action", self.paypalURL );
$form.find( "input[name='business']" ).val( self.paypalBusinessEmail );
$form.find( "input[name='currency_code']" ).val( self.paypalCurrency );
for( var i = 0; i < cartItems.length; ++i ) {
var cartItem = cartItems[i];
var n = i + 1;
var name = cartItem.product;
var price = cartItem.price;
var qty = cartItem.qty;
$( "<div/>" ).html( "<input type='hidden' name='quantity_" + n + "' value='" + qty + "'/>" ).
insertBefore( "#paypal-btn" );
$( "<div/>" ).html( "<input type='hidden' name='item_name_" + n + "' value='" + name + "'/>" ).
insertBefore( "#paypal-btn" );
$( "<div/>" ).html( "<input type='hidden' name='item_number_" + n + "' value='SKU " + name + "'/>" ).
insertBefore( "#paypal-btn" );
$( "<div/>" ).html( "<input type='hidden' name='amount_" + n + "' value='" + self._formatNumber( price, 2 ) + "'/>" ).
insertBefore( "#paypal-btn" );
$( "<div/>" ).html( "<input type='hidden' name='shipping_" + n + "' value='" + self._formatNumber( singShipping, 2 ) + "'/>" ).
insertBefore( "#paypal-btn" );
}
}
},
// Displays the user's information
displayUserDetails: function() {
if( this.$userDetails.length ) {
if( this.storage.getItem( "shipping-name" ) == null ) {
var name = this.storage.getItem( "billing-name" );
var email = this.storage.getItem( "billing-email" );
var city = this.storage.getItem( "billing-city" );
var address = this.storage.getItem( "billing-address" );
var zip = this.storage.getItem( "billing-zip" );
var country = this.storage.getItem( "billing-country" );
var html = "<div class='detail'>";
html += "<h2>Billing and Shipping</h2>";
html += "<ul>";
html += "<li>" + name + "</li>";
html += "<li>" + email + "</li>";
html += "<li>" + city + "</li>";
html += "<li>" + address + "</li>";
html += "<li>" + zip + "</li>";
html += "<li>" + country + "</li>";
html += "</ul></div>";
this.$userDetails[0].innerHTML = html;
} else {
var name = this.storage.getItem( "billing-name" );
var email = this.storage.getItem( "billing-email" );
var city = this.storage.getItem( "billing-city" );
var address = this.storage.getItem( "billing-address" );
var zip = this.storage.getItem( "billing-zip" );
var country = this.storage.getItem( "billing-country" );
var sName = this.storage.getItem( "shipping-name" );
var sEmail = this.storage.getItem( "shipping-email" );
var sCity = this.storage.getItem( "shipping-city" );
var sAddress = this.storage.getItem( "shipping-address" );
var sZip = this.storage.getItem( "shipping-zip" );
var sCountry = this.storage.getItem( "shipping-country" );
var html = "<div class='detail'>";
html += "<h2>Billing</h2>";
html += "<ul>";
html += "<li>" + name + "</li>";
html += "<li>" + email + "</li>";
html += "<li>" + city + "</li>";
html += "<li>" + address + "</li>";
html += "<li>" + zip + "</li>";
html += "<li>" + country + "</li>";
html += "</ul></div>";
html += "<div class='detail right'>";
html += "<h2>Shipping</h2>";
html += "<ul>";
html += "<li>" + sName + "</li>";
html += "<li>" + sEmail + "</li>";
html += "<li>" + sCity + "</li>";
html += "<li>" + sAddress + "</li>";
html += "<li>" + sZip + "</li>";
html += "<li>" + sCountry + "</li>";
html += "</ul></div>";
this.$userDetails[0].innerHTML = html;
}
}
},
// Delete a product from the shopping cart
deleteProduct: function() {
var self = this;
if( self.$formCart.length ) {
var cart = this._toJSONObject( this.storage.getItem( this.cartName ) );
var items = cart.items;
$( document ).on( "click", ".pdelete a", function( e ) {
e.preventDefault();
var productName = $( this ).data( "product" );
var newItems = [];
for( var i = 0; i < items.length; ++i ) {
var item = items[i];
var product = item.product;
if( product == productName ) {
items.splice( i, 1 );
}
}
newItems = items;
var updatedCart = {};
updatedCart.items = newItems;
var updatedTotal = 0;
var totalQty = 0;
if( newItems.length == 0 ) {
updatedTotal = 0;
totalQty = 0;
} else {
for( var j = 0; j < newItems.length; ++j ) {
var prod = newItems[j];
var sub = prod.price * prod.qty;
updatedTotal += sub;
totalQty += prod.qty;
}
}
self.storage.setItem( self.total, self._convertNumber( updatedTotal ) );
self.storage.setItem( self.shippingRates, self._convertNumber( self._calculateShipping( totalQty ) ) );
self.storage.setItem( self.cartName, self._toJSONString( updatedCart ) );
$( this ).parents( "tr" ).remove();
self.$subTotal[0].innerHTML = self.currency + " " + self.storage.getItem( self.total );
});
}
},
// Displays the shopping cart
displayCart: function() {
if( this.$formCart.length ) {
var cart = this._toJSONObject( this.storage.getItem( this.cartName ) );
var items = cart.items;
var $tableCart = this.$formCart.find( ".shopping-cart" );
var $tableCartBody = $tableCart.find( "tbody" );
if( items.length == 0 ) {
$tableCartBody.html( "" );
} else {
for( var i = 0; i < items.length; ++i ) {
var item = items[i];
var product = item.product;
var price = this.currency + " " + item.price;
var qty = item.qty;
var html = "<tr><td class='pname'>" + product + "</td>" + "<td class='pqty'><input type='text' value='" + qty + "' class='qty'/></td>";
html += "<td class='pprice'>" + price + "</td><td class='pdelete'><a href='' data-product='" + product + "'>×</a></td></tr>";
$tableCartBody.html( $tableCartBody.html() + html );
}
}
if( items.length == 0 ) {
this.$subTotal[0].innerHTML = this.currency + " " + 0.00;
} else {
var total = this.storage.getItem( this.total );
this.$subTotal[0].innerHTML = this.currency + " " + total;
}
} else if( this.$checkoutCart.length ) {
var checkoutCart = this._toJSONObject( this.storage.getItem( this.cartName ) );
var cartItems = checkoutCart.items;
var $cartBody = this.$checkoutCart.find( "tbody" );
if( cartItems.length > 0 ) {
for( var j = 0; j < cartItems.length; ++j ) {
var cartItem = cartItems[j];
var cartProduct = cartItem.product;
var cartPrice = this.currency + " " + cartItem.price;
var cartQty = cartItem.qty;
var cartHTML = "<tr><td class='pname'>" + cartProduct + "</td>" + "<td class='pqty'>" + cartQty + "</td>" + "<td class='pprice'>" + cartPrice + "</td></tr>";
$cartBody.html( $cartBody.html() + cartHTML );
}
} else {
$cartBody.html( "" );
}
if( cartItems.length > 0 ) {
var cartTotal = this.storage.getItem( this.total );
var cartShipping = this.storage.getItem( this.shippingRates );
var subTot = this._convertString( cartTotal ) + this._convertString( cartShipping );
this.$subTotal[0].innerHTML = this.currency + " " + this._convertNumber( subTot );
this.$shipping[0].innerHTML = this.currency + " " + cartShipping;
} else {
this.$subTotal[0].innerHTML = this.currency + " " + 0.00;
this.$shipping[0].innerHTML = this.currency + " " + 0.00;
}
}
},
// Empties the cart by calling the _emptyCart() method
// @see $.Shop._emptyCart()
emptyCart: function() {
var self = this;
if( self.$emptyCartBtn.length ) {
self.$emptyCartBtn.on( "click", function() {
self._emptyCart();
});
}
},
// Updates the cart
updateCart: function() {
var self = this;
if( self.$updateCartBtn.length ) {
self.$updateCartBtn.on( "click", function() {
var $rows = self.$formCart.find( "tbody tr" );
var cart = self.storage.getItem( self.cartName );
var shippingRates = self.storage.getItem( self.shippingRates );
var total = self.storage.getItem( self.total );
var updatedTotal = 0;
var totalQty = 0;
var updatedCart = {};
updatedCart.items = [];
$rows.each(function() {
var $row = $( this );
var pname = $.trim( $row.find( ".pname" ).text() );
var pqty = self._convertString( $row.find( ".pqty > .qty" ).val() );
var pprice = self._convertString( self._extractPrice( $row.find( ".pprice" ) ) );
var cartObj = {
product: pname,
price: pprice,
qty: pqty
};
updatedCart.items.push( cartObj );
var subTotal = pqty * pprice;
updatedTotal += subTotal;
totalQty += pqty;
});
self.storage.setItem( self.total, self._convertNumber( updatedTotal ) );
self.storage.setItem( self.shippingRates, self._convertNumber( self._calculateShipping( totalQty ) ) );
self.storage.setItem( self.cartName, self._toJSONString( updatedCart ) );
});
}
},
// Adds items to the shopping cart
handleAddToCartForm: function() {
var self = this;
self.$formAddToCart.each(function() {
var $form = $( this );
var $product = $form.parent();
var price = self._convertString( $product.data( "price" ) );
var name = $product.data( "name" );
$form.on( "submit", function() {
var qty = self._convertString( $form.find( ".qty" ).val() );
var subTotal = qty * price;
var total = self._convertString( self.storage.getItem( self.total ) );
var sTotal = total + subTotal;
self.storage.setItem( self.total, sTotal );
self._addToCart({
product: name,
price: price,
qty: qty
});
var shipping = self._convertString( self.storage.getItem( self.shippingRates ) );
var shippingRates = self._calculateShipping( qty );
var totalShipping = shipping + shippingRates;
self.storage.setItem( self.shippingRates, totalShipping );
});
});
},
// Handles the checkout form by adding a validation routine and saving user's info into the session storage
handleCheckoutOrderForm: function() {
var self = this;
if( self.$checkoutOrderForm.length ) {
var $sameAsBilling = $( "#same-as-billing" );
$sameAsBilling.on( "change", function() {
var $check = $( this );
if( $check.prop( "checked" ) ) {
$( "#fieldset-shipping" ).slideUp( "normal" );
} else {
$( "#fieldset-shipping" ).slideDown( "normal" );
}
});
self.$checkoutOrderForm.on( "submit", function() {
var $form = $( this );
var valid = self._validateForm( $form );
if( !valid ) {
return valid;
} else {
self._saveFormData( $form );
}
});
}
},
// Private methods
// Empties the session storage
_emptyCart: function() {
this.storage.clear();
},
/* Format a number by decimal places
* @param num Number the number to be formatted
* @param places Number the decimal places
* @returns n Number the formatted number
*/
_formatNumber: function( num, places ) {
var n = num.toFixed( places );
return n;
},
/* Extract the numeric portion from a string
* @param element Object the jQuery element that contains the relevant string
* @returns price String the numeric string
*/
_extractPrice: function( element ) {
var self = this;
var text = element.text();
var price = text.replace( self.currencyString, "" ).replace( " ", "" );
return price;
},
/* Converts a numeric string into a number
* @param numStr String the numeric string to be converted
* @returns num Number the number
*/
_convertString: function( numStr ) {
var num;
if( /^[-+]?[0-9]+\.[0-9]+$/.test( numStr ) ) {
num = parseFloat( numStr );
} else if( /^\d+$/.test( numStr ) ) {
num = parseInt( numStr, 10 );
} else {
num = Number( numStr );
}
if( !isNaN( num ) ) {
return num;
} else {
console.warn( numStr + " cannot be converted into a number" );
return false;
}
},
/* Converts a number to a string
* @param n Number the number to be converted
* @returns str String the string returned
*/
_convertNumber: function( n ) {
var str = n.toString();
return str;
},
/* Converts a JSON string to a JavaScript object
* @param str String the JSON string
* @returns obj Object the JavaScript object
*/
_toJSONObject: function( str ) {
var obj = JSON.parse( str );
return obj;
},
/* Converts a JavaScript object to a JSON string
* @param obj Object the JavaScript object
* @returns str String the JSON string
*/
_toJSONString: function( obj ) {
var str = JSON.stringify( obj );
return str;
},
/* Add an object to the cart as a JSON string
* @param values Object the object to be added to the cart
* @returns void
*/
_addToCart: function( values ) {
var cart = this.storage.getItem( this.cartName );
var cartObject = this._toJSONObject( cart );
var cartCopy = cartObject;
var items = cartCopy.items;
items.push( values );
this.storage.setItem( this.cartName, this._toJSONString( cartCopy ) );
},
/* Custom shipping rates calculation based on the total quantity of items in the cart
* @param qty Number the total quantity of items
* @returns shipping Number the shipping rates
*/
_calculateShipping: function( qty ) {
var shipping = 0;
if( qty >= 6 ) {
shipping = 10;
}
if( qty >= 12 && qty <= 30 ) {
shipping = 20;
}
if( qty >= 30 && qty <= 60 ) {
shipping = 30;
}
if( qty > 60 ) {
shipping = 0;
}
return shipping;
},
/* Validates the checkout form
* @param form Object the jQuery element of the checkout form
* @returns valid Boolean true for success, false for failure
*/
_validateForm: function( form ) {
var self = this;
var fields = self.requiredFields;
var $visibleSet = form.find( "fieldset:visible" );
var valid = true;
form.find( ".message" ).remove();
$visibleSet.each(function() {
$( this ).find( ":input" ).each(function() {
var $input = $( this );
var type = $input.data( "type" );
var msg = $input.data( "message" );
if( type == "string" ) {
if( $input.val() == fields.str.value ) {
$( "<span class='message'/>" ).text( msg ).
insertBefore( $input );
valid = false;
}
} else {
if( !fields.expression.value.test( $input.val() ) ) {
$( "<span class='message'/>" ).text( msg ).
insertBefore( $input );
valid = false;
}
}
});
});
return valid;
},
/* Save the data entered by the user in the ckeckout form
* @param form Object the jQuery element of the checkout form
* @returns void
*/
_saveFormData: function( form ) {
var self = this;
var $visibleSet = form.find( "fieldset:visible" );
$visibleSet.each(function() {
var $set = $( this );
if( $set.is( "#fieldset-billing" ) ) {
var name = $( "#name", $set ).val();
var email = $( "#email", $set ).val();
var city = $( "#city", $set ).val();
var address = $( "#address", $set ).val();
var zip = $( "#zip", $set ).val();
var country = $( "#country", $set ).val();
self.storage.setItem( "billing-name", name );
self.storage.setItem( "billing-email", email );
self.storage.setItem( "billing-city", city );
self.storage.setItem( "billing-address", address );
self.storage.setItem( "billing-zip", zip );
self.storage.setItem( "billing-country", country );
} else {
var sName = $( "#sname", $set ).val();
var sEmail = $( "#semail", $set ).val();
var sCity = $( "#scity", $set ).val();
var sAddress = $( "#saddress", $set ).val();
var sZip = $( "#szip", $set ).val();
var sCountry = $( "#scountry", $set ).val();
self.storage.setItem( "shipping-name", sName );
self.storage.setItem( "shipping-email", sEmail );
self.storage.setItem( "shipping-city", sCity );
self.storage.setItem( "shipping-address", sAddress );
self.storage.setItem( "shipping-zip", sZip );
self.storage.setItem( "shipping-country", sCountry );
}
});
}
};
$(function() {
var shop = new $.Shop( "#site" );
});
})( jQuery );