only clear selection on success
[omsmith/pos-js.git] / www / assets / js / ui.js
1 /*
2  * Ask for configuration at page load
3  */
4
5 var client = {};
6
7 $('#config-modal').modal().find('#save-config').click(function (e) {
8         var authKey = $('input[name=auth-key]').val();
9         var serverLocation = $('input[name=server-location]').val();
10
11         client = new PosClientWrapper( authKey, serverLocation );
12 });
13
14 /*
15  * End configuation ask
16  */
17
18 /*
19  * Selections ( used for knowing things, and also data binding
20  */
21
22 function Selection (upc, price) {
23         var self = this;
24
25         self.upc = upc;
26         self.name = ko.observable('');
27         self.size = ko.observable('');
28         self.quantity = ko.observable(1);
29         self.price = price;
30 }
31
32 function SelectionsViewModel () {
33         var self = this;
34
35         self.selections = ko.observableArray([]);
36
37         self.addSelection = function (data, e) {
38                 var input = $(e.target);
39                 var upc = input.val();
40                 input.val('');
41
42                 if (upc.length === 12) {
43                         for (var i in self.selections()) {
44                                 var selection = self.selections()[i];
45
46                                 if (selection.upc === upc) {
47                                         selection.quantity(selection.quantity() + 1);
48                                         return;
49                                 }
50                         }
51
52                         var selection = new Selection( upc, client.getPrice(upc) );
53                         request_upc_data(upc, function (data) {
54                                 selection.name(data.name).size(data.size);
55                         });
56
57                         self.selections.push( selection );
58
59                 }
60         };
61
62         self.removeSelection = function (selection) {
63                 self.selections.remove(selection);
64         };
65
66         self.clearSelection = function () {
67                 self.selections.removeAll();
68         };
69
70         self.purchase = function (data, e) {
71                 var selected = self.selections();
72
73                 var input = $(e.target);
74                 var cardData = input.val();
75                 input.val('');
76
77                 var result = client.process(cardData, selected);
78                 if (result === 2) {
79                         self.clearSelection();
80                         $('#checkout-modal').modal('hide');
81                 }
82         };
83 }
84
85 ko.applyBindings(new SelectionsViewModel());
86
87 /*
88  * End of selections
89  */
90
91
92 function request_upc_data (upc, callback) {
93         $.ajax( 'upc.php?upc=' + upc )
94                 .done(function (data) { callback(JSON.parse(data)); });
95 }